@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 kB
JavaScript
var X=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var k=(n,e,t,i)=>{for(var r=i>1?void 0:i?Z(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&&X(e,t,r),r};import{DataSourceCollection as te,defined as x,EntityCollection as I,ImageryLayerCollection as ie,PrimitiveCollection as re}from"cesium";function P(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 E(n,e,t){let i=e.split(".");for(let a of i)if(R(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(R(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(P(r,s))return{success:!1,reason:"read-only",message:`Cannot set read-only property "${e}"`}}return r[s]=t,{success:!0}}var ee=["__proto__","constructor","prototype"];function R(n){return ee.includes(n)}var w=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 I)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)x(i.show)&&(i.show=!0);return this}hide(e){let t=this.get(e);for(let i of t)x(i.show)&&(i.show=!1);return this}toggle(e){let t=this.get(e);for(let i of t)x(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=E(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 I?(e.collectionChanged.addEventListener(this._invalidateCache),this._eventCleanupFunctions.push(()=>e.collectionChanged.removeEventListener(this._invalidateCache))):e instanceof re?(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 te?(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 ie&&(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)))}},H=w;import{Cesium3DTileFeature as F,Color as ce,defined as B,Entity as A,GroundPrimitive as $}from"cesium";import{Cesium3DTileFeature as ne,Color as O,ConstantProperty as _,defined as oe,PostProcessStageLibrary as D}from"cesium";var d=class{_color=O.RED;_silhouette;_composite;_stages;_entity;_currentObject;_currentOptions;constructor(e){this._stages=e.scene.postProcessStages,this._silhouette=D.createEdgeDetectionStage(),this._silhouette.uniforms.color=this._color,this._silhouette.uniforms.length=.01,this._silhouette.selected=[],this._composite=D.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(oe(e)&&!(this._currentObject===e&&this._optionsEqual(this._currentOptions,t))){this._clearHighlights();try{if(e instanceof ne)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 _(t?.width||2),e.model.silhouetteColor=new _(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&&O.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 _(O.TRANSPARENT),this._entity.model.silhouetteSize=new _(0),this._entity=void 0)}};import{Cartesian3 as u,ClassificationType as j,Color as V,defined as se,Entity as L,GroundPrimitive as G,HeightReference as S,PolygonGraphics as N,PolygonHierarchy as ae,PolylineGraphics as C,RectangleGraphics as le}from"cesium";var f=class{_color=V.RED;_entity;_entities;_currentObject;_currentOptions;constructor(e){this._entities=e.entities,this._entity=this._entities.add(new L({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(!(!se(e)||!this._entity)){if(this._currentObject===e&&this._optionsEqual(this._currentOptions,t))return this._entity;this._clearGeometries();try{if(e instanceof L&&(e.polygon||e.polyline||e.rectangle))this._update(e,t);else if(e instanceof G)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&&V.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){if(e.polygon)if(t.outline){let i=e.polygon.hierarchy?.getValue();if(i&&i.positions){let r;i.positions.length>0&&!u.equals(i.positions[0],i.positions[i.positions.length-1])?r=[...i.positions,i.positions[0]]:r=i.positions,this._entity.polyline=new C({positions:r,material:t.color,width:t.width||2,clampToGround:!0})}}else{let i=e.polygon.hierarchy?.getValue();i&&(this._entity.polygon=new N({hierarchy:i,material:t.color,heightReference:S.CLAMP_TO_GROUND,classificationType:e.polygon.classificationType?.getValue()||j.BOTH}))}else if(e.polyline){let i=e.polyline.positions?.getValue();if(i){let r=e.polyline.width?.getValue();this._entity.polyline=new C({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=[u.fromRadians(i.west,i.north),u.fromRadians(i.east,i.north),u.fromRadians(i.east,i.south),u.fromRadians(i.west,i.south),u.fromRadians(i.west,i.north)];this._entity.polyline=new C({positions:r,material:t.color,width:t.width||2,clampToGround:!0})}}else{let i=e.rectangle.coordinates?.getValue();i&&(this._entity.rectangle=new le({coordinates:i,material:t.color,heightReference:S.CLAMP_TO_GROUND}))}}else if(e instanceof G){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 u(o[a],o[a+1],o[a+2]));t.outline?this._entity.polyline=new C({positions:s,material:t.color,width:t.width||2,clampToGround:!0}):this._entity.polygon=new N({hierarchy:new ae(s),material:t.color,heightReference:S.CLAMP_TO_GROUND,classificationType:j.BOTH})}}};var M=class n{static instances=new WeakMap;_surface;_silhouette;_color=ce.RED;constructor(e){this._surface=new f(e),this._silhouette=new d(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(B(i))return i instanceof F?this._silhouette.show(i,t):i instanceof A&&i.model?this._silhouette.show(i,t):this._surface.show(i,t)}_getObject(e){if(B(e)){if(e instanceof A||e instanceof F||e instanceof $)return e;if(e.id instanceof A)return e.id;if(e.primitive instanceof $)return e.primitive}}hide(){this._surface.hide(),this._silhouette.hide()}},W=M;import{Credit as ue,EllipsoidTerrainProvider as fe,Event as me}from"cesium";var v=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))})(v||={});var q=v;var he=q.get();function g({once:n=!0,includeStack:e=!1,message:t}){return(i,r,o)=>{let{label:s}=t;function a(){(!n||!g.has(s))&&(he.warn(de(t)),e&&console.trace("Deprecation stack trace:"),g.add(s))}if(r===void 0)return class extends i{constructor(...h){a(),super(...h)}};if(o===void 0){a();return}if(o.get){let h=o.get;if(o.get=function(){return a(),h.call(this)},o.set){let c=o.set;o.set=function(p){a(),c.call(this,p)}}return o}if(o.set){let h=o.set;return o.set=function(c){a(),h.call(this,c)},o}if(typeof o.value=="function"){let h=o.value;return o.value=function(...c){return a(),h.apply(this,c)},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})(g||={});function de({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 z=g;var m=class m{_regions;_defaultProvider;_fallbackProvider;_tilingScheme;_ready=!1;_availability;_errorEvent;_removeEventListeners;_hasWaterMask;_hasVertexNormals;constructor(e){this._defaultProvider=e.defaultProvider,this._fallbackProvider=e.fallbackProvider||new fe,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 me,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 ue(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(m.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(m.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(m.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}};k([z({message:{label:"_fallbackProvider",since:"0.4.6",removedIn:"0.5.0"}})],m.prototype,"fallbackProvider",1);var y=m;(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 l=r.tiles.get(a);if(!l)return!1;let[h,c]=Array.isArray(l.x)?l.x:[l.x,l.x],[p,T]=Array.isArray(l.y)?l.y:[l.y,l.y];return o>=h&&o<=c&&s>=p&&s<=T}return!1}i.regionContainsTile=e;let t;(o=>{function r(s,a,l,h){if(s.levels&&!s.levels.includes(h))return!1;if(s.tiles){let c=s.tiles.get(h);if(!c)return!1;let[p,T]=Array.isArray(c.x)?c.x:[c.x,c.x],[J,Q]=Array.isArray(c.y)?c.y:[c.y,c.y];return a>=p&&a<=T&&l>=J&&l<=Q}return!1}o.contains=r})(t=i.TerrainRegion||={})})(y||={});var K=y;import{Viewer as pe}from"cesium";import{defined as U}from"cesium";function b(n,e){if(U(n)&&U(e)){let{camera:t}=n;e.camera.position=t.positionWC.clone(),e.camera.direction=t.directionWC.clone(),e.camera.up=t.upWC.clone()}}function Y(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 pe(e,{...i,...t});b(n,r);let o=n.imageryLayers;r.imageryLayers.removeAll();for(let l=0;l<o.length;l++){let h=o.get(l);r.imageryLayers.addImageryProvider(h.imageryProvider,l)}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}export{H as Collection,W as Highlight,K as HybridTerrainProvider,d as SilhouetteHighlight,f as SurfaceHighlight,Y as cloneViewer,b as syncCamera};