UNPKG

@juun-roh/cesium-utils

Version:

Solve common Cesium.js challenges: combine multiple terrain sources, tag and filter entity collections, and add visual highlights.

2 lines (1 loc) 20.7 kB
"use strict";var E=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var q=(n,e)=>{for(var t in e)E(n,t,{get:e[t],enumerable:!0})},z=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $(e))!W.call(n,r)&&r!==t&&E(n,r,{get:()=>e[r],enumerable:!(i=H(e,r))||i.enumerable});return n};var K=n=>z(E({},"__esModule",{value:!0}),n),D=(n,e,t,i)=>{for(var r=i>1?void 0:i?H(e,t):e,o=n.length-1,s;o>=0;o--)(s=n[o])&&(r=(i?s(e,t,r):s(r))||r);return i&&r&&E(e,t,r),r};var Q={};q(Q,{Collection:()=>S,Highlight:()=>M,HybridTerrainProvider:()=>k,SilhouetteHighlight:()=>p,SurfaceHighlight:()=>v,cloneViewer:()=>I,syncCamera:()=>P});module.exports=K(Q);var m=require("cesium");function w(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}function O(n,e,t){let i=e.split(".");for(let a of i)if(j(a))return{success:!1,reason:"dangerous-property",message:`Property path contains dangerous property name: "${a}"`};let r=n,o=0;for(;o<i.length-1;o++){let a=i[o];if(!r||typeof r!="object"||!Object.prototype.hasOwnProperty.call(r,a))return{success:!1,reason:"invalid-path",message:`Property path "${e}" does not exist or contains inherited properties`};if(r=r[a],!r||typeof r!="object"||r===Object.prototype)return{success:!1,reason:"invalid-path",message:`Cannot traverse path "${e}" - reached non-object or prototype`}}if(o!==i.length-1)return{success:!1,reason:"invalid-path",message:`Failed to traverse property path "${e}"`};let s=i[i.length-1];if(j(s))return{success:!1,reason:"dangerous-property",message:`Cannot set dangerous property "${s}"`};if(!r||typeof r!="object"||r===Object.prototype)return{success:!1,reason:"invalid-path",message:"Cannot set property on invalid target"};if(s in r){if(typeof r[s]=="function")return{success:!1,reason:"function-property",message:`Cannot set function property "${s}"`};if(w(r,s))return{success:!1,reason:"read-only",message:`Cannot set read-only property "${e}"`}}return r[s]=t,{success:!0}}var U=["__proto__","constructor","prototype"];function j(n){return U.includes(n)}var L=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]()}get values(){if(this._valuesCache!==null)return this._valuesCache;let e;if(this.collection instanceof m.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 tags(){return Array.from(this._tagMap.keys())}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(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}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,m.defined)(i.show)&&(i.show=!0);return this}hide(e){let t=this.get(e);for(let i of t)(0,m.defined)(i.show)&&(i.show=!1);return this}toggle(e){let t=this.get(e);for(let i of t)(0,m.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){let s=O(o,e,t);if(!s.success&&s.reason==="read-only")throw Error(`Cannot set read-only property '${e}' on ${o.constructor.name}`)}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)}_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 m.EntityCollection?(e.collectionChanged.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.collectionChanged.removeEventListener(this._invalidateCache))):e instanceof m.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 m.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 m.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)))}},S=L;var u=require("cesium");var d=require("cesium"),p=class{_color=d.Color.RED;_silhouette;_composite;_stages;_entity;_currentObject;_currentOptions;constructor(e){this._stages=e.scene.postProcessStages,this._silhouette=d.PostProcessStageLibrary.createEdgeDetectionStage(),this._silhouette.uniforms.color=this._color,this._silhouette.uniforms.length=.01,this._silhouette.selected=[],this._composite=d.PostProcessStageLibrary.createSilhouetteStage([this._silhouette]),this._stages.add(this._composite)}get color(){return this._color}set color(e){this._color=e}get currentObject(){return this._currentObject}show(e,t){if((0,d.defined)(e)&&!(this._currentObject===e&&this._optionsEqual(this._currentOptions,t))){this._clearHighlights();try{if(e instanceof d.Cesium3DTileFeature)this._silhouette.uniforms.color=t?.color||this._color,this._silhouette.selected.push(e);else{if(!e.model)return;this._entity=e,e.model.silhouetteSize=new d.ConstantProperty(t?.width||2),e.model.silhouetteColor=new d.ConstantProperty(t?.color||this._color)}this._currentObject=e,this._currentOptions=t?{...t}:void 0}catch(i){console.error("Failed to highlight object:",i),this._currentObject=void 0,this._currentOptions=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}_optionsEqual(e,t){return!e&&!t?!0:!e||!t?!1:e.outline===t.outline&&e.width===t.width&&d.Color.equals(e.color||this._color,t.color||this._color)}_clearHighlights(){this._silhouette.selected.length>0&&(this._silhouette.selected=[]),this._entity?.model&&(this._entity.model.silhouetteColor=new d.ConstantProperty(d.Color.TRANSPARENT),this._entity.model.silhouetteSize=new d.ConstantProperty(0),this._entity=void 0)}};var l=require("cesium"),v=class{_color=l.Color.RED;_entity;_entities;_currentObject;_currentOptions;constructor(e){this._entities=e.entities,this._entity=this._entities.add(new l.Entity({id:`highlight-entity-${Math.random().toString(36).substring(2)}`,show:!1}))}get color(){return this._color}set color(e){this._color=e}get entity(){return this._entity}get currentObject(){return this._currentObject}show(e,t){if(!(!(0,l.defined)(e)||!this._entity)){if(this._currentObject===e&&this._optionsEqual(this._currentOptions,t))return this._entity;this._clearGeometries();try{if(e instanceof l.Entity&&(e.polygon||e.polyline||e.rectangle))this._update(e,t);else if(e instanceof l.GroundPrimitive)this._update(e,t);else{this._currentObject=void 0,this._currentOptions=void 0;return}return this._currentObject=e,this._currentOptions=t?{...t}:void 0,this._entity.show=!0,this._entity}catch(i){console.error("Failed to highlight object:",i),this._currentObject=void 0,this._currentOptions=void 0;return}}}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}_optionsEqual(e,t){return!e&&!t?!0:!e||!t?!1:e.outline===t.outline&&e.width===t.width&&l.Color.equals(e.color||this._color,t.color||this._color)}_clearGeometries(){this._entity.polygon=void 0,this._entity.polyline=void 0,this._entity.rectangle=void 0}_update(e,t={color:this._color,outline:!1,width:2}){if(e instanceof l.Entity){if(e.polygon)if(t.outline){let i=e.polygon.hierarchy?.getValue();if(i&&i.positions){let r;i.positions.length>0&&!l.Cartesian3.equals(i.positions[0],i.positions[i.positions.length-1])?r=[...i.positions,i.positions[0]]:r=i.positions,this._entity.polyline=new l.PolylineGraphics({positions:r,material:t.color,width:t.width||2,clampToGround:!0})}}else{let i=e.polygon.hierarchy?.getValue();i&&(this._entity.polygon=new l.PolygonGraphics({hierarchy:i,material:t.color,heightReference:l.HeightReference.CLAMP_TO_GROUND,classificationType:e.polygon.classificationType?.getValue()||l.ClassificationType.BOTH}))}else if(e.polyline){let i=e.polyline.positions?.getValue();if(i){let r=e.polyline.width?.getValue();this._entity.polyline=new l.PolylineGraphics({positions:i,material:t.color,width:r+(t.width||2),clampToGround:!0})}}else if(e.rectangle)if(t.outline){let i=e.rectangle.coordinates?.getValue();if(i){let r=[l.Cartesian3.fromRadians(i.west,i.north),l.Cartesian3.fromRadians(i.east,i.north),l.Cartesian3.fromRadians(i.east,i.south),l.Cartesian3.fromRadians(i.west,i.south),l.Cartesian3.fromRadians(i.west,i.north)];this._entity.polyline=new l.PolylineGraphics({positions:r,material:t.color,width:t.width||2,clampToGround:!0})}}else{let i=e.rectangle.coordinates?.getValue();i&&(this._entity.rectangle=new l.RectangleGraphics({coordinates:i,material:t.color,heightReference:l.HeightReference.CLAMP_TO_GROUND}))}}else if(e instanceof l.GroundPrimitive){let i=e.geometryInstances,r=Array.isArray(i)?i[0]:i;if(!r.geometry.attributes.position)return;let o=r.geometry.attributes.position.values,s=[];for(let a=0;a<o.length;a+=3)s.push(new l.Cartesian3(o[a],o[a+1],o[a+2]));t.outline?this._entity.polyline=new l.PolylineGraphics({positions:s,material:t.color,width:t.width||2,clampToGround:!0}):this._entity.polygon=new l.PolygonGraphics({hierarchy:new l.PolygonHierarchy(s),material:t.color,heightReference:l.HeightReference.CLAMP_TO_GROUND,classificationType:l.ClassificationType.BOTH})}}};var A=class n{static instances=new WeakMap;_surface;_silhouette;_color=u.Color.RED;constructor(e){this._surface=new v(e),this._silhouette=new p(e),this._surface.color=this._color,this._silhouette.color=this._color}get color(){return this._color}set color(e){this._color=e,this._surface.color=e,this._silhouette.color=e}static getInstance(e){let t=e.container;return n.instances.has(t)||n.instances.set(t,new n(e)),n.instances.get(t)}static releaseInstance(e){let t=e.container,i=n.instances.get(t);i&&(i.hide(),i._surface&&i._surface.destroy(),i._silhouette&&i._silhouette.destroy(),n.instances.delete(t))}show(e,t={color:this._color}){let i=this._getObject(e);if((0,u.defined)(i))return i instanceof u.Cesium3DTileFeature?this._silhouette.show(i,t):i instanceof u.Entity&&i.model?this._silhouette.show(i,t):this._surface.show(i,t)}_getObject(e){if((0,u.defined)(e)){if(e instanceof u.Entity||e instanceof u.Cesium3DTileFeature||e instanceof u.GroundPrimitive)return e;if(e.id instanceof u.Entity)return e.id;if(e.primitive instanceof u.GroundPrimitive)return e.primitive}}hide(){this._surface.hide(),this._silhouette.hide()}},M=A;var y=require("cesium");var C=class n{static _instance;_level=n._fromEnv();constructor(){}static get(){return this._instance||(this._instance=new n),this._instance}debug(...e){this._emit(n.Level.debug,e)}info(...e){this._emit(n.Level.info,e)}warn(...e){this._emit(n.Level.warn,e)}error(...e){this._emit(n.Level.error,e)}static _fromEnv(){let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in n.Level?n.Level[e]:n.Level.info}_emit(e,t){if(e<this._level)return;let i=n.Level[e];console[i==="debug"?"log":i](`[${i.toUpperCase()}]`.padEnd(n.LABEL_PAD+2),...t)}};(t=>{let n;(a=>(a[a.debug=0]="debug",a[a.info=1]="info",a[a.warn=2]="warn",a[a.error=3]="error"))(n=t.Level||={}),t.LABEL_PAD=Math.max(...Object.keys(t.Level).map(i=>i.length))})(C||={});var V=C;var Y=V.get();function b({once:n=!0,includeStack:e=!1,message:t}){return(i,r,o)=>{let{label:s}=t;function a(){(!n||!b.has(s))&&(Y.warn(J(t)),e&&console.trace("Deprecation stack trace:"),b.add(s))}if(r===void 0)return class extends i{constructor(...f){a(),super(...f)}};if(o===void 0){a();return}if(o.get){let f=o.get;if(o.get=function(){return a(),f.call(this)},o.set){let h=o.set;o.set=function(_){a(),h.call(this,_)}}return o}if(o.set){let f=o.set;return o.set=function(h){a(),f.call(this,h)},o}if(typeof o.value=="function"){let f=o.value;return o.value=function(...h){return a(),f.apply(this,h)},o}return o}}(o=>{let n=new Set;function e(s){n.add(s)}o.add=e;function t(){n.clear()}o.clear=t;function i(){return n.size}o.size=i;function r(s){return n.has(s)}o.has=r})(b||={});function J({label:n,since:e,removedIn:t,replacement:i,additional:r}){return[`${n} is deprecated since ${e}.`,i?`Use ${i} instead.`:void 0,`This will be removed in ${t}.`,r].filter(Boolean).join(" ")}var G=b;var g=class g{_regions;_defaultProvider;_fallbackProvider;_tilingScheme;_ready=!1;_availability;_errorEvent;_removeEventListeners;_hasWaterMask;_hasVertexNormals;constructor(e){this._defaultProvider=e.defaultProvider,this._fallbackProvider=e.fallbackProvider||new y.EllipsoidTerrainProvider,this._tilingScheme=e.defaultProvider.tilingScheme,this._regions=e.regions||[],this._availability=e.defaultProvider.availability,this._hasWaterMask=this._defaultProvider.hasWaterMask||this._regions.some(i=>i.provider.hasWaterMask),this._hasVertexNormals=this._defaultProvider.hasVertexNormals||this._regions.some(i=>i.provider.hasVertexNormals),this._errorEvent=new y.Event,this._removeEventListeners=[];let t=new Set;for(let i of this._regions)t.has(i.provider)||(t.add(i.provider),this._removeEventListeners.push(i.provider.errorEvent.addEventListener(r=>{this._errorEvent.raiseEvent(r)})));t.has(this._defaultProvider)||this._removeEventListeners.push(this._defaultProvider.errorEvent.addEventListener(i=>{this._errorEvent.raiseEvent(i)})),t.has(this._fallbackProvider)||this._removeEventListeners.push(this._fallbackProvider.errorEvent.addEventListener(i=>{this._errorEvent.raiseEvent(i)})),this._ready=!0}get ready(){return this._ready}get tilingScheme(){return this._tilingScheme}get availability(){return this._availability}get regions(){return[...this._regions]}get defaultProvider(){return this._defaultProvider}get fallbackProvider(){return this._fallbackProvider}get credit(){let e=new Set,t=[];for(let i of this._regions){if(e.has(i.provider))continue;e.add(i.provider);let r=i.provider.credit?.html;r&&t.push(r)}if(!e.has(this._defaultProvider)){let i=this._defaultProvider.credit?.html;i&&t.push(i)}return new y.Credit(t.join(" "))}get errorEvent(){return this._errorEvent}get hasWaterMask(){return this._hasWaterMask}get hasVertexNormals(){return this._hasVertexNormals}loadTileDataAvailability(e,t,i){for(let r of this._regions)if(g.regionContainsTile(r,e,t,i))return r.provider.loadTileDataAvailability(e,t,i);return this._defaultProvider.loadTileDataAvailability(e,t,i)}getLevelMaximumGeometricError(e){let t=this._defaultProvider.getLevelMaximumGeometricError(e);for(let i of this._regions){let r=i.provider.getLevelMaximumGeometricError(e);r>t&&(t=r)}return t}requestTileGeometry(e,t,i,r){if(this._ready){for(let o of this._regions)if(g.regionContainsTile(o,e,t,i))return o.provider.requestTileGeometry(e,t,i,r);return this._defaultProvider.getTileDataAvailable(e,t,i)?this._defaultProvider.requestTileGeometry(e,t,i,r):this._fallbackProvider.requestTileGeometry(e,t,i,r)}}getTileDataAvailable(e,t,i){for(let r of this._regions)if(g.regionContainsTile(r,e,t,i))return!0;return this._defaultProvider.getTileDataAvailable(e,t,i)}destroy(){for(let e of this._removeEventListeners)e();this._removeEventListeners.length=0,this._ready=!1}};D([G({message:{label:"_fallbackProvider",since:"0.4.6",removedIn:"0.5.0"}})],g.prototype,"fallbackProvider",1);var T=g;(i=>{function n(r,o,s){return new i({regions:r.map(a=>({...a})),defaultProvider:o,fallbackProvider:s})}i.fromTileRanges=n;function e(r,o,s,a){if(r.levels&&!r.levels.includes(a))return!1;if(r.tiles){let c=r.tiles.get(a);if(!c)return!1;let[f,h]=Array.isArray(c.x)?c.x:[c.x,c.x],[_,x]=Array.isArray(c.y)?c.y:[c.y,c.y];return o>=f&&o<=h&&s>=_&&s<=x}return!1}i.regionContainsTile=e;let t;(o=>{function r(s,a,c,f){if(s.levels&&!s.levels.includes(f))return!1;if(s.tiles){let h=s.tiles.get(f);if(!h)return!1;let[_,x]=Array.isArray(h.x)?h.x:[h.x,h.x],[F,B]=Array.isArray(h.y)?h.y:[h.y,h.y];return a>=_&&a<=x&&c>=F&&c<=B}return!1}o.contains=r})(t=i.TerrainRegion||={})})(T||={});var k=T;var N=require("cesium");var R=require("cesium");function P(n,e){if((0,R.defined)(n)&&(0,R.defined)(e)){let{camera:t}=n;e.camera.position=t.positionWC.clone(),e.camera.direction=t.directionWC.clone(),e.camera.up=t.upWC.clone()}}function I(n,e,t){let i={baseLayerPicker:n.baseLayerPicker!==void 0,geocoder:n.geocoder!==void 0,homeButton:n.homeButton!==void 0,sceneModePicker:n.sceneModePicker!==void 0,timeline:n.timeline!==void 0,navigationHelpButton:n.navigationHelpButton!==void 0,animation:n.animation!==void 0,fullscreenButton:n.fullscreenButton!==void 0,shouldAnimate:n.clock.shouldAnimate,terrainProvider:n.terrainProvider,requestRenderMode:n.scene.requestRenderMode,infoBox:n.infoBox!==void 0},r=new N.Viewer(e,{...i,...t});P(n,r);let o=n.imageryLayers;r.imageryLayers.removeAll();for(let c=0;c<o.length;c++){let f=o.get(c);r.imageryLayers.addImageryProvider(f.imageryProvider,c)}r.clock.startTime=n.clock.startTime.clone(),r.clock.stopTime=n.clock.stopTime.clone(),r.clock.currentTime=n.clock.currentTime.clone(),r.clock.multiplier=n.clock.multiplier,r.clock.clockStep=n.clock.clockStep,r.clock.clockRange=n.clock.clockRange,r.clock.shouldAnimate=n.clock.shouldAnimate,r.scene.globe.enableLighting=n.scene.globe.enableLighting,r.scene.globe.depthTestAgainstTerrain=n.scene.globe.depthTestAgainstTerrain,r.scene.screenSpaceCameraController.enableCollisionDetection=n.scene.screenSpaceCameraController.enableCollisionDetection;let s=n.scene.screenSpaceCameraController.tiltEventTypes;s&&(r.scene.screenSpaceCameraController.tiltEventTypes=Array.isArray(s)?[...s]:s);let a=n.scene.screenSpaceCameraController.zoomEventTypes;return a&&(r.scene.screenSpaceCameraController.zoomEventTypes=Array.isArray(a)?[...a]:a),r}