cesium-multi-target-framework 0.1.0

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.
Files changed (41) hide show
  1. package/README.md +474 -0
  2. package/dist/assets/renderWorker-118e8f3b.js +1 -0
  3. package/dist/cesium-multi-target-framework.js +4605 -0
  4. package/dist/cesium-multi-target-framework.umd.cjs +101 -0
  5. package/dist/cluster/QuadCluster.d.ts +66 -0
  6. package/dist/cluster/clusterClient.d.ts +44 -0
  7. package/dist/cluster/clusterWorker.d.ts +1 -0
  8. package/dist/config/types.d.ts +266 -0
  9. package/dist/core/EventEmitter.d.ts +9 -0
  10. package/dist/core/MultiTargetFramework.d.ts +184 -0
  11. package/dist/core/MultiTargetScene.d.ts +224 -0
  12. package/dist/data/types.d.ts +67 -0
  13. package/dist/events/bus.d.ts +336 -0
  14. package/dist/index.d.ts +22 -0
  15. package/dist/render/AirGroundReferenceRenderer.d.ts +20 -0
  16. package/dist/render/InstancedGltfBatch.d.ts +37 -0
  17. package/dist/render/InstancedSymbolRenderer.d.ts +65 -0
  18. package/dist/render/LowModelInstancedRenderer.d.ts +39 -0
  19. package/dist/render/ModelPoolRenderer.d.ts +43 -0
  20. package/dist/render/PointCloudRenderer.d.ts +135 -0
  21. package/dist/render/SelectionOverlayRenderer.d.ts +37 -0
  22. package/dist/render/targetVisualMetrics.d.ts +9 -0
  23. package/dist/site/SiteLayer.d.ts +43 -0
  24. package/dist/site/SiteLowModelRenderer.d.ts +12 -0
  25. package/dist/site/SiteSpatialIndex.d.ts +10 -0
  26. package/dist/site/types.d.ts +72 -0
  27. package/dist/track/TrackHoverPicker.d.ts +26 -0
  28. package/dist/track/TrackManager.d.ts +42 -0
  29. package/dist/track/TrackRenderer.d.ts +29 -0
  30. package/dist/track/types.d.ts +27 -0
  31. package/dist/worker/protocol.d.ts +182 -0
  32. package/dist/worker/renderWorker.d.ts +1 -0
  33. package/doc//345/244/232/347/233/256/346/240/207/344/274/230/345/214/226/344/270/216/351/242/204/346/265/213/346/270/262/346/237/223/350/257/264/346/230/216.md +186 -0
  34. package/doc//345/244/232/347/273/204/344/273/266/344/272/213/344/273/266/346/226/271/346/241/210.md +410 -0
  35. package/doc//345/257/271/345/244/226/346/216/245/345/217/243/350/257/264/346/230/216.md +519 -0
  36. package/doc//345/267/245/344/275/234/350/256/241/345/210/222.md +59 -0
  37. package/doc//346/270/262/346/237/223/344/270/232/345/212/241/351/200/273/350/276/221.md +202 -0
  38. package/doc//347/253/231/347/202/271/346/270/262/346/237/223/344/270/216/345/217/263/351/224/256/350/217/234/345/215/225/345/256/236/347/216/260/350/257/264/346/230/216.md +49 -0
  39. package/doc//350/247/206/345/217/243/351/251/261/345/212/250/346/225/260/346/215/256/346/265/201/347/250/213/344/277/256/346/224/271/350/256/241/345/210/222.md +69 -0
  40. package/doc//351/241/271/347/233/256/350/257/264/346/230/216/344/271/246.md +729 -0
  41. package/package.json +51 -0
@@ -0,0 +1,101 @@
1
+ (function(P,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("cesium")):typeof define=="function"&&define.amd?define(["exports","cesium"],a):(P=typeof globalThis<"u"?globalThis:P||self,a(P.CesiumMultiTarget={},P.Cesium))})(this,function(P,a){"use strict";var ys=Object.defineProperty;var ws=(P,a,Q)=>a in P?ys(P,a,{enumerable:!0,configurable:!0,writable:!0,value:Q}):P[a]=Q;var l=(P,a,Q)=>(ws(P,typeof a!="symbol"?a+"":a,Q),Q);function Q(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const de=Q(a),oe={SURFACE:"surface",AIR:"air",UNDERWATER:"underwater"},Ue={pointAbove:15e4,animatedBelow:1e4},Xe={size:3e4},Ge={size:64},se={updateFps:30,predictSeconds:10,predictFitSeconds:2,masterHideHeight:15e4};function ai(i){var s,r,c,d,h,m,f,v,u,p,g,y,w,M,S,b,k,I,T,N,A,H,_,G,j,Z,J,Y,W,he,xe,Te,be,x,L,D;const t=new Map;for(const K of i.nodeTypes??[])t.set(K.type,K);const e=Array.from(t.values()).map(li),n=((s=i.pool)==null?void 0:s.size)??Xe.size,o=((r=i.frame)==null?void 0:r.heatmapAboveHeight)??2e6;return{nodeTypes:t,renderTypes:e,lod:i.lod??Ue,poolSize:n,animatedCapacity:((c=i.animatedPool)==null?void 0:c.size)??Ge.size,updateFps:i.updateFps??se.updateFps,predictSeconds:i.predictSeconds??se.predictSeconds,predictFitSeconds:i.predictFitSeconds??se.predictFitSeconds,fadeMs:i.fadeMs??350,masterHideHeight:i.masterHideHeight??se.masterHideHeight,groundSymbols:i.groundSymbols??!1,groundSymbolPixelSize:i.groundSymbolPixelSize??30,merge:mi(i.merge,n),pick:{enabled:((d=i.pick)==null?void 0:d.enabled)??!0,pixelThreshold:((h=i.pick)==null?void 0:h.pixelThreshold)??20,hover:((m=i.pick)==null?void 0:m.hover)??!0},cull:{enabled:((f=i.cull)==null?void 0:f.enabled)??!0,padding:((v=i.cull)==null?void 0:v.padding)??3e4,viewportCull:((u=i.cull)==null?void 0:u.viewportCull)??!0,viewportBufferRatio:((p=i.cull)==null?void 0:p.viewportBufferRatio)??.15,viewportBufferMinMeters:Math.max(0,((g=i.cull)==null?void 0:g.viewportBufferMinMeters)??500)},horizonCull:{enabled:((y=i.horizonCull)==null?void 0:y.enabled)??!0,pitchThreshold:((w=i.horizonCull)==null?void 0:w.pitchThreshold)??-25,minDistance:Math.max(0,((M=i.horizonCull)==null?void 0:M.minDistance)??8e3),maxDistance:Math.max(0,((S=i.horizonCull)==null?void 0:S.maxDistance)??4e4),cameraHeightMultiplier:Math.max(0,((b=i.horizonCull)==null?void 0:b.cameraHeightMultiplier)??6),maxCameraHeight:Math.max(0,((k=i.horizonCull)==null?void 0:k.maxCameraHeight)??8e4)},label:Ce(i.label),frame:{maxScanPerFrame:((I=i.frame)==null?void 0:I.maxScanPerFrame)??3e4,maxScanMs:((T=i.frame)==null?void 0:T.maxScanMs)??4,maxIngestPerFrame:((N=i.frame)==null?void 0:N.maxIngestPerFrame)??2e4,maxLowModelRenderItems:((A=i.frame)==null?void 0:A.maxLowModelRenderItems)??((H=i.frame)==null?void 0:H.maxModelRenderItems)??3e3,maxModelRenderItems:((_=i.frame)==null?void 0:_.maxModelRenderItems)??2e3,suspendRenderUpdateWhileMoving:((G=i.frame)==null?void 0:G.suspendRenderUpdateWhileMoving)??!0,heatmapAboveHeight:o,heatmapBelowHeight:((j=i.frame)==null?void 0:j.heatmapBelowHeight)??Math.max(0,o*.9),heatmapSwitchSettleMs:((Z=i.frame)==null?void 0:Z.heatmapSwitchSettleMs)??300,heatmapUpdateIntervalMs:((J=i.frame)==null?void 0:J.heatmapUpdateIntervalMs)??6e5},data:{commitIntervalMs:((Y=i.data)==null?void 0:Y.commitIntervalMs)??2e3,leading:((W=i.data)==null?void 0:W.leading)??!0,worker:((he=i.data)==null?void 0:he.worker)??!0},adaptive:{enabled:((xe=i.adaptive)==null?void 0:xe.enabled)??!0,dynamic:((Te=i.adaptive)==null?void 0:Te.dynamic)??!0,minFps:((be=i.adaptive)==null?void 0:be.minFps)??25,upFps:((x=i.adaptive)==null?void 0:x.upFps)??50,windowMs:((L=i.adaptive)==null?void 0:L.windowMs)??2e3,baseTier:((D=i.adaptive)==null?void 0:D.baseTier)??"high"}}}function li(i){const t=i.targetDomain??ci(i.type);return{...i,targetDomain:t,forceHighModelInLowLod:i.forceHighModelInLowLod??t===oe.AIR,iconPath:i.iconPath??i.pointIcon??hi(i.type),defaultColor:i.defaultColor??di(i.type),pointHeadingOffset:i.pointHeadingOffset??0,smoothMove:i.smoothMove??!1,smoothMoveMinCameraHeight:i.smoothMoveMinCameraHeight??25e3,smoothMoveDurationMs:i.smoothMoveDurationMs??i.moveAnimationDurationMs??400,predictMove:i.predictMove??!1,predictMinCameraHeight:i.predictMinCameraHeight??25e3,predictSeconds:i.predictSeconds,predictFitSeconds:i.predictFitSeconds}}function ci(i){return i.startsWith("air")||i.startsWith("uav")||i.includes("bird")||i.includes("aircraft")||i.includes("fpv")?oe.AIR:i.startsWith("underwater")||i.startsWith("subsea")?oe.UNDERWATER:oe.SURFACE}function hi(i){return i.startsWith("air")||i.startsWith("uav")?"/icons/target-uav-mask.png":i.startsWith("person")?"/icons/target-person-mask.png":i.startsWith("car")?"/icons/target-car-mask.png":"/icons/target-ship-mask.png"}function di(i){return i.startsWith("air")||i.startsWith("uav")?"#22d2f2":i.startsWith("person")?"#ffdc40":i.startsWith("car")?"#ff9a2a":"#25e65c"}function Ze(i){return{key:i.key,label:i.label,source:i.source??"standard",fallback:i.fallback,minCameraHeight:i.minCameraHeight,maxCameraHeight:i.maxCameraHeight}}function Ye(i){let t=0;for(const e of i??[])e.maxCameraHeight!=null&&e.maxCameraHeight>t&&(t=e.maxCameraHeight);return t}function ui(i){var t;return{...i,fields:(t=i.fields)==null?void 0:t.map(Ze),maxCameraHeight:i.maxCameraHeight!=null?Math.max(0,i.maxCameraHeight):void 0,maxCount:i.maxCount!=null?Math.max(0,i.maxCount):void 0}}function Ce(i){var s;const t=Math.max(0,(i==null?void 0:i.maxCameraHeight)??5e3),e=(s=i==null?void 0:i.fields)!=null&&s.length?i.fields.map(Ze):[{key:"id"}];let n=Math.max(t,Ye(e));const o=i!=null&&i.byType?Object.fromEntries(Object.entries(i.byType).map(([r,c])=>[r,ui(c)])):void 0;if(o)for(const r of Object.values(o))n=Math.max(n,r.maxCameraHeight??0,Ye(r.fields));return{enabled:(i==null?void 0:i.enabled)??!0,maxCount:Math.max(0,(i==null?void 0:i.maxCount)??200),maxCameraHeight:n,maxDistance:i==null?void 0:i.maxDistance,fields:e,byType:o,resolve:i==null?void 0:i.resolve,backgroundColor:(i==null?void 0:i.backgroundColor)??"#0000008c",textColor:(i==null?void 0:i.textColor)??"#ffffff",fontSize:Math.max(1,(i==null?void 0:i.fontSize)??12),fontFamily:(i==null?void 0:i.fontFamily)??"sans-serif",backgroundRadius:Math.max(0,(i==null?void 0:i.backgroundRadius)??6),overlapThreshold:fi((i==null?void 0:i.overlapThreshold)??.35,0,1),occlusionGraceMs:Math.max(0,(i==null?void 0:i.occlusionGraceMs)??300),offsetX:Math.max(0,(i==null?void 0:i.offsetX)??18),offsetY:Math.max(0,(i==null?void 0:i.offsetY)??24),connectorColor:(i==null?void 0:i.connectorColor)??(i==null?void 0:i.backgroundColor)??"#0000008c",connectorWidth:Math.max(0,(i==null?void 0:i.connectorWidth)??1.5),connectorStemLength:Math.max(0,(i==null?void 0:i.connectorStemLength)??50),showFieldLabels:(i==null?void 0:i.showFieldLabels)??!0}}function fi(i,t,e){return Math.max(t,Math.min(e,i))}function mi(i,t){if(!i)return;const e=(i.radii??[100,200,500,1e3,2e3,5e3,1e4]).slice().sort((n,o)=>n-o);return{enabled:i.enabled,mode:i.mode??"global",maxVisible:i.maxVisible??t,globalRootLimit:Math.max(1,i.globalRootLimit??500),globalMaxLevels:Math.max(1,i.globalMaxLevels??64),globalRebuildIntervalMs:Math.max(0,i.globalRebuildIntervalMs??3e5),globalViewportHeight:Math.max(0,i.globalViewportHeight??45e4),cameraMergeBaseHeight:Math.max(0,i.cameraMergeBaseHeight??1e5),cameraMergeStepHeight:Math.max(1,i.cameraMergeStepHeight??1e4),cameraMergeStepRadius:Math.max(1,i.cameraMergeStepRadius??100),innerRatio:Math.max(0,Math.min(1,i.innerRatio??.6)),radii:e,byType:i.byType??!0,minSecrecy:i.minSecrecy,bucketCellDeg:i.bucketCellDeg??.02}}class ue{constructor(){l(this,"handlers",new Map)}on(t,e){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(e),()=>this.off(t,e)}off(t,e){var n;(n=this.handlers.get(t))==null||n.delete(e)}emit(t,e){const n=this.handlers.get(t);if(n)for(const o of n)o(e)}clear(){this.handlers.clear()}}const Ke=new a.Color(.22,.82,1,.68),pi=new a.Color(.22,.82,1,0),Re=new a.Color(.12,.72,1,.72),ke=new a.Color(1,1,1,.9);class gi{constructor(t){l(this,"lineCollection");l(this,"pointCollection");l(this,"pool",[]);this.scene=t,this.lineCollection=this.scene.primitives.add(new a.PolylineCollection({show:!0})),this.pointCollection=this.scene.primitives.add(new a.PointPrimitiveCollection({show:!0}))}setTargets(t){this.ensurePool(t.length);for(let e=0;e<t.length;e++)this.updateSlot(this.pool[e],t[e]);for(let e=t.length;e<this.pool.length;e++)this.pool[e].line.show=!1,this.pool[e].point.show=!1}clear(){for(const t of this.pool)t.line.show=!1,t.point.show=!1}destroy(){this.clear(),this.scene.primitives.remove(this.lineCollection),this.scene.primitives.remove(this.pointCollection)}ensurePool(t){for(;this.pool.length<t;)this.pool.push(this.createSlot())}createSlot(){const t=a.Cartesian3.clone(a.Cartesian3.ZERO),e=a.Cartesian3.clone(a.Cartesian3.ZERO),n=[t,e],o=a.Material.fromType(a.Material.PolylineDashType,{color:a.Color.clone(Ke),gapColor:a.Color.clone(pi),dashLength:14,dashPattern:255}),s=this.lineCollection.add({show:!1,positions:n,width:1.5,material:o}),r=this.pointCollection.add({show:!1,position:e,pixelSize:7,color:a.Color.clone(Re),outlineColor:a.Color.clone(ke),outlineWidth:1.5,disableDepthTestDistance:Number.POSITIVE_INFINITY});return{line:s,point:r,top:t,ground:e,positions:n,cartographic:new a.Cartographic,lineMaterial:o}}updateSlot(t,e){a.Cartesian3.clone(e.position,t.top);const n=a.Cartographic.fromCartesian(e.position,void 0,t.cartographic);if(!n){t.line.show=!1,t.point.show=!1;return}a.Cartesian3.fromRadians(n.longitude,n.latitude,0,void 0,t.ground),t.line.positions=t.positions,t.point.position=t.ground,t.line.id=e.id,t.point.id=e.id;const o=Math.max(0,Math.min(1,e.visualScale));vi(t.lineMaterial,o*Ke.alpha),t.point.color=qe(Re,o*Re.alpha,t.point.color),t.point.outlineColor=qe(ke,o*ke.alpha,t.point.outlineColor),t.line.show=o>.001,t.point.show=o>.001}}function vi(i,t){const e=i.uniforms;!e||!e.color||(e.color.alpha=t)}function qe(i,t,e){const n=e??new a.Color;return n.red=i.red,n.green=i.green,n.blue=i.blue,n.alpha=t,n}const O=de,re=O.Buffer,ae=O.BufferUsage,yi=O.VertexArray,$e=O.IndexDatatype,wi=O.ShaderProgram,Mi=O.DrawCommand,Si=O.RenderState,Ii=O.Pass,xi=O.PrimitiveType,ee=O.ComponentDatatype,Ti=O.Texture,bi=O.Sampler,Pi={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Ci={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT4:16};class Ri{constructor(t,e,n=8e3){l(this,"url");l(this,"scene");l(this,"capacity");l(this,"center",new a.Cartesian3);l(this,"instMatrices",new Float32Array(0));l(this,"count",0);l(this,"dirty",!1);l(this,"ready",!1);l(this,"show",!0);l(this,"groups",[]);l(this,"segments",[]);l(this,"built",!1);l(this,"_mm");l(this,"_cols",[]);this.scene=t,this.url=e,this.capacity=n,this.instMatrices=new Float32Array(n*16),this.load(e)}setInstances(t,e,n){this.count=Math.min(e,this.capacity),this.instMatrices.set(t.subarray(0,this.count*16)),a.Cartesian3.clone(n,this.center),this.dirty=!0}setVisible(t){this.show=t}async load(t){try{const n=await(await fetch(t)).json(),o=(n.buffers??[]).map(s=>Li(s.uri));this.groups=Oi(n,o),this.ready=this.groups.length>0}catch(e){console.warn("[multi-target] InstancedGltfBatch load failed",t,e)}}update(t){if(!this.show||!this.ready||this.count===0)return;const e=t.context;this.built||this.build(e),a.Matrix4.fromTranslation(this.center,this._mm??(this._mm=new a.Matrix4));for(const n of this.segments){if(this.dirty)for(let o=0;o<4;o++)n.instBufs[o].copyFromArrayView(this.columnView(o),0);a.Matrix4.clone(this._mm,n.cmd.modelMatrix),n.cmd.instanceCount=this.count,t.commandList.push(n.cmd)}this.dirty=!1}columnView(t){this._cols[t]||(this._cols[t]=new Float32Array(this.capacity*4));const e=this._cols[t];for(let n=0;n<this.count;n++)e[n*4+0]=this.instMatrices[n*16+t*4+0],e[n*4+1]=this.instMatrices[n*16+t*4+1],e[n*4+2]=this.instMatrices[n*16+t*4+2],e[n*4+3]=this.instMatrices[n*16+t*4+3];return e}build(t){this.built=!0;for(const e of this.groups){const n=re.createVertexBuffer({context:t,typedArray:new Float32Array(e.positions),usage:ae.STATIC_DRAW}),o=re.createVertexBuffer({context:t,typedArray:new Float32Array(e.normals),usage:ae.STATIC_DRAW}),s=re.createVertexBuffer({context:t,typedArray:new Float32Array(e.uvs),usage:ae.STATIC_DRAW}),r=e.vcount>65535?new Uint32Array(e.indices):new Uint16Array(e.indices),c=re.createIndexBuffer({context:t,typedArray:r,usage:ae.STATIC_DRAW,indexDatatype:e.vcount>65535?$e.UNSIGNED_INT:$e.UNSIGNED_SHORT}),d=[0,1,2,3].map(()=>re.createVertexBuffer({context:t,typedArray:new Float32Array(this.capacity*4),usage:ae.DYNAMIC_DRAW})),h=new yi({context:t,attributes:[{index:0,vertexBuffer:n,componentsPerAttribute:3,componentDatatype:ee.FLOAT},{index:1,vertexBuffer:o,componentsPerAttribute:3,componentDatatype:ee.FLOAT},{index:2,vertexBuffer:s,componentsPerAttribute:2,componentDatatype:ee.FLOAT},{index:3,vertexBuffer:d[0],componentsPerAttribute:4,componentDatatype:ee.FLOAT,instanceDivisor:1},{index:4,vertexBuffer:d[1],componentsPerAttribute:4,componentDatatype:ee.FLOAT,instanceDivisor:1},{index:5,vertexBuffer:d[2],componentsPerAttribute:4,componentDatatype:ee.FLOAT,instanceDivisor:1},{index:6,vertexBuffer:d[3],componentsPerAttribute:4,componentDatatype:ee.FLOAT,instanceDivisor:1}],indexBuffer:c}),m=wi.fromCache({context:t,vertexShaderSource:ki,fragmentShaderSource:Ai,attributeLocations:{a_pos:0,a_nrm:1,a_uv:2,a_m0:3,a_m1:4,a_m2:5,a_m3:6}}),f=this.makeTexture(t,e.imageUri),v={u_tex:()=>f.value??t.defaultTexture,u_hasTex:()=>f.value?1:0},u=new Mi({primitiveType:xi.TRIANGLES,vertexArray:h,shaderProgram:m,renderState:Si.fromCache({depthTest:{enabled:!0},depthMask:!0,cull:{enabled:!1}}),pass:Ii.OPAQUE,modelMatrix:a.Matrix4.clone(a.Matrix4.IDENTITY,new a.Matrix4),uniformMap:v,count:e.indices.length,instanceCount:this.count,cull:!1,boundingVolume:new a.BoundingSphere(a.Cartesian3.ZERO,1e8),owner:this});this.segments.push({cmd:u,instBufs:d,va:h,sp:m,texture:f})}}makeTexture(t,e){const n={value:void 0};if(!e)return n;const o=new Image;return o.onload=()=>{var s,r;n.value=new Ti({context:t,source:o,flipY:!1,sampler:new bi({})}),(r=(s=this.scene).requestRender)==null||r.call(s)},o.src=e,n}isDestroyed(){return!1}destroy(){for(const t of this.segments)t.sp&&t.sp.destroy(),t.va&&t.va.destroy(),t.texture&&t.texture.value&&t.texture.value.destroy();return this.segments=[],!0}}const ki=`
2
+ in vec3 a_pos;
3
+ in vec3 a_nrm;
4
+ in vec2 a_uv;
5
+ in vec4 a_m0;
6
+ in vec4 a_m1;
7
+ in vec4 a_m2;
8
+ in vec4 a_m3;
9
+ out vec2 v_uv;
10
+ out vec3 v_nrm;
11
+ void main() {
12
+ mat4 inst = mat4(a_m0, a_m1, a_m2, a_m3);
13
+ vec4 worldRTC = inst * vec4(a_pos, 1.0);
14
+ v_uv = a_uv;
15
+ v_nrm = normalize(mat3(a_m0.xyz, a_m1.xyz, a_m2.xyz) * a_nrm);
16
+ gl_Position = czm_modelViewProjection * worldRTC;
17
+ czm_vertexLogDepth();
18
+ }
19
+ `,Ai=`
20
+ in vec2 v_uv;
21
+ in vec3 v_nrm;
22
+ uniform sampler2D u_tex;
23
+ uniform float u_hasTex;
24
+ void main() {
25
+ vec3 base = u_hasTex > 0.5 ? texture(u_tex, v_uv).rgb : vec3(0.7);
26
+ float lambert = 0.45 + 0.55 * max(0.0, dot(v_nrm, czm_sunDirectionWC));
27
+ out_FragColor = vec4(base * lambert, 1.0);
28
+ }
29
+ `;function Li(i){const t=i.split(",")[1]??"",e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}function fe(i,t,e){const n=i.accessors[e],o=i.bufferViews[n.bufferView],s=t[o.buffer],r=Ci[n.type],c=Pi[n.componentType],d=c.BYTES_PER_ELEMENT,h=(o.byteOffset??0)+(n.byteOffset??0),m=o.byteStride,f=new Float32Array(n.count*r);if(!m||m===r*d){const v=new c(s,h,n.count*r);for(let u=0;u<f.length;u++)f[u]=v[u]}else{const v=new DataView(s);for(let u=0;u<n.count;u++)for(let p=0;p<r;p++){const g=h+u*m+p*d;f[u*r+p]=Ei(v,g,n.componentType)}}return f}function Ei(i,t,e){switch(e){case 5126:return i.getFloat32(t,!0);case 5125:return i.getUint32(t,!0);case 5123:return i.getUint16(t,!0);case 5122:return i.getInt16(t,!0);case 5121:return i.getUint8(t);default:return i.getInt8(t)}}function Hi(i){if(i.matrix)return a.Matrix4.fromColumnMajorArray(i.matrix,new a.Matrix4);const t=i.translation?new a.Cartesian3(i.translation[0],i.translation[1],i.translation[2]):a.Cartesian3.ZERO,e=i.rotation?new de.Quaternion(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]):de.Quaternion.IDENTITY,n=i.scale?new a.Cartesian3(i.scale[0],i.scale[1],i.scale[2]):new a.Cartesian3(1,1,1);return a.Matrix4.fromTranslationQuaternionRotationScale(t,e,n,new a.Matrix4)}function Di(i,t){var s,r,c,d,h,m,f;if(t==null)return;const e=(s=i.materials)==null?void 0:s[t],n=(c=(r=e==null?void 0:e.pbrMetallicRoughness)==null?void 0:r.baseColorTexture)==null?void 0:c.index;if(n==null)return;const o=(h=(d=i.textures)==null?void 0:d[n])==null?void 0:h.source;if(o!=null)return(f=(m=i.images)==null?void 0:m[o])==null?void 0:f.uri}function _i(){const i=O.Axis,t=a.Matrix4.clone(i.Y_UP_TO_Z_UP,new a.Matrix4);return a.Matrix4.multiplyTransformation(t,i.Z_UP_TO_X_UP,t)}function Oi(i,t){var c,d;const e=new Map,n=((d=(c=i.scenes)==null?void 0:c[i.scene??0])==null?void 0:d.nodes)??[],o=_i(),s=new a.Cartesian3,r=(h,m)=>{const f=i.nodes[h],v=a.Matrix4.multiply(m,Hi(f),new a.Matrix4);if(f.mesh!=null)for(const u of i.meshes[f.mesh].primitives){const p=fe(i,t,u.attributes.POSITION),g=u.attributes.NORMAL!=null?fe(i,t,u.attributes.NORMAL):null,y=u.attributes.TEXCOORD_0!=null?fe(i,t,u.attributes.TEXCOORD_0):null,w=u.indices!=null?fe(i,t,u.indices):null,M=Di(i,u.material)??"__none__";let S=e.get(M);S||(S={positions:[],normals:[],uvs:[],indices:[],vcount:0,imageUri:M==="__none__"?void 0:M},e.set(M,S));const b=S.vcount,k=p.length/3;for(let I=0;I<k;I++)s.x=p[I*3],s.y=p[I*3+1],s.z=p[I*3+2],a.Matrix4.multiplyByPoint(v,s,s),S.positions.push(s.x,s.y,s.z),g?(s.x=g[I*3],s.y=g[I*3+1],s.z=g[I*3+2],a.Matrix4.multiplyByPointAsVector(v,s,s),a.Cartesian3.normalize(s,s),S.normals.push(s.x,s.y,s.z)):S.normals.push(0,0,1),y?S.uvs.push(y[I*2],y[I*2+1]):S.uvs.push(0,0);if(w)for(let I=0;I<w.length;I++)S.indices.push(b+w[I]);else for(let I=0;I<k;I++)S.indices.push(b+I);S.vcount+=k}for(const u of f.children??[])r(u,v)};for(const h of n)r(h,o);return Array.from(e.values())}const Bi=400,Ae=8e3;class je{constructor(t,e){l(this,"renderIds",new Set);l(this,"states",new Map);l(this,"batches",new Map);l(this,"scratch",new Map);l(this,"center",new a.Cartesian3);this.scene=t,this.fadeMs=e}activeTargetIds(){return Array.from(this.renderIds)}setCandidates(t){const e=new Set(t.map(n=>n.id));this.renderIds.clear();for(const n of t)this.renderIds.add(n.id);for(const n of t){let o=this.states.get(n.id);o||(o=Ni(n),this.states.set(n.id,o)),this.applyCandidate(o,n)}for(const[,n]of this.states)e.has(n.id)||(n.active=!1);return this.activeTargetIds()}getTargetFrame(t,e=new a.Cartesian3){const n=this.states.get(t);if(!(!n||n.visualScale<=.001))return{position:a.Cartesian3.clone(n.currentPosition,e),heading:n.currentHeading}}update(t){const e=Vi(t,this.fadeMs);for(const[o,s]of Array.from(this.states))zi(s,t),s.visualScale=Wi(s.visualScale,s.active?1:0,e),s.modelMatrix=Je(s,s.modelStyle,s.modelMatrix),s.scaledMatrix=a.Matrix4.multiplyByUniformScale(s.modelMatrix,Math.max(.001,s.visualScale),s.scaledMatrix),!s.active&&s.visualScale<=.001&&(this.states.delete(o),this.renderIds.delete(o));a.Cartesian3.clone(this.scene.camera.positionWC,this.center);const n=new Map;for(const o of this.states.values()){if(o.visualScale<=.001)continue;const s=o.url;let r=this.batches.get(s);r||(r=new Ri(this.scene,s,Ae),this.batches.set(s,r),this.scene.primitives.add(r));let c=this.scratch.get(s);c||(c=new Float32Array(Ae*16),this.scratch.set(s,c));const d=n.get(s)??0;if(d>=Ae)continue;const h=o.scaledMatrix,m=d*16;for(let f=0;f<16;f++)c[m+f]=h[f];c[m+12]=h[12]-this.center.x,c[m+13]=h[13]-this.center.y,c[m+14]=h[14]-this.center.z,n.set(s,d+1)}for(const[o,s]of this.batches){const r=this.scratch.get(o);s.setInstances(r??Fi,n.get(o)??0,this.center)}}clear(){this.renderIds.clear();for(const t of this.states.values())t.active=!1}suspend(){this.renderIds.clear(),this.states.clear();for(const t of this.batches.values())this.scene.primitives.remove(t);this.batches.clear(),this.scratch.clear()}destroy(){this.suspend()}applyCandidate(t,e){t.active=!0,t.url=e.url,t.modelKey=e.modelKey,t.modelStyle=e.modelStyle,t.position=e.position,t.heading=e.heading,t.smoothMove=e.smoothMove,t.moveDurationMs=e.moveDurationMs,e.smoothMove?(a.Cartesian3.clone(t.currentPosition,t.startPosition),a.Cartesian3.clone(e.position,t.targetPosition),t.startHeading=t.currentHeading,t.targetHeading=e.heading,t.moveElapsedSec=0,t.moveDurationSec=Math.max(16,e.moveDurationMs||Bi)/1e3):(a.Cartesian3.clone(e.position,t.currentPosition),a.Cartesian3.clone(e.position,t.startPosition),a.Cartesian3.clone(e.position,t.targetPosition),t.currentHeading=e.heading,t.startHeading=e.heading,t.targetHeading=e.heading,t.moveElapsedSec=0,t.moveDurationSec=0)}}const Fi=new Float32Array(0);function Ni(i){const t=Je({...i,currentPosition:i.position,currentHeading:i.heading},i.modelStyle,a.Matrix4.clone(a.Matrix4.IDENTITY));return{...i,active:!0,currentPosition:a.Cartesian3.clone(i.position),startPosition:a.Cartesian3.clone(i.position),targetPosition:a.Cartesian3.clone(i.position),currentHeading:i.heading,startHeading:i.heading,targetHeading:i.heading,moveElapsedSec:0,moveDurationSec:0,visualScale:0,modelMatrix:t,scaledMatrix:a.Matrix4.clone(t)}}function zi(i,t){if(i.moveDurationSec<=0)return;i.moveElapsedSec+=t;const e=Ui(Math.min(1,i.moveElapsedSec/Math.max(.001,i.moveDurationSec)));a.Cartesian3.lerp(i.startPosition,i.targetPosition,e,i.currentPosition),i.currentHeading=Xi(i.startHeading,i.targetHeading,e),e>=1&&(a.Cartesian3.clone(i.targetPosition,i.currentPosition),i.currentHeading=i.targetHeading,i.moveElapsedSec=0,i.moveDurationSec=0)}function Je(i,t,e){const n=new a.HeadingPitchRoll(a.Math.toRadians(i.currentHeading+(t.headingOffset??0)),a.Math.toRadians(t.pitchOffset??0),a.Math.toRadians(t.rollOffset??0));return a.Transforms.headingPitchRollToFixedFrame(i.currentPosition,n,void 0,void 0,e),a.Matrix4.multiplyByUniformScale(e,t.scale??1,e)}function Vi(i,t){return t<=0?1:Math.max(0,i*1e3/t)}function Wi(i,t,e){return i<t?Math.min(t,i+e):i>t?Math.max(t,i-e):i}function Ui(i){return i<.5?4*i*i*i:1-Math.pow(-2*i+2,3)/2}function Xi(i,t,e){const n=((t-i)%360+540)%360-180;return i+n*e}const Gi=1,Zi=2,Yi=16,Ki=32,qi=64,Qe=400,$i=.75;class ji{constructor(t,e,n,o,s,r){l(this,"lowModels");l(this,"airReferences");l(this,"renderIds",new Set);l(this,"states",new Map);l(this,"retiring",[]);l(this,"scene");l(this,"animationKeepAliveElapsedSec",0);l(this,"lastLowRenderCount",0);l(this,"lastHighRenderCount",0);this.viewer=t,this.styles=e,this.lowCapacity=n,this.highCapacity=o,this.fadeMs=r,this.scene=t.scene,this.lowModels=new je(this.scene,r),this.airReferences=new gi(this.scene)}activeTargetIds(){return[...this.lowModels.activeTargetIds(),...Array.from(this.renderIds)]}renderStats(){return{low:this.lastLowRenderCount,high:this.lastHighRenderCount}}getTargetFrame(t,e=new a.Cartesian3){const n=this.states.get(t);return n!=null&&n.active&&n.visualScale>.001?{position:a.Cartesian3.clone(n.currentPosition,e),heading:n.currentHeading}:this.lowModels.getTargetFrame(t,e)}setPacket(t){const e=Ji(t,this.styles,this.viewer.scene.camera.positionCartographic.height),n=e.filter(d=>d.lodKind===1).slice(0,this.lowCapacity),o=e.filter(d=>d.lodKind===2).slice(0,this.highCapacity);this.lastLowRenderCount=n.length,this.lastHighRenderCount=o.length,this.lowModels.setCandidates(n);const s=o,r=new Set(s.map(d=>d.id));for(const d of Array.from(this.renderIds))r.has(d)||this.renderIds.delete(d);for(const d of s)this.renderIds.add(d.id);const c=new Map(s.map(d=>[d.id,d]));for(const d of this.renderIds){const h=c.get(d);if(!h)continue;let m=this.states.get(d);m||(m=Qi(h),this.states.set(d,m)),this.applyCandidate(m,h)}for(const[d,h]of Array.from(this.states))this.renderIds.has(d)||(h.active=!1);return this.activeTargetIds()}update(t){this.lowModels.update(t),this.animationKeepAliveElapsedSec+=t;const e=this.animationKeepAliveElapsedSec>=$i;let n=!1;const o=tn(t,this.fadeMs);for(const[s,r]of Array.from(this.states))en(r,t),r.visualScale=et(r.visualScale,r.active?1:0,o),r.modelMatrix=Le(r.currentPosition,r.currentHeading,r.modelStyle,r.modelMatrix),r.model&&(r.model.modelMatrix=le(r.modelMatrix,r.visualScale,r.transitionMatrix),r.model.show=r.visualScale>.001,r.modelStyle.runAnimations&&r.active&&(n=!0,e&&this.ensureModelAnimations(r.model,r.modelStyle))),!r.active&&r.visualScale<=.001&&this.removeState(s,r);this.updateAirReferences();for(let s=this.retiring.length-1;s>=0;s--){const r=this.retiring[s];r.visualScale=et(r.visualScale,0,o),r.model.modelMatrix=le(r.modelMatrix,r.visualScale,r.transitionMatrix),r.model.show=r.visualScale>.001,r.visualScale<=.001&&(this.scene.primitives.remove(r.model),this.retiring.splice(s,1))}n&&this.ensureAnimationClock(),e&&(this.animationKeepAliveElapsedSec=0)}clear(){this.lowModels.clear(),this.airReferences.clear(),this.lastLowRenderCount=0,this.lastHighRenderCount=0,this.renderIds.clear();for(const t of this.states.values())t.active=!1}suspend(){if(this.lowModels.suspend(),this.airReferences.clear(),this.lastLowRenderCount=0,this.lastHighRenderCount=0,!(this.renderIds.size===0&&this.states.size===0&&this.retiring.length===0)){this.renderIds.clear();for(const t of this.states.values())t.model&&this.scene.primitives.remove(t.model),t.model=null,t.loading=!1,t.loadToken++;this.states.clear();for(const t of this.retiring)this.scene.primitives.remove(t.model);this.retiring.length=0}}destroy(){this.lowModels.destroy(),this.airReferences.destroy();for(const t of this.states.values())t.model&&this.scene.primitives.remove(t.model),t.model=null,t.loading=!1,t.loadToken++;this.states.clear(),this.renderIds.clear();for(const t of this.retiring)this.scene.primitives.remove(t.model);this.retiring.length=0}applyCandidate(t,e){const n=sn(t,e),o=t.url!==e.url||t.lodKind!==e.lodKind;if(o&&(this.retireStateModel(t),t.url=e.url,t.modelKey=e.modelKey,t.lodKind=e.lodKind,t.targetDomain=e.targetDomain,t.modelStyle=e.modelStyle,t.visualScale=0),t.active=!0,t.url=e.url,t.modelKey=e.modelKey,t.modelStyle=e.modelStyle,t.targetDomain=e.targetDomain,t.category=e.category,t.position=e.position,t.heading=e.heading,t.smoothMove=e.smoothMove,t.moveDurationMs=e.moveDurationMs,t.predictMove=e.predictMove,(e.smoothMove||e.predictMove)&&t.model&&!o&&n?(a.Cartesian3.clone(t.currentPosition,t.startPosition),a.Cartesian3.clone(e.position,t.targetPosition),t.startHeading=t.currentHeading,t.targetHeading=e.heading,t.moveElapsedSec=0,t.moveDurationSec=Math.max(16,e.moveDurationMs||Qe)/1e3):(a.Cartesian3.clone(e.position,t.currentPosition),a.Cartesian3.clone(e.position,t.startPosition),a.Cartesian3.clone(e.position,t.targetPosition),t.currentHeading=e.heading,t.startHeading=e.heading,t.targetHeading=e.heading,t.moveElapsedSec=0,t.moveDurationSec=0),t.modelMatrix=Le(t.currentPosition,t.currentHeading,t.modelStyle,t.modelMatrix),t.model){t.model.id=t.id,t.model.modelMatrix=le(t.modelMatrix,t.visualScale,t.transitionMatrix),t.model.show=!0;return}t.loading||this.loadModel(t)}loadModel(t){const e=++t.loadToken,n=t.url,o=t.id,s=t.lodKind;t.loading=!0,a.Model.fromGltfAsync({url:n,scene:this.scene,modelMatrix:le(t.modelMatrix,t.visualScale,t.transitionMatrix),scale:t.modelStyle.scale??1,allowPicking:!0,id:o}).then(r=>{if(t.loadToken!==e||t.url!==n||t.id!==o||t.lodKind!==s||!t.active){this.scene.primitives.remove(r);return}t.model=this.scene.primitives.add(r),t.model.id=t.id,t.model.show=!0,t.model.modelMatrix=le(t.modelMatrix,t.visualScale,t.transitionMatrix),this.ensureModelAnimations(t.model,t.modelStyle),this.scene.requestRender()}).catch(r=>{console.warn("[multi-target] model load failed",n,r)}).finally(()=>{t.loadToken===e&&(t.loading=!1)})}removeState(t,e){this.retireStateModel(e),e.loadToken++,e.loading=!1,this.states.delete(t)}retireStateModel(t){t.model&&(this.retiring.push({model:t.model,modelMatrix:a.Matrix4.clone(t.modelMatrix),transitionMatrix:a.Matrix4.clone(t.transitionMatrix),visualScale:t.visualScale}),t.model=null)}ensureAnimationClock(){this.viewer.clock&&(this.viewer.clock.shouldAnimate=!0)}ensureModelAnimations(t,e){if(!e.runAnimations)return;const n=t;if(!n.__multiTargetAnimationUnavailable&&(this.ensureAnimationClock(),!nt(t)&&!Ee(t,e))){if(n.ready===!0){n.__multiTargetAnimationStarted||(n.__multiTargetAnimationUnavailable=!0);return}if(!n.__multiTargetAnimationReadyHooked){if(n.readyEvent&&typeof n.readyEvent.addEventListener=="function"){n.__multiTargetAnimationReadyHooked=!0;const o=n.readyEvent.addEventListener(()=>{n.__multiTargetAnimationReadyHooked=!1,Ee(t,e),typeof o=="function"&&o()});return}n.readyPromise&&typeof n.readyPromise.then=="function"&&(n.__multiTargetAnimationReadyHooked=!0,n.readyPromise.then(()=>{n.__multiTargetAnimationReadyHooked=!1,Ee(t,e)}).catch(()=>{n.__multiTargetAnimationReadyHooked=!1}))}}}updateAirReferences(){const t=[];for(const e of this.states.values())!e.active||e.targetDomain!=="air"||e.visualScale<=.001||t.push({id:e.id,position:e.currentPosition,visualScale:e.visualScale});this.airReferences.setTargets(t)}}function Ji(i,t,e){const n=[];for(let o=0;o<i.lon.length;o++){const s=i.flags[o],r=s>>Zi&3;if(r===0||s&Gi||!(s&qi))continue;const c=i.ids[o]??"";if(!c)continue;const d=i.category[o],h=t[d],m=an(h,r);if(!m)continue;const f=m.url,v=(s&Ki)!==0;n.push({id:c,url:f,category:d,modelKey:rn(f),lodKind:r,targetDomain:h==null?void 0:h.targetDomain,modelStyle:m,position:a.Cartesian3.fromDegrees(i.lon[o],i.lat[o],i.height[o]),heading:i.heading[o]||0,smoothMove:(s&Yi)!==0,moveDurationMs:i.moveDurationMs[o]||Qe,predictMove:v})}return n}function Qi(i){const t=Le(i.position,i.heading,void 0,a.Matrix4.clone(a.Matrix4.IDENTITY));return{...i,model:null,loading:!1,loadToken:0,active:!0,visualScale:0,currentPosition:a.Cartesian3.clone(i.position),startPosition:a.Cartesian3.clone(i.position),targetPosition:a.Cartesian3.clone(i.position),currentHeading:i.heading,startHeading:i.heading,targetHeading:i.heading,moveElapsedSec:0,moveDurationSec:0,modelMatrix:t,transitionMatrix:a.Matrix4.clone(a.Matrix4.IDENTITY)}}function en(i,t){if(i.moveDurationSec<=0)return;i.moveElapsedSec+=t;const e=Math.min(1,i.moveElapsedSec/Math.max(.001,i.moveDurationSec)),n=i.predictMove?e:nn(e);a.Cartesian3.lerp(i.startPosition,i.targetPosition,n,i.currentPosition),i.currentHeading=on(i.startHeading,i.targetHeading,n),n>=1&&(a.Cartesian3.clone(i.targetPosition,i.currentPosition),i.currentHeading=i.targetHeading,i.moveElapsedSec=0,i.moveDurationSec=0)}function tn(i,t){return t<=0?1:Math.max(0,i*1e3/t)}function et(i,t,e){return i<t?Math.min(t,i+e):i>t?Math.max(t,i-e):i}function Le(i,t,e,n){const o=new a.HeadingPitchRoll(a.Math.toRadians(t+((e==null?void 0:e.headingOffset)??0)),a.Math.toRadians((e==null?void 0:e.pitchOffset)??0),a.Math.toRadians((e==null?void 0:e.rollOffset)??0));return a.Transforms.headingPitchRollToFixedFrame(i,o,void 0,void 0,n)}function le(i,t,e){return a.Matrix4.multiplyByUniformScale(i,Math.max(.001,t),e)}function nn(i){return i<.5?4*i*i*i:1-Math.pow(-2*i+2,3)/2}function on(i,t,e){const n=tt(i,t);return i+n*e}function tt(i,t){return((t-i)%360+540)%360-180}function sn(i,t){return a.Cartesian3.distanceSquared(i.position,t.position)>1e-4||Math.abs(tt(i.heading,t.heading))>.001}function rn(i){const t=i.split(/[?#]/,1)[0]??i;return t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1).toLowerCase()}function an(i,t){if(!i)return;const e=t===1?i.lowModel:i.highModel;if(e)return it(e,t);const n=t===1?i.lowModelUrl:i.highModelUrl;if(n)return it({url:n,scale:i.scale,headingOffset:i.modelHeadingOffset,pitchOffset:i.modelPitchOffset,rollOffset:i.modelRollOffset},t)}function it(i,t){return{...i,runAnimations:i.runAnimations??t===2,animationLoop:i.animationLoop??"repeat",animationMultiplier:i.animationMultiplier??1}}function Ee(i,t){if(!t.runAnimations)return!1;const e=i,n=e.activeAnimations;if(!n||typeof n.addAll!="function")return!1;try{const o=n.addAll({loop:ln(t.animationLoop),multiplier:t.animationMultiplier??1});return(Array.isArray(o)?o.length>0:!!o)||nt(i)?(e.__multiTargetAnimationStarted=!0,!0):!1}catch{return!1}}function nt(i){const t=i.activeAnimations;return!!t&&typeof t.length=="number"&&t.length>0}function ln(i){return i==="none"?a.ModelAnimationLoop.NONE:i==="mirroredRepeat"?a.ModelAnimationLoop.MIRRORED_REPEAT:a.ModelAnimationLoop.REPEAT}const cn=1.75,q=36;function ot(i,t,e=!1){const n=Math.max(8,t+(e?4:2))*2,o=Math.min(n,64);let s=o*1.35,r=o*.9;return i.startsWith("ship")?(s=o*1.15,r=o*1.45):i.startsWith("uav")?(s=o*1.35,r=o*1.35):i.startsWith("person")&&(s=o*.9,r=o*1.2),{width:s,height:r,maxDimension:Math.max(s,r)}}function st(i,t,e=!1){const n=ot(i,t,e);return Math.max(q,n.maxDimension*cn)}const hn=[{type:"ship",iconPath:"/icons/target-ship-mask.png",defaultColor:"#25e65c"},{type:"uav",iconPath:"/icons/target-uav-mask.png",defaultColor:"#22d2f2"},{type:"person",iconPath:"/icons/target-person-mask.png",defaultColor:"#ffdc40"},{type:"car",iconPath:"/icons/target-car-mask.png",defaultColor:"#ff9a2a"}],He=400,dn=180,rt=100,at=1e3,un="target-glow-circle",lt=3.6,fn=.34,mn=.22,pn=64,U={enabled:!0,maxCount:200,maxCameraHeight:5e3,maxDistance:void 0,fields:[{key:"id",source:"standard"}],byType:void 0,resolve:void 0,backgroundColor:"#0000008c",textColor:"#ffffff",fontSize:12,fontFamily:"sans-serif",backgroundRadius:6,overlapThreshold:.35,occlusionGraceMs:300,offsetX:18,offsetY:24,connectorColor:"#eafcffcc",connectorWidth:1.5,connectorStemLength:50,showFieldLabels:!0};let gn=0;class vn{constructor(t,e,n={}){l(this,"glowCollection");l(this,"collection");l(this,"labelCollection");l(this,"pool",[]);l(this,"glowPool",[]);l(this,"labelPool",[]);l(this,"typeStyles");l(this,"labelConfig");l(this,"labelTextResolver");l(this,"imageIds");l(this,"imageUrls");l(this,"processedImages");l(this,"glowImage");l(this,"labelImageCache",new Map);l(this,"glowSourceIndexes",[]);l(this,"labelSourceIndexes",[]);l(this,"labelIds",[]);l(this,"labelSmoothStarts",[]);l(this,"labelSmoothTargets",[]);l(this,"labelSmoothElapsedSec",[]);l(this,"labelSmoothDurationSec",[]);l(this,"labelScales",[]);l(this,"labelTargetScales",[]);l(this,"labelPositionsById",new Map);l(this,"labelScalesById",new Map);l(this,"labelLastClearVisibleAt",new Map);l(this,"labelVisibleIds",new Set);l(this,"poolCategories",[]);l(this,"poolIds",[]);l(this,"poolHeadings",[]);l(this,"poolMerged",[]);l(this,"colorCache",new Map);l(this,"glowColorCache",new Map);l(this,"smoothStarts",[]);l(this,"smoothTargets",[]);l(this,"smoothElapsedSec",[]);l(this,"smoothDurationSec",[]);l(this,"baseWidths",[]);l(this,"baseHeights",[]);l(this,"pointScales",new Map);l(this,"modelTargetIds",new Set);l(this,"modelHandoffEnabled",!1);l(this,"anchorPositionResolver",null);l(this,"anchorPositionScratch",new a.Cartesian3);l(this,"directionalExternal",!1);l(this,"targetVisible",!0);l(this,"visibleCount",0);l(this,"glowActiveCount",0);l(this,"labelActiveCount",0);l(this,"glowPhase",0);l(this,"labelRtcRef",new a.Cartesian3);l(this,"labelRtcScratch",new a.Cartesian3);var o;this.scene=t,this.typeStyles=(o=n.targetTypes)!=null&&o.length?n.targetTypes:hn,this.labelConfig=ut(n.label),this.labelTextResolver=n.labelTextResolver??(s=>kn(s,this.labelConfig)),this.imageIds=this.typeStyles.map((s,r)=>`target-${r}-${s.type}`),this.imageUrls=this.typeStyles.map(s=>s.iconPath),this.processedImages=[...this.imageUrls],this.glowImage=Hn(),this.glowCollection=this.scene.primitives.add(new a.BillboardCollection({scene:t})),this.collection=this.scene.primitives.add(new a.BillboardCollection({scene:t})),this.labelCollection=this.scene.primitives.add(new a.BillboardCollection({scene:t})),this.glowCollection.show=!0,this.collection.show=!0,this.labelCollection.show=!0,this.preprocessImages(),this.ensureLabelPool(Math.min(this.labelConfig.maxCount,rt))}setPacket(t){var d;const e=t.lon.length;this.ensurePool(e),this.ensureGlowPool(),this.syncLabelRtcReference();let n=0,o=0;const s=new Set,r=this.labelVisibleIds,c=this.selectLabelInfos(t);this.ensureLabelPool(c.size);for(let h=0;h<e;h++){const m=this.pool[h],f=(t.flags[h]&1)===1;this.poolMerged[h]=f;const v=ct(t.category[h]??0,this.imageIds.length),u=yn(t.color[h],f,this.colorCache),p=ot(((d=this.typeStyles[v])==null?void 0:d.type)??"",t.size[h],f),g=this.poolIds[h]===t.ids[h];this.poolCategories[h]!==v&&(m.setImage(this.imageIds[v],this.processedImages[v]),this.poolCategories[h]=v),this.poolIds[h]=t.ids[h];const y=a.Cartesian3.fromDegrees(t.lon[h],t.lat[h],t.height[h]),w=(t.flags[h]&16)!==0&&g&&(m.show||this.directionalExternal);w?(this.smoothStarts[h]=a.Cartesian3.clone(m.position,this.smoothStarts[h]??new a.Cartesian3),this.smoothTargets[h]=y,this.smoothElapsedSec[h]=0,this.smoothDurationSec[h]=Math.max(16,t.moveDurationMs[h]||He)/1e3):(m.position=y,this.smoothStarts[h]=null,this.smoothTargets[h]=null,this.smoothElapsedSec[h]=0,this.smoothDurationSec[h]=0),this.baseWidths[h]=p.width,this.baseHeights[h]=p.height;const M=this.modelHandoffEnabled?this.pointScales.get(t.ids[h])??(this.modelTargetIds.has(t.ids[h])?0:1):1;if(m.width=p.width*Math.max(.001,M),m.height=p.height*Math.max(.001,M),m.rotation=-a.Math.toRadians(t.heading[h]||0),this.poolHeadings[h]=t.heading[h]||0,m.color=u,m.id=t.ids[h],m.show=this.slotVisible(h),t.animation[h]===1&&this.targetVisible&&n<at){const b=this.glowPool[n];b.position=m.position,b.width=p.width*lt,b.height=p.height*lt,b.color=wn(t.animationColor[h]||t.color[h],this.glowColorCache,this.glowPhase),b.show=!0,this.glowSourceIndexes[n]=h,n++}const S=c.get(h);if(S){const b=t.ids[h]??"",k=this.labelPool[o],I=this.labelIds[o]!==b;I&&(k.show=!1,k.scale=0),this.setLabelPosition(o,k,b,m.position,w,t.moveDurationMs[h]),k.width=S.width,k.height=S.height,k.pixelOffset=new a.Cartesian2(-S.anchorX,S.marginY),k.setImage(S.id,S.image),I&&(this.labelScales[o]=b&&r.has(b)?this.labelScalesById.get(b)??1:0),this.labelTargetScales[o]=1,k.scale=this.labelScales[o]||0,this.labelSourceIndexes[o]=h,this.labelIds[o]=b,this.updateLabelPosition(o),k.show=!0,b&&(s.add(b),this.labelScalesById.set(b,this.labelScales[o]??0)),o++}}this.hideUnusedGlows(n),this.hideUnusedLabels(o,s),this.labelVisibleIds=s,this.glowActiveCount=n,this.labelActiveCount=Math.max(this.labelActiveCount,o),this.hideUnused(e)}clear(){this.hideUnused(0)}getTargetFrame(t,e=new a.Cartesian3){for(let n=0;n<this.visibleCount;n++)if(!(this.poolIds[n]!==t||!this.pool[n].show))return{position:a.Cartesian3.clone(this.pool[n].position,e),heading:this.poolHeadings[n]||0}}update(t){this.glowPhase=(this.glowPhase+t*2.8)%(Math.PI*2),this.collection.show=this.targetVisible,this.glowCollection.show=this.targetVisible,this.labelCollection.show=!0,this.syncLabelRtcReference();for(let n=0;n<this.visibleCount;n++){const o=this.smoothStarts[n],s=this.smoothTargets[n];if(!o||!s)continue;this.smoothElapsedSec[n]+=t;const r=Math.max(.001,this.smoothDurationSec[n]||He/1e3),c=An(Math.min(1,this.smoothElapsedSec[n]/r)),d=a.Cartesian3.lerp(o,s,c,new a.Cartesian3);this.pool[n].position=d,c>=1&&(this.pool[n].position=s,this.smoothStarts[n]=null,this.smoothTargets[n]=null)}const e=Ln(t,He);for(let n=0;n<this.visibleCount;n++){const o=this.poolIds[n];if(!o)continue;if(!this.modelHandoffEnabled){this.pool[n].width=this.baseWidths[n]||9,this.pool[n].height=this.baseHeights[n]||9,this.pool[n].show=this.slotVisible(n);continue}const s=this.modelHandoffEnabled&&this.modelTargetIds.has(o)?0:1,r=this.pointScales.get(o)??1,c=ft(r,s,e);this.pointScales.set(o,c),this.pool[n].width=(this.baseWidths[n]||9)*Math.max(.001,c),this.pool[n].height=(this.baseHeights[n]||9)*Math.max(.001,c),this.pool[n].show=this.slotVisible(n)&&c>.001}if(this.glowActiveCount>0){const n=dt(this.glowPhase);for(let o=0;o<this.glowActiveCount;o++){const s=this.glowPool[o],r=this.glowSourceIndexes[o];s.position=this.pool[r].position,s.color=s.color.withAlpha(n)}}for(let n=0;n<this.labelActiveCount;n++)this.updateLabelScale(n,t),this.labelPool[n].show&&this.updateLabelPosition(n);this.trimInactiveLabels()}setPointLayerVisible(t){this.targetVisible=t,this.collection.show=t,this.glowCollection.show=t}setDirectionalHandledExternally(t){this.directionalExternal=t}slotVisible(t){return!(!this.targetVisible||this.directionalExternal&&!this.poolMerged[t])}setModelTargetIds(t,e=!0){this.modelHandoffEnabled=e&&t.length>0,this.modelTargetIds=this.modelHandoffEnabled?new Set(t):new Set,this.modelHandoffEnabled||this.pointScales.clear()}setAnchorPositionResolver(t){this.anchorPositionResolver=t}syncLabelRtcReference(){const t=this.scene.camera.positionWC;this.labelRtcRef.x=Math.floor(t.x/100)*100,this.labelRtcRef.y=Math.floor(t.y/100)*100,this.labelRtcRef.z=Math.floor(t.z/100)*100,a.Matrix4.fromTranslation(this.labelRtcRef,this.labelCollection.modelMatrix)}updateLabelPosition(t){const e=this.labelSourceIndexes[t];if(e<0)return;const n=this.labelIds[t];let o=this.pool[e].position;if(n&&this.anchorPositionResolver){const s=this.anchorPositionResolver(n,this.anchorPositionScratch);s&&(o=s)}this.labelPool[t].position=a.Cartesian3.subtract(o,this.labelRtcRef,this.labelRtcScratch),n&&this.labelPositionsById.set(n,a.Cartesian3.clone(o,this.labelPositionsById.get(n)??new a.Cartesian3))}setLabelOptions(t,e){this.labelConfig=ut(t),e&&(this.labelTextResolver=e),this.applyLabelStyle(),this.ensureLabelPool(Math.min(this.labelConfig.maxCount,rt)),this.scene.requestRender()}get pointLayerVisible(){return this.targetVisible}get heatmapActive(){return!1}destroy(){this.scene.primitives.remove(this.glowCollection),this.scene.primitives.remove(this.collection),this.scene.primitives.remove(this.labelCollection)}ensurePool(t){for(;this.pool.length<t;){const e=this.collection.add({position:a.Cartesian3.ZERO,show:!1,width:9,height:9,color:a.Color.WHITE.withAlpha(.92),rotation:0});e.setImage(this.imageIds[0],this.processedImages[0]),this.pool.push(e),this.poolCategories.push(0),this.poolIds.push(""),this.smoothStarts.push(null),this.smoothTargets.push(null),this.smoothElapsedSec.push(0),this.smoothDurationSec.push(0),this.baseWidths.push(9),this.baseHeights.push(9)}}ensureGlowPool(){for(;this.glowPool.length<at;){const t=this.glowCollection.add({position:a.Cartesian3.ZERO,show:!1,width:20,height:20,color:a.Color.WHITE.withAlpha(.22),rotation:0});t.setImage(un,this.glowImage),this.glowPool.push(t),this.glowSourceIndexes.push(-1)}}ensureLabelPool(t){const e=Math.max(0,Math.min(this.labelConfig.maxCount,Math.ceil(t)));for(;this.labelPool.length<e;){const n=this.labelCollection.add({position:a.Cartesian3.ZERO,show:!1,width:1,height:1,color:a.Color.WHITE,horizontalOrigin:a.HorizontalOrigin.LEFT,verticalOrigin:a.VerticalOrigin.BOTTOM,pixelOffset:a.Cartesian2.ZERO,disableDepthTestDistance:Number.POSITIVE_INFINITY});this.labelPool.push(n),this.labelSourceIndexes.push(-1),this.labelIds.push(""),this.labelSmoothStarts.push(null),this.labelSmoothTargets.push(null),this.labelSmoothElapsedSec.push(0),this.labelSmoothDurationSec.push(0),this.labelScales.push(0),this.labelTargetScales.push(0),n.scale=0}}applyLabelStyle(){this.labelImageCache.clear();for(const t of this.labelPool)t.show=!1,t.width=1,t.height=1,t.scale=0;for(let t=0;t<this.labelPool.length;t++)this.labelScales[t]=0,this.labelTargetScales[t]=0;this.labelScalesById.clear(),this.labelLastClearVisibleAt.clear(),this.labelActiveCount=0}setLabelPosition(t,e,n,o,s,r){const c=n?this.labelPositionsById.get(n):void 0;this.labelSmoothStarts[t]=null,this.labelSmoothTargets[t]=null,this.labelSmoothElapsedSec[t]=0,this.labelSmoothDurationSec[t]=0,n&&this.labelPositionsById.set(n,a.Cartesian3.clone(o,c??new a.Cartesian3))}updateLabelScale(t,e){const n=this.labelPool[t],o=this.labelTargetScales[t]??0,s=this.labelScales[t]??0,r=e*1e3/dn,c=ft(s,o,r);this.labelScales[t]=c;const d=this.labelIds[t];if(d&&this.labelScalesById.set(d,c),n.scale=c,c<=.001&&o<=0){n.show=!1,this.labelSourceIndexes[t]=-1,d&&this.labelScalesById.set(d,0),this.labelIds[t]="",this.labelScales[t]=0,d&&this.labelLastClearVisibleAt.delete(d);return}n.show=!0}trimInactiveLabels(){for(;this.labelActiveCount>0&&!this.labelPool[this.labelActiveCount-1].show;)this.labelActiveCount--}selectLabelInfos(t){var v,u,p;const e=this.scene.camera.positionCartographic;if(!this.labelConfig.enabled||this.labelConfig.maxCount<=0||e.height>this.labelConfig.maxCameraHeight)return new Map;const n=this.labelConfig.maxDistance!=null&&Number.isFinite(this.labelConfig.maxDistance)?this.labelConfig.maxDistance*this.labelConfig.maxDistance:Number.POSITIVE_INFINITY,o=a.Math.toDegrees(e.longitude),s=a.Math.toDegrees(e.latitude),r=En(),c=[],d=this.scene.canvas;for(let g=0;g<t.lon.length;g++){if(!(t.flags[g]&pn))continue;const y=Mn(o,s,e.height,t.lon[g],t.lat[g],t.height[g]);if(y>n)continue;const w=ct(t.category[g]??0,this.typeStyles.length),M=((v=this.typeStyles[w])==null?void 0:v.type)??"",S=this.labelTextResolver({id:t.ids[g]??"",type:M,data:void 0,cameraHeight:e.height,distance:Math.sqrt(y),count:t.count[g]});if(!S)continue;const b=typeof S=="string"||Array.isArray(S)?S:S.text,k=Array.isArray(b)?b.join(`
30
+ `):b;if(!k)continue;const I=typeof S=="object"&&!Array.isArray(S)&&S.style?S.style:void 0,T=I?{...this.labelConfig,...I}:this.labelConfig,N=this.labelImageOf(k,T),A=a.SceneTransforms.wgs84ToWindowCoordinates(this.scene,a.Cartesian3.fromDegrees(t.lon[g],t.lat[g],t.height[g]));if(!A)continue;const H=Sn(A.x,A.y,N.plateWidth,N.plateHeight,T);H.right<0||H.bottom<0||H.left>d.clientWidth||H.top>d.clientHeight||c.push({index:g,id:t.ids[g]??"",distance2:y,info:N,rect:H,type:M})}c.sort((g,y)=>g.distance2-y.distance2);const h=new Map,m=[],f=new Map;for(const g of c){if(h.size>=this.labelConfig.maxCount)break;const y=(p=(u=this.labelConfig.byType)==null?void 0:u[g.type])==null?void 0:p.maxCount;if(y!=null&&(f.get(g.type)??0)>=y)continue;const w=In(g.rect,m,this.labelConfig.overlapThreshold),M=w&&this.isLabelWithinOcclusionGrace(g.id,r);w&&!M||(!w&&g.id&&this.labelLastClearVisibleAt.set(g.id,r),h.set(g.index,{index:g.index,...g.info}),m.push(g.rect),f.set(g.type,(f.get(g.type)??0)+1))}return h}labelImageOf(t,e){const n=e??this.labelConfig,o=Tn(t,n),s=this.labelImageCache.get(o);if(s)return s;const r=bn(t,n),c={id:`nameplate-${gn++}`,image:r.canvas,width:r.width,height:r.height,plateWidth:r.plateWidth,plateHeight:r.plateHeight,anchorX:r.anchorX,marginY:r.marginY};return this.labelImageCache.set(o,c),c}isLabelWithinOcclusionGrace(t,e){if(!t||this.labelConfig.occlusionGraceMs<=0)return!1;const n=this.labelLastClearVisibleAt.get(t);return n!=null&&e-n<=this.labelConfig.occlusionGraceMs}hideUnused(t){for(let e=t;e<this.visibleCount;e++)this.pool[e].show=!1,this.smoothStarts[e]=null,this.smoothTargets[e]=null,this.smoothElapsedSec[e]=0,this.smoothDurationSec[e]=0,this.poolIds[e]="",this.baseWidths[e]=0,this.baseHeights[e]=0;this.visibleCount=t}hideUnusedGlows(t){for(let e=t;e<this.glowActiveCount;e++)this.glowPool[e].show=!1,this.glowSourceIndexes[e]=-1}hideUnusedLabels(t,e){for(let n=t;n<this.labelActiveCount;n++){const o=this.labelIds[n];if(o&&e.has(o)){this.labelPool[n].show=!1,this.labelSourceIndexes[n]=-1,this.labelIds[n]="",this.labelScales[n]=0,this.labelTargetScales[n]=0,this.labelSmoothStarts[n]=null,this.labelSmoothTargets[n]=null,this.labelSmoothElapsedSec[n]=0,this.labelSmoothDurationSec[n]=0;continue}this.labelTargetScales[n]=0,this.labelSourceIndexes[n]=-1,this.labelSmoothStarts[n]=null,this.labelSmoothTargets[n]=null,this.labelSmoothElapsedSec[n]=0,this.labelSmoothDurationSec[n]=0}}preprocessImages(){for(let t=0;t<this.imageUrls.length;t++){const e=new Image;e.decoding="async",e.onload=()=>{const n=Dn(e,"#ffffff");this.processedImages[t]=n;for(let o=0;o<this.pool.length;o++)this.poolCategories[o]===t&&this.pool[o].setImage(this.imageIds[t],n);this.scene.requestRender()},e.src=this.imageUrls[t]}}}function ct(i,t){return i>=0&&i<t?i:0}function yn(i,t,e){const n=(i&16777215)<<1|(t?1:0),o=e.get(n);if(o)return o;const s=ht(i,t?1:.92);return e.set(n,s),s}function wn(i,t,e){const n=dt(e),o=(i&16777215)<<8|Math.round(n*255),s=t.get(o);if(s)return s;const r=ht(i,n);return t.set(o,r),r}function ht(i,t){return a.Color.fromBytes(i>>16&255,i>>8&255,i&255,Math.round(t*255))}function dt(i){return fn+(Math.sin(i)+1)*mn}function Mn(i,t,e,n,o,s){const r=a.Math.toRadians((t+o)*.5),c=(n-i)*111320*Math.cos(r),d=(o-t)*110540,h=s-e;return c*c+d*d+h*h}function Sn(i,t,e,n,o){const s=i+(o.offsetX??0),r=t-(o.offsetY??0)-(o.connectorStemLength??0),c=r-n;return{left:s,top:c,right:s+e,bottom:r,area:e*n}}function In(i,t,e){for(const n of t){const o=Math.max(i.left,n.left),s=Math.min(i.right,n.right);if(s<=o)continue;const r=Math.max(i.top,n.top),c=Math.min(i.bottom,n.bottom);if(c<=r)continue;if((s-o)*(c-r)/Math.max(1,Math.min(i.area,n.area))>=e)return!0}return!1}function ut(i){var t;return Ce({...U,...i??{},fontSize:Math.max(1,(i==null?void 0:i.fontSize)??U.fontSize),backgroundRadius:Math.max(0,(i==null?void 0:i.backgroundRadius)??U.backgroundRadius),overlapThreshold:Math.max(0,Math.min(1,(i==null?void 0:i.overlapThreshold)??U.overlapThreshold)),offsetX:Math.max(0,(i==null?void 0:i.offsetX)??U.offsetX),offsetY:Math.max(0,(i==null?void 0:i.offsetY)??U.offsetY),connectorColor:(i==null?void 0:i.connectorColor)??(i==null?void 0:i.backgroundColor)??U.connectorColor,connectorWidth:Math.max(0,(i==null?void 0:i.connectorWidth)??U.connectorWidth),connectorStemLength:Math.max(0,(i==null?void 0:i.connectorStemLength)??U.connectorStemLength),fields:(t=i==null?void 0:i.fields)!=null&&t.length?i.fields.map(e=>({key:e.key,label:e.label,source:e.source??"standard",fallback:e.fallback,minCameraHeight:e.minCameraHeight,maxCameraHeight:e.maxCameraHeight})):U.fields})}function xn(i){return`${Math.max(1,i.fontSize??12)}px ${i.fontFamily||"sans-serif"}`}function Tn(i,t){return[i,t.backgroundColor??"",t.textColor??"",t.fontSize??12,t.fontFamily??"sans-serif",t.backgroundRadius??0,t.offsetX??0,t.offsetY??0,t.connectorColor??"",t.connectorWidth??0,t.connectorStemLength??0].join("")}function bn(i,t){const n=i.split(/\r?\n/).filter(A=>A.length>0),o=Math.max(1,t.fontSize),s=xn(t),r=Math.ceil(o*1.35),c=Math.ceil(o*.7),d=Math.ceil(o*.45),m=document.createElement("canvas").getContext("2d");let f=1;if(m){m.font=s;for(const A of n)f=Math.max(f,m.measureText(A).width)}else for(const A of n)f=Math.max(f,A.length*o*.6);const v=Math.ceil(f+c*2),u=Math.ceil(n.length*r+d*2),p=Math.ceil(t.connectorWidth*.5)+1,g=p+t.offsetX,y=Math.ceil(g+v),w=Math.ceil(t.connectorStemLength+t.offsetY+u),M=y+2*2,S=w+2*2,b=p+2,k=Math.min(2,Math.max(1,window.devicePixelRatio||1)),I=document.createElement("canvas");I.width=Math.ceil(M*k),I.height=Math.ceil(S*k),I.style.width=`${M}px`,I.style.height=`${S}px`;const T=I.getContext("2d");if(!T)return{canvas:I,width:M,height:S,plateWidth:v,plateHeight:u,anchorX:b,marginY:2};T.scale(k,k),T.clearRect(0,0,M,S),T.translate(2,2);const N=Math.min(t.backgroundRadius,u*.5,v*.5);if(t.connectorWidth>0){const A=w-t.connectorStemLength,H=Cn(g,u,N),_=Math.min(10,Math.max(3,t.connectorStemLength*.35)),G=H.x-p,j=H.y-A,Z=Math.max(.001,Math.sqrt(G*G+j*j)),J=p+G/Z*_,Y=A+j/Z*_;T.lineWidth=t.connectorWidth,T.lineCap="round",T.lineJoin="round";const W=T.createLinearGradient(p,A+_,p,w);W.addColorStop(0,t.connectorColor),W.addColorStop(1,Rn(t.connectorColor)),T.beginPath(),T.strokeStyle=W,T.moveTo(p,w),T.lineTo(p,A+_),T.stroke(),T.beginPath(),T.strokeStyle=t.connectorColor,T.moveTo(p,A+_),T.quadraticCurveTo(p,A,J,Y),T.lineTo(H.x,H.y),T.stroke()}T.fillStyle=t.backgroundColor,Pn(T,g,0,v,u,N),T.fill(),T.font=s,T.fillStyle=t.textColor,T.textAlign="left",T.textBaseline="middle";for(let A=0;A<n.length;A++)T.fillText(n[A],g+c,d+r*A+r*.5);return{canvas:I,width:M,height:S,plateWidth:v,plateHeight:u,anchorX:b,marginY:2}}function Pn(i,t,e,n,o,s){i.beginPath(),i.moveTo(t+s,e),i.lineTo(t+n-s,e),i.quadraticCurveTo(t+n,e,t+n,e+s),i.lineTo(t+n,e+o-s),i.quadraticCurveTo(t+n,e+o,t+n-s,e+o),i.lineTo(t+s,e+o),i.quadraticCurveTo(t,e+o,t,e+o-s),i.lineTo(t,e+s),i.quadraticCurveTo(t,e,t+s,e),i.closePath()}function Cn(i,t,e){return{x:i+e,y:t}}function Rn(i){const t=i.trim(),e=t.startsWith("#")?t.slice(1):"";if(e.length===3||e.length===4){const o=Number.parseInt(e[0]+e[0],16),s=Number.parseInt(e[1]+e[1],16),r=Number.parseInt(e[2]+e[2],16);if(Number.isFinite(o)&&Number.isFinite(s)&&Number.isFinite(r))return`rgba(${o}, ${s}, ${r}, 0)`}if(e.length===6||e.length===8){const o=Number.parseInt(e.slice(0,2),16),s=Number.parseInt(e.slice(2,4),16),r=Number.parseInt(e.slice(4,6),16);if(Number.isFinite(o)&&Number.isFinite(s)&&Number.isFinite(r))return`rgba(${o}, ${s}, ${r}, 0)`}const n=t.match(/^rgba?\(([^)]+)\)$/i);if(n){const o=n[1].split(",").map(s=>s.trim());if(o.length>=3)return`rgba(${o[0]}, ${o[1]}, ${o[2]}, 0)`}return"rgba(255, 255, 255, 0)"}function kn(i,t){const e=i.count>1?`merged x${i.count}`:i.id;return t.showFieldLabels===!1?e:`target: ${e}`}function An(i){return i<.5?4*i*i*i:1-Math.pow(-2*i+2,3)/2}function Ln(i,t){return t<=0?1:Math.max(0,i*1e3/t)}function ft(i,t,e){return i<t?Math.min(t,i+e):i>t?Math.max(t,i-e):i}function En(){return typeof performance<"u"?performance.now():Date.now()}function Hn(){const e=document.createElement("canvas");e.width=160,e.height=160;const n=e.getContext("2d");if(!n)return e;const o=n.createRadialGradient(80,80,0,80,80,80);return o.addColorStop(0,"rgba(255,255,255,1)"),o.addColorStop(.2,"rgba(255,255,255,1)"),o.addColorStop(.52,"rgba(255,255,255,0.72)"),o.addColorStop(.82,"rgba(255,255,255,0.3)"),o.addColorStop(1,"rgba(255,255,255,0)"),n.fillStyle=o,n.fillRect(0,0,160,160),e}function Dn(i,t){const o=document.createElement("canvas");o.width=128,o.height=128;const s=o.getContext("2d");if(!s)return o;s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high",s.clearRect(0,0,128,128);const r=document.createElement("canvas");r.width=128,r.height=128;const c=r.getContext("2d");return c&&(c.imageSmoothingEnabled=!0,c.imageSmoothingQuality="high",c.drawImage(i,8,8,128-8*2,128-8*2),_n(s,r,t)),o}function _n(i,t,e){const n=t.getContext("2d");if(!n)return;const{width:o,height:s}=t,r=n.getImageData(0,0,o,s),c=i.createImageData(o,s),d=On(e),h=new Float32Array(o*s),m=new Float32Array(o*s);for(let u=0;u<r.data.length;u+=4){const p=u/4,g=r.data[u],y=r.data[u+1],w=r.data[u+2],M=r.data[u+3]/255,S=(g*.2126+y*.7152+w*.0722)/255;h[p]=S*M,m[p]=(1-S)*M}const f=mt(h,o,s,3),v=mt(m,o,s,4);for(let u=0;u<r.data.length;u+=4){const p=u/4,g=Math.min(1,Math.max(h[p],f[p]*.72)),y=Math.min(.34,m[p]*.24+v[p]*.7),w=y+g*(1-y);if(w<=0)continue;const M=g*(1-y)/w;c.data[u]=Math.round(d.r*M),c.data[u+1]=Math.round(d.g*M),c.data[u+2]=Math.round(d.b*M),c.data[u+3]=Math.round(w*255)}i.putImageData(c,0,0)}function mt(i,t,e,n){const o=[.00443,.05401,.24204,.39905,.24204,.05401,.00443],s=3,r=new Float32Array(i.length);let c=i,d=new Float32Array(i.length);for(let h=0;h<n;h++){for(let m=0;m<e;m++)for(let f=0;f<t;f++){let v=0;for(let u=-s;u<=s;u++){const p=pt(f+u,0,t-1);v+=c[m*t+p]*o[u+s]}r[m*t+f]=v}d=new Float32Array(i.length);for(let m=0;m<e;m++)for(let f=0;f<t;f++){let v=0;for(let u=-s;u<=s;u++){const p=pt(m+u,0,e-1);v+=r[p*t+f]*o[u+s]}d[m*t+f]=v}c=d}return d}function pt(i,t,e){return Math.max(t,Math.min(e,i))}function On(i){const t=i.startsWith("#")?i.slice(1):i;return{r:Number.parseInt(t.slice(0,2),16),g:Number.parseInt(t.slice(2,4),16),b:Number.parseInt(t.slice(4,6),16)}}const B=de,me=B.Buffer,pe=B.BufferUsage,Bn=B.VertexArray,Fn=B.ShaderProgram,Nn=B.DrawCommand,zn=B.RenderState,Vn=B.BlendingState,Wn=B.Pass,Un=B.PrimitiveType,ge=B.ComponentDatatype,Xn=B.Texture,Gn=B.Sampler,Zn=1,Yn=2,Kn=64;class gt{constructor(t,e){l(this,"scene");l(this,"capacity");l(this,"pixelSize");l(this,"iconCount");l(this,"headingOffsets");l(this,"center",new a.Cartesian3);l(this,"pos");l(this,"col");l(this,"ico");l(this,"ids");l(this,"count",0);l(this,"dirty",!1);l(this,"idIndex",new Map);l(this,"headingById",new Map);l(this,"cmd");l(this,"posBuf");l(this,"colBuf");l(this,"icoBuf");l(this,"texture");l(this,"iconImages");l(this,"iconReady",0);l(this,"show",!0);this.scene=t,this.capacity=e.capacity??3e4,this.pixelSize=e.pixelSize??30;const n=e.typeStyles;this.iconCount=Math.max(1,n.length),this.headingOffsets=n.map(o=>o.pointHeadingOffset??0),this.pos=new Float32Array(this.capacity*4),this.col=new Float32Array(this.capacity*4),this.ico=new Float32Array(this.capacity),this.ids=new Array(this.capacity).fill(""),this.iconImages=new Array(this.iconCount).fill(null),n.forEach((o,s)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{this.iconImages[s]=r,this.iconReady++},r.onerror=()=>{this.iconReady++},r.src=o.iconPath})}setVisible(t){this.show=t}setInstances(t){a.Cartesian3.clone(this.scene.camera.positionWC,this.center),this.idIndex.clear(),this.headingById.clear();const e=new a.Cartesian3;let n=0;for(let o=0;o<t.length&&n<this.capacity;o++){const s=t[o];a.Cartesian3.fromDegrees(s.lon,s.lat,s.height??0,void 0,e),this.pos[n*4+0]=e.x-this.center.x,this.pos[n*4+1]=e.y-this.center.y,this.pos[n*4+2]=e.z-this.center.z;const r=s.iconIndex??0,c=r<0?0:r>=this.iconCount?this.iconCount-1:r,d=this.renderHeadingOf(s.heading??0,c);this.pos[n*4+3]=d;const h=s.color??[1,1,1,1];this.col[n*4+0]=h[0],this.col[n*4+1]=h[1],this.col[n*4+2]=h[2],this.col[n*4+3]=h[3],this.ico[n]=c,this.ids[n]=s.id,this.idIndex.set(s.id,n),this.headingById.set(s.id,s.heading??0),n++}this.clearSlotsFrom(n),this.count=n,this.dirty=!0}setPacket(t){const e=this.scene.camera.positionWC;a.Cartesian3.clone(e,this.center),this.idIndex.clear(),this.headingById.clear();let n=0;const o=t.lon.length,s=new a.Cartesian3;for(let r=0;r<o&&n<this.capacity;r++){const c=t.flags[r];if(c>>Yn&3||!(c&Kn)||c&Zn||t.count[r]!==1)continue;a.Cartesian3.fromDegrees(t.lon[r],t.lat[r],t.height[r],void 0,s),this.pos[n*4+0]=s.x-this.center.x,this.pos[n*4+1]=s.y-this.center.y,this.pos[n*4+2]=s.z-this.center.z;const d=t.heading[r]||0,h=t.color[r]>>>0;this.col[n*4+0]=(h>>16&255)/255,this.col[n*4+1]=(h>>8&255)/255,this.col[n*4+2]=(h&255)/255,this.col[n*4+3]=1;const m=t.category[r]??0,f=m<0?0:m>=this.iconCount?this.iconCount-1:m;this.ico[n]=f;const v=t.ids[r],u=this.renderHeadingOf(d,f);this.ids[n]=v,this.pos[n*4+3]=u,this.idIndex.set(v,n),this.headingById.set(v,d),n++}this.clearSlotsFrom(n),this.count=n,this.dirty=!0}getTargetFrame(t,e=new a.Cartesian3){const n=this.idIndex.get(t);if(n!==void 0)return e.x=this.pos[n*4+0]+this.center.x,e.y=this.pos[n*4+1]+this.center.y,e.z=this.pos[n*4+2]+this.center.z,{position:e,heading:this.headingById.get(t)??0}}update(t){if(!this.show||this.count===0)return;const e=t.context;this.cmd||this.build(e),!this.texture&&this.iconReady>=this.iconCount&&this.buildAtlas(e),this.dirty&&(this.posBuf.copyFromArrayView(this.pos,0),this.colBuf.copyFromArrayView(this.col,0),this.icoBuf.copyFromArrayView(this.ico,0),this.dirty=!1),a.Matrix4.fromTranslation(this.center,this.cmd.modelMatrix),this.cmd.instanceCount=this.count,t.commandList.push(this.cmd)}buildAtlas(t){const n=document.createElement("canvas");n.width=128*this.iconCount,n.height=128;const o=n.getContext("2d");if(o){for(let s=0;s<this.iconCount;s++){const r=this.iconImages[s];r&&o.drawImage(r,s*128,0,128,128)}this.texture=new Xn({context:t,source:n,sampler:new Gn({})})}}build(t){const e=new Float32Array([-.5,-.5,0,1,.5,-.5,1,1,.5,.5,1,0,-.5,-.5,0,1,.5,.5,1,0,-.5,.5,0,0]),n=me.createVertexBuffer({context:t,typedArray:e,usage:pe.STATIC_DRAW});this.posBuf=me.createVertexBuffer({context:t,typedArray:this.pos,usage:pe.DYNAMIC_DRAW}),this.colBuf=me.createVertexBuffer({context:t,typedArray:this.col,usage:pe.DYNAMIC_DRAW}),this.icoBuf=me.createVertexBuffer({context:t,typedArray:this.ico,usage:pe.DYNAMIC_DRAW});const o=new Bn({context:t,attributes:[{index:0,vertexBuffer:n,componentsPerAttribute:4,componentDatatype:ge.FLOAT},{index:1,vertexBuffer:this.posBuf,componentsPerAttribute:4,componentDatatype:ge.FLOAT,instanceDivisor:1},{index:2,vertexBuffer:this.colBuf,componentsPerAttribute:4,componentDatatype:ge.FLOAT,instanceDivisor:1},{index:3,vertexBuffer:this.icoBuf,componentsPerAttribute:1,componentDatatype:ge.FLOAT,instanceDivisor:1}]}),s=`
31
+ in vec4 a_quad; // xy=corner, zw=uv
32
+ in vec4 a_inst; // xyz=ECEF相对中心, w=heading(度)
33
+ in vec4 a_color; // rgba
34
+ in float a_icon; // 图标索引
35
+ uniform vec3 u_center;
36
+ uniform float u_pixelSize;
37
+ uniform float u_iconCount;
38
+ out vec2 v_uv;
39
+ out vec4 v_color;
40
+ void main() {
41
+ vec3 pRel = a_inst.xyz;
42
+ float heading = radians(a_inst.w);
43
+ vec3 ecefAbs = u_center + pRel;
44
+ vec3 up = normalize(ecefAbs);
45
+ vec3 east = normalize(cross(vec3(0.0, 0.0, 1.0), up));
46
+ vec3 north = cross(up, east);
47
+ float ch = cos(heading), sh = sin(heading);
48
+ vec2 r = vec2(ch * a_quad.x - sh * a_quad.y, sh * a_quad.x + ch * a_quad.y);
49
+ vec4 eye = czm_modelView * vec4(pRel, 1.0);
50
+ float worldPerPixel = 2.0 * length(eye.xyz) / (czm_viewport.w * czm_projection[1][1]);
51
+ vec3 offset = (r.x * east + r.y * north) * (u_pixelSize * worldPerPixel);
52
+ v_uv = vec2((a_icon + a_quad.z) / u_iconCount, a_quad.w);
53
+ v_color = a_color;
54
+ gl_Position = czm_modelViewProjection * vec4(pRel + offset, 1.0);
55
+ czm_vertexLogDepth();
56
+ }
57
+ `,r=`
58
+ in vec2 v_uv;
59
+ in vec4 v_color;
60
+ uniform sampler2D u_icon;
61
+ uniform float u_hasIcon;
62
+ void main() {
63
+ vec4 tex = u_hasIcon > 0.5 ? texture(u_icon, v_uv) : vec4(1.0);
64
+ if (tex.a < 0.05) discard;
65
+ // 图标 rgb 携带"白色填充 + 深色描边",乘以实例颜色着色(保留描边)。
66
+ out_FragColor = vec4(v_color.rgb * tex.rgb, v_color.a * tex.a);
67
+ }
68
+ `,c=Fn.fromCache({context:t,vertexShaderSource:s,fragmentShaderSource:r,attributeLocations:{a_quad:0,a_inst:1,a_color:2,a_icon:3}}),d={u_center:()=>this.center,u_pixelSize:()=>this.pixelSize,u_iconCount:()=>this.iconCount,u_icon:()=>this.texture,u_hasIcon:()=>this.texture?1:0};this.cmd=new Nn({primitiveType:Un.TRIANGLES,vertexArray:o,shaderProgram:c,renderState:zn.fromCache({depthTest:{enabled:!0},depthMask:!0,blending:Vn.ALPHA_BLEND}),pass:Wn.TRANSLUCENT,modelMatrix:a.Matrix4.fromTranslation(this.center,new a.Matrix4),uniformMap:d,count:6,instanceCount:this.count,cull:!1,boundingVolume:new a.BoundingSphere(a.Cartesian3.ZERO,1e8),owner:this})}isDestroyed(){return!1}destroy(){return this.cmd&&(this.cmd.shaderProgram&&this.cmd.shaderProgram.destroy(),this.cmd.vertexArray&&this.cmd.vertexArray.destroy(),this.cmd=void 0),this.texture&&(this.texture.destroy(),this.texture=void 0),!0}renderHeadingOf(t,e){return qn((this.headingOffsets[e]??0)-t)}clearSlotsFrom(t){for(let e=t;e<this.count;e++)this.ids[e]=""}}function qn(i){return(i%360+360)%360}const $n="target-selection-overlay",jn="target-hover-overlay",vt=500,yt=.85,Jn=.42,wt=1;class Qn{constructor(t,e){l(this,"collection");l(this,"pool",[]);l(this,"baseSizes",[]);l(this,"selectedIds",new Set);l(this,"pulseElapsedById",new Map);l(this,"hoveredId",null);l(this,"lastPacket",null);l(this,"activeCount",0);l(this,"selectionImage");l(this,"hoverImage");l(this,"hoverBillboard");this.scene=t,this.renderTypes=e,this.selectionImage=St("rgba(255, 42, 42, 0.98)","rgba(255, 24, 24, 0.72)","rgba(255, 190, 190, 0.9)"),this.hoverImage=St("rgba(154, 255, 184, 0.98)","rgba(120, 255, 160, 0.58)","rgba(222, 255, 231, 0.95)"),this.collection=this.scene.primitives.add(new a.BillboardCollection({scene:t})),this.collection.show=!0,this.hoverBillboard=this.collection.add({position:a.Cartesian3.ZERO,show:!1,width:q,height:q,color:a.Color.WHITE,disableDepthTestDistance:Number.POSITIVE_INFINITY}),this.hoverBillboard.setImage(jn,this.hoverImage)}setSelectedIds(t){const e=new Set(this.selectedIds),n=new Set(t);for(const o of e)n.has(o)||this.pulseElapsedById.delete(o);this.selectedIds.clear();for(const o of t)!e.has(o)&&!this.pulseElapsedById.has(o)&&this.pulseElapsedById.set(o,0),this.selectedIds.add(o);this.refresh()}setPacket(t){this.lastPacket=t,this.refresh()}setHoveredId(t){this.hoveredId!==t&&(this.hoveredId=t,this.refresh())}update(t){if(this.activeCount===0||this.pulseElapsedById.size===0)return;let e=!1;for(const[n,o]of this.pulseElapsedById){const s=o+t;if(s>=yt){this.pulseElapsedById.delete(n),e=!0;continue}this.pulseElapsedById.set(n,s),e=!0}for(let n=0;n<this.activeCount;n++){const o=this.baseSizes[n]||q,s=eo(this.pool[n]),r=s?Mt(this.pulseElapsedById.get(s)):wt;this.pool[n].width=o*r,this.pool[n].height=o*r}e&&this.scene.requestRender()}getRenderedTarget(t){const e=this.lastPacket;if(!(!e||!this.selectedIds.has(t))){for(let n=0;n<e.ids.length;n++)if(!(e.ids[n]!==t||e.count[n]!==1))return{id:t,position:a.Cartesian3.fromDegrees(e.lon[n],e.lat[n],e.height[n]),size:this.overlaySizeOf(e,n)}}}clear(){this.lastPacket=null,this.hoveredId=null,this.pulseElapsedById.clear(),this.hideUnused(0),this.hoverBillboard.show=!1}destroy(){this.clear(),this.scene.primitives.remove(this.collection)}refresh(){const t=this.lastPacket;if(!t){this.hideUnused(0),this.hoverBillboard.show=!1;return}if(this.selectedIds.size===0){this.hideUnused(0),this.refreshHover(t),this.scene.requestRender();return}let e=0;this.ensurePool(Math.min(this.selectedIds.size,vt));for(let n=0;n<t.ids.length&&!(e>=vt);n++){const o=t.ids[n];if(!o||t.count[n]!==1||!this.selectedIds.has(o))continue;const s=this.pool[e],r=this.overlaySizeOf(t,n);s.position=a.Cartesian3.fromDegrees(t.lon[n],t.lat[n],t.height[n]),this.baseSizes[e]=r;const c=Mt(this.pulseElapsedById.get(o));s.width=r*c,s.height=r*c,s.rotation=0,s.id={targetId:o,selectionOverlay:!0},s.show=!0,e++}this.hideUnused(e),this.refreshHover(t),this.scene.requestRender()}ensurePool(t){for(;this.pool.length<t;){const e=this.collection.add({position:a.Cartesian3.ZERO,show:!1,width:q,height:q,color:a.Color.WHITE,disableDepthTestDistance:Number.POSITIVE_INFINITY});e.setImage($n,this.selectionImage),this.pool.push(e),this.baseSizes.push(q)}}hideUnused(t){for(let e=t;e<this.activeCount;e++)this.pool[e].show=!1,this.baseSizes[e]=q;this.activeCount=t}refreshHover(t){const e=this.hoveredId;if(!e){this.hoverBillboard.show=!1;return}for(let n=0;n<t.ids.length;n++){if(t.ids[n]!==e||t.count[n]!==1)continue;const o=this.overlaySizeOf(t,n);this.hoverBillboard.position=a.Cartesian3.fromDegrees(t.lon[n],t.lat[n],t.height[n]),this.hoverBillboard.width=o,this.hoverBillboard.height=o,this.hoverBillboard.rotation=0,this.hoverBillboard.id={targetId:e,hoverOverlay:!0},this.hoverBillboard.show=!0;return}this.hoverBillboard.show=!1}overlaySizeOf(t,e){var s;const n=t.category[e]??0,o=((s=this.renderTypes[n])==null?void 0:s.type)??"";return st(o,t.size[e],t.count[e]>1)}}function Mt(i){if(i==null)return wt;const t=i/yt;return 1+(1-t)*(1-t)*Jn}function eo(i){const t=i.id;return t==null?void 0:t.targetId}function St(i,t,e){const o=document.createElement("canvas");o.width=64,o.height=64;const s=o.getContext("2d");if(!s)return o;s.clearRect(0,0,64,64),s.strokeStyle=i,s.lineWidth=4.5,s.shadowColor=t,s.shadowBlur=10;const r=9,c=17;return ve(s,r,r,c,1,1),ve(s,64-r,r,c,-1,1),ve(s,r,64-r,c,1,-1),ve(s,64-r,64-r,c,-1,-1),s.shadowBlur=0,s.strokeStyle=e,s.lineWidth=1.6,s.beginPath(),s.arc(64*.5,64*.5,6,0,a.Math.TWO_PI),s.stroke(),o}function ve(i,t,e,n,o,s){i.beginPath(),i.moveTo(t,e+s*n),i.lineTo(t,e),i.lineTo(t+o*n,e),i.stroke()}const to=80,It=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();class io{constructor(t,e){l(this,"points",[]);l(this,"index",null);l(this,"builtCameraPosition",null);l(this,"builtCameraDirection",null);l(this,"lastBuiltAt",0);this.scene=t,this.pixelThreshold=e}setPoints(t){this.points=t.slice(),this.index=null}invalidate(){this.index=null}rebuild(){this.index=null,this.ensureIndex()}pick(t){const e=this.ensureIndex();if(!e)return null;const n=Math.max(1,this.pixelThreshold),o=n*n,s=Math.floor(t.x/e.cellSize),r=Math.floor(t.y/e.cellSize);let c=null,d=0,h=0,m=o;for(let f=r-1;f<=r+1;f++)for(let v=s-1;v<=s+1;v++){const u=e.bins.get(xt(v,f));if(u)for(const p of u){const g=e.screenX[p]-t.x,y=e.screenY[p]-t.y,w=g*g+y*y;w>m||(m=w,c=this.points[p],d=e.screenX[p],h=e.screenY[p])}}return c?{targetId:c.targetId,pointIndex:c.pointIndex,point:c.point,screenX:d,screenY:h}:null}ensureIndex(){const t=this.scene.canvas,e=this.scene.camera,n=!!this.index&&this.index.canvasWidth===t.clientWidth&&this.index.canvasHeight===t.clientHeight,o=n&&!!this.builtCameraPosition&&!!this.builtCameraDirection&&a.Cartesian3.equalsEpsilon(e.positionWC,this.builtCameraPosition,a.Math.EPSILON7)&&a.Cartesian3.equalsEpsilon(e.directionWC,this.builtCameraDirection,a.Math.EPSILON9);if(this.index&&n&&o)return this.index;if(this.index&&n&&!o&&It()-this.lastBuiltAt<to)return this.index;if(this.index=null,this.builtCameraPosition=a.Cartesian3.clone(e.positionWC,this.builtCameraPosition??new a.Cartesian3),this.builtCameraDirection=a.Cartesian3.clone(e.directionWC,this.builtCameraDirection??new a.Cartesian3),this.lastBuiltAt=It(),this.points.length===0)return null;const s=Math.max(48,this.pixelThreshold*2),r=new Map,c=new Float32Array(this.points.length),d=new Float32Array(this.points.length);c.fill(Number.NaN),d.fill(Number.NaN);for(let h=0;h<this.points.length;h++){const m=a.SceneTransforms.wgs84ToWindowCoordinates(this.scene,this.points[h].position);if(!m)continue;const f=m.x,v=m.y;if(!Number.isFinite(f)||!Number.isFinite(v)||f<0||v<0||f>t.clientWidth||v>t.clientHeight)continue;c[h]=f,d[h]=v;const u=xt(Math.floor(f/s),Math.floor(v/s)),p=r.get(u);p?p.push(h):r.set(u,[h])}return this.index={bins:r,screenX:c,screenY:d,canvasWidth:t.clientWidth,canvasHeight:t.clientHeight,cellSize:s},this.index}}function xt(i,t){return`${i}:${t}`}const Tt=new a.Color(.22,.82,1,.84),no="track-point-overlay",bt=12,oo=new a.Cartesian3(0,0,-24);class so{constructor(t){l(this,"historyCollection");l(this,"connectorCollection");l(this,"pointCollection");l(this,"linePool",[]);l(this,"pointPool",[]);l(this,"lineCount",0);l(this,"pointImage");this.scene=t,this.historyCollection=this.scene.primitives.add(new a.PolylineCollection({show:!0})),this.connectorCollection=this.scene.primitives.add(new a.PolylineCollection({show:!0})),this.pointCollection=this.scene.primitives.add(new a.BillboardCollection({show:!0,scene:t})),this.pointImage=ro()}setTracks(t){this.ensureLinePool(t.length);let e=0;for(let n=0;n<t.length;n++){const o=t[n],s=this.linePool[n];s.history.positions=o.cartesianPoints,s.history.show=o.cartesianPoints.length>=2,s.history.id={targetId:o.targetId,trackHistory:!0},Pt(s,o.cartesianPoints,o.currentPosition);for(let r=0;r<o.cartesianPoints.length;r++){const c=this.ensurePoint(e++);c.position=o.cartesianPoints[r],c.id={targetId:o.targetId,trackPointIndex:r,trackPoint:!0},c.show=!0}}this.lineCount=t.length,this.hideUnusedLines(t.length),this.hideUnusedPoints(e)}updateConnectors(t){const e=Math.min(t.length,this.lineCount);for(let n=0;n<e;n++)Pt(this.linePool[n],t[n].cartesianPoints,t[n].currentPosition)}clear(){this.hideUnusedLines(0),this.hideUnusedPoints(0),this.lineCount=0}destroy(){this.clear(),this.scene.primitives.remove(this.historyCollection),this.scene.primitives.remove(this.connectorCollection),this.scene.primitives.remove(this.pointCollection)}ensureLinePool(t){for(;this.linePool.length<t;)this.linePool.push(this.createLineSlot())}ensurePoint(t){for(;this.pointPool.length<=t;){const e=this.pointCollection.add({show:!1,position:a.Cartesian3.ZERO,width:bt,height:bt,color:a.Color.WHITE,eyeOffset:a.Cartesian3.clone(oo),disableDepthTestDistance:Number.POSITIVE_INFINITY});e.setImage(no,this.pointImage),this.pointPool.push(e)}return this.pointPool[t]}createLineSlot(){const t=a.Cartesian3.clone(a.Cartesian3.ZERO),e=a.Cartesian3.clone(a.Cartesian3.ZERO),n=[t,e],o=a.Material.fromType(a.Material.ColorType,{color:a.Color.clone(Tt)}),s=a.Material.fromType(a.Material.ColorType,{color:a.Color.clone(Tt)}),r=this.historyCollection.add({show:!1,positions:[],width:2.2,material:o}),c=this.connectorCollection.add({show:!1,positions:n,width:1.5,material:s});return{history:r,connector:c,connectorStart:t,connectorEnd:e,connectorPositions:n,historyMaterial:o,connectorMaterial:s}}hideUnusedLines(t){for(let e=t;e<this.linePool.length;e++)this.linePool[e].history.show=!1,this.linePool[e].connector.show=!1}hideUnusedPoints(t){for(let e=t;e<this.pointPool.length;e++)this.pointPool[e].show=!1}}function ro(){const t=document.createElement("canvas");t.width=48,t.height=48;const e=t.getContext("2d");if(!e)return t;const n=48*.5;return e.clearRect(0,0,48,48),e.fillStyle="rgba(234,252,255,0.98)",e.strokeStyle="rgba(18,138,184,0.95)",e.lineWidth=5,e.beginPath(),e.arc(n,n,11,0,Math.PI*2),e.fill(),e.stroke(),e.strokeStyle="rgba(255,255,255,0.95)",e.lineWidth=2,e.beginPath(),e.arc(n,n,15,0,Math.PI*2),e.stroke(),t}function Pt(i,t,e){if(t.length===0||!e){i.connector.show=!1;return}const n=t[t.length-1];if(a.Cartesian3.distance(n,e)<1){i.connector.show=!1;return}a.Cartesian3.clone(n,i.connectorStart),a.Cartesian3.clone(e,i.connectorEnd),i.connector.positions=i.connectorPositions,i.connector.show=!0}class Ct extends ue{constructor(e,n){super();l(this,"records",new Map);l(this,"renderer");l(this,"hoverPicker");l(this,"lastPacket",null);l(this,"hoverPosition",null);l(this,"lastPointerPosition",null);l(this,"hoverRafId",0);l(this,"rebuildHoverIndexTimer",0);l(this,"currentHoverKey","");l(this,"removeCameraListener");l(this,"onPointerMoveBound");l(this,"onPointerLeaveBound");l(this,"onPointerDownBound");l(this,"onWheelBound");this.viewer=e,this.renderer=new so(this.viewer.scene),this.hoverPicker=new io(this.viewer.scene,n),this.removeCameraListener=this.viewer.camera.changed.addEventListener(()=>{this.hoverPicker.invalidate(),this.clearHover({keepPointer:!0}),this.scheduleHoverIndexRebuild()}),this.onPointerMoveBound=s=>this.onPointerMove(s),this.onPointerLeaveBound=()=>this.clearHover(),this.onPointerDownBound=()=>this.clearHover(),this.onWheelBound=()=>this.clearHover();const o=this.viewer.scene.canvas;o.addEventListener("pointermove",this.onPointerMoveBound),o.addEventListener("pointerleave",this.onPointerLeaveBound),o.addEventListener("pointerdown",this.onPointerDownBound),o.addEventListener("wheel",this.onWheelBound,{passive:!0})}setTracks(e){if(e.length!==0){for(const n of e){const o=ao(n);this.records.set(o.targetId,o)}this.refresh()}}getTracks(e){var s;const n=e!=null&&e.length?e:Array.from(this.records.keys()),o=[];for(const r of n){const c=this.records.get(r);c&&o.push({targetId:c.targetId,visible:c.visible,pointList:(s=c.pointList)==null?void 0:s.map(kt),trackLine:c.trackLine})}return o}showTracks(e){this.setVisible(e,!0)}hideTracks(e){this.setVisible(e,!1)}removeTracks(e){if(e.length!==0){for(const n of e)this.records.delete(n);this.refresh()}}clearTracks(){this.records.size!==0&&(this.records.clear(),this.refresh())}setRenderPacket(e){this.lastPacket=e;const n=this.getVisibleRecords();if(n.length===0)return;const o=new Set(n.map(r=>r.targetId)),s=new Set;for(let r=0;r<e.ids.length;r++){const c=e.ids[r];if(!c||e.count[r]!==1||!o.has(c))continue;const d=this.records.get(c);if(!d)continue;const h=a.Cartesian3.fromDegrees(e.lon[r],e.lat[r],e.height[r]);d.currentPosition?(a.Cartesian3.clone(d.currentPosition,d.motionFrom),a.Cartesian3.clone(h,d.motionTo),d.motionElapsedSec=0,d.motionDurationSec=Math.max(0,e.moveDurationMs[r]/1e3)):(d.currentPosition=a.Cartesian3.clone(h),a.Cartesian3.clone(h,d.motionFrom),a.Cartesian3.clone(h,d.motionTo),d.motionElapsedSec=0,d.motionDurationSec=0),s.add(c)}for(const r of n)s.has(r.targetId)||(r.currentPosition=null,r.motionElapsedSec=0,r.motionDurationSec=0);this.renderer.updateConnectors(this.toRenderRecords(n))}update(e){const n=this.getVisibleRecords();if(n.length===0)return;let o=!1;for(const s of n){if(!s.currentPosition||s.motionDurationSec<=0)continue;s.motionElapsedSec=Math.min(s.motionElapsedSec+e,s.motionDurationSec);const r=s.motionDurationSec<=0?1:s.motionElapsedSec/s.motionDurationSec;a.Cartesian3.lerp(s.motionFrom,s.motionTo,uo(r),s.currentPosition),s.motionElapsedSec<s.motionDurationSec?o=!0:s.motionDurationSec=0}o&&this.renderer.updateConnectors(this.toRenderRecords(n))}destroy(){this.hoverRafId&&cancelAnimationFrame(this.hoverRafId),this.rebuildHoverIndexTimer&&window.clearTimeout(this.rebuildHoverIndexTimer),this.clearHover();const e=this.viewer.scene.canvas;e.removeEventListener("pointermove",this.onPointerMoveBound),e.removeEventListener("pointerleave",this.onPointerLeaveBound),e.removeEventListener("pointerdown",this.onPointerDownBound),e.removeEventListener("wheel",this.onWheelBound),this.removeCameraListener(),this.renderer.destroy(),this.clear()}setVisible(e,n){if(e.length===0)return;let o=!1;for(const s of e){const r=this.records.get(s);!r||r.visible===n||(r.visible=n,o=!0)}o&&this.refresh()}refresh(){const e=this.getVisibleRecords();this.renderer.setTracks(this.toRenderRecords(e)),this.hoverPicker.setPoints(e.flatMap(n=>n.cartesianPoints.map((o,s)=>({targetId:n.targetId,pointIndex:s,point:n.normalizedPoints[s],position:o})))),this.clearHover(),this.lastPacket&&this.setRenderPacket(this.lastPacket)}getVisibleRecords(){const e=[];for(const n of this.records.values())n.visible&&n.normalizedPoints.length>0&&e.push(n);return e}toRenderRecords(e){return e.map(n=>({targetId:n.targetId,points:n.normalizedPoints,cartesianPoints:n.cartesianPoints,currentPosition:n.currentPosition}))}onPointerMove(e){const n=this.viewer.scene.canvas.getBoundingClientRect();this.lastPointerPosition=new a.Cartesian2(e.clientX-n.left,e.clientY-n.top),this.scheduleHoverPick(this.lastPointerPosition)}flushHoverPick(){if(this.hoverRafId=0,!this.hoverPosition)return;const e=this.hoverPicker.pick(this.hoverPosition),n=e?`${e.targetId}:${e.pointIndex}`:"";n!==this.currentHoverKey&&(this.currentHoverKey=n,this.emit("hover",e))}clearHover(e={}){this.hoverPosition=null,e.keepPointer||(this.lastPointerPosition=null),this.currentHoverKey&&(this.currentHoverKey="",this.emit("hover",null))}scheduleHoverPick(e){this.hoverPosition=a.Cartesian2.clone(e,this.hoverPosition??new a.Cartesian2),!this.hoverRafId&&(this.hoverRafId=requestAnimationFrame(()=>this.flushHoverPick()))}scheduleHoverPickFromLastPointer(){this.lastPointerPosition&&(this.hoverRafId||(this.hoverRafId=requestAnimationFrame(()=>{this.hoverRafId=0,this.lastPointerPosition&&this.scheduleHoverPick(this.lastPointerPosition)})))}scheduleHoverIndexRebuild(){this.rebuildHoverIndexTimer&&window.clearTimeout(this.rebuildHoverIndexTimer),this.rebuildHoverIndexTimer=window.setTimeout(()=>{this.rebuildHoverIndexTimer=0,this.hoverPicker.rebuild(),this.scheduleHoverPickFromLastPointer()},120)}}function ao(i){var n;if(!i||typeof i!="object")throw new Error("track must be an object.");if(typeof i.targetId!="string"||i.targetId.length===0)throw new Error("track.targetId must be a non-empty string.");const t=lo(i.pointList),e=t.length>0?t:co(i.trackLine,i.targetId);return{targetId:i.targetId,visible:i.visible??!0,pointList:(n=i.pointList)==null?void 0:n.map(kt),trackLine:i.trackLine,normalizedPoints:e,cartesianPoints:e.map(o=>a.Cartesian3.fromDegrees(o.lon,o.lat,o.height)),currentPosition:null,motionFrom:a.Cartesian3.clone(a.Cartesian3.ZERO),motionTo:a.Cartesian3.clone(a.Cartesian3.ZERO),motionElapsedSec:0,motionDurationSec:0}}function lo(i){if(!(i!=null&&i.length))return[];const t=[];for(const e of i){if(!e||typeof e!="object")continue;const n=Number(e.lon),o=Number(e.lat),s=Number(e.height),r=ho(e.time);!Number.isFinite(n)||!Number.isFinite(o)||!Number.isFinite(s)||!Number.isFinite(r)||t.push({lon:n,lat:o,height:s,time:r,heading:Rt(e.heading),speed:Rt(e.speed),source:typeof e.source=="string"&&e.source?e.source:void 0})}return t.sort((e,n)=>e.time-n.time),t}function co(i,t){if(!i)return[];const e=/^\s*LINESTRING(?:\s+Z)?\s*\((.+)\)\s*$/i.exec(i);if(!e)return console.warn(`[tracks] ignored invalid LINESTRING for ${t}`),[];const n=[],o=e[1].split(",");for(let s=0;s<o.length;s++){const r=o[s].trim().split(/\s+/).map(Number);r.length<2||!Number.isFinite(r[0])||!Number.isFinite(r[1])||n.push({lon:r[0],lat:r[1],height:Number.isFinite(r[2])?r[2]:0,time:s,source:"trackLine"})}return n.length===0&&console.warn(`[tracks] ignored empty LINESTRING for ${t}`),n}function ho(i){if(typeof i=="number")return i;if(typeof i=="string"){const t=Date.parse(i);if(Number.isFinite(t))return t;const e=Number(i);return Number.isFinite(e)?e:Number.NaN}return Number.NaN}function Rt(i){if(i==null)return;const t=Number(i);return Number.isFinite(t)?t:void 0}function kt(i){return{lon:i.lon,lat:i.lat,height:i.height,time:i.time,heading:i.heading,speed:i.speed,source:i.source}}function uo(i){const t=a.Math.clamp(i,0,1);return 1-Math.pow(1-t,3)}function fo(){return new Worker("/assets/renderWorker-118e8f3b.js")}const mo=40,At=2,Lt=1.25,po=.75,go=.3,Et=.35,Ht=16,Dt=200,vo=200,_t=120,yo=512,wo=48,Mo=32,So=64;class Ot extends ue{constructor(e,n){var o,s,r,c,d,h,m,f,v;super();l(this,"config");l(this,"render");l(this,"models");l(this,"symbols");l(this,"selection");l(this,"tracks");l(this,"ready");l(this,"nodes",{visibleCount:0,bufferCount:0,renderedCount:0,clusterCount:0,lastMergeRadius:0,pointRenderCount:0,mergedPointRenderCount:0,plainPointRenderCount:0,lowModelRenderCount:0,highModelRenderCount:0,mergedLowModelRenderCount:0,mergedHighModelRenderCount:0,forcedPointMode:!1,level:0,outsideLevel:0});l(this,"quality",{tier:"high"});l(this,"worker");l(this,"resolveReady");l(this,"readyResolved",!1);l(this,"commitIntervalMs");l(this,"commitTimer",null);l(this,"rafId",0);l(this,"paused",!1);l(this,"destroyed",!1);l(this,"total",0);l(this,"commitRequestId",0);l(this,"viewportRequestId",0);l(this,"dataRevision",0);l(this,"viewportRequestRevisions",new Map);l(this,"globalViewportRequestIds",new Set);l(this,"globalViewportRevision",-1);l(this,"targetQueryRequestId",0);l(this,"targetQueryResolvers",new Map);l(this,"viewportInFlight",!1);l(this,"viewportDirty",!1);l(this,"lastCommitSubmitAt",0);l(this,"lastFrameAt",E());l(this,"lastPredictionViewportAt",0);l(this,"lastSymbolsUpdateAt",0);l(this,"stagedUpserts",0);l(this,"stagedBatches",0);l(this,"removeCameraListener");l(this,"inputHandler");l(this,"selectedIds",new Set);l(this,"selectedTargets",new Map);l(this,"hoverRequestSerial",0);l(this,"pickRequestSerial",0);l(this,"contextMenuRequestSerial",0);l(this,"hoverPickPosition",null);l(this,"hoverPickRafId",0);l(this,"lastHoverPickAt",0);l(this,"lastHoverPointerSample",null);l(this,"hoverPointerSpeedPxPerMs",0);l(this,"pointerButtonsMask",0);l(this,"wheelSuppressPickUntil",0);l(this,"cameraMoving",!1);l(this,"cameraMoveTrailingTimer",0);l(this,"wheelSuppressResetTimer",0);l(this,"cameraViewportThrottleTimer",0);l(this,"lastCameraViewportAt",0);l(this,"lastHoverId",null);l(this,"hoverTargetCache",new Map);l(this,"labelDataById",new Map);l(this,"latestRenderPacket",null);l(this,"hoverPickIndex",null);l(this,"hoverPickWarmupRafId",0);l(this,"cameraRevision",0);l(this,"labelConfig");this.viewer=e,this.config=ai(n),this.labelConfig=this.config.label,this.commitIntervalMs=this.config.data.commitIntervalMs,this.render=new vn(e.scene,this.config.fadeMs,{targetTypes:this.config.renderTypes.map(De),label:this.labelConfig,labelTextResolver:u=>this.nameplateText(u)}),this.selection=new Qn(e.scene,this.config.renderTypes),this.tracks=new Ct(e,this.config.pick.pixelThreshold),this.config.groundSymbols&&(this.symbols=new gt(e.scene,{typeStyles:this.config.renderTypes.map(De),capacity:this.config.poolSize,pixelSize:this.config.groundSymbolPixelSize}),e.scene.primitives.add(this.symbols),this.render.setDirectionalHandledExternally(!0)),this.models=new ji(e,this.config.renderTypes.map(De),this.config.frame.maxLowModelRenderItems,Math.max(this.config.animatedCapacity,this.config.frame.maxModelRenderItems),this.config.animatedCapacity,this.config.fadeMs),this.render.setAnchorPositionResolver((u,p)=>{var g;return(g=this.getRenderedTargetFrame(u,p))==null?void 0:g.position}),this.ready=new Promise(u=>{this.resolveReady=u}),this.worker=new fo,this.worker.onmessage=u=>this.handleWorkerMessage(u.data),this.worker.postMessage({type:"init",config:{maxVisible:((o=this.config.merge)==null?void 0:o.maxVisible)??this.config.poolSize,rootLimit:((s=this.config.merge)==null?void 0:s.globalRootLimit)??500,maxLevels:((r=this.config.merge)==null?void 0:r.globalMaxLevels)??64,cameraMergeBaseHeight:((c=this.config.merge)==null?void 0:c.cameraMergeBaseHeight)??1e5,cameraMergeStepHeight:((d=this.config.merge)==null?void 0:d.cameraMergeStepHeight)??1e4,cameraMergeStepRadius:((h=this.config.merge)==null?void 0:h.cameraMergeStepRadius)??100,globalViewportHeight:((m=this.config.merge)==null?void 0:m.globalViewportHeight)??45e4,globalCacheIntervalMs:((f=this.config.merge)==null?void 0:f.globalRebuildIntervalMs)??3e5,innerRatio:((v=this.config.merge)==null?void 0:v.innerRatio)??.6,viewportBufferRatio:this.config.cull.viewportBufferRatio,viewportBufferMinMeters:this.config.cull.viewportBufferMinMeters,pointAbove:this.config.lod.pointAbove,animatedBelow:this.config.lod.animatedBelow,predictSeconds:this.config.predictSeconds,predictFitSeconds:this.config.predictFitSeconds,targetTypes:this.config.renderTypes.map((u,p)=>({type:u.type,category:p,targetDomain:u.targetDomain,forceHighModelInLowLod:u.forceHighModelInLowLod,iconPath:u.iconPath,defaultColor:Po(u.defaultColor),smoothMove:u.smoothMove,smoothMoveMinCameraHeight:u.smoothMoveMinCameraHeight,smoothMoveDurationMs:u.smoothMoveDurationMs,predictMove:u.predictMove,predictMinCameraHeight:u.predictMinCameraHeight,predictSeconds:u.predictSeconds,predictFitSeconds:u.predictFitSeconds}))}}),this.removeCameraListener=this.viewer.camera.changed.addEventListener(()=>{this.requestViewportThrottled(),this.noteCameraMovement()}),this.inputHandler=new a.ScreenSpaceEventHandler(this.viewer.scene.canvas),this.inputHandler.setInputAction(u=>{this.handleContextMenuAt(u.position)},a.ScreenSpaceEventType.RIGHT_CLICK),this.config.pick.enabled&&(this.inputHandler.setInputAction(u=>{this.handlePickAt(u.position)},a.ScreenSpaceEventType.LEFT_CLICK),this.config.pick.hover&&(this.bindHoverSuppressionInput(),this.inputHandler.setInputAction(u=>{this.scheduleHoverPick(u.endPosition)},a.ScreenSpaceEventType.MOUSE_MOVE))),this.startCommitLoop(),this.startRenderLoop()}get targetCount(){return this.total}setData(e){if(this.destroyed)return;this.replaceLabelData(e);const n=this.postWithTiming({type:"set-data",targets:e});this.stagedUpserts=e.length,this.stagedBatches=1,this.emit("perf",{phase:"worker-submit",full:e.length,batches:1,upserts:e.length,submitMs:n}),this.config.data.leading&&this.commitNow()}applyIncremental(e){var r,c;if(this.destroyed)return;this.applyLabelIncremental(e);const n=((r=e.upserts)==null?void 0:r.length)??0,o=((c=e.removes)==null?void 0:c.length)??0,s=this.postWithTiming({type:"incremental",payload:e});this.stagedUpserts+=n,this.stagedBatches++,this.emit("perf",{phase:"worker-submit",full:this.total,batches:this.stagedBatches,upserts:n,submitMs:s}),this.config.data.leading&&this.total===0&&this.commitNow(),(n||o)&&this.emit("dirty",{added:e.upserts??[],updated:[],removed:e.removes??[]})}applyRealtimeUpsert(e){this.destroyed||e.length===0||(this.upsertLabelData(e),this.worker.postMessage({type:"realtime-upsert",targets:e}))}applyRealtimeRemove(e){this.destroyed||e.length===0||(this.removeLabelData(e),this.worker.postMessage({type:"realtime-remove",ids:e.slice()}))}applyPacked(e){var r;if(this.destroyed)return;e.replacePending&&this.labelDataById.clear();const n=Io(e),o=this.postWithTiming({type:"stage-packed",payload:e},n),s=((r=e.ids)==null?void 0:r.length)??e.lon.length;this.stagedUpserts=e.replacePending?s:this.stagedUpserts+s,this.stagedBatches=e.replacePending?1:this.stagedBatches+1,this.emit("perf",{phase:"worker-submit",full:this.total,batches:this.stagedBatches,upserts:s,submitMs:o}),this.config.data.leading&&this.total===0&&this.commitNow()}applyTargetStyle(e){this.destroyed||e.length===0||this.worker.postMessage({type:"style-patch",patches:e})}setBoxedTargetIds(e){this.setSelectedTargetIds(e),this.viewer.scene.requestRender()}setLabelConfig(e){this.labelConfig=Ce({...this.labelConfig,...e}),this.render.setLabelOptions(this.labelConfig,n=>this.nameplateText(n))}async selectTarget(e,n=!0){n&&this.clearSelection(!1),this.selectedIds.add(e),this.selection.setSelectedIds(Array.from(this.selectedIds));const o=await this.getPickedNode(e);return o&&this.selectedTargets.set(e,o),this.emitSelection(),o}async selectTargets(e,n=!0){n&&this.clearSelection(!1);for(const s of e)this.selectedIds.add(s);this.selection.setSelectedIds(Array.from(this.selectedIds));const o=await Promise.all(e.map(s=>this.getPickedNode(s)));for(const s of o)s&&this.selectedTargets.set(s.id,s);return this.emitSelection(),o.filter(s=>s!=null)}unselectTarget(e){this.selectedIds.delete(e),this.selectedTargets.delete(e),this.selection.setSelectedIds(Array.from(this.selectedIds)),this.emitSelection()}clearSelection(e=!0){this.selectedIds.clear(),this.selectedTargets.clear(),this.selection.setSelectedIds([]),e&&this.emitSelection()}flushNow(){this.commitNow()}getTargetSnapshot(e){if(this.destroyed)return Promise.resolve(null);const n=++this.targetQueryRequestId;return new Promise(o=>{this.targetQueryResolvers.set(n,o),this.worker.postMessage({type:"target-query",requestId:n,id:e})})}pause(){this.paused=!0}resume(){this.paused=!1,this.requestViewport("resume")}destroy(){var e,n;this.destroyed||(this.destroyed=!0,this.readyResolved||(this.readyResolved=!0,this.resolveReady()),this.commitTimer!=null&&window.clearInterval(this.commitTimer),this.rafId&&cancelAnimationFrame(this.rafId),this.hoverPickWarmupRafId&&cancelAnimationFrame(this.hoverPickWarmupRafId),this.cancelPendingHoverPick(),this.cameraMoveTrailingTimer&&window.clearTimeout(this.cameraMoveTrailingTimer),this.wheelSuppressResetTimer&&window.clearTimeout(this.wheelSuppressResetTimer),this.cameraViewportThrottleTimer&&window.clearTimeout(this.cameraViewportThrottleTimer),(e=this.removeCameraListener)==null||e.call(this),this.worker.postMessage({type:"destroy"}),this.worker.terminate(),this.models.destroy(),this.tracks.destroy(),this.selection.destroy(),this.render.destroy(),this.symbols&&this.viewer.scene.primitives.remove(this.symbols),(n=this.inputHandler)==null||n.destroy(),this.clear())}startCommitLoop(){this.commitIntervalMs<=0||(this.commitTimer=window.setInterval(()=>this.commitNow(),this.commitIntervalMs))}startRenderLoop(){const e=n=>{if(this.destroyed)return;const o=Math.max(0,(n-this.lastFrameAt)/1e3);this.lastFrameAt=n;const s=E();this.isModelRenderActive()&&this.models.update(o),this.render.update(o),this.selection.update(o),this.tracks.update(o);const r=E()-s;r>=16&&this.emit("perf",{phase:"tick-slow",at:E(),totalMs:r,flushMs:0,ingestMs:0,scanMs:0,visualMs:0,motionMs:0,renderMs:r,rendered:this.nodes.renderedCount}),this.viewportDirty&&!this.viewportInFlight?(this.viewportDirty=!1,this.requestViewport("dirty-frame")):this.shouldRefreshPredictionViewport(n)&&this.requestViewport("predict-frame"),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}commitNow(){this.destroyed||this.paused||(this.lastCommitSubmitAt=E(),this.worker.postMessage({type:"commit",requestId:++this.commitRequestId}))}requestViewportThrottled(){if(this.destroyed||this.paused)return;const e=E(),n=e-this.lastCameraViewportAt;if(n>=_t){this.lastCameraViewportAt=e,this.requestViewport("camera");return}this.cameraViewportThrottleTimer||(this.cameraViewportThrottleTimer=window.setTimeout(()=>{this.cameraViewportThrottleTimer=0,this.lastCameraViewportAt=E(),this.requestViewport("camera-trailing")},_t-n))}requestViewport(e){var v,u;if(this.destroyed||this.paused)return;const n=this.viewer.scene.camera.positionCartographic,o=n.height,s=a.Math.toDegrees(n.longitude),r=a.Math.toDegrees(n.latitude),c=a.Math.toDegrees(this.viewer.camera.pitch),d=o>=(((v=this.config.merge)==null?void 0:v.globalViewportHeight)??45e4);if(d&&this.globalViewportRevision===this.dataRevision&&!this.viewportInFlight)return;if(this.viewportInFlight){this.viewportDirty=!0;return}this.viewportInFlight=!0;const h=++this.viewportRequestId;this.viewportRequestRevisions.set(h,this.dataRevision),d&&this.globalViewportRequestIds.add(h);const m=d?{west:-180,east:180,south:-85,north:85}:this.currentBounds(),f=d?void 0:To(this.config.horizonCull,o,c);this.worker.postMessage({type:"viewport",requestId:h,bounds:m,global:d,cameraHeight:o,cameraLon:s,cameraLat:r,cameraPitch:c,horizonCullDistance:f,maxRender:((u=this.config.merge)==null?void 0:u.maxVisible)??this.config.poolSize})}handleWorkerMessage(e){if(this.destroyed)return;if(e.type==="ready"){this.readyResolved||(this.readyResolved=!0,this.resolveReady()),this.requestViewport("ready");return}if(e.type==="input"){this.emit("perf",{phase:"input",kind:e.kind,upserts:e.upserts,removes:e.removes,pendingBatches:e.pendingBatches});return}if(e.type==="commit-done"){this.total=e.size,this.stagedBatches=0,this.stagedUpserts=0,(e.added||e.updated||e.removed)&&this.dataRevision++,this.emit("perf",{phase:"worker-done",added:e.added,updated:e.updated,removed:e.removed,size:e.size,computeMs:e.computeMs,roundTripMs:E()-this.lastCommitSubmitAt}),this.emit("packedDirty",{added:void 0,updated:void 0,removed:[]}),this.requestViewport("commit");return}if(e.type==="realtime-done"){this.total=e.size,this.dataRevision++,this.emit("perf",{phase:"worker-done",added:e.upserts,updated:0,removed:e.removes,size:e.size,computeMs:e.computeMs,roundTripMs:0}),this.requestViewport("realtime");return}if(e.type==="style-done"){e.updated>0&&(this.dataRevision++,this.requestViewport("style"));return}if(e.type==="target-info"){const s=this.targetQueryResolvers.get(e.requestId);s&&(this.targetQueryResolvers.delete(e.requestId),s(e.target));return}if(e.type==="viewport-cache-ready"){this.globalViewportRevision=-1,this.requestViewport("cache-ready");return}this.viewportInFlight=!1;const n=this.viewportRequestRevisions.get(e.packet.requestId);this.viewportRequestRevisions.delete(e.packet.requestId);const o=this.globalViewportRequestIds.delete(e.packet.requestId);if(e.packet.requestId<this.viewportRequestId||n!==this.dataRevision){this.viewportDirty=!1,this.requestViewport("stale-data");return}o&&n!=null&&(this.globalViewportRevision=n),this.applyRenderPacket(e.packet),this.viewportDirty&&(this.viewportDirty=!1,this.requestViewport("queued"))}applyRenderPacket(e){const n=E();this.latestRenderPacket=e,this.hoverPickIndex=null;const o=this.isModelRenderActive(),s=o?this.models.setPacket(e):[];o||this.models.suspend(),this.render.setModelTargetIds(s,o),this.render.setPacket(e),this.updateSymbolsThrottled(e),this.selection.setPacket(e),this.tracks.setRenderPacket(e),this.scheduleHoverPickIndexWarmup(),this.applyStats(e.stats),this.applyActualRenderStats(e,this.models.renderStats()),this.viewer.scene.requestRender();const r=E()-n;(r>=12||e.computeMs>=16)&&this.emit("perf",{phase:"tick-slow",at:E(),totalMs:r+e.computeMs,flushMs:0,ingestMs:0,scanMs:e.computeMs,visualMs:0,motionMs:0,renderMs:r,rendered:e.stats.rendered})}updateSymbolsThrottled(e){if(!this.symbols)return;const n=E();this.lastSymbolsUpdateAt>0&&n-this.lastSymbolsUpdateAt<1e3||(this.lastSymbolsUpdateAt=n,this.symbols.setPacket(e))}applyStats(e){this.nodes.visibleCount=e.rawInView,this.nodes.bufferCount=Math.max(0,e.rawInBuffer-e.rawInView),this.nodes.renderedCount=e.rendered,this.nodes.clusterCount=e.clusters,this.nodes.lastMergeRadius=e.lastMergeRadius,this.nodes.pointRenderCount=e.pointCount,this.nodes.lowModelRenderCount=e.lowModelCount,this.nodes.highModelRenderCount=e.highModelCount,this.nodes.plainPointRenderCount=e.plainPointCount,this.nodes.mergedPointRenderCount=e.mergedPointCount,this.nodes.mergedLowModelRenderCount=e.mergedLowModelCount,this.nodes.mergedHighModelRenderCount=e.mergedHighModelCount,this.nodes.forcedPointMode=e.forcedPointMode,this.nodes.level=e.level,this.nodes.outsideLevel=e.outsideLevel}applyActualRenderStats(e,n){const o=n.low+n.high,s=Math.max(0,e.ids.length-o),r=e.stats.clusters;this.nodes.lowModelRenderCount=n.low,this.nodes.highModelRenderCount=n.high,this.nodes.pointRenderCount=s,this.nodes.mergedPointRenderCount=Math.min(s,r),this.nodes.plainPointRenderCount=Math.max(0,s-this.nodes.mergedPointRenderCount),this.nodes.mergedLowModelRenderCount=0,this.nodes.mergedHighModelRenderCount=0}shouldRefreshPredictionViewport(e){if(this.viewportInFlight||this.paused||this.destroyed||!this.isModelRenderActive()||!this.latestRenderPacket||!xo(this.latestRenderPacket))return!1;const n=1e3/Math.max(1,this.config.updateFps);return e-this.lastPredictionViewportAt<n?!1:(this.lastPredictionViewportAt=e,!0)}async handlePickAt(e){const n=this.pickTargetId(e,Ht),o=++this.pickRequestSerial;if(!n){this.clearSelection(),this.emit("pick",null);return}const s=await this.selectTarget(n,!0);o===this.pickRequestSerial&&this.emit("pick",s)}async handleContextMenuAt(e){const n=++this.contextMenuRequestSerial,o=this.pickTargetId(e,Ht),s=this.pickGroundCartesian(e,new a.Cartesian3);let r=null;if(o&&(r=this.hoverTargetCache.get(o)??await this.getPickedNode(o)),n!==this.contextMenuRequestSerial)return;if(r){const h=this.getRenderedTargetPosition(r.id,new a.Cartesian3)??a.Cartesian3.fromDegrees(r.data.lon,r.data.lat,r.data.height,void 0,new a.Cartesian3);this.emit("contextmenu",{kind:"target",target:r,screenX:e.x,screenY:e.y,cartesian:h,lon:r.data.lon,lat:r.data.lat,height:r.data.height});return}if(!s){this.emit("contextmenu",null);return}const c=a.Math.toDegrees,d=this.viewer.scene.globe.ellipsoid.cartesianToCartographic(s);this.emit("contextmenu",{kind:"ground",target:null,screenX:e.x,screenY:e.y,cartesian:a.Cartesian3.clone(s,new a.Cartesian3),lon:c(d.longitude),lat:c(d.latitude),height:d.height})}bindHoverSuppressionInput(){var e,n,o,s,r,c,d;(e=this.inputHandler)==null||e.setInputAction(()=>{this.pointerButtonsMask|=1,this.onViewManipulationStart()},a.ScreenSpaceEventType.LEFT_DOWN),(n=this.inputHandler)==null||n.setInputAction(()=>{this.pointerButtonsMask&=-2},a.ScreenSpaceEventType.LEFT_UP),(o=this.inputHandler)==null||o.setInputAction(()=>{this.pointerButtonsMask|=2,this.onViewManipulationStart()},a.ScreenSpaceEventType.RIGHT_DOWN),(s=this.inputHandler)==null||s.setInputAction(()=>{this.pointerButtonsMask&=-3},a.ScreenSpaceEventType.RIGHT_UP),(r=this.inputHandler)==null||r.setInputAction(()=>{this.pointerButtonsMask|=4,this.onViewManipulationStart()},a.ScreenSpaceEventType.MIDDLE_DOWN),(c=this.inputHandler)==null||c.setInputAction(()=>{this.pointerButtonsMask&=-5},a.ScreenSpaceEventType.MIDDLE_UP),(d=this.inputHandler)==null||d.setInputAction(()=>{this.noteWheelInteraction()},a.ScreenSpaceEventType.WHEEL)}scheduleHoverPick(e){if(!(this.destroyed||!this.config.pick.hover)){if(this.noteHoverPointerSample(e),this.hoverPickPosition){const n=Math.abs(e.x-this.hoverPickPosition.x),o=Math.abs(e.y-this.hoverPickPosition.y);if(n<At&&o<At)return;a.Cartesian2.clone(e,this.hoverPickPosition)}else this.hoverPickPosition=a.Cartesian2.clone(e);this.shouldSkipHoverPick()||this.hoverPickRafId||(this.hoverPickRafId=requestAnimationFrame(()=>this.flushHoverPick()))}}flushHoverPick(){if(this.hoverPickRafId=0,this.destroyed||!this.hoverPickPosition||this.shouldSkipHoverPick())return;const e=E();if(e-this.lastHoverPickAt<mo){this.hoverPickRafId=requestAnimationFrame(()=>this.flushHoverPick());return}this.lastHoverPickAt=e,this.handleHoverAt(this.hoverPickPosition)}async handleHoverAt(e){if(this.hoverPointerSpeedPxPerMs>go){this.lastHoverId!=null&&(this.lastHoverId=null,this.hoverRequestSerial++,this.selection.setHoveredId(null),this.emit("hover",null));return}const n=this.pickIndexedTargetId(e,1);if(n===this.lastHoverId)return;this.lastHoverId=n;const o=++this.hoverRequestSerial;if(!n){this.selection.setHoveredId(null),this.emit("hover",null);return}this.selection.setHoveredId(n);const s=this.hoverTargetCache.get(n);if(s){this.emit("hover",s);return}const r=await this.getPickedNode(n);o===this.hoverRequestSerial&&(r&&this.cacheHoverTarget(r),this.selection.setHoveredId((r==null?void 0:r.id)??null),this.emit("hover",r))}pickIndexedTargetId(e,n){const o=this.ensureHoverPickIndex();if(!o)return null;const s=Math.floor(e.x/o.cellSize),r=Math.floor(e.y/o.cellSize);let c=null,d=Number.POSITIVE_INFINITY;for(let h=r-1;h<=r+1;h++)for(let m=s-1;m<=s+1;m++){const f=o.bins.get(Bt(m,h));if(f)for(const v of f){const u=Math.max(1,n,o.hitRadius[v]),p=u*u,g=o.windowX[v]-e.x,y=o.windowY[v]-e.y,w=g*g+y*y;if(w>p||w>d)continue;const M=o.ids[v];!M||M.startsWith("cluster:")||(d=w,c=M)}}return c}ensureHoverPickIndex(){var m;const e=this.latestRenderPacket;if(!e||e.ids.length===0)return null;const n=this.viewer.scene.canvas;if(this.hoverPickIndex&&this.hoverPickIndex.requestId===e.requestId&&this.hoverPickIndex.cameraRevision===this.cameraRevision&&this.hoverPickIndex.canvasWidth===n.clientWidth&&this.hoverPickIndex.canvasHeight===n.clientHeight)return this.hoverPickIndex;const o=new Float32Array(e.ids.length),s=new Float32Array(e.ids.length),r=new Float32Array(e.ids.length);let c=this.config.pick.pixelThreshold*Lt;s.fill(Number.NaN),r.fill(Number.NaN);for(let f=0;f<e.ids.length;f++){if(!(e.flags[f]&So)||e.count[f]!==1)continue;const v=a.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene,a.Cartesian3.fromDegrees(e.lon[f],e.lat[f],e.height[f]));if(!v)continue;const u=v.x,p=v.y;if(!Number.isFinite(u)||!Number.isFinite(p)||u<0||p<0||u>n.clientWidth||p>n.clientHeight)continue;const g=e.category[f]??0,y=((m=this.config.renderTypes[g])==null?void 0:m.type)??"",w=st(y,e.size[f],e.count[f]>1),M=Math.max(1,w*.5*po);o[f]=M,c=Math.max(c,M),s[f]=u,r[f]=p}const d=Math.max(wo,c*2),h=new Map;for(let f=0;f<e.ids.length;f++){const v=s[f],u=r[f];if(!Number.isFinite(v)||!Number.isFinite(u))continue;const p=Bt(Math.floor(v/d),Math.floor(u/d)),g=h.get(p);g?g.push(f):h.set(p,[f])}return this.hoverPickIndex={requestId:e.requestId,ids:e.ids.slice(),cameraRevision:this.cameraRevision,canvasWidth:n.clientWidth,canvasHeight:n.clientHeight,cellSize:d,bins:h,windowX:s,windowY:r,hitRadius:o},this.hoverPickIndex}pickTargetId(e,n){const o=this.pickIndexedTargetId(e,Math.max(18,this.config.pick.pixelThreshold*1.25)*Lt);if(o)return o;const s=this.viewer.scene.pick(e,1,1),r=Ft(s);if(r||n<=0)return r;const c=this.viewer.scene.drillPick(e,n,1,1)??[];for(const d of c){const h=Ft(d);if(h)return h}return null}getRenderedTargetFrame(e,n=new a.Cartesian3){var o;return this.models.getTargetFrame(e,n)??this.render.getTargetFrame(e,n)??((o=this.symbols)==null?void 0:o.getTargetFrame(e,n))}getRenderedTargetPosition(e,n=new a.Cartesian3){const o=this.latestRenderPacket;if(!o)return null;const s=o.ids.indexOf(e);return s<0||o.count[s]!==1?null:a.Cartesian3.fromDegrees(o.lon[s],o.lat[s],o.height[s],void 0,n)}pickGroundCartesian(e,n){const o=this.viewer.scene;if(o.pickPositionSupported&&typeof o.pickPosition=="function"){const d=o.pickPosition(e);if(d)return a.Cartesian3.clone(d,n)}const r=this.viewer.camera.getPickRay(e);if(!r)return null;const c=o.globe.pick(r,o);return c?a.Cartesian3.clone(c,n):null}shouldSkipHoverPick(){return this.pointerButtonsMask!==0||this.cameraMoving||E()<this.wheelSuppressPickUntil}noteHoverPointerSample(e){const n=E(),o=this.lastHoverPointerSample;if(!o){this.lastHoverPointerSample={x:e.x,y:e.y,at:n},this.hoverPointerSpeedPxPerMs=0;return}const s=Math.max(1,n-o.at),r=e.x-o.x,c=e.y-o.y,d=Math.sqrt(r*r+c*c)/s;this.hoverPointerSpeedPxPerMs=d*Et+this.hoverPointerSpeedPxPerMs*(1-Et),o.x=e.x,o.y=e.y,o.at=n}cancelPendingHoverPick(){this.hoverPickRafId&&(cancelAnimationFrame(this.hoverPickRafId),this.hoverPickRafId=0)}onViewManipulationStart(){this.cancelPendingHoverPick(),this.lastHoverPointerSample=null,this.hoverPointerSpeedPxPerMs=0,this.lastHoverId!=null&&(this.lastHoverId=null,this.hoverRequestSerial++,this.selection.setHoveredId(null),this.emit("hover",null))}noteWheelInteraction(){this.lastHoverPointerSample=null,this.hoverPointerSpeedPxPerMs=0,this.wheelSuppressPickUntil=E()+Dt,this.wheelSuppressResetTimer&&window.clearTimeout(this.wheelSuppressResetTimer),this.wheelSuppressResetTimer=window.setTimeout(()=>{this.wheelSuppressResetTimer=0,this.wheelSuppressPickUntil=0},Dt),this.onViewManipulationStart()}noteCameraMovement(){this.config.pick.hover&&(this.cameraRevision++,this.hoverPickIndex=null,this.cameraMoving=!0,this.lastHoverPointerSample=null,this.hoverPointerSpeedPxPerMs=0,this.onViewManipulationStart(),this.cameraMoveTrailingTimer&&window.clearTimeout(this.cameraMoveTrailingTimer),this.cameraMoveTrailingTimer=window.setTimeout(()=>{this.cameraMoveTrailingTimer=0,this.cameraMoving=!1,this.scheduleHoverPickIndexWarmup()},vo))}scheduleHoverPickIndexWarmup(){this.destroyed||!this.config.pick.hover||this.hoverPickWarmupRafId||this.hoverPickIndex||!this.latestRenderPacket||(this.hoverPickWarmupRafId=requestAnimationFrame(()=>{this.hoverPickWarmupRafId=0,!(this.destroyed||this.cameraMoving||!this.latestRenderPacket||this.hoverPickIndex)&&this.ensureHoverPickIndex()}))}cacheHoverTarget(e){if(this.hoverTargetCache.set(e.id,e),this.hoverTargetCache.size<=yo)return;const n=this.hoverTargetCache.keys().next().value;n&&this.hoverTargetCache.delete(n)}async getPickedNode(e){const n=await this.getTargetSnapshot(e);if(!n)return null;const o=Ro(n),s=this.labelDataById.get(e);return s?{...o,data:{...o.data,nationality:s.nationality,customInfo:s.customInfo}}:o}replaceLabelData(e){this.labelDataById.clear(),this.upsertLabelData(e)}applyLabelIncremental(e){var n,o;(n=e.removes)!=null&&n.length&&this.removeLabelData(e.removes),(o=e.upserts)!=null&&o.length&&this.upsertLabelData(e.upserts)}upsertLabelData(e){for(const n of e)this.labelDataById.set(n.id,n);this.hoverTargetCache.clear()}removeLabelData(e){for(const n of e)this.labelDataById.delete(n);this.hoverTargetCache.clear()}nameplateText(e){var h,m,f,v;const n=e.data??this.labelDataById.get(e.id),o=n&&n!==e.data?{...e,data:n,type:n.type??e.type}:e,s=(m=(h=this.labelConfig).resolve)==null?void 0:m.call(h,o);if(s!==void 0)return s;if(o.count>1)return`merged x${o.count}`;if(!n)return e.id;const r=(f=this.labelConfig.byType)==null?void 0:f[o.type];if((r==null?void 0:r.maxCameraHeight)!=null&&o.cameraHeight>r.maxCameraHeight)return null;const c=(r==null?void 0:r.fields)??this.labelConfig.fields,d=[];for(const u of c){if(!Ao(u,o.cameraHeight))continue;const p=u.source==="custom"?(v=n.customInfo)==null?void 0:v[u.key]:n[u.key],g=ko(p,u.fallback);g&&d.push(this.labelConfig.showFieldLabels===!1||!u.label?g:`${u.label}: ${g}`)}return d.length?d:null}setSelectedTargetIds(e){this.selectedIds.clear();for(const n of e)this.selectedIds.add(n);this.selection.setSelectedIds(Array.from(this.selectedIds)),Promise.all(e.map(n=>this.getPickedNode(n))).then(n=>{this.selectedTargets.clear();for(const o of n)o&&this.selectedTargets.set(o.id,o);this.emitSelection()})}emitSelection(){const e=[];for(const n of this.selectedIds){const o=this.selectedTargets.get(n);o&&e.push(o)}this.emit("selection",e)}isModelRenderActive(){return this.viewer.scene.camera.positionCartographic.height<=this.config.lod.pointAbove}currentBounds(){const e=this.viewer.camera.computeViewRectangle();if(!e)return{west:-180,east:180,south:-85,north:85};const n=a.Math.toDegrees(e.west),o=a.Math.toDegrees(e.east),s=a.Math.toDegrees(e.south),r=a.Math.toDegrees(e.north);return!Number.isFinite(n)||!Number.isFinite(o)||o<=n?{west:-180,east:180,south:-85,north:85}:{west:n,east:o,south:s,north:r}}postWithTiming(e,n){const o=E();return this.worker.postMessage(e,n??[]),E()-o}}function Io(i){const t=[];return X(t,i.lon),X(t,i.lat),X(t,i.height),X(t,i.speedH),X(t,i.speedV),X(t,i.heading),X(t,i.secrecy),X(t,i.renderColor),X(t,i.animate),X(t,i.animateColor),t}function X(i,t){t&&t.buffer instanceof ArrayBuffer&&!i.includes(t.buffer)&&i.push(t.buffer)}function xo(i){for(let t=0;t<i.flags.length;t++)if(i.flags[t]&Mo)return!0;return!1}function E(){return typeof performance<"u"?performance.now():Date.now()}function Bt(i,t){return`${i}:${t}`}function To(i,t,e){if(i.enabled&&!(t>i.maxCameraHeight)&&!(e<i.pitchThreshold))return bo(t*i.cameraHeightMultiplier,i.minDistance,i.maxDistance)}function bo(i,t,e){return Math.max(t,Math.min(e,i))}function De(i){return{type:i.type,targetDomain:i.targetDomain,iconPath:i.iconPath,defaultColor:i.defaultColor,pointHeadingOffset:i.pointHeadingOffset,lowModel:i.lowModel,highModel:i.highModel,lowModelUrl:i.lowModelUrl,highModelUrl:i.highModelUrl,scale:i.scale,modelHeadingOffset:i.modelHeadingOffset,modelPitchOffset:i.modelPitchOffset,modelRollOffset:i.modelRollOffset,predictMove:i.predictMove,predictMinCameraHeight:i.predictMinCameraHeight,predictSeconds:i.predictSeconds,predictFitSeconds:i.predictFitSeconds}}function Po(i){const t=i.startsWith("#")?i.slice(1):i;if(t.length!==6&&t.length!==8)return 16777215;const e=t.length===8?t.slice(0,6):t,n=Number.parseInt(e,16);return Number.isFinite(n)?n:16777215}function Ft(i){var e,n,o;if(!i)return null;const t=[i.id,(e=i.primitive)==null?void 0:e.id,(n=i.collection)==null?void 0:n.id,(o=i.id)==null?void 0:o.id];for(const s of t){const r=Co(s);if(r)return r}return null}function Co(i){if(typeof i=="string")return i;if(!i||typeof i!="object")return null;const t=i;return typeof t.targetId=="string"?t.targetId:typeof t.id=="string"?t.id:null}function Ro(i){return{id:i.id,type:i.type,data:{id:i.id,type:i.type,lon:i.lon,lat:i.lat,height:i.height,speedH:i.speedH,speedV:0,heading:i.heading,renderColor:i.renderColor,openAnimate:i.openAnimate,animateColor:i.animateColor,nationality:i.nationality,customInfo:i.customInfo,extra:i.hidden?{hidden:!0}:void 0}}}function ko(i,t){if(i==null||i==="")return t??"";if(typeof i=="string")return i;if(typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return String(i);if(i instanceof Date)return i.toISOString();try{return JSON.stringify(i)}catch{return t??""}}function Ao(i,t){return!(i.minCameraHeight!=null&&t<i.minCameraHeight||i.maxCameraHeight!=null&&t>i.maxCameraHeight)}function Nt(){const i=new Map,t=new Map,e={register(n,o,s){if(i.has(n))throw new Error(`[web-event-bus] Action "${n}" is already registered.`);i.set(n,{action:n,handler:o,owner:s==null?void 0:s.owner,description:s==null?void 0:s.description})},unregister(n){i.delete(n)},unregisterAll(n){for(const[o,s]of i)s.owner===n&&i.delete(o)},emit(n,o){const s=t.get(n);if(s)for(const r of s)try{r(o)}catch(c){console.error(`[web-event-bus] Listener error on "${n}":`,c)}},on(n,o){return t.has(n)||t.set(n,new Set),t.get(n).add(o),()=>{e.off(n,o)}},off(n,o){const s=t.get(n);s&&(s.delete(o),s.size===0&&t.delete(n))},async invoke(n,o){const s=i.get(n);if(!s)throw new Error(`[web-event-bus] Action "${n}" is not registered. Cannot invoke.`);return await s.handler(o)},has(n){return i.has(n)},inspect(){return Array.from(i.values()).map(({handler:n,...o})=>o)}};return e}var _e="__WEB_EVENT_BUS__";function Lo(){if(typeof window>"u")throw new Error("[web-event-bus] getGlobalBus() requires a browser environment (window).");return window[_e]||(window[_e]=Nt()),window[_e]}const F={scene:{perf:"mtf.scene.perf",dirty:"mtf.scene.dirty",packedDirty:"mtf.scene.packedDirty",pick:"mtf.scene.pick",hover:"mtf.scene.hover",selection:"mtf.scene.selection",contextmenu:"mtf.scene.contextmenu"},track:{hover:"mtf.track.hover"},site:{contextmenu:"mtf.site.contextmenu",pick:"mtf.site.pick",hover:"mtf.site.hover"}},C={framework:{addTarget:"mtf.framework.addTarget",updateTarget:"mtf.framework.updateTarget",setTargetData:"mtf.framework.setTargetData",upsertTargetData:"mtf.framework.upsertTargetData",removeTargetData:"mtf.framework.removeTargetData",applyTargetIncremental:"mtf.framework.applyTargetIncremental",setTargetColor:"mtf.framework.setTargetColor",setTargetGlow:"mtf.framework.setTargetGlow",hideTarget:"mtf.framework.hideTarget",showTarget:"mtf.framework.showTarget",disappearTarget:"mtf.framework.disappearTarget",appearTarget:"mtf.framework.appearTarget",setNameplateConfig:"mtf.framework.setNameplateConfig",selectTarget:"mtf.framework.selectTarget",selectTargets:"mtf.framework.selectTargets",unselectTarget:"mtf.framework.unselectTarget",clearSelection:"mtf.framework.clearSelection",boxTarget:"mtf.framework.boxTarget",unboxTarget:"mtf.framework.unboxTarget",locateTarget:"mtf.framework.locateTarget",registerContextMenuItem:"mtf.framework.registerContextMenuItem",showContextMenu:"mtf.framework.showContextMenu",closeContextMenu:"mtf.framework.closeContextMenu",destroy:"mtf.framework.destroy"},tracks:{setTracks:"mtf.tracks.setTracks",getTracks:"mtf.tracks.getTracks",showTracks:"mtf.tracks.showTracks",hideTracks:"mtf.tracks.hideTracks",removeTracks:"mtf.tracks.removeTracks",clearTracks:"mtf.tracks.clearTracks"},site:{setData:"mtf.site.setData",clear:"mtf.site.clear",pickAt:"mtf.site.pickAt",destroy:"mtf.site.destroy"}},Eo="cesium-multi-target-framework";let zt=0;function Vt(){return Lo()}function Oe(){try{return Vt()}catch{return null}}function Ho(){return Nt()}function Wt(i,t={}){const e=t.bus??Oe(),n=t.owner??Zt("framework");if(!e)return Gt(n);const o=[],s=[];return t.registerActions!==!1&&Do(e,i,n,t.replaceExisting===!0,s),t.bridgeEvents!==!1&&o.push(...Oo(e,i)),Xt(e,n,o,s)}function Ut(i,t={}){const e=t.bus??Oe(),n=t.owner??Zt("site");if(!e)return Gt(n);const o=[],s=[];return t.registerActions!==!1&&_o(e,i,n,t.replaceExisting===!0,s),t.bridgeEvents!==!1&&o.push(...Bo(e,i)),Xt(e,n,o,s)}function Do(i,t,e,n,o){R(i,C.framework.addTarget,({target:s})=>t.addTarget(s),e,n,o),R(i,C.framework.updateTarget,({target:s})=>t.updateTarget(s),e,n,o),R(i,C.framework.setTargetData,({targets:s})=>t.setTargetData(s),e,n,o),R(i,C.framework.upsertTargetData,({targets:s})=>t.upsertTargetData(s),e,n,o),R(i,C.framework.removeTargetData,({ids:s})=>t.removeTargetData(s),e,n,o),R(i,C.framework.applyTargetIncremental,({payload:s})=>t.applyTargetIncremental(s),e,n,o),R(i,C.framework.setTargetColor,({id:s,color:r,options:c})=>t.setTargetColor(s,r,c),e,n,o),R(i,C.framework.setTargetGlow,({id:s,enabled:r,color:c,options:d})=>t.setTargetGlow(s,r,c,d),e,n,o),R(i,C.framework.hideTarget,({id:s,options:r})=>t.hideTarget(s,r),e,n,o),R(i,C.framework.showTarget,({id:s,options:r})=>t.showTarget(s,r),e,n,o),R(i,C.framework.disappearTarget,({id:s,options:r})=>t.disappearTarget(s,r),e,n,o),R(i,C.framework.appearTarget,({id:s,options:r})=>t.appearTarget(s,r),e,n,o),R(i,C.framework.setNameplateConfig,({config:s})=>t.setNameplateConfig(s),e,n,o),R(i,C.framework.selectTarget,({id:s,options:r})=>t.selectTarget(s,r),e,n,o),R(i,C.framework.selectTargets,({ids:s,options:r})=>t.selectTargets(s,r),e,n,o),R(i,C.framework.unselectTarget,({id:s})=>t.unselectTarget(s),e,n,o),R(i,C.framework.clearSelection,()=>t.clearSelection(),e,n,o),R(i,C.framework.boxTarget,({id:s,enabled:r,options:c})=>t.boxTarget(s,r,c),e,n,o),R(i,C.framework.unboxTarget,({id:s,options:r})=>t.unboxTarget(s,r),e,n,o),R(i,C.framework.locateTarget,({id:s,options:r})=>t.locateTarget(s,r),e,n,o),R(i,C.framework.registerContextMenuItem,({item:s})=>t.registerContextMenuItem(s),e,n,o),R(i,C.framework.showContextMenu,({context:s})=>t.showContextMenu(s),e,n,o),R(i,C.framework.closeContextMenu,()=>t.closeContextMenu(),e,n,o),R(i,C.framework.destroy,()=>t.destroy(),e,n,o),R(i,C.tracks.setTracks,({tracks:s})=>t.tracks.setTracks(s),e,n,o),R(i,C.tracks.getTracks,s=>t.tracks.getTracks(s==null?void 0:s.targetIds),e,n,o),R(i,C.tracks.showTracks,({targetIds:s})=>t.tracks.showTracks(s),e,n,o),R(i,C.tracks.hideTracks,({targetIds:s})=>t.tracks.hideTracks(s),e,n,o),R(i,C.tracks.removeTracks,({targetIds:s})=>t.tracks.removeTracks(s),e,n,o),R(i,C.tracks.clearTracks,()=>t.tracks.clearTracks(),e,n,o)}function _o(i,t,e,n,o){R(i,C.site.setData,({sites:s})=>t.setData(s),e,n,o),R(i,C.site.clear,()=>t.clear(),e,n,o),R(i,C.site.pickAt,({position:s,thresholdPx:r})=>t.pickAt(s,r),e,n,o),R(i,C.site.destroy,()=>t.destroy(),e,n,o)}function Oo(i,t){return[t.scene.on("perf",e=>V(i,F.scene.perf,e)),t.scene.on("dirty",e=>V(i,F.scene.dirty,e)),t.scene.on("packedDirty",e=>V(i,F.scene.packedDirty,e)),t.scene.on("pick",e=>V(i,F.scene.pick,e)),t.scene.on("hover",e=>V(i,F.scene.hover,e)),t.scene.on("selection",e=>V(i,F.scene.selection,e)),t.scene.on("contextmenu",e=>V(i,F.scene.contextmenu,e)),t.tracks.on("hover",e=>V(i,F.track.hover,e))]}function Bo(i,t){return[t.on("contextmenu",e=>V(i,F.site.contextmenu,e)),t.on("pick",e=>V(i,F.site.pick,e)),t.on("hover",e=>V(i,F.site.hover,e))]}function R(i,t,e,n,o,s){if(i.has(t)){if(!o)return;i.unregister(t)}i.register(t,e,{owner:n}),s.push(t)}function V(i,t,e){try{i.emit(t,e)}catch{}}function Xt(i,t,e,n){let o=!1;return{active:!0,owner:t,dispose(){if(!o){o=!0;for(const s of e.splice(0))s();for(const s of n.splice(0))Fo(i,s,t)&&i.unregister(s)}}}}function Gt(i){return{active:!1,owner:i,dispose(){}}}function Zt(i){return zt++,`${Eo}:${i}:${zt}`}function Fo(i,t,e){try{return i.inspect().some(n=>n.action===t&&n.owner===e)}catch{return!1}}class ye{constructor(t,e){l(this,"scene");l(this,"viewer");l(this,"tracks");l(this,"ready");l(this,"boxedTargetIds",new Set);l(this,"contextMenuItems",new Map);l(this,"contextMenuRoot");l(this,"contextMenuList");l(this,"removeSceneContextMenuListener");l(this,"eventBusBinding");l(this,"handleDocumentPointerDownBound");l(this,"handleKeyDownBound");l(this,"activeContextMenuContext",null);const n=zo(e);this.viewer=t,this.scene=new Ot(t,n),this.ready=this.scene.ready,this.tracks=this.scene.tracks,this.contextMenuRoot=Zo(),this.contextMenuList=document.createElement("div"),this.contextMenuList.className="mtf-context-menu-list",this.contextMenuRoot.appendChild(this.contextMenuList),document.body.appendChild(this.contextMenuRoot),this.removeSceneContextMenuListener=this.scene.on("contextmenu",o=>{this.handleSceneContextMenu(o)}),this.handleDocumentPointerDownBound=o=>this.handleDocumentPointerDown(o),this.handleKeyDownBound=o=>this.handleDocumentKeyDown(o),document.addEventListener("pointerdown",this.handleDocumentPointerDownBound,!0),document.addEventListener("keydown",this.handleKeyDownBound),this.eventBusBinding=Wt(this,{replaceExisting:!0})}setData(t){this.setTargetData(t)}upsert(t){this.upsertTargetData(t)}remove(t){this.removeTargetData(t)}addTarget(t){return this.updateTarget(t)}updateTarget(t){const[e]=we([t],this.scene.config.nodeTypes);return this.scene.applyRealtimeUpsert([e]),e}setTargetData(t){this.scene.setData(we(t,this.scene.config.nodeTypes))}upsertTargetData(t){this.scene.applyIncremental({upserts:we(t,this.scene.config.nodeTypes)})}removeTargetData(t){this.scene.applyRealtimeRemove(t)}applyTargetIncremental(t){var e;this.scene.applyIncremental({upserts:t.upserts?we(t.upserts,this.scene.config.nodeTypes):void 0,removes:(e=t.removes)==null?void 0:e.slice()})}setTargetColor(t,e,n){const o=ie(t);Me(e,"color");const s=te(n);this.scene.applyTargetStyle(o.map((r,c)=>({id:r,styleKind:"color",clearBefore:s&&c===0,renderColor:e})))}setTargetGlow(t,e=!0,n,o){const s=ie(t);n&&Me(n,"color");const r=te(o);this.scene.applyTargetStyle(s.map((c,d)=>({id:c,styleKind:"glow",clearBefore:r&&d===0,openAnimate:e,animateType:e?"发光":void 0,animateColor:n})))}hideTarget(t,e){const n=ie(t),o=te(e);this.scene.applyTargetStyle(n.map((s,r)=>({id:s,styleKind:"hidden",clearBefore:o&&r===0,hidden:!0})))}showTarget(t,e){const n=ie(t),o=te(e);this.scene.applyTargetStyle(n.map((s,r)=>({id:s,styleKind:"hidden",clearBefore:o&&r===0,hidden:!1})))}disappearTarget(t,e){this.hideTarget(t,e)}appearTarget(t,e){this.showTarget(t,e)}setNameplateConfig(t){this.scene.setLabelConfig(t)}async selectTarget(t,e){$(t,"id");const n=await this.scene.selectTarget(t,te(e));return n?Yt(n):null}async selectTargets(t,e){const n=ie(t);return(await this.scene.selectTargets(n,te(e))).map(Yt)}unselectTarget(t){$(t,"id"),this.boxedTargetIds.delete(t),this.scene.unselectTarget(t)}clearSelection(){this.boxedTargetIds.clear(),this.scene.clearSelection()}boxTarget(t,e=!0,n){const o=ie(t);te(n)&&this.boxedTargetIds.clear();for(const s of o)e?this.boxedTargetIds.add(s):this.boxedTargetIds.delete(s);this.scene.setBoxedTargetIds(Array.from(this.boxedTargetIds))}unboxTarget(t,e){this.boxTarget(t,!1,e)}async locateTarget(t,e={}){$(t,"id");const n=await this.scene.getTargetSnapshot(t);if(!n)return null;const o=e.range??e.height??18e3,s=a.Cartesian3.fromDegrees(n.lon,n.lat,n.height),r=a.Transforms.eastNorthUpToFixedFrame(s),c=new a.HeadingPitchRange(a.Math.toRadians(e.heading??0),a.Math.toRadians(e.pitch??-65),o);return this.viewer.camera.flyToBoundingSphere(new a.BoundingSphere(s,1),{duration:e.duration??.8,offset:c,complete:()=>{this.viewer.camera.lookAtTransform(r,c),this.viewer.camera.lookAtTransform(a.Matrix4.IDENTITY)}}),n}registerContextMenuItem(t){var n;if($(t.key,"context menu item key"),$(t.label,"context menu item label"),typeof t.onClick!="function")throw new Error("context menu item onClick must be a function.");const e={...t,targetKinds:(n=t.targetKinds)!=null&&n.length?[...t.targetKinds]:["target"],order:t.order??0};return this.contextMenuItems.set(e.key,e),()=>{this.contextMenuItems.get(e.key)===e&&(this.contextMenuItems.delete(e.key),this.activeContextMenuContext&&this.renderContextMenu(this.activeContextMenuContext))}}async showContextMenu(t){await this.renderContextMenu(t)}closeContextMenu(){this.activeContextMenuContext=null,this.contextMenuRoot.style.display="none",this.contextMenuRoot.style.left="-9999px",this.contextMenuRoot.style.top="-9999px",this.contextMenuList.innerHTML=""}destroy(){this.eventBusBinding.dispose(),this.closeContextMenu(),this.removeSceneContextMenuListener(),document.removeEventListener("pointerdown",this.handleDocumentPointerDownBound,!0),document.removeEventListener("keydown",this.handleKeyDownBound),this.contextMenuRoot.remove(),this.scene.destroy()}static async create(t,e){const n=new ye(t,e);return await n.ready,n}async handleSceneContextMenu(t){if(!t){this.closeContextMenu();return}const e=await this.toContextMenuContext(t);if(!e){this.closeContextMenu();return}await this.renderContextMenu(e)}async toContextMenuContext(t){if(t.kind==="target"&&t.target){const e=await this.scene.getTargetSnapshot(t.target.id);return e?{screenX:t.screenX,screenY:t.screenY,cartesian:t.cartesian?a.Cartesian3.clone(t.cartesian,new a.Cartesian3):void 0,target:{kind:"target",id:e.id,type:e.type,data:e},viewer:this.viewer,scene:this.scene,framework:this}:null}return t.kind==="ground"&&t.lon!=null&&t.lat!=null&&t.height!=null?{screenX:t.screenX,screenY:t.screenY,cartesian:t.cartesian?a.Cartesian3.clone(t.cartesian,new a.Cartesian3):void 0,target:{kind:"ground",lon:t.lon,lat:t.lat,height:t.height},viewer:this.viewer,scene:this.scene,framework:this}:null}async renderContextMenu(t){const e=this.resolveVisibleContextMenuItems(t);if(e.length===0){this.closeContextMenu();return}this.activeContextMenuContext=t,this.contextMenuList.innerHTML="";for(const n of e){const o=document.createElement("button");o.type="button",o.className="mtf-context-menu-item",o.textContent=n.label,o.addEventListener("click",()=>{this.closeContextMenu(),n.onClick(t)}),this.contextMenuList.appendChild(o)}this.contextMenuRoot.style.display="block",this.contextMenuRoot.style.left=`${t.screenX}px`,this.contextMenuRoot.style.top=`${t.screenY}px`,requestAnimationFrame(()=>this.repositionContextMenu())}resolveVisibleContextMenuItems(t){const e=Array.from(this.contextMenuItems.values());return e.sort((n,o)=>(n.order??0)-(o.order??0)||n.label.localeCompare(o.label,"zh-CN")),e.filter(n=>n.targetKinds.includes(t.target.kind)?n.visible?n.visible(t)!==!1:!0:!1)}repositionContextMenu(){if(this.contextMenuRoot.style.display==="none")return;const t=8,e=this.contextMenuRoot.offsetWidth,n=this.contextMenuRoot.offsetHeight,o=Math.max(t,window.innerWidth-e-t),s=Math.max(t,window.innerHeight-n-t),r=Number.parseFloat(this.contextMenuRoot.style.left||"0"),c=Number.parseFloat(this.contextMenuRoot.style.top||"0"),d=Math.min(Math.max(t,r),o),h=Math.min(Math.max(t,c),s);this.contextMenuRoot.style.left=`${d}px`,this.contextMenuRoot.style.top=`${h}px`}handleDocumentPointerDown(t){if(this.contextMenuRoot.style.display==="none")return;const e=t.target;e instanceof Node&&this.contextMenuRoot.contains(e)||this.closeContextMenu()}handleDocumentKeyDown(t){t.key==="Escape"&&this.closeContextMenu()}}function No(i,t){return ye.create(i,t)}function zo(i){if(!i.targetTypes.length)throw new Error("MultiTargetFramework requires at least one target type config.");return{...i.scene??{},nodeTypes:i.targetTypes.map(Vo)}}function Vo(i){return{name:i.name??i.type,type:i.type,targetDomain:i.targetDomain,forceHighModelInLowLod:i.forceHighModelInLowLod,iconPath:i.iconPath,defaultColor:i.defaultColor,highModel:i.highModel,lowModel:i.lowModel,highModelUrl:i.highModelUrl,lowModelUrl:i.lowModelUrl,pointPixelSize:i.pointPixelSize,pointHeadingOffset:i.pointHeadingOffset,scale:i.scale,modelHeadingOffset:i.modelHeadingOffset,modelPitchOffset:i.modelPitchOffset,modelRollOffset:i.modelRollOffset,smoothMove:i.smoothMove??!1,smoothMoveMinCameraHeight:i.smoothMoveMinCameraHeight??25e3,smoothMoveDurationMs:i.smoothMoveDurationMs??i.moveAnimationDurationMs??400,predictMove:i.predictMove??i.predict??!1,predictMinCameraHeight:i.predictMinCameraHeight??25e3,predictSeconds:i.predictSeconds,predictFitSeconds:i.predictFitSeconds}}function we(i,t){return i.map((e,n)=>{if(!e||typeof e!="object")throw new Error(`Invalid target at index ${n}.`);if(Uo(e,`targets[${n}]`),$(e.id,`targets[${n}].id`),$(e.type,`targets[${n}].type`),!t.has(e.type))throw new Error(`Unknown target type "${e.type}" at index ${n}.`);return ne(e.lon,`targets[${n}].lon`),ne(e.lat,`targets[${n}].lat`),ne(e.height,`targets[${n}].height`),ne(e.speedH,`targets[${n}].speedH`),ne(e.speedV,`targets[${n}].speedV`),ne(e.heading,`targets[${n}].heading`),e.renderColor&&Me(e.renderColor,`targets[${n}].renderColor`),e.animateColor&&Me(e.animateColor,`targets[${n}].animateColor`),e.nationality!=null&&Xo(e.nationality,`targets[${n}].nationality`),e.customInfo!=null&&Go(e.customInfo,`targets[${n}].customInfo`),{...e}})}const Wo=new Set(["id","type","lon","lat","height","speedH","speedV","heading","renderColor","openAnimate","animateType","animateColor","nationality","customInfo","track","secrecy","extra"]);function Uo(i,t){for(const e of Object.keys(i))if(!Wo.has(e))throw new Error(`${t}.${e} is not part of StandardTargetData.`)}function ie(i){const t=typeof i=="string"?[i]:i.slice();if(t.length===0)throw new Error("target id list must not be empty.");for(let e=0;e<t.length;e++)$(t[e],`ids[${e}]`);return t}function te(i){return(i==null?void 0:i.clearBefore)??(i==null?void 0:i.clearBefor)??!0}function Yt(i){var t;return{id:i.id,type:i.type,lon:i.data.lon,lat:i.data.lat,height:i.data.height,heading:i.data.heading,speedH:i.data.speedH,renderColor:i.data.renderColor??"",openAnimate:i.data.openAnimate??!1,animateColor:i.data.animateColor??"",hidden:((t=i.data.extra)==null?void 0:t.hidden)===!0,nationality:i.data.nationality,customInfo:i.data.customInfo}}function $(i,t){if(typeof i!="string"||i.length===0)throw new Error(`${t} must be a non-empty string.`)}function Xo(i,t){if(typeof i!="string")throw new Error(`${t} must be a string.`)}function ne(i,t){if(typeof i!="number"||!Number.isFinite(i))throw new Error(`${t} must be a finite number.`)}function Me(i,t){if(!/^#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(i))throw new Error(`${t} must be #RRGGBB or #RRGGBBAA.`)}function Go(i,t){if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`${t} must be an object.`)}function Zo(){Yo();const i=document.createElement("div");return i.className="mtf-context-menu",i.style.display="none",i.style.left="-9999px",i.style.top="-9999px",i}let Kt=!1;function Yo(){if(Kt)return;Kt=!0;const i=document.createElement("style");i.dataset.mtfContextMenu="true",i.textContent=`
69
+ .mtf-context-menu {
70
+ position: fixed;
71
+ z-index: 9999;
72
+ min-width: 144px;
73
+ background: #ffffff;
74
+ color: #111111;
75
+ border: 1px solid rgba(15, 23, 42, 0.14);
76
+ border-radius: 8px;
77
+ box-shadow: 0 10px 28px rgba(15, 23, 42, 0.18);
78
+ padding: 6px;
79
+ box-sizing: border-box;
80
+ }
81
+ .mtf-context-menu-list {
82
+ display: grid;
83
+ gap: 2px;
84
+ }
85
+ .mtf-context-menu-item {
86
+ appearance: none;
87
+ width: 100%;
88
+ min-height: 34px;
89
+ padding: 8px 12px;
90
+ border: 0;
91
+ border-radius: 6px;
92
+ background: transparent;
93
+ color: #111111;
94
+ text-align: left;
95
+ cursor: pointer;
96
+ font: 500 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
97
+ }
98
+ .mtf-context-menu-item:hover {
99
+ background: rgba(15, 23, 42, 0.08);
100
+ }
101
+ `,document.head.appendChild(i)}class Ko{constructor(t,e,n){l(this,"renderer");l(this,"typeByName",new Map);this.renderer=new je(t,n);for(const o of e)this.typeByName.set(o.type,o)}setSites(t){const e=[];for(const n of t){const o=this.typeByName.get(n.type),s=o==null?void 0:o.lowModel;!o||!(s!=null&&s.url)||e.push({id:n.id,url:s.url,modelKey:qo(o),modelStyle:{url:s.url,scale:s.scale,headingOffset:s.headingOffset,pitchOffset:s.pitchOffset,rollOffset:s.rollOffset},position:a.Cartesian3.fromDegrees(n.lon,n.lat,n.height),heading:n.heading??0,smoothMove:!1,moveDurationMs:0})}this.renderer.setCandidates(e)}clear(){this.renderer.clear()}update(t){this.renderer.update(t)}destroy(){this.renderer.destroy()}}function qo(i){const t=i.lowModel;return[i.type,(t==null?void 0:t.url)??"",(t==null?void 0:t.scale)??1,(t==null?void 0:t.headingOffset)??0,(t==null?void 0:t.pitchOffset)??0,(t==null?void 0:t.rollOffset)??0].join("|")}class $o{constructor(t){l(this,"buckets",new Map);l(this,"sites",[]);this.cellDeg=t}build(t){this.sites=t,this.buckets.clear();for(let e=0;e<t.length;e++){const n=t[e],o=Qo(n.lon,n.lat,this.cellDeg);let s=this.buckets.get(o);s||(s=[],this.buckets.set(o,s)),s.push(e)}}query(t){if(this.sites.length===0)return[];const e=[],n=new Set,o=jo(t);for(const s of o){const r=Be(s.west,this.cellDeg),c=Be(s.east,this.cellDeg),d=Fe(s.south,this.cellDeg),h=Fe(s.north,this.cellDeg);for(let m=d;m<=h;m++)for(let f=r;f<=c;f++){const v=this.buckets.get(`${f}:${m}`);if(v)for(const u of v){if(n.has(u))continue;const p=this.sites[u];Jo(t,p.lon,p.lat)&&(n.add(u),e.push(u))}}}return e}}function jo(i){return i.east>=i.west?[i]:[{west:i.west,east:180,south:i.south,north:i.north},{west:-180,east:i.east,south:i.south,north:i.north}]}function Jo(i,t,e){return e>=i.south&&e<=i.north?i.east>=i.west?t>=i.west&&t<=i.east:t>=i.west||t<=i.east:!1}function Qo(i,t,e){return`${Be(i,e)}:${Fe(t,e)}`}function Be(i,t){return Math.floor((es(i)+180)/t)}function Fe(i,t){return Math.floor((ts(i,-90,90)+90)/t)}function es(i){let t=i;for(;t<-180;)t+=360;for(;t>180;)t-=360;return t}function ts(i,t,e){return Math.min(e,Math.max(t,i))}const Ne=22,qt=2,is=48;class ns extends ue{constructor(e,n){super();l(this,"options");l(this,"stats",{total:0,inView:0,iconCount:0,lowModelCount:0,lowModelEligibleCount:0,mode:"icon"});l(this,"iconRenderer");l(this,"lowModelRenderer");l(this,"spatialIndex");l(this,"typeIndex",new Map);l(this,"typeColor",[]);l(this,"visibleSites",[]);l(this,"sites",[]);l(this,"screenPickIndex",null);l(this,"hoverPosition",null);l(this,"hoverRafId",0);l(this,"lastHoverSiteId",null);l(this,"destroyed",!1);l(this,"lastUpdateAt",0);l(this,"lastFrameAt",ze());l(this,"rafId",0);l(this,"removeCameraListener");l(this,"inputHandler");l(this,"eventBusBinding");this.viewer=e,this.options=os(n);const o=this.options.siteTypes;o.forEach((r,c)=>{this.typeIndex.set(r.type,c);const d=a.Color.fromCssColorString(r.defaultColor);this.typeColor.push([d.red,d.green,d.blue,d.alpha])});const s=Math.max(16,...o.map(r=>r.pointPixelSize*2));this.iconRenderer=new gt(e.scene,{typeStyles:o.map(r=>({type:r.type,iconPath:r.iconPath,defaultColor:r.defaultColor})),pixelSize:s}),e.scene.primitives.add(this.iconRenderer),this.lowModelRenderer=new Ko(e.scene,this.options.siteTypes,this.options.fadeMs),this.spatialIndex=new $o(this.options.indexCellDeg),this.removeCameraListener=this.viewer.camera.changed.addEventListener(()=>this.scheduleRefresh()),this.inputHandler=new a.ScreenSpaceEventHandler(this.viewer.scene.canvas),this.inputHandler.setInputAction(r=>{this.handleContextMenuAt(r.position)},a.ScreenSpaceEventType.RIGHT_CLICK),this.inputHandler.setInputAction(r=>{this.emit("pick",this.pickAt(r.position))},a.ScreenSpaceEventType.LEFT_CLICK),this.inputHandler.setInputAction(r=>{this.scheduleHoverAt(r.endPosition)},a.ScreenSpaceEventType.MOUSE_MOVE),this.rafId=requestAnimationFrame(r=>this.tick(r)),this.eventBusBinding=Ut(this,{replaceExisting:!0})}pickAt(e,n=22){return this.nearestSiteAtScreen(e,n)}setData(e){this.destroyed||(this.sites=rs(e,this.options.siteTypesByType),this.spatialIndex.build(this.sites),this.stats.total=this.sites.length,this.refresh(!0))}clear(){this.sites=[],this.spatialIndex.build(this.sites),this.iconRenderer.setInstances([]),this.lowModelRenderer.clear(),this.visibleSites=[],this.screenPickIndex=null,this.clearHover(),this.stats.total=0,this.stats.inView=0,this.stats.iconCount=0,this.stats.lowModelCount=0,this.stats.lowModelEligibleCount=0}destroy(){var e;this.destroyed||(this.destroyed=!0,this.eventBusBinding.dispose(),this.rafId&&cancelAnimationFrame(this.rafId),(e=this.removeCameraListener)==null||e.call(this),this.inputHandler.destroy(),this.clearHover(),this.viewer.scene.primitives.remove(this.iconRenderer),this.lowModelRenderer.destroy(),this.clear())}tick(e){if(this.destroyed)return;const n=Math.max(0,(e-this.lastFrameAt)/1e3);this.lastFrameAt=e,this.lowModelRenderer.update(n),this.rafId=requestAnimationFrame(o=>this.tick(o))}scheduleRefresh(){ze()-this.lastUpdateAt<this.options.updateThrottleMs||this.refresh(!1)}refresh(e){if(this.destroyed)return;const n=ze();if(!e&&n-this.lastUpdateAt<this.options.updateThrottleMs)return;if(this.lastUpdateAt=n,this.sites.length===0){this.iconRenderer.setInstances([]),this.lowModelRenderer.clear(),this.visibleSites=[],this.screenPickIndex=null,this.clearHover(),this.stats.inView=0,this.stats.iconCount=0,this.stats.lowModelCount=0,this.stats.lowModelEligibleCount=0;return}const o=as(this.viewer),r=this.spatialIndex.query(o).map(u=>this.sites[u]),d=this.viewer.scene.camera.positionCartographic.height<=this.options.modelSwitchHeight,h=r.filter(u=>{var g;const p=this.options.siteTypesByType.get(u.type);return!!((g=p==null?void 0:p.lowModel)!=null&&g.url)}),m=d?h.slice(0,this.options.maxVisibleLowModels):[],f=new Set(m.map(u=>u.id)),v=d?r.filter(u=>!f.has(u.id)):r;this.iconRenderer.setInstances(v.map(u=>{const p=this.typeIndex.get(u.type)??0;return{id:u.id,lon:u.lon,lat:u.lat,height:u.height,heading:u.heading,color:this.typeColor[p],iconIndex:p}})),this.lowModelRenderer.setSites(m),this.visibleSites=r,this.screenPickIndex=this.buildScreenPickIndex(r),this.repickHover(),this.stats.inView=r.length,this.stats.lowModelEligibleCount=h.length,this.stats.lowModelCount=m.length,this.stats.iconCount=v.length,this.stats.mode=d?"low-model":"icon"}handleContextMenuAt(e){const n=this.nearestSiteAtScreen(e,Ne);n&&this.emit("contextmenu",{site:n,screenX:e.x,screenY:e.y,cartesian:a.Cartesian3.fromDegrees(n.lon,n.lat,n.height)})}scheduleHoverAt(e){if(!this.destroyed){if(this.hoverPosition){const n=Math.abs(e.x-this.hoverPosition.x),o=Math.abs(e.y-this.hoverPosition.y);if(n<qt&&o<qt)return;a.Cartesian2.clone(e,this.hoverPosition)}else this.hoverPosition=a.Cartesian2.clone(e);this.hoverRafId||(this.hoverRafId=requestAnimationFrame(()=>this.flushHover()))}}flushHover(){if(this.hoverRafId=0,this.destroyed||!this.hoverPosition)return;const e=this.nearestSiteAtScreen(this.hoverPosition,Ne),n=(e==null?void 0:e.id)??null;n!==this.lastHoverSiteId&&(this.lastHoverSiteId=n,this.emit("hover",e))}repickHover(){this.hoverPosition&&(this.hoverRafId||(this.hoverRafId=requestAnimationFrame(()=>this.flushHover())))}clearHover(){this.hoverRafId&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=0),this.hoverPosition=null,this.lastHoverSiteId!==null&&(this.lastHoverSiteId=null,this.emit("hover",null))}buildScreenPickIndex(e){const n=this.viewer.scene.canvas;if(e.length===0||n.clientWidth<=0||n.clientHeight<=0)return null;const o=new Float32Array(e.length),s=new Float32Array(e.length);o.fill(Number.NaN),s.fill(Number.NaN);const r=new a.Cartesian3;for(let h=0;h<e.length;h++){const m=e[h];a.Cartesian3.fromDegrees(m.lon,m.lat,m.height,void 0,r);const f=a.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene,r);f&&(!Number.isFinite(f.x)||!Number.isFinite(f.y)||f.x<0||f.y<0||f.x>n.clientWidth||f.y>n.clientHeight||(o[h]=f.x,s[h]=f.y))}const c=Math.max(is,Ne*2),d=new Map;for(let h=0;h<e.length;h++){const m=o[h],f=s[h];if(!Number.isFinite(m)||!Number.isFinite(f))continue;const v=$t(Math.floor(m/c),Math.floor(f/c)),u=d.get(v);u?u.push(h):d.set(v,[h])}return{canvasWidth:n.clientWidth,canvasHeight:n.clientHeight,cellSize:c,bins:d,windowX:o,windowY:s}}nearestSiteAtScreen(e,n){const o=this.screenPickIndex;if(!o)return null;const s=this.viewer.scene.canvas;if(o.canvasWidth!==s.clientWidth||o.canvasHeight!==s.clientHeight)return this.screenPickIndex=this.buildScreenPickIndex(this.visibleSites),this.nearestSiteAtScreen(e,n);let r=null,c=n*n;const d=Math.floor(e.x/o.cellSize),h=Math.floor(e.y/o.cellSize);for(let m=h-1;m<=h+1;m++)for(let f=d-1;f<=d+1;f++){const v=o.bins.get($t(f,m));if(v)for(const u of v){const p=o.windowX[u]-e.x,g=o.windowY[u]-e.y,y=p*p+g*g;y<=c&&(c=y,r=this.visibleSites[u]??null)}}return r}}function $t(i,t){return`${i}:${t}`}function os(i){var n;if(!((n=i.siteTypes)!=null&&n.length))throw new Error("SiteLayer requires at least one site type.");if(!Number.isFinite(i.modelSwitchHeight)||i.modelSwitchHeight<=0)throw new Error("SiteLayer modelSwitchHeight must be a positive number.");const t=i.siteTypes.map(ss),e=new Map;for(const o of t)e.set(o.type,o);return{siteTypes:t,siteTypesByType:e,modelSwitchHeight:i.modelSwitchHeight,maxVisibleLowModels:Math.max(0,i.maxVisibleLowModels??3e3),updateThrottleMs:Math.max(16,i.updateThrottleMs??100),indexCellDeg:ls(i.indexCellDeg??.25,.02,10),fadeMs:Math.max(0,i.fadeMs??250)}}function ss(i){if(!i||typeof i!="object")throw new Error("Invalid site type config.");if(typeof i.type!="string"||i.type.length===0)throw new Error("site type must be a non-empty string.");if(typeof i.iconPath!="string"||i.iconPath.length===0)throw new Error(`site type "${i.type}" iconPath is required.`);return{...i,name:i.name??i.type,defaultColor:i.defaultColor??"#ffffff",pointPixelSize:Math.max(6,i.pointPixelSize??12)}}function rs(i,t){return i.map((e,n)=>{if(!e||typeof e!="object")throw new Error(`Invalid site at index ${n}.`);if(typeof e.id!="string"||e.id.length===0)throw new Error(`sites[${n}].id must be a non-empty string.`);if(typeof e.type!="string"||!t.has(e.type))throw new Error(`sites[${n}].type "${e.type}" is not registered.`);return Se(e.lon,`sites[${n}].lon`),Se(e.lat,`sites[${n}].lat`),Se(e.height,`sites[${n}].height`),e.heading!=null&&Se(e.heading,`sites[${n}].heading`),{...e}})}function as(i){const t=i.camera.computeViewRectangle();return t?{west:a.Math.toDegrees(t.west),east:a.Math.toDegrees(t.east),south:a.Math.toDegrees(t.south),north:a.Math.toDegrees(t.north)}:{west:-180,east:180,south:-85,north:85}}function Se(i,t){if(typeof i!="number"||!Number.isFinite(i))throw new Error(`${t} must be a finite number.`)}function ls(i,t,e){return Math.min(e,Math.max(t,i))}function ze(){return typeof performance<"u"?performance.now():Date.now()}const jt="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHEoZSxyLHMsbixvKXtsZXQgdT1uLGY9bztpZih1PT1udWxsfHxmPT1udWxsKXtsZXQgYz0wLHg9MDtmb3IobGV0IGE9MDthPHM7YSsrKWMrPWVbYV0seCs9clthXTt1PWMvcyxmPXgvc31jb25zdCBBPTExMTMyMCpNYXRoLmNvcyhmKk1hdGguUEkvMTgwKSxkPW5ldyBGbG9hdDY0QXJyYXkocyksST1uZXcgRmxvYXQ2NEFycmF5KHMpO2ZvcihsZXQgYz0wO2M8cztjKyspZFtjXT0oZVtjXS11KSpBLElbY109KHJbY10tZikqMTExMzIwO3JldHVybnt4czpkLHlzOkksbG9uMDp1LGxhdDA6Zn19ZnVuY3Rpb24gWChlKXtyZXR1cm4gZSY9NjU1MzUsZT0oZXxlPDw4KSYxNjcxMTkzNSxlPShlfGU8PDQpJjI1MjY0NTEzNSxlPShlfGU8PDIpJjg1ODk5MzQ1OSxlPShlfGU8PDEpJjE0MzE2NTU3NjUsZX1mdW5jdGlvbiBKKGUscil7cmV0dXJuKFgoZSl8WChyKTw8MSk+Pj4wfWNvbnN0IGI9MTEscD0xPDxiLEY9cC0xLHo9bmV3IEludDMyQXJyYXkocCksQz1uZXcgSW50MzJBcnJheSgxNik7ZnVuY3Rpb24gTihlKXtyZXR1cm57Y2FwOmUsa2V5czpuZXcgVWludDMyQXJyYXkoZSksaWR4QTpuZXcgSW50MzJBcnJheShlKSxpZHhCOm5ldyBJbnQzMkFycmF5KGUpLHNvcnRlZEtleXM6bmV3IFVpbnQzMkFycmF5KGUpLGNsdXN0ZXJPZjpuZXcgSW50MzJBcnJheShlKSxoZWFkczpuZXcgSW50MzJBcnJheShlKSxzaXplczpuZXcgSW50MzJBcnJheShlKX19ZnVuY3Rpb24gVihlLHIpe2lmKHI8PWUuY2FwKXJldHVybjtjb25zdCBzPU1hdGgubWF4KHIsZS5jYXAqMik7ZS5jYXA9cyxlLmtleXM9bmV3IFVpbnQzMkFycmF5KHMpLGUuaWR4QT1uZXcgSW50MzJBcnJheShzKSxlLmlkeEI9bmV3IEludDMyQXJyYXkocyksZS5zb3J0ZWRLZXlzPW5ldyBVaW50MzJBcnJheShzKSxlLmNsdXN0ZXJPZj1uZXcgSW50MzJBcnJheShzKSxlLmhlYWRzPW5ldyBJbnQzMkFycmF5KHMpLGUuc2l6ZXM9bmV3IEludDMyQXJyYXkocyl9Y29uc3QgVz0oZSxyKT0+KHtjb3VudDpyLGxldmVsOjAsY2VsbE1ldGVyczplLGNsdXN0ZXJDb3VudDowLGNsdXN0ZXJPZjpuZXcgSW50MzJBcnJheSgwKSxoZWFkSW5kZXg6bmV3IEludDMyQXJyYXkoMCksY2x1c3RlclNpemU6bmV3IEludDMyQXJyYXkoMCksbGV2ZWxzOltdfSk7ZnVuY3Rpb24gJChlLHIscyxuLG8sdSxmLG0pe2xldCBBPTEvMCxkPTEvMCxJPS0xLzAsYz0tMS8wO2ZvcihsZXQgdD0wO3Q8bjt0Kyspe2NvbnN0IGw9clt0XSxpPXNbdF07bDxBJiYoQT1sKSxpPGQmJihkPWkpLGw+SSYmKEk9bCksaT5jJiYoYz1pKX1jb25zdCB4PTEvbztsZXQgYT1vLEU9TWF0aC5tYXgoKEktQSkqeCwoYy1kKSp4KTtmb3IoO0U+PTY1NTM1OylhKj0yLEUvPTI7Y29uc3QgTz0xL2EsaD1lLmtleXM7bGV0IHc9MDtmb3IobGV0IHQ9MDt0PG47dCsrKXtjb25zdCBsPShyW3RdLUEpKk98MCxpPShzW3RdLWQpKk98MCxMPUoobCxpKTtoW3RdPUwsTD53JiYodz1MKX1jb25zdCBUPXc+MD8zMi1NYXRoLmNsejMyKHcpOjEsRz1NYXRoLm1heCgxLE1hdGguY2VpbChUL2IpKTtsZXQgdj1lLmlkeEEsZz1lLmlkeEI7Zm9yKGxldCB0PTA7dDxuO3QrKyl2W3RdPXQ7Y29uc3QgUz1lLnNvcnRlZEtleXM7Zm9yKGxldCB0PTA7dDxHO3QrKyl7Y29uc3QgbD10KmIsaT10PT09Ry0xO3ouZmlsbCgwKTtmb3IobGV0IHk9MDt5PG47eSsrKXpbaFt2W3ldXT4+PmwmRl0rKztsZXQgTD0wO2ZvcihsZXQgeT0wO3k8cDt5Kyspe2NvbnN0IF89elt5XTt6W3ldPUwsTCs9X31mb3IobGV0IHk9MDt5PG47eSsrKXtjb25zdCBfPXZbeV0sUT1oW19dLFo9eltRPj4+bCZGXSsrO2dbWl09XyxpJiYoU1taXT1RKX1jb25zdCBhZT12O3Y9ZyxnPWFlfWNvbnN0IHNlPXY7Qy5maWxsKDApO2xldCBZPVNbMF07Zm9yKGxldCB0PTE7dDxuO3QrKyl7Y29uc3QgbD1TW3RdLGk9bF5ZO1k9bCxpIT09MCYmQ1szMS1NYXRoLmNsejMyKGkpPj4xXSsrfWNvbnN0IEg9W107bGV0IEI9MCxNPW4sRD0wO2ZvcihsZXQgdD0xNTt0Pj0wO3QtLSlEKz1DW3RdO2ZvcihsZXQgdD0wO3Q8Zjt0Kyspe2NvbnN0IGw9MStEO2lmKEgucHVzaCh7bGV2ZWw6dCxjZWxsTWV0ZXJzOmEqKDE8PHQpLGNsdXN0ZXJzOmx9KSxCPXQsTT1sLGw8PXUpYnJlYWs7dDwxNiYmKEQtPUNbdF0pfWNvbnN0IHJlPTIqQixQPWUuY2x1c3Rlck9mLFU9ZS5oZWFkcyxrPWUuc2l6ZXM7ay5maWxsKDAsMCxNKTtsZXQgUj0tMSxqPS0xO2ZvcihsZXQgdD0wO3Q8bjt0Kyspe2NvbnN0IGw9c2VbdF0saT1TW3RdPj4+cmU7KHQ9PT0wfHxpIT09aikmJihSKyssVVtSXT1sLGo9aSksUFtsXT1SLGtbUl0rK31jb25zdCBuZT1tP1Auc3ViYXJyYXkoMCxuKTpQLnNsaWNlKDAsbiksbGU9bT9VLnN1YmFycmF5KDAsTSk6VS5zbGljZSgwLE0pLG9lPW0/ay5zdWJhcnJheSgwLE0pOmsuc2xpY2UoMCxNKTtyZXR1cm57Y291bnQ6bixsZXZlbDpCLGNlbGxNZXRlcnM6YSooMTw8QiksY2x1c3RlckNvdW50Ok0sY2x1c3Rlck9mOm5lLGhlYWRJbmRleDpsZSxjbHVzdGVyU2l6ZTpvZSxsZXZlbHM6SH19ZnVuY3Rpb24gZWUoZT0wKXtjb25zdCByPU4oTWF0aC5tYXgoMSxlKSk7cmV0dXJuKHMsbixvLHU9e30pPT57Y29uc3QgZj11LmJhc2VDZWxsTWV0ZXJzPz8yMDA7cmV0dXJuIG88PTA/VyhmLG8pOihWKHIsbyksJChyLHMsbixvLGYsdS5tYXhDbHVzdGVycz8/M2U0LHUubWF4TGV2ZWxzPz8yMCwhMCkpfX1jb25zdCB0ZT1lZSgpO2Z1bmN0aW9uIEsoZSxyKXtyZXR1cm4gZSYmZS5ieXRlTGVuZ3RoPj1yKjQ/bmV3IEludDMyQXJyYXkoZSwwLHIpOm5ldyBJbnQzMkFycmF5KHIpfXNlbGYub25tZXNzYWdlPWU9Pntjb25zdHtqb2JJZDpyLGxvbkJ1ZjpzLGxhdEJ1ZjpuLGNvdW50Om8sYmFzZTp1LG1heDpmLGxvbjA6bSxsYXQwOkF9PWUuZGF0YSxkPW5ldyBGbG9hdDY0QXJyYXkocywwLG8pLEk9bmV3IEZsb2F0NjRBcnJheShuLDAsbyksYz1wZXJmb3JtYW5jZS5ub3coKSx4PXEoZCxJLG8sbSxBKSxhPXRlKHgueHMseC55cyxvLHtiYXNlQ2VsbE1ldGVyczp1LG1heENsdXN0ZXJzOmZ9KSxFPWEuY2x1c3RlckNvdW50LE89SyhlLmRhdGEucmV0Q2x1c3Rlck9mLG8pO08uc2V0KGEuY2x1c3Rlck9mLnN1YmFycmF5KDAsbykpO2NvbnN0IGg9SyhlLmRhdGEucmV0SGVhZCxmKTtoLnNldChhLmhlYWRJbmRleC5zdWJhcnJheSgwLEUpKTtjb25zdCB3PUsoZS5kYXRhLnJldFNpemUsZik7dy5zZXQoYS5jbHVzdGVyU2l6ZS5zdWJhcnJheSgwLEUpKTtjb25zdCBUPXBlcmZvcm1hbmNlLm5vdygpLWM7c2VsZi5wb3N0TWVzc2FnZSh7am9iSWQ6cixsb25CdWY6cyxsYXRCdWY6bixjbHVzdGVyT2Y6Ty5idWZmZXIsaGVhZDpoLmJ1ZmZlcixzaXplOncuYnVmZmVyLGNsdXN0ZXJDb3VudDpFLGxldmVsOmEubGV2ZWwsY2VsbE1ldGVyczphLmNlbGxNZXRlcnMsY29tcHV0ZU1zOlR9LFtzLG4sTy5idWZmZXIsaC5idWZmZXIsdy5idWZmZXJdKX19KSgpOwo=",Jt=typeof window<"u"&&window.Blob&&new Blob([atob(jt)],{type:"text/javascript;charset=utf-8"});function cs(){let i;try{if(i=Jt&&(window.URL||window.webkitURL).createObjectURL(Jt),!i)throw"";return new Worker(i)}catch{return new Worker("data:application/javascript;base64,"+jt)}finally{i&&(window.URL||window.webkitURL).revokeObjectURL(i)}}function hs(){const i=new cs;let t=1,e=!1,n=new Float64Array(0),o=new Float64Array(0),s=null,r=null,c=null,d=null,h=new Float64Array(0),m=new Float64Array(0),f=null;function v(p){n.length<p&&(n=new Float64Array(p),o=new Float64Array(p))}function u(p,g,y,w,M){v(p),M&&(n.set(M.lons.subarray(0,p)),o.set(M.lats.subarray(0,p)));const S=n.buffer,b=o.buffer,k=t++;e=!0,d={resolve:y,startMs:w};const I={jobId:k,lonBuf:S,latBuf:b,count:p,base:g.baseCellMeters??200,max:g.maxClusters??3e4,lon0:g.lon0??0,lat0:g.lat0??0},T=[S,b];s&&(I.retClusterOf=s,T.push(s)),r&&(I.retHead=r,T.push(r)),c&&(I.retSize=c,T.push(c)),s=r=c=null,i.postMessage(I,T)}return i.onmessage=p=>{const g=p.data;e=!1,n=new Float64Array(g.lonBuf),o=new Float64Array(g.latBuf);const y=d;d=null;const w=g.clusterCount;if(s=g.clusterOf,r=g.head,c=g.size,y==null||y.resolve({clusterOf:new Int32Array(g.clusterOf),headIndex:new Int32Array(g.head,0,w),clusterSize:new Int32Array(g.size,0,w),clusterCount:w,level:g.level,cellMeters:g.cellMeters,computeMs:g.computeMs,roundTripMs:performance.now()-((y==null?void 0:y.startMs)??performance.now())}),f){const M=f;f=null,u(M.count,M.options,M.resolve,M.startMs,{lons:h,lats:m})}},{run(p,g,y,w={}){return new Promise(M=>{if(!e){u(y,w,M,performance.now(),{lons:p,lats:g});return}f&&f.resolve(null),h.length<y&&(h=new Float64Array(y),m=new Float64Array(y)),h.set(p.subarray(0,y)),m.set(g.subarray(0,y)),f={count:y,options:w,resolve:M,startMs:performance.now()}})},inputBuffers(p){if(e)throw new Error("inputBuffers 只能在 Worker 空闲时调用(输入缓冲此刻已被 transfer)");return v(p),{lons:n.subarray(0,p),lats:o.subarray(0,p)}},runReusing(p,g={}){return new Promise(y=>{if(e)throw new Error("runReusing 仅限串行使用:上一次任务尚未返回");u(p,g,y,performance.now(),null)})},terminate(){i.terminate(),d=null,f=null,s=r=c=null}}}const Qt=111320;function ds(i,t,e,n,o){let s=n,r=o;if(s==null||r==null){let f=0,v=0;for(let u=0;u<e;u++)f+=i[u],v+=t[u];s=f/e,r=v/e}const c=Math.cos(r*Math.PI/180),d=Qt*c,h=new Float64Array(e),m=new Float64Array(e);for(let f=0;f<e;f++)h[f]=(i[f]-s)*d,m[f]=(t[f]-r)*Qt;return{xs:h,ys:m,lon0:s,lat0:r}}function ei(i){return i&=65535,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,i}function us(i,t){return(ei(i)|ei(t)<<1)>>>0}const Ve=11,We=1<<Ve,ti=We-1,ce=new Int32Array(We),Ie=new Int32Array(16);function ii(i){return{cap:i,keys:new Uint32Array(i),idxA:new Int32Array(i),idxB:new Int32Array(i),sortedKeys:new Uint32Array(i),clusterOf:new Int32Array(i),heads:new Int32Array(i),sizes:new Int32Array(i)}}function fs(i,t){if(t<=i.cap)return;const e=Math.max(t,i.cap*2);i.cap=e,i.keys=new Uint32Array(e),i.idxA=new Int32Array(e),i.idxB=new Int32Array(e),i.sortedKeys=new Uint32Array(e),i.clusterOf=new Int32Array(e),i.heads=new Int32Array(e),i.sizes=new Int32Array(e)}const ni=(i,t)=>({count:t,level:0,cellMeters:i,clusterCount:0,clusterOf:new Int32Array(0),headIndex:new Int32Array(0),clusterSize:new Int32Array(0),levels:[]});function oi(i,t,e,n,o,s,r,c){let d=1/0,h=1/0,m=-1/0,f=-1/0;for(let x=0;x<n;x++){const L=t[x],D=e[x];L<d&&(d=L),D<h&&(h=D),L>m&&(m=L),D>f&&(f=D)}const v=1/o;let u=o,p=Math.max((m-d)*v,(f-h)*v);for(;p>=65535;)u*=2,p/=2;const g=1/u,y=i.keys;let w=0;for(let x=0;x<n;x++){const L=(t[x]-d)*g|0,D=(e[x]-h)*g|0,K=us(L,D);y[x]=K,K>w&&(w=K)}const M=w>0?32-Math.clz32(w):1,S=Math.max(1,Math.ceil(M/Ve));let b=i.idxA,k=i.idxB;for(let x=0;x<n;x++)b[x]=x;const I=i.sortedKeys;for(let x=0;x<S;x++){const L=x*Ve,D=x===S-1;ce.fill(0);for(let z=0;z<n;z++)ce[y[b[z]]>>>L&ti]++;let K=0;for(let z=0;z<We;z++){const Pe=ce[z];ce[z]=K,K+=Pe}for(let z=0;z<n;z++){const Pe=b[z],si=y[Pe],ri=ce[si>>>L&ti]++;k[ri]=Pe,D&&(I[ri]=si)}const vs=b;b=k,k=vs}const T=b;Ie.fill(0);let N=I[0];for(let x=1;x<n;x++){const L=I[x],D=L^N;N=L,D!==0&&Ie[31-Math.clz32(D)>>1]++}const A=[];let H=0,_=n,G=0;for(let x=15;x>=0;x--)G+=Ie[x];for(let x=0;x<r;x++){const L=1+G;if(A.push({level:x,cellMeters:u*(1<<x),clusters:L}),H=x,_=L,L<=s)break;x<16&&(G-=Ie[x])}const j=2*H,Z=i.clusterOf,J=i.heads,Y=i.sizes;Y.fill(0,0,_);let W=-1,he=-1;for(let x=0;x<n;x++){const L=T[x],D=I[x]>>>j;(x===0||D!==he)&&(W++,J[W]=L,he=D),Z[L]=W,Y[W]++}const xe=c?Z.subarray(0,n):Z.slice(0,n),Te=c?J.subarray(0,_):J.slice(0,_),be=c?Y.subarray(0,_):Y.slice(0,_);return{count:n,level:H,cellMeters:u*(1<<H),clusterCount:_,clusterOf:xe,headIndex:Te,clusterSize:be,levels:A}}function ms(i=0){const t=ii(Math.max(1,i));return(e,n,o,s={})=>{const r=s.baseCellMeters??200;return o<=0?ni(r,o):(fs(t,o),oi(t,e,n,o,r,s.maxClusters??3e4,s.maxLevels??20,!0))}}function ps(i,t,e,n={}){const o=n.baseCellMeters??200;if(e<=0)return ni(o,e);const s=ii(e);return oi(s,i,t,e,o,n.maxClusters??3e4,n.maxLevels??20,!1)}const gs="0.2.0";P.DEFAULT_ANIMATED_POOL=Ge,P.DEFAULT_LOD=Ue,P.DEFAULT_POOL=Xe,P.DEFAULT_SCENE=se,P.EventEmitter=ue,P.MTF_ACTION_NAMES=C,P.MTF_EVENT_NAMES=F,P.MultiTargetFramework=ye,P.MultiTargetScene=Ot,P.SiteLayer=ns,P.TARGET_DOMAINS=oe,P.TrackManager=Ct,P.VERSION=gs,P.bindFrameworkEventBus=Wt,P.bindSiteLayerEventBus=Ut,P.clusterProgressive=ps,P.createClusterWorkerClient=hs,P.createFrameworkEventBus=Ho,P.createMultiTargetFramework=No,P.createQuadClusterer=ms,P.getFrameworkEventBus=Vt,P.lonLatToLocalPlane=ds,P.tryGetFrameworkEventBus=Oe,Object.keys(a).forEach(i=>{i!=="default"&&!Object.prototype.hasOwnProperty.call(P,i)&&Object.defineProperty(P,i,{enumerable:!0,get:()=>a[i]})}),Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});
@@ -0,0 +1,66 @@
1
+ /** 经纬批量投影到本地切平面(米)的结果 */
2
+ export interface LocalPlane {
3
+ xs: Float64Array;
4
+ ys: Float64Array;
5
+ lon0: number;
6
+ lat0: number;
7
+ }
8
+ /** 递进聚类参数 */
9
+ export interface ProgressiveClusterOptions {
10
+ /** 最细层级格子边长(米),即第 0 层的合并半径。默认 200 */
11
+ baseCellMeters?: number;
12
+ /** 合并后簇数上限;超过则升一层(半径翻倍)继续合并。默认 30000 */
13
+ maxClusters?: number;
14
+ /** 层级数上限(保护,避免极端数据无限上探)。默认 20 */
15
+ maxLevels?: number;
16
+ }
17
+ /** 单个层级的簇数统计(用于展示递进过程) */
18
+ export interface LevelStat {
19
+ level: number;
20
+ /** 该层格子边长(米)= 该层合并半径 */
21
+ cellMeters: number;
22
+ /** 该层聚类后的簇数 */
23
+ clusters: number;
24
+ }
25
+ /** 递进聚类结果 */
26
+ export interface ProgressiveClusterResult {
27
+ count: number;
28
+ /** 采用的层级 */
29
+ level: number;
30
+ /** 采用层级的格子边长(米)= 实际合并半径 */
31
+ cellMeters: number;
32
+ /** 采用层级的簇数 = 实际渲染目标数 */
33
+ clusterCount: number;
34
+ /** 每个原始点 → 所属簇序号(0..clusterCount-1) */
35
+ clusterOf: Int32Array;
36
+ /** 每个簇 → 簇心点的原始索引 */
37
+ headIndex: Int32Array;
38
+ /** 每个簇的成员数 */
39
+ clusterSize: Int32Array;
40
+ /** 递进过程:第 0 层到采用层级的逐层簇数 */
41
+ levels: LevelStat[];
42
+ }
43
+ /**
44
+ * 经纬度数组投影到以 (lon0, lat0) 为原点的本地切平面(等距矩形近似,单位米)。
45
+ * 小范围(百公里级)下足够精确,用于把球面距离阈值(如 200m)变成平面格子边长。
46
+ */
47
+ export declare function lonLatToLocalPlane(lons: Float64Array | number[], lats: Float64Array | number[], count: number, lon0?: number, lat0?: number): LocalPlane;
48
+ /** 复用缓冲的聚类器:同一函数对象跨调用复用内部缓冲,稳态零分配。 */
49
+ export type QuadClusterer = (xs: Float64Array, ys: Float64Array, count: number, options?: ProgressiveClusterOptions) => ProgressiveClusterResult;
50
+ /**
51
+ * 创建一个复用缓冲的聚类器,适合**每秒/每帧高频调用**的生产场景。
52
+ *
53
+ * 注意:返回结果中的 clusterOf / headIndex / clusterSize 是内部缓冲的视图,
54
+ * 仅在「下一次调用本聚类器之前」有效。调用方应即时消费(如直接用于本帧渲染分发),
55
+ * 不要长期持有。需要长期保存请自行拷贝,或改用一次性的 clusterProgressive。
56
+ */
57
+ export declare function createQuadClusterer(initialCapacity?: number): QuadClusterer;
58
+ /**
59
+ * 多分辨率四叉树递进聚类(一次性便捷版)。
60
+ * 每次调用独立分配并返回**可长期持有**的结果数组;适合单次/低频处理。
61
+ * 高频(每秒/每帧)调用请用 createQuadClusterer 复用缓冲,避免 GC 尖峰。
62
+ *
63
+ * @param xs/ys 本地平面坐标(米),长度 ≥ count
64
+ * @param count 点数
65
+ */
66
+ export declare function clusterProgressive(xs: Float64Array, ys: Float64Array, count: number, options?: ProgressiveClusterOptions): ProgressiveClusterResult;
@@ -0,0 +1,44 @@
1
+ import { ProgressiveClusterOptions } from './QuadCluster';
2
+
3
+ export interface ClusterJobResult {
4
+ /** 每个原始点 → 所属簇序号 */
5
+ clusterOf: Int32Array;
6
+ /** 每个簇 → 簇心点的原始索引 */
7
+ headIndex: Int32Array;
8
+ /** 每个簇的成员数 */
9
+ clusterSize: Int32Array;
10
+ clusterCount: number;
11
+ level: number;
12
+ cellMeters: number;
13
+ /** Worker 内的纯计算耗时(投影 + 聚类,毫秒) */
14
+ computeMs: number;
15
+ /** 主线程视角的端到端往返耗时(发出 → 拿到结果,毫秒) */
16
+ roundTripMs: number;
17
+ }
18
+ type RunOptions = ProgressiveClusterOptions & {
19
+ lon0?: number;
20
+ lat0?: number;
21
+ };
22
+ export interface ClusterWorkerClient {
23
+ /**
24
+ * 发起一次聚类(会把输入拷进内部缓冲再 transfer,调用方数组保持可用)。
25
+ * 若 Worker 正忙且本次请求随后被更新的请求取代,则该 Promise resolve `null`。
26
+ */
27
+ run(lons: Float64Array, lats: Float64Array, count: number, options?: RunOptions): Promise<ClusterJobResult | null>;
28
+ /**
29
+ * 借出 client 的内部输入缓冲(容量 ≥ count)。调用方把经纬度直接写进返回的视图,
30
+ * 再配合 runReusing 提交即可实现零拷贝。仅在 Worker 空闲时调用(串行使用)。
31
+ */
32
+ inputBuffers(count: number): {
33
+ lons: Float64Array;
34
+ lats: Float64Array;
35
+ };
36
+ /**
37
+ * 零拷贝提交:直接 transfer 当前内部输入缓冲(inputBuffers 写入或上一轮交还的内容),
38
+ * 不做拷贝。仅限串行使用(Worker 空闲时调用)。
39
+ */
40
+ runReusing(count: number, options?: RunOptions): Promise<ClusterJobResult | null>;
41
+ terminate(): void;
42
+ }
43
+ export declare function createClusterWorkerClient(): ClusterWorkerClient;
44
+ export {};
@@ -0,0 +1 @@
1
+ export {};