@terra.gl/core 0.0.1-alpha.14 → 0.0.1-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +881 -871
- package/dist/index.umd.cjs +5 -5
- package/package.json +3 -3
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(ee,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],m):(ee=typeof globalThis<"u"?globalThis:ee||self,m(ee["terra-gl"]={},ee.THREE))})(this,function(ee,m){"use strict";var Ab=Object.defineProperty;var Fb=(ee,m,cr)=>m in ee?Ab(ee,m,{enumerable:!0,configurable:!0,writable:!0,value:cr}):ee[m]=cr;var T=(ee,m,cr)=>Fb(ee,typeof m!="symbol"?m+"":m,cr);function cr(l){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const e in l)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(l,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>l[e]})}}return t.default=l,Object.freeze(t)}const wt=cr(m),Vh="0.0.1-alpha.
|
|
1
|
+
(function(ee,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],m):(ee=typeof globalThis<"u"?globalThis:ee||self,m(ee["terra-gl"]={},ee.THREE))})(this,function(ee,m){"use strict";var Ab=Object.defineProperty;var Fb=(ee,m,cr)=>m in ee?Ab(ee,m,{enumerable:!0,configurable:!0,writable:!0,value:cr}):ee[m]=cr;var T=(ee,m,cr)=>Fb(ee,typeof m!="symbol"?m+"":m,cr);function cr(l){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const e in l)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(l,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>l[e]})}}return t.default=l,Object.freeze(t)}const wt=cr(m),Vh="0.0.1-alpha.16",Zs={name:"Criska"};var Cr=function(){var l=0,t=document.createElement("div");t.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",t.addEventListener("click",function(p){p.preventDefault(),n(++l%t.children.length)},!1);function e(p){return t.appendChild(p.dom),p}function n(p){for(var f=0;f<t.children.length;f++)t.children[f].style.display=f===p?"block":"none";l=p}var r=(performance||Date).now(),s=r,a=0,c=e(new Cr.Panel("FPS","#0ff","#002")),u=e(new Cr.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=e(new Cr.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:t,addPanel:e,showPanel:n,begin:function(){r=(performance||Date).now()},end:function(){a++;var p=(performance||Date).now();if(u.update(p-r,200),p>=s+1e3&&(c.update(a*1e3/(p-s),100),s=p,a=0,d)){var f=performance.memory;d.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return p},update:function(){r=this.end()},domElement:t,setMode:n}};Cr.Panel=function(l,t,e){var n=1/0,r=0,s=Math.round,a=s(window.devicePixelRatio||1),c=80*a,u=48*a,d=3*a,p=2*a,f=3*a,y=15*a,v=74*a,x=30*a,L=document.createElement("canvas");L.width=c,L.height=u,L.style.cssText="width:80px;height:48px";var _=L.getContext("2d");return _.font="bold "+9*a+"px Helvetica,Arial,sans-serif",_.textBaseline="top",_.fillStyle=e,_.fillRect(0,0,c,u),_.fillStyle=t,_.fillText(l,d,p),_.fillRect(f,y,v,x),_.fillStyle=e,_.globalAlpha=.9,_.fillRect(f,y,v,x),{dom:L,update:function(S,Z){n=Math.min(n,S),r=Math.max(r,S),_.fillStyle=e,_.globalAlpha=1,_.fillRect(0,0,c,y),_.fillStyle=t,_.fillText(s(S)+" "+l+" ("+s(n)+"-"+s(r)+")",d,p),_.drawImage(L,f+a,y,v-a,x,f,y,v-a,x),_.fillRect(f+v-a,y,a,x),_.fillStyle=e,_.globalAlpha=.9,_.fillRect(f+v-a,y,a,s((1-S/Z)*x))}}};const fi=parseInt(m.REVISION.replace(/\D+/g,"")),Ts=fi>=125?"uv1":"uv2";function Wa(l,t){if(t===m.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),l;if(t===m.TriangleFanDrawMode||t===m.TriangleStripDrawMode){let e=l.getIndex();if(e===null){const a=[],c=l.getAttribute("position");if(c!==void 0){for(let u=0;u<c.count;u++)a.push(u);l.setIndex(a),e=l.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),l}const n=e.count-2,r=[];if(e)if(t===m.TriangleFanDrawMode)for(let a=1;a<=n;a++)r.push(e.getX(0)),r.push(e.getX(a)),r.push(e.getX(a+1));else for(let a=0;a<n;a++)a%2===0?(r.push(e.getX(a)),r.push(e.getX(a+1)),r.push(e.getX(a+2))):(r.push(e.getX(a+2)),r.push(e.getX(a+1)),r.push(e.getX(a)));r.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=l.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),l}var Tt=Uint8Array,bn=Uint16Array,Gs=Uint32Array,Ca=new Tt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Va=new Tt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ah=new Tt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Aa=function(l,t){for(var e=new bn(31),n=0;n<31;++n)e[n]=t+=1<<l[n-1];for(var r=new Gs(e[30]),n=1;n<30;++n)for(var s=e[n];s<e[n+1];++s)r[s]=s-e[n]<<5|n;return[e,r]},Fa=Aa(Ca,2),Xa=Fa[0],Fh=Fa[1];Xa[28]=258,Fh[258]=28;for(var Xh=Aa(Va,0),kh=Xh[0],Ps=new bn(32768),We=0;We<32768;++We){var _n=(We&43690)>>>1|(We&21845)<<1;_n=(_n&52428)>>>2|(_n&13107)<<2,_n=(_n&61680)>>>4|(_n&3855)<<4,Ps[We]=((_n&65280)>>>8|(_n&255)<<8)>>>1}for(var Vr=function(l,t,e){for(var n=l.length,r=0,s=new bn(t);r<n;++r)++s[l[r]-1];var a=new bn(t);for(r=0;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;var c;if(e){c=new bn(1<<t);var u=15-t;for(r=0;r<n;++r)if(l[r])for(var d=r<<4|l[r],p=t-l[r],f=a[l[r]-1]++<<p,y=f|(1<<p)-1;f<=y;++f)c[Ps[f]>>>u]=d}else for(c=new bn(n),r=0;r<n;++r)l[r]&&(c[r]=Ps[a[l[r]-1]++]>>>15-l[r]);return c},Ar=new Tt(288),We=0;We<144;++We)Ar[We]=8;for(var We=144;We<256;++We)Ar[We]=9;for(var We=256;We<280;++We)Ar[We]=7;for(var We=280;We<288;++We)Ar[We]=8;for(var ka=new Tt(32),We=0;We<32;++We)ka[We]=5;var Dh=Vr(Ar,9,1),zh=Vr(ka,5,1),Is=function(l){for(var t=l[0],e=1;e<l.length;++e)l[e]>t&&(t=l[e]);return t},Kt=function(l,t,e){var n=t/8|0;return(l[n]|l[n+1]<<8)>>(t&7)&e},Ws=function(l,t){var e=t/8|0;return(l[e]|l[e+1]<<8|l[e+2]<<16)>>(t&7)},Oh=function(l){return(l/8|0)+(l&7&&1)},Kh=function(l,t,e){(e==null||e>l.length)&&(e=l.length);var n=new(l instanceof bn?bn:l instanceof Gs?Gs:Tt)(e-t);return n.set(l.subarray(t,e)),n},Rh=function(l,t,e){var n=l.length;if(!n||e&&!e.l&&n<5)return t||new Tt(0);var r=!t||e,s=!e||e.i;e||(e={}),t||(t=new Tt(n*3));var a=function(je){var Je=t.length;if(je>Je){var Qe=new Tt(Math.max(Je*2,je));Qe.set(t),t=Qe}},c=e.f||0,u=e.p||0,d=e.b||0,p=e.l,f=e.d,y=e.m,v=e.n,x=n*8;do{if(!p){e.f=c=Kt(l,u,1);var L=Kt(l,u+1,3);if(u+=3,L)if(L==1)p=Dh,f=zh,y=9,v=5;else if(L==2){var G=Kt(l,u,31)+257,A=Kt(l,u+10,15)+4,K=G+Kt(l,u+5,31)+1;u+=14;for(var D=new Tt(K),O=new Tt(19),V=0;V<A;++V)O[Ah[V]]=Kt(l,u+V*3,7);u+=A*3;for(var R=Is(O),W=(1<<R)-1,k=Vr(O,R,1),V=0;V<K;){var N=k[Kt(l,u,W)];u+=N&15;var _=N>>>4;if(_<16)D[V++]=_;else{var H=0,j=0;for(_==16?(j=3+Kt(l,u,3),u+=2,H=D[V-1]):_==17?(j=3+Kt(l,u,7),u+=3):_==18&&(j=11+Kt(l,u,127),u+=7);j--;)D[V++]=H}}var q=D.subarray(0,G),J=D.subarray(G);y=Is(q),v=Is(J),p=Vr(q,y,1),f=Vr(J,v,1)}else throw"invalid block type";else{var _=Oh(u)+4,S=l[_-4]|l[_-3]<<8,Z=_+S;if(Z>n){if(s)throw"unexpected EOF";break}r&&a(d+S),t.set(l.subarray(_,Z),d),e.b=d+=S,e.p=u=Z*8;continue}if(u>x){if(s)throw"unexpected EOF";break}}r&&a(d+131072);for(var oe=(1<<y)-1,ie=(1<<v)-1,te=u;;te=u){var H=p[Ws(l,u)&oe],me=H>>>4;if(u+=H&15,u>x){if(s)throw"unexpected EOF";break}if(!H)throw"invalid length/literal";if(me<256)t[d++]=me;else if(me==256){te=u,p=null;break}else{var be=me-254;if(me>264){var V=me-257,he=Ca[V];be=Kt(l,u,(1<<he)-1)+Xa[V],u+=he}var ve=f[Ws(l,u)&ie],ke=ve>>>4;if(!ve)throw"invalid distance";u+=ve&15;var J=kh[ke];if(ke>3){var he=Va[ke];J+=Ws(l,u)&(1<<he)-1,u+=he}if(u>x){if(s)throw"unexpected EOF";break}r&&a(d+131072);for(var Ye=d+be;d<Ye;d+=4)t[d]=t[d-J],t[d+1]=t[d+1-J],t[d+2]=t[d+2-J],t[d+3]=t[d+3-J];d=Ye}}e.l=p,e.p=te,e.b=d,p&&(c=1,e.m=y,e.d=f,e.n=v)}while(!c);return d==t.length?t:Kh(t,0,d)},Yh=new Tt(0),Uh=function(l){if((l[0]&15)!=8||l[0]>>>4>7||(l[0]<<8|l[1])%31)throw"invalid zlib data";if(l[1]&32)throw"invalid zlib data: preset dictionaries not supported"};function Bh(l,t){return Rh((Uh(l),l.subarray(2,-4)),t)}var Nh=typeof TextDecoder<"u"&&new TextDecoder,jh=0;try{Nh.decode(Yh,{stream:!0}),jh=1}catch{}class Jh extends m.Mesh{constructor(t,e={}){super(t),this.isWater=!0;const n=this,r=e.textureWidth!==void 0?e.textureWidth:512,s=e.textureHeight!==void 0?e.textureHeight:512,a=e.clipBias!==void 0?e.clipBias:0,c=e.alpha!==void 0?e.alpha:1,u=e.time!==void 0?e.time:0,d=e.waterNormals!==void 0?e.waterNormals:null,p=e.sunDirection!==void 0?e.sunDirection:new m.Vector3(.70707,.70707,0),f=new m.Color(e.sunColor!==void 0?e.sunColor:16777215),y=new m.Color(e.waterColor!==void 0?e.waterColor:8355711),v=e.eye!==void 0?e.eye:new m.Vector3(0,0,0),x=e.distortionScale!==void 0?e.distortionScale:20,L=e.side!==void 0?e.side:m.FrontSide,_=e.fog!==void 0?e.fog:!1,S=new m.Plane,Z=new m.Vector3,G=new m.Vector3,A=new m.Vector3,K=new m.Matrix4,D=new m.Vector3(0,0,-1),O=new m.Vector4,V=new m.Vector3,R=new m.Vector3,W=new m.Vector4,k=new m.Matrix4,N=new m.PerspectiveCamera,H=new m.WebGLRenderTarget(r,s),j={uniforms:m.UniformsUtils.merge([m.UniformsLib.fog,m.UniformsLib.lights,{normalSampler:{value:null},mirrorSampler:{value:null},alpha:{value:1},time:{value:0},size:{value:1},distortionScale:{value:20},textureMatrix:{value:new m.Matrix4},sunColor:{value:new m.Color(8355711)},sunDirection:{value:new m.Vector3(.70707,.70707,0)},eye:{value:new m.Vector3},waterColor:{value:new m.Color(5592405)}}]),vertexShader:`
|
|
2
2
|
uniform mat4 textureMatrix;
|
|
3
3
|
uniform float time;
|
|
4
4
|
|
|
@@ -536,7 +536,7 @@
|
|
|
536
536
|
gl_FragColor = vec4(finalColor, uOpacity);
|
|
537
537
|
if (uOpacity >= 0.99) gl_FragDepthEXT = gl_FragCoord.z;
|
|
538
538
|
}
|
|
539
|
-
`,transparent:!0,side:m.DoubleSide,depthWrite:!0}),p=new m.Mesh(a,d);return p.renderOrder=5e3,p}function Kf(l,t,e){const{geometry:n,center:r,avgY:s}=Ml(e),a=new Jh(n,{textureWidth:512,textureHeight:512,waterNormals:new m.TextureLoader().load(l.normalMap,function(d){d.wrapS=d.wrapT=m.RepeatWrapping}),waterColor:l.color||"#19AAEE",sunColor:l.sunColor||"#05FFF8",distortionScale:1,alpha:l.opacity||.8}),c=a.onBeforeRender,u=a.onAfterRender;return a.onBeforeRender=(d,p,f,y,v,x)=>{t.tilemap.autoUpdate=!1,c.call(a,d,p,f,y,v,x)},a.onAfterRender=(d,p,f,y,v,x)=>{t.tilemap.autoUpdate=!0,u.call(a,d,p,f,y,v,x)},a.material.uniforms.size.value=.1,a.rotation.x=-Math.PI/2,a.position.set(r.x,s,r.z),t.viewer.addEventListener("update",()=>{a.material.uniforms.time.value+=1/60}),a}function Ml(l){let t=0;for(let a=1;a<l.length;a+=3)t+=l[a];t/=l.length/3;const e={x:0,z:0},n=[];for(let a=0;a<l.length;a+=3)e.x+=l[a],e.z+=l[a+2];e.x/=l.length/3,e.z/=l.length/3;for(let a=0;a<l.length;a+=3)n.push(new m.Vector2(l[a]-e.x,-(l[a+2]-e.z)));const r=new m.Shape(n);return{geometry:new m.ShapeGeometry(r),center:e,avgY:t}}async function Rf(l,t){const{geometry:e,center:n,avgY:r}=Ml(t),s=await Pt._loadTexture(l.normalMap),a=await Pt._loadTexture(l.normalMap);s.wrapS=s.wrapT=m.RepeatWrapping,a.wrapS=a.wrapT=m.RepeatWrapping,s.repeat.set(.015,.015),a.repeat.set(.005,.005);const c=new m.MeshStandardMaterial({color:new m.Color(l.color).multiplyScalar(3.5),roughness:.1,metalness:.8,transparent:!0,opacity:.9,fog:!1,normalMap:s,normalScale:new m.Vector2(1.5,1.5),envMapIntensity:2}),u=new m.Mesh(e,c);u.rotation.x=-Math.PI/2,u.position.set(n.x,r+.15,n.z),u.castShadow=!1,u.receiveShadow=!0;let d=0;return u.onBeforeRender=()=>{const p=performance.now(),f=d?(p-d)/1e3:.016;s.offset.x+=f*.08,s.offset.y+=f*.03,a.offset.x-=f*.12,a.offset.y+=f*.02,u.position.y=r+.5+Math.sin(p*.02)*.02,d=p},u}function Yf(l,t){l.color=new m.Color(l.hexcolor),l.boundstext&&(l.bounds=new m.Vector3(l.boundstext.x,l.boundstext.y,l.boundstext.z));const e=new kf(l);return e.castShadow=!0,e.scale.setScalar(50),e.position.copy(t),e}async function Uf(l,t){const n={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,fixedSize:50},...l};n.fontSize=Math.min(Math.max(n.fontSize,8),128);const r=document.createElement("canvas"),s=r.getContext("2d");if(!s)throw new Error("canvas context is null");const a=`${n.fontStyle} ${n.fontWeight} ${n.fontSize}px ${n.fontFamily}`;s.font=a;const c=n.showBackground?20:0,u=100,d=50,p=s.measureText(n.text),f=Math.max(u,p.width+c*2),y=Math.max(d,n.fontSize*1.5+c*2);r.width=Math.min(f,2048),r.height=Math.min(y,2048),s.clearRect(0,0,r.width,r.height),s.font=a,n.showBackground&&(n.bgStyle===1?(s.fillStyle=n.bgColor,s.globalAlpha=n.bgOpacity,s.beginPath(),Ll(s,c/2,c/2,r.width-c,r.height-c,n.roundRectRadius),s.fill(),s.globalAlpha=1,s.shadowColor=n.shadowColor,s.shadowBlur=n.shadowBlur,s.shadowOffsetX=n.shadowOffsetX,s.shadowOffsetY=n.shadowOffsetY):(s.fillStyle=n.bgColor,s.globalAlpha=n.bgOpacity,s.beginPath(),Sl(s,r.width/2,r.height/2,r.width*.8,r.height*.8,n.roundRectRadius,n.bubblePointerHeight,n.bubblePointerWidth),s.fill(),s.globalAlpha=1,s.strokeStyle=n.bubbleBorderColor,s.lineWidth=n.bubbleBorderWidth,s.stroke())),s.textAlign="center",s.textBaseline="middle",n.strokeWidth>0&&(s.strokeStyle=n.strokeColor,s.lineWidth=n.strokeWidth,s.lineJoin="round",s.strokeText(n.text,r.width/2,r.height/2)),s.fillStyle=n.textColor,s.fillText(n.text,r.width/2,r.height/2),s.shadowColor="transparent";const v=new m.CanvasTexture(r);v.magFilter=m.NearestFilter,v.minFilter=m.LinearMipmapLinearFilter,v.anisotropy=16;const x=new m.SpriteMaterial({map:v,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),L=new m.Sprite(x),_=n.fixedSize;return L.scale.set(r.width*_/100,r.height*_/100,1),t&&L.position.copy(t),L.renderOrder=9999,L}async function Bf(l,t,e){const r={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,screenSpaceSize:20,maxVisibleDistance:1/0},...l};r.fontSize=Math.min(Math.max(r.fontSize,8),128);const s=document.createElement("canvas"),a=s.getContext("2d");if(!a)throw new Error("Failed to get canvas context");const c=`${r.fontStyle} ${r.fontWeight} ${r.fontSize}px ${r.fontFamily}`;a.font=c;const u=r.showBackground?20:0,d=100,p=50,f=a.measureText(r.text),y=Math.max(d,f.width+u*2),v=Math.max(p,r.fontSize*1.5+u*2);s.width=Math.min(y,2048),s.height=Math.min(v,2048),a.clearRect(0,0,s.width,s.height),a.font=c,r.showBackground&&(r.bgStyle===1?(a.fillStyle=r.bgColor,a.globalAlpha=r.bgOpacity,a.beginPath(),Ll(a,u/2,u/2,s.width-u,s.height-u,r.roundRectRadius),a.fill(),a.globalAlpha=1,a.shadowColor=r.shadowColor,a.shadowBlur=r.shadowBlur,a.shadowOffsetX=r.shadowOffsetX,a.shadowOffsetY=r.shadowOffsetY):(a.fillStyle=r.bgColor,a.globalAlpha=r.bgOpacity,a.beginPath(),Sl(a,s.width/2,s.height/2,s.width*.8,s.height*.8,r.roundRectRadius,r.bubblePointerHeight,r.bubblePointerWidth),a.fill(),a.globalAlpha=1,a.strokeStyle=r.bubbleBorderColor,a.lineWidth=r.bubbleBorderWidth,a.stroke())),a.textAlign="center",a.textBaseline="middle",r.strokeWidth>0&&(a.strokeStyle=r.strokeColor,a.lineWidth=r.strokeWidth,a.lineJoin="round",a.strokeText(r.text,s.width/2,s.height/2)),a.fillStyle=r.textColor,a.fillText(r.text,s.width/2,s.height/2),a.shadowColor="transparent";const x=new m.CanvasTexture(s),L=new m.SpriteMaterial({map:x,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),_=new m.Sprite(L);_.position.copy(t),_.renderOrder=9999,_.userData.isLabel=!0;const S=()=>{if(!_.visible)return;const G=e.viewer.camera.position.distanceTo(_.position);if(G>r.maxVisibleDistance){_.visible=!1;return}_.visible=!0;const A=new m.Vector2;e.viewer.renderer.getSize(A);const K=A.height,D=r.screenSpaceSize/s.height*(G/Math.tan(m.MathUtils.degToRad(e.viewer.camera.fov)/2))*(2/K);_.scale.set(D*s.width,D*s.height,1),_.lookAt(e.viewer.camera.position)};S();const Z=()=>S();return _.addEventListener("dispose",()=>{e.viewer.renderer.domElement.removeEventListener("resize",S)}),e.viewer.renderer.domElement.addEventListener("resize",S),e.viewer.camera.addEventListener("change",S),_.onBeforeRender=Z,_}function Ll(l,t,e,n,r,s){l.beginPath(),l.moveTo(t+s,e),l.lineTo(t+n-s,e),l.quadraticCurveTo(t+n,e,t+n,e+s),l.lineTo(t+n,e+r-s),l.quadraticCurveTo(t+n,e+r,t+n-s,e+r),l.lineTo(t+s,e+r),l.quadraticCurveTo(t,e+r,t,e+r-s),l.lineTo(t,e+s),l.quadraticCurveTo(t,e,t+s,e),l.closePath()}function Sl(l,t,e,n,r,s,a,c){if(n<=0)throw new Error("Width must be positive");if(r<=0)throw new Error("Height must be positive");if(s<0)throw new Error("Radius cannot be negative");const u=n,d=r,p=Math.min(s,n/2,r/2),f=a??10,y=c??15;l.beginPath(),l.moveTo(t-u/2+p,e-d/2),l.lineTo(t+u/2-p,e-d/2),l.quadraticCurveTo(t+u/2,e-d/2,t+u/2,e-d/2+p),l.lineTo(t+u/2,e+d/2-p),l.quadraticCurveTo(t+u/2,e+d/2,t+u/2-p,e+d/2),l.lineTo(t+y/2,e+d/2),l.lineTo(t,e+d/2+f),l.lineTo(t-y/2,e+d/2),l.lineTo(t-u/2+p,e+d/2),l.quadraticCurveTo(t-u/2,e+d/2,t-u/2,e+d/2-p),l.lineTo(t-u/2,e-d/2+p),l.quadraticCurveTo(t-u/2,e-d/2,t-u/2+p,e-d/2),l.closePath()}async function Nf(l,t,e){const{text:n,iconUrl:r,fontSize:s=30,iconSize:a=60,fontFamily:c="Arial",padding:u={},bgColor:d="rgba(0,0,0,0.0)",textColor:p="rgb(255,255,255)",strokeColor:f="rgb(0,0,0)",strokeWidth:y=s/9,iconScale:v=.8,canvasScale:x=1,renderbg:L=!0,textOffset:_={x:0,y:0}}=l,S={top:0,right:1,bottom:0,left:0,...u};let Z=null;r&&(Z=await Jf(r));const{canvas:G,width:A,height:K,center:D}=await jf({text:n,iconImage:Z,fontSize:s,iconSize:a,fontFamily:c,padding:S,bgColor:d,textColor:p,strokeColor:f,strokeWidth:y,iconScale:v,canvasScale:x,renderbg:L,textOffset:_},t),O=new m.Texture(G);O.needsUpdate=!0;const V=new m.SpriteMaterial({map:O,transparent:!0,depthTest:!0,depthWrite:!0,blending:m.NormalBlending,sizeAttenuation:!1,alphaTest:.01}),R=new m.Sprite(V),W=.001;return R.scale.set(A*W,K*W,1),R.center.set(D[0],D[1]),e&&R.position.copy(e),R.renderOrder=999,R}async function jf(l,t){return new Promise(e=>{const{text:n,iconImage:r,fontSize:s,iconSize:a,fontFamily:c,padding:u,bgColor:d,textColor:p,strokeColor:f,strokeWidth:y,iconScale:v,canvasScale:x,renderbg:L,textOffset:_={x:0,y:0}}=l,Z=document.createElement("canvas").getContext("2d");if(!Z)throw new Error("Could not get temp canvas context");Z.font=`500 ${s}px ${c}`;const G=Z.measureText(n),A=G.width,K=G.actualBoundingBoxAscent||s*.8,D=G.actualBoundingBoxDescent||s*.2,O=r!==null;let V=0,R=0,W=0,k=0;if(O){V=0,R=0,W=a,k=a;const he=a/2+_.x,ve=a/2+_.y,ke=he,Ye=he+A,je=ve-K,Je=ve+D;V=Math.min(V,ke),W=Math.max(W,Ye),R=Math.min(R,je),k=Math.max(k,Je)}else{const he=_.x,ve=_.x+A,ke=_.y-K,Ye=_.y+D;V=he,W=ve,R=ke,k=Ye}const N=W-V,H=k-R,j=Math.ceil(N+u.left+u.right)*x,q=Math.ceil(H+u.top+u.bottom)*x,J=u.left-V,oe=u.top-R,ie=t._getCanvas(j,q,n);ie.width=j,ie.height=q;const te=ie.getContext("2d");if(!te)throw new Error("Could not get canvas context");te.clearRect(0,0,j,q),te.globalCompositeOperation="source-over",te.save(),te.scale(x,x);const me=j/x,be=q/x;if(L&&(te.fillStyle=d,te.fillRect(0,0,me,be)),r){const he=J,ve=oe,ke=a*v,Ye=(a-ke)/2,je=(a-ke)/2;te.imageSmoothingEnabled=!1,te.drawImage(r,he+Ye,ve+je,ke,ke),te.font=`500 ${s}px ${c}`,te.textBaseline="alphabetic",te.textAlign="left";const Je=J+a/2+_.x,Qe=oe+a/2+_.y;y>0&&(te.strokeStyle=f,te.lineWidth=y,te.strokeText(n,Je,Qe)),te.fillStyle=p,te.fillText(n,Je,Qe)}else{te.font=`500 ${s}px ${c}`,te.textBaseline="alphabetic",te.textAlign="left";const he=J+_.x,ve=oe+_.y;y>0&&(te.strokeStyle=f,te.lineWidth=y,te.strokeText(n,he,ve)),te.fillStyle=p,te.fillText(n,he,ve)}te.restore(),e({canvas:ie,width:me,height:be,center:[(a*.5+u.left)/me,(1-v)*.5]})})}function Jf(l){return new Promise((t,e)=>{const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=r=>e(new Error(`Failed to load image: ${l} ${r}`)),n.src=l})}async function Qf(l,t,e){const r=new m.CylinderGeometry(.2,.2,24,12),s=new m.MeshBasicMaterial({color:l.color}),a=await Pt._loadTexture(l.icon),c=new m.PointsMaterial({size:80*window.innerHeight/window.innerHeight,fog:!1,opacity:1,transparent:!0,toneMapped:!1,blending:m.AdditiveBlending,map:a,sizeAttenuation:!0,depthTest:!0,depthWrite:!1}),u=new m.InstancedMesh(r,s,t.length);u.position.add(e.prjcenter),u.castShadow=!0,u.renderOrder=1;const d=new m.Object3D,p=[];for(let x=0;x<t.length;x++){const L=t[x],_=new m.Vector3(L.coordinates[0],L.coordinates[1],L.coordinates[2]||0),Z=e.geo2world(_).sub(e.prjcenter);d.position.copy(Z),d.updateMatrix(),u.setMatrixAt(x,d.matrix),p.push(Z.x,0,Z.z)}const f=new Float32Array(p),y=new m.BufferGeometry;y.setAttribute("position",new m.BufferAttribute(f,3));const v=new m.Points(y,c);return v.position.add(e.prjcenter),v.position.y=1.5*10,v.renderOrder=99999999,v.visible=!0,console.log(e,"map"),{points:v,InstancedCol:u}}const Yt=class Yt{constructor(t){this.config=t}async applyTo(t){if(!t)return!1;try{switch(t.visible=this.config.visible!==!1,this.config.zIndex&&(t.renderOrder=this.config.zIndex),this.config.type){case"basic-point":case"icon-point":case"icon-label-point":return this._applyPointStyle(t);case"basic-line":return this._applyLineStyle(t);case"gltf":case"fbx":return this._applyModelStyle(t);case"basic-polygon":return this._applyPolygonStyle(t);case"extrude-polygon":return this._applyExtrudeStyle(t);case"water":case"base-water":return this._applyWaterStyle(t);case"cloud":return this._applyCloudStyle(t);case"canvas-label":case"canvas-label-fixed":return this._applyTextSpriteStyle(t);case"light":return this._applyLightStyle(t);case"custom":return this._applyCustomStyle(t);default:throw new Error("Unknown style type")}}catch(e){return console.error("Style apply failed:",e),t.visible=!1,!1}}async _applyPointStyle(t){const e=this.config;return e.type==="icon-point"?await this._applyIconPoint(t,e):e.type==="basic-point"?this._applyBasicPoint(t,e):e.type==="icon-label-point"&&this._applyIconLabelPoint(t,e),!0}async _applyIconPoint(t,e){let n;if(t instanceof m.Sprite)n=t;else if(n=await _l(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let u=t.parent;u._threeGeometry=n,u._updateGeometry()}const r=e.size,[s,a]=Array.isArray(r)?r:[r,r];if(s<=0||a<=0){console.error("Invalid sprite size:",e.size),n.visible=!1;return}const c=n.material;try{if(c.map=await Yt._loadTexture(e.url),!c.map)throw new Error("Texture failed to load");c.needsUpdate=!0,n.scale.set(s,a,1),e.rotation!==void 0&&(n.rotation.z=e.rotation)}catch(u){console.error("Failed to load texture:",e.url,u),n.visible=!1}}_applyBasicPoint(t,e){let n;if(t instanceof m.Points)n=t;else if(n=bl(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let s=t.parent;s._threeGeometry=n,s._updateGeometry()}const r=n.material;r.size=e.size,e.color&&r.color.set(e.color),e.glow&&(r.sizeAttenuation=!1)}_applyIconLabelPoint(t,e){return!0}_applyLineStyle(t){const e=this.config;if(t.parent){let n=t.parent;n._threeGeometry=Gi(e,n._vertexPoints),n._updateGeometry()}return!0}_applyPolygonStyle(t){return!0}_applyExtrudeStyle(t){return!0}_applyWaterStyle(t){return!0}_applyCloudStyle(t){return!0}_applyTextSpriteStyle(t){return!0}_applyLightStyle(t){return!0}async _applyModelStyle(t){return!0}async _applyCustomStyle(t){const n=await this.config.build();return t instanceof m.Group&&(t.clear(),t.add(n)),!0}static async _loadTexture(t){if(Yt._textureCache.has(t))return Yt._textureCache.get(t);const e=await new Promise((n,r)=>{Yt._textureLoader.load(t,n,void 0,r)});return e.premultiplyAlpha=!0,Yt._textureCache.set(t,e),e}static create(t){return t instanceof Yt?t:new Yt(t)}};T(Yt,"_textureCache",new Map),T(Yt,"_textureLoader",new m.TextureLoader);let Pt=Yt;const et=[];for(let l=0;l<256;++l)et.push((l+256).toString(16).slice(1));function Hf(l,t=0){return(et[l[t+0]]+et[l[t+1]]+et[l[t+2]]+et[l[t+3]]+"-"+et[l[t+4]]+et[l[t+5]]+"-"+et[l[t+6]]+et[l[t+7]]+"-"+et[l[t+8]]+et[l[t+9]]+"-"+et[l[t+10]]+et[l[t+11]]+et[l[t+12]]+et[l[t+13]]+et[l[t+14]]+et[l[t+15]]).toLowerCase()}let to;const Ef=new Uint8Array(16);function qf(){if(!to){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");to=crypto.getRandomValues.bind(crypto)}return to(Ef)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function $f(l,t,e){if(Zl.randomUUID&&!l)return Zl.randomUUID();l=l||{};const n=l.random??l.rng?.()??qf();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Hf(n)}var Tl=(l=>(l.POINT="point",l.LINE_VERTEX="line_vertex",l.POLYGON_CENTER="polygon_center",l.LABEL="label",l.ICON="icon",l.CLUSTER="cluster",l))(Tl||{}),rn=(l=>(l.NO_COLLISION="no_collision",l.PRIORITY_LOST="priority_lost",l.OUT_OF_VIEWPORT="out_of_viewport",l.ZOOM_FILTERED="zoom_filtered",l.MANUAL_HIDDEN="manual_hidden",l.GROUP_COLLISION="group_collision",l))(rn||{});class Sn extends Es(Mi(Li(m.Object3D))){constructor(e){super();T(this,"_position");T(this,"_threeGeometry");T(this,"_geometry");T(this,"_layer");T(this,"_style");T(this,"_id");T(this,"_styleQueue",[]);T(this,"_isApplyingStyle",!1);T(this,"_isGeometryInitializing",!1);T(this,"_collisionState",{visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:Date.now()});T(this,"_collisionConfig",{enabled:!0,priority:50,padding:4,minZoom:0,maxZoom:24});T(this,"_animationRef",null);Ns(e.geometry,"geometry","geometry must be specified"),this._geometry=e.geometry,this._position=new m.Vector3(0,0,0),this._threeGeometry=new m.Object3D,e.userData&&(this.userData=Object.assign({},JSON.parse(JSON.stringify(e.userData)))),e.style&&this.setStyle(e.style),e.id?this._id=e.id:this._id=$f()}async initializeGeometry(){if(!(this._isGeometryInitializing||this._threeGeometry)){this._isGeometryInitializing=!0;try{await this._toThreeJSGeometry(),this._processStyleQueue()}finally{this._isGeometryInitializing=!1}}}setStyle(e){const n=e instanceof Pt?e:new Pt(e);this._style=n;const r=JSON.parse(JSON.stringify(n.config));return this._styleQueue.push(r),this._tryProcessQueue(),this}getStyle(){return this._style}async _applyStyleWithRetry(e,n=3,r=100){let s=null;for(let a=1;a<=n;a++)try{this._threeGeometry.parent||(this.add(this._threeGeometry),await new Promise(c=>requestAnimationFrame(c))),await e.applyTo(this._threeGeometry);return}catch(c){if(s=c,a<n){const u=r*Math.pow(2,a-1);await new Promise(d=>setTimeout(d,u))}}throw s||new Error("样式应用失败,重试次数耗尽")}async _processStyleQueue(){if(!this._threeGeometry||this._isApplyingStyle||this._styleQueue.length===0)return;this._isApplyingStyle=!0;const e=this._styleQueue[0];try{const n=new Pt(JSON.parse(JSON.stringify(e)));await this._applyStyleWithRetry(n),this._styleQueue.shift(),this._styleQueue.length>0&&await this._processStyleQueue()}catch(n){throw n}finally{this._isApplyingStyle=!1,this._styleQueue.length>0&&this._tryProcessQueue()}}_tryProcessQueue(){this._threeGeometry&&!this._isApplyingStyle&&this._styleQueue.length>0?this._processStyleQueue().catch(n=>{this._isApplyingStyle=!1,this._tryProcessQueue(),console.warn(n)}):!this._threeGeometry&&!this._isGeometryInitializing&&this.initializeGeometry()}addTo(e){return e.addFeature(this),this}getLayer(){return this._layer||null}getMap(){return this._layer?.getMap()||null}_bindLayer(e){if(this._layer&&this._layer!==e)throw new Error("Feature cannot be added to multiple layers");this._layer=e}_updateGeometry(){this._disposeGeometry(),this._threeGeometry&&(this._threeGeometry.position.copy(this._position),this._threeGeometry.renderOrder=999,this.add(this._threeGeometry),this.updateMatrixWorld(!0),this._tryProcessQueue())}_remove(){return this.getLayer()?(this._unbind(),this):this}_unbind(){const e=this.getLayer();e&&(e.onRemoveFeature&&e.onRemoveFeature(this),delete this._layer)}_disposeGeometry(){this._threeGeometry&&(this.clear(),"traverse"in this&&this._threeGeometry.traverse(e=>{e instanceof m.Mesh?(e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(n=>n.dispose()):e.material?.dispose()):"isLine"in e&&e.isLine&&(e.geometry?.dispose(),e.material?.dispose())}))}get collidable(){return this._collisionConfig.enabled}get collisionType(){return Tl.POINT}getCollisionPriority(){return this.userData.collisionPriority??this._style?.config.collisionPriority??this._collisionConfig.priority}getScreenBoundingBox(e,n){if(!this.collidable)return null;try{const r=new m.Vector3;this._threeGeometry.getWorldPosition(r);const s=r.clone().project(e);if(!(s.x>=-1.1&&s.x<=1.1&&s.y>=-1.1&&s.y<=1.1&&s.z>=-1&&s.z<=1))return null;const{width:c,height:u}=n.domElement,d=(s.x*.5+.5)*c,p=(-s.y*.5+.5)*u,f=this._calculateCollisionBoundingBox(e,n);return f?{id:this._id,x:d+f.offsetX,y:p+f.offsetY,width:20+this._collisionConfig.padding*2,height:20+this._collisionConfig.padding*2,priority:this.getCollisionPriority(),featureId:this._id,layerId:this._layer?.getId()||"unknown",type:this.collisionType,data:this.getCollisionData()}:null}catch(r){return console.warn(`Feature ${this._id} 包围盒计算失败:`,r),null}}setCollisionVisibility(e,n=rn.MANUAL_HIDDEN){this._collisionState.visible!==e&&(this._animationRef!==null&&(cancelAnimationFrame(this._animationRef),this._animationRef=null),this.visible=e,this._applyFinalAlpha(e?1:0),this._collisionState={visible:e,reason:n,collidedWith:e?[]:this._collisionState.collidedWith,timestamp:Date.now()})}getCollisionVisibility(){return this._collisionState.visible}setCollisionConfig(e){return Object.assign(this._collisionConfig,e),this}enableCollision(){return this._collisionConfig.enabled=!0,this}disableCollision(){return this._collisionConfig.enabled=!1,this.setCollisionVisibility(!0,rn.MANUAL_HIDDEN),this}_applyVisibilityAlpha(e){this.traverse(n=>{n instanceof m.Mesh&&(Array.isArray(n.material)?n.material.forEach(r=>{r.opacity!==void 0&&(r.opacity=e)}):n.material.opacity!==void 0&&(n.material.opacity=e))})}_applyFinalAlpha(e){this._applyVisibilityAlpha(e),this.traverse(n=>{n instanceof m.Mesh&&(n.material.needsUpdate=!0)})}getCollisionData(){return{featureType:this.constructor.name,userData:this.userData,styleConfig:this._style?.config}}_calculateCollisionBoundingBox(e,n){if(!this.visible||!this._threeGeometry||!e||!n)return null;try{const r=new m.Box3().setFromObject(this._threeGeometry);if(r.isEmpty())return this._getFallbackBoundingBox();const s=[new m.Vector3(r.min.x,r.min.y,r.min.z),new m.Vector3(r.max.x,r.min.y,r.min.z),new m.Vector3(r.min.x,r.max.y,r.min.z),new m.Vector3(r.max.x,r.max.y,r.min.z),new m.Vector3(r.min.x,r.min.y,r.max.z),new m.Vector3(r.max.x,r.min.y,r.max.z),new m.Vector3(r.min.x,r.max.y,r.max.z),new m.Vector3(r.max.x,r.max.y,r.max.z)],{width:a,height:c}=n.domElement,u=[];s.forEach(D=>{const O=D.clone().project(e),V=(O.x*.5+.5)*a,R=(-O.y*.5+.5)*c;u.push(new m.Vector2(V,R))});let d=1/0,p=-1/0,f=1/0,y=-1/0;u.forEach(D=>{d=Math.min(d,D.x),p=Math.max(p,D.x),f=Math.min(f,D.y),y=Math.max(y,D.y)});const v=p-d,x=y-f,L=4,_=Math.max(v,L),S=Math.max(x,L),Z=new m.Vector3;r.getCenter(Z);const G=Z.clone().project(e),A=(G.x*.5+.5)*a,K=(-G.y*.5+.5)*c;return{width:_,height:S,offsetX:d-A,offsetY:f-K}}catch(r){return console.warn("包围盒计算失败:",r),this._getFallbackBoundingBox()}}_getFallbackBoundingBox(){return{width:20,height:20,offsetX:-10,offsetY:-10}}_tileCoordToLocalWorld(e,n,r,s){const{tileZ:a,tileX:c,tileY:u,extent:d,tileSize:p}=r,f=(e/d-.5)*p,y=(.5-n/d)*p;return s.tileIDToWorldCenter(a,c,u).clone().add(new m.Vector3(f,y,0)).sub(s.prjcenter)}}class Bn extends Si{constructor(e,n){super(e,n);T(this,"_feaList");T(this,"_collision",!1);this._feaList=[],n?.collision&&(this._collision=!0)}addFeature(e){const n=Array.isArray(e)?e:[e];for(const r of n)if(!(!r||!(r instanceof Sn))&&!r.getLayer()){if(!this.validateFeature(r)){console.error(`Feature ${r.id} does not match the layer's type requirements`);continue}r._bindLayer(this),this._feaList.push(r),r.getMap()&&r._toThreeJSGeometry(),this._clouds&&(this.map.viewer.scene.add(this._clouds),console.log("我是云朵被添加cloud",this.map.viewer.scene)),this.add(r)}return this}getFeatures(e,n){if(!e)return this._feaList.slice(0);const r=[];let s,a;for(let c=0,u=this._feaList.length;c<u;c++)s=this._feaList[c],n?a=e.call(n,s):a=e(s),a&&r.push(s);return r}getCount(){return this._feaList.length}isEmpty(){return!this._feaList.length}removeFeature(e){if(!Array.isArray(e))return this.removeFeature([e]);for(let n=e.length-1;n>=0;n--)e[n]instanceof Sn||(e[n]=this.removeFeature(e[n])),!(!e[n]||this!==e[n].getLayer())&&e[n]._remove();return this}onRemoveFeature(e){if(!e)return;const n=e.getLayer();if(!n||n!==this)return;const r=this._findInList(e);r>=0&&this._feaList.splice(r,1),e.parent&&e.parent===this?this.remove(e):console.warn("Feature parent mismatch:",e.parent),this._disposeFeatureResources(e)}_findInList(e){const n=this._feaList.length;if(n===0)return-1;let r=0,s=n-1,a;for(;r<=s;){if(a=Math.floor((r+s)/2),this._feaList[a]===e)return a;r=a+1}return-1}_disposeFeatureResources(e){try{e.geometry&&e.geometry.dispose&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>n.dispose?.()):e.material.dispose&&e.material.dispose()),e instanceof m.Object3D&&e.traverse(n=>{n!==e&&this._disposeFeatureResources(n)})}catch(n){console.error("Error disposing feature resources:",n)}}_mergedGeometry(){this.traverse(e=>{e.isMesh&&e.geometry&&e.material&&console.log("几何体合并中",e)})}setCollisionEngine(e){return this._collisionEngine=e,this}}class ep extends m.Group{constructor(){super(...arguments);T(this,"_layers",new Set);T(this,"_layerids",new Set)}add(...e){return e.forEach(n=>{if(!(n instanceof Si))throw new Error("LayerContainer只能包含Layer实例!");const r=n.getId();if(this._layerids.has(r))throw new Error(`ID为'${r}'的图层已存在于容器中!`);this._layers.add(n),this._layerids.add(r),super.add(n)}),this}remove(...e){return e.forEach(n=>{this._layers.delete(n),this._layerids.delete(n.getId()),super.remove(n)}),this}getLayers(){return Array.from(this._layers)}getLayerById(e){for(const n of this._layers)if(n.getId()===e)return n}clearLayers(){return this._layers.clear(),this._layerids.clear(),super.clear(),this}}class tp{constructor(){T(this,"canvasDict",{})}getCanvas(t=40,e=30,n=1,r){const s=Math.ceil(t*n),a=Math.ceil(e*n),c=r?`${s}_${a}_${r}`:`${s}_${a}`;if(!this.canvasDict[c]){const p=document.createElement("canvas");p.width=s,p.height=a,this.canvasDict[c]=p}const u=this.canvasDict[c],d=u.getContext("2d");return d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,u.width,u.height),d.scale(n,n),u}}function np(l){const t=+this._x.call(null,l),e=+this._y.call(null,l);return Gl(this.cover(t,e),t,e,l)}function Gl(l,t,e,n){if(isNaN(t)||isNaN(e))return l;var r,s=l._root,a={data:n},c=l._x0,u=l._y0,d=l._x1,p=l._y1,f,y,v,x,L,_,S,Z;if(!s)return l._root=a,l;for(;s.length;)if((L=t>=(f=(c+d)/2))?c=f:d=f,(_=e>=(y=(u+p)/2))?u=y:p=y,r=s,!(s=s[S=_<<1|L]))return r[S]=a,l;if(v=+l._x.call(null,s.data),x=+l._y.call(null,s.data),t===v&&e===x)return a.next=s,r?r[S]=a:l._root=a,l;do r=r?r[S]=new Array(4):l._root=new Array(4),(L=t>=(f=(c+d)/2))?c=f:d=f,(_=e>=(y=(u+p)/2))?u=y:p=y;while((S=_<<1|L)===(Z=(x>=y)<<1|v>=f));return r[Z]=s,r[S]=a,l}function rp(l){var t,e,n=l.length,r,s,a=new Array(n),c=new Array(n),u=1/0,d=1/0,p=-1/0,f=-1/0;for(e=0;e<n;++e)isNaN(r=+this._x.call(null,t=l[e]))||isNaN(s=+this._y.call(null,t))||(a[e]=r,c[e]=s,r<u&&(u=r),r>p&&(p=r),s<d&&(d=s),s>f&&(f=s));if(u>p||d>f)return this;for(this.cover(u,d).cover(p,f),e=0;e<n;++e)Gl(this,a[e],c[e],l[e]);return this}function ip(l,t){if(isNaN(l=+l)||isNaN(t=+t))return this;var e=this._x0,n=this._y0,r=this._x1,s=this._y1;if(isNaN(e))r=(e=Math.floor(l))+1,s=(n=Math.floor(t))+1;else{for(var a=r-e||1,c=this._root,u,d;e>l||l>=r||n>t||t>=s;)switch(d=(t<n)<<1|l<e,u=new Array(4),u[d]=c,c=u,a*=2,d){case 0:r=e+a,s=n+a;break;case 1:e=r-a,s=n+a;break;case 2:r=e+a,n=s-a;break;case 3:e=r-a,n=s-a;break}this._root&&this._root.length&&(this._root=c)}return this._x0=e,this._y0=n,this._x1=r,this._y1=s,this}function sp(){var l=[];return this.visit(function(t){if(!t.length)do l.push(t.data);while(t=t.next)}),l}function op(l){return arguments.length?this.cover(+l[0][0],+l[0][1]).cover(+l[1][0],+l[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function at(l,t,e,n,r){this.node=l,this.x0=t,this.y0=e,this.x1=n,this.y1=r}function ap(l,t,e){var n,r=this._x0,s=this._y0,a,c,u,d,p=this._x1,f=this._y1,y=[],v=this._root,x,L;for(v&&y.push(new at(v,r,s,p,f)),e==null?e=1/0:(r=l-e,s=t-e,p=l+e,f=t+e,e*=e);x=y.pop();)if(!(!(v=x.node)||(a=x.x0)>p||(c=x.y0)>f||(u=x.x1)<r||(d=x.y1)<s))if(v.length){var _=(a+u)/2,S=(c+d)/2;y.push(new at(v[3],_,S,u,d),new at(v[2],a,S,_,d),new at(v[1],_,c,u,S),new at(v[0],a,c,_,S)),(L=(t>=S)<<1|l>=_)&&(x=y[y.length-1],y[y.length-1]=y[y.length-1-L],y[y.length-1-L]=x)}else{var Z=l-+this._x.call(null,v.data),G=t-+this._y.call(null,v.data),A=Z*Z+G*G;if(A<e){var K=Math.sqrt(e=A);r=l-K,s=t-K,p=l+K,f=t+K,n=v.data}}return n}function lp(l){if(isNaN(p=+this._x.call(null,l))||isNaN(f=+this._y.call(null,l)))return this;var t,e=this._root,n,r,s,a=this._x0,c=this._y0,u=this._x1,d=this._y1,p,f,y,v,x,L,_,S;if(!e)return this;if(e.length)for(;;){if((x=p>=(y=(a+u)/2))?a=y:u=y,(L=f>=(v=(c+d)/2))?c=v:d=v,t=e,!(e=e[_=L<<1|x]))return this;if(!e.length)break;(t[_+1&3]||t[_+2&3]||t[_+3&3])&&(n=t,S=_)}for(;e.data!==l;)if(r=e,!(e=e.next))return this;return(s=e.next)&&delete e.next,r?(s?r.next=s:delete r.next,this):t?(s?t[_]=s:delete t[_],(e=t[0]||t[1]||t[2]||t[3])&&e===(t[3]||t[2]||t[1]||t[0])&&!e.length&&(n?n[S]=e:this._root=e),this):(this._root=s,this)}function cp(l){for(var t=0,e=l.length;t<e;++t)this.remove(l[t]);return this}function up(){return this._root}function hp(){var l=0;return this.visit(function(t){if(!t.length)do++l;while(t=t.next)}),l}function dp(l){var t=[],e,n=this._root,r,s,a,c,u;for(n&&t.push(new at(n,this._x0,this._y0,this._x1,this._y1));e=t.pop();)if(!l(n=e.node,s=e.x0,a=e.y0,c=e.x1,u=e.y1)&&n.length){var d=(s+c)/2,p=(a+u)/2;(r=n[3])&&t.push(new at(r,d,p,c,u)),(r=n[2])&&t.push(new at(r,s,p,d,u)),(r=n[1])&&t.push(new at(r,d,a,c,p)),(r=n[0])&&t.push(new at(r,s,a,d,p))}return this}function fp(l){var t=[],e=[],n;for(this._root&&t.push(new at(this._root,this._x0,this._y0,this._x1,this._y1));n=t.pop();){var r=n.node;if(r.length){var s,a=n.x0,c=n.y0,u=n.x1,d=n.y1,p=(a+u)/2,f=(c+d)/2;(s=r[0])&&t.push(new at(s,a,c,p,f)),(s=r[1])&&t.push(new at(s,p,c,u,f)),(s=r[2])&&t.push(new at(s,a,f,p,d)),(s=r[3])&&t.push(new at(s,p,f,u,d))}e.push(n)}for(;n=e.pop();)l(n.node,n.x0,n.y0,n.x1,n.y1);return this}function pp(l){return l[0]}function mp(l){return arguments.length?(this._x=l,this):this._x}function gp(l){return l[1]}function yp(l){return arguments.length?(this._y=l,this):this._y}function Pl(l,t,e){var n=new no(t??pp,e??gp,NaN,NaN,NaN,NaN);return l==null?n:n.addAll(l)}function no(l,t,e,n,r,s){this._x=l,this._y=t,this._x0=e,this._y0=n,this._x1=r,this._y1=s,this._root=void 0}function Il(l){for(var t={data:l.data},e=t;l=l.next;)e=e.next={data:l.data};return t}var lt=Pl.prototype=no.prototype;lt.copy=function(){var l=new no(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,e,n;if(!t)return l;if(!t.length)return l._root=Il(t),l;for(e=[{source:t,target:l._root=new Array(4)}];t=e.pop();)for(var r=0;r<4;++r)(n=t.source[r])&&(n.length?e.push({source:n,target:t.target[r]=new Array(4)}):t.target[r]=Il(n));return l},lt.add=np,lt.addAll=rp,lt.cover=ip,lt.data=sp,lt.extent=op,lt.find=ap,lt.remove=lp,lt.removeAll=cp,lt.root=up,lt.size=hp,lt.visit=dp,lt.visitAfter=fp,lt.x=mp,lt.y=yp;class Wl{constructor(t){T(this,"_quadtree");T(this,"_viewport");this._viewport=t,this._rebuildQuadTree()}updateViewport(t){(t.width!==this._viewport.width||t.height!==this._viewport.height)&&(this._viewport=t,this._rebuildQuadTree())}addBoxes(t){t.forEach(e=>{this._isBoxInViewport(e)&&this._quadtree.add(e)})}findCollisions(t){const e=[],n=this._getSearchBounds(t);return this._quadtree.visit((r,s,a,c,u)=>this._checkNodeCollision(n,s,a,c,u)?(r.length||this._getNodeData(r).forEach(p=>{p.id!==t.id&&this._checkBoxCollision(t,p)&&e.push(p)}),!1):void 0),e}clear(){this._rebuildQuadTree()}getAllBoxes(){const t=[];return this._quadtree.visit(e=>{if(!e.length){const n=this._getNodeData(e);t.push(...n)}return!1}),t}_rebuildQuadTree(){this._quadtree=Pl().x(t=>t.x).y(t=>t.y).extent([[0,0],[this._viewport.width,this._viewport.height]])}_isBoxInViewport(t){const e=t.width/2,n=t.height/2;return t.x+e>=0&&t.x-e<=this._viewport.width&&t.y+n>=0&&t.y-n<=this._viewport.height}_getSearchBounds(t){return{x:t.x,y:t.y,width:t.width*2,height:t.height*2}}_checkNodeCollision(t,e,n,r,s){const a=(e+r)/2,c=(n+s)/2,u=r-e,d=s-n;return Math.abs(t.x-a)*2<t.width+u&&Math.abs(t.y-c)*2<t.height+d}_checkBoxCollision(t,e){return Math.abs(t.x-e.x)*2<t.width+e.width&&Math.abs(t.y-e.y)*2<t.height+e.height}_getNodeData(t){return t?Array.isArray(t.data)?t.data:t.data?[t.data]:[]:[]}removeBox(t){const n=this.getAllBoxes().filter(r=>r.id!==t);this.clear(),n.length>0&&this.addBoxes(n)}}class vp{constructor(){T(this,"_strategies",new Map);T(this,"_executionOrder",[])}registerStrategy(t,e){return this._strategies.set(t.name,t),e!==void 0?this._executionOrder.splice(e,0,t.name):this._executionOrder.push(t.name),this}async executeStrategies(t,e){const n=new Map;t.forEach(r=>{n.set(r._id,{featureId:r._id,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp})});for(const r of this._executionOrder){const s=this._strategies.get(r);if(s?.enabled)try{const a=await s.execute(t,e,n);this._mergeResults(n,a)}catch(a){console.error(`策略 ${r} 执行失败:`,a)}}return n}_mergeResults(t,e){e.forEach(n=>{const r=t.get(n.featureId);r&&!r.visible||t.set(n.featureId,n)})}}class wp{constructor(){T(this,"frameStats",new Map);T(this,"summaryStats",{totalFrames:0,averageFrameTime:0,averageFPS:0,minFrameTime:1/0,maxFrameTime:0,totalFeaturesProcessed:0});T(this,"sampleWindowSize",60);T(this,"currentFrameId",0);T(this,"lastReportTime",0);T(this,"reportInterval",5e3);T(this,"performanceThresholds",{criticalFrameTime:33,warningFrameTime:16,idealFrameTime:8});this.lastReportTime=Date.now()}startFrame(t){this.currentFrameId=t;const e={frameId:t,startTime:performance.now(),endTime:0,duration:0,featureCount:0,visibleCount:0,hiddenCount:0,collisionChecks:0,memoryUsage:0,strategyTimes:new Map};this.frameStats.set(t,e),this.cleanupOldFrames()}endFrame(t,e){const n=this.frameStats.get(t);if(!n)return;const r=performance.now();n.endTime=r,n.duration=r-n.startTime,e&&Object.assign(n,e),"memory"in performance&&(n.memoryUsage=performance.memory.usedJSHeapSize),this.updateSummaryStats(n),this.maybeOutputReport()}recordStrategyTime(t,e){const n=this.frameStats.get(this.currentFrameId);n&&n.strategyTimes.set(t,e)}recordCollisionChecks(t){const e=this.frameStats.get(this.currentFrameId);e&&(e.collisionChecks+=t)}getStats(){const t=this.getRecentFrames(this.sampleWindowSize),e=this.calculateFPS(t),n=this.calculateAverageFrameTime(t);return{summary:{...this.summaryStats},recent:{fps:e,frameTime:n,frameTimeStdDev:this.calculateFrameTimeStdDev(t),averageFeaturesPerFrame:this.calculateAverageFeatures(t),performanceLevel:this.getPerformanceLevel(n)},currentFrame:this.frameStats.get(this.currentFrameId)||null,strategies:this.getStrategyPerformance(t),warnings:this.getPerformanceWarnings(t)}}getDetailedReport(){const t=this.getRecentFrames(this.sampleWindowSize),e=this.getStats();return{...e,frameHistory:Array.from(t.values()),trends:this.calculateTrends(t),recommendations:this.getPerformanceRecommendations(e)}}reset(){this.frameStats.clear(),this.summaryStats={totalFrames:0,averageFrameTime:0,averageFPS:0,minFrameTime:1/0,maxFrameTime:0,totalFeaturesProcessed:0},this.currentFrameId=0,this.lastReportTime=Date.now()}cleanupOldFrames(){this.frameStats.size>this.sampleWindowSize*2&&Array.from(this.frameStats.keys()).sort((e,n)=>e-n).slice(0,this.frameStats.size-this.sampleWindowSize).forEach(e=>{this.frameStats.delete(e)})}updateSummaryStats(t){this.summaryStats.totalFrames++,this.summaryStats.totalFeaturesProcessed+=t.featureCount||0,this.summaryStats.averageFrameTime=(this.summaryStats.averageFrameTime*(this.summaryStats.totalFrames-1)+t.duration)/this.summaryStats.totalFrames,this.summaryStats.minFrameTime=Math.min(this.summaryStats.minFrameTime,t.duration),this.summaryStats.maxFrameTime=Math.max(this.summaryStats.maxFrameTime,t.duration),this.summaryStats.averageFPS=1e3/this.summaryStats.averageFrameTime}maybeOutputReport(){const t=Date.now();if(t-this.lastReportTime>=this.reportInterval){const e=this.getStats();e.warnings.length>0?console.warn("避让系统性能报告:",e):console.log("避让系统性能正常:",e),this.lastReportTime=t}}getRecentFrames(t){return Array.from(this.frameStats.values()).slice(-t).filter(n=>n.duration>0)}calculateFPS(t){if(t.length===0)return 0;const e=this.calculateAverageFrameTime(t);return e>0?1e3/e:0}calculateAverageFrameTime(t){return t.length===0?0:t.reduce((e,n)=>e+n.duration,0)/t.length}calculateFrameTimeStdDev(t){if(t.length===0)return 0;const e=this.calculateAverageFrameTime(t),n=t.map(r=>Math.pow(r.duration-e,2));return Math.sqrt(n.reduce((r,s)=>r+s,0)/t.length)}calculateAverageFeatures(t){return t.length===0?0:t.reduce((e,n)=>e+(n.featureCount||0),0)/t.length}getPerformanceLevel(t){return t>this.performanceThresholds.criticalFrameTime?"critical":t>this.performanceThresholds.warningFrameTime?"warning":t>this.performanceThresholds.idealFrameTime?"good":"excellent"}getStrategyPerformance(t){const e=new Map;return t.forEach(n=>{n.strategyTimes.forEach((r,s)=>{e.has(s)||e.set(s,[]),e.get(s).push(r)})}),Array.from(e.entries()).map(([n,r])=>({name:n,averageTime:r.reduce((s,a)=>s+a,0)/r.length,maxTime:Math.max(...r),minTime:Math.min(...r),callCount:r.length}))}getPerformanceWarnings(t){const e=[],n=t.slice(-30);if(n.length===0)return e;const r=this.calculateAverageFrameTime(n);r>this.performanceThresholds.criticalFrameTime?e.push({type:"critical",message:`帧率过低: ${Math.round(1e3/r)}fps`,suggestion:"考虑减少要素数量或简化避让策略"}):r>this.performanceThresholds.warningFrameTime&&e.push({type:"warning",message:`帧率较低: ${Math.round(1e3/r)}fps`,suggestion:"建议优化避让算法或增加更新间隔"});const s=n.map(a=>a.memoryUsage).filter(a=>a>0);if(s.length>0){const a=s.reduce((c,u)=>c+u,0)/s.length;a>100*1024*1024&&e.push({type:"warning",message:`内存使用较高: ${(a/1024/1024).toFixed(1)}MB`,suggestion:"检查内存泄漏,及时清理无用资源"})}return e}calculateTrends(t){if(t.length<2)return{frameTime:"stable",fps:"stable",features:"stable"};const e=t.slice(0,Math.floor(t.length/2)),n=t.slice(Math.floor(t.length/2)),r=this.calculateAverageFrameTime(e),a=(this.calculateAverageFrameTime(n)-r)/r*100;return{frameTime:Math.abs(a)<5?"stable":a>0?"worsening":"improving",fps:Math.abs(a)<5?"stable":a>0?"improving":"worsening",features:"stable"}}getPerformanceRecommendations(t){const e=[];return t.recent.performanceLevel==="critical"&&(e.push("建议启用要素抽样或聚合显示"),e.push("考虑增加避让更新间隔时间"),e.push("检查是否有不必要的避让策略")),t.recent.averageFeaturesPerFrame>5e3&&e.push("要素数量过多,建议启用LOD分级"),t.strategies.forEach(n=>{n.averageTime>10&&e.push(`策略 "${n.name}" 执行时间较长,考虑优化`)}),e}}class xp{constructor(){T(this,"name","priority");T(this,"enabled",!0);T(this,"weight",1);T(this,"description","基于优先级的避让策略,数值越小优先级越高")}async execute(t,e,n){const r=[],s=new Wl(e.viewport),a=[],c=new Map;return t.forEach(u=>{if(!u.collidable)return;const d=u.getScreenBoundingBox(e.camera,e.renderer);d&&(a.push(d),c.set(u._id,u),n?.get(u._id)?.visible)}),a.sort((u,d)=>u.priority-d.priority),a.forEach(u=>{const d=s.findCollisions(u);d.length===0?(s.addBoxes([u]),r.push({featureId:u.featureId,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp})):d.some(f=>f.priority<u.priority)?r.push({featureId:u.featureId,visible:!1,reason:rn.PRIORITY_LOST,collidedWith:d.map(f=>f.featureId),timestamp:e.timestamp}):(s.addBoxes([u]),r.push({featureId:u.featureId,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp}),d.forEach(f=>{r.push({featureId:f.featureId,visible:!1,reason:rn.PRIORITY_LOST,collidedWith:[u.featureId],timestamp:e.timestamp})}))}),r}}class bp{constructor(t,e={}){T(this,"_quadTreeManager");T(this,"_strategyOrchestrator");T(this,"_performanceMonitor");T(this,"_layers",new Set);T(this,"_config");T(this,"_isUpdating",!1);T(this,"_lastUpdateTime",0);T(this,"_frameCount",0);this.renderer=t,this._config={enabled:!0,padding:4,updateInterval:0,animationDuration:300,maxFeaturesPerFrame:2e3,viewportMargin:50,strategies:{priority:!0,grouping:!1,proximity:!1},...e},this._initializeComponents(),this._setupPerformanceMonitoring()}async update(t){if(!this._config.enabled||this._isUpdating)return;const e=Date.now();if(!(this._config.updateInterval>0&&e-this._lastUpdateTime<this._config.updateInterval)){this._isUpdating=!0,this._frameCount++;try{this._resetAllFeaturesVisibility();const n=this._createCollisionContext(t,e),r=this._collectCollidableFeatures();if(r.length===0)return;this._performanceMonitor.startFrame(this._frameCount);const s=await this._strategyOrchestrator.executeStrategies(r,n);await this._applyCollisionResults(s,r),this._performanceMonitor.endFrame(this._frameCount,{featureCount:r.length,visibleCount:Array.from(s.values()).filter(a=>a.visible).length,hiddenCount:Array.from(s.values()).filter(a=>!a.visible).length}),this._lastUpdateTime=e}catch(n){console.error("避让引擎更新失败:",n)}finally{this._isUpdating=!1}}}_resetAllFeaturesVisibility(){this._layers.forEach(t=>{t.getFeatures().filter(n=>n.collidable).forEach(n=>{n.setCollisionVisibility(!0,rn.NO_COLLISION)})})}registerLayer(t){return this._layers.add(t),this}unregisterLayer(t){return this._layers.delete(t),this}setConfig(t){return Object.assign(this._config,t),this}getPerformanceStats(){return this._performanceMonitor.getStats()}_initializeComponents(){const t={width:this.renderer.domElement.width,height:this.renderer.domElement.height};this._quadTreeManager=new Wl(t),this._strategyOrchestrator=new vp,this._performanceMonitor=new wp,this._strategyOrchestrator.registerStrategy(new xp,0),this._setupViewportResizeHandler()}_createCollisionContext(t,e){return{camera:t,renderer:this.renderer,viewport:{width:this.renderer.domElement.width,height:this.renderer.domElement.height},zoomLevel:t.position.z,timestamp:e,frameNumber:this._frameCount}}_collectCollidableFeatures(){const t=[];return this._layers.forEach(e=>{const n=e.getFeatures().filter(r=>r.collidable&&r instanceof Sn);if(t.length+n.length>this._config.maxFeaturesPerFrame){console.warn(`达到每帧最大要素处理限制: ${this._config.maxFeaturesPerFrame}`);return}t.push(...n)}),t}async _applyCollisionResults(t,e){const n=e.map(r=>{const s=t.get(r._id);return s&&r.setCollisionVisibility(s.visible,s.reason),Promise.resolve()});await Promise.all(n)}_setupViewportResizeHandler(){new ResizeObserver(e=>{e.forEach(n=>{const{width:r,height:s}=n.contentRect;this._quadTreeManager.updateViewport({width:r,height:s})})}).observe(this.renderer.domElement)}_setupPerformanceMonitoring(){setInterval(()=>{const t=this.getPerformanceStats();t.frameRate<30&&console.warn("避让系统性能警告:",t)},5e3)}}var Yr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Pi={exports:{}};/**
|
|
539
|
+
`,transparent:!0,side:m.DoubleSide,depthWrite:!0}),p=new m.Mesh(a,d);return p.renderOrder=5e3,p}function Kf(l,t,e){const{geometry:n,center:r,avgY:s}=Ml(e),a=new Jh(n,{textureWidth:512,textureHeight:512,waterNormals:new m.TextureLoader().load(l.normalMap,function(d){d.wrapS=d.wrapT=m.RepeatWrapping}),waterColor:l.color||"#19AAEE",sunColor:l.sunColor||"#05FFF8",distortionScale:1,alpha:l.opacity||.8}),c=a.onBeforeRender,u=a.onAfterRender;return a.onBeforeRender=(d,p,f,y,v,x)=>{t.tilemap.autoUpdate=!1,c.call(a,d,p,f,y,v,x)},a.onAfterRender=(d,p,f,y,v,x)=>{t.tilemap.autoUpdate=!0,u.call(a,d,p,f,y,v,x)},a.material.uniforms.size.value=.1,a.rotation.x=-Math.PI/2,a.position.set(r.x,s,r.z),t.viewer.addEventListener("update",()=>{a.material.uniforms.time.value+=1/60}),a}function Ml(l){let t=0;for(let a=1;a<l.length;a+=3)t+=l[a];t/=l.length/3;const e={x:0,z:0},n=[];for(let a=0;a<l.length;a+=3)e.x+=l[a],e.z+=l[a+2];e.x/=l.length/3,e.z/=l.length/3;for(let a=0;a<l.length;a+=3)n.push(new m.Vector2(l[a]-e.x,-(l[a+2]-e.z)));const r=new m.Shape(n);return{geometry:new m.ShapeGeometry(r),center:e,avgY:t}}async function Rf(l,t){const{geometry:e,center:n,avgY:r}=Ml(t),s=await Pt._loadTexture(l.normalMap),a=await Pt._loadTexture(l.normalMap);s.wrapS=s.wrapT=m.RepeatWrapping,a.wrapS=a.wrapT=m.RepeatWrapping,s.repeat.set(.015,.015),a.repeat.set(.005,.005);const c=new m.MeshStandardMaterial({color:new m.Color(l.color).multiplyScalar(3.5),roughness:.1,metalness:.8,transparent:!0,opacity:.9,fog:!1,normalMap:s,normalScale:new m.Vector2(1.5,1.5),envMapIntensity:2}),u=new m.Mesh(e,c);u.rotation.x=-Math.PI/2,u.position.set(n.x,r+.15,n.z),u.castShadow=!1,u.receiveShadow=!0;let d=0;return u.onBeforeRender=()=>{const p=performance.now(),f=d?(p-d)/1e3:.016;s.offset.x+=f*.08,s.offset.y+=f*.03,a.offset.x-=f*.12,a.offset.y+=f*.02,u.position.y=r+.5+Math.sin(p*.02)*.02,d=p},u}function Yf(l,t){l.color=new m.Color(l.hexcolor),l.boundstext&&(l.bounds=new m.Vector3(l.boundstext.x,l.boundstext.y,l.boundstext.z));const e=new kf(l);return e.castShadow=!0,e.scale.setScalar(50),e.position.copy(t),e}async function Uf(l,t){const n={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,fixedSize:50},...l};n.fontSize=Math.min(Math.max(n.fontSize,8),128);const r=document.createElement("canvas"),s=r.getContext("2d");if(!s)throw new Error("canvas context is null");const a=`${n.fontStyle} ${n.fontWeight} ${n.fontSize}px ${n.fontFamily}`;s.font=a;const c=n.showBackground?20:0,u=100,d=50,p=s.measureText(n.text),f=Math.max(u,p.width+c*2),y=Math.max(d,n.fontSize*1.5+c*2);r.width=Math.min(f,2048),r.height=Math.min(y,2048),s.clearRect(0,0,r.width,r.height),s.font=a,n.showBackground&&(n.bgStyle===1?(s.fillStyle=n.bgColor,s.globalAlpha=n.bgOpacity,s.beginPath(),Ll(s,c/2,c/2,r.width-c,r.height-c,n.roundRectRadius),s.fill(),s.globalAlpha=1,s.shadowColor=n.shadowColor,s.shadowBlur=n.shadowBlur,s.shadowOffsetX=n.shadowOffsetX,s.shadowOffsetY=n.shadowOffsetY):(s.fillStyle=n.bgColor,s.globalAlpha=n.bgOpacity,s.beginPath(),Sl(s,r.width/2,r.height/2,r.width*.8,r.height*.8,n.roundRectRadius,n.bubblePointerHeight,n.bubblePointerWidth),s.fill(),s.globalAlpha=1,s.strokeStyle=n.bubbleBorderColor,s.lineWidth=n.bubbleBorderWidth,s.stroke())),s.textAlign="center",s.textBaseline="middle",n.strokeWidth>0&&(s.strokeStyle=n.strokeColor,s.lineWidth=n.strokeWidth,s.lineJoin="round",s.strokeText(n.text,r.width/2,r.height/2)),s.fillStyle=n.textColor,s.fillText(n.text,r.width/2,r.height/2),s.shadowColor="transparent";const v=new m.CanvasTexture(r);v.magFilter=m.NearestFilter,v.minFilter=m.LinearMipmapLinearFilter,v.anisotropy=16;const x=new m.SpriteMaterial({map:v,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),L=new m.Sprite(x),_=n.fixedSize;return L.scale.set(r.width*_/100,r.height*_/100,1),t&&L.position.copy(t),L.renderOrder=9999,L}async function Bf(l,t,e){const r={...{fontSize:48,fontFamily:"'Microsoft YaHei', sans-serif",fontWeight:"bold",fontStyle:"normal",textColor:"#ffffff",strokeColor:"#000000",strokeWidth:2,showBackground:!0,bgStyle:1,bgColor:"#3498db",bgOpacity:.8,shadowColor:"rgba(0, 0, 0, 0.5)",shadowBlur:5,shadowOffsetX:3,shadowOffsetY:3,roundRectRadius:20,bubblePointerHeight:10,bubblePointerWidth:15,bubbleBorderColor:"#ffffff",bubbleBorderWidth:3,screenSpaceSize:20,maxVisibleDistance:1/0},...l};r.fontSize=Math.min(Math.max(r.fontSize,8),128);const s=document.createElement("canvas"),a=s.getContext("2d");if(!a)throw new Error("Failed to get canvas context");const c=`${r.fontStyle} ${r.fontWeight} ${r.fontSize}px ${r.fontFamily}`;a.font=c;const u=r.showBackground?20:0,d=100,p=50,f=a.measureText(r.text),y=Math.max(d,f.width+u*2),v=Math.max(p,r.fontSize*1.5+u*2);s.width=Math.min(y,2048),s.height=Math.min(v,2048),a.clearRect(0,0,s.width,s.height),a.font=c,r.showBackground&&(r.bgStyle===1?(a.fillStyle=r.bgColor,a.globalAlpha=r.bgOpacity,a.beginPath(),Ll(a,u/2,u/2,s.width-u,s.height-u,r.roundRectRadius),a.fill(),a.globalAlpha=1,a.shadowColor=r.shadowColor,a.shadowBlur=r.shadowBlur,a.shadowOffsetX=r.shadowOffsetX,a.shadowOffsetY=r.shadowOffsetY):(a.fillStyle=r.bgColor,a.globalAlpha=r.bgOpacity,a.beginPath(),Sl(a,s.width/2,s.height/2,s.width*.8,s.height*.8,r.roundRectRadius,r.bubblePointerHeight,r.bubblePointerWidth),a.fill(),a.globalAlpha=1,a.strokeStyle=r.bubbleBorderColor,a.lineWidth=r.bubbleBorderWidth,a.stroke())),a.textAlign="center",a.textBaseline="middle",r.strokeWidth>0&&(a.strokeStyle=r.strokeColor,a.lineWidth=r.strokeWidth,a.lineJoin="round",a.strokeText(r.text,s.width/2,s.height/2)),a.fillStyle=r.textColor,a.fillText(r.text,s.width/2,s.height/2),a.shadowColor="transparent";const x=new m.CanvasTexture(s),L=new m.SpriteMaterial({map:x,transparent:!0,depthTest:!1,depthWrite:!1,fog:!1}),_=new m.Sprite(L);_.position.copy(t),_.renderOrder=9999,_.userData.isLabel=!0;const S=()=>{if(!_.visible)return;const G=e.viewer.camera.position.distanceTo(_.position);if(G>r.maxVisibleDistance){_.visible=!1;return}_.visible=!0;const A=new m.Vector2;e.viewer.renderer.getSize(A);const K=A.height,D=r.screenSpaceSize/s.height*(G/Math.tan(m.MathUtils.degToRad(e.viewer.camera.fov)/2))*(2/K);_.scale.set(D*s.width,D*s.height,1),_.lookAt(e.viewer.camera.position)};S();const Z=()=>S();return _.addEventListener("dispose",()=>{e.viewer.renderer.domElement.removeEventListener("resize",S)}),e.viewer.renderer.domElement.addEventListener("resize",S),e.viewer.camera.addEventListener("change",S),_.onBeforeRender=Z,_}function Ll(l,t,e,n,r,s){l.beginPath(),l.moveTo(t+s,e),l.lineTo(t+n-s,e),l.quadraticCurveTo(t+n,e,t+n,e+s),l.lineTo(t+n,e+r-s),l.quadraticCurveTo(t+n,e+r,t+n-s,e+r),l.lineTo(t+s,e+r),l.quadraticCurveTo(t,e+r,t,e+r-s),l.lineTo(t,e+s),l.quadraticCurveTo(t,e,t+s,e),l.closePath()}function Sl(l,t,e,n,r,s,a,c){if(n<=0)throw new Error("Width must be positive");if(r<=0)throw new Error("Height must be positive");if(s<0)throw new Error("Radius cannot be negative");const u=n,d=r,p=Math.min(s,n/2,r/2),f=a??10,y=c??15;l.beginPath(),l.moveTo(t-u/2+p,e-d/2),l.lineTo(t+u/2-p,e-d/2),l.quadraticCurveTo(t+u/2,e-d/2,t+u/2,e-d/2+p),l.lineTo(t+u/2,e+d/2-p),l.quadraticCurveTo(t+u/2,e+d/2,t+u/2-p,e+d/2),l.lineTo(t+y/2,e+d/2),l.lineTo(t,e+d/2+f),l.lineTo(t-y/2,e+d/2),l.lineTo(t-u/2+p,e+d/2),l.quadraticCurveTo(t-u/2,e+d/2,t-u/2,e+d/2-p),l.lineTo(t-u/2,e-d/2+p),l.quadraticCurveTo(t-u/2,e-d/2,t-u/2+p,e-d/2),l.closePath()}async function Nf(l,t,e){const{text:n,iconUrl:r,fontSize:s=30,iconSize:a=60,fontFamily:c="Arial",padding:u={},bgColor:d="rgba(0,0,0,0.0)",textColor:p="rgb(255,255,255)",strokeColor:f="rgb(0,0,0)",strokeWidth:y=s/9,iconScale:v=.8,canvasScale:x=1,renderbg:L=!0,textOffset:_={x:0,y:0}}=l,S={top:0,right:1,bottom:0,left:0,...u};let Z=null;r&&(Z=await Jf(r));const{canvas:G,width:A,height:K,center:D}=await jf({text:n,iconImage:Z,fontSize:s,iconSize:a,fontFamily:c,padding:S,bgColor:d,textColor:p,strokeColor:f,strokeWidth:y,iconScale:v,canvasScale:x,renderbg:L,textOffset:_},t),O=new m.Texture(G);O.needsUpdate=!0;const V=new m.SpriteMaterial({map:O,transparent:!0,depthTest:!0,depthWrite:!0,blending:m.NormalBlending,sizeAttenuation:!1,alphaTest:.01}),R=new m.Sprite(V),W=.001;return R.scale.set(A*W,K*W,1),R.center.set(D[0],D[1]),e&&R.position.copy(e),R.renderOrder=999,R}async function jf(l,t){return new Promise(e=>{const{text:n,iconImage:r,fontSize:s,iconSize:a,fontFamily:c,padding:u,bgColor:d,textColor:p,strokeColor:f,strokeWidth:y,iconScale:v,canvasScale:x,renderbg:L,textOffset:_={x:0,y:0}}=l,Z=document.createElement("canvas").getContext("2d");if(!Z)throw new Error("Could not get temp canvas context");Z.font=`500 ${s}px ${c}`;const G=Z.measureText(n),A=G.width,K=G.actualBoundingBoxAscent||s*.8,D=G.actualBoundingBoxDescent||s*.2,O=r!==null;let V=0,R=0,W=0,k=0;if(O){V=0,R=0,W=a,k=a;const he=a/2+_.x,ve=a/2+_.y,ke=he,Ye=he+A,je=ve-K,Je=ve+D;V=Math.min(V,ke),W=Math.max(W,Ye),R=Math.min(R,je),k=Math.max(k,Je)}else{const he=_.x,ve=_.x+A,ke=_.y-K,Ye=_.y+D;V=he,W=ve,R=ke,k=Ye}const N=W-V,H=k-R,j=Math.ceil(N+u.left+u.right)*x,q=Math.ceil(H+u.top+u.bottom)*x,J=u.left-V,oe=u.top-R,ie=t._getCanvas(j,q,n);ie.width=j,ie.height=q;const te=ie.getContext("2d");if(!te)throw new Error("Could not get canvas context");te.clearRect(0,0,j,q),te.globalCompositeOperation="source-over",te.save(),te.scale(x,x);const me=j/x,be=q/x;if(L&&(te.fillStyle=d,te.fillRect(0,0,me,be)),r){const he=J,ve=oe,ke=a*v,Ye=(a-ke)/2,je=(a-ke)/2;te.imageSmoothingEnabled=!1,te.drawImage(r,he+Ye,ve+je,ke,ke),te.font=`500 ${s}px ${c}`,te.textBaseline="alphabetic",te.textAlign="left";const Je=J+a/2+_.x,Qe=oe+a/2+_.y;y>0&&(te.strokeStyle=f,te.lineWidth=y,te.strokeText(n,Je,Qe)),te.fillStyle=p,te.fillText(n,Je,Qe)}else{te.font=`500 ${s}px ${c}`,te.textBaseline="alphabetic",te.textAlign="left";const he=J+_.x,ve=oe+_.y;y>0&&(te.strokeStyle=f,te.lineWidth=y,te.strokeText(n,he,ve)),te.fillStyle=p,te.fillText(n,he,ve)}te.restore(),e({canvas:ie,width:me,height:be,center:[(a*.5+u.left)/me,(1-v)*.5]})})}function Jf(l){return new Promise((t,e)=>{const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>t(n),n.onerror=r=>e(new Error(`Failed to load image: ${l} ${r}`)),n.src=l})}async function Qf(l,t,e){const r=new m.CylinderGeometry(.2,.2,24,12),s=new m.MeshBasicMaterial({color:l.color}),a=await Pt._loadTexture(l.icon),c=new m.PointsMaterial({size:80*window.innerHeight/window.innerHeight,fog:!1,opacity:1,transparent:!0,toneMapped:!1,blending:m.AdditiveBlending,map:a,sizeAttenuation:!0,depthTest:!0,depthWrite:!1}),u=new m.InstancedMesh(r,s,t.length);u.position.add(e.prjcenter),u.castShadow=!0,u.renderOrder=1;const d=new m.Object3D,p=[];for(let x=0;x<t.length;x++){const L=t[x],_=new m.Vector3(L.coordinates[0],L.coordinates[1],L.coordinates[2]||0),Z=e.geo2world(_).sub(e.prjcenter);d.position.copy(Z),d.updateMatrix(),u.setMatrixAt(x,d.matrix),p.push(Z.x,0,Z.z)}const f=new Float32Array(p),y=new m.BufferGeometry;y.setAttribute("position",new m.BufferAttribute(f,3));const v=new m.Points(y,c);return v.position.add(e.prjcenter),v.position.y=1.5*10,v.renderOrder=99999999,v.visible=!0,console.log(e,"map"),{points:v,InstancedCol:u}}const Yt=class Yt{constructor(t){this.config=t}async applyTo(t){if(!t)return!1;try{switch(t.visible=this.config.visible!==!1,this.config.zIndex&&(t.renderOrder=this.config.zIndex),this.config.type){case"basic-point":case"icon-point":case"icon-label-point":return this._applyPointStyle(t);case"basic-line":return this._applyLineStyle(t);case"gltf":case"fbx":return this._applyModelStyle(t);case"basic-polygon":return this._applyPolygonStyle(t);case"extrude-polygon":return this._applyExtrudeStyle(t);case"water":case"base-water":return this._applyWaterStyle(t);case"cloud":return this._applyCloudStyle(t);case"canvas-label":case"canvas-label-fixed":return this._applyTextSpriteStyle(t);case"light":return this._applyLightStyle(t);case"custom":return this._applyCustomStyle(t);default:throw new Error("Unknown style type")}}catch(e){return console.error("Style apply failed:",e),t.visible=!1,!1}}async _applyPointStyle(t){const e=this.config;return e.type==="icon-point"?await this._applyIconPoint(t,e):e.type==="basic-point"?this._applyBasicPoint(t,e):e.type==="icon-label-point"&&this._applyIconLabelPoint(t,e),!0}async _applyIconPoint(t,e){let n;if(t instanceof m.Sprite)n=t;else if(n=await _l(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let u=t.parent;u._threeGeometry=n,u._updateGeometry()}const r=e.size,[s,a]=Array.isArray(r)?r:[r,r];if(s<=0||a<=0){console.error("Invalid sprite size:",e.size),n.visible=!1;return}const c=n.material;try{if(c.map=await Yt._loadTexture(e.url),!c.map)throw new Error("Texture failed to load");c.needsUpdate=!0,n.scale.set(s,a,1),e.rotation!==void 0&&(n.rotation.z=e.rotation)}catch(u){console.error("Failed to load texture:",e.url,u),n.visible=!1}}_applyBasicPoint(t,e){let n;if(t instanceof m.Points)n=t;else if(n=bl(e,t.position),n.position.copy(t.position),n.rotation.copy(t.rotation),n.scale.copy(t.scale),n.renderOrder=999,t.parent){let s=t.parent;s._threeGeometry=n,s._updateGeometry()}const r=n.material;r.size=e.size,e.color&&r.color.set(e.color),e.glow&&(r.sizeAttenuation=!1)}_applyIconLabelPoint(t,e){return!0}_applyLineStyle(t){const e=this.config;if(t.parent){let n=t.parent;n._threeGeometry=Gi(e,n._vertexPoints),n._updateGeometry()}return!0}_applyPolygonStyle(t){return!0}_applyExtrudeStyle(t){return!0}_applyWaterStyle(t){return!0}_applyCloudStyle(t){return!0}_applyTextSpriteStyle(t){return!0}_applyLightStyle(t){return!0}async _applyModelStyle(t){return!0}async _applyCustomStyle(t){const n=await this.config.build();return t instanceof m.Group&&(t.clear(),t.add(n)),!0}static async _loadTexture(t){if(Yt._textureCache.has(t))return Yt._textureCache.get(t);const e=await new Promise((n,r)=>{Yt._textureLoader.load(t,n,void 0,r)});return e.premultiplyAlpha=!0,Yt._textureCache.set(t,e),e}static create(t){return t instanceof Yt?t:new Yt(t)}};T(Yt,"_textureCache",new Map),T(Yt,"_textureLoader",new m.TextureLoader);let Pt=Yt;const et=[];for(let l=0;l<256;++l)et.push((l+256).toString(16).slice(1));function Hf(l,t=0){return(et[l[t+0]]+et[l[t+1]]+et[l[t+2]]+et[l[t+3]]+"-"+et[l[t+4]]+et[l[t+5]]+"-"+et[l[t+6]]+et[l[t+7]]+"-"+et[l[t+8]]+et[l[t+9]]+"-"+et[l[t+10]]+et[l[t+11]]+et[l[t+12]]+et[l[t+13]]+et[l[t+14]]+et[l[t+15]]).toLowerCase()}let to;const Ef=new Uint8Array(16);function qf(){if(!to){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");to=crypto.getRandomValues.bind(crypto)}return to(Ef)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function $f(l,t,e){if(Zl.randomUUID&&!l)return Zl.randomUUID();l=l||{};const n=l.random??l.rng?.()??qf();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Hf(n)}var Tl=(l=>(l.POINT="point",l.LINE_VERTEX="line_vertex",l.POLYGON_CENTER="polygon_center",l.LABEL="label",l.ICON="icon",l.CLUSTER="cluster",l))(Tl||{}),rn=(l=>(l.NO_COLLISION="no_collision",l.PRIORITY_LOST="priority_lost",l.OUT_OF_VIEWPORT="out_of_viewport",l.ZOOM_FILTERED="zoom_filtered",l.MANUAL_HIDDEN="manual_hidden",l.GROUP_COLLISION="group_collision",l))(rn||{});class Sn extends Es(Mi(Li(m.Object3D))){constructor(e){super();T(this,"_position");T(this,"_threeGeometry");T(this,"_geometry");T(this,"_layer");T(this,"_style");T(this,"_id");T(this,"_styleQueue",[]);T(this,"_isApplyingStyle",!1);T(this,"_isGeometryInitializing",!1);T(this,"_collisionState",{visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:Date.now()});T(this,"_collisionConfig",{enabled:!0,priority:50,padding:4,minZoom:0,maxZoom:24});T(this,"_animationRef",null);Ns(e.geometry,"geometry","geometry must be specified"),this._geometry=e.geometry,this._position=new m.Vector3(0,0,0),this._threeGeometry=new m.Object3D,e.userData&&(this.userData=Object.assign({},JSON.parse(JSON.stringify(e.userData)))),e.style&&this.setStyle(e.style),e.id?this._id=e.id:this._id=$f()}async initializeGeometry(){if(!(this._isGeometryInitializing||this._threeGeometry)){this._isGeometryInitializing=!0;try{await this._toThreeJSGeometry(),this._processStyleQueue()}finally{this._isGeometryInitializing=!1}}}setStyle(e){const n=e instanceof Pt?e:new Pt(e);this._style=n;const r=JSON.parse(JSON.stringify(n.config));return this._styleQueue.push(r),this._tryProcessQueue(),this}getStyle(){return this._style}async _applyStyleWithRetry(e,n=3,r=100){let s=null;for(let a=1;a<=n;a++)try{this._threeGeometry.parent||(this.add(this._threeGeometry),await new Promise(c=>requestAnimationFrame(c))),await e.applyTo(this._threeGeometry);return}catch(c){if(s=c,a<n){const u=r*Math.pow(2,a-1);await new Promise(d=>setTimeout(d,u))}}throw s||new Error("样式应用失败,重试次数耗尽")}async _processStyleQueue(){if(!this._threeGeometry||this._isApplyingStyle||this._styleQueue.length===0)return;this._isApplyingStyle=!0;const e=this._styleQueue[0];try{const n=new Pt(JSON.parse(JSON.stringify(e)));await this._applyStyleWithRetry(n),this._styleQueue.shift(),this._styleQueue.length>0&&await this._processStyleQueue()}catch(n){throw n}finally{this._isApplyingStyle=!1,this._styleQueue.length>0&&this._tryProcessQueue()}}_tryProcessQueue(){this._threeGeometry&&!this._isApplyingStyle&&this._styleQueue.length>0?this._processStyleQueue().catch(n=>{this._isApplyingStyle=!1,this._tryProcessQueue(),console.warn(n)}):!this._threeGeometry&&!this._isGeometryInitializing&&this.initializeGeometry()}addTo(e){return e.addFeature(this),this}getLayer(){return this._layer||null}getMap(){return this._layer?.getMap()||null}_bindLayer(e){if(this._layer&&this._layer!==e)throw new Error("Feature cannot be added to multiple layers");this._layer=e}_updateGeometry(){this._disposeGeometry(),this._threeGeometry&&(this._threeGeometry.position.copy(this._position),this._threeGeometry.renderOrder=999,this.add(this._threeGeometry),this.updateMatrixWorld(!0),this._tryProcessQueue())}_remove(){return this.getLayer()?(this._unbind(),this):this}_unbind(){const e=this.getLayer();e&&(e.onRemoveFeature&&e.onRemoveFeature(this),delete this._layer)}_disposeGeometry(){this._threeGeometry&&(this.clear(),"traverse"in this&&this._threeGeometry.traverse(e=>{e instanceof m.Mesh?(e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(n=>n.dispose()):e.material?.dispose()):"isLine"in e&&e.isLine&&(e.geometry?.dispose(),e.material?.dispose())}))}get collidable(){return this._collisionConfig.enabled}get collisionType(){return Tl.POINT}getCollisionPriority(){return this.userData.collisionPriority??this._style?.config.collisionPriority??this._collisionConfig.priority}getScreenBoundingBox(e,n){if(!this.collidable)return null;try{const r=new m.Vector3;this._threeGeometry.getWorldPosition(r);const s=r.clone().project(e);if(!(s.x>=-1.1&&s.x<=1.1&&s.y>=-1.1&&s.y<=1.1&&s.z>=-1&&s.z<=1))return null;const{width:c,height:u}=n.domElement,d=(s.x*.5+.5)*c,p=(-s.y*.5+.5)*u,f=this._calculateCollisionBoundingBox(e,n);return f?{id:this._id,x:d+f.offsetX,y:p+f.offsetY,width:20+this._collisionConfig.padding*2,height:20+this._collisionConfig.padding*2,priority:this.getCollisionPriority(),featureId:this._id,layerId:this._layer?.getId()||"unknown",type:this.collisionType,data:this.getCollisionData()}:null}catch(r){return console.warn(`Feature ${this._id} 包围盒计算失败:`,r),null}}setCollisionVisibility(e,n=rn.MANUAL_HIDDEN){this._collisionState.visible!==e&&(this._animationRef!==null&&(cancelAnimationFrame(this._animationRef),this._animationRef=null),this.visible=e,this._applyFinalAlpha(e?1:0),this._collisionState={visible:e,reason:n,collidedWith:e?[]:this._collisionState.collidedWith,timestamp:Date.now()})}getCollisionVisibility(){return this._collisionState.visible}setCollisionConfig(e){return Object.assign(this._collisionConfig,e),this}enableCollision(){return this._collisionConfig.enabled=!0,this}disableCollision(){return this._collisionConfig.enabled=!1,this.setCollisionVisibility(!0,rn.MANUAL_HIDDEN),this}_applyVisibilityAlpha(e){this.traverse(n=>{n instanceof m.Mesh&&(Array.isArray(n.material)?n.material.forEach(r=>{r.opacity!==void 0&&(r.opacity=e)}):n.material.opacity!==void 0&&(n.material.opacity=e))})}_applyFinalAlpha(e){this._applyVisibilityAlpha(e),this.traverse(n=>{n instanceof m.Mesh&&(n.material.needsUpdate=!0)})}getCollisionData(){return{featureType:this.constructor.name,userData:this.userData,styleConfig:this._style?.config}}_calculateCollisionBoundingBox(e,n){if(!this.visible||!this._threeGeometry||!e||!n)return null;try{const r=new m.Box3().setFromObject(this._threeGeometry);if(r.isEmpty())return this._getFallbackBoundingBox();const s=[new m.Vector3(r.min.x,r.min.y,r.min.z),new m.Vector3(r.max.x,r.min.y,r.min.z),new m.Vector3(r.min.x,r.max.y,r.min.z),new m.Vector3(r.max.x,r.max.y,r.min.z),new m.Vector3(r.min.x,r.min.y,r.max.z),new m.Vector3(r.max.x,r.min.y,r.max.z),new m.Vector3(r.min.x,r.max.y,r.max.z),new m.Vector3(r.max.x,r.max.y,r.max.z)],{width:a,height:c}=n.domElement,u=[];s.forEach(D=>{const O=D.clone().project(e),V=(O.x*.5+.5)*a,R=(-O.y*.5+.5)*c;u.push(new m.Vector2(V,R))});let d=1/0,p=-1/0,f=1/0,y=-1/0;u.forEach(D=>{d=Math.min(d,D.x),p=Math.max(p,D.x),f=Math.min(f,D.y),y=Math.max(y,D.y)});const v=p-d,x=y-f,L=4,_=Math.max(v,L),S=Math.max(x,L),Z=new m.Vector3;r.getCenter(Z);const G=Z.clone().project(e),A=(G.x*.5+.5)*a,K=(-G.y*.5+.5)*c;return{width:_,height:S,offsetX:d-A,offsetY:f-K}}catch(r){return console.warn("包围盒计算失败:",r),this._getFallbackBoundingBox()}}_getFallbackBoundingBox(){return{width:20,height:20,offsetX:-10,offsetY:-10}}_tileCoordToLocalWorld(e,n,r,s){const{tileZ:a,tileX:c,tileY:u,extent:d,tileSize:p}=r,f=(e/d-.5)*p,y=(.5-n/d)*p;return s.tileIDToWorldCenter(a,c,u).clone().add(new m.Vector3(f,y,0)).sub(s.prjcenter)}}class Bn extends Si{constructor(e,n){super(e,n);T(this,"_feaList");T(this,"_collision",!1);this._feaList=[],n?.collision&&(this._collision=!0)}addFeature(e){const n=Array.isArray(e)?e:[e];for(const r of n)if(!(!r||!(r instanceof Sn))&&!r.getLayer()){if(!this.validateFeature(r)){console.error(`Feature ${r.id} does not match the layer's type requirements`);continue}r._bindLayer(this),this._feaList.push(r),r.getMap()&&r._toThreeJSGeometry(),this._clouds&&(this.map.viewer.scene.add(this._clouds),console.log("我是云朵被添加cloud",this.map.viewer.scene)),this.add(r)}return this}getFeatures(e,n){if(!e)return this._feaList.slice(0);const r=[];let s,a;for(let c=0,u=this._feaList.length;c<u;c++)s=this._feaList[c],n?a=e.call(n,s):a=e(s),a&&r.push(s);return r}getCount(){return this._feaList.length}isEmpty(){return!this._feaList.length}removeFeature(e){if(!Array.isArray(e))return this.removeFeature([e]);for(let n=e.length-1;n>=0;n--)e[n]instanceof Sn||(e[n]=this.removeFeature(e[n])),!(!e[n]||this!==e[n].getLayer())&&e[n]._remove();return this}clear(){const e=this._feaList.slice();for(const n of e)n._remove();return this}onRemoveFeature(e){if(!e)return;const n=e.getLayer();if(!n||n!==this)return;const r=this._findInList(e);r>=0&&this._feaList.splice(r,1),e.parent&&e.parent===this?this.remove(e):console.warn("Feature parent mismatch:",e.parent),this._disposeFeatureResources(e)}_findInList(e){const n=this._feaList.length;if(n===0)return-1;let r=0,s=n-1,a;for(;r<=s;){if(a=Math.floor((r+s)/2),this._feaList[a]===e)return a;r=a+1}return-1}_disposeFeatureResources(e){try{e.geometry&&e.geometry.dispose&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(n=>n.dispose?.()):e.material.dispose&&e.material.dispose()),e instanceof m.Object3D&&e.traverse(n=>{n!==e&&this._disposeFeatureResources(n)})}catch(n){console.error("Error disposing feature resources:",n)}}_mergedGeometry(){this.traverse(e=>{e.isMesh&&e.geometry&&e.material&&console.log("几何体合并中",e)})}setCollisionEngine(e){return this._collisionEngine=e,this}}class ep extends m.Group{constructor(){super(...arguments);T(this,"_layers",new Set);T(this,"_layerids",new Set)}add(...e){return e.forEach(n=>{if(!(n instanceof Si))throw new Error("LayerContainer只能包含Layer实例!");const r=n.getId();if(this._layerids.has(r))throw new Error(`ID为'${r}'的图层已存在于容器中!`);this._layers.add(n),this._layerids.add(r),super.add(n)}),this}remove(...e){return e.forEach(n=>{this._layers.delete(n),this._layerids.delete(n.getId()),super.remove(n)}),this}getLayers(){return Array.from(this._layers)}getLayerById(e){for(const n of this._layers)if(n.getId()===e)return n}clearLayers(){return this._layers.clear(),this._layerids.clear(),super.clear(),this}}class tp{constructor(){T(this,"canvasDict",{})}getCanvas(t=40,e=30,n=1,r){const s=Math.ceil(t*n),a=Math.ceil(e*n),c=r?`${s}_${a}_${r}`:`${s}_${a}`;if(!this.canvasDict[c]){const p=document.createElement("canvas");p.width=s,p.height=a,this.canvasDict[c]=p}const u=this.canvasDict[c],d=u.getContext("2d");return d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,u.width,u.height),d.scale(n,n),u}}function np(l){const t=+this._x.call(null,l),e=+this._y.call(null,l);return Gl(this.cover(t,e),t,e,l)}function Gl(l,t,e,n){if(isNaN(t)||isNaN(e))return l;var r,s=l._root,a={data:n},c=l._x0,u=l._y0,d=l._x1,p=l._y1,f,y,v,x,L,_,S,Z;if(!s)return l._root=a,l;for(;s.length;)if((L=t>=(f=(c+d)/2))?c=f:d=f,(_=e>=(y=(u+p)/2))?u=y:p=y,r=s,!(s=s[S=_<<1|L]))return r[S]=a,l;if(v=+l._x.call(null,s.data),x=+l._y.call(null,s.data),t===v&&e===x)return a.next=s,r?r[S]=a:l._root=a,l;do r=r?r[S]=new Array(4):l._root=new Array(4),(L=t>=(f=(c+d)/2))?c=f:d=f,(_=e>=(y=(u+p)/2))?u=y:p=y;while((S=_<<1|L)===(Z=(x>=y)<<1|v>=f));return r[Z]=s,r[S]=a,l}function rp(l){var t,e,n=l.length,r,s,a=new Array(n),c=new Array(n),u=1/0,d=1/0,p=-1/0,f=-1/0;for(e=0;e<n;++e)isNaN(r=+this._x.call(null,t=l[e]))||isNaN(s=+this._y.call(null,t))||(a[e]=r,c[e]=s,r<u&&(u=r),r>p&&(p=r),s<d&&(d=s),s>f&&(f=s));if(u>p||d>f)return this;for(this.cover(u,d).cover(p,f),e=0;e<n;++e)Gl(this,a[e],c[e],l[e]);return this}function ip(l,t){if(isNaN(l=+l)||isNaN(t=+t))return this;var e=this._x0,n=this._y0,r=this._x1,s=this._y1;if(isNaN(e))r=(e=Math.floor(l))+1,s=(n=Math.floor(t))+1;else{for(var a=r-e||1,c=this._root,u,d;e>l||l>=r||n>t||t>=s;)switch(d=(t<n)<<1|l<e,u=new Array(4),u[d]=c,c=u,a*=2,d){case 0:r=e+a,s=n+a;break;case 1:e=r-a,s=n+a;break;case 2:r=e+a,n=s-a;break;case 3:e=r-a,n=s-a;break}this._root&&this._root.length&&(this._root=c)}return this._x0=e,this._y0=n,this._x1=r,this._y1=s,this}function sp(){var l=[];return this.visit(function(t){if(!t.length)do l.push(t.data);while(t=t.next)}),l}function op(l){return arguments.length?this.cover(+l[0][0],+l[0][1]).cover(+l[1][0],+l[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function at(l,t,e,n,r){this.node=l,this.x0=t,this.y0=e,this.x1=n,this.y1=r}function ap(l,t,e){var n,r=this._x0,s=this._y0,a,c,u,d,p=this._x1,f=this._y1,y=[],v=this._root,x,L;for(v&&y.push(new at(v,r,s,p,f)),e==null?e=1/0:(r=l-e,s=t-e,p=l+e,f=t+e,e*=e);x=y.pop();)if(!(!(v=x.node)||(a=x.x0)>p||(c=x.y0)>f||(u=x.x1)<r||(d=x.y1)<s))if(v.length){var _=(a+u)/2,S=(c+d)/2;y.push(new at(v[3],_,S,u,d),new at(v[2],a,S,_,d),new at(v[1],_,c,u,S),new at(v[0],a,c,_,S)),(L=(t>=S)<<1|l>=_)&&(x=y[y.length-1],y[y.length-1]=y[y.length-1-L],y[y.length-1-L]=x)}else{var Z=l-+this._x.call(null,v.data),G=t-+this._y.call(null,v.data),A=Z*Z+G*G;if(A<e){var K=Math.sqrt(e=A);r=l-K,s=t-K,p=l+K,f=t+K,n=v.data}}return n}function lp(l){if(isNaN(p=+this._x.call(null,l))||isNaN(f=+this._y.call(null,l)))return this;var t,e=this._root,n,r,s,a=this._x0,c=this._y0,u=this._x1,d=this._y1,p,f,y,v,x,L,_,S;if(!e)return this;if(e.length)for(;;){if((x=p>=(y=(a+u)/2))?a=y:u=y,(L=f>=(v=(c+d)/2))?c=v:d=v,t=e,!(e=e[_=L<<1|x]))return this;if(!e.length)break;(t[_+1&3]||t[_+2&3]||t[_+3&3])&&(n=t,S=_)}for(;e.data!==l;)if(r=e,!(e=e.next))return this;return(s=e.next)&&delete e.next,r?(s?r.next=s:delete r.next,this):t?(s?t[_]=s:delete t[_],(e=t[0]||t[1]||t[2]||t[3])&&e===(t[3]||t[2]||t[1]||t[0])&&!e.length&&(n?n[S]=e:this._root=e),this):(this._root=s,this)}function cp(l){for(var t=0,e=l.length;t<e;++t)this.remove(l[t]);return this}function up(){return this._root}function hp(){var l=0;return this.visit(function(t){if(!t.length)do++l;while(t=t.next)}),l}function dp(l){var t=[],e,n=this._root,r,s,a,c,u;for(n&&t.push(new at(n,this._x0,this._y0,this._x1,this._y1));e=t.pop();)if(!l(n=e.node,s=e.x0,a=e.y0,c=e.x1,u=e.y1)&&n.length){var d=(s+c)/2,p=(a+u)/2;(r=n[3])&&t.push(new at(r,d,p,c,u)),(r=n[2])&&t.push(new at(r,s,p,d,u)),(r=n[1])&&t.push(new at(r,d,a,c,p)),(r=n[0])&&t.push(new at(r,s,a,d,p))}return this}function fp(l){var t=[],e=[],n;for(this._root&&t.push(new at(this._root,this._x0,this._y0,this._x1,this._y1));n=t.pop();){var r=n.node;if(r.length){var s,a=n.x0,c=n.y0,u=n.x1,d=n.y1,p=(a+u)/2,f=(c+d)/2;(s=r[0])&&t.push(new at(s,a,c,p,f)),(s=r[1])&&t.push(new at(s,p,c,u,f)),(s=r[2])&&t.push(new at(s,a,f,p,d)),(s=r[3])&&t.push(new at(s,p,f,u,d))}e.push(n)}for(;n=e.pop();)l(n.node,n.x0,n.y0,n.x1,n.y1);return this}function pp(l){return l[0]}function mp(l){return arguments.length?(this._x=l,this):this._x}function gp(l){return l[1]}function yp(l){return arguments.length?(this._y=l,this):this._y}function Pl(l,t,e){var n=new no(t??pp,e??gp,NaN,NaN,NaN,NaN);return l==null?n:n.addAll(l)}function no(l,t,e,n,r,s){this._x=l,this._y=t,this._x0=e,this._y0=n,this._x1=r,this._y1=s,this._root=void 0}function Il(l){for(var t={data:l.data},e=t;l=l.next;)e=e.next={data:l.data};return t}var lt=Pl.prototype=no.prototype;lt.copy=function(){var l=new no(this._x,this._y,this._x0,this._y0,this._x1,this._y1),t=this._root,e,n;if(!t)return l;if(!t.length)return l._root=Il(t),l;for(e=[{source:t,target:l._root=new Array(4)}];t=e.pop();)for(var r=0;r<4;++r)(n=t.source[r])&&(n.length?e.push({source:n,target:t.target[r]=new Array(4)}):t.target[r]=Il(n));return l},lt.add=np,lt.addAll=rp,lt.cover=ip,lt.data=sp,lt.extent=op,lt.find=ap,lt.remove=lp,lt.removeAll=cp,lt.root=up,lt.size=hp,lt.visit=dp,lt.visitAfter=fp,lt.x=mp,lt.y=yp;class Wl{constructor(t){T(this,"_quadtree");T(this,"_viewport");this._viewport=t,this._rebuildQuadTree()}updateViewport(t){(t.width!==this._viewport.width||t.height!==this._viewport.height)&&(this._viewport=t,this._rebuildQuadTree())}addBoxes(t){t.forEach(e=>{this._isBoxInViewport(e)&&this._quadtree.add(e)})}findCollisions(t){const e=[],n=this._getSearchBounds(t);return this._quadtree.visit((r,s,a,c,u)=>this._checkNodeCollision(n,s,a,c,u)?(r.length||this._getNodeData(r).forEach(p=>{p.id!==t.id&&this._checkBoxCollision(t,p)&&e.push(p)}),!1):void 0),e}clear(){this._rebuildQuadTree()}getAllBoxes(){const t=[];return this._quadtree.visit(e=>{if(!e.length){const n=this._getNodeData(e);t.push(...n)}return!1}),t}_rebuildQuadTree(){this._quadtree=Pl().x(t=>t.x).y(t=>t.y).extent([[0,0],[this._viewport.width,this._viewport.height]])}_isBoxInViewport(t){const e=t.width/2,n=t.height/2;return t.x+e>=0&&t.x-e<=this._viewport.width&&t.y+n>=0&&t.y-n<=this._viewport.height}_getSearchBounds(t){return{x:t.x,y:t.y,width:t.width*2,height:t.height*2}}_checkNodeCollision(t,e,n,r,s){const a=(e+r)/2,c=(n+s)/2,u=r-e,d=s-n;return Math.abs(t.x-a)*2<t.width+u&&Math.abs(t.y-c)*2<t.height+d}_checkBoxCollision(t,e){return Math.abs(t.x-e.x)*2<t.width+e.width&&Math.abs(t.y-e.y)*2<t.height+e.height}_getNodeData(t){return t?Array.isArray(t.data)?t.data:t.data?[t.data]:[]:[]}removeBox(t){const n=this.getAllBoxes().filter(r=>r.id!==t);this.clear(),n.length>0&&this.addBoxes(n)}}class vp{constructor(){T(this,"_strategies",new Map);T(this,"_executionOrder",[])}registerStrategy(t,e){return this._strategies.set(t.name,t),e!==void 0?this._executionOrder.splice(e,0,t.name):this._executionOrder.push(t.name),this}async executeStrategies(t,e){const n=new Map;t.forEach(r=>{n.set(r._id,{featureId:r._id,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp})});for(const r of this._executionOrder){const s=this._strategies.get(r);if(s?.enabled)try{const a=await s.execute(t,e,n);this._mergeResults(n,a)}catch(a){console.error(`策略 ${r} 执行失败:`,a)}}return n}_mergeResults(t,e){e.forEach(n=>{const r=t.get(n.featureId);r&&!r.visible||t.set(n.featureId,n)})}}class wp{constructor(){T(this,"frameStats",new Map);T(this,"summaryStats",{totalFrames:0,averageFrameTime:0,averageFPS:0,minFrameTime:1/0,maxFrameTime:0,totalFeaturesProcessed:0});T(this,"sampleWindowSize",60);T(this,"currentFrameId",0);T(this,"lastReportTime",0);T(this,"reportInterval",5e3);T(this,"performanceThresholds",{criticalFrameTime:33,warningFrameTime:16,idealFrameTime:8});this.lastReportTime=Date.now()}startFrame(t){this.currentFrameId=t;const e={frameId:t,startTime:performance.now(),endTime:0,duration:0,featureCount:0,visibleCount:0,hiddenCount:0,collisionChecks:0,memoryUsage:0,strategyTimes:new Map};this.frameStats.set(t,e),this.cleanupOldFrames()}endFrame(t,e){const n=this.frameStats.get(t);if(!n)return;const r=performance.now();n.endTime=r,n.duration=r-n.startTime,e&&Object.assign(n,e),"memory"in performance&&(n.memoryUsage=performance.memory.usedJSHeapSize),this.updateSummaryStats(n),this.maybeOutputReport()}recordStrategyTime(t,e){const n=this.frameStats.get(this.currentFrameId);n&&n.strategyTimes.set(t,e)}recordCollisionChecks(t){const e=this.frameStats.get(this.currentFrameId);e&&(e.collisionChecks+=t)}getStats(){const t=this.getRecentFrames(this.sampleWindowSize),e=this.calculateFPS(t),n=this.calculateAverageFrameTime(t);return{summary:{...this.summaryStats},recent:{fps:e,frameTime:n,frameTimeStdDev:this.calculateFrameTimeStdDev(t),averageFeaturesPerFrame:this.calculateAverageFeatures(t),performanceLevel:this.getPerformanceLevel(n)},currentFrame:this.frameStats.get(this.currentFrameId)||null,strategies:this.getStrategyPerformance(t),warnings:this.getPerformanceWarnings(t)}}getDetailedReport(){const t=this.getRecentFrames(this.sampleWindowSize),e=this.getStats();return{...e,frameHistory:Array.from(t.values()),trends:this.calculateTrends(t),recommendations:this.getPerformanceRecommendations(e)}}reset(){this.frameStats.clear(),this.summaryStats={totalFrames:0,averageFrameTime:0,averageFPS:0,minFrameTime:1/0,maxFrameTime:0,totalFeaturesProcessed:0},this.currentFrameId=0,this.lastReportTime=Date.now()}cleanupOldFrames(){this.frameStats.size>this.sampleWindowSize*2&&Array.from(this.frameStats.keys()).sort((e,n)=>e-n).slice(0,this.frameStats.size-this.sampleWindowSize).forEach(e=>{this.frameStats.delete(e)})}updateSummaryStats(t){this.summaryStats.totalFrames++,this.summaryStats.totalFeaturesProcessed+=t.featureCount||0,this.summaryStats.averageFrameTime=(this.summaryStats.averageFrameTime*(this.summaryStats.totalFrames-1)+t.duration)/this.summaryStats.totalFrames,this.summaryStats.minFrameTime=Math.min(this.summaryStats.minFrameTime,t.duration),this.summaryStats.maxFrameTime=Math.max(this.summaryStats.maxFrameTime,t.duration),this.summaryStats.averageFPS=1e3/this.summaryStats.averageFrameTime}maybeOutputReport(){const t=Date.now();if(t-this.lastReportTime>=this.reportInterval){const e=this.getStats();e.warnings.length>0?console.warn("避让系统性能报告:",e):console.log("避让系统性能正常:",e),this.lastReportTime=t}}getRecentFrames(t){return Array.from(this.frameStats.values()).slice(-t).filter(n=>n.duration>0)}calculateFPS(t){if(t.length===0)return 0;const e=this.calculateAverageFrameTime(t);return e>0?1e3/e:0}calculateAverageFrameTime(t){return t.length===0?0:t.reduce((e,n)=>e+n.duration,0)/t.length}calculateFrameTimeStdDev(t){if(t.length===0)return 0;const e=this.calculateAverageFrameTime(t),n=t.map(r=>Math.pow(r.duration-e,2));return Math.sqrt(n.reduce((r,s)=>r+s,0)/t.length)}calculateAverageFeatures(t){return t.length===0?0:t.reduce((e,n)=>e+(n.featureCount||0),0)/t.length}getPerformanceLevel(t){return t>this.performanceThresholds.criticalFrameTime?"critical":t>this.performanceThresholds.warningFrameTime?"warning":t>this.performanceThresholds.idealFrameTime?"good":"excellent"}getStrategyPerformance(t){const e=new Map;return t.forEach(n=>{n.strategyTimes.forEach((r,s)=>{e.has(s)||e.set(s,[]),e.get(s).push(r)})}),Array.from(e.entries()).map(([n,r])=>({name:n,averageTime:r.reduce((s,a)=>s+a,0)/r.length,maxTime:Math.max(...r),minTime:Math.min(...r),callCount:r.length}))}getPerformanceWarnings(t){const e=[],n=t.slice(-30);if(n.length===0)return e;const r=this.calculateAverageFrameTime(n);r>this.performanceThresholds.criticalFrameTime?e.push({type:"critical",message:`帧率过低: ${Math.round(1e3/r)}fps`,suggestion:"考虑减少要素数量或简化避让策略"}):r>this.performanceThresholds.warningFrameTime&&e.push({type:"warning",message:`帧率较低: ${Math.round(1e3/r)}fps`,suggestion:"建议优化避让算法或增加更新间隔"});const s=n.map(a=>a.memoryUsage).filter(a=>a>0);if(s.length>0){const a=s.reduce((c,u)=>c+u,0)/s.length;a>100*1024*1024&&e.push({type:"warning",message:`内存使用较高: ${(a/1024/1024).toFixed(1)}MB`,suggestion:"检查内存泄漏,及时清理无用资源"})}return e}calculateTrends(t){if(t.length<2)return{frameTime:"stable",fps:"stable",features:"stable"};const e=t.slice(0,Math.floor(t.length/2)),n=t.slice(Math.floor(t.length/2)),r=this.calculateAverageFrameTime(e),a=(this.calculateAverageFrameTime(n)-r)/r*100;return{frameTime:Math.abs(a)<5?"stable":a>0?"worsening":"improving",fps:Math.abs(a)<5?"stable":a>0?"improving":"worsening",features:"stable"}}getPerformanceRecommendations(t){const e=[];return t.recent.performanceLevel==="critical"&&(e.push("建议启用要素抽样或聚合显示"),e.push("考虑增加避让更新间隔时间"),e.push("检查是否有不必要的避让策略")),t.recent.averageFeaturesPerFrame>5e3&&e.push("要素数量过多,建议启用LOD分级"),t.strategies.forEach(n=>{n.averageTime>10&&e.push(`策略 "${n.name}" 执行时间较长,考虑优化`)}),e}}class xp{constructor(){T(this,"name","priority");T(this,"enabled",!0);T(this,"weight",1);T(this,"description","基于优先级的避让策略,数值越小优先级越高")}async execute(t,e,n){const r=[],s=new Wl(e.viewport),a=[],c=new Map;return t.forEach(u=>{if(!u.collidable)return;const d=u.getScreenBoundingBox(e.camera,e.renderer);d&&(a.push(d),c.set(u._id,u),n?.get(u._id)?.visible)}),a.sort((u,d)=>u.priority-d.priority),a.forEach(u=>{const d=s.findCollisions(u);d.length===0?(s.addBoxes([u]),r.push({featureId:u.featureId,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp})):d.some(f=>f.priority<u.priority)?r.push({featureId:u.featureId,visible:!1,reason:rn.PRIORITY_LOST,collidedWith:d.map(f=>f.featureId),timestamp:e.timestamp}):(s.addBoxes([u]),r.push({featureId:u.featureId,visible:!0,reason:rn.NO_COLLISION,collidedWith:[],timestamp:e.timestamp}),d.forEach(f=>{r.push({featureId:f.featureId,visible:!1,reason:rn.PRIORITY_LOST,collidedWith:[u.featureId],timestamp:e.timestamp})}))}),r}}class bp{constructor(t,e={}){T(this,"_quadTreeManager");T(this,"_strategyOrchestrator");T(this,"_performanceMonitor");T(this,"_layers",new Set);T(this,"_config");T(this,"_isUpdating",!1);T(this,"_lastUpdateTime",0);T(this,"_frameCount",0);this.renderer=t,this._config={enabled:!0,padding:4,updateInterval:0,animationDuration:300,maxFeaturesPerFrame:2e3,viewportMargin:50,strategies:{priority:!0,grouping:!1,proximity:!1},...e},this._initializeComponents(),this._setupPerformanceMonitoring()}async update(t){if(!this._config.enabled||this._isUpdating)return;const e=Date.now();if(!(this._config.updateInterval>0&&e-this._lastUpdateTime<this._config.updateInterval)){this._isUpdating=!0,this._frameCount++;try{this._resetAllFeaturesVisibility();const n=this._createCollisionContext(t,e),r=this._collectCollidableFeatures();if(r.length===0)return;this._performanceMonitor.startFrame(this._frameCount);const s=await this._strategyOrchestrator.executeStrategies(r,n);await this._applyCollisionResults(s,r),this._performanceMonitor.endFrame(this._frameCount,{featureCount:r.length,visibleCount:Array.from(s.values()).filter(a=>a.visible).length,hiddenCount:Array.from(s.values()).filter(a=>!a.visible).length}),this._lastUpdateTime=e}catch(n){console.error("避让引擎更新失败:",n)}finally{this._isUpdating=!1}}}_resetAllFeaturesVisibility(){this._layers.forEach(t=>{t.getFeatures().filter(n=>n.collidable).forEach(n=>{n.setCollisionVisibility(!0,rn.NO_COLLISION)})})}registerLayer(t){return this._layers.add(t),this}unregisterLayer(t){return this._layers.delete(t),this}setConfig(t){return Object.assign(this._config,t),this}getPerformanceStats(){return this._performanceMonitor.getStats()}_initializeComponents(){const t={width:this.renderer.domElement.width,height:this.renderer.domElement.height};this._quadTreeManager=new Wl(t),this._strategyOrchestrator=new vp,this._performanceMonitor=new wp,this._strategyOrchestrator.registerStrategy(new xp,0),this._setupViewportResizeHandler()}_createCollisionContext(t,e){return{camera:t,renderer:this.renderer,viewport:{width:this.renderer.domElement.width,height:this.renderer.domElement.height},zoomLevel:t.position.z,timestamp:e,frameNumber:this._frameCount}}_collectCollidableFeatures(){const t=[];return this._layers.forEach(e=>{const n=e.getFeatures().filter(r=>r.collidable&&r instanceof Sn);if(t.length+n.length>this._config.maxFeaturesPerFrame){console.warn(`达到每帧最大要素处理限制: ${this._config.maxFeaturesPerFrame}`);return}t.push(...n)}),t}async _applyCollisionResults(t,e){const n=e.map(r=>{const s=t.get(r._id);return s&&r.setCollisionVisibility(s.visible,s.reason),Promise.resolve()});await Promise.all(n)}_setupViewportResizeHandler(){new ResizeObserver(e=>{e.forEach(n=>{const{width:r,height:s}=n.contentRect;this._quadTreeManager.updateViewport({width:r,height:s})})}).observe(this.renderer.domElement)}_setupPerformanceMonitoring(){setInterval(()=>{const t=this.getPerformanceStats();t.frameRate<30&&console.warn("避让系统性能警告:",t)},5e3)}}var Yr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Pi={exports:{}};/**
|
|
540
540
|
* @license
|
|
541
541
|
* Lodash <https://lodash.com/>
|
|
542
542
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|
|
@@ -654,7 +654,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
654
654
|
}
|
|
655
655
|
`)}setDiffusionFromObject(e){if(!this.shaderOption.effects?.diffusion)return;const n=new wt.Box3().setFromObject(e);if(n.isEmpty())return;const r=new wt.Vector3;n.getCenter(r);const s=[new wt.Vector3(n.min.x,n.min.y,n.min.z),new wt.Vector3(n.max.x,n.max.y,n.max.z)];let a=0;s.forEach(c=>{const u=r.distanceTo(c);u>a&&(a=u)}),this.shaderOption.effects.diffusion={...this.shaderOption.effects.diffusion,center:r,maxDistance:a},this.needsUpdate=!0}updateBoundingBox(e,n){this.shaderOption.minY=e,this.shaderOption.maxY=n,this.needsUpdate=!0}updateEffects(e){this.shaderOption.effects={...this.shaderOption.effects,...e},this.needsUpdate=!0}animate(){requestAnimationFrame(()=>this.animate()),this.time.value=this.clock.getElapsedTime(),this.startTime.value<1&&(this.startTime.value+=.01)}}const Pp={emissive:!1,emissiveIntensity:1,emissiveColor:"#ffffff"};class Fl extends Ur{constructor(e){super(e);T(this,"_type","Model");T(this,"_emissive",!1);T(this,"_emissiveIntensity",1);T(this,"_emissiveColor","#ffffff");T(this,"_mixer",null);T(this,"_currentAction",null);T(this,"_animations",[]);T(this,"_clock",new m.Clock);T(this,"_autoUpdate",!0);T(this,"_animationRequestId",null);T(this,"_iscity",!1);this._emissive=e.emissive||!1,this._emissiveIntensity=e.emissiveIntensity||1,this._emissiveColor=e.emissiveColor||"#ffffff",this.castShadow=e.castShadow||!1,this.receiveShadow=e.receiveShadow||!1,this._iscity=e.iscity||!1}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this.modelunino=await this._createObject(this._style),this._threeGeometry=this.modelunino.model,this._threeGeometry.userData._type="Model",this.modelunino.animations&&this.modelunino.animations.length>0&&(this._animations=this.modelunino.animations,this._mixer=new m.AnimationMixer(this._threeGeometry),this._startAnimationLoop(),this.playAnimation({name:this._animations[0].name,loop:!0,speed:1.5,fadeInDuration:.5,fadeOutDuration:.3})),this._updateGeometry(),this.setShadows({cast:this.castShadow,receive:this.receiveShadow}),this._applyEmissionProperties(),this._iscity&&this._rendercity())}async _createObject(e){switch(e.config.type){case"fbx":case"gltf":return Df(e.config,this._position);default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}_applyEmissionProperties(){this._threeGeometry&&this._threeGeometry.traverse(e=>{if("material"in e){const n=e.material;n&&(n.emissiveIntensity=this._emissive?this._emissiveIntensity:0,n.emissive&&n.emissive.setStyle(this._emissiveColor))}})}get emissive(){return this._emissive}set emissive(e){this._emissive=e,this._applyEmissionProperties()}get emissiveIntensity(){return this._emissiveIntensity}set emissiveIntensity(e){this._emissiveIntensity=e,this._applyEmissionProperties()}get emissiveColor(){return this._emissiveColor}set emissiveColor(e){this._emissiveColor=e,this._applyEmissionProperties()}setEmission(e,n,r){this._emissive=e,n!==void 0&&(this._emissiveIntensity=n),r!==void 0&&(this._emissiveColor=r),this._applyEmissionProperties()}async setShadows(e){this.castShadow=e.cast,this.receiveShadow=e.receive,this._threeGeometry&&this._threeGeometry.traverse(n=>{n.isMesh&&n.material&&(n.castShadow=e.cast,n.receiveShadow=e.receive)})}playAnimation(e){if(!this._mixer||this._animations.length===0){console.warn("模型没有可用的动画");return}this._currentAction&&(e.fadeOutDuration&&e.fadeOutDuration>0?this._currentAction.fadeOut(e.fadeOutDuration):this._currentAction.stop());const n=typeof e.name=="number"?this._animations[e.name]:this._animations.find(r=>r.name===e.name);if(!n){console.warn(`找不到动画: ${e.name}`);return}this._currentAction=this._mixer.clipAction(n),this._currentAction.setLoop(e.loop?m.LoopRepeat:m.LoopOnce,e.loop?1/0:1),this._currentAction.timeScale=e.speed||1,this._currentAction.time=e.startAt||0,this._currentAction.setEffectiveWeight(e.weight||1),e.fadeInDuration&&e.fadeInDuration>0&&this._currentAction.fadeIn(e.fadeInDuration),this._currentAction.play(),this._autoUpdate&&this._animationRequestId===null&&this._startAnimationLoop()}stopAnimation(e={}){this._currentAction&&(e.fadeDuration&&e.fadeDuration>0?(this._currentAction.fadeOut(e.fadeDuration),setTimeout(()=>{this._currentAction&&(this._currentAction.stop(),this._currentAction=null)},e.fadeDuration*1e3)):(this._currentAction.stop(),this._currentAction=null))}setAnimationPaused(e){this._currentAction&&(this._currentAction.paused=e.paused)}setAnimationSpeed(e){this._currentAction&&(this._currentAction.timeScale=e.speed)}updateAnimation(e){this._mixer&&this._mixer.update(e.deltaTime)}getAnimationNames(){return this._animations.map(e=>e.name)}getCurrentAnimationName(){return this._currentAction?this._currentAction.getClip().name:null}getAnimationDuration(e){let n;return typeof e.name=="number"?n=this._animations[e.name]:n=this._animations.find(r=>r.name===e.name),n?n.duration:null}dispose(){this._stopAnimationLoop(),this._mixer&&(this._mixer.stopAllAction(),this._mixer.uncacheRoot(this._threeGeometry)),super.dispose()}_startAnimationLoop(){if(!this._autoUpdate||this._animationRequestId!==null)return;const e=()=>{if(this._mixer){const n=this._clock.getDelta();this._mixer.update(n)}this._animationRequestId=requestAnimationFrame(e)};this._clock.start(),this._animationRequestId=requestAnimationFrame(e)}_stopAnimationLoop(){this._animationRequestId!==null&&(cancelAnimationFrame(this._animationRequestId),this._animationRequestId=null),this._clock.stop()}setAutoUpdate(e){this._autoUpdate=e,e?this._startAnimationLoop():this._stopAnimationLoop()}_rendercity(){this.traverse(async e=>{if(e instanceof m.Mesh&&e.material){if(e.castShadow=!0,e.name==="building"){const n=new Gp({color:new m.Color("#6BA7EC").multiplyScalar(1.8),opacity:.95,shaderOption:{minY:0,maxY:50,minRate:.3,maxRate:1.5,effects:{diffusion:{enabled:!0,color:new m.Color("#FFFFF"),width:300,speed:.05},flow:{enabled:!1,color:new m.Color("#FFFFF"),range:1e3,speed:3e3},sweep:{enabled:!0,color:new m.Color("#ffffff"),width:3,speed:5}}}}),r=new m.Box3().setFromObject(e);n.updateBoundingBox(r.min.y,r.max.y),n.setDiffusionFromObject(e),e.material=n,e.material.needsUpdate=!0}e.name==="grass"&&(e.castShadow=!1,e.receiveShadow=!0,e.material.color=new m.Color("#81e4d8ff)").multiplyScalar(.7),e.material.metalness=.2,e.material.roughness=.8,["metalnessMap","normalMap","roughnessMap","specularColorMap"].forEach(n=>{const r=e.material[n];r&&(r.wrapS=r.wrapT=m.RepeatWrapping,r.repeat.set(.3,.3),r.needsUpdate=!0)}),e.material.normalScale=new m.Vector2(3,3))}})}}Fl.mergeOptions(Pp);const Ip={};class Xl extends Ur{constructor(e){super(e);T(this,"_type","Cloud")}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}_updateGeometry(){this._disposeGeometry();const e=this.getLayer();this._threeGeometry&&(this._threeGeometry.position.copy(this._position),this._threeGeometry.renderOrder=1e3,e&&(e._clouds.add(this._threeGeometry),e._clouds.updateMatrixWorld()))}async _createObject(e){switch(e.config.type){case"cloud":return Yf(e.config,this._position);default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}}Xl.mergeOptions(Ip);const Wp={};class kl extends Ur{constructor(e){super(e);T(this,"_type","Label")}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}async _createObject(e){switch(e.config.type){case"canvas-label-fixed":return Bf(e.config,new m.Vector3(0,0,0),this.getMap());case"canvas-label":return Uf(e.config,new m.Vector3(0,0,0));default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}}kl.mergeOptions(Wp);const Cp={};class Dl extends Ur{constructor(e){super(e);T(this,"_type","TPoints");T(this,"_geometries");this._geometries=e.geometries}async _toThreeJSGeometry(){this._position=this._coordsTransform(),this._style&&(this._threeGeometry&&this._disposeGeometry(),this._threeGeometry=await this._createObject(this._style),this._updateGeometry())}_updateGeometry(){this._threeGeometry&&(this._threeGeometry.points&&this.add(this._threeGeometry.points),this._threeGeometry.InstancedCol&&this.add(this._threeGeometry.InstancedCol),this.updateMatrixWorld(!0))}async _createObject(e){switch(e.config.type){case"light":return Qf(e.config,this._geometries,this.getMap());default:throw new Error(`不支持的样式类型: ${e.config.type}`)}}}Dl.mergeOptions(Cp);function Ii(l,t){if(!l||l===!0)return!0;if(!Array.isArray(l))return!!l;switch(l[0]){case"all":return l.slice(1).every(n=>Ii(n,t));case"any":return l.slice(1).some(n=>Ii(n,t));case"!":return!Ii(l[1],t);case"==":{const n=it(l[1],t),r=it(l[2],t);return Wi(n)==Wi(r)}case"!=":{const n=it(l[1],t),r=it(l[2],t);return Wi(n)!=Wi(r)}case">":{const n=it(l[1],t),r=it(l[2],t);return Zn(n)>Zn(r)}case"<":{const n=it(l[1],t),r=it(l[2],t);return Zn(n)<Zn(r)}case">=":{const n=it(l[1],t),r=it(l[2],t);return Zn(n)>=Zn(r)}case"<=":{const n=it(l[1],t),r=it(l[2],t);return Zn(n)<=Zn(r)}case"in":{const n=it(l[1],t);return l.slice(2).map(s=>it(s,t)).includes(n)}case"!in":{const n=it(l[1],t);return!l.slice(2).map(s=>it(s,t)).includes(n)}case"has":{const n=l[1];return t!=null&&Object.prototype.hasOwnProperty.call(t,n)}case"!has":{const n=l[1];return!(t!=null&&Object.prototype.hasOwnProperty.call(t,n))}default:return!0}}function it(l,t){if(Array.isArray(l))switch(l[0]){case"get":return t?t[l[1]]:void 0;default:return l}return l}function Wi(l){if(l==null)return null;if(typeof l=="string"){const t=Number(l);if(!isNaN(t)&&l.trim()!=="")return t}return typeof l=="boolean"?l?1:0:l}function Zn(l){if(l==null)return 0;if(typeof l=="number")return l;if(typeof l=="boolean")return l?1:0;if(typeof l=="string"){const t=Number(l);return isNaN(t)?0:t}return Number(l)}class Vp extends Bn{constructor(e,n){super(e,n);T(this,"TILE_SIZE");T(this,"EXTENT");T(this,"style");T(this,"_tileFeatureMap",new Map);T(this,"_activeFeatureFilter");this.TILE_SIZE=n.tileSize??256,this.EXTENT=n.extent??4096,this.style=n.style||[],this._onMapUpdate=this._onMapUpdate.bind(this)}processTileData(e,n){const r=this.getMap(),s=`${e.z}-${e.x}-${e.y}`,a=this._tileFeatureMap.get(s);if(a&&a.length>0){a.forEach(p=>{p.visible=!0,this.children.some(f=>f&&p&&f.uuid===p.uuid)||p.addTo(this)});return}const c=n.vectorData;if(!c||!c.layers||!r||this.style.length===0)return;const u=[],d=this.style;Object.keys(c.layers).forEach(p=>{const f=c.layers[p];for(let y=0;y<f.length;y++){const v=f[y],x=v.geometry;if(this._activeFeatureFilter&&!this._activeFeatureFilter(v.properties))continue;let L=null;for(const _ of d)if(this._evaluateFilter(_.filter,v.properties,p,v.geometry.type)){L=_.style;break}if(L){const _={isVectorTile:!0,tileZ:e.z,tileX:e.x,tileY:e.y,rawCoordinates:x,extent:this.EXTENT,tileSize:this.TILE_SIZE},S=this._createFeatureInstance(v.geometry,v.geometry.type,L,v.properties);S&&(S.userData.tileData=_,S.style=Pt.create(L),S.addTo(this),S.initializeGeometry(),u.push(S))}}}),this._tileFeatureMap.set(s,u)}_evaluateFilter(e,n,r,s){if(!e||e===!0)return!0;const a={...n,$layer:r,$type:s};return Ii(e,a)}hideFeaturesByTileKey(e){const n=this._tileFeatureMap.get(e);n&&n.forEach(r=>{r.visible=!1})}removeFeaturesByTileKey(e){this._removeFeaturesByTileKey(e)}_removeFeaturesByTileKey(e){const n=this._tileFeatureMap.get(e);n&&(n.forEach(r=>{r._remove()}),this._tileFeatureMap.delete(e))}_createFeatureInstance(e,n,r,s){const c={geometry:{ismvt:!0,...e},style:r,userData:s};switch(n){case"Point":return new ro(c);case"LineString":return new io(c);default:return null}}setFeatureFilter(e){this._activeFeatureFilter=e}clearFeatureFilter(){this._activeFeatureFilter=void 0}setOpacity(e){this.opacity=e,this._tileFeatureMap.forEach(n=>{n.forEach(r=>{r.material&&(r.material.opacity=e,r.material.transparent=e<1)})})}_onMapUpdate(){}validateFeature(e){return e instanceof Sn}dispose(){this._tileFeatureMap.forEach((e,n)=>{this._removeFeaturesByTileKey(n)}),super.dispose()}}class zl extends Si{constructor(e,n){super(e,n);T(this,"isTileLayer",!0);T(this,"layerType","base");T(this,"isBaseLayer",!1);T(this,"_enabled",!0);T(this,"_visible",!0);T(this,"_rootTile");T(this,"_loader");T(this,"_LODThreshold",1);T(this,"isSceneLayer",!1);T(this,"opacity",1);T(this,"source");T(this,"projection");T(this,"minLevel",2);T(this,"maxLevel",19);this.layerId=e,this.source=n.source,this.projection=n.projection,this.minLevel=n.minLevel??2,this.maxLevel=n.maxLevel??19,this._LODThreshold=n.LODThreshold??1,this.opacity=n.opacity??1,this.name=`Layer-${e}`,this._loader=this.createLoader(),this._rootTile=new nn,this._rootTile.matrixAutoUpdate=!0,this._rootTile.scale.set(this.projection.mapWidth,this.projection.mapHeight,1),this.add(this._rootTile),this._rootTile.updateMatrix(),this.layerId=e,this.name==="Layer-label-layer"&&this.position.set(0,0,1)}get LODThreshold(){return this._LODThreshold}set LODThreshold(e){this._LODThreshold=e}get loader(){return this._loader}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._rootTile&&(this._rootTile.visible=e&&this._visible)}get ivisible(){return this._visible&&super._visible}set ivisible(e){this._visible=e,this._rootTile&&(this._rootTile.visible=e&&this._enabled)}update(e){if(!(!this._enabled||!this._visible)){try{this._rootTile.update({camera:e,loader:this._loader,minLevel:this.minLevel,maxLevel:this.maxLevel,LODThreshold:this.LODThreshold})}catch{}console.groupEnd()}}_debugTileTree(){this._rootTile.traverse(e=>{e.isTile&&(e.loaded,e.visible,e.inFrustum,e.loaded)})}_getLODThreshold(){return 1}_getCurrentTileLevel(){let e=0;return this._rootTile.traverse(n=>{n.isTile&&n.loaded&&(e=Math.max(e,n.z))}),`最大层级: ${e}`}dispose(){this.remove(this._rootTile),this._rootTile.reload(this._loader)}reload(){this._rootTile.reload(this._loader)}setElevation(e){this.position.y=e,this.updateMatrix(),this.updateMatrixWorld(!0)}raiseElevation(e){this.position.z+=e,this.updateMatrix(),this.updateMatrixWorld(!0)}getElevation(){return this.position.y}}class Ol extends m.LoadingManager{constructor(){super(...arguments);T(this,"onParseEnd")}parseEnd(e){this.onParseEnd&&this.onParseEnd(e)}}const Xe={manager:new Ol,demLoaderMap:new Map,meshLoaderMap:new Map,imgLoaderMap:new Map,registerMaterialLoader(l){Xe.imgLoaderMap.set(l.dataType,l),l.info.author=l.info.author??Zs.name},registerGeometryLoader(l){Xe.demLoaderMap.set(l.dataType,l),l.info.author=l.info.author??Zs.name},registerMeshLoader(l){Xe.meshLoaderMap.set(l.dataType,l),l.info.author=l.info.author??Zs.name},getMaterialLoader(l){const t=Xe.imgLoaderMap.get(l.dataType);if(t)return t;throw`Source dataType "${l.dataType}" is not support!`},getGeometryLoader(l){const t=Xe.demLoaderMap.get(l.dataType);if(t)return t;throw`Source dataType "${l.dataType}" is not support!`},getMeshLoader(l){const t=Xe.meshLoaderMap.get(l.dataType);if(t)return t;throw`Source dataType "${l.dataType}" is not support!`}};class Ap{constructor(t){T(this,"worker");this.worker=t()}async run(t,e){return new Promise(n=>{this.worker.onmessage=r=>{n(r.data)},this.worker.postMessage(t,e)})}terminate(){this.worker.terminate()}}const Fp=4096,Kl=Math.PI;function so(l,t){const e=Math.floor(l[0]*t),n=Math.floor(l[1]*t),r=Math.floor((l[2]-l[0])*t),s=Math.floor((l[3]-l[1])*t);return{sx:e,sy:n,sw:r,sh:s}}function oo(l,t,e,n){if(n<l.minLevel)return{url:void 0,clipBounds:[0,0,1,1]};if(n<=l.maxLevel)return{url:l._getUrl(t,e,n),clipBounds:[0,0,1,1]};const r=Xp(t,e,n,l.maxLevel),s=r.parentNO;return{url:l._getUrl(s.x,s.y,s.z),clipBounds:r.bounds}}function Xp(l,t,e,n){const r=e-n,s={x:l>>r,y:t>>r,z:e-r},a=Math.pow(2,r),c=Math.pow(.5,r),u=l%a/a-.5+c/2,d=t%a/a-.5+c/2,p=new m.Vector2(u,d),f=new m.Box2().setFromCenterAndSize(p,new m.Vector2(c,c)),y=[f.min.x+.5,f.min.y+.5,f.max.x+.5,f.max.y+.5];return{parentNO:s,bounds:y}}function ao(l,t,e,n,r=Fp){const{x:s,y:a}=l,c=(t+s/r)/Math.pow(2,n),u=(e+a/r)/Math.pow(2,n),d=c*360-180,f=Math.atan(Math.sinh(Kl*(1-2*u)))*180/Kl;return[parseFloat(d.toFixed(8)),parseFloat(f.toFixed(8))]}function kp(l,t,e,n){if(!l||!l.coordinates)throw new Error("无效的geometry数据格式");const r={type:l.type,coordinates:null};function s(a){if(typeof a=="object"&&a.x!==void 0&&a.y!==void 0)return ao(a,t,e,n);if(Array.isArray(a)&&a.length>0){const c=a[0];return typeof c=="object"&&c.x!==void 0&&c.y!==void 0?a.map(u=>ao(u,t,e,n)):a.map(u=>s(u))}return a}return r.coordinates=s(l.coordinates),r}class Ci{constructor(){T(this,"_imgSource",[]);T(this,"_demSource");T(this,"_vtSource");T(this,"manager",Xe.manager)}get imgSource(){return this._imgSource}set imgSource(t){this._imgSource=t}get demSource(){return this._demSource}set demSource(t){this._demSource=t}get vtSource(){return this._vtSource}set vtSource(t){this._vtSource=t}async load(t){const e=await this.loadGeometry(t),n=await this.loadMaterial(t);console.assert(!!n&&!!e);for(let r=0;r<n.length;r++)e.addGroup(0,1/0,r);return{materials:n,geometry:e}}unload(t){const e=t.material,n=t.geometry;for(let r=0;r<e.length;r++)e[r].dispose();n.dispose()}async loadGeometry(t){let e;if(this.demSource&&t.z>=this.demSource.minLevel&&this._isBoundsInSourceBounds(this.demSource,t.bounds)){const n=Xe.getGeometryLoader(this.demSource),r=this.demSource;e=await n.load({source:r,...t}).catch(s=>(console.error("Load material error",r.dataType,t.x,t.y,t.z),new m.PlaneGeometry)),e.addEventListener("dispose",()=>{n.unload&&n.unload(e)})}else if(this.vtSource&&t.z>=this.vtSource.minLevel&&this._isBoundsInSourceBounds(this.vtSource,t.bounds)){const n=Xe.getMeshLoader(this.vtSource),r=this.vtSource;e=await n.load({source:r,...t}).catch(s=>(console.error("Load geometry error",r.dataType,t.x,t.y,t.z),new m.PlaneGeometry)),e.addEventListener("dispose",()=>{n.unload&&n.unload(e)})}else e=new m.PlaneGeometry;return e}async loadMaterial(t){const n=this.imgSource.filter(r=>t.z>=r.minLevel&&this._isBoundsInSourceBounds(r,t.bounds)).map(async r=>{const s=Xe.getMaterialLoader(r),a=await s.load({source:r,...t}).catch(u=>(console.error("Load material error",r.dataType,t.x,t.y,t.z),new m.MeshBasicMaterial)),c=u=>{s.unload&&s.unload(u.target),u.target.removeEventListener("dispose",c)};return a instanceof m.MeshBasicMaterial||a.addEventListener("dispose",c),a});return Promise.all(n)}_isBoundsInSourceBounds(t,e){const n=t._projectionBounds;return!(e[2]<n[0]||e[3]<n[1]||e[0]>n[2]||e[1]>n[3])}}function Br(...l){const t=l,e=t&&t.length>1&&t[0].constructor||null;if(!e)throw new Error("concatenateTypedArrays - incorrect quantity of arguments or arguments have incompatible data types");const n=t.reduce((a,c)=>a+c.length,0),r=new e(n);let s=0;for(const a of t)r.set(a,s),s+=a.length;return r}function Rl(l,t,e,n){const r=n?zp(n,l.position.value):Dp(t),s=r.length,a=new Float32Array(s*6),c=new Float32Array(s*4),u=new t.constructor(s*6),d=new Float32Array(s*6);for(let f=0;f<s;f++)Op({edge:r[f],edgeIndex:f,attributes:l,skirtHeight:e,newPosition:a,newTexcoord0:c,newTriangles:u,newNormals:d});l.position.value=Br(l.position.value,a),l.texcoord.value=Br(l.texcoord.value,c),l.normal.value=Br(l.normal.value,d);const p=Br(t,u);return{attributes:l,indices:p}}function Dp(l){const t=[],e=Array.isArray(l)?l:Array.from(l);for(let r=0;r<e.length;r+=3){const s=e[r],a=e[r+1],c=e[r+2];t.push([s,a],[a,c],[c,s])}t.sort(([r,s],[a,c])=>{const u=Math.min(r,s),d=Math.min(a,c);return u!==d?u-d:Math.max(r,s)-Math.max(a,c)});const n=[];for(let r=0;r<t.length;r++)r+1<t.length&&t[r][0]===t[r+1][1]&&t[r][1]===t[r+1][0]?r++:n.push(t[r]);return n}function zp(l,t){const e=(r,s)=>{r.sort(s)};e(l.westIndices,(r,s)=>t[3*r+1]-t[3*s+1]),e(l.eastIndices,(r,s)=>t[3*s+1]-t[3*r+1]),e(l.southIndices,(r,s)=>t[3*s]-t[3*r]),e(l.northIndices,(r,s)=>t[3*r]-t[3*s]);const n=[];return Object.values(l).forEach(r=>{if(r.length>1)for(let s=0;s<r.length-1;s++)n.push([r[s],r[s+1]])}),n}function Op({edge:l,edgeIndex:t,attributes:e,skirtHeight:n,newPosition:r,newTexcoord0:s,newTriangles:a,newNormals:c}){const u=e.position.value.length,d=t*2,p=d+1;r.set(e.position.value.subarray(l[0]*3,l[0]*3+3),d*3),r[d*3+2]=r[d*3+2]-n,r.set(e.position.value.subarray(l[1]*3,l[1]*3+3),p*3),r[p*3+2]=r[p*3+2]-n,s.set(e.texcoord.value.subarray(l[0]*2,l[0]*2+2),d*2),s.set(e.texcoord.value.subarray(l[1]*2,l[1]*2+2),p*2);const f=t*2*3;a[f]=l[0],a[f+1]=u/3+p,a[f+2]=l[1],a[f+3]=u/3+p,a[f+4]=l[0],a[f+5]=u/3+d,c[f]=0,c[f+1]=0,c[f+2]=1,c[f+3]=0,c[f+4]=0,c[f+5]=1}function Yl(l){if(l.length<4)throw new Error(`DEM数组长度必须大于4,当前长度: ${l.length}!`);const t=Math.floor(Math.sqrt(l.length)),e=t,n=t,r=lo(n,e);return{attributes:Kp(l,n,e),indices:r}}function Kp(l,t,e){const n=e*t,r=new Float32Array(n*3),s=new Float32Array(n*2);let a=0;for(let c=0;c<t;c++)for(let u=0;u<e;u++){const d=u/(e-1),p=c/(t-1);s[a*2]=d,s[a*2+1]=p,r[a*3]=d-.5,r[a*3+1]=p-.5,r[a*3+2]=l[(t-c-1)*e+u],a++}return{position:{value:r,size:3},texcoord:{value:s,size:2},normal:{value:co(r,lo(t,e)),size:3}}}function lo(l,t){const e=6*(t-1)*(l-1),n=new Uint16Array(e);let r=0;for(let s=0;s<l-1;s++)for(let a=0;a<t-1;a++){const c=s*t+a,u=c+1,d=c+t,p=d+1,f=r*6;n[f]=c,n[f+1]=u,n[f+2]=d,n[f+3]=d,n[f+4]=u,n[f+5]=p,r++}return n}function co(l,t){const e=new Float32Array(l.length);for(let n=0;n<t.length;n+=3){const r=t[n]*3,s=t[n+1]*3,a=t[n+2]*3,c=l[r],u=l[r+1],d=l[r+2],p=l[s],f=l[s+1],y=l[s+2],v=l[a],x=l[a+1],L=l[a+2],_=p-c,S=f-u,Z=y-d,G=v-c,A=x-u,K=L-d,D=S*K-Z*A,O=Z*G-_*K,V=_*A-S*G,R=Math.sqrt(D*D+O*O+V*V),W=[0,0,1];if(R>0){const k=1/R;W[0]=D*k,W[1]=O*k,W[2]=V*k}for(let k=0;k<3;k++)e[r+k]=e[s+k]=e[a+k]=W[k]}return e}class fr extends m.PlaneGeometry{constructor(){super(...arguments);T(this,"type","TileGeometry")}setData(e,n=1e3){let r=e instanceof Float32Array?Yl(e):e;r=Rl(r.attributes,r.indices,n);const{attributes:s,indices:a}=r;return this.setIndex(new m.BufferAttribute(a,1)),this.setAttribute("position",new m.BufferAttribute(s.position.value,s.position.size)),this.setAttribute("uv",new m.BufferAttribute(s.texcoord.value,s.texcoord.size)),this.setAttribute("normal",new m.BufferAttribute(s.normal.value,s.normal.size)),this.computeBoundingBox(),this.computeBoundingSphere(),this}}class Ul{constructor(t=257){T(this,"gridSize");T(this,"numTriangles");T(this,"numParentTriangles");T(this,"indices");T(this,"coords");this.gridSize=t;const e=t-1;if(e&e-1)throw new Error(`Expected grid size to be 2^n+1, got ${t}.`);this.numTriangles=e*e*2-2,this.numParentTriangles=this.numTriangles-e*e,this.indices=new Uint32Array(this.gridSize*this.gridSize),this.coords=new Uint16Array(this.numTriangles*4);for(let n=0;n<this.numTriangles;n++){let r=n+2,s=0,a=0,c=0,u=0,d=0,p=0;for(r&1?c=u=d=e:s=a=p=e;(r>>=1)>1;){const y=s+c>>1,v=a+u>>1;r&1?(c=s,u=a,s=d,a=p):(s=c,a=u,c=d,u=p),d=y,p=v}const f=n*4;this.coords[f+0]=s,this.coords[f+1]=a,this.coords[f+2]=c,this.coords[f+3]=u}}createTile(t){return new Rp(t,this)}}class Rp{constructor(t,e){T(this,"martini");T(this,"terrain");T(this,"errors");const n=e.gridSize;if(t.length!==n*n)throw new Error(`Expected terrain data of length ${n*n} (${n} x ${n}), got ${t.length}.`);this.terrain=t,this.martini=e,this.errors=new Float32Array(t.length),this.update()}update(){const{numTriangles:t,numParentTriangles:e,coords:n,gridSize:r}=this.martini,{terrain:s,errors:a}=this;for(let c=t-1;c>=0;c--){const u=c*4,d=n[u+0],p=n[u+1],f=n[u+2],y=n[u+3],v=d+f>>1,x=p+y>>1,L=v+x-p,_=x+d-v,S=(s[p*r+d]+s[y*r+f])/2,Z=x*r+v,G=Math.abs(S-s[Z]);if(a[Z]=Math.max(a[Z],G),c<e){const A=(p+_>>1)*r+(d+L>>1),K=(y+_>>1)*r+(f+L>>1);a[Z]=Math.max(a[Z],a[A],a[K])}}}getGeometryData(t=0){const{gridSize:e,indices:n}=this.martini,{errors:r}=this;let s=0,a=0;const c=e-1;let u,d,p=0;n.fill(0);function f(Z,G,A,K,D,O){const V=Z+A>>1,R=G+K>>1;Math.abs(Z-D)+Math.abs(G-O)>1&&r[R*e+V]>t?(f(D,O,Z,G,V,R),f(A,K,D,O,V,R)):(u=G*e+Z,d=K*e+A,p=O*e+D,n[u]===0&&(n[u]=++s),n[d]===0&&(n[d]=++s),n[p]===0&&(n[p]=++s),a++)}f(0,0,c,c,c,0),f(c,c,0,0,0,c);const y=s*2,v=a*3,x=new Uint16Array(y),L=new Uint32Array(v);let _=0;function S(Z,G,A,K,D,O){const V=Z+A>>1,R=G+K>>1;if(Math.abs(Z-D)+Math.abs(G-O)>1&&r[R*e+V]>t)S(D,O,Z,G,V,R),S(A,K,D,O,V,R);else{const W=n[G*e+Z]-1,k=n[K*e+A]-1,N=n[O*e+D]-1;x[2*W]=Z,x[2*W+1]=G,x[2*k]=A,x[2*k+1]=K,x[2*N]=D,x[2*N+1]=O,L[_++]=W,L[_++]=k,L[_++]=N}}return S(0,0,c,c,c,0),S(c,c,0,0,0,c),{attributes:this._getMeshAttributes(this.terrain,x,L),indices:L}}_getMeshAttributes(t,e,n){const r=Math.floor(Math.sqrt(t.length)),s=r-1,a=e.length/2,c=new Float32Array(a*3),u=new Float32Array(a*2);for(let p=0;p<a;p++){const f=e[p*2],y=e[p*2+1],v=y*r+f;c[3*p+0]=f/s-.5,c[3*p+1]=.5-y/s,c[3*p+2]=t[v],u[2*p+0]=f/s,u[2*p+1]=1-y/s}const d=co(c,n);return{position:{value:c,size:3},texcoord:{value:u,size:2},normal:{value:d,size:3}}}}class uo{constructor(){T(this,"info",{version:"0.10.0",description:"Terrain loader base class"});T(this,"dataType","")}async load(t){const{source:e,x:n,y:r,z:s}=t,{url:a,clipBounds:c}=oo(e,n,r,s);if(!a)return new fr;const u=await this.doLoad(a,{source:e,x:n,y:r,z:s,bounds:c});return Xe.manager.parseEnd(a),u}}class ho extends m.MeshStandardMaterial{constructor(t={}){super({transparent:!0,side:m.FrontSide,...t})}setTexture(t){this.map=t,this.needsUpdate=!0}dispose(){const t=this.map;t&&(t.image instanceof ImageBitmap&&t.image.close(),t.dispose())}}var tt=(l=>(l[l.Unknown=0]="Unknown",l[l.Point=1]="Point",l[l.Linestring=2]="Linestring",l[l.Polygon=3]="Polygon",l))(tt||{});class Bl{render(t,e,n,r,s=1){switch(t.lineCap="round",t.lineJoin="round",(r.shadowBlur??0)>0&&(t.shadowBlur=r.shadowBlur??2,t.shadowColor=r.shadowColor??"black",t.shadowOffsetX=r.shadowOffset?r.shadowOffset[0]:0,t.shadowOffsetY=r.shadowOffset?r.shadowOffset[1]:0),e){case tt.Point:t.textAlign="center",t.textBaseline="middle",t.font=r.font??"14px Arial",t.fillStyle=r.fontColor??"white",this._renderPointText(t,n,s,r.textField??"name",r.fontOffset??[0,-8]);break;case tt.Linestring:this._renderLineString(t,n,s);break;case tt.Polygon:this._renderPolygon(t,n,s);break;default:console.warn(`Unknown feature type: ${e}`)}(r.fill||e===tt.Point)&&(t.globalAlpha=r.fillOpacity||.5,t.fillStyle=r.fillColor||r.color||"#3388ff",t.fill(r.fillRule||"evenodd")),(r.stroke??!0)&&(r.weight??1)>0&&(t.globalAlpha=r.opacity||1,t.lineWidth=r.weight||1,t.strokeStyle=r.color||"#3388ff",t.setLineDash(r.dashArray||[]),t.stroke())}_renderPointText(t,e,n=1,r="name",s=[0,0]){const a=e.geometry;t.beginPath();for(const u of a)for(let d=0;d<u.length;d++){const p=u[d];t.arc(p.x*n,p.y*n,2,0,2*Math.PI)}const c=e.properties;c&&c[r]&&t.fillText(c[r],a[0][0].x*n+s[0],a[0][0].y*n+s[1])}_renderLineString(t,e,n){const r=e.geometry;t.beginPath();for(const s of r)for(let a=0;a<s.length;a++){const{x:c,y:u}=s[a];a===0?t.moveTo(c*n,u*n):t.lineTo(c*n,u*n)}}_renderPolygon(t,e,n){const r=e.geometry;t.beginPath();for(let s=0;s<r.length;s++){const a=r[s];for(let c=0;c<a.length;c++){const{x:u,y:d}=a[c];c===0?t.moveTo(u*n,d*n):t.lineTo(u*n,d*n)}t.closePath()}}}class fo{constructor(){T(this,"info",{version:"0.10.0",description:"Image loader base class"});T(this,"dataType","")}async load(t){const{source:e,x:n,y:r,z:s}=t,a=new ho,{url:c,clipBounds:u}=oo(e,n,r,s);if(c){const d=await this.doLoad(c,{source:e,x:n,y:r,z:s,bounds:u});a.map=d,Xe.manager.parseEnd(c)}return a}}class Yp{constructor(){T(this,"info",{version:"0.10.0",description:"Canvas tile abstract loader"});T(this,"dataType","")}async load(t){const e=this._creatCanvasContext(256,256);this.drawTile(e,t);const n=new m.CanvasTexture(e.canvas.transferToImageBitmap());return new ho({transparent:!0,map:n,opacity:t.source.opacity})}_creatCanvasContext(t,e){const r=new OffscreenCanvas(t,e).getContext("2d");if(!r)throw new Error("create canvas context failed");return r.scale(1,-1),r.translate(0,-e),r}}class Up extends fo{constructor(){super(...arguments);T(this,"info",{version:"0.10.0",description:"Tile image loader. It can load xyz tile image."});T(this,"dataType","image");T(this,"loader",new m.ImageLoader(Xe.manager))}async doLoad(e,n){const r=await this.loader.loadAsync(e).catch(c=>new Image(1,1)),s=new m.Texture;s.colorSpace=m.SRGBColorSpace;const{bounds:a}=n;return a[2]-a[0]<1?s.image=Bp(r,a):s.image=r,s.needsUpdate=!0,s}}function Bp(l,t){const e=l.width,n=new OffscreenCanvas(e,e),r=n.getContext("2d"),{sx:s,sy:a,sw:c,sh:u}=so(t,l.width);return r.drawImage(l,s,a,c,u,0,0,e,e),n}const Np=`{
|
|
656
656
|
"name": "@terra.gl/core",
|
|
657
|
-
"version": "0.0.1-alpha.
|
|
657
|
+
"version": "0.0.1-alpha.16",
|
|
658
658
|
"type": "module",
|
|
659
659
|
"files": [
|
|
660
660
|
"dist"
|
|
@@ -670,10 +670,10 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
670
670
|
}
|
|
671
671
|
},
|
|
672
672
|
"author": {
|
|
673
|
-
"name": "
|
|
673
|
+
"name": "Criska"
|
|
674
674
|
},
|
|
675
675
|
"description": "a map using threejs",
|
|
676
|
-
"license": "
|
|
676
|
+
"license": "Apache-2.0",
|
|
677
677
|
"keywords": [
|
|
678
678
|
"three",
|
|
679
679
|
"gis",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@terra.gl/core",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.16",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -16,10 +16,10 @@
|
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
18
|
"author": {
|
|
19
|
-
"name": "
|
|
19
|
+
"name": "Criska"
|
|
20
20
|
},
|
|
21
21
|
"description": "a map using threejs",
|
|
22
|
-
"license": "
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
23
|
"keywords": [
|
|
24
24
|
"three",
|
|
25
25
|
"gis",
|