@juun-roh/cesium-utils 0.1.2 → 0.2.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.
package/README.md CHANGED
@@ -65,6 +65,12 @@ pnpm test
65
65
 
66
66
  Working on the demonstration at [Cesium Utils Demo](https://juun.vercel.app/cesium-utils).
67
67
 
68
+ Run a local live demonstration where you can see changes directly by:
69
+
70
+ ```bash
71
+ pnpm dev
72
+ ```
73
+
68
74
  ### Documentation
69
75
 
70
76
  Generate API documentation:
@@ -0,0 +1 @@
1
+ import{Color as s,Entity as O,HeightReference as F,Rectangle as E,TileCoordinatesImageryProvider as V}from"cesium";import{DataSourceCollection as A,defined as _,EntityCollection as b,ImageryLayerCollection as S,PrimitiveCollection as M}from"cesium";var y=class o{static symbol=Symbol("cesium-item-tag");tag;collection;_valuesCache=null;_tagMap=new Map;_eventListeners=new Map;_eventCleanupFunctions=[];constructor({collection:e,tag:t}){this.tag=t||"default",this.collection=e,this._setupCacheInvalidator(e)}[Symbol.iterator](){return this.values[Symbol.iterator]()}_emit(e,t){let i=this._eventListeners.get(e);if(i){let r={type:e,...t};i.forEach(n=>n(r))}}_addToTagMap(e,t){this._tagMap.has(t)||this._tagMap.set(t,new Set),this._tagMap.get(t)?.add(e)}_removeFromTagMap(e){let t=e[o.symbol],i=this._tagMap.get(t);i&&(i.delete(e),i.size===0&&this._tagMap.delete(t))}_invalidateCache=()=>{this._valuesCache=null};_setupCacheInvalidator(e){e instanceof b?(e.collectionChanged.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.collectionChanged.removeEventListener(this._invalidateCache))):e instanceof M?(e.primitiveAdded.addEventListener(this._invalidateCache),e.primitiveRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.primitiveAdded.removeEventListener(this._invalidateCache),()=>e.primitiveRemoved.removeEventListener(this._invalidateCache))):e instanceof A?(e.dataSourceAdded.addEventListener(this._invalidateCache),e.dataSourceMoved.addEventListener(this._invalidateCache),e.dataSourceRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.dataSourceAdded.removeEventListener(this._invalidateCache),()=>e.dataSourceMoved.removeEventListener(this._invalidateCache),()=>e.dataSourceRemoved.removeEventListener(this._invalidateCache))):e instanceof S&&(e.layerAdded.addEventListener(this._invalidateCache),e.layerMoved.addEventListener(this._invalidateCache),e.layerRemoved.addEventListener(this._invalidateCache),e.layerShownOrHidden.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.layerAdded.removeEventListener(this._invalidateCache),()=>e.layerMoved.removeEventListener(this._invalidateCache),()=>e.layerRemoved.removeEventListener(this._invalidateCache),()=>e.layerShownOrHidden.removeEventListener(this._invalidateCache)))}addEventListener(e,t){return this._eventListeners.has(e)||this._eventListeners.set(e,new Set),this._eventListeners.get(e)?.add(t),this}removeEventListener(e,t){return this._eventListeners.get(e)?.delete(t),this}add(e,t=this.tag,i){return Array.isArray(e)?e.forEach(r=>{this.add(r,t)}):(Object.defineProperty(e,o.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this.collection.add(e,i),this._addToTagMap(e,t),this._invalidateCache(),this._emit("add",{items:[e],tag:t})),this}contains(e){if(typeof e=="object")return this.collection.contains(e);let t=this._tagMap.get(e);return!!t&&t.size>0}remove(e){if(typeof e=="object"&&!Array.isArray(e)&&this.collection.remove(e)&&(this._removeFromTagMap(e),this._invalidateCache(),this._emit("remove",{items:[e]})),Array.isArray(e)){if(e.length===0)return this;for(let i of e)this.remove(i)}let t=this.get(e);if(t.length===0)return this;for(let i of t)this.remove(i);return this}removeAll(){this._tagMap.clear(),this.collection.removeAll(),this._invalidateCache(),this._emit("clear")}destroy(){this._eventCleanupFunctions.forEach(e=>e()),this._eventCleanupFunctions=[],this._tagMap.clear(),this._eventListeners.clear(),this._valuesCache=null}get values(){if(this._valuesCache!==null)return this._valuesCache;let e;if(this.collection instanceof b)e=this.collection.values;else{e=[];for(let t=0;t<this.collection.length;t++)e.push(this.collection.get(t))}return this._valuesCache=e,e}get length(){return this.values?.length||0}get(e){let t=this._tagMap.get(e);return t?Array.from(t):[]}first(e){let t=this._tagMap.get(e);if(t&&t.size>0)return t.values().next().value}get tags(){return Array.from(this._tagMap.keys())}update(e,t){let i=this.get(e);for(let r of i)this._removeFromTagMap(r),Object.defineProperty(r,o.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this._addToTagMap(r,t);return i.length>0&&this._emit("update",{items:i,tag:t}),i.length}show(e){let t=this.get(e);for(let i of t)_(i.show)&&(i.show=!0);return this}hide(e){let t=this.get(e);for(let i of t)_(i.show)&&(i.show=!1);return this}toggle(e){let t=this.get(e);for(let i of t)_(i.show)&&(i.show=!i.show);return this}setProperty(e,t,i=this.tag){let r=this.get(i);for(let n of r)if(e in n&&typeof n[e]!="function"){if(C(n,e))throw Error(`Cannot set read-only property '${String(e)}' on ${n.constructor.name}`);n[e]=t}return this}filter(e,t){return(t?this.get(t):this.values).filter(e)}forEach(e,t){(t?this.get(t):this.values).forEach((r,n)=>e(r,n))}map(e,t){return(t?this.get(t):this.values).map(e)}find(e,t){return(t?this.get(t):this.values).find(e)}},T=y;var v=class o{_viewer;_collection;_terrainProvider;_visible=!1;_level=15;_tileCoordinatesLayer;_colors=new Map([["custom",s.RED],["default",s.BLUE],["fallback",s.GRAY],["grid",s.YELLOW]]);constructor(e,t){this._viewer=e,this._collection=new T({collection:e.entities,tag:o.tag.default}),t&&(t.colors&&Object.entries(t.colors).forEach(([i,r])=>{this._colors.set(i,r)}),t.tile!==void 0&&(this._visible=t.tile),t.activeLevel!==void 0&&(this._level=t.activeLevel),t.terrainProvider&&this.setTerrainProvider(t.terrainProvider))}setTerrainProvider(e){this._terrainProvider=e,this.update()}update(){this.clear(),this._visible&&this.show(this._level)}clear(){this._collection.remove(this._collection.tags)}show(e=15){if(!this._terrainProvider)return;this._collection.remove(o.tag.grid),this._level=e,this._ensureTileCoordinatesLayer();let t=this._getVisibleRectangle();if(!t||!this._isValidRectangle(t)){console.warn("Invalid visible rectangle detected, skipping grid display");return}this._displayTileGrid(t,e),this._visible=!0}_ensureTileCoordinatesLayer(){this._tileCoordinatesLayer||(this._tileCoordinatesLayer=this._viewer.imageryLayers.addImageryProvider(new V({tilingScheme:this._terrainProvider.tilingScheme,color:s.YELLOW})))}_isValidRectangle(e){return e&&Number.isFinite(e.west)&&Number.isFinite(e.south)&&Number.isFinite(e.east)&&Number.isFinite(e.north)&&e.west<=e.east&&e.south<=e.north}_displayTileGrid(e,t){let i=this._terrainProvider.tilingScheme;try{let r=this._calculateTileBounds(e,t,i);this._generateVisibleTiles(r,t,i).forEach(a=>{this._collection.add(a.entity,o.tag.grid)})}catch(r){console.error("Error displaying tile grid:",r)}}_calculateTileBounds(e,t,i){let r=i.positionToTileXY(E.northwest(e),t),n=i.positionToTileXY(E.southeast(e),t);if(!r||!n)throw new Error("Failed to calculate tile bounds");return{start:r,end:n}}_generateVisibleTiles(e,t,i){let r=[],a=Math.min(e.end.x-e.start.x+1,100),l=Math.min(e.end.y-e.start.y+1,100);for(let c=e.start.x;c<e.start.x+a;c++)for(let h=e.start.y;h<e.start.y+l;h++)try{let d=this._createTileEntity(c,h,t,i);d&&r.push({entity:d})}catch(d){console.warn(`Error creating tile (${c}, ${h}, ${t}):`,d)}return r}_createTileEntity(e,t,i,r){let n=r.tileXYToRectangle(e,t,i);if(!this._isValidRectangle(n))return null;let a=this._getTileColor(e,t,i),l=o.createRectangle(n,a.withAlpha(.3));return l.properties?.addProperty("tileX",e),l.properties?.addProperty("tileY",t),l.properties?.addProperty("tileLevel",i),l}_getTileColor(e,t,i){if(!this._terrainProvider)return this._colors.get("fallback")||s.TRANSPARENT;for(let r of this._terrainProvider.terrainAreas)if(r.contains(e,t,i))return r.isCustom?this._colors.get("custom")||s.RED:this._colors.get("default")||s.BLUE;return this._terrainProvider.getTileDataAvailable(e,t,i)?this._colors.get("default")||s.BLUE:this._colors.get("fallback")||s.GRAY}hide(){this._collection.remove(o.tag.grid),this._tileCoordinatesLayer&&(this._viewer.imageryLayers.remove(this._tileCoordinatesLayer),this._tileCoordinatesLayer=void 0),this._visible=!1}setColors(e){Object.entries(e).forEach(([t,i])=>{this._colors.set(t,i)}),this.update()}flyTo(e,t){let{rectangle:i}=e;this._viewer.camera.flyTo({destination:i,...t,complete:()=>{this._visible&&this.update()}})}_getVisibleRectangle(){return this._viewer.camera.computeViewRectangle()}get level(){return this._level}set level(e){this._level=e,this._visible&&this.update()}get visible(){return this._visible}get collection(){return this._collection}get viewer(){return this._viewer}get colors(){return this._colors}get terrainProvider(){return this._terrainProvider}};(i=>{i.tag={default:"Terrain Visualizer",boundary:"Terrain Visualizer Boundary",grid:"Terrain Visualizer Tile Grid"};function e(r,n){return new O({rectangle:{coordinates:r,material:n,heightReference:F.CLAMP_TO_GROUND}})}i.createRectangle=e;function t(r,n,a){let l=a?.tag||"terrain_area_visualization",c=a?.color||s.RED,h=a?.maxTilesToShow||100,d=a?.show??!0,w=a?.alpha||.7,L=a?.tileAlpha||.2,m=new T({collection:n.entities,tag:l}),{rectangle:I}=r;if(m.add(i.createRectangle(I,c.withAlpha(w)),l),d&&r.tileRanges.size>0){let{tilingScheme:P}=r.terrainProvider,g=0;r.tileRanges.forEach((u,R)=>{for(let f=u.start.x;f<=u.end.x&&g<h;f++)for(let p=u.start.y;p<=u.end.y&&g<h;p++){let x=P.tileXYToRectangle(f,p,R);m.add(e(x,c.withAlpha(L)),`${l}_tile`),g++}})}return m}i.visualize=t})(v||={});function C(o,e){let t=!1,i=Object.getOwnPropertyDescriptor(o,e);if(!i){let r=Object.getPrototypeOf(o);for(;r&&!i;)i=Object.getOwnPropertyDescriptor(r,e),r=Object.getPrototypeOf(r)}return i&&i.get&&!i.set&&(t=!0),t}export{v as a,C as b,T as c};
@@ -0,0 +1 @@
1
+ import{EllipsoidTerrainProvider as P,Rectangle as _}from"cesium";import{CesiumTerrainProvider as A}from"cesium";var o=class{_terrainProvider;_rectangle;_tileRanges;_ready=!1;_credit;_isCustom;constructor(r){this._terrainProvider=r.terrainProvider,this._tileRanges=r.tileRanges,this._credit=r.credit||"custom",this._isCustom=r.isCustom!==void 0?r.isCustom:!0,this._rectangle=c.computeRectangle(r.terrainProvider.tilingScheme,r.tileRanges),r.tileRanges.forEach((i,t)=>{this._terrainProvider.availability?.addAvailableTileRange(t,i.start.x,i.start.y,i.end.x,i.end.y)}),this._ready=!0}contains(r,i,t){if(this._tileRanges.size===0||!this._tileRanges.has(t))return!1;let e=this._tileRanges.get(t);return r>=e.start.x&&r<=e.end.x&&i>=e.start.y&&i<=e.end.y}requestTileGeometry(r,i,t,e){if(!(!this._ready||!this.contains(r,i,t)))return this._terrainProvider.requestTileGeometry(r,i,t,e)}getTileDataAvailable(r,i,t){if(this._tileRanges.size===0||!this._tileRanges.has(t))return!1;let e=this._tileRanges.get(t);return r>=e.start.x&&r<=e.end.x&&i>=e.start.y&&i<=e.end.y}get isCustom(){return this._isCustom}get credit(){return this._credit}get terrainProvider(){return this._terrainProvider}get tileRanges(){return this._tileRanges}get rectangle(){return this._rectangle}get ready(){return this._ready}};(i=>{async function d(t,e,a){let n=a?.credit||"custom",s=await A.fromUrl(t,{...a,credit:n});return new i({terrainProvider:s,tileRanges:e,credit:n})}i.fromUrl=d;class r extends Array{add(e){if(Array.isArray(e)){for(let n of e)this.add(n);return this}let a;return e instanceof i?a=e:a=new i(e),this.push(a),this}remove(e){if(Array.isArray(e))return e.forEach(n=>this.remove(n)),this;let a=this.indexOf(e);return a>=0&&this.splice(a,1),this}removeAll(){this.length=0}}i.Collection=r})(o||={});var m=o;var l=class{_terrainAreas;_terrainProvider;_fallbackProvider;_tilingScheme;_ready=!1;_availability;constructor(r){this._terrainProvider=r.terrainProvider,this._fallbackProvider=r.fallbackProvider||new P,this._tilingScheme=r.terrainProvider.tilingScheme,this._terrainAreas=new m.Collection(...r.terrainAreas),this._availability=r.terrainProvider.availability,this._ready=!0}get ready(){return this._ready}get tilingScheme(){return this._tilingScheme}get availability(){return this._availability}get terrainAreas(){return[...this._terrainAreas]}get defaultProvider(){return this._terrainProvider}get fallbackProvider(){return this._fallbackProvider}get credit(){return this._terrainProvider?.credit}get errorEvent(){return this._terrainProvider.errorEvent}get hasWaterMask(){return this._terrainProvider.hasWaterMask}get hasVertexNormals(){return this._terrainProvider.hasVertexNormals}loadTileDataAvailability(r,i,t){return this._terrainProvider.loadTileDataAvailability(r,i,t)}getLevelMaximumGeometricError(r){return this._terrainProvider.getLevelMaximumGeometricError(r)}requestTileGeometry(r,i,t,e){if(this._ready){for(let a of this._terrainAreas)if(a.contains(r,i,t))return a.requestTileGeometry(r,i,t,e);return this._terrainProvider.getTileDataAvailable(r,i,t)?this._terrainProvider.requestTileGeometry(r,i,t,e):this._fallbackProvider.requestTileGeometry(r,i,t,e)}}getTileDataAvailable(r,i,t){for(let e of this._terrainAreas)if(e.contains(r,i,t))return e.getTileDataAvailable(r,i,t);return this._terrainProvider.getTileDataAvailable(r,i,t)}};(r=>{function d(i,t){if(t.size===0)return new _;let e=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,h=Array.from(t.keys()),u=Math.min(...h),v=t.get(u);if(v){let{start:T,end:b}=v,g=i.tileXYToRectangle(T.x,T.y,u),f=i.tileXYToRectangle(b.x,b.y,u);e=Math.min(g.west,e),a=Math.min(f.south,a),n=Math.max(f.east,n),s=Math.max(g.north,s)}return new _(e,a,n,s)}r.computeRectangle=d})(l||={});var c=l;export{m as a,c as b};
@@ -0,0 +1 @@
1
+ import{Cesium3DTileFeature as P,Color as R,defined as H,Entity as p,GroundPrimitive as E}from"cesium";import{Cesium3DTileFeature as T,Color as f,ConstantProperty as u,defined as G,PostProcessStageLibrary as m}from"cesium";var s=class{_color=f.RED;_silhouette;_composite;_stages;_entity;_currentObject;_currentOptions;constructor(t){this._stages=t.scene.postProcessStages,this._silhouette=m.createEdgeDetectionStage(),this._silhouette.uniforms.color=this._color,this._silhouette.uniforms.length=.01,this._silhouette.selected=[],this._composite=m.createSilhouetteStage([this._silhouette]),this._stages.add(this._composite)}show(t,i){if(G(t)&&!(this._currentObject===t&&this._optionsEqual(this._currentOptions,i))){this._clearHighlights();try{if(t instanceof T)this._silhouette.uniforms.color=i?.color||this._color,this._silhouette.selected.push(t);else{if(!t.model)return;this._entity=t,t.model.silhouetteSize=new u(i?.width||2),t.model.silhouetteColor=new u(i?.color||this._color)}this._currentObject=t,this._currentOptions=i?{...i}:void 0}catch(e){console.error("Failed to highlight object:",e),this._currentObject=void 0,this._currentOptions=void 0}}}_optionsEqual(t,i){return!t&&!i?!0:!t||!i?!1:t.outline===i.outline&&t.width===i.width&&f.equals(t.color||this._color,i.color||this._color)}_clearHighlights(){this._silhouette.selected.length>0&&(this._silhouette.selected=[]),this._entity?.model&&(this._entity.model.silhouetteColor=new u(f.TRANSPARENT),this._entity.model.silhouetteSize=new u(0),this._entity=void 0)}hide(){this._clearHighlights(),this._currentObject=void 0,this._currentOptions=void 0}destroy(){this.hide(),this._composite&&this._stages.remove(this._composite),this._currentObject=void 0,this._currentOptions=void 0}get color(){return this._color}set color(t){this._color=t}get currentObject(){return this._currentObject}};import{Cartesian3 as o,ClassificationType as v,Color as O,defined as S,Entity as g,GroundPrimitive as w,HeightReference as _,PolygonGraphics as C,PolygonHierarchy as b,PolylineGraphics as a,RectangleGraphics as D}from"cesium";var l=class{_color=O.RED;_entity;_entities;_currentObject;_currentOptions;constructor(t){this._entities=t.entities,this._entity=this._entities.add(new g({id:`highlight-entity-${Math.random().toString(36).substring(2)}`,show:!1}))}show(t,i){if(!(!S(t)||!this._entity)){if(this._currentObject===t&&this._optionsEqual(this._currentOptions,i))return this._entity;this._clearGeometries();try{if(t instanceof g&&(t.polygon||t.polyline||t.rectangle))this._update(t,i);else if(t instanceof w)this._update(t,i);else{this._currentObject=void 0,this._currentOptions=void 0;return}return this._currentObject=t,this._currentOptions=i?{...i}:void 0,this._entity.show=!0,this._entity}catch(e){console.error("Failed to highlight object:",e),this._currentObject=void 0,this._currentOptions=void 0;return}}}_optionsEqual(t,i){return!t&&!i?!0:!t||!i?!1:t.outline===i.outline&&t.width===i.width&&O.equals(t.color||this._color,i.color||this._color)}_clearGeometries(){this._entity.polygon=void 0,this._entity.polyline=void 0,this._entity.rectangle=void 0}_update(t,i={color:this._color,outline:!1,width:2}){if(t instanceof g){if(t.polygon)if(i.outline){let e=t.polygon.hierarchy?.getValue();if(e&&e.positions){let r;e.positions.length>0&&!o.equals(e.positions[0],e.positions[e.positions.length-1])?r=[...e.positions,e.positions[0]]:r=e.positions,this._entity.polyline=new a({positions:r,material:i.color,width:i.width||2,clampToGround:!0})}}else{let e=t.polygon.hierarchy?.getValue();e&&(this._entity.polygon=new C({hierarchy:e,material:i.color,heightReference:_.CLAMP_TO_GROUND,classificationType:t.polygon.classificationType?.getValue()||v.BOTH}))}else if(t.polyline){let e=t.polyline.positions?.getValue();if(e){let r=t.polyline.width?.getValue();this._entity.polyline=new a({positions:e,material:i.color,width:r+(i.width||2),clampToGround:!0})}}else if(t.rectangle)if(i.outline){let e=t.rectangle.coordinates?.getValue();if(e){let r=[o.fromRadians(e.west,e.north),o.fromRadians(e.east,e.north),o.fromRadians(e.east,e.south),o.fromRadians(e.west,e.south),o.fromRadians(e.west,e.north)];this._entity.polyline=new a({positions:r,material:i.color,width:i.width||2,clampToGround:!0})}}else{let e=t.rectangle.coordinates?.getValue();e&&(this._entity.rectangle=new D({coordinates:e,material:i.color,heightReference:_.CLAMP_TO_GROUND}))}}else if(t instanceof w){let e=t.geometryInstances,r=Array.isArray(e)?e[0]:e;if(!r.geometry.attributes.position)return;let c=r.geometry.attributes.position.values,d=[];for(let h=0;h<c.length;h+=3)d.push(new o(c[h],c[h+1],c[h+2]));i.outline?this._entity.polyline=new a({positions:d,material:i.color,width:i.width||2,clampToGround:!0}):this._entity.polygon=new C({hierarchy:new b(d),material:i.color,heightReference:_.CLAMP_TO_GROUND,classificationType:v.BOTH})}}hide(){this._entity&&(this._entity.show=!1),this._currentObject=void 0,this._currentOptions=void 0}destroy(){this._entities.contains(this._entity)&&this._entities.remove(this._entity),this._currentObject=void 0,this._currentOptions=void 0}get color(){return this._color}set color(t){this._color=t}get entity(){return this._entity}get currentObject(){return this._currentObject}};var y=class n{static instances=new WeakMap;_surface;_silhouette;_color=R.RED;constructor(t){this._surface=new l(t),this._silhouette=new s(t),this._surface.color=this._color,this._silhouette.color=this._color}static getInstance(t){let i=t.container;return n.instances.has(i)||n.instances.set(i,new n(t)),n.instances.get(i)}static releaseInstance(t){let i=t.container,e=n.instances.get(i);e&&(e.hide(),e._surface&&e._surface.destroy(),e._silhouette&&e._silhouette.destroy(),n.instances.delete(i))}show(t,i={color:this._color}){let e=this._getObject(t);if(H(e))return e instanceof P?this._silhouette.show(e,i):e instanceof p&&e.model?this._silhouette.show(e,i):this._surface.show(e,i)}_getObject(t){if(H(t)){if(t instanceof p||t instanceof P||t instanceof E)return t;if(t.id instanceof p)return t.id;if(t.primitive instanceof E)return t.primitive}}hide(){this._surface.hide(),this._silhouette.hide()}get color(){return this._color}set color(t){this._color=t,this._surface.color=t,this._silhouette.color=t}},V=y;export{s as a,l as b,V as c};
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var M=(n,e)=>{for(var t in e)T(n,t,{get:e[t],enumerable:!0})},O=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of S(e))!x.call(n,r)&&r!==t&&T(n,r,{get:()=>e[r],enumerable:!(i=P(e,r))||i.enumerable});return n};var F=n=>O(T({},"__esModule",{value:!0}),n);var V={};M(V,{Collection:()=>m});module.exports=F(V);var o=require("cesium");var s=require("cesium");var u=class n{_viewer;_collection;_terrainProvider;_visible=!1;_level=15;_tileCoordinatesLayer;_colors=new Map([["custom",s.Color.RED],["default",s.Color.BLUE],["fallback",s.Color.GRAY],["grid",s.Color.YELLOW]]);constructor(e,t){this._viewer=e,this._collection=new m({collection:e.entities,tag:n.tag.default}),t&&(t.colors&&Object.entries(t.colors).forEach(([i,r])=>{this._colors.set(i,r)}),t.tile!==void 0&&(this._visible=t.tile),t.activeLevel!==void 0&&(this._level=t.activeLevel),t.terrainProvider&&this.setTerrainProvider(t.terrainProvider))}setTerrainProvider(e){this._terrainProvider=e,this.update()}update(){this.clear(),this._visible&&this.show(this._level)}clear(){this._collection.remove(this._collection.tags)}show(e=15){if(!this._terrainProvider)return;this._collection.remove(n.tag.grid),this._level=e,this._ensureTileCoordinatesLayer();let t=this._getVisibleRectangle();if(!t||!this._isValidRectangle(t)){console.warn("Invalid visible rectangle detected, skipping grid display");return}this._displayTileGrid(t,e),this._visible=!0}_ensureTileCoordinatesLayer(){this._tileCoordinatesLayer||(this._tileCoordinatesLayer=this._viewer.imageryLayers.addImageryProvider(new s.TileCoordinatesImageryProvider({tilingScheme:this._terrainProvider.tilingScheme,color:s.Color.YELLOW})))}_isValidRectangle(e){return e&&Number.isFinite(e.west)&&Number.isFinite(e.south)&&Number.isFinite(e.east)&&Number.isFinite(e.north)&&e.west<=e.east&&e.south<=e.north}_displayTileGrid(e,t){let i=this._terrainProvider.tilingScheme;try{let r=this._calculateTileBounds(e,t,i);this._generateVisibleTiles(r,t,i).forEach(l=>{this._collection.add(l.entity,n.tag.grid)})}catch(r){console.error("Error displaying tile grid:",r)}}_calculateTileBounds(e,t,i){let r=i.positionToTileXY(s.Rectangle.northwest(e),t),a=i.positionToTileXY(s.Rectangle.southeast(e),t);if(!r||!a)throw new Error("Failed to calculate tile bounds");return{start:r,end:a}}_generateVisibleTiles(e,t,i){let r=[],l=Math.min(e.end.x-e.start.x+1,100),h=Math.min(e.end.y-e.start.y+1,100);for(let c=e.start.x;c<e.start.x+l;c++)for(let d=e.start.y;d<e.start.y+h;d++)try{let v=this._createTileEntity(c,d,t,i);v&&r.push({entity:v})}catch(v){console.warn(`Error creating tile (${c}, ${d}, ${t}):`,v)}return r}_createTileEntity(e,t,i,r){let a=r.tileXYToRectangle(e,t,i);if(!this._isValidRectangle(a))return null;let l=this._getTileColor(e,t,i),h=n.createRectangle(a,l.withAlpha(.3));return h.properties?.addProperty("tileX",e),h.properties?.addProperty("tileY",t),h.properties?.addProperty("tileLevel",i),h}_getTileColor(e,t,i){if(!this._terrainProvider)return this._colors.get("fallback")||s.Color.TRANSPARENT;for(let r of this._terrainProvider.terrainAreas)if(r.contains(e,t,i))return r.isCustom?this._colors.get("custom")||s.Color.RED:this._colors.get("default")||s.Color.BLUE;return this._terrainProvider.getTileDataAvailable(e,t,i)?this._colors.get("default")||s.Color.BLUE:this._colors.get("fallback")||s.Color.GRAY}hide(){this._collection.remove(n.tag.grid),this._tileCoordinatesLayer&&(this._viewer.imageryLayers.remove(this._tileCoordinatesLayer),this._tileCoordinatesLayer=void 0),this._visible=!1}setColors(e){Object.entries(e).forEach(([t,i])=>{this._colors.set(t,i)}),this.update()}flyTo(e,t){let{rectangle:i}=e;this._viewer.camera.flyTo({destination:i,...t,complete:()=>{this._visible&&this.update()}})}_getVisibleRectangle(){return this._viewer.camera.computeViewRectangle()}get level(){return this._level}set level(e){this._level=e,this._visible&&this.update()}get visible(){return this._visible}get collection(){return this._collection}get viewer(){return this._viewer}get colors(){return this._colors}get terrainProvider(){return this._terrainProvider}};(i=>{i.tag={default:"Terrain Visualizer",boundary:"Terrain Visualizer Boundary",grid:"Terrain Visualizer Tile Grid"};function e(r,a){return new s.Entity({rectangle:{coordinates:r,material:a,heightReference:s.HeightReference.CLAMP_TO_GROUND}})}i.createRectangle=e;function t(r,a,l){let h=l?.tag||"terrain_area_visualization",c=l?.color||s.Color.RED,d=l?.maxTilesToShow||100,v=l?.show??!0,E=l?.alpha||.7,w=l?.tileAlpha||.2,f=new m({collection:a.entities,tag:h}),{rectangle:L}=r;if(f.add(i.createRectangle(L,c.withAlpha(E)),h),v&&r.tileRanges.size>0){let{tilingScheme:I}=r.terrainProvider,_=0;r.tileRanges.forEach((g,R)=>{for(let p=g.start.x;p<=g.end.x&&_<d;p++)for(let y=g.start.y;y<=g.end.y&&_<d;y++){let A=I.tileXYToRectangle(p,y,R);f.add(e(A,c.withAlpha(w)),`${h}_tile`),_++}})}return f}i.visualize=t})(u||={});function C(n,e){let t=!1,i=Object.getOwnPropertyDescriptor(n,e);if(!i){let r=Object.getPrototypeOf(n);for(;r&&!i;)i=Object.getOwnPropertyDescriptor(r,e),r=Object.getPrototypeOf(r)}return i&&i.get&&!i.set&&(t=!0),t}var b=class n{static symbol=Symbol("cesium-item-tag");tag;collection;_valuesCache=null;_tagMap=new Map;_eventListeners=new Map;_eventCleanupFunctions=[];constructor({collection:e,tag:t}){this.tag=t||"default",this.collection=e,this._setupCacheInvalidator(e)}[Symbol.iterator](){return this.values[Symbol.iterator]()}_emit(e,t){let i=this._eventListeners.get(e);if(i){let r={type:e,...t};i.forEach(a=>a(r))}}_addToTagMap(e,t){this._tagMap.has(t)||this._tagMap.set(t,new Set),this._tagMap.get(t)?.add(e)}_removeFromTagMap(e){let t=e[n.symbol],i=this._tagMap.get(t);i&&(i.delete(e),i.size===0&&this._tagMap.delete(t))}_invalidateCache=()=>{this._valuesCache=null};_setupCacheInvalidator(e){e instanceof o.EntityCollection?(e.collectionChanged.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.collectionChanged.removeEventListener(this._invalidateCache))):e instanceof o.PrimitiveCollection?(e.primitiveAdded.addEventListener(this._invalidateCache),e.primitiveRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.primitiveAdded.removeEventListener(this._invalidateCache),()=>e.primitiveRemoved.removeEventListener(this._invalidateCache))):e instanceof o.DataSourceCollection?(e.dataSourceAdded.addEventListener(this._invalidateCache),e.dataSourceMoved.addEventListener(this._invalidateCache),e.dataSourceRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.dataSourceAdded.removeEventListener(this._invalidateCache),()=>e.dataSourceMoved.removeEventListener(this._invalidateCache),()=>e.dataSourceRemoved.removeEventListener(this._invalidateCache))):e instanceof o.ImageryLayerCollection&&(e.layerAdded.addEventListener(this._invalidateCache),e.layerMoved.addEventListener(this._invalidateCache),e.layerRemoved.addEventListener(this._invalidateCache),e.layerShownOrHidden.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.layerAdded.removeEventListener(this._invalidateCache),()=>e.layerMoved.removeEventListener(this._invalidateCache),()=>e.layerRemoved.removeEventListener(this._invalidateCache),()=>e.layerShownOrHidden.removeEventListener(this._invalidateCache)))}addEventListener(e,t){return this._eventListeners.has(e)||this._eventListeners.set(e,new Set),this._eventListeners.get(e)?.add(t),this}removeEventListener(e,t){return this._eventListeners.get(e)?.delete(t),this}add(e,t=this.tag,i){return Array.isArray(e)?e.forEach(r=>{this.add(r,t)}):(Object.defineProperty(e,n.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this.collection.add(e,i),this._addToTagMap(e,t),this._invalidateCache(),this._emit("add",{items:[e],tag:t})),e}contains(e){if(typeof e=="object")return this.collection.contains(e);let t=this._tagMap.get(e);return!!t&&t.size>0}remove(e){if(typeof e=="object"&&!Array.isArray(e)){let r=this.collection.remove(e);return r&&(this._removeFromTagMap(e),this._invalidateCache(),this._emit("remove",{items:[e]})),r}if(Array.isArray(e)){if(e.length===0)return!1;let r=!1;for(let a of e)this.remove(a)&&(r=!0);return r}let t=this.get(e);if(t.length===0)return!1;let i=!1;for(let r of t)this.remove(r)&&(i=!0);return i}removeAll(){this._tagMap.clear(),this.collection.removeAll(),this._invalidateCache(),this._emit("clear")}destroy(){this._eventCleanupFunctions.forEach(e=>e()),this._eventCleanupFunctions=[],this._tagMap.clear(),this._eventListeners.clear(),this._valuesCache=null}get values(){if(this._valuesCache!==null)return this._valuesCache;let e;if(this.collection instanceof o.EntityCollection)e=this.collection.values;else{e=[];for(let t=0;t<this.collection.length;t++)e.push(this.collection.get(t))}return this._valuesCache=e,e}get length(){return this.values?.length||0}get(e){let t=this._tagMap.get(e);return t?Array.from(t):[]}first(e){let t=this._tagMap.get(e);if(t&&t.size>0)return t.values().next().value}get tags(){return Array.from(this._tagMap.keys())}update(e,t){let i=this.get(e);for(let r of i)this._removeFromTagMap(r),Object.defineProperty(r,n.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this._addToTagMap(r,t);return i.length>0&&this._emit("update",{items:i,tag:t}),i.length}show(e){let t=this.get(e);for(let i of t)(0,o.defined)(i.show)&&(i.show=!0);return this}hide(e){let t=this.get(e);for(let i of t)(0,o.defined)(i.show)&&(i.show=!1);return this}toggle(e){let t=this.get(e);for(let i of t)(0,o.defined)(i.show)&&(i.show=!i.show);return this}setProperty(e,t,i=this.tag){let r=this.get(i);for(let a of r)if(e in a&&typeof a[e]!="function"){if(C(a,e))throw Error(`Cannot set read-only property '${String(e)}' on ${a.constructor.name}`);a[e]=t}return this}filter(e,t){return(t?this.get(t):this.values).filter(e)}forEach(e,t){(t?this.get(t):this.values).forEach((r,a)=>e(r,a))}map(e,t){return(t?this.get(t):this.values).map(e)}find(e,t){return(t?this.get(t):this.values).find(e)}},m=b;
1
+ "use strict";var C=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var M=(n,e)=>{for(var t in e)C(n,t,{get:e[t],enumerable:!0})},O=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of A(e))!S.call(n,r)&&r!==t&&C(n,r,{get:()=>e[r],enumerable:!(i=x(e,r))||i.enumerable});return n};var F=n=>O(C({},"__esModule",{value:!0}),n);var V={};M(V,{Collection:()=>m});module.exports=F(V);var s=require("cesium");var a=require("cesium");var u=class n{_viewer;_collection;_terrainProvider;_visible=!1;_level=15;_tileCoordinatesLayer;_colors=new Map([["custom",a.Color.RED],["default",a.Color.BLUE],["fallback",a.Color.GRAY],["grid",a.Color.YELLOW]]);constructor(e,t){this._viewer=e,this._collection=new m({collection:e.entities,tag:n.tag.default}),t&&(t.colors&&Object.entries(t.colors).forEach(([i,r])=>{this._colors.set(i,r)}),t.tile!==void 0&&(this._visible=t.tile),t.activeLevel!==void 0&&(this._level=t.activeLevel),t.terrainProvider&&this.setTerrainProvider(t.terrainProvider))}setTerrainProvider(e){this._terrainProvider=e,this.update()}update(){this.clear(),this._visible&&this.show(this._level)}clear(){this._collection.remove(this._collection.tags)}show(e=15){if(!this._terrainProvider)return;this._collection.remove(n.tag.grid),this._level=e,this._ensureTileCoordinatesLayer();let t=this._getVisibleRectangle();if(!t||!this._isValidRectangle(t)){console.warn("Invalid visible rectangle detected, skipping grid display");return}this._displayTileGrid(t,e),this._visible=!0}_ensureTileCoordinatesLayer(){this._tileCoordinatesLayer||(this._tileCoordinatesLayer=this._viewer.imageryLayers.addImageryProvider(new a.TileCoordinatesImageryProvider({tilingScheme:this._terrainProvider.tilingScheme,color:a.Color.YELLOW})))}_isValidRectangle(e){return e&&Number.isFinite(e.west)&&Number.isFinite(e.south)&&Number.isFinite(e.east)&&Number.isFinite(e.north)&&e.west<=e.east&&e.south<=e.north}_displayTileGrid(e,t){let i=this._terrainProvider.tilingScheme;try{let r=this._calculateTileBounds(e,t,i);this._generateVisibleTiles(r,t,i).forEach(l=>{this._collection.add(l.entity,n.tag.grid)})}catch(r){console.error("Error displaying tile grid:",r)}}_calculateTileBounds(e,t,i){let r=i.positionToTileXY(a.Rectangle.northwest(e),t),o=i.positionToTileXY(a.Rectangle.southeast(e),t);if(!r||!o)throw new Error("Failed to calculate tile bounds");return{start:r,end:o}}_generateVisibleTiles(e,t,i){let r=[],l=Math.min(e.end.x-e.start.x+1,100),c=Math.min(e.end.y-e.start.y+1,100);for(let h=e.start.x;h<e.start.x+l;h++)for(let d=e.start.y;d<e.start.y+c;d++)try{let v=this._createTileEntity(h,d,t,i);v&&r.push({entity:v})}catch(v){console.warn(`Error creating tile (${h}, ${d}, ${t}):`,v)}return r}_createTileEntity(e,t,i,r){let o=r.tileXYToRectangle(e,t,i);if(!this._isValidRectangle(o))return null;let l=this._getTileColor(e,t,i),c=n.createRectangle(o,l.withAlpha(.3));return c.properties?.addProperty("tileX",e),c.properties?.addProperty("tileY",t),c.properties?.addProperty("tileLevel",i),c}_getTileColor(e,t,i){if(!this._terrainProvider)return this._colors.get("fallback")||a.Color.TRANSPARENT;for(let r of this._terrainProvider.terrainAreas)if(r.contains(e,t,i))return r.isCustom?this._colors.get("custom")||a.Color.RED:this._colors.get("default")||a.Color.BLUE;return this._terrainProvider.getTileDataAvailable(e,t,i)?this._colors.get("default")||a.Color.BLUE:this._colors.get("fallback")||a.Color.GRAY}hide(){this._collection.remove(n.tag.grid),this._tileCoordinatesLayer&&(this._viewer.imageryLayers.remove(this._tileCoordinatesLayer),this._tileCoordinatesLayer=void 0),this._visible=!1}setColors(e){Object.entries(e).forEach(([t,i])=>{this._colors.set(t,i)}),this.update()}flyTo(e,t){let{rectangle:i}=e;this._viewer.camera.flyTo({destination:i,...t,complete:()=>{this._visible&&this.update()}})}_getVisibleRectangle(){return this._viewer.camera.computeViewRectangle()}get level(){return this._level}set level(e){this._level=e,this._visible&&this.update()}get visible(){return this._visible}get collection(){return this._collection}get viewer(){return this._viewer}get colors(){return this._colors}get terrainProvider(){return this._terrainProvider}};(i=>{i.tag={default:"Terrain Visualizer",boundary:"Terrain Visualizer Boundary",grid:"Terrain Visualizer Tile Grid"};function e(r,o){return new a.Entity({rectangle:{coordinates:r,material:o,heightReference:a.HeightReference.CLAMP_TO_GROUND}})}i.createRectangle=e;function t(r,o,l){let c=l?.tag||"terrain_area_visualization",h=l?.color||a.Color.RED,d=l?.maxTilesToShow||100,v=l?.show??!0,E=l?.alpha||.7,w=l?.tileAlpha||.2,f=new m({collection:o.entities,tag:c}),{rectangle:L}=r;if(f.add(i.createRectangle(L,h.withAlpha(E)),c),v&&r.tileRanges.size>0){let{tilingScheme:I}=r.terrainProvider,p=0;r.tileRanges.forEach((g,P)=>{for(let _=g.start.x;_<=g.end.x&&p<d;_++)for(let y=g.start.y;y<=g.end.y&&p<d;y++){let R=I.tileXYToRectangle(_,y,P);f.add(e(R,h.withAlpha(w)),`${c}_tile`),p++}})}return f}i.visualize=t})(u||={});function T(n,e){let t=!1,i=Object.getOwnPropertyDescriptor(n,e);if(!i){let r=Object.getPrototypeOf(n);for(;r&&!i;)i=Object.getOwnPropertyDescriptor(r,e),r=Object.getPrototypeOf(r)}return i&&i.get&&!i.set&&(t=!0),t}var b=class n{static symbol=Symbol("cesium-item-tag");tag;collection;_valuesCache=null;_tagMap=new Map;_eventListeners=new Map;_eventCleanupFunctions=[];constructor({collection:e,tag:t}){this.tag=t||"default",this.collection=e,this._setupCacheInvalidator(e)}[Symbol.iterator](){return this.values[Symbol.iterator]()}_emit(e,t){let i=this._eventListeners.get(e);if(i){let r={type:e,...t};i.forEach(o=>o(r))}}_addToTagMap(e,t){this._tagMap.has(t)||this._tagMap.set(t,new Set),this._tagMap.get(t)?.add(e)}_removeFromTagMap(e){let t=e[n.symbol],i=this._tagMap.get(t);i&&(i.delete(e),i.size===0&&this._tagMap.delete(t))}_invalidateCache=()=>{this._valuesCache=null};_setupCacheInvalidator(e){e instanceof s.EntityCollection?(e.collectionChanged.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.collectionChanged.removeEventListener(this._invalidateCache))):e instanceof s.PrimitiveCollection?(e.primitiveAdded.addEventListener(this._invalidateCache),e.primitiveRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.primitiveAdded.removeEventListener(this._invalidateCache),()=>e.primitiveRemoved.removeEventListener(this._invalidateCache))):e instanceof s.DataSourceCollection?(e.dataSourceAdded.addEventListener(this._invalidateCache),e.dataSourceMoved.addEventListener(this._invalidateCache),e.dataSourceRemoved.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.dataSourceAdded.removeEventListener(this._invalidateCache),()=>e.dataSourceMoved.removeEventListener(this._invalidateCache),()=>e.dataSourceRemoved.removeEventListener(this._invalidateCache))):e instanceof s.ImageryLayerCollection&&(e.layerAdded.addEventListener(this._invalidateCache),e.layerMoved.addEventListener(this._invalidateCache),e.layerRemoved.addEventListener(this._invalidateCache),e.layerShownOrHidden.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.layerAdded.removeEventListener(this._invalidateCache),()=>e.layerMoved.removeEventListener(this._invalidateCache),()=>e.layerRemoved.removeEventListener(this._invalidateCache),()=>e.layerShownOrHidden.removeEventListener(this._invalidateCache)))}addEventListener(e,t){return this._eventListeners.has(e)||this._eventListeners.set(e,new Set),this._eventListeners.get(e)?.add(t),this}removeEventListener(e,t){return this._eventListeners.get(e)?.delete(t),this}add(e,t=this.tag,i){return Array.isArray(e)?e.forEach(r=>{this.add(r,t)}):(Object.defineProperty(e,n.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this.collection.add(e,i),this._addToTagMap(e,t),this._invalidateCache(),this._emit("add",{items:[e],tag:t})),this}contains(e){if(typeof e=="object")return this.collection.contains(e);let t=this._tagMap.get(e);return!!t&&t.size>0}remove(e){if(typeof e=="object"&&!Array.isArray(e)&&this.collection.remove(e)&&(this._removeFromTagMap(e),this._invalidateCache(),this._emit("remove",{items:[e]})),Array.isArray(e)){if(e.length===0)return this;for(let i of e)this.remove(i)}let t=this.get(e);if(t.length===0)return this;for(let i of t)this.remove(i);return this}removeAll(){this._tagMap.clear(),this.collection.removeAll(),this._invalidateCache(),this._emit("clear")}destroy(){this._eventCleanupFunctions.forEach(e=>e()),this._eventCleanupFunctions=[],this._tagMap.clear(),this._eventListeners.clear(),this._valuesCache=null}get values(){if(this._valuesCache!==null)return this._valuesCache;let e;if(this.collection instanceof s.EntityCollection)e=this.collection.values;else{e=[];for(let t=0;t<this.collection.length;t++)e.push(this.collection.get(t))}return this._valuesCache=e,e}get length(){return this.values?.length||0}get(e){let t=this._tagMap.get(e);return t?Array.from(t):[]}first(e){let t=this._tagMap.get(e);if(t&&t.size>0)return t.values().next().value}get tags(){return Array.from(this._tagMap.keys())}update(e,t){let i=this.get(e);for(let r of i)this._removeFromTagMap(r),Object.defineProperty(r,n.symbol,{value:t,enumerable:!1,writable:!0,configurable:!0}),this._addToTagMap(r,t);return i.length>0&&this._emit("update",{items:i,tag:t}),i.length}show(e){let t=this.get(e);for(let i of t)(0,s.defined)(i.show)&&(i.show=!0);return this}hide(e){let t=this.get(e);for(let i of t)(0,s.defined)(i.show)&&(i.show=!1);return this}toggle(e){let t=this.get(e);for(let i of t)(0,s.defined)(i.show)&&(i.show=!i.show);return this}setProperty(e,t,i=this.tag){let r=this.get(i);for(let o of r)if(e in o&&typeof o[e]!="function"){if(T(o,e))throw Error(`Cannot set read-only property '${String(e)}' on ${o.constructor.name}`);o[e]=t}return this}filter(e,t){return(t?this.get(t):this.values).filter(e)}forEach(e,t){(t?this.get(t):this.values).forEach((r,o)=>e(r,o))}map(e,t){return(t?this.get(t):this.values).map(e)}find(e,t){return(t?this.get(t):this.values).find(e)}},m=b;
@@ -1,493 +1,2 @@
1
- import { DataSourceCollection, EntityCollection, ImageryLayerCollection, PrimitiveCollection, DataSource, Entity, ImageryLayer, Billboard, Cesium3DTileset, GroundPrimitive, Label, PointPrimitive, Polyline, Primitive } from 'cesium';
2
-
3
- type CesiumCollection = DataSourceCollection | EntityCollection | ImageryLayerCollection | PrimitiveCollection;
4
- type Primitives = Billboard | Cesium3DTileset | GroundPrimitive | Label | PointPrimitive | Polyline | Primitive;
5
- type CesiumCollectionItem = DataSource | Entity | ImageryLayer | Primitives;
6
- type Tag = string | number;
7
- interface WithTag {
8
- [key: symbol]: Tag;
9
- }
10
- /**
11
- * Collection event types
12
- */
13
- type CollectionEventType = "add" | "remove" | "update" | "clear";
14
- /**
15
- * Event handler function type
16
- */
17
- type EventHandler<I> = (event: {
18
- type: CollectionEventType;
19
- items?: I[];
20
- tag?: Tag;
21
- }) => void;
22
- type NonFunction<T> = {
23
- [K in keyof T]: T[K] extends Function ? never : K;
24
- }[keyof T];
25
-
26
- /**
27
- * @class
28
- * A wrapper class that enhances Cesium collection objects with tagging functionality.
29
- * This class provides a consistent API for working with different types of Cesium collections
30
- * and allows grouping and manipulating collection items by custom tags.
31
- *
32
- * @template C - The type of Cesium collection (e.g., EntityCollection, PrimitiveCollection)
33
- * @template I - The type of items in the collection (e.g., Entity, Primitive)
34
- *
35
- * @example
36
- * // Example 1: Managing Complex Scene with Multiple Object Types
37
- * class SceneOrganizer {
38
- * private entities: Collection<EntityCollection, Entity>;
39
- * private billboards: Collection<BillboardCollection, Billboard>;
40
- * private primitives: Collection<PrimitiveCollection, Primitive>;
41
- *
42
- * constructor(viewer: Viewer) {
43
- * this.entities = new Collection({ collection: viewer.entities });
44
- * this.billboards = new Collection({
45
- * collection: viewer.scene.primitives.add(new BillboardCollection())
46
- * });
47
- * this.primitives = new Collection({
48
- * collection: viewer.scene.primitives
49
- * });
50
- * }
51
- *
52
- * // Unified API across different collection types!
53
- * showLayer(layerName: string) {
54
- * this.entities.show(layerName);
55
- * this.billboards.show(layerName);
56
- * this.primitives.show(layerName);
57
- * }
58
- *
59
- * hideLayer(layerName: string) {
60
- * this.entities.hide(layerName);
61
- * this.billboards.hide(layerName);
62
- * this.primitives.hide(layerName);
63
- * }
64
- *
65
- * removeLayer(layerName: string) {
66
- * this.entities.remove(layerName);
67
- * this.billboards.remove(layerName);
68
- * this.primitives.remove(layerName);
69
- * }
70
- * }
71
- *
72
- * // Example 2: Extend the class for Domain-Specific Needs
73
- * class BuildingCollection extends Collection<EntityCollection, Entity> {
74
- * constructor(viewer: Viewer) {
75
- * super({ collection: viewer.entities, tag: 'buildings' });
76
- * }
77
- *
78
- * addBuilding(options: {
79
- * position: Cartesian3;
80
- * height: number;
81
- * floors: number;
82
- * type: 'residential' | 'commercial' | 'industrial';
83
- * }): Entity {
84
- * const building = new Entity({
85
- * position: options.position,
86
- * box: {
87
- * dimensions: new Cartesian3(50, 50, options.height),
88
- * material: this.getMaterialForType(options.type)
89
- * }
90
- * });
91
- *
92
- * // Tag by type AND by floor count
93
- * this.add(building, options.type);
94
- * this.add(building, `floors-${options.floors}`);
95
- *
96
- * return building;
97
- * }
98
- *
99
- * getByFloorRange(min: number, max: number): Entity[] {
100
- * const results: Entity[] = [];
101
- * for (let i = min; i <= max; i++) {
102
- * results.push(...this.get(`floors-${i}`));
103
- * }
104
- * return results;
105
- * }
106
- *
107
- * private getMaterialForType(type: string): Material {
108
- * const colors = {
109
- * residential: Color.GREEN,
110
- * commercial: Color.BLUE,
111
- * industrial: Color.YELLOW
112
- * };
113
- * return new ColorMaterialProperty(colors[type] || Color.WHITE);
114
- * }
115
- * }
116
- */
117
- declare class Collection<C extends CesiumCollection, I extends CesiumCollectionItem> {
118
- /**
119
- * Symbol used as a property key to store tags on collection items.
120
- * Using a Symbol ensures no property naming conflicts with the item's own properties.
121
- * @readonly
122
- */
123
- static readonly symbol: unique symbol;
124
- /**
125
- * Default tag used when adding items without specifying a tag.
126
- * @protected
127
- */
128
- protected tag: Tag;
129
- /**
130
- * The underlying Cesium collection being wrapped.
131
- * @protected
132
- */
133
- protected collection: C;
134
- /**
135
- * Cache for values array to improve performance
136
- * @private
137
- */
138
- private _valuesCache;
139
- /**
140
- * Tag to items map for faster lookups
141
- * @private
142
- */
143
- private _tagMap;
144
- /**
145
- * Event listeners
146
- * @private
147
- */
148
- private _eventListeners;
149
- /**
150
- * For cleaning up the instances
151
- * @private
152
- */
153
- private _eventCleanupFunctions;
154
- /**
155
- * Creates a new Collection instance.
156
- *
157
- * @param options - Configuration options
158
- * @param options.collection - The Cesium collection to wrap
159
- * @param options.tag - The default tag to use for items (defaults to 'default')
160
- */
161
- constructor({ collection, tag }: {
162
- collection: C;
163
- tag?: Tag;
164
- });
165
- /**
166
- * Makes the collection directly iterable, allowing it to be used in `for...of` loops
167
- * and with spread operators.
168
- *
169
- * @returns An iterator for the items in the collection
170
- *
171
- * @example
172
- * // Iterate through all items in the collection
173
- * for (const entity of collection) {
174
- * console.log(entity.id);
175
- * }
176
- *
177
- * // Convert collection to array using spread syntax
178
- * const entitiesArray = [...collection];
179
- */
180
- [Symbol.iterator](): Iterator<I>;
181
- /**
182
- * Emits an event to all registered listeners.
183
- *
184
- * @private
185
- * @param type - The event type
186
- * @param data - Additional event data
187
- */
188
- private _emit;
189
- /**
190
- * Adds an item to the internal tag map for quick lookups.
191
- *
192
- * @private
193
- * @param item - The item to add
194
- * @param tag - The tag to associate with the item
195
- */
196
- private _addToTagMap;
197
- /**
198
- * Removes an item from the internal tag map.
199
- *
200
- * @private
201
- * @param item - The item to remove
202
- */
203
- private _removeFromTagMap;
204
- /**
205
- * Invalidates the values cache when collection changes.
206
- *
207
- * @private
208
- */
209
- private _invalidateCache;
210
- /**
211
- * Sets up automatic cache invalidation by registering event listeners on the underlying Cesium collection.
212
- *
213
- * @private
214
- * @param collection - The Cesium collection to monitor for changes
215
- *
216
- * @see {@link destroy} For cleanup of event listeners
217
- * @see {@link _invalidateCache} For the actual cache invalidation logic
218
- */
219
- private _setupCacheInvalidator;
220
- /**
221
- * Registers an event listener for collection events.
222
- *
223
- * @param type - The event type to listen for
224
- * @param handler - The callback function
225
- * @returns The collection instance for method chaining
226
- */
227
- addEventListener(type: CollectionEventType, handler: EventHandler<I>): this;
228
- /**
229
- * Removes an event listener.
230
- *
231
- * @param type - The event type
232
- * @param handler - The callback function to remove
233
- * @returns The collection instance for method chaining
234
- */
235
- removeEventListener(type: CollectionEventType, handler: EventHandler<I>): this;
236
- /**
237
- * Adds a single item with a tag to the collection.
238
- *
239
- * @param item - The item to add to the collection
240
- * @param tag - Tag to associate with this item (defaults to the collection's default tag)
241
- * @param index - The index to add the item at (if supported by the collection)
242
- * @returns The added item for chaining
243
- *
244
- * @example
245
- * const entity = collection.add(new Entity({ ... }), 'landmarks');
246
- */
247
- add(item: I, tag?: Tag, index?: number): I;
248
- /**
249
- * Adds multiple items with the same tag to the collection.
250
- *
251
- * @param items - The array of items to add to the collection
252
- * @param tag - Tag to associate with this item (defaults to the collection's default tag)
253
- * @returns The array of added items
254
- *
255
- * @example
256
- * // Add multiple entities with the same tag
257
- * const entities = [new Entity({ ... }), new Entity({ ... })];
258
- * const addedEntities = collection.add(entities, 'buildings');
259
- */
260
- add(items: I[], tag?: Tag): I[];
261
- /**
262
- * Returns true if the provided item is in this collection, false otherwise.
263
- *
264
- * @param item - The item instance to check for
265
- * @returns True if the item is in the collection, false otherwise
266
- */
267
- contains(item: I): boolean;
268
- /**
269
- * Checks if the collection has any items with the specified tag.
270
- *
271
- * @param tag - The tag to check for
272
- * @returns True if items with the tag exist, false otherwise
273
- *
274
- * @example
275
- * if (collection.contains('temporary')) {
276
- * console.log('Temporary items exist');
277
- * }
278
- */
279
- contains(tag: Tag): boolean;
280
- /**
281
- * Removes an item from the collection.
282
- *
283
- * @param item - The item to remove
284
- * @returns True if the item was removed, false if it wasn't found
285
- */
286
- remove(item: I): boolean;
287
- /**
288
- * Removes all items with the specified tag from the collection.
289
- *
290
- * @param by - The tag identifying which items to remove
291
- * @returns True if the item was removed, false if it wasn't found
292
- */
293
- remove(by: Tag): boolean;
294
- /**
295
- * Removes all items with the array of tags from the collection.
296
- *
297
- * @param by - The tags identifying which items to remove
298
- * @returns True if the item was removed, false if it wasn't found
299
- */
300
- remove(by: Tag[]): boolean;
301
- /**
302
- * Removes all items from the collection.
303
- */
304
- removeAll(): void;
305
- /**
306
- * Permanently destroys this Collection instance.
307
- * Removes all event listeners and clears internal state.
308
- * The Collection instance should not be used after calling this method.
309
- */
310
- destroy(): void;
311
- /**
312
- * Gets all item instances in the collection.
313
- * This array should not be modified directly.
314
- *
315
- * @returns An array of all items in the collection
316
- */
317
- get values(): I[];
318
- /**
319
- * Gets the number of items in the collection.
320
- *
321
- * @returns The item count
322
- */
323
- get length(): number;
324
- /**
325
- * Gets all items with the specified tag from the collection.
326
- * Uses an optimized internal map for faster lookups.
327
- *
328
- * @param by - The tag to filter by
329
- * @returns An array of items with the specified tag, or an empty array if none found
330
- *
331
- * @example
332
- * // Get all buildings
333
- * const buildings = collection.get('buildings');
334
- */
335
- get(by: Tag): I[];
336
- /**
337
- * Gets the first item matching the tag. More efficient than `get` when
338
- * you only need one item, especially for large collections.
339
- *
340
- * @param by - The tag to search for
341
- * @returns The first matching item or undefined if none found
342
- *
343
- * @example
344
- * // Get the first building
345
- * const firstBuilding = collection.first('buildings');
346
- */
347
- first(by: Tag): I | undefined;
348
- /**
349
- * Gets all unique tags currently in use in the collection.
350
- *
351
- * @returns An array of all unique tags
352
- *
353
- * @example
354
- * // Get all tags
355
- * const tags = collection.tags;
356
- * console.log(`Collection has these tags: ${tags.join(', ')}`);
357
- */
358
- get tags(): Tag[];
359
- /**
360
- * Updates the tag for all items with the specified tag.
361
- *
362
- * @param from - The tag to replace
363
- * @param to - The new tag to assign
364
- * @returns The number of items updated
365
- *
366
- * @example
367
- * // Rename a tag
368
- * const count = collection.update('temp', 'temporary');
369
- * console.log(`Updated ${count} items`);
370
- */
371
- update(from: Tag, to: Tag): number;
372
- /**
373
- * Makes all items with the specified tag visible.
374
- * Only affects items that have a 'show' property.
375
- *
376
- * @param by - The tag identifying which items to show
377
- * @returns The collection itself.
378
- *
379
- * @example
380
- * // Show all buildings
381
- * collection.show('buildings');
382
- */
383
- show(by: Tag): this;
384
- /**
385
- * Hides all items with the specified tag.
386
- * Only affects items that have a 'show' property.
387
- *
388
- * @param by - The tag identifying which items to hide
389
- * @returns The collection itself.
390
- *
391
- * @example
392
- * // Hide all buildings
393
- * collection.hide('buildings');
394
- */
395
- hide(by: Tag): this;
396
- /**
397
- * Toggles visibility of all items with the specified tag.
398
- * Only affects items that have a 'show' property.
399
- *
400
- * @param by - The tag identifying which items to toggle
401
- * @returns The collection itself.
402
- *
403
- * @example
404
- * // Toggle visibility of all buildings
405
- * collection.toggle('buildings');
406
- */
407
- toggle(by: Tag): this;
408
- /**
409
- * Sets a property value on all items with the specified tag.
410
- *
411
- * @param by - The tag identifying which items to update
412
- * @param property - The property name to set
413
- * @param value - The value to set
414
- * @returns The number of items updated
415
- *
416
- * @example
417
- * // Change color of all buildings to red
418
- * collection.setProperty('buildings', 'color', Color.RED);
419
- */
420
- setProperty<K extends NonFunction<I>>(property: K, value: I[K], by?: Tag): this;
421
- /**
422
- * Filters items in the collection based on a predicate function.
423
- * Optionally only filters items with a specific tag.
424
- *
425
- * @param predicate - Function that tests each item
426
- * @param by - Optional tag to filter by before applying the predicate
427
- * @returns Array of items that pass the test
428
- *
429
- * @example
430
- * // Get all buildings taller than 100 meters
431
- * const tallBuildings = collection.filter(
432
- * entity => entity.properties?.height?.getValue() > 100,
433
- * 'buildings'
434
- * );
435
- */
436
- filter(predicate: (item: I) => boolean, by?: Tag): I[];
437
- /**
438
- * Executes a callback function for each item in the collection.
439
- * Optionally filters items by tag before execution.
440
- *
441
- * @param callback - Function to execute for each item
442
- * @param by - Optional tag to filter items (if not provided, processes all items)
443
- *
444
- * @example
445
- * // Highlight all buildings
446
- * collection.forEach((entity) => {
447
- * if (entity.polygon) {
448
- * entity.polygon.material = new ColorMaterialProperty(Color.YELLOW);
449
- * }
450
- * }, 'buildings');
451
- */
452
- forEach(callback: (value: I, index: number) => void, by?: Tag): void;
453
- /**
454
- * Creates a new array with the results of calling a provided function on every element
455
- * in the collection. Optionally filters by tag before mapping.
456
- *
457
- * @param callbackfn - Function that produces an element of the new array
458
- * @param by - Optional tag to filter items by before mapping
459
- * @returns A new array with each element being the result of the callback function
460
- *
461
- * @example
462
- * // Get all entity IDs
463
- * const entityIds = collection.map(entity => entity.id);
464
- *
465
- * // Get positions of all buildings
466
- * const buildingPositions = collection.map(
467
- * entity => entity.position.getValue(Cesium.JulianDate.now()),
468
- * 'buildings'
469
- * );
470
- */
471
- map<R>(callbackfn: (value: I, index: number) => R, by?: Tag): R[];
472
- /**
473
- * Returns the first element in the collection that satisfies the provided testing function.
474
- * Optionally filters by tag before searching.
475
- *
476
- * @param predicate - Function to test each element
477
- * @param by - Optional tag to filter items by before searching
478
- * @returns The first element that passes the test, or undefined if no elements pass
479
- *
480
- * @example
481
- * // Find the first entity with a specific name
482
- * const namedEntity = collection.find(entity => entity.name === 'Target');
483
- *
484
- * // Find the first building taller than 100 meters
485
- * const tallBuilding = collection.find(
486
- * entity => entity.properties?.height?.getValue() > 100,
487
- * 'buildings'
488
- * );
489
- */
490
- find(predicate: (value: I) => boolean, by?: Tag): I | undefined;
491
- }
492
-
493
- export { type CesiumCollection, type CesiumCollectionItem, Collection, type CollectionEventType, type EventHandler, type NonFunction, type Tag, type WithTag };
1
+ export { C as Collection } from '../index-Bd_-DTWl.cjs';
2
+ import 'cesium';