You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Viewer.js 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. /**
  2. * @Author : Caven Chen
  3. */
  4. import { Cesium } from '../../namespace'
  5. const {
  6. BoundingSphere,
  7. BoundingSphereState,
  8. Cartographic,
  9. CesiumWidget,
  10. Cesium3DTileset,
  11. Clock,
  12. computeFlyToLocationForRectangle,
  13. DataSourceCollection,
  14. DataSourceDisplay,
  15. defaultValue,
  16. defined,
  17. destroyObject,
  18. DeveloperError,
  19. Entity,
  20. EntityView,
  21. Event,
  22. EventHelper,
  23. getElement,
  24. HeadingPitchRange,
  25. ImageryLayer,
  26. Matrix4,
  27. Property,
  28. SceneMode,
  29. ScreenSpaceEventType,
  30. TimeDynamicPointCloud,
  31. VoxelPrimitive,
  32. Color,
  33. } = Cesium
  34. const boundingSphereScratch = new BoundingSphere()
  35. function trackDataSourceClock(timeline, clock, dataSource) {
  36. if (defined(dataSource)) {
  37. const dataSourceClock = dataSource.clock
  38. if (defined(dataSourceClock)) {
  39. dataSourceClock.getValue(clock)
  40. }
  41. }
  42. }
  43. /**
  44. * @typedef {object} Viewer.ConstructorOptions
  45. *
  46. * Initialization options for the Viewer constructor
  47. *
  48. * @property {ImageryProvider|false} [imageryProvider=createWorldImagery()] The imagery provider to use. This value is only valid if `baseLayerPicker` is set to false. Deprecated.
  49. * @property {ImageryLayer|false} [baseLayer=ImageryLayer.fromWorldImagery()] The bottommost imagery layer applied to the globe. If set to <code>false</code>, no imagery provider will be added. This value is only valid if `baseLayerPicker` is set to false.
  50. * @property {TerrainProvider} [terrainProvider=new EllipsoidTerrainProvider()] The terrain provider to use
  51. * @property {Terrain} [terrain] A terrain object which handles asynchronous terrain provider. Can only specify if options.terrainProvider is undefined.
  52. * @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.
  53. * @property {SkyAtmosphere|false} [skyAtmosphere] Blue sky, and the glow around the Earth's limb. Set to <code>false</code> to turn it off.
  54. * @property {Element|string} [fullscreenElement=document.body] The element or id to be placed into fullscreen mode when the full screen button is pressed.
  55. * @property {boolean} [useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
  56. * @property {number} [targetFrameRate] The target frame rate when using the default render loop.
  57. * @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.
  58. * @property {boolean} [useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
  59. * @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.
  60. * @property {ContextOptions} [contextOptions] Context and WebGL creation properties passed to {@link Scene}.
  61. * @property {SceneMode} [sceneMode=SceneMode.SCENE3D] The initial scene mode.
  62. * @property {MapProjection} [mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
  63. * @property {Globe|false} [globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene. If set to <code>false</code>, no globe will be added and the sky atmosphere will be hidden by default.
  64. * @property {boolean} [orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
  65. * @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.
  66. * @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.
  67. * @property {DataSourceCollection} [dataSources=new DataSourceCollection()] The collection of data sources visualized by the widget. If this parameter is provided,
  68. * the instance is assumed to be owned by the caller and will not be destroyed when the viewer is destroyed.
  69. * @property {boolean} [shadows=false] Determines if shadows are cast by light sources.
  70. * @property {ShadowMode} [terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
  71. * @property {MapMode2D} [mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  72. * @property {boolean} [projectionPicker=false] If set to true, the ProjectionPicker widget will be created.
  73. * @property {boolean} [blurActiveElementOnCanvasFocus=true] If true, the active element will blur when the viewer's canvas is clicked. Setting this to false is useful for cases when the canvas is clicked only for retrieving position or an entity data without actually meaning to set the canvas to be the active element.
  74. * @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}.
  75. * @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}.
  76. * @property {number} [depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
  77. * @property {number} [msaaSamples=1] If provided, this value controls the rate of multisample antialiasing. Typical multisampling rates are 2, 4, and sometimes 8 samples per pixel. Higher sampling rates of MSAA may impact performance in exchange for improved visual quality. This value only applies to WebGL2 contexts that support multisample render targets.
  78. */
  79. /**
  80. * A base widget for building applications. It composites all of the standard Cesium widgets into one reusable package.
  81. * The widget can always be extended by using mixins, which add functionality useful for a variety of applications.
  82. *
  83. * @alias Viewer
  84. * @constructor
  85. *
  86. * @param {Element|string} container The DOM element or ID that will contain the widget.
  87. * @param {Viewer.ConstructorOptions} [options] Object describing initialization options
  88. *
  89. * @exception {DeveloperError} Element with id "container" does not exist in the document.
  90. * @exception {DeveloperError} options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.baseLayer instead.
  91. * @exception {DeveloperError} options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.terrainProvider instead.
  92. *
  93. * @see Animation
  94. * @see BaseLayerPicker
  95. * @see CesiumWidget
  96. * @see FullscreenButton
  97. * @see HomeButton
  98. * @see SceneModePicker
  99. * @see Timeline
  100. * @see viewerDragDropMixin
  101. *
  102. * @demo {@link https://sandcastle.cesium.com/index.html?src=Hello%20World.html|Cesium Sandcastle Hello World Demo}
  103. *
  104. * @example
  105. * // Initialize the viewer widget with several custom options and mixins.
  106. * try {
  107. * const viewer = new Cesium.Viewer("cesiumContainer", {
  108. * // Start in Columbus Viewer
  109. * sceneMode: Cesium.SceneMode.COLUMBUS_VIEW,
  110. * // Use Cesium World Terrain
  111. * terrain: Cesium.Terrain.fromWorldTerrain(),
  112. * // Hide the base layer picker
  113. * baseLayerPicker: false,
  114. * // Use OpenStreetMaps
  115. * baseLayer: new Cesium.ImageryLayer(new Cesium.OpenStreetMapImageryProvider({
  116. * url: "https://tile.openstreetmap.org/"
  117. * })),
  118. * skyBox: new Cesium.SkyBox({
  119. * sources: {
  120. * positiveX: "stars/TychoSkymapII.t3_08192x04096_80_px.jpg",
  121. * negativeX: "stars/TychoSkymapII.t3_08192x04096_80_mx.jpg",
  122. * positiveY: "stars/TychoSkymapII.t3_08192x04096_80_py.jpg",
  123. * negativeY: "stars/TychoSkymapII.t3_08192x04096_80_my.jpg",
  124. * positiveZ: "stars/TychoSkymapII.t3_08192x04096_80_pz.jpg",
  125. * negativeZ: "stars/TychoSkymapII.t3_08192x04096_80_mz.jpg"
  126. * }
  127. * }),
  128. * // Show Columbus View map with Web Mercator projection
  129. * mapProjection: new Cesium.WebMercatorProjection()
  130. * });
  131. * } catch (error) {
  132. * console.log(error);
  133. * }
  134. *
  135. * // Add basic drag and drop functionality
  136. * viewer.extend(Cesium.viewerDragDropMixin);
  137. *
  138. * // Show a pop-up alert if we encounter an error when processing a dropped file
  139. * viewer.dropError.addEventListener(function(dropHandler, name, error) {
  140. * console.log(error);
  141. * window.alert(error);
  142. * });
  143. */
  144. function Viewer(container, options) {
  145. //>>includeStart('debug', pragmas.debug);
  146. if (!defined(container)) {
  147. throw new DeveloperError('container is required.')
  148. }
  149. //>>includeEnd('debug');
  150. container = getElement(container)
  151. options = defaultValue(options, defaultValue.EMPTY_OBJECT)
  152. const scene3DOnly = defaultValue(options.scene3DOnly, false)
  153. let clock = new Clock()
  154. if (defined(options.shouldAnimate)) {
  155. clock.shouldAnimate = options.shouldAnimate
  156. }
  157. // Cesium widget
  158. const cesiumWidget = new CesiumWidget(container, {
  159. baseLayer: false,
  160. clock: clock,
  161. skyBox: options.skyBox,
  162. skyAtmosphere: options.skyAtmosphere,
  163. sceneMode: options.sceneMode,
  164. mapProjection: options.mapProjection,
  165. globe: options.globe,
  166. orderIndependentTranslucency: options.orderIndependentTranslucency,
  167. contextOptions: options.contextOptions,
  168. useDefaultRenderLoop: options.useDefaultRenderLoop,
  169. targetFrameRate: options.targetFrameRate,
  170. showRenderLoopErrors: options.showRenderLoopErrors,
  171. useBrowserRecommendedResolution: options.useBrowserRecommendedResolution,
  172. creditContainer: document.createElement('div'),
  173. creditViewport: document.createElement('div'),
  174. scene3DOnly: scene3DOnly,
  175. shadows: options.shadows,
  176. terrainShadows: options.terrainShadows,
  177. mapMode2D: options.mapMode2D,
  178. blurActiveElementOnCanvasFocus: options.blurActiveElementOnCanvasFocus,
  179. requestRenderMode: options.requestRenderMode,
  180. maximumRenderTimeChange: options.maximumRenderTimeChange,
  181. depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
  182. msaaSamples: options.msaaSamples,
  183. })
  184. cesiumWidget.scene.backgroundColor = Color.TRANSPARENT
  185. cesiumWidget.canvas.parentNode.className = 'viewer-canvas'
  186. let dataSourceCollection = options.dataSources
  187. let destroyDataSourceCollection = false
  188. if (!defined(dataSourceCollection)) {
  189. dataSourceCollection = new DataSourceCollection()
  190. destroyDataSourceCollection = true
  191. }
  192. const scene = cesiumWidget.scene
  193. scene.screenSpaceCameraController.maximumZoomDistance = 40489014.0
  194. const dataSourceDisplay = new DataSourceDisplay({
  195. scene: scene,
  196. dataSourceCollection: dataSourceCollection,
  197. })
  198. const eventHelper = new EventHelper()
  199. eventHelper.add(clock.onTick, Viewer.prototype._onTick, this)
  200. eventHelper.add(scene.morphStart, Viewer.prototype._clearTrackedObject, this)
  201. // Main Toolbar
  202. const toolbar = document.createElement('div')
  203. //Assign all properties to this instance. No "this" assignments should
  204. //take place above this line.
  205. this._dataSourceChangedListeners = {}
  206. this._automaticallyTrackDataSourceClocks = defaultValue(
  207. options.automaticallyTrackDataSourceClocks,
  208. true
  209. )
  210. this._clock = clock
  211. this._container = container
  212. this._bottomContainer = document.createElement('div')
  213. this._element = document.createElement('div')
  214. this._cesiumWidget = cesiumWidget
  215. this._dataSourceCollection = dataSourceCollection
  216. this._destroyDataSourceCollection = destroyDataSourceCollection
  217. this._dataSourceDisplay = dataSourceDisplay
  218. this._toolbar = toolbar
  219. this._eventHelper = eventHelper
  220. this._lastWidth = 0
  221. this._lastHeight = 0
  222. this._allowDataSourcesToSuspendAnimation = true
  223. this._entityView = undefined
  224. this._enableInfoOrSelection = false
  225. this._clockTrackedDataSource = undefined
  226. this._trackedEntity = undefined
  227. this._needTrackedEntityUpdate = false
  228. this._selectedEntity = undefined
  229. this._zoomIsFlight = false
  230. this._zoomTarget = undefined
  231. this._zoomPromise = undefined
  232. this._zoomOptions = undefined
  233. this._selectedEntityChanged = new Event()
  234. this._trackedEntityChanged = new Event()
  235. //Listen to data source events in order to track clock changes.
  236. eventHelper.add(
  237. dataSourceCollection.dataSourceAdded,
  238. Viewer.prototype._onDataSourceAdded,
  239. this
  240. )
  241. eventHelper.add(
  242. dataSourceCollection.dataSourceRemoved,
  243. Viewer.prototype._onDataSourceRemoved,
  244. this
  245. )
  246. // Prior to each render, check if anything needs to be resized.
  247. eventHelper.add(scene.postUpdate, Viewer.prototype.resize, this)
  248. eventHelper.add(scene.postRender, Viewer.prototype._postRender, this)
  249. // We need to subscribe to the data sources and collections so that we can clear the
  250. // tracked object when it is removed from the scene.
  251. // Subscribe to current data sources
  252. const dataSourceLength = dataSourceCollection.length
  253. for (let i = 0; i < dataSourceLength; i++) {
  254. this._dataSourceAdded(dataSourceCollection, dataSourceCollection.get(i))
  255. }
  256. this._dataSourceAdded(undefined, dataSourceDisplay.defaultDataSource)
  257. // Hook up events so that we can subscribe to future sources.
  258. eventHelper.add(
  259. dataSourceCollection.dataSourceAdded,
  260. Viewer.prototype._dataSourceAdded,
  261. this
  262. )
  263. eventHelper.add(
  264. dataSourceCollection.dataSourceRemoved,
  265. Viewer.prototype._dataSourceRemoved,
  266. this
  267. )
  268. }
  269. /**
  270. *
  271. */
  272. Object.defineProperties(Viewer.prototype, {
  273. /**
  274. * Gets the parent container.
  275. * @memberof Viewer.prototype
  276. * @type {Element}
  277. * @readonly
  278. */
  279. container: {
  280. get: function () {
  281. return this._container
  282. },
  283. },
  284. /**
  285. * Gets the DOM element for the area at the bottom of the window containing the
  286. * {@link CreditDisplay} and potentially other things.
  287. * @memberof Viewer.prototype
  288. * @type {Element}
  289. * @readonly
  290. */
  291. bottomContainer: {
  292. get: function () {
  293. return this._bottomContainer
  294. },
  295. },
  296. /**
  297. * Gets the CesiumWidget.
  298. * @memberof Viewer.prototype
  299. * @type {CesiumWidget}
  300. * @readonly
  301. */
  302. cesiumWidget: {
  303. get: function () {
  304. return this._cesiumWidget
  305. },
  306. },
  307. /**
  308. * Gets the display used for {@link DataSource} visualization.
  309. * @memberof Viewer.prototype
  310. * @type {DataSourceDisplay}
  311. * @readonly
  312. */
  313. dataSourceDisplay: {
  314. get: function () {
  315. return this._dataSourceDisplay
  316. },
  317. },
  318. /**
  319. * Gets the collection of entities not tied to a particular data source.
  320. * This is a shortcut to [dataSourceDisplay.defaultDataSource.entities]{@link Viewer#dataSourceDisplay}.
  321. * @memberof Viewer.prototype
  322. * @type {EntityCollection}
  323. * @readonly
  324. */
  325. entities: {
  326. get: function () {
  327. return this._dataSourceDisplay.defaultDataSource.entities
  328. },
  329. },
  330. /**
  331. * Gets the set of {@link DataSource} instances to be visualized.
  332. * @memberof Viewer.prototype
  333. * @type {DataSourceCollection}
  334. * @readonly
  335. */
  336. dataSources: {
  337. get: function () {
  338. return this._dataSourceCollection
  339. },
  340. },
  341. /**
  342. * Gets the canvas.
  343. * @memberof Viewer.prototype
  344. * @type {HTMLCanvasElement}
  345. * @readonly
  346. */
  347. canvas: {
  348. get: function () {
  349. return this._cesiumWidget.canvas
  350. },
  351. },
  352. /**
  353. * Gets the scene.
  354. * @memberof Viewer.prototype
  355. * @type {Scene}
  356. * @readonly
  357. */
  358. scene: {
  359. get: function () {
  360. return this._cesiumWidget.scene
  361. },
  362. },
  363. /**
  364. * Determines if shadows are cast by light sources.
  365. * @memberof Viewer.prototype
  366. * @type {boolean}
  367. */
  368. shadows: {
  369. get: function () {
  370. return this.scene.shadowMap.enabled
  371. },
  372. set: function (value) {
  373. this.scene.shadowMap.enabled = value
  374. },
  375. },
  376. /**
  377. * Determines if the terrain casts or shadows from light sources.
  378. * @memberof Viewer.prototype
  379. * @type {ShadowMode}
  380. */
  381. terrainShadows: {
  382. get: function () {
  383. return this.scene.globe.shadows
  384. },
  385. set: function (value) {
  386. this.scene.globe.shadows = value
  387. },
  388. },
  389. /**
  390. * Get the scene's shadow map
  391. * @memberof Viewer.prototype
  392. * @type {ShadowMap}
  393. * @readonly
  394. */
  395. shadowMap: {
  396. get: function () {
  397. return this.scene.shadowMap
  398. },
  399. },
  400. /**
  401. * Gets the collection of image layers that will be rendered on the globe.
  402. * @memberof Viewer.prototype
  403. *
  404. * @type {ImageryLayerCollection}
  405. * @readonly
  406. */
  407. imageryLayers: {
  408. get: function () {
  409. return this.scene.imageryLayers
  410. },
  411. },
  412. /**
  413. * The terrain provider providing surface geometry for the globe.
  414. * @memberof Viewer.prototype
  415. *
  416. * @type {TerrainProvider}
  417. */
  418. terrainProvider: {
  419. get: function () {
  420. return this.scene.terrainProvider
  421. },
  422. set: function (terrainProvider) {
  423. this.scene.terrainProvider = terrainProvider
  424. },
  425. },
  426. /**
  427. * Gets the camera.
  428. * @memberof Viewer.prototype
  429. *
  430. * @type {Camera}
  431. * @readonly
  432. */
  433. camera: {
  434. get: function () {
  435. return this.scene.camera
  436. },
  437. },
  438. /**
  439. * Gets the post-process stages.
  440. * @memberof Viewer.prototype
  441. *
  442. * @type {PostProcessStageCollection}
  443. * @readonly
  444. */
  445. postProcessStages: {
  446. get: function () {
  447. return this.scene.postProcessStages
  448. },
  449. },
  450. /**
  451. * Gets the clock.
  452. * @memberof Viewer.prototype
  453. * @type {Clock}
  454. * @readonly
  455. */
  456. clock: {
  457. get: function () {
  458. return this._clock
  459. },
  460. },
  461. /**
  462. * Gets the screen space event handler.
  463. * @memberof Viewer.prototype
  464. * @type {ScreenSpaceEventHandler}
  465. * @readonly
  466. */
  467. screenSpaceEventHandler: {
  468. get: function () {
  469. return this._cesiumWidget.screenSpaceEventHandler
  470. },
  471. },
  472. /**
  473. * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
  474. * is true. If undefined, the browser's requestAnimationFrame implementation
  475. * determines the frame rate. If defined, this value must be greater than 0. A value higher
  476. * than the underlying requestAnimationFrame implementation will have no effect.
  477. * @memberof Viewer.prototype
  478. *
  479. * @type {number}
  480. */
  481. targetFrameRate: {
  482. get: function () {
  483. return this._cesiumWidget.targetFrameRate
  484. },
  485. set: function (value) {
  486. this._cesiumWidget.targetFrameRate = value
  487. },
  488. },
  489. /**
  490. * Gets or sets whether or not this widget should control the render loop.
  491. * If true the widget will use requestAnimationFrame to
  492. * perform rendering and resizing of the widget, as well as drive the
  493. * simulation clock. If set to false, you must manually call the
  494. * <code>resize</code>, <code>render</code> methods
  495. * as part of a custom render loop. If an error occurs during rendering, {@link Scene}'s
  496. * <code>renderError</code> event will be raised and this property
  497. * will be set to false. It must be set back to true to continue rendering
  498. * after the error.
  499. * @memberof Viewer.prototype
  500. *
  501. * @type {boolean}
  502. */
  503. useDefaultRenderLoop: {
  504. get: function () {
  505. return this._cesiumWidget.useDefaultRenderLoop
  506. },
  507. set: function (value) {
  508. this._cesiumWidget.useDefaultRenderLoop = value
  509. },
  510. },
  511. /**
  512. * Gets or sets a scaling factor for rendering resolution. Values less than 1.0 can improve
  513. * performance on less powerful devices while values greater than 1.0 will render at a higher
  514. * resolution and then scale down, resulting in improved visual fidelity.
  515. * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
  516. * will cause the scene to be rendered at 320x240 and then scaled up while setting
  517. * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
  518. * @memberof Viewer.prototype
  519. *
  520. * @type {number}
  521. * @default 1.0
  522. */
  523. resolutionScale: {
  524. get: function () {
  525. return this._cesiumWidget.resolutionScale
  526. },
  527. set: function (value) {
  528. this._cesiumWidget.resolutionScale = value
  529. },
  530. },
  531. /**
  532. * Boolean flag indicating if the browser's recommended resolution is used.
  533. * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
  534. * effectively rendering based on CSS pixels instead of device pixels. This can improve
  535. * performance on less powerful devices that have high pixel density. When false, rendering
  536. * will be in device pixels. {@link Viewer#resolutionScale} will still take effect whether
  537. * this flag is true or false.
  538. * @memberof Viewer.prototype
  539. *
  540. * @type {boolean}
  541. * @default true
  542. */
  543. useBrowserRecommendedResolution: {
  544. get: function () {
  545. return this._cesiumWidget.useBrowserRecommendedResolution
  546. },
  547. set: function (value) {
  548. this._cesiumWidget.useBrowserRecommendedResolution = value
  549. },
  550. },
  551. /**
  552. * Gets or sets whether or not data sources can temporarily pause
  553. * animation in order to avoid showing an incomplete picture to the user.
  554. * For example, if asynchronous primitives are being processed in the
  555. * background, the clock will not advance until the geometry is ready.
  556. *
  557. * @memberof Viewer.prototype
  558. *
  559. * @type {boolean}
  560. */
  561. allowDataSourcesToSuspendAnimation: {
  562. get: function () {
  563. return this._allowDataSourcesToSuspendAnimation
  564. },
  565. set: function (value) {
  566. this._allowDataSourcesToSuspendAnimation = value
  567. },
  568. },
  569. /**
  570. * Gets or sets the Entity instance currently being tracked by the camera.
  571. * @memberof Viewer.prototype
  572. * @type {Entity | undefined}
  573. */
  574. trackedEntity: {
  575. get: function () {
  576. return this._trackedEntity
  577. },
  578. set: function (value) {
  579. if (this._trackedEntity !== value) {
  580. this._trackedEntity = value
  581. //Cancel any pending zoom
  582. cancelZoom(this)
  583. const scene = this.scene
  584. const sceneMode = scene.mode
  585. //Stop tracking
  586. if (!defined(value) || !defined(value.position)) {
  587. this._needTrackedEntityUpdate = false
  588. if (
  589. sceneMode === SceneMode.COLUMBUS_VIEW ||
  590. sceneMode === SceneMode.SCENE2D
  591. ) {
  592. scene.screenSpaceCameraController.enableTranslate = true
  593. }
  594. if (
  595. sceneMode === SceneMode.COLUMBUS_VIEW ||
  596. sceneMode === SceneMode.SCENE3D
  597. ) {
  598. scene.screenSpaceCameraController.enableTilt = true
  599. }
  600. this._entityView = undefined
  601. this.camera.lookAtTransform(Matrix4.IDENTITY)
  602. } else {
  603. //We can't start tracking immediately, so we set a flag and start tracking
  604. //when the bounding sphere is ready (most likely next frame).
  605. this._needTrackedEntityUpdate = true
  606. }
  607. this._trackedEntityChanged.raiseEvent(value)
  608. this.scene.requestRender()
  609. }
  610. },
  611. },
  612. /**
  613. * Gets or sets the object instance for which to display a selection indicator.
  614. *
  615. * If a user interactively picks a Cesium3DTilesFeature instance, then this property
  616. * will contain a transient Entity instance with a property named "feature" that is
  617. * the instance that was picked.
  618. * @memberof Viewer.prototype
  619. * @type {Entity | undefined}
  620. */
  621. selectedEntity: {
  622. get: function () {
  623. return this._selectedEntity
  624. },
  625. set: function (value) {
  626. if (this._selectedEntity !== value) {
  627. this._selectedEntity = value
  628. this._selectedEntityChanged.raiseEvent(value)
  629. }
  630. },
  631. },
  632. /**
  633. * Gets the event that is raised when the selected entity changes.
  634. * @memberof Viewer.prototype
  635. * @type {Event}
  636. * @readonly
  637. */
  638. selectedEntityChanged: {
  639. get: function () {
  640. return this._selectedEntityChanged
  641. },
  642. },
  643. /**
  644. * Gets the event that is raised when the tracked entity changes.
  645. * @memberof Viewer.prototype
  646. * @type {Event}
  647. * @readonly
  648. */
  649. trackedEntityChanged: {
  650. get: function () {
  651. return this._trackedEntityChanged
  652. },
  653. },
  654. /**
  655. * Gets or sets the data source to track with the viewer's clock.
  656. * @memberof Viewer.prototype
  657. * @type {DataSource}
  658. */
  659. clockTrackedDataSource: {
  660. get: function () {
  661. return this._clockTrackedDataSource
  662. },
  663. set: function (value) {
  664. if (this._clockTrackedDataSource !== value) {
  665. this._clockTrackedDataSource = value
  666. trackDataSourceClock(undefined, this.clock, value)
  667. }
  668. },
  669. },
  670. })
  671. /**
  672. * Extends the base viewer functionality with the provided mixin.
  673. * A mixin may add additional properties, functions, or other behavior
  674. * to the provided viewer instance.
  675. *
  676. * @param {Viewer.ViewerMixin} mixin The Viewer mixin to add to this instance.
  677. * @param {object} [options] The options object to be passed to the mixin function.
  678. *
  679. * @see viewerDragDropMixin
  680. */
  681. Viewer.prototype.extend = function (mixin, options) {
  682. //>>includeStart('debug', pragmas.debug);
  683. if (!defined(mixin)) {
  684. throw new DeveloperError('mixin is required.')
  685. }
  686. //>>includeEnd('debug')
  687. mixin(this, options)
  688. }
  689. /**
  690. * Resizes the widget to match the container size.
  691. * This function is called automatically as needed unless
  692. * <code>useDefaultRenderLoop</code> is set to false.
  693. */
  694. Viewer.prototype.resize = function () {
  695. const cesiumWidget = this._cesiumWidget
  696. const container = this._container
  697. const width = container.clientWidth
  698. const height = container.clientHeight
  699. cesiumWidget.resize()
  700. if (width === this._lastWidth && height === this._lastHeight) {
  701. return
  702. }
  703. this._lastWidth = width
  704. this._lastHeight = height
  705. }
  706. /**
  707. * This forces the widget to re-think its layout, including
  708. * widget sizes and credit placement.
  709. */
  710. Viewer.prototype.forceResize = function () {
  711. this._lastWidth = 0
  712. this.resize()
  713. }
  714. /**
  715. * Renders the scene. This function is called automatically
  716. * unless <code>useDefaultRenderLoop</code> is set to false;
  717. */
  718. Viewer.prototype.render = function () {
  719. this._cesiumWidget.render()
  720. }
  721. /**
  722. * @returns {boolean} true if the object has been destroyed, false otherwise.
  723. */
  724. Viewer.prototype.isDestroyed = function () {
  725. return false
  726. }
  727. /**
  728. * Destroys the widget. Should be called if permanently
  729. * removing the widget from layout.
  730. */
  731. Viewer.prototype.destroy = function () {
  732. if (this.isDestroyed()) {
  733. return undefined
  734. }
  735. let i
  736. if (
  737. defined(this.screenSpaceEventHandler) &&
  738. !this.screenSpaceEventHandler.isDestroyed()
  739. ) {
  740. this.screenSpaceEventHandler.removeInputAction(
  741. ScreenSpaceEventType.LEFT_CLICK
  742. )
  743. this.screenSpaceEventHandler.removeInputAction(
  744. ScreenSpaceEventType.LEFT_DOUBLE_CLICK
  745. )
  746. }
  747. // Unsubscribe from data sources
  748. const dataSources = this.dataSources
  749. const dataSourceLength = dataSources.length
  750. for (i = 0; i < dataSourceLength; i++) {
  751. this._dataSourceRemoved(dataSources, dataSources.get(i))
  752. }
  753. this._dataSourceRemoved(undefined, this._dataSourceDisplay.defaultDataSource)
  754. this._eventHelper.removeAll()
  755. this._dataSourceDisplay = this._dataSourceDisplay.destroy()
  756. this._cesiumWidget = this._cesiumWidget.destroy()
  757. if (this._destroyDataSourceCollection) {
  758. this._dataSourceCollection = this._dataSourceCollection.destroy()
  759. }
  760. return destroyObject(this)
  761. }
  762. /**
  763. * @private
  764. */
  765. Viewer.prototype._dataSourceAdded = function (
  766. dataSourceCollection,
  767. dataSource
  768. ) {
  769. const entityCollection = dataSource.entities
  770. entityCollection.collectionChanged.addEventListener(
  771. Viewer.prototype._onEntityCollectionChanged,
  772. this
  773. )
  774. }
  775. /**
  776. * @private
  777. */
  778. Viewer.prototype._dataSourceRemoved = function (
  779. dataSourceCollection,
  780. dataSource
  781. ) {
  782. const entityCollection = dataSource.entities
  783. entityCollection.collectionChanged.removeEventListener(
  784. Viewer.prototype._onEntityCollectionChanged,
  785. this
  786. )
  787. if (defined(this.trackedEntity)) {
  788. if (
  789. entityCollection.getById(this.trackedEntity.id) === this.trackedEntity
  790. ) {
  791. this.trackedEntity = undefined
  792. }
  793. }
  794. if (defined(this.selectedEntity)) {
  795. if (
  796. entityCollection.getById(this.selectedEntity.id) === this.selectedEntity
  797. ) {
  798. this.selectedEntity = undefined
  799. }
  800. }
  801. }
  802. /**
  803. * @private
  804. */
  805. Viewer.prototype._onTick = function (clock) {
  806. const time = clock.currentTime
  807. const isUpdated = this._dataSourceDisplay.update(time)
  808. if (this._allowDataSourcesToSuspendAnimation) {
  809. this._clock.canAnimate = isUpdated
  810. }
  811. const entityView = this._entityView
  812. if (defined(entityView)) {
  813. const trackedEntity = this._trackedEntity
  814. const trackedState = this._dataSourceDisplay.getBoundingSphere(
  815. trackedEntity,
  816. false,
  817. boundingSphereScratch
  818. )
  819. if (trackedState === BoundingSphereState.DONE) {
  820. entityView.update(time, boundingSphereScratch)
  821. }
  822. }
  823. let position
  824. let enableCamera = false
  825. const selectedEntity = this.selectedEntity
  826. const showSelection = defined(selectedEntity) && this._enableInfoOrSelection
  827. if (
  828. showSelection &&
  829. selectedEntity.isShowing &&
  830. selectedEntity.isAvailable(time)
  831. ) {
  832. const state = this._dataSourceDisplay.getBoundingSphere(
  833. selectedEntity,
  834. true,
  835. boundingSphereScratch
  836. )
  837. if (state !== BoundingSphereState.FAILED) {
  838. position = boundingSphereScratch.center
  839. } else if (defined(selectedEntity.position)) {
  840. position = selectedEntity.position.getValue(time, position)
  841. }
  842. enableCamera = defined(position)
  843. }
  844. }
  845. /**
  846. * @private
  847. */
  848. Viewer.prototype._onEntityCollectionChanged = function (
  849. collection,
  850. added,
  851. removed
  852. ) {
  853. const length = removed.length
  854. for (let i = 0; i < length; i++) {
  855. const removedObject = removed[i]
  856. if (this.trackedEntity === removedObject) {
  857. this.trackedEntity = undefined
  858. }
  859. if (this.selectedEntity === removedObject) {
  860. this.selectedEntity = undefined
  861. }
  862. }
  863. }
  864. /**
  865. * @private
  866. */
  867. Viewer.prototype._onInfoBoxCameraClicked = function (infoBoxViewModel) {
  868. if (
  869. infoBoxViewModel.isCameraTracking &&
  870. this.trackedEntity === this.selectedEntity
  871. ) {
  872. this.trackedEntity = undefined
  873. } else {
  874. const selectedEntity = this.selectedEntity
  875. const position = selectedEntity.position
  876. if (defined(position)) {
  877. this.trackedEntity = this.selectedEntity
  878. } else {
  879. this.zoomTo(this.selectedEntity)
  880. }
  881. }
  882. }
  883. /**
  884. * @private
  885. */
  886. Viewer.prototype._clearTrackedObject = function () {
  887. this.trackedEntity = undefined
  888. }
  889. /**
  890. * @private
  891. */
  892. Viewer.prototype._clearObjects = function () {
  893. this.trackedEntity = undefined
  894. this.selectedEntity = undefined
  895. }
  896. /**
  897. * @private
  898. */
  899. Viewer.prototype._onDataSourceChanged = function (dataSource) {
  900. if (this.clockTrackedDataSource === dataSource) {
  901. trackDataSourceClock(undefined, this.clock, dataSource)
  902. }
  903. }
  904. /**
  905. * @private
  906. */
  907. Viewer.prototype._onDataSourceAdded = function (
  908. dataSourceCollection,
  909. dataSource
  910. ) {
  911. if (this._automaticallyTrackDataSourceClocks) {
  912. this.clockTrackedDataSource = dataSource
  913. }
  914. const id = dataSource.entities.id
  915. const removalFunc = this._eventHelper.add(
  916. dataSource.changedEvent,
  917. Viewer.prototype._onDataSourceChanged,
  918. this
  919. )
  920. this._dataSourceChangedListeners[id] = removalFunc
  921. }
  922. /**
  923. * @private
  924. */
  925. Viewer.prototype._onDataSourceRemoved = function (
  926. dataSourceCollection,
  927. dataSource
  928. ) {
  929. const resetClock = this.clockTrackedDataSource === dataSource
  930. const id = dataSource.entities.id
  931. this._dataSourceChangedListeners[id]()
  932. this._dataSourceChangedListeners[id] = undefined
  933. if (resetClock) {
  934. const numDataSources = dataSourceCollection.length
  935. if (this._automaticallyTrackDataSourceClocks && numDataSources > 0) {
  936. this.clockTrackedDataSource = dataSourceCollection.get(numDataSources - 1)
  937. } else {
  938. this.clockTrackedDataSource = undefined
  939. }
  940. }
  941. }
  942. /**
  943. * Asynchronously sets the camera to view the provided entity, entities, or data source.
  944. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  945. * this method waits for the data to be ready before performing the zoom.
  946. *
  947. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  948. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  949. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  950. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  951. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  952. *
  953. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  954. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  955. * determined from the offset, the heading will be north.</p>
  956. *
  957. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|VoxelPrimitive>} 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.
  958. * @param {HeadingPitchRange} [offset] The offset from the center of the entity in the local east-north-up reference frame.
  959. * @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.
  960. */
  961. Viewer.prototype.zoomTo = function (target, offset) {
  962. const options = {
  963. offset: offset,
  964. }
  965. return zoomToOrFly(this, target, options, false)
  966. }
  967. /**
  968. * Flies the camera to the provided entity, entities, or data source.
  969. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  970. * this method waits for the data to be ready before performing the flight.
  971. *
  972. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  973. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  974. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  975. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  976. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  977. *
  978. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  979. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  980. * determined from the offset, the heading will be north.</p>
  981. *
  982. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|VoxelPrimitive>} 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.
  983. * @param {object} [options] Object with the following properties:
  984. * @param {number} [options.duration=3.0] The duration of the flight in seconds.
  985. * @param {number} [options.maximumHeight] The maximum height at the peak of the flight.
  986. * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
  987. * @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
  988. */
  989. Viewer.prototype.flyTo = function (target, options) {
  990. return zoomToOrFly(this, target, options, true)
  991. }
  992. function zoomToOrFly(that, zoomTarget, options, isFlight) {
  993. //>>includeStart('debug', pragmas.debug);
  994. if (!defined(zoomTarget)) {
  995. throw new DeveloperError('zoomTarget is required.')
  996. }
  997. //>>includeEnd('debug');
  998. cancelZoom(that)
  999. //We can't actually perform the zoom until all visualization is ready and
  1000. //bounding spheres have been computed. Therefore we create and return
  1001. //a deferred which will be resolved as part of the post-render step in the
  1002. //frame that actually performs the zoom.
  1003. const zoomPromise = new Promise((resolve) => {
  1004. that._completeZoom = function (value) {
  1005. resolve(value)
  1006. }
  1007. })
  1008. that._zoomPromise = zoomPromise
  1009. that._zoomIsFlight = isFlight
  1010. that._zoomOptions = options
  1011. Promise.resolve(zoomTarget).then(function (zoomTarget) {
  1012. //Only perform the zoom if it wasn't cancelled before the promise resolved.
  1013. if (that._zoomPromise !== zoomPromise) {
  1014. return
  1015. }
  1016. //If the zoom target is a rectangular imagery in an ImageLayer
  1017. if (zoomTarget instanceof ImageryLayer) {
  1018. let rectanglePromise
  1019. if (defined(zoomTarget.imageryProvider)) {
  1020. rectanglePromise = Promise.resolve(zoomTarget.getImageryRectangle())
  1021. } else {
  1022. rectanglePromise = new Promise((resolve) => {
  1023. const removeListener = zoomTarget.readyEvent.addEventListener(() => {
  1024. removeListener()
  1025. resolve(zoomTarget.getImageryRectangle())
  1026. })
  1027. })
  1028. }
  1029. rectanglePromise
  1030. .then(function (rectangle) {
  1031. return computeFlyToLocationForRectangle(rectangle, that.scene)
  1032. })
  1033. .then(function (position) {
  1034. //Only perform the zoom if it wasn't cancelled before the promise was resolved
  1035. if (that._zoomPromise === zoomPromise) {
  1036. that._zoomTarget = position
  1037. }
  1038. })
  1039. return
  1040. }
  1041. if (
  1042. zoomTarget instanceof Cesium3DTileset ||
  1043. zoomTarget instanceof TimeDynamicPointCloud ||
  1044. zoomTarget instanceof VoxelPrimitive
  1045. ) {
  1046. that._zoomTarget = zoomTarget
  1047. return
  1048. }
  1049. //If the zoom target is a data source, and it's in the middle of loading, wait for it to finish loading.
  1050. if (zoomTarget.isLoading && defined(zoomTarget.loadingEvent)) {
  1051. const removeEvent = zoomTarget.loadingEvent.addEventListener(function () {
  1052. removeEvent()
  1053. //Only perform the zoom if it wasn't cancelled before the data source finished.
  1054. if (that._zoomPromise === zoomPromise) {
  1055. that._zoomTarget = zoomTarget.entities.values.slice(0)
  1056. }
  1057. })
  1058. return
  1059. }
  1060. //Zoom target is already an array, just copy it and return.
  1061. if (Array.isArray(zoomTarget)) {
  1062. that._zoomTarget = zoomTarget.slice(0)
  1063. return
  1064. }
  1065. //If zoomTarget is an EntityCollection, this will retrieve the array
  1066. zoomTarget = defaultValue(zoomTarget.values, zoomTarget)
  1067. //If zoomTarget is a DataSource, this will retrieve the array.
  1068. if (defined(zoomTarget.entities)) {
  1069. zoomTarget = zoomTarget.entities.values
  1070. }
  1071. //Zoom target is already an array, just copy it and return.
  1072. if (Array.isArray(zoomTarget)) {
  1073. that._zoomTarget = zoomTarget.slice(0)
  1074. } else {
  1075. //Single entity
  1076. that._zoomTarget = [zoomTarget]
  1077. }
  1078. })
  1079. that.scene.requestRender()
  1080. return zoomPromise
  1081. }
  1082. function clearZoom(viewer) {
  1083. viewer._zoomPromise = undefined
  1084. viewer._zoomTarget = undefined
  1085. viewer._zoomOptions = undefined
  1086. }
  1087. function cancelZoom(viewer) {
  1088. const zoomPromise = viewer._zoomPromise
  1089. if (defined(zoomPromise)) {
  1090. clearZoom(viewer)
  1091. viewer._completeZoom(false)
  1092. }
  1093. }
  1094. /**
  1095. * @private
  1096. */
  1097. Viewer.prototype._postRender = function () {
  1098. updateZoomTarget(this)
  1099. updateTrackedEntity(this)
  1100. }
  1101. function updateZoomTarget(viewer) {
  1102. const target = viewer._zoomTarget
  1103. if (!defined(target) || viewer.scene.mode === SceneMode.MORPHING) {
  1104. return
  1105. }
  1106. const scene = viewer.scene
  1107. const camera = scene.camera
  1108. const zoomOptions = defaultValue(viewer._zoomOptions, {})
  1109. let options
  1110. function zoomToBoundingSphere(boundingSphere) {
  1111. // If offset was originally undefined then give it base value instead of empty object
  1112. if (!defined(zoomOptions.offset)) {
  1113. zoomOptions.offset = new HeadingPitchRange(
  1114. 0.0,
  1115. -0.5,
  1116. boundingSphere.radius
  1117. )
  1118. }
  1119. options = {
  1120. offset: zoomOptions.offset,
  1121. duration: zoomOptions.duration,
  1122. maximumHeight: zoomOptions.maximumHeight,
  1123. complete: function () {
  1124. viewer._completeZoom(true)
  1125. },
  1126. cancel: function () {
  1127. viewer._completeZoom(false)
  1128. },
  1129. }
  1130. if (viewer._zoomIsFlight) {
  1131. camera.flyToBoundingSphere(target.boundingSphere, options)
  1132. } else {
  1133. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset)
  1134. camera.lookAtTransform(Matrix4.IDENTITY)
  1135. // Finish the promise
  1136. viewer._completeZoom(true)
  1137. }
  1138. clearZoom(viewer)
  1139. }
  1140. if (target instanceof TimeDynamicPointCloud) {
  1141. if (defined(target.boundingSphere)) {
  1142. zoomToBoundingSphere(target.boundingSphere)
  1143. return
  1144. }
  1145. // Otherwise, the first "frame" needs to have been rendered
  1146. const removeEventListener = target.frameChanged.addEventListener(function (
  1147. timeDynamicPointCloud
  1148. ) {
  1149. zoomToBoundingSphere(timeDynamicPointCloud.boundingSphere)
  1150. removeEventListener()
  1151. })
  1152. return
  1153. }
  1154. if (target instanceof Cesium3DTileset || target instanceof VoxelPrimitive) {
  1155. zoomToBoundingSphere(target.boundingSphere)
  1156. return
  1157. }
  1158. // If zoomTarget was an ImageryLayer
  1159. if (target instanceof Cartographic) {
  1160. options = {
  1161. destination:
  1162. scene.mapProjection.ellipsoid.cartographicToCartesian(target),
  1163. duration: zoomOptions.duration,
  1164. maximumHeight: zoomOptions.maximumHeight,
  1165. complete: function () {
  1166. viewer._completeZoom(true)
  1167. },
  1168. cancel: function () {
  1169. viewer._completeZoom(false)
  1170. },
  1171. }
  1172. if (viewer._zoomIsFlight) {
  1173. camera.flyTo(options)
  1174. } else {
  1175. camera.setView(options)
  1176. viewer._completeZoom(true)
  1177. }
  1178. clearZoom(viewer)
  1179. return
  1180. }
  1181. const entities = target
  1182. const boundingSpheres = []
  1183. for (let i = 0, len = entities.length; i < len; i++) {
  1184. const state = viewer._dataSourceDisplay.getBoundingSphere(
  1185. entities[i],
  1186. false,
  1187. boundingSphereScratch
  1188. )
  1189. if (state === BoundingSphereState.PENDING) {
  1190. return
  1191. } else if (state !== BoundingSphereState.FAILED) {
  1192. boundingSpheres.push(BoundingSphere.clone(boundingSphereScratch))
  1193. }
  1194. }
  1195. if (boundingSpheres.length === 0) {
  1196. cancelZoom(viewer)
  1197. return
  1198. }
  1199. //Stop tracking the current entity.
  1200. viewer.trackedEntity = undefined
  1201. const boundingSphere = BoundingSphere.fromBoundingSpheres(boundingSpheres)
  1202. if (!viewer._zoomIsFlight) {
  1203. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset)
  1204. camera.lookAtTransform(Matrix4.IDENTITY)
  1205. clearZoom(viewer)
  1206. viewer._completeZoom(true)
  1207. } else {
  1208. clearZoom(viewer)
  1209. camera.flyToBoundingSphere(boundingSphere, {
  1210. duration: zoomOptions.duration,
  1211. maximumHeight: zoomOptions.maximumHeight,
  1212. complete: function () {
  1213. viewer._completeZoom(true)
  1214. },
  1215. cancel: function () {
  1216. viewer._completeZoom(false)
  1217. },
  1218. offset: zoomOptions.offset,
  1219. })
  1220. }
  1221. }
  1222. function updateTrackedEntity(viewer) {
  1223. if (!viewer._needTrackedEntityUpdate) {
  1224. return
  1225. }
  1226. const trackedEntity = viewer._trackedEntity
  1227. const currentTime = viewer.clock.currentTime
  1228. //Verify we have a current position at this time. This is only triggered if a position
  1229. //has become undefined after trackedEntity is set but before the boundingSphere has been
  1230. //computed. In this case, we will track the entity once it comes back into existence.
  1231. const currentPosition = Property.getValueOrUndefined(
  1232. trackedEntity.position,
  1233. currentTime
  1234. )
  1235. if (!defined(currentPosition)) {
  1236. return
  1237. }
  1238. const scene = viewer.scene
  1239. const state = viewer._dataSourceDisplay.getBoundingSphere(
  1240. trackedEntity,
  1241. false,
  1242. boundingSphereScratch
  1243. )
  1244. if (state === BoundingSphereState.PENDING) {
  1245. return
  1246. }
  1247. const sceneMode = scene.mode
  1248. if (
  1249. sceneMode === SceneMode.COLUMBUS_VIEW ||
  1250. sceneMode === SceneMode.SCENE2D
  1251. ) {
  1252. scene.screenSpaceCameraController.enableTranslate = false
  1253. }
  1254. if (
  1255. sceneMode === SceneMode.COLUMBUS_VIEW ||
  1256. sceneMode === SceneMode.SCENE3D
  1257. ) {
  1258. scene.screenSpaceCameraController.enableTilt = false
  1259. }
  1260. const bs =
  1261. state !== BoundingSphereState.FAILED ? boundingSphereScratch : undefined
  1262. viewer._entityView = new EntityView(
  1263. trackedEntity,
  1264. scene,
  1265. scene.mapProjection.ellipsoid
  1266. )
  1267. viewer._entityView.update(currentTime, bs)
  1268. viewer._needTrackedEntityUpdate = false
  1269. }
  1270. /**
  1271. * A function that augments a Viewer instance with additional functionality.
  1272. * @callback Viewer.ViewerMixin
  1273. * @param {Viewer} viewer The viewer instance.
  1274. * @param {object} options Options object to be passed to the mixin function.
  1275. *
  1276. * @see Viewer#extend
  1277. */
  1278. export default Viewer