Viewer.js 74 KB

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