Viewer.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  1. import BoundingSphere from "../../Core/BoundingSphere.js";
  2. import Cartesian3 from "../../Core/Cartesian3.js";
  3. import Cartographic from "../../Core/Cartographic.js";
  4. import Clock from "../../Core/Clock.js";
  5. import defaultValue from "../../Core/defaultValue.js";
  6. import defer from "../../Core/defer.js";
  7. import defined from "../../Core/defined.js";
  8. import destroyObject from "../../Core/destroyObject.js";
  9. import DeveloperError from "../../Core/DeveloperError.js";
  10. import Event from "../../Core/Event.js";
  11. import EventHelper from "../../Core/EventHelper.js";
  12. import HeadingPitchRange from "../../Core/HeadingPitchRange.js";
  13. import Matrix4 from "../../Core/Matrix4.js";
  14. import ScreenSpaceEventType from "../../Core/ScreenSpaceEventType.js";
  15. import BoundingSphereState from "../../DataSources/BoundingSphereState.js";
  16. import ConstantPositionProperty from "../../DataSources/ConstantPositionProperty.js";
  17. import DataSourceCollection from "../../DataSources/DataSourceCollection.js";
  18. import DataSourceDisplay from "../../DataSources/DataSourceDisplay.js";
  19. import Entity from "../../DataSources/Entity.js";
  20. import EntityView from "../../DataSources/EntityView.js";
  21. import Property from "../../DataSources/Property.js";
  22. import Cesium3DTileset from "../../Scene/Cesium3DTileset.js";
  23. import computeFlyToLocationForRectangle from "../../Scene/computeFlyToLocationForRectangle.js";
  24. import ImageryLayer from "../../Scene/ImageryLayer.js";
  25. import SceneMode from "../../Scene/SceneMode.js";
  26. import TimeDynamicPointCloud from "../../Scene/TimeDynamicPointCloud.js";
  27. import knockout from "../../ThirdParty/knockout.js";
  28. import Animation from "../Animation/Animation.js";
  29. import AnimationViewModel from "../Animation/AnimationViewModel.js";
  30. import BaseLayerPicker from "../BaseLayerPicker/BaseLayerPicker.js";
  31. import createDefaultImageryProviderViewModels from "../BaseLayerPicker/createDefaultImageryProviderViewModels.js";
  32. import createDefaultTerrainProviderViewModels from "../BaseLayerPicker/createDefaultTerrainProviderViewModels.js";
  33. import CesiumWidget from "../CesiumWidget/CesiumWidget.js";
  34. import ClockViewModel from "../ClockViewModel.js";
  35. import FullscreenButton from "../FullscreenButton/FullscreenButton.js";
  36. import Geocoder from "../Geocoder/Geocoder.js";
  37. import getElement from "../getElement.js";
  38. import HomeButton from "../HomeButton/HomeButton.js";
  39. import InfoBox from "../InfoBox/InfoBox.js";
  40. import NavigationHelpButton from "../NavigationHelpButton/NavigationHelpButton.js";
  41. import ProjectionPicker from "../ProjectionPicker/ProjectionPicker.js";
  42. import SceneModePicker from "../SceneModePicker/SceneModePicker.js";
  43. import SelectionIndicator from "../SelectionIndicator/SelectionIndicator.js";
  44. import subscribeAndEvaluate from "../subscribeAndEvaluate.js";
  45. import Timeline from "../Timeline/Timeline.js";
  46. import VRButton from "../VRButton/VRButton.js";
  47. import Cesium3DTileFeature from "../../Scene/Cesium3DTileFeature.js";
  48. import JulianDate from "../../Core/JulianDate.js";
  49. import CesiumMath from "../../Core/Math.js";
  50. const boundingSphereScratch = new BoundingSphere();
  51. function onTimelineScrubfunction(e) {
  52. const clock = e.clock;
  53. clock.currentTime = e.timeJulian;
  54. clock.shouldAnimate = false;
  55. }
  56. function getCesium3DTileFeatureDescription(feature) {
  57. const propertyNames = feature.getPropertyNames();
  58. let html = "";
  59. propertyNames.forEach(function (propertyName) {
  60. const value = feature.getProperty(propertyName);
  61. if (defined(value)) {
  62. html += `<tr><th>${propertyName}</th><td>${value}</td></tr>`;
  63. }
  64. });
  65. if (html.length > 0) {
  66. html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
  67. }
  68. return html;
  69. }
  70. function getCesium3DTileFeatureName(feature) {
  71. // We need to iterate all property names to find potential
  72. // candidates, but since we prefer some property names
  73. // over others, we store them in an indexed array
  74. // and then use the first defined element in the array
  75. // as the preferred choice.
  76. let i;
  77. const possibleNames = [];
  78. const propertyNames = feature.getPropertyNames();
  79. for (i = 0; i < propertyNames.length; i++) {
  80. const propertyName = propertyNames[i];
  81. if (/^name$/i.test(propertyName)) {
  82. possibleNames[0] = feature.getProperty(propertyName);
  83. } else if (/name/i.test(propertyName)) {
  84. possibleNames[1] = feature.getProperty(propertyName);
  85. } else if (/^title$/i.test(propertyName)) {
  86. possibleNames[2] = feature.getProperty(propertyName);
  87. } else if (/^(id|identifier)$/i.test(propertyName)) {
  88. possibleNames[3] = feature.getProperty(propertyName);
  89. } else if (/element/i.test(propertyName)) {
  90. possibleNames[4] = feature.getProperty(propertyName);
  91. } else if (/(id|identifier)$/i.test(propertyName)) {
  92. possibleNames[5] = feature.getProperty(propertyName);
  93. }
  94. }
  95. const length = possibleNames.length;
  96. for (i = 0; i < length; i++) {
  97. const item = possibleNames[i];
  98. if (defined(item) && item !== "") {
  99. return item;
  100. }
  101. }
  102. return "Unnamed Feature";
  103. }
  104. function pickEntity(viewer, e) {
  105. const picked = viewer.scene.pick(e.position);
  106. if (defined(picked)) {
  107. const id = defaultValue(picked.id, picked.primitive.id);
  108. if (id instanceof Entity) {
  109. return id;
  110. }
  111. if (picked instanceof Cesium3DTileFeature) {
  112. return new Entity({
  113. name: getCesium3DTileFeatureName(picked),
  114. description: getCesium3DTileFeatureDescription(picked),
  115. feature: picked,
  116. });
  117. }
  118. }
  119. // No regular entity picked. Try picking features from imagery layers.
  120. if (defined(viewer.scene.globe)) {
  121. return pickImageryLayerFeature(viewer, e.position);
  122. }
  123. }
  124. const scratchStopTime = new JulianDate();
  125. function trackDataSourceClock(timeline, clock, dataSource) {
  126. if (defined(dataSource)) {
  127. const dataSourceClock = dataSource.clock;
  128. if (defined(dataSourceClock)) {
  129. dataSourceClock.getValue(clock);
  130. if (defined(timeline)) {
  131. const startTime = dataSourceClock.startTime;
  132. let stopTime = dataSourceClock.stopTime;
  133. // When the start and stop times are equal, set the timeline to the shortest interval
  134. // starting at the start time. This prevents an invalid timeline configuration.
  135. if (JulianDate.equals(startTime, stopTime)) {
  136. stopTime = JulianDate.addSeconds(
  137. startTime,
  138. CesiumMath.EPSILON2,
  139. scratchStopTime
  140. );
  141. }
  142. timeline.updateFromClock();
  143. timeline.zoomTo(startTime, stopTime);
  144. }
  145. }
  146. }
  147. }
  148. const cartesian3Scratch = new Cartesian3();
  149. function pickImageryLayerFeature(viewer, windowPosition) {
  150. const scene = viewer.scene;
  151. const pickRay = scene.camera.getPickRay(windowPosition);
  152. const imageryLayerFeaturePromise = scene.imageryLayers.pickImageryLayerFeatures(
  153. pickRay,
  154. scene
  155. );
  156. if (!defined(imageryLayerFeaturePromise)) {
  157. return;
  158. }
  159. // Imagery layer feature picking is asynchronous, so put up a message while loading.
  160. const loadingMessage = new Entity({
  161. id: "Loading...",
  162. description: "Loading feature information...",
  163. });
  164. imageryLayerFeaturePromise.then(
  165. function (features) {
  166. // Has this async pick been superseded by a later one?
  167. if (viewer.selectedEntity !== loadingMessage) {
  168. return;
  169. }
  170. if (!defined(features) || features.length === 0) {
  171. viewer.selectedEntity = createNoFeaturesEntity();
  172. return;
  173. }
  174. // Select the first feature.
  175. const feature = features[0];
  176. const entity = new Entity({
  177. id: feature.name,
  178. description: feature.description,
  179. });
  180. if (defined(feature.position)) {
  181. const ecfPosition = viewer.scene.globe.ellipsoid.cartographicToCartesian(
  182. feature.position,
  183. cartesian3Scratch
  184. );
  185. entity.position = new ConstantPositionProperty(ecfPosition);
  186. }
  187. viewer.selectedEntity = entity;
  188. },
  189. function () {
  190. // Has this async pick been superseded by a later one?
  191. if (viewer.selectedEntity !== loadingMessage) {
  192. return;
  193. }
  194. viewer.selectedEntity = createNoFeaturesEntity();
  195. }
  196. );
  197. return loadingMessage;
  198. }
  199. function createNoFeaturesEntity() {
  200. return new Entity({
  201. id: "None",
  202. description: "No features found.",
  203. });
  204. }
  205. function enableVRUI(viewer, enabled) {
  206. const geocoder = viewer._geocoder;
  207. const homeButton = viewer._homeButton;
  208. const sceneModePicker = viewer._sceneModePicker;
  209. const projectionPicker = viewer._projectionPicker;
  210. const baseLayerPicker = viewer._baseLayerPicker;
  211. const animation = viewer._animation;
  212. const timeline = viewer._timeline;
  213. const fullscreenButton = viewer._fullscreenButton;
  214. const infoBox = viewer._infoBox;
  215. const selectionIndicator = viewer._selectionIndicator;
  216. const visibility = enabled ? "hidden" : "visible";
  217. if (defined(geocoder)) {
  218. geocoder.container.style.visibility = visibility;
  219. }
  220. if (defined(homeButton)) {
  221. homeButton.container.style.visibility = visibility;
  222. }
  223. if (defined(sceneModePicker)) {
  224. sceneModePicker.container.style.visibility = visibility;
  225. }
  226. if (defined(projectionPicker)) {
  227. projectionPicker.container.style.visibility = visibility;
  228. }
  229. if (defined(baseLayerPicker)) {
  230. baseLayerPicker.container.style.visibility = visibility;
  231. }
  232. if (defined(animation)) {
  233. animation.container.style.visibility = visibility;
  234. }
  235. if (defined(timeline)) {
  236. timeline.container.style.visibility = visibility;
  237. }
  238. if (
  239. defined(fullscreenButton) &&
  240. fullscreenButton.viewModel.isFullscreenEnabled
  241. ) {
  242. fullscreenButton.container.style.visibility = visibility;
  243. }
  244. if (defined(infoBox)) {
  245. infoBox.container.style.visibility = visibility;
  246. }
  247. if (defined(selectionIndicator)) {
  248. selectionIndicator.container.style.visibility = visibility;
  249. }
  250. if (viewer._container) {
  251. const right =
  252. enabled || !defined(fullscreenButton)
  253. ? 0
  254. : fullscreenButton.container.clientWidth;
  255. viewer._vrButton.container.style.right = `${right}px`;
  256. viewer.forceResize();
  257. }
  258. }
  259. /**
  260. * @typedef {Object} Viewer.ConstructorOptions
  261. *
  262. * Initialization options for the Viewer constructor
  263. *
  264. * @property {Boolean} [animation=true] If set to false, the Animation widget will not be created.
  265. * @property {Boolean} [baseLayerPicker=true] If set to false, the BaseLayerPicker widget will not be created.
  266. * @property {Boolean} [fullscreenButton=true] If set to false, the FullscreenButton widget will not be created.
  267. * @property {Boolean} [vrButton=false] If set to true, the VRButton widget will be created.
  268. * @property {Boolean|GeocoderService[]} [geocoder=true] If set to false, the Geocoder widget will not be created.
  269. * @property {Boolean} [homeButton=true] If set to false, the HomeButton widget will not be created.
  270. * @property {Boolean} [infoBox=true] If set to false, the InfoBox widget will not be created.
  271. * @property {Boolean} [sceneModePicker=true] If set to false, the SceneModePicker widget will not be created.
  272. * @property {Boolean} [selectionIndicator=true] If set to false, the SelectionIndicator widget will not be created.
  273. * @property {Boolean} [timeline=true] If set to false, the Timeline widget will not be created.
  274. * @property {Boolean} [navigationHelpButton=true] If set to false, the navigation help button will not be created.
  275. * @property {Boolean} [navigationInstructionsInitiallyVisible=true] True if the navigation instructions should initially be visible, or false if the should not be shown until the user explicitly clicks the button.
  276. * @property {Boolean} [scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
  277. * @property {Boolean} [shouldAnimate=false] <code>true</code> if the clock should attempt to advance simulation time by default, <code>false</code> otherwise. This option takes precedence over setting {@link Viewer#clockViewModel}.
  278. * @property {ClockViewModel} [clockViewModel=new ClockViewModel(clock)] The clock view model to use to control current time.
  279. * @property {ProviderViewModel} [selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available base layer is used. This value is only valid if `baseLayerPicker` is set to true.
  280. * @property {ProviderViewModel[]} [imageryProviderViewModels=createDefaultImageryProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if `baseLayerPicker` is set to true.
  281. * @property {ProviderViewModel} [selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available base layer is used. This value is only valid if `baseLayerPicker` is set to true.
  282. * @property {ProviderViewModel[]} [terrainProviderViewModels=createDefaultTerrainProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if `baseLayerPicker` is set to true.
  283. * @property {ImageryProvider} [imageryProvider=createWorldImagery()] The imagery provider to use. This value is only valid if `baseLayerPicker` is set to false.
  284. * @property {TerrainProvider} [terrainProvider=new EllipsoidTerrainProvider()] The terrain provider to use
  285. * @property {SkyBox|false} [skyBox] The skybox used to render the stars. When <code>undefined</code>, the default stars are used. If set to <code>false</code>, no skyBox, Sun, or Moon will be added.
  286. * @property {SkyAtmosphere|false} [skyAtmosphere] Blue sky, and the glow around the Earth's limb. Set to <code>false</code> to turn it off.
  287. * @property {Element|String} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode when the full screen button is pressed.
  288. * @property {Boolean} [useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
  289. * @property {Number} [targetFrameRate] The target frame rate when using the default render loop.
  290. * @property {Boolean} [showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
  291. * @property {Boolean} [useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
  292. * @property {Boolean} [automaticallyTrackDataSourceClocks=true] If true, this widget will automatically track the clock settings of newly added DataSources, updating if the DataSource's clock changes. Set this to false if you want to configure the clock independently.
  293. * @property {Object} [contextOptions] Context and WebGL creation properties corresponding to <code>options</code> passed to {@link Scene}.
  294. * @property {SceneMode} [sceneMode=SceneMode.SCENE3D] The initial scene mode.
  295. * @property {MapProjection} [mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
  296. * @property {Globe|false} [globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene. If set to <code>false</code>, no globe will be added.
  297. * @property {Boolean} [orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
  298. * @property {Element|String} [creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}. If not specified, the credits are added to the bottom of the widget itself.
  299. * @property {Element|String} [creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}. If not specified, it will appear over the widget itself.
  300. * @property {DataSourceCollection} [dataSources=new DataSourceCollection()] The collection of data sources visualized by the widget. If this parameter is provided,
  301. * the instance is assumed to be owned by the caller and will not be destroyed when the viewer is destroyed.
  302. * @property {Boolean} [shadows=false] Determines if shadows are cast by light sources.
  303. * @property {ShadowMode} [terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
  304. * @property {MapMode2D} [mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  305. * @property {Boolean} [projectionPicker=false] If set to true, the ProjectionPicker widget will be created.
  306. * @property {Boolean} [requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling reduces the CPU/GPU usage of your application and uses less battery on mobile, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
  307. * @property {Number} [maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
  308. * @property {Number} [depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
  309. * @property {Number} [msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
  310. */
  311. /**
  312. * A base widget for building applications. It composites all of the standard Cesium widgets into one reusable package.
  313. * The widget can always be extended by using mixins, which add functionality useful for a variety of applications.
  314. *
  315. * @alias Viewer
  316. * @constructor
  317. *
  318. * @param {Element|String} container The DOM element or ID that will contain the widget.
  319. * @param {Viewer.ConstructorOptions} [options] Object describing initialization options
  320. *
  321. * @exception {DeveloperError} Element with id "container" does not exist in the document.
  322. * @exception {DeveloperError} options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.imageryProvider instead.
  323. * @exception {DeveloperError} options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.terrainProvider instead.
  324. *
  325. * @see Animation
  326. * @see BaseLayerPicker
  327. * @see CesiumWidget
  328. * @see FullscreenButton
  329. * @see HomeButton
  330. * @see SceneModePicker
  331. * @see Timeline
  332. * @see viewerDragDropMixin
  333. *
  334. * @demo {@link https://sandcastle.cesium.com/index.html?src=Hello%20World.html|Cesium Sandcastle Hello World Demo}
  335. *
  336. * @example
  337. * //Initialize the viewer widget with several custom options and mixins.
  338. * const viewer = new Cesium.Viewer('cesiumContainer', {
  339. * //Start in Columbus Viewer
  340. * sceneMode : Cesium.SceneMode.COLUMBUS_VIEW,
  341. * //Use Cesium World Terrain
  342. * terrainProvider : Cesium.createWorldTerrain(),
  343. * //Hide the base layer picker
  344. * baseLayerPicker : false,
  345. * //Use OpenStreetMaps
  346. * imageryProvider : new Cesium.OpenStreetMapImageryProvider({
  347. * url : 'https://a.tile.openstreetmap.org/'
  348. * }),
  349. * skyBox : new Cesium.SkyBox({
  350. * sources : {
  351. * positiveX : 'stars/TychoSkymapII.t3_08192x04096_80_px.jpg',
  352. * negativeX : 'stars/TychoSkymapII.t3_08192x04096_80_mx.jpg',
  353. * positiveY : 'stars/TychoSkymapII.t3_08192x04096_80_py.jpg',
  354. * negativeY : 'stars/TychoSkymapII.t3_08192x04096_80_my.jpg',
  355. * positiveZ : 'stars/TychoSkymapII.t3_08192x04096_80_pz.jpg',
  356. * negativeZ : 'stars/TychoSkymapII.t3_08192x04096_80_mz.jpg'
  357. * }
  358. * }),
  359. * // Show Columbus View map with Web Mercator projection
  360. * mapProjection : new Cesium.WebMercatorProjection()
  361. * });
  362. *
  363. * //Add basic drag and drop functionality
  364. * viewer.extend(Cesium.viewerDragDropMixin);
  365. *
  366. * //Show a pop-up alert if we encounter an error when processing a dropped file
  367. * viewer.dropError.addEventListener(function(dropHandler, name, error) {
  368. * console.log(error);
  369. * window.alert(error);
  370. * });
  371. */
  372. function Viewer(container, options) {
  373. //>>includeStart('debug', pragmas.debug);
  374. if (!defined(container)) {
  375. throw new DeveloperError("container is required.");
  376. }
  377. //>>includeEnd('debug');
  378. container = getElement(container);
  379. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  380. const createBaseLayerPicker =
  381. (!defined(options.globe) || options.globe !== false) &&
  382. (!defined(options.baseLayerPicker) || options.baseLayerPicker !== false);
  383. //>>includeStart('debug', pragmas.debug);
  384. // If not using BaseLayerPicker, selectedImageryProviderViewModel is an invalid option
  385. if (
  386. !createBaseLayerPicker &&
  387. defined(options.selectedImageryProviderViewModel)
  388. ) {
  389. throw new DeveloperError(
  390. "options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget. \
  391. Either specify options.imageryProvider instead or set options.baseLayerPicker to true."
  392. );
  393. }
  394. // If not using BaseLayerPicker, selectedTerrainProviderViewModel is an invalid option
  395. if (
  396. !createBaseLayerPicker &&
  397. defined(options.selectedTerrainProviderViewModel)
  398. ) {
  399. throw new DeveloperError(
  400. "options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget. \
  401. Either specify options.terrainProvider instead or set options.baseLayerPicker to true."
  402. );
  403. }
  404. //>>includeEnd('debug')
  405. const that = this;
  406. const viewerContainer = document.createElement("div");
  407. viewerContainer.className = "cesium-viewer";
  408. container.appendChild(viewerContainer);
  409. // Cesium widget container
  410. const cesiumWidgetContainer = document.createElement("div");
  411. cesiumWidgetContainer.className = "cesium-viewer-cesiumWidgetContainer";
  412. viewerContainer.appendChild(cesiumWidgetContainer);
  413. // Bottom container
  414. const bottomContainer = document.createElement("div");
  415. bottomContainer.className = "cesium-viewer-bottom";
  416. viewerContainer.appendChild(bottomContainer);
  417. const scene3DOnly = defaultValue(options.scene3DOnly, false);
  418. let clock;
  419. let clockViewModel;
  420. let destroyClockViewModel = false;
  421. if (defined(options.clockViewModel)) {
  422. clockViewModel = options.clockViewModel;
  423. clock = clockViewModel.clock;
  424. } else {
  425. clock = new Clock();
  426. clockViewModel = new ClockViewModel(clock);
  427. destroyClockViewModel = true;
  428. }
  429. if (defined(options.shouldAnimate)) {
  430. clock.shouldAnimate = options.shouldAnimate;
  431. }
  432. // Cesium widget
  433. const cesiumWidget = new CesiumWidget(cesiumWidgetContainer, {
  434. imageryProvider:
  435. createBaseLayerPicker || defined(options.imageryProvider)
  436. ? false
  437. : undefined,
  438. clock: clock,
  439. skyBox: options.skyBox,
  440. skyAtmosphere: options.skyAtmosphere,
  441. sceneMode: options.sceneMode,
  442. mapProjection: options.mapProjection,
  443. globe: options.globe,
  444. orderIndependentTranslucency: options.orderIndependentTranslucency,
  445. contextOptions: options.contextOptions,
  446. useDefaultRenderLoop: options.useDefaultRenderLoop,
  447. targetFrameRate: options.targetFrameRate,
  448. showRenderLoopErrors: options.showRenderLoopErrors,
  449. useBrowserRecommendedResolution: options.useBrowserRecommendedResolution,
  450. creditContainer: defined(options.creditContainer)
  451. ? options.creditContainer
  452. : bottomContainer,
  453. creditViewport: options.creditViewport,
  454. scene3DOnly: scene3DOnly,
  455. shadows: options.shadows,
  456. terrainShadows: options.terrainShadows,
  457. mapMode2D: options.mapMode2D,
  458. requestRenderMode: options.requestRenderMode,
  459. maximumRenderTimeChange: options.maximumRenderTimeChange,
  460. depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
  461. msaaSamples: options.msaaSamples,
  462. });
  463. let dataSourceCollection = options.dataSources;
  464. let destroyDataSourceCollection = false;
  465. if (!defined(dataSourceCollection)) {
  466. dataSourceCollection = new DataSourceCollection();
  467. destroyDataSourceCollection = true;
  468. }
  469. const scene = cesiumWidget.scene;
  470. const dataSourceDisplay = new DataSourceDisplay({
  471. scene: scene,
  472. dataSourceCollection: dataSourceCollection,
  473. });
  474. const eventHelper = new EventHelper();
  475. eventHelper.add(clock.onTick, Viewer.prototype._onTick, this);
  476. eventHelper.add(scene.morphStart, Viewer.prototype._clearTrackedObject, this);
  477. // Selection Indicator
  478. let selectionIndicator;
  479. if (
  480. !defined(options.selectionIndicator) ||
  481. options.selectionIndicator !== false
  482. ) {
  483. const selectionIndicatorContainer = document.createElement("div");
  484. selectionIndicatorContainer.className =
  485. "cesium-viewer-selectionIndicatorContainer";
  486. viewerContainer.appendChild(selectionIndicatorContainer);
  487. selectionIndicator = new SelectionIndicator(
  488. selectionIndicatorContainer,
  489. scene
  490. );
  491. }
  492. // Info Box
  493. let infoBox;
  494. if (!defined(options.infoBox) || options.infoBox !== false) {
  495. const infoBoxContainer = document.createElement("div");
  496. infoBoxContainer.className = "cesium-viewer-infoBoxContainer";
  497. viewerContainer.appendChild(infoBoxContainer);
  498. infoBox = new InfoBox(infoBoxContainer);
  499. const infoBoxViewModel = infoBox.viewModel;
  500. eventHelper.add(
  501. infoBoxViewModel.cameraClicked,
  502. Viewer.prototype._onInfoBoxCameraClicked,
  503. this
  504. );
  505. eventHelper.add(
  506. infoBoxViewModel.closeClicked,
  507. Viewer.prototype._onInfoBoxClockClicked,
  508. this
  509. );
  510. }
  511. // Main Toolbar
  512. const toolbar = document.createElement("div");
  513. toolbar.className = "cesium-viewer-toolbar";
  514. viewerContainer.appendChild(toolbar);
  515. // Geocoder
  516. let geocoder;
  517. if (!defined(options.geocoder) || options.geocoder !== false) {
  518. const geocoderContainer = document.createElement("div");
  519. geocoderContainer.className = "cesium-viewer-geocoderContainer";
  520. toolbar.appendChild(geocoderContainer);
  521. let geocoderService;
  522. if (defined(options.geocoder) && typeof options.geocoder !== "boolean") {
  523. geocoderService = Array.isArray(options.geocoder)
  524. ? options.geocoder
  525. : [options.geocoder];
  526. }
  527. geocoder = new Geocoder({
  528. container: geocoderContainer,
  529. geocoderServices: geocoderService,
  530. scene: scene,
  531. });
  532. // Subscribe to search so that we can clear the trackedEntity when it is clicked.
  533. eventHelper.add(
  534. geocoder.viewModel.search.beforeExecute,
  535. Viewer.prototype._clearObjects,
  536. this
  537. );
  538. }
  539. // HomeButton
  540. let homeButton;
  541. if (!defined(options.homeButton) || options.homeButton !== false) {
  542. homeButton = new HomeButton(toolbar, scene);
  543. if (defined(geocoder)) {
  544. eventHelper.add(homeButton.viewModel.command.afterExecute, function () {
  545. const viewModel = geocoder.viewModel;
  546. viewModel.searchText = "";
  547. if (viewModel.isSearchInProgress) {
  548. viewModel.search();
  549. }
  550. });
  551. }
  552. // Subscribe to the home button beforeExecute event so that we can clear the trackedEntity.
  553. eventHelper.add(
  554. homeButton.viewModel.command.beforeExecute,
  555. Viewer.prototype._clearTrackedObject,
  556. this
  557. );
  558. }
  559. // SceneModePicker
  560. // By default, we silently disable the scene mode picker if scene3DOnly is true,
  561. // but if sceneModePicker is explicitly set to true, throw an error.
  562. //>>includeStart('debug', pragmas.debug);
  563. if (options.sceneModePicker === true && scene3DOnly) {
  564. throw new DeveloperError(
  565. "options.sceneModePicker is not available when options.scene3DOnly is set to true."
  566. );
  567. }
  568. //>>includeEnd('debug');
  569. let sceneModePicker;
  570. if (
  571. !scene3DOnly &&
  572. (!defined(options.sceneModePicker) || options.sceneModePicker !== false)
  573. ) {
  574. sceneModePicker = new SceneModePicker(toolbar, scene);
  575. }
  576. let projectionPicker;
  577. if (options.projectionPicker) {
  578. projectionPicker = new ProjectionPicker(toolbar, scene);
  579. }
  580. // BaseLayerPicker
  581. let baseLayerPicker;
  582. let baseLayerPickerDropDown;
  583. if (createBaseLayerPicker) {
  584. const imageryProviderViewModels = defaultValue(
  585. options.imageryProviderViewModels,
  586. createDefaultImageryProviderViewModels()
  587. );
  588. const terrainProviderViewModels = defaultValue(
  589. options.terrainProviderViewModels,
  590. createDefaultTerrainProviderViewModels()
  591. );
  592. baseLayerPicker = new BaseLayerPicker(toolbar, {
  593. globe: scene.globe,
  594. imageryProviderViewModels: imageryProviderViewModels,
  595. selectedImageryProviderViewModel:
  596. options.selectedImageryProviderViewModel,
  597. terrainProviderViewModels: terrainProviderViewModels,
  598. selectedTerrainProviderViewModel:
  599. options.selectedTerrainProviderViewModel,
  600. });
  601. //Grab the dropdown for resize code.
  602. const elements = toolbar.getElementsByClassName(
  603. "cesium-baseLayerPicker-dropDown"
  604. );
  605. baseLayerPickerDropDown = elements[0];
  606. }
  607. // These need to be set after the BaseLayerPicker is created in order to take effect
  608. if (defined(options.imageryProvider) && options.imageryProvider !== false) {
  609. if (createBaseLayerPicker) {
  610. baseLayerPicker.viewModel.selectedImagery = undefined;
  611. }
  612. scene.imageryLayers.removeAll();
  613. scene.imageryLayers.addImageryProvider(options.imageryProvider);
  614. }
  615. if (defined(options.terrainProvider)) {
  616. if (createBaseLayerPicker) {
  617. baseLayerPicker.viewModel.selectedTerrain = undefined;
  618. }
  619. scene.terrainProvider = options.terrainProvider;
  620. }
  621. // Navigation Help Button
  622. let navigationHelpButton;
  623. if (
  624. !defined(options.navigationHelpButton) ||
  625. options.navigationHelpButton !== false
  626. ) {
  627. let showNavHelp = true;
  628. try {
  629. //window.localStorage is null if disabled in Firefox or undefined in browsers with implementation
  630. if (defined(window.localStorage)) {
  631. const hasSeenNavHelp = window.localStorage.getItem(
  632. "cesium-hasSeenNavHelp"
  633. );
  634. if (defined(hasSeenNavHelp) && Boolean(hasSeenNavHelp)) {
  635. showNavHelp = false;
  636. } else {
  637. window.localStorage.setItem("cesium-hasSeenNavHelp", "true");
  638. }
  639. }
  640. } catch (e) {
  641. //Accessing window.localStorage throws if disabled in Chrome
  642. //window.localStorage.setItem throws if in Safari private browsing mode or in any browser if we are over quota.
  643. }
  644. navigationHelpButton = new NavigationHelpButton({
  645. container: toolbar,
  646. instructionsInitiallyVisible: defaultValue(
  647. options.navigationInstructionsInitiallyVisible,
  648. showNavHelp
  649. ),
  650. });
  651. }
  652. // Animation
  653. let animation;
  654. if (!defined(options.animation) || options.animation !== false) {
  655. const animationContainer = document.createElement("div");
  656. animationContainer.className = "cesium-viewer-animationContainer";
  657. viewerContainer.appendChild(animationContainer);
  658. animation = new Animation(
  659. animationContainer,
  660. new AnimationViewModel(clockViewModel)
  661. );
  662. }
  663. // Timeline
  664. let timeline;
  665. if (!defined(options.timeline) || options.timeline !== false) {
  666. const timelineContainer = document.createElement("div");
  667. timelineContainer.className = "cesium-viewer-timelineContainer";
  668. viewerContainer.appendChild(timelineContainer);
  669. timeline = new Timeline(timelineContainer, clock);
  670. timeline.addEventListener("settime", onTimelineScrubfunction, false);
  671. timeline.zoomTo(clock.startTime, clock.stopTime);
  672. }
  673. // Fullscreen
  674. let fullscreenButton;
  675. let fullscreenSubscription;
  676. let fullscreenContainer;
  677. if (
  678. !defined(options.fullscreenButton) ||
  679. options.fullscreenButton !== false
  680. ) {
  681. fullscreenContainer = document.createElement("div");
  682. fullscreenContainer.className = "cesium-viewer-fullscreenContainer";
  683. viewerContainer.appendChild(fullscreenContainer);
  684. fullscreenButton = new FullscreenButton(
  685. fullscreenContainer,
  686. options.fullscreenElement
  687. );
  688. //Subscribe to fullscreenButton.viewModel.isFullscreenEnabled so
  689. //that we can hide/show the button as well as size the timeline.
  690. fullscreenSubscription = subscribeAndEvaluate(
  691. fullscreenButton.viewModel,
  692. "isFullscreenEnabled",
  693. function (isFullscreenEnabled) {
  694. fullscreenContainer.style.display = isFullscreenEnabled
  695. ? "block"
  696. : "none";
  697. if (defined(timeline)) {
  698. timeline.container.style.right = `${fullscreenContainer.clientWidth}px`;
  699. timeline.resize();
  700. }
  701. }
  702. );
  703. }
  704. // VR
  705. let vrButton;
  706. let vrSubscription;
  707. let vrModeSubscription;
  708. if (options.vrButton) {
  709. const vrContainer = document.createElement("div");
  710. vrContainer.className = "cesium-viewer-vrContainer";
  711. viewerContainer.appendChild(vrContainer);
  712. vrButton = new VRButton(vrContainer, scene, options.fullScreenElement);
  713. vrSubscription = subscribeAndEvaluate(
  714. vrButton.viewModel,
  715. "isVREnabled",
  716. function (isVREnabled) {
  717. vrContainer.style.display = isVREnabled ? "block" : "none";
  718. if (defined(fullscreenButton)) {
  719. vrContainer.style.right = `${fullscreenContainer.clientWidth}px`;
  720. }
  721. if (defined(timeline)) {
  722. timeline.container.style.right = `${vrContainer.clientWidth}px`;
  723. timeline.resize();
  724. }
  725. }
  726. );
  727. vrModeSubscription = subscribeAndEvaluate(
  728. vrButton.viewModel,
  729. "isVRMode",
  730. function (isVRMode) {
  731. enableVRUI(that, isVRMode);
  732. }
  733. );
  734. }
  735. //Assign all properties to this instance. No "this" assignments should
  736. //take place above this line.
  737. this._baseLayerPickerDropDown = baseLayerPickerDropDown;
  738. this._fullscreenSubscription = fullscreenSubscription;
  739. this._vrSubscription = vrSubscription;
  740. this._vrModeSubscription = vrModeSubscription;
  741. this._dataSourceChangedListeners = {};
  742. this._automaticallyTrackDataSourceClocks = defaultValue(
  743. options.automaticallyTrackDataSourceClocks,
  744. true
  745. );
  746. this._container = container;
  747. this._bottomContainer = bottomContainer;
  748. this._element = viewerContainer;
  749. this._cesiumWidget = cesiumWidget;
  750. this._selectionIndicator = selectionIndicator;
  751. this._infoBox = infoBox;
  752. this._dataSourceCollection = dataSourceCollection;
  753. this._destroyDataSourceCollection = destroyDataSourceCollection;
  754. this._dataSourceDisplay = dataSourceDisplay;
  755. this._clockViewModel = clockViewModel;
  756. this._destroyClockViewModel = destroyClockViewModel;
  757. this._toolbar = toolbar;
  758. this._homeButton = homeButton;
  759. this._sceneModePicker = sceneModePicker;
  760. this._projectionPicker = projectionPicker;
  761. this._baseLayerPicker = baseLayerPicker;
  762. this._navigationHelpButton = navigationHelpButton;
  763. this._animation = animation;
  764. this._timeline = timeline;
  765. this._fullscreenButton = fullscreenButton;
  766. this._vrButton = vrButton;
  767. this._geocoder = geocoder;
  768. this._eventHelper = eventHelper;
  769. this._lastWidth = 0;
  770. this._lastHeight = 0;
  771. this._allowDataSourcesToSuspendAnimation = true;
  772. this._entityView = undefined;
  773. this._enableInfoOrSelection = defined(infoBox) || defined(selectionIndicator);
  774. this._clockTrackedDataSource = undefined;
  775. this._trackedEntity = undefined;
  776. this._needTrackedEntityUpdate = false;
  777. this._selectedEntity = undefined;
  778. this._zoomIsFlight = false;
  779. this._zoomTarget = undefined;
  780. this._zoomPromise = undefined;
  781. this._zoomOptions = undefined;
  782. this._selectedEntityChanged = new Event();
  783. this._trackedEntityChanged = new Event();
  784. knockout.track(this, [
  785. "_trackedEntity",
  786. "_selectedEntity",
  787. "_clockTrackedDataSource",
  788. ]);
  789. //Listen to data source events in order to track clock changes.
  790. eventHelper.add(
  791. dataSourceCollection.dataSourceAdded,
  792. Viewer.prototype._onDataSourceAdded,
  793. this
  794. );
  795. eventHelper.add(
  796. dataSourceCollection.dataSourceRemoved,
  797. Viewer.prototype._onDataSourceRemoved,
  798. this
  799. );
  800. // Prior to each render, check if anything needs to be resized.
  801. eventHelper.add(scene.postUpdate, Viewer.prototype.resize, this);
  802. eventHelper.add(scene.postRender, Viewer.prototype._postRender, this);
  803. // We need to subscribe to the data sources and collections so that we can clear the
  804. // tracked object when it is removed from the scene.
  805. // Subscribe to current data sources
  806. const dataSourceLength = dataSourceCollection.length;
  807. for (let i = 0; i < dataSourceLength; i++) {
  808. this._dataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
  809. }
  810. this._dataSourceAdded(undefined, dataSourceDisplay.defaultDataSource);
  811. // Hook up events so that we can subscribe to future sources.
  812. eventHelper.add(
  813. dataSourceCollection.dataSourceAdded,
  814. Viewer.prototype._dataSourceAdded,
  815. this
  816. );
  817. eventHelper.add(
  818. dataSourceCollection.dataSourceRemoved,
  819. Viewer.prototype._dataSourceRemoved,
  820. this
  821. );
  822. // Subscribe to left clicks and zoom to the picked object.
  823. function pickAndTrackObject(e) {
  824. const entity = pickEntity(that, e);
  825. if (defined(entity)) {
  826. //Only track the entity if it has a valid position at the current time.
  827. if (
  828. Property.getValueOrUndefined(entity.position, that.clock.currentTime)
  829. ) {
  830. that.trackedEntity = entity;
  831. } else {
  832. that.zoomTo(entity);
  833. }
  834. } else if (defined(that.trackedEntity)) {
  835. that.trackedEntity = undefined;
  836. }
  837. }
  838. function pickAndSelectObject(e) {
  839. that.selectedEntity = pickEntity(that, e);
  840. }
  841. cesiumWidget.screenSpaceEventHandler.setInputAction(
  842. pickAndSelectObject,
  843. ScreenSpaceEventType.LEFT_CLICK
  844. );
  845. cesiumWidget.screenSpaceEventHandler.setInputAction(
  846. pickAndTrackObject,
  847. ScreenSpaceEventType.LEFT_DOUBLE_CLICK
  848. );
  849. }
  850. Object.defineProperties(Viewer.prototype, {
  851. /**
  852. * Gets the parent container.
  853. * @memberof Viewer.prototype
  854. * @type {Element}
  855. * @readonly
  856. */
  857. container: {
  858. get: function () {
  859. return this._container;
  860. },
  861. },
  862. /**
  863. * Gets the DOM element for the area at the bottom of the window containing the
  864. * {@link CreditDisplay} and potentially other things.
  865. * @memberof Viewer.prototype
  866. * @type {Element}
  867. * @readonly
  868. */
  869. bottomContainer: {
  870. get: function () {
  871. return this._bottomContainer;
  872. },
  873. },
  874. /**
  875. * Gets the CesiumWidget.
  876. * @memberof Viewer.prototype
  877. * @type {CesiumWidget}
  878. * @readonly
  879. */
  880. cesiumWidget: {
  881. get: function () {
  882. return this._cesiumWidget;
  883. },
  884. },
  885. /**
  886. * Gets the selection indicator.
  887. * @memberof Viewer.prototype
  888. * @type {SelectionIndicator}
  889. * @readonly
  890. */
  891. selectionIndicator: {
  892. get: function () {
  893. return this._selectionIndicator;
  894. },
  895. },
  896. /**
  897. * Gets the info box.
  898. * @memberof Viewer.prototype
  899. * @type {InfoBox}
  900. * @readonly
  901. */
  902. infoBox: {
  903. get: function () {
  904. return this._infoBox;
  905. },
  906. },
  907. /**
  908. * Gets the Geocoder.
  909. * @memberof Viewer.prototype
  910. * @type {Geocoder}
  911. * @readonly
  912. */
  913. geocoder: {
  914. get: function () {
  915. return this._geocoder;
  916. },
  917. },
  918. /**
  919. * Gets the HomeButton.
  920. * @memberof Viewer.prototype
  921. * @type {HomeButton}
  922. * @readonly
  923. */
  924. homeButton: {
  925. get: function () {
  926. return this._homeButton;
  927. },
  928. },
  929. /**
  930. * Gets the SceneModePicker.
  931. * @memberof Viewer.prototype
  932. * @type {SceneModePicker}
  933. * @readonly
  934. */
  935. sceneModePicker: {
  936. get: function () {
  937. return this._sceneModePicker;
  938. },
  939. },
  940. /**
  941. * Gets the ProjectionPicker.
  942. * @memberof Viewer.prototype
  943. * @type {ProjectionPicker}
  944. * @readonly
  945. */
  946. projectionPicker: {
  947. get: function () {
  948. return this._projectionPicker;
  949. },
  950. },
  951. /**
  952. * Gets the BaseLayerPicker.
  953. * @memberof Viewer.prototype
  954. * @type {BaseLayerPicker}
  955. * @readonly
  956. */
  957. baseLayerPicker: {
  958. get: function () {
  959. return this._baseLayerPicker;
  960. },
  961. },
  962. /**
  963. * Gets the NavigationHelpButton.
  964. * @memberof Viewer.prototype
  965. * @type {NavigationHelpButton}
  966. * @readonly
  967. */
  968. navigationHelpButton: {
  969. get: function () {
  970. return this._navigationHelpButton;
  971. },
  972. },
  973. /**
  974. * Gets the Animation widget.
  975. * @memberof Viewer.prototype
  976. * @type {Animation}
  977. * @readonly
  978. */
  979. animation: {
  980. get: function () {
  981. return this._animation;
  982. },
  983. },
  984. /**
  985. * Gets the Timeline widget.
  986. * @memberof Viewer.prototype
  987. * @type {Timeline}
  988. * @readonly
  989. */
  990. timeline: {
  991. get: function () {
  992. return this._timeline;
  993. },
  994. },
  995. /**
  996. * Gets the FullscreenButton.
  997. * @memberof Viewer.prototype
  998. * @type {FullscreenButton}
  999. * @readonly
  1000. */
  1001. fullscreenButton: {
  1002. get: function () {
  1003. return this._fullscreenButton;
  1004. },
  1005. },
  1006. /**
  1007. * Gets the VRButton.
  1008. * @memberof Viewer.prototype
  1009. * @type {VRButton}
  1010. * @readonly
  1011. */
  1012. vrButton: {
  1013. get: function () {
  1014. return this._vrButton;
  1015. },
  1016. },
  1017. /**
  1018. * Gets the display used for {@link DataSource} visualization.
  1019. * @memberof Viewer.prototype
  1020. * @type {DataSourceDisplay}
  1021. * @readonly
  1022. */
  1023. dataSourceDisplay: {
  1024. get: function () {
  1025. return this._dataSourceDisplay;
  1026. },
  1027. },
  1028. /**
  1029. * Gets the collection of entities not tied to a particular data source.
  1030. * This is a shortcut to [dataSourceDisplay.defaultDataSource.entities]{@link Viewer#dataSourceDisplay}.
  1031. * @memberof Viewer.prototype
  1032. * @type {EntityCollection}
  1033. * @readonly
  1034. */
  1035. entities: {
  1036. get: function () {
  1037. return this._dataSourceDisplay.defaultDataSource.entities;
  1038. },
  1039. },
  1040. /**
  1041. * Gets the set of {@link DataSource} instances to be visualized.
  1042. * @memberof Viewer.prototype
  1043. * @type {DataSourceCollection}
  1044. * @readonly
  1045. */
  1046. dataSources: {
  1047. get: function () {
  1048. return this._dataSourceCollection;
  1049. },
  1050. },
  1051. /**
  1052. * Gets the canvas.
  1053. * @memberof Viewer.prototype
  1054. * @type {HTMLCanvasElement}
  1055. * @readonly
  1056. */
  1057. canvas: {
  1058. get: function () {
  1059. return this._cesiumWidget.canvas;
  1060. },
  1061. },
  1062. /**
  1063. * Gets the scene.
  1064. * @memberof Viewer.prototype
  1065. * @type {Scene}
  1066. * @readonly
  1067. */
  1068. scene: {
  1069. get: function () {
  1070. return this._cesiumWidget.scene;
  1071. },
  1072. },
  1073. /**
  1074. * Determines if shadows are cast by light sources.
  1075. * @memberof Viewer.prototype
  1076. * @type {Boolean}
  1077. */
  1078. shadows: {
  1079. get: function () {
  1080. return this.scene.shadowMap.enabled;
  1081. },
  1082. set: function (value) {
  1083. this.scene.shadowMap.enabled = value;
  1084. },
  1085. },
  1086. /**
  1087. * Determines if the terrain casts or shadows from light sources.
  1088. * @memberof Viewer.prototype
  1089. * @type {ShadowMode}
  1090. */
  1091. terrainShadows: {
  1092. get: function () {
  1093. return this.scene.globe.shadows;
  1094. },
  1095. set: function (value) {
  1096. this.scene.globe.shadows = value;
  1097. },
  1098. },
  1099. /**
  1100. * Get the scene's shadow map
  1101. * @memberof Viewer.prototype
  1102. * @type {ShadowMap}
  1103. * @readonly
  1104. */
  1105. shadowMap: {
  1106. get: function () {
  1107. return this.scene.shadowMap;
  1108. },
  1109. },
  1110. /**
  1111. * Gets the collection of image layers that will be rendered on the globe.
  1112. * @memberof Viewer.prototype
  1113. *
  1114. * @type {ImageryLayerCollection}
  1115. * @readonly
  1116. */
  1117. imageryLayers: {
  1118. get: function () {
  1119. return this.scene.imageryLayers;
  1120. },
  1121. },
  1122. /**
  1123. * The terrain provider providing surface geometry for the globe.
  1124. * @memberof Viewer.prototype
  1125. *
  1126. * @type {TerrainProvider}
  1127. */
  1128. terrainProvider: {
  1129. get: function () {
  1130. return this.scene.terrainProvider;
  1131. },
  1132. set: function (terrainProvider) {
  1133. this.scene.terrainProvider = terrainProvider;
  1134. },
  1135. },
  1136. /**
  1137. * Gets the camera.
  1138. * @memberof Viewer.prototype
  1139. *
  1140. * @type {Camera}
  1141. * @readonly
  1142. */
  1143. camera: {
  1144. get: function () {
  1145. return this.scene.camera;
  1146. },
  1147. },
  1148. /**
  1149. * Gets the post-process stages.
  1150. * @memberof Viewer.prototype
  1151. *
  1152. * @type {PostProcessStageCollection}
  1153. * @readonly
  1154. */
  1155. postProcessStages: {
  1156. get: function () {
  1157. return this.scene.postProcessStages;
  1158. },
  1159. },
  1160. /**
  1161. * Gets the clock.
  1162. * @memberof Viewer.prototype
  1163. * @type {Clock}
  1164. * @readonly
  1165. */
  1166. clock: {
  1167. get: function () {
  1168. return this._clockViewModel.clock;
  1169. },
  1170. },
  1171. /**
  1172. * Gets the clock view model.
  1173. * @memberof Viewer.prototype
  1174. * @type {ClockViewModel}
  1175. * @readonly
  1176. */
  1177. clockViewModel: {
  1178. get: function () {
  1179. return this._clockViewModel;
  1180. },
  1181. },
  1182. /**
  1183. * Gets the screen space event handler.
  1184. * @memberof Viewer.prototype
  1185. * @type {ScreenSpaceEventHandler}
  1186. * @readonly
  1187. */
  1188. screenSpaceEventHandler: {
  1189. get: function () {
  1190. return this._cesiumWidget.screenSpaceEventHandler;
  1191. },
  1192. },
  1193. /**
  1194. * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
  1195. * is true. If undefined, the browser's {@link requestAnimationFrame} implementation
  1196. * determines the frame rate. If defined, this value must be greater than 0. A value higher
  1197. * than the underlying requestAnimationFrame implementation will have no effect.
  1198. * @memberof Viewer.prototype
  1199. *
  1200. * @type {Number}
  1201. */
  1202. targetFrameRate: {
  1203. get: function () {
  1204. return this._cesiumWidget.targetFrameRate;
  1205. },
  1206. set: function (value) {
  1207. this._cesiumWidget.targetFrameRate = value;
  1208. },
  1209. },
  1210. /**
  1211. * Gets or sets whether or not this widget should control the render loop.
  1212. * If set to true the widget will use {@link requestAnimationFrame} to
  1213. * perform rendering and resizing of the widget, as well as drive the
  1214. * simulation clock. If set to false, you must manually call the
  1215. * <code>resize</code>, <code>render</code> methods
  1216. * as part of a custom render loop. If an error occurs during rendering, {@link Scene}'s
  1217. * <code>renderError</code> event will be raised and this property
  1218. * will be set to false. It must be set back to true to continue rendering
  1219. * after the error.
  1220. * @memberof Viewer.prototype
  1221. *
  1222. * @type {Boolean}
  1223. */
  1224. useDefaultRenderLoop: {
  1225. get: function () {
  1226. return this._cesiumWidget.useDefaultRenderLoop;
  1227. },
  1228. set: function (value) {
  1229. this._cesiumWidget.useDefaultRenderLoop = value;
  1230. },
  1231. },
  1232. /**
  1233. * Gets or sets a scaling factor for rendering resolution. Values less than 1.0 can improve
  1234. * performance on less powerful devices while values greater than 1.0 will render at a higher
  1235. * resolution and then scale down, resulting in improved visual fidelity.
  1236. * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
  1237. * will cause the scene to be rendered at 320x240 and then scaled up while setting
  1238. * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
  1239. * @memberof Viewer.prototype
  1240. *
  1241. * @type {Number}
  1242. * @default 1.0
  1243. */
  1244. resolutionScale: {
  1245. get: function () {
  1246. return this._cesiumWidget.resolutionScale;
  1247. },
  1248. set: function (value) {
  1249. this._cesiumWidget.resolutionScale = value;
  1250. },
  1251. },
  1252. /**
  1253. * Boolean flag indicating if the browser's recommended resolution is used.
  1254. * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
  1255. * effectively rendering based on CSS pixels instead of device pixels. This can improve
  1256. * performance on less powerful devices that have high pixel density. When false, rendering
  1257. * will be in device pixels. {@link Viewer#resolutionScale} will still take effect whether
  1258. * this flag is true or false.
  1259. * @memberof Viewer.prototype
  1260. *
  1261. * @type {Boolean}
  1262. * @default true
  1263. */
  1264. useBrowserRecommendedResolution: {
  1265. get: function () {
  1266. return this._cesiumWidget.useBrowserRecommendedResolution;
  1267. },
  1268. set: function (value) {
  1269. this._cesiumWidget.useBrowserRecommendedResolution = value;
  1270. },
  1271. },
  1272. /**
  1273. * Gets or sets whether or not data sources can temporarily pause
  1274. * animation in order to avoid showing an incomplete picture to the user.
  1275. * For example, if asynchronous primitives are being processed in the
  1276. * background, the clock will not advance until the geometry is ready.
  1277. *
  1278. * @memberof Viewer.prototype
  1279. *
  1280. * @type {Boolean}
  1281. */
  1282. allowDataSourcesToSuspendAnimation: {
  1283. get: function () {
  1284. return this._allowDataSourcesToSuspendAnimation;
  1285. },
  1286. set: function (value) {
  1287. this._allowDataSourcesToSuspendAnimation = value;
  1288. },
  1289. },
  1290. /**
  1291. * Gets or sets the Entity instance currently being tracked by the camera.
  1292. * @memberof Viewer.prototype
  1293. * @type {Entity | undefined}
  1294. */
  1295. trackedEntity: {
  1296. get: function () {
  1297. return this._trackedEntity;
  1298. },
  1299. set: function (value) {
  1300. if (this._trackedEntity !== value) {
  1301. this._trackedEntity = value;
  1302. //Cancel any pending zoom
  1303. cancelZoom(this);
  1304. const scene = this.scene;
  1305. const sceneMode = scene.mode;
  1306. //Stop tracking
  1307. if (!defined(value) || !defined(value.position)) {
  1308. this._needTrackedEntityUpdate = false;
  1309. if (
  1310. sceneMode === SceneMode.COLUMBUS_VIEW ||
  1311. sceneMode === SceneMode.SCENE2D
  1312. ) {
  1313. scene.screenSpaceCameraController.enableTranslate = true;
  1314. }
  1315. if (
  1316. sceneMode === SceneMode.COLUMBUS_VIEW ||
  1317. sceneMode === SceneMode.SCENE3D
  1318. ) {
  1319. scene.screenSpaceCameraController.enableTilt = true;
  1320. }
  1321. this._entityView = undefined;
  1322. this.camera.lookAtTransform(Matrix4.IDENTITY);
  1323. } else {
  1324. //We can't start tracking immediately, so we set a flag and start tracking
  1325. //when the bounding sphere is ready (most likely next frame).
  1326. this._needTrackedEntityUpdate = true;
  1327. }
  1328. this._trackedEntityChanged.raiseEvent(value);
  1329. this.scene.requestRender();
  1330. }
  1331. },
  1332. },
  1333. /**
  1334. * Gets or sets the object instance for which to display a selection indicator.
  1335. *
  1336. * If a user interactively picks a Cesium3DTilesFeature instance, then this property
  1337. * will contain a transient Entity instance with a property named "feature" that is
  1338. * the instance that was picked.
  1339. * @memberof Viewer.prototype
  1340. * @type {Entity | undefined}
  1341. */
  1342. selectedEntity: {
  1343. get: function () {
  1344. return this._selectedEntity;
  1345. },
  1346. set: function (value) {
  1347. if (this._selectedEntity !== value) {
  1348. this._selectedEntity = value;
  1349. const selectionIndicatorViewModel = defined(this._selectionIndicator)
  1350. ? this._selectionIndicator.viewModel
  1351. : undefined;
  1352. if (defined(value)) {
  1353. if (defined(selectionIndicatorViewModel)) {
  1354. selectionIndicatorViewModel.animateAppear();
  1355. }
  1356. } else if (defined(selectionIndicatorViewModel)) {
  1357. // Leave the info text in place here, it is needed during the exit animation.
  1358. selectionIndicatorViewModel.animateDepart();
  1359. }
  1360. this._selectedEntityChanged.raiseEvent(value);
  1361. }
  1362. },
  1363. },
  1364. /**
  1365. * Gets the event that is raised when the selected entity changes.
  1366. * @memberof Viewer.prototype
  1367. * @type {Event}
  1368. * @readonly
  1369. */
  1370. selectedEntityChanged: {
  1371. get: function () {
  1372. return this._selectedEntityChanged;
  1373. },
  1374. },
  1375. /**
  1376. * Gets the event that is raised when the tracked entity changes.
  1377. * @memberof Viewer.prototype
  1378. * @type {Event}
  1379. * @readonly
  1380. */
  1381. trackedEntityChanged: {
  1382. get: function () {
  1383. return this._trackedEntityChanged;
  1384. },
  1385. },
  1386. /**
  1387. * Gets or sets the data source to track with the viewer's clock.
  1388. * @memberof Viewer.prototype
  1389. * @type {DataSource}
  1390. */
  1391. clockTrackedDataSource: {
  1392. get: function () {
  1393. return this._clockTrackedDataSource;
  1394. },
  1395. set: function (value) {
  1396. if (this._clockTrackedDataSource !== value) {
  1397. this._clockTrackedDataSource = value;
  1398. trackDataSourceClock(this._timeline, this.clock, value);
  1399. }
  1400. },
  1401. },
  1402. });
  1403. /**
  1404. * Extends the base viewer functionality with the provided mixin.
  1405. * A mixin may add additional properties, functions, or other behavior
  1406. * to the provided viewer instance.
  1407. *
  1408. * @param {Viewer.ViewerMixin} mixin The Viewer mixin to add to this instance.
  1409. * @param {Object} [options] The options object to be passed to the mixin function.
  1410. *
  1411. * @see viewerDragDropMixin
  1412. */
  1413. Viewer.prototype.extend = function (mixin, options) {
  1414. //>>includeStart('debug', pragmas.debug);
  1415. if (!defined(mixin)) {
  1416. throw new DeveloperError("mixin is required.");
  1417. }
  1418. //>>includeEnd('debug')
  1419. mixin(this, options);
  1420. };
  1421. /**
  1422. * Resizes the widget to match the container size.
  1423. * This function is called automatically as needed unless
  1424. * <code>useDefaultRenderLoop</code> is set to false.
  1425. */
  1426. Viewer.prototype.resize = function () {
  1427. const cesiumWidget = this._cesiumWidget;
  1428. const container = this._container;
  1429. const width = container.clientWidth;
  1430. const height = container.clientHeight;
  1431. const animationExists = defined(this._animation);
  1432. const timelineExists = defined(this._timeline);
  1433. cesiumWidget.resize();
  1434. if (width === this._lastWidth && height === this._lastHeight) {
  1435. return;
  1436. }
  1437. const panelMaxHeight = height - 125;
  1438. const baseLayerPickerDropDown = this._baseLayerPickerDropDown;
  1439. if (defined(baseLayerPickerDropDown)) {
  1440. baseLayerPickerDropDown.style.maxHeight = `${panelMaxHeight}px`;
  1441. }
  1442. if (defined(this._geocoder)) {
  1443. const geocoderSuggestions = this._geocoder.searchSuggestionsContainer;
  1444. geocoderSuggestions.style.maxHeight = `${panelMaxHeight}px`;
  1445. }
  1446. if (defined(this._infoBox)) {
  1447. this._infoBox.viewModel.maxHeight = panelMaxHeight;
  1448. }
  1449. const timeline = this._timeline;
  1450. let animationContainer;
  1451. let animationWidth = 0;
  1452. let creditLeft = 0;
  1453. let creditBottom = 0;
  1454. if (
  1455. animationExists &&
  1456. window.getComputedStyle(this._animation.container).visibility !== "hidden"
  1457. ) {
  1458. const lastWidth = this._lastWidth;
  1459. animationContainer = this._animation.container;
  1460. if (width > 900) {
  1461. animationWidth = 169;
  1462. if (lastWidth <= 900) {
  1463. animationContainer.style.width = "169px";
  1464. animationContainer.style.height = "112px";
  1465. this._animation.resize();
  1466. }
  1467. } else if (width >= 600) {
  1468. animationWidth = 136;
  1469. if (lastWidth < 600 || lastWidth > 900) {
  1470. animationContainer.style.width = "136px";
  1471. animationContainer.style.height = "90px";
  1472. this._animation.resize();
  1473. }
  1474. } else {
  1475. animationWidth = 106;
  1476. if (lastWidth > 600 || lastWidth === 0) {
  1477. animationContainer.style.width = "106px";
  1478. animationContainer.style.height = "70px";
  1479. this._animation.resize();
  1480. }
  1481. }
  1482. creditLeft = animationWidth + 5;
  1483. }
  1484. if (
  1485. timelineExists &&
  1486. window.getComputedStyle(this._timeline.container).visibility !== "hidden"
  1487. ) {
  1488. const fullscreenButton = this._fullscreenButton;
  1489. const vrButton = this._vrButton;
  1490. const timelineContainer = timeline.container;
  1491. const timelineStyle = timelineContainer.style;
  1492. creditBottom = timelineContainer.clientHeight + 3;
  1493. timelineStyle.left = `${animationWidth}px`;
  1494. let pixels = 0;
  1495. if (defined(fullscreenButton)) {
  1496. pixels += fullscreenButton.container.clientWidth;
  1497. }
  1498. if (defined(vrButton)) {
  1499. pixels += vrButton.container.clientWidth;
  1500. }
  1501. timelineStyle.right = `${pixels}px`;
  1502. timeline.resize();
  1503. }
  1504. this._bottomContainer.style.left = `${creditLeft}px`;
  1505. this._bottomContainer.style.bottom = `${creditBottom}px`;
  1506. this._lastWidth = width;
  1507. this._lastHeight = height;
  1508. };
  1509. /**
  1510. * This forces the widget to re-think its layout, including
  1511. * widget sizes and credit placement.
  1512. */
  1513. Viewer.prototype.forceResize = function () {
  1514. this._lastWidth = 0;
  1515. this.resize();
  1516. };
  1517. /**
  1518. * Renders the scene. This function is called automatically
  1519. * unless <code>useDefaultRenderLoop</code> is set to false;
  1520. */
  1521. Viewer.prototype.render = function () {
  1522. this._cesiumWidget.render();
  1523. };
  1524. /**
  1525. * @returns {Boolean} true if the object has been destroyed, false otherwise.
  1526. */
  1527. Viewer.prototype.isDestroyed = function () {
  1528. return false;
  1529. };
  1530. /**
  1531. * Destroys the widget. Should be called if permanently
  1532. * removing the widget from layout.
  1533. */
  1534. Viewer.prototype.destroy = function () {
  1535. let i;
  1536. this.screenSpaceEventHandler.removeInputAction(
  1537. ScreenSpaceEventType.LEFT_CLICK
  1538. );
  1539. this.screenSpaceEventHandler.removeInputAction(
  1540. ScreenSpaceEventType.LEFT_DOUBLE_CLICK
  1541. );
  1542. // Unsubscribe from data sources
  1543. const dataSources = this.dataSources;
  1544. const dataSourceLength = dataSources.length;
  1545. for (i = 0; i < dataSourceLength; i++) {
  1546. this._dataSourceRemoved(dataSources, dataSources.get(i));
  1547. }
  1548. this._dataSourceRemoved(undefined, this._dataSourceDisplay.defaultDataSource);
  1549. this._container.removeChild(this._element);
  1550. this._element.removeChild(this._toolbar);
  1551. this._eventHelper.removeAll();
  1552. if (defined(this._geocoder)) {
  1553. this._geocoder = this._geocoder.destroy();
  1554. }
  1555. if (defined(this._homeButton)) {
  1556. this._homeButton = this._homeButton.destroy();
  1557. }
  1558. if (defined(this._sceneModePicker)) {
  1559. this._sceneModePicker = this._sceneModePicker.destroy();
  1560. }
  1561. if (defined(this._projectionPicker)) {
  1562. this._projectionPicker = this._projectionPicker.destroy();
  1563. }
  1564. if (defined(this._baseLayerPicker)) {
  1565. this._baseLayerPicker = this._baseLayerPicker.destroy();
  1566. }
  1567. if (defined(this._animation)) {
  1568. this._element.removeChild(this._animation.container);
  1569. this._animation = this._animation.destroy();
  1570. }
  1571. if (defined(this._timeline)) {
  1572. this._timeline.removeEventListener(
  1573. "settime",
  1574. onTimelineScrubfunction,
  1575. false
  1576. );
  1577. this._element.removeChild(this._timeline.container);
  1578. this._timeline = this._timeline.destroy();
  1579. }
  1580. if (defined(this._fullscreenButton)) {
  1581. this._fullscreenSubscription.dispose();
  1582. this._element.removeChild(this._fullscreenButton.container);
  1583. this._fullscreenButton = this._fullscreenButton.destroy();
  1584. }
  1585. if (defined(this._vrButton)) {
  1586. this._vrSubscription.dispose();
  1587. this._vrModeSubscription.dispose();
  1588. this._element.removeChild(this._vrButton.container);
  1589. this._vrButton = this._vrButton.destroy();
  1590. }
  1591. if (defined(this._infoBox)) {
  1592. this._element.removeChild(this._infoBox.container);
  1593. this._infoBox = this._infoBox.destroy();
  1594. }
  1595. if (defined(this._selectionIndicator)) {
  1596. this._element.removeChild(this._selectionIndicator.container);
  1597. this._selectionIndicator = this._selectionIndicator.destroy();
  1598. }
  1599. if (this._destroyClockViewModel) {
  1600. this._clockViewModel = this._clockViewModel.destroy();
  1601. }
  1602. this._dataSourceDisplay = this._dataSourceDisplay.destroy();
  1603. this._cesiumWidget = this._cesiumWidget.destroy();
  1604. if (this._destroyDataSourceCollection) {
  1605. this._dataSourceCollection = this._dataSourceCollection.destroy();
  1606. }
  1607. return destroyObject(this);
  1608. };
  1609. /**
  1610. * @private
  1611. */
  1612. Viewer.prototype._dataSourceAdded = function (
  1613. dataSourceCollection,
  1614. dataSource
  1615. ) {
  1616. const entityCollection = dataSource.entities;
  1617. entityCollection.collectionChanged.addEventListener(
  1618. Viewer.prototype._onEntityCollectionChanged,
  1619. this
  1620. );
  1621. };
  1622. /**
  1623. * @private
  1624. */
  1625. Viewer.prototype._dataSourceRemoved = function (
  1626. dataSourceCollection,
  1627. dataSource
  1628. ) {
  1629. const entityCollection = dataSource.entities;
  1630. entityCollection.collectionChanged.removeEventListener(
  1631. Viewer.prototype._onEntityCollectionChanged,
  1632. this
  1633. );
  1634. if (defined(this.trackedEntity)) {
  1635. if (
  1636. entityCollection.getById(this.trackedEntity.id) === this.trackedEntity
  1637. ) {
  1638. this.trackedEntity = undefined;
  1639. }
  1640. }
  1641. if (defined(this.selectedEntity)) {
  1642. if (
  1643. entityCollection.getById(this.selectedEntity.id) === this.selectedEntity
  1644. ) {
  1645. this.selectedEntity = undefined;
  1646. }
  1647. }
  1648. };
  1649. /**
  1650. * @private
  1651. */
  1652. Viewer.prototype._onTick = function (clock) {
  1653. const time = clock.currentTime;
  1654. const isUpdated = this._dataSourceDisplay.update(time);
  1655. if (this._allowDataSourcesToSuspendAnimation) {
  1656. this._clockViewModel.canAnimate = isUpdated;
  1657. }
  1658. const entityView = this._entityView;
  1659. if (defined(entityView)) {
  1660. const trackedEntity = this._trackedEntity;
  1661. const trackedState = this._dataSourceDisplay.getBoundingSphere(
  1662. trackedEntity,
  1663. false,
  1664. boundingSphereScratch
  1665. );
  1666. if (trackedState === BoundingSphereState.DONE) {
  1667. entityView.update(time, boundingSphereScratch);
  1668. }
  1669. }
  1670. let position;
  1671. let enableCamera = false;
  1672. const selectedEntity = this.selectedEntity;
  1673. const showSelection = defined(selectedEntity) && this._enableInfoOrSelection;
  1674. if (
  1675. showSelection &&
  1676. selectedEntity.isShowing &&
  1677. selectedEntity.isAvailable(time)
  1678. ) {
  1679. const state = this._dataSourceDisplay.getBoundingSphere(
  1680. selectedEntity,
  1681. true,
  1682. boundingSphereScratch
  1683. );
  1684. if (state !== BoundingSphereState.FAILED) {
  1685. position = boundingSphereScratch.center;
  1686. } else if (defined(selectedEntity.position)) {
  1687. position = selectedEntity.position.getValue(time, position);
  1688. }
  1689. enableCamera = defined(position);
  1690. }
  1691. const selectionIndicatorViewModel = defined(this._selectionIndicator)
  1692. ? this._selectionIndicator.viewModel
  1693. : undefined;
  1694. if (defined(selectionIndicatorViewModel)) {
  1695. selectionIndicatorViewModel.position = Cartesian3.clone(
  1696. position,
  1697. selectionIndicatorViewModel.position
  1698. );
  1699. selectionIndicatorViewModel.showSelection = showSelection && enableCamera;
  1700. selectionIndicatorViewModel.update();
  1701. }
  1702. const infoBoxViewModel = defined(this._infoBox)
  1703. ? this._infoBox.viewModel
  1704. : undefined;
  1705. if (defined(infoBoxViewModel)) {
  1706. infoBoxViewModel.showInfo = showSelection;
  1707. infoBoxViewModel.enableCamera = enableCamera;
  1708. infoBoxViewModel.isCameraTracking =
  1709. this.trackedEntity === this.selectedEntity;
  1710. if (showSelection) {
  1711. infoBoxViewModel.titleText = defaultValue(
  1712. selectedEntity.name,
  1713. selectedEntity.id
  1714. );
  1715. infoBoxViewModel.description = Property.getValueOrDefault(
  1716. selectedEntity.description,
  1717. time,
  1718. ""
  1719. );
  1720. } else {
  1721. infoBoxViewModel.titleText = "";
  1722. infoBoxViewModel.description = "";
  1723. }
  1724. }
  1725. };
  1726. /**
  1727. * @private
  1728. */
  1729. Viewer.prototype._onEntityCollectionChanged = function (
  1730. collection,
  1731. added,
  1732. removed
  1733. ) {
  1734. const length = removed.length;
  1735. for (let i = 0; i < length; i++) {
  1736. const removedObject = removed[i];
  1737. if (this.trackedEntity === removedObject) {
  1738. this.trackedEntity = undefined;
  1739. }
  1740. if (this.selectedEntity === removedObject) {
  1741. this.selectedEntity = undefined;
  1742. }
  1743. }
  1744. };
  1745. /**
  1746. * @private
  1747. */
  1748. Viewer.prototype._onInfoBoxCameraClicked = function (infoBoxViewModel) {
  1749. if (
  1750. infoBoxViewModel.isCameraTracking &&
  1751. this.trackedEntity === this.selectedEntity
  1752. ) {
  1753. this.trackedEntity = undefined;
  1754. } else {
  1755. const selectedEntity = this.selectedEntity;
  1756. const position = selectedEntity.position;
  1757. if (defined(position)) {
  1758. this.trackedEntity = this.selectedEntity;
  1759. } else {
  1760. this.zoomTo(this.selectedEntity);
  1761. }
  1762. }
  1763. };
  1764. /**
  1765. * @private
  1766. */
  1767. Viewer.prototype._clearTrackedObject = function () {
  1768. this.trackedEntity = undefined;
  1769. };
  1770. /**
  1771. * @private
  1772. */
  1773. Viewer.prototype._onInfoBoxClockClicked = function (infoBoxViewModel) {
  1774. this.selectedEntity = undefined;
  1775. };
  1776. /**
  1777. * @private
  1778. */
  1779. Viewer.prototype._clearObjects = function () {
  1780. this.trackedEntity = undefined;
  1781. this.selectedEntity = undefined;
  1782. };
  1783. /**
  1784. * @private
  1785. */
  1786. Viewer.prototype._onDataSourceChanged = function (dataSource) {
  1787. if (this.clockTrackedDataSource === dataSource) {
  1788. trackDataSourceClock(this.timeline, this.clock, dataSource);
  1789. }
  1790. };
  1791. /**
  1792. * @private
  1793. */
  1794. Viewer.prototype._onDataSourceAdded = function (
  1795. dataSourceCollection,
  1796. dataSource
  1797. ) {
  1798. if (this._automaticallyTrackDataSourceClocks) {
  1799. this.clockTrackedDataSource = dataSource;
  1800. }
  1801. const id = dataSource.entities.id;
  1802. const removalFunc = this._eventHelper.add(
  1803. dataSource.changedEvent,
  1804. Viewer.prototype._onDataSourceChanged,
  1805. this
  1806. );
  1807. this._dataSourceChangedListeners[id] = removalFunc;
  1808. };
  1809. /**
  1810. * @private
  1811. */
  1812. Viewer.prototype._onDataSourceRemoved = function (
  1813. dataSourceCollection,
  1814. dataSource
  1815. ) {
  1816. const resetClock = this.clockTrackedDataSource === dataSource;
  1817. const id = dataSource.entities.id;
  1818. this._dataSourceChangedListeners[id]();
  1819. this._dataSourceChangedListeners[id] = undefined;
  1820. if (resetClock) {
  1821. const numDataSources = dataSourceCollection.length;
  1822. if (this._automaticallyTrackDataSourceClocks && numDataSources > 0) {
  1823. this.clockTrackedDataSource = dataSourceCollection.get(
  1824. numDataSources - 1
  1825. );
  1826. } else {
  1827. this.clockTrackedDataSource = undefined;
  1828. }
  1829. }
  1830. };
  1831. /**
  1832. * Asynchronously sets the camera to view the provided entity, entities, or data source.
  1833. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  1834. * this method waits for the data to be ready before performing the zoom.
  1835. *
  1836. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  1837. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  1838. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1839. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  1840. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  1841. *
  1842. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  1843. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  1844. * determined from the offset, the heading will be north.</p>
  1845. *
  1846. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
  1847. * @param {HeadingPitchRange} [offset] The offset from the center of the entity in the local east-north-up reference frame.
  1848. * @returns {Promise.<Boolean>} A Promise that resolves to true if the zoom was successful or false if the target is not currently visualized in the scene or the zoom was cancelled.
  1849. */
  1850. Viewer.prototype.zoomTo = function (target, offset) {
  1851. const options = {
  1852. offset: offset,
  1853. };
  1854. return zoomToOrFly(this, target, options, false);
  1855. };
  1856. /**
  1857. * Flies the camera to the provided entity, entities, or data source.
  1858. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  1859. * this method waits for the data to be ready before performing the flight.
  1860. *
  1861. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  1862. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  1863. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1864. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  1865. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  1866. *
  1867. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  1868. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  1869. * determined from the offset, the heading will be north.</p>
  1870. *
  1871. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
  1872. * @param {Object} [options] Object with the following properties:
  1873. * @param {Number} [options.duration=3.0] The duration of the flight in seconds.
  1874. * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
  1875. * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
  1876. * @returns {Promise.<Boolean>} A Promise that resolves to true if the flight was successful or false if the target is not currently visualized in the scene or the flight was cancelled. //TODO: Cleanup entity mentions
  1877. */
  1878. Viewer.prototype.flyTo = function (target, options) {
  1879. return zoomToOrFly(this, target, options, true);
  1880. };
  1881. function zoomToOrFly(that, zoomTarget, options, isFlight) {
  1882. //>>includeStart('debug', pragmas.debug);
  1883. if (!defined(zoomTarget)) {
  1884. throw new DeveloperError("zoomTarget is required.");
  1885. }
  1886. //>>includeEnd('debug');
  1887. cancelZoom(that);
  1888. //We can't actually perform the zoom until all visualization is ready and
  1889. //bounding spheres have been computed. Therefore we create and return
  1890. //a deferred which will be resolved as part of the post-render step in the
  1891. //frame that actually performs the zoom
  1892. const zoomPromise = defer();
  1893. that._zoomPromise = zoomPromise;
  1894. that._zoomIsFlight = isFlight;
  1895. that._zoomOptions = options;
  1896. Promise.resolve(zoomTarget).then(function (zoomTarget) {
  1897. //Only perform the zoom if it wasn't cancelled before the promise resolved.
  1898. if (that._zoomPromise !== zoomPromise) {
  1899. return;
  1900. }
  1901. //If the zoom target is a rectangular imagery in an ImageLayer
  1902. if (zoomTarget instanceof ImageryLayer) {
  1903. zoomTarget
  1904. .getViewableRectangle()
  1905. .then(function (rectangle) {
  1906. return computeFlyToLocationForRectangle(rectangle, that.scene);
  1907. })
  1908. .then(function (position) {
  1909. //Only perform the zoom if it wasn't cancelled before the promise was resolved
  1910. if (that._zoomPromise === zoomPromise) {
  1911. that._zoomTarget = position;
  1912. }
  1913. });
  1914. return;
  1915. }
  1916. //If the zoom target is a Cesium3DTileset
  1917. if (zoomTarget instanceof Cesium3DTileset) {
  1918. that._zoomTarget = zoomTarget;
  1919. return;
  1920. }
  1921. //If the zoom target is a TimeDynamicPointCloud
  1922. if (zoomTarget instanceof TimeDynamicPointCloud) {
  1923. that._zoomTarget = zoomTarget;
  1924. return;
  1925. }
  1926. //If the zoom target is a data source, and it's in the middle of loading, wait for it to finish loading.
  1927. if (zoomTarget.isLoading && defined(zoomTarget.loadingEvent)) {
  1928. const removeEvent = zoomTarget.loadingEvent.addEventListener(function () {
  1929. removeEvent();
  1930. //Only perform the zoom if it wasn't cancelled before the data source finished.
  1931. if (that._zoomPromise === zoomPromise) {
  1932. that._zoomTarget = zoomTarget.entities.values.slice(0);
  1933. }
  1934. });
  1935. return;
  1936. }
  1937. //Zoom target is already an array, just copy it and return.
  1938. if (Array.isArray(zoomTarget)) {
  1939. that._zoomTarget = zoomTarget.slice(0);
  1940. return;
  1941. }
  1942. //If zoomTarget is an EntityCollection, this will retrieve the array
  1943. zoomTarget = defaultValue(zoomTarget.values, zoomTarget);
  1944. //If zoomTarget is a DataSource, this will retrieve the array.
  1945. if (defined(zoomTarget.entities)) {
  1946. zoomTarget = zoomTarget.entities.values;
  1947. }
  1948. //Zoom target is already an array, just copy it and return.
  1949. if (Array.isArray(zoomTarget)) {
  1950. that._zoomTarget = zoomTarget.slice(0);
  1951. } else {
  1952. //Single entity
  1953. that._zoomTarget = [zoomTarget];
  1954. }
  1955. });
  1956. that.scene.requestRender();
  1957. return zoomPromise.promise;
  1958. }
  1959. function clearZoom(viewer) {
  1960. viewer._zoomPromise = undefined;
  1961. viewer._zoomTarget = undefined;
  1962. viewer._zoomOptions = undefined;
  1963. }
  1964. function cancelZoom(viewer) {
  1965. const zoomPromise = viewer._zoomPromise;
  1966. if (defined(zoomPromise)) {
  1967. clearZoom(viewer);
  1968. zoomPromise.resolve(false);
  1969. }
  1970. }
  1971. /**
  1972. * @private
  1973. */
  1974. Viewer.prototype._postRender = function () {
  1975. updateZoomTarget(this);
  1976. updateTrackedEntity(this);
  1977. };
  1978. function updateZoomTarget(viewer) {
  1979. const target = viewer._zoomTarget;
  1980. if (!defined(target) || viewer.scene.mode === SceneMode.MORPHING) {
  1981. return;
  1982. }
  1983. const scene = viewer.scene;
  1984. const camera = scene.camera;
  1985. const zoomPromise = viewer._zoomPromise;
  1986. const zoomOptions = defaultValue(viewer._zoomOptions, {});
  1987. let options;
  1988. // If zoomTarget was Cesium3DTileset
  1989. if (target instanceof Cesium3DTileset) {
  1990. return target.readyPromise.then(function () {
  1991. const boundingSphere = target.boundingSphere;
  1992. // If offset was originally undefined then give it base value instead of empty object
  1993. if (!defined(zoomOptions.offset)) {
  1994. zoomOptions.offset = new HeadingPitchRange(
  1995. 0.0,
  1996. -0.5,
  1997. boundingSphere.radius
  1998. );
  1999. }
  2000. options = {
  2001. offset: zoomOptions.offset,
  2002. duration: zoomOptions.duration,
  2003. maximumHeight: zoomOptions.maximumHeight,
  2004. complete: function () {
  2005. zoomPromise.resolve(true);
  2006. },
  2007. cancel: function () {
  2008. zoomPromise.resolve(false);
  2009. },
  2010. };
  2011. if (viewer._zoomIsFlight) {
  2012. camera.flyToBoundingSphere(target.boundingSphere, options);
  2013. } else {
  2014. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  2015. camera.lookAtTransform(Matrix4.IDENTITY);
  2016. // Finish the promise
  2017. zoomPromise.resolve(true);
  2018. }
  2019. clearZoom(viewer);
  2020. });
  2021. }
  2022. // If zoomTarget was TimeDynamicPointCloud
  2023. if (target instanceof TimeDynamicPointCloud) {
  2024. return target.readyPromise.then(function () {
  2025. const boundingSphere = target.boundingSphere;
  2026. // If offset was originally undefined then give it base value instead of empty object
  2027. if (!defined(zoomOptions.offset)) {
  2028. zoomOptions.offset = new HeadingPitchRange(
  2029. 0.0,
  2030. -0.5,
  2031. boundingSphere.radius
  2032. );
  2033. }
  2034. options = {
  2035. offset: zoomOptions.offset,
  2036. duration: zoomOptions.duration,
  2037. maximumHeight: zoomOptions.maximumHeight,
  2038. complete: function () {
  2039. zoomPromise.resolve(true);
  2040. },
  2041. cancel: function () {
  2042. zoomPromise.resolve(false);
  2043. },
  2044. };
  2045. if (viewer._zoomIsFlight) {
  2046. camera.flyToBoundingSphere(boundingSphere, options);
  2047. } else {
  2048. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  2049. camera.lookAtTransform(Matrix4.IDENTITY);
  2050. // Finish the promise
  2051. zoomPromise.resolve(true);
  2052. }
  2053. clearZoom(viewer);
  2054. });
  2055. }
  2056. // If zoomTarget was an ImageryLayer
  2057. if (target instanceof Cartographic) {
  2058. options = {
  2059. destination: scene.mapProjection.ellipsoid.cartographicToCartesian(
  2060. target
  2061. ),
  2062. duration: zoomOptions.duration,
  2063. maximumHeight: zoomOptions.maximumHeight,
  2064. complete: function () {
  2065. zoomPromise.resolve(true);
  2066. },
  2067. cancel: function () {
  2068. zoomPromise.resolve(false);
  2069. },
  2070. };
  2071. if (viewer._zoomIsFlight) {
  2072. camera.flyTo(options);
  2073. } else {
  2074. camera.setView(options);
  2075. zoomPromise.resolve(true);
  2076. }
  2077. clearZoom(viewer);
  2078. return;
  2079. }
  2080. const entities = target;
  2081. const boundingSpheres = [];
  2082. for (let i = 0, len = entities.length; i < len; i++) {
  2083. const state = viewer._dataSourceDisplay.getBoundingSphere(
  2084. entities[i],
  2085. false,
  2086. boundingSphereScratch
  2087. );
  2088. if (state === BoundingSphereState.PENDING) {
  2089. return;
  2090. } else if (state !== BoundingSphereState.FAILED) {
  2091. boundingSpheres.push(BoundingSphere.clone(boundingSphereScratch));
  2092. }
  2093. }
  2094. if (boundingSpheres.length === 0) {
  2095. cancelZoom(viewer);
  2096. return;
  2097. }
  2098. //Stop tracking the current entity.
  2099. viewer.trackedEntity = undefined;
  2100. const boundingSphere = BoundingSphere.fromBoundingSpheres(boundingSpheres);
  2101. if (!viewer._zoomIsFlight) {
  2102. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  2103. camera.lookAtTransform(Matrix4.IDENTITY);
  2104. clearZoom(viewer);
  2105. zoomPromise.resolve(true);
  2106. } else {
  2107. clearZoom(viewer);
  2108. camera.flyToBoundingSphere(boundingSphere, {
  2109. duration: zoomOptions.duration,
  2110. maximumHeight: zoomOptions.maximumHeight,
  2111. complete: function () {
  2112. zoomPromise.resolve(true);
  2113. },
  2114. cancel: function () {
  2115. zoomPromise.resolve(false);
  2116. },
  2117. offset: zoomOptions.offset,
  2118. });
  2119. }
  2120. }
  2121. function updateTrackedEntity(viewer) {
  2122. if (!viewer._needTrackedEntityUpdate) {
  2123. return;
  2124. }
  2125. const trackedEntity = viewer._trackedEntity;
  2126. const currentTime = viewer.clock.currentTime;
  2127. //Verify we have a current position at this time. This is only triggered if a position
  2128. //has become undefined after trackedEntity is set but before the boundingSphere has been
  2129. //computed. In this case, we will track the entity once it comes back into existence.
  2130. const currentPosition = Property.getValueOrUndefined(
  2131. trackedEntity.position,
  2132. currentTime
  2133. );
  2134. if (!defined(currentPosition)) {
  2135. return;
  2136. }
  2137. const scene = viewer.scene;
  2138. const state = viewer._dataSourceDisplay.getBoundingSphere(
  2139. trackedEntity,
  2140. false,
  2141. boundingSphereScratch
  2142. );
  2143. if (state === BoundingSphereState.PENDING) {
  2144. return;
  2145. }
  2146. const sceneMode = scene.mode;
  2147. if (
  2148. sceneMode === SceneMode.COLUMBUS_VIEW ||
  2149. sceneMode === SceneMode.SCENE2D
  2150. ) {
  2151. scene.screenSpaceCameraController.enableTranslate = false;
  2152. }
  2153. if (
  2154. sceneMode === SceneMode.COLUMBUS_VIEW ||
  2155. sceneMode === SceneMode.SCENE3D
  2156. ) {
  2157. scene.screenSpaceCameraController.enableTilt = false;
  2158. }
  2159. const bs =
  2160. state !== BoundingSphereState.FAILED ? boundingSphereScratch : undefined;
  2161. viewer._entityView = new EntityView(
  2162. trackedEntity,
  2163. scene,
  2164. scene.mapProjection.ellipsoid
  2165. );
  2166. viewer._entityView.update(currentTime, bs);
  2167. viewer._needTrackedEntityUpdate = false;
  2168. }
  2169. /**
  2170. * A function that augments a Viewer instance with additional functionality.
  2171. * @callback Viewer.ViewerMixin
  2172. * @param {Viewer} viewer The viewer instance.
  2173. * @param {Object} options Options object to be passed to the mixin function.
  2174. *
  2175. * @see Viewer#extend
  2176. */
  2177. export default Viewer;