智慧水务管理系统 - 精河县供水工程综合管理平台

I3SDataProvider.js 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /*
  2. * Esri Contribution: This code implements support for I3S (Indexed 3D Scene Layers), an OGC Community Standard.
  3. * Co-authored-by: Alexandre Jean-Claude ajeanclaude@spiria.com
  4. * Co-authored-by: Anthony Mirabeau anthony.mirabeau@presagis.com
  5. * Co-authored-by: Elizabeth Rudkin elizabeth.rudkin@presagis.com
  6. * Co-authored-by: Tamrat Belayneh tbelayneh@esri.com
  7. *
  8. * The I3S format has been developed by Esri and is shared under an Apache 2.0 license and is maintained @ https://github.com/Esri/i3s-spec.
  9. * This implementation supports loading, displaying, and querying an I3S layer (supported versions include Esri github I3S versions 1.6, 1.7/1.8 -
  10. * whose OGC equivalent are I3S Community Standard Version 1.1 & 1.2) in the CesiumJS viewer.
  11. * It enables the user to access an I3S layer via its URL and load it inside of the CesiumJS viewer.
  12. *
  13. * When a scene layer is initialized it accomplishes the following:
  14. *
  15. * It processes the 3D Scene Layer resource (https://github.com/Esri/i3s-spec/blob/master/docs/1.8/3DSceneLayer.cmn.md) of an I3S dataset
  16. * and loads the layers data. It does so by creating a Cesium 3D Tileset for the given i3s layer and loads the root node.
  17. * When the root node is imported, it creates a Cesium 3D Tile that is parented to the Cesium 3D Tileset
  18. * and loads all children of the root node:
  19. * for each children
  20. * Create a place holder 3D tile so that the LOD display can use the nodes' selection criteria (maximumScreenSpaceError) to select the appropriate node
  21. * based on the current LOD display & evaluation. If the Cesium 3D tile is visible, it invokes requestContent on it.
  22. * At that moment, we intercept the call to requestContent, and we load the geometry in I3S format
  23. * That geometry is transcoded on the fly to glTF format and ingested by CesiumJS
  24. * When the geometry is loaded, we then load all children of this node as placeholders so that the LOD
  25. * can know about them too.
  26. *
  27. * About transcoding:
  28. *
  29. * We use web workers to transcode I3S geometries into glTF
  30. * The steps are:
  31. *
  32. * Decode geometry attributes (positions, normals, etc..) either from DRACO or Binary format.
  33. * If requested, when creating an I3SDataProvider the user has the option to specify a tiled elevation terrain provider
  34. * (geoidTiledTerrainProvider) such as the one shown in the sandcastle example based on ArcGISTiledElevationTerrainProvider, that allows
  35. * conversion of heights for all vertices & bounding boxes of an I3S layer from (typically) gravity related (Orthometric) heights to Ellipsoidal.
  36. * This step is essential when fusing data with varying height sources (as is the case when fusing the I3S dataset (gravity related) in the sandcastle examples with the cesium world terrain (ellipsoidal)).
  37. * We then transform vertex coordinates from LONG/LAT/HEIGHT to Cartesian in local space and
  38. * scale appropriately if specified in the attribute metadata
  39. * Crop UVs if UV regions are defined in the attribute metadata
  40. * Create a glTF document in memory that will be ingested as part of a glb payload
  41. *
  42. * About GEOID data:
  43. *
  44. * We provide the ability to use GEOID data to convert heights from gravity related (orthometric) height systems to ellipsoidal.
  45. * We employ a service architecture to get the conversion factor for a given long lat values, leveraging existing implementation based on ArcGISTiledElevationTerrainProvider
  46. * to avoid requiring bloated look up files. The source Data used in this transcoding service was compiled from https://earth-info.nga.mil/#tab_wgs84-data and is based on
  47. * EGM2008 Gravity Model. The sandcastle examples show how to set the terrain provider service if required.
  48. */
  49. import Cartesian2 from "../Core/Cartesian2.js";
  50. import Cartographic from "../Core/Cartographic.js";
  51. import Check from "../Core/Check.js";
  52. import Frozen from "../Core/Frozen.js";
  53. import defined from "../Core/defined.js";
  54. import destroyObject from "../Core/destroyObject.js";
  55. import HeightmapEncoding from "../Core/HeightmapEncoding.js";
  56. import Resource from "../Core/Resource.js";
  57. import RuntimeError from "../Core/RuntimeError.js";
  58. import WebMercatorProjection from "../Core/WebMercatorProjection.js";
  59. import I3SLayer from "./I3SLayer.js";
  60. import I3SStatistics from "./I3SStatistics.js";
  61. import I3SSublayer from "./I3SSublayer.js";
  62. import Lerc from "lerc";
  63. import Rectangle from "../Core/Rectangle.js";
  64. /**
  65. * @typedef {object} I3SDataProvider.ConstructorOptions
  66. *
  67. * Initialization options for the I3SDataProvider constructor
  68. *
  69. * @property {string} [name] The name of the I3S dataset.
  70. * @property {boolean} [show=true] Determines if the dataset will be shown.
  71. * @property {ArcGISTiledElevationTerrainProvider|Promise<ArcGISTiledElevationTerrainProvider>} [geoidTiledTerrainProvider] Tiled elevation provider describing an Earth Gravitational Model. If defined, geometry will be shifted based on the offsets given by this provider. Required to position I3S data sets with gravity-related height at the correct location.
  72. * @property {Cesium3DTileset.ConstructorOptions} [cesium3dTilesetOptions] Object containing options to pass to an internally created {@link Cesium3DTileset}. See {@link Cesium3DTileset} for list of valid properties. All options can be used with the exception of <code>url</code> and <code>show</code> which are overridden by values from I3SDataProvider.
  73. * @property {boolean} [showFeatures=false] Determines if the features will be shown.
  74. * @property {boolean} [adjustMaterialAlphaMode=false] The option to adjust the alpha mode of the material based on the transparency of the vertex color. When <code>true</code>, the alpha mode of the material (if not defined) will be set to BLEND for geometry with any transparency in the color vertex attribute.
  75. * @property {boolean} [applySymbology=false] Determines if the I3S symbology will be parsed and applied for the layers.
  76. * @property {boolean} [calculateNormals=false] Determines if the flat normals will be generated for I3S geometry without normals.
  77. *
  78. * @example
  79. * // Increase LOD by reducing SSE
  80. * const cesium3dTilesetOptions = {
  81. * maximumScreenSpaceError: 1,
  82. * };
  83. * const i3sOptions = {
  84. * cesium3dTilesetOptions: cesium3dTilesetOptions,
  85. * };
  86. *
  87. * @example
  88. * // Set a custom outline color to replace the color defined in I3S symbology
  89. * const cesium3dTilesetOptions = {
  90. * outlineColor: Cesium.Color.BLUE,
  91. * };
  92. * const i3sOptions = {
  93. * cesium3dTilesetOptions: cesium3dTilesetOptions,
  94. * applySymbology: true,
  95. * };
  96. */
  97. /**
  98. * An I3SDataProvider is the main public class for I3S support. The url option
  99. * should return a scene object. Currently supported I3S versions are 1.6 and
  100. * 1.7/1.8 (OGC I3S 1.2). I3SFeature and I3SNode classes implement the
  101. * Object Model for I3S entities, with public interfaces.
  102. *
  103. * <div class="notice">
  104. * This object is normally not instantiated directly, use {@link I3SDataProvider.fromUrl}.
  105. * </div>
  106. *
  107. * @alias I3SDataProvider
  108. * @constructor
  109. *
  110. * @param {I3SDataProvider.ConstructorOptions} options An object describing initialization options
  111. *
  112. * @see I3SDataProvider.fromUrl
  113. * @see ArcGISTiledElevationTerrainProvider
  114. *
  115. * @example
  116. * try {
  117. * const i3sData = await I3SDataProvider.fromUrl(
  118. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/Frankfurt2017_vi3s_18/SceneServer/layers/0"
  119. * );
  120. * viewer.scene.primitives.add(i3sData);
  121. * } catch (error) {
  122. * console.log(`There was an error creating the I3S Data Provider: ${error}`);
  123. * }
  124. *
  125. * @example
  126. * try {
  127. * const geoidService = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
  128. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/EGM2008/ImageServer"
  129. * );
  130. * const i3sData = await I3SDataProvider.fromUrl(
  131. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/Frankfurt2017_vi3s_18/SceneServer/layers/0", {
  132. * geoidTiledTerrainProvider: geoidService
  133. * });
  134. * viewer.scene.primitives.add(i3sData);
  135. * } catch (error) {
  136. * console.log(`There was an error creating the I3S Data Provider: ${error}`);
  137. * }
  138. */
  139. function I3SDataProvider(options) {
  140. options = options ?? Frozen.EMPTY_OBJECT;
  141. // All public configuration is defined as ES5 properties
  142. // These are just the "private" variables and their defaults.
  143. this._name = options.name;
  144. this._show = options.show ?? true;
  145. this._geoidTiledTerrainProvider = options.geoidTiledTerrainProvider;
  146. this._showFeatures = options.showFeatures ?? false;
  147. this._adjustMaterialAlphaMode = options.adjustMaterialAlphaMode ?? false;
  148. this._applySymbology = options.applySymbology ?? false;
  149. this._calculateNormals = options.calculateNormals ?? false;
  150. this._cesium3dTilesetOptions =
  151. options.cesium3dTilesetOptions ?? Frozen.EMPTY_OBJECT;
  152. this._layers = [];
  153. this._sublayers = [];
  154. this._data = undefined;
  155. this._extent = undefined;
  156. this._geoidDataPromise = undefined;
  157. this._geoidDataList = undefined;
  158. this._decoderTaskProcessor = undefined;
  159. this._taskProcessorReadyPromise = undefined;
  160. this._attributeStatistics = [];
  161. this._layersExtent = [];
  162. }
  163. Object.defineProperties(I3SDataProvider.prototype, {
  164. /**
  165. * Gets a human-readable name for this dataset.
  166. * @memberof I3SDataProvider.prototype
  167. * @type {string}
  168. * @readonly
  169. */
  170. name: {
  171. get: function () {
  172. return this._name;
  173. },
  174. },
  175. /**
  176. * Determines if the dataset will be shown.
  177. * @memberof I3SDataProvider.prototype
  178. * @type {boolean}
  179. */
  180. show: {
  181. get: function () {
  182. return this._show;
  183. },
  184. set: function (value) {
  185. //>>includeStart('debug', pragmas.debug);
  186. Check.defined("value", value);
  187. //>>includeEnd('debug');
  188. if (this._show !== value) {
  189. this._show = value;
  190. for (let i = 0; i < this._layers.length; i++) {
  191. this._layers[i]._updateVisibility();
  192. }
  193. }
  194. },
  195. },
  196. /**
  197. * The terrain provider referencing the GEOID service to be used for orthometric to ellipsoidal conversion.
  198. * @memberof I3SDataProvider.prototype
  199. * @type {ArcGISTiledElevationTerrainProvider}
  200. * @readonly
  201. */
  202. geoidTiledTerrainProvider: {
  203. get: function () {
  204. return this._geoidTiledTerrainProvider;
  205. },
  206. },
  207. /**
  208. * Gets the collection of layers.
  209. * @memberof I3SDataProvider.prototype
  210. * @type {I3SLayer[]}
  211. * @readonly
  212. */
  213. layers: {
  214. get: function () {
  215. return this._layers;
  216. },
  217. },
  218. /**
  219. * Gets the collection of building sublayers.
  220. * @memberof I3SDataProvider.prototype
  221. * @type {I3SSublayer[]}
  222. * @readonly
  223. */
  224. sublayers: {
  225. get: function () {
  226. return this._sublayers;
  227. },
  228. },
  229. /**
  230. * Gets the I3S data for this object.
  231. * @memberof I3SDataProvider.prototype
  232. * @type {object}
  233. * @readonly
  234. */
  235. data: {
  236. get: function () {
  237. return this._data;
  238. },
  239. },
  240. /**
  241. * Gets the extent covered by this I3S.
  242. * @memberof I3SDataProvider.prototype
  243. * @type {Rectangle}
  244. * @readonly
  245. */
  246. extent: {
  247. get: function () {
  248. return this._extent;
  249. },
  250. },
  251. /**
  252. * The resource used to fetch the I3S dataset.
  253. * @memberof I3SDataProvider.prototype
  254. * @type {Resource}
  255. * @readonly
  256. */
  257. resource: {
  258. get: function () {
  259. return this._resource;
  260. },
  261. },
  262. /**
  263. * Determines if the features will be shown.
  264. * @memberof I3SDataProvider.prototype
  265. * @type {boolean}
  266. * @readonly
  267. */
  268. showFeatures: {
  269. get: function () {
  270. return this._showFeatures;
  271. },
  272. },
  273. /**
  274. * Determines if the alpha mode of the material will be adjusted depending on the color vertex attribute.
  275. * @memberof I3SDataProvider.prototype
  276. * @type {boolean}
  277. * @readonly
  278. */
  279. adjustMaterialAlphaMode: {
  280. get: function () {
  281. return this._adjustMaterialAlphaMode;
  282. },
  283. },
  284. /**
  285. * Determines if the I3S symbology will be parsed and applied for the layers.
  286. * @memberof I3SDataProvider.prototype
  287. * @type {boolean}
  288. * @readonly
  289. */
  290. applySymbology: {
  291. get: function () {
  292. return this._applySymbology;
  293. },
  294. },
  295. /**
  296. * Determines if the flat normals will be generated for I3S geometry without normals.
  297. * @memberof I3SDataProvider.prototype
  298. * @type {boolean}
  299. * @readonly
  300. */
  301. calculateNormals: {
  302. get: function () {
  303. return this._calculateNormals;
  304. },
  305. },
  306. });
  307. /**
  308. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  309. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  310. * <p>
  311. * Once an object is destroyed, it should not be used; calling any function other than
  312. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  313. * assign the return value (<code>undefined</code>) to the object as done in the example.
  314. * </p>
  315. *
  316. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  317. *
  318. * @see I3SDataProvider#isDestroyed
  319. */
  320. I3SDataProvider.prototype.destroy = function () {
  321. for (let i = 0; i < this._layers.length; i++) {
  322. if (defined(this._layers[i]._tileset)) {
  323. this._layers[i]._tileset.destroy();
  324. }
  325. }
  326. return destroyObject(this);
  327. };
  328. /**
  329. * Returns true if this object was destroyed; otherwise, false.
  330. * <p>
  331. * If this object was destroyed, it should not be used; calling any function other than
  332. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  333. * </p>
  334. *
  335. * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  336. *
  337. * @see I3SDataProvider#destroy
  338. */
  339. I3SDataProvider.prototype.isDestroyed = function () {
  340. return false;
  341. };
  342. /**
  343. * @private
  344. */
  345. I3SDataProvider.prototype.update = function (frameState) {
  346. for (let i = 0; i < this._layers.length; i++) {
  347. if (defined(this._layers[i]._tileset)) {
  348. this._layers[i]._tileset.update(frameState);
  349. }
  350. }
  351. };
  352. /**
  353. * @private
  354. */
  355. I3SDataProvider.prototype.prePassesUpdate = function (frameState) {
  356. for (let i = 0; i < this._layers.length; i++) {
  357. if (defined(this._layers[i]._tileset)) {
  358. this._layers[i]._tileset.prePassesUpdate(frameState);
  359. }
  360. }
  361. };
  362. /**
  363. * @private
  364. */
  365. I3SDataProvider.prototype.postPassesUpdate = function (frameState) {
  366. for (let i = 0; i < this._layers.length; i++) {
  367. if (defined(this._layers[i]._tileset)) {
  368. this._layers[i]._tileset.postPassesUpdate(frameState);
  369. }
  370. }
  371. };
  372. /**
  373. * @private
  374. */
  375. I3SDataProvider.prototype.updateForPass = function (frameState, passState) {
  376. for (let i = 0; i < this._layers.length; i++) {
  377. if (defined(this._layers[i]._tileset)) {
  378. this._layers[i]._tileset.updateForPass(frameState, passState);
  379. }
  380. }
  381. };
  382. function buildLayerUrl(provider, layerId) {
  383. const dataProviderUrl = provider.resource.getUrlComponent();
  384. let layerUrl = "";
  385. if (dataProviderUrl.match(/layers\/\d/)) {
  386. layerUrl = `${dataProviderUrl}`.replace(/\/+$/, "");
  387. } else {
  388. // Add '/' to url if needed + `$layers/${layerId}/` if tilesetUrl not already in ../layers/[id] format
  389. layerUrl = `${dataProviderUrl}`
  390. .replace(/\/?$/, "/")
  391. .concat(`layers/${layerId}`);
  392. }
  393. return layerUrl;
  394. }
  395. async function addLayers(provider, data, options) {
  396. if (data.layerType === "Building") {
  397. if (!defined(options.showFeatures)) {
  398. // The Building Scene Layer requires features to be shown to support filtering
  399. provider._showFeatures = true;
  400. }
  401. if (!defined(options.adjustMaterialAlphaMode)) {
  402. // The Building Scene Layer enables transparency by default
  403. provider._adjustMaterialAlphaMode = true;
  404. }
  405. if (!defined(options.applySymbology)) {
  406. // The Building Scene Layer applies symbology by default
  407. provider._applySymbology = true;
  408. }
  409. if (!defined(options.calculateNormals)) {
  410. // The Building Scene Layer calculates flat normals by default
  411. provider._calculateNormals = true;
  412. }
  413. const buildingLayerUrl = buildLayerUrl(provider, data.id);
  414. if (defined(data.sublayers)) {
  415. const promises = [];
  416. for (let i = 0; i < data.sublayers.length; i++) {
  417. const promise = I3SSublayer._fromData(
  418. provider,
  419. buildingLayerUrl,
  420. data.sublayers[i],
  421. provider,
  422. );
  423. promises.push(promise);
  424. }
  425. const sublayers = await Promise.all(promises);
  426. for (let i = 0; i < sublayers.length; i++) {
  427. const sublayer = sublayers[i];
  428. provider._sublayers.push(sublayer);
  429. provider._layers.push(...sublayer._i3sLayers);
  430. }
  431. }
  432. if (defined(data.statisticsHRef)) {
  433. const uri = buildingLayerUrl.concat(`/${data.statisticsHRef}`);
  434. const statistics = new I3SStatistics(provider, uri);
  435. await statistics.load();
  436. provider._attributeStatistics.push(statistics);
  437. }
  438. if (defined(data.fullExtent)) {
  439. const extent = Rectangle.fromDegrees(
  440. data.fullExtent.xmin,
  441. data.fullExtent.ymin,
  442. data.fullExtent.xmax,
  443. data.fullExtent.ymax,
  444. );
  445. provider._layersExtent.push(extent);
  446. }
  447. } else if (
  448. data.layerType === "3DObject" ||
  449. data.layerType === "IntegratedMesh"
  450. ) {
  451. if (
  452. !defined(options.calculateNormals) &&
  453. !defined(data.textureSetDefinitions)
  454. ) {
  455. // I3S Layers without textures should calculate flat normals by default
  456. provider._calculateNormals = true;
  457. }
  458. const newLayer = new I3SLayer(provider, data, provider);
  459. provider._layers.push(newLayer);
  460. if (defined(newLayer._extent)) {
  461. provider._layersExtent.push(newLayer._extent);
  462. }
  463. } else {
  464. // Filter other scene layer types out
  465. console.log(
  466. `${data.layerType} layer ${data.name} is skipped as not supported.`,
  467. );
  468. }
  469. }
  470. /**
  471. * Creates an I3SDataProvider. Currently supported I3S versions are 1.6 and
  472. * 1.7/1.8 (OGC I3S 1.2).
  473. *
  474. * @param {string|Resource} url The url of the I3S dataset, which should return an I3S scene object
  475. * @param {I3SDataProvider.ConstructorOptions} options An object describing initialization options
  476. * @returns {Promise<I3SDataProvider>}
  477. *
  478. * @example
  479. * try {
  480. * const i3sData = await I3SDataProvider.fromUrl(
  481. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/Frankfurt2017_vi3s_18/SceneServer/layers/0"
  482. * );
  483. * viewer.scene.primitives.add(i3sData);
  484. * } catch (error) {
  485. * console.log(`There was an error creating the I3S Data Provider: ${error}`);
  486. * }
  487. *
  488. * @example
  489. * try {
  490. * const geoidService = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
  491. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/EGM2008/ImageServer"
  492. * );
  493. * const i3sData = await I3SDataProvider.fromUrl(
  494. * "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/Frankfurt2017_vi3s_18/SceneServer/layers/0", {
  495. * geoidTiledTerrainProvider: geoidService
  496. * });
  497. * viewer.scene.primitives.add(i3sData);
  498. * } catch (error) {
  499. * console.log(`There was an error creating the I3S Data Provider: ${error}`);
  500. * }
  501. */
  502. I3SDataProvider.fromUrl = async function (url, options) {
  503. //>>includeStart('debug', pragmas.debug);
  504. Check.defined("url", url);
  505. //>>includeEnd('debug');
  506. options = options ?? Frozen.EMPTY_OBJECT;
  507. const resource = Resource.createIfNeeded(url);
  508. // Set a query parameter for json to avoid failure on html pages
  509. resource.setQueryParameters({ f: "pjson" }, true);
  510. const data = await I3SDataProvider.loadJson(resource);
  511. const provider = new I3SDataProvider(options);
  512. provider._resource = resource;
  513. provider._data = data;
  514. // Success
  515. if (defined(data.layers)) {
  516. const promises = [];
  517. for (let layerIndex = 0; layerIndex < data.layers.length; layerIndex++) {
  518. const promise = addLayers(provider, data.layers[layerIndex], options);
  519. promises.push(promise);
  520. }
  521. await Promise.all(promises);
  522. } else {
  523. await addLayers(provider, data, options);
  524. }
  525. provider._computeExtent();
  526. // Start loading all of the tiles
  527. const layerPromises = [];
  528. for (let i = 0; i < provider._layers.length; i++) {
  529. layerPromises.push(
  530. provider._layers[i].load(options.cesium3dTilesetOptions),
  531. );
  532. }
  533. await Promise.all(layerPromises);
  534. return provider;
  535. };
  536. /**
  537. * @private
  538. */
  539. I3SDataProvider._fetchJson = function (resource) {
  540. return resource.fetchJson();
  541. };
  542. /**
  543. * @private
  544. *
  545. * @param {Resource} resource The JSON resource to request
  546. * @returns {Promise<object>} The fetched data
  547. */
  548. I3SDataProvider.loadJson = async function (resource) {
  549. const data = await I3SDataProvider._fetchJson(resource);
  550. if (defined(data.error)) {
  551. console.error("Failed to fetch I3S ", resource.url);
  552. if (defined(data.error.message)) {
  553. console.error(data.error.message);
  554. }
  555. if (defined(data.error.details)) {
  556. for (let i = 0; i < data.error.details.length; i++) {
  557. console.log(data.error.details[i]);
  558. }
  559. }
  560. throw new RuntimeError(data.error);
  561. }
  562. return data;
  563. };
  564. /**
  565. * @private
  566. */
  567. I3SDataProvider.prototype._loadBinary = async function (resource) {
  568. const buffer = await resource.fetchArrayBuffer();
  569. if (buffer.byteLength > 0) {
  570. // Check if we have a JSON response with 404
  571. const array = new Uint8Array(buffer);
  572. if (array[0] === "{".charCodeAt(0)) {
  573. const textContent = new TextDecoder();
  574. const str = textContent.decode(buffer);
  575. if (str.includes("404")) {
  576. throw new RuntimeError(`Failed to load binary: ${resource.url}`);
  577. }
  578. }
  579. }
  580. return buffer;
  581. };
  582. /**
  583. * @private
  584. */
  585. I3SDataProvider.prototype._binarizeGltf = function (rawGltf) {
  586. const encoder = new TextEncoder();
  587. const rawGltfData = encoder.encode(JSON.stringify(rawGltf));
  588. const binaryGltfData = new Uint8Array(rawGltfData.byteLength + 20);
  589. const binaryGltf = {
  590. magic: new Uint8Array(binaryGltfData.buffer, 0, 4),
  591. version: new Uint32Array(binaryGltfData.buffer, 4, 1),
  592. length: new Uint32Array(binaryGltfData.buffer, 8, 1),
  593. chunkLength: new Uint32Array(binaryGltfData.buffer, 12, 1),
  594. chunkType: new Uint32Array(binaryGltfData.buffer, 16, 1),
  595. chunkData: new Uint8Array(
  596. binaryGltfData.buffer,
  597. 20,
  598. rawGltfData.byteLength,
  599. ),
  600. };
  601. binaryGltf.magic[0] = "g".charCodeAt();
  602. binaryGltf.magic[1] = "l".charCodeAt();
  603. binaryGltf.magic[2] = "T".charCodeAt();
  604. binaryGltf.magic[3] = "F".charCodeAt();
  605. binaryGltf.version[0] = 2;
  606. binaryGltf.length[0] = binaryGltfData.byteLength;
  607. binaryGltf.chunkLength[0] = rawGltfData.byteLength;
  608. binaryGltf.chunkType[0] = 0x4e4f534a; // JSON
  609. binaryGltf.chunkData.set(rawGltfData);
  610. return binaryGltfData;
  611. };
  612. const scratchCartesian2 = new Cartesian2();
  613. function getCoveredTiles(terrainProvider, extent) {
  614. const tilingScheme = terrainProvider.tilingScheme;
  615. // Sort points into a set of tiles
  616. const tileRequests = []; // Result will be an Array as it's easier to work with
  617. const tileRequestSet = {}; // A unique set
  618. const maxLevel = terrainProvider._lodCount;
  619. const topLeftCorner = Cartographic.fromRadians(extent.west, extent.north);
  620. const bottomRightCorner = Cartographic.fromRadians(extent.east, extent.south);
  621. const minCornerXY = tilingScheme.positionToTileXY(topLeftCorner, maxLevel);
  622. const maxCornerXY = tilingScheme.positionToTileXY(
  623. bottomRightCorner,
  624. maxLevel,
  625. );
  626. // Get all the tiles in between
  627. for (let x = minCornerXY.x; x <= maxCornerXY.x; x++) {
  628. for (let y = minCornerXY.y; y <= maxCornerXY.y; y++) {
  629. const xy = Cartesian2.fromElements(x, y, scratchCartesian2);
  630. const key = xy.toString();
  631. if (!tileRequestSet.hasOwnProperty(key)) {
  632. // When tile is requested for the first time
  633. const value = {
  634. x: xy.x,
  635. y: xy.y,
  636. level: maxLevel,
  637. tilingScheme: tilingScheme,
  638. terrainProvider: terrainProvider,
  639. positions: [],
  640. };
  641. tileRequestSet[key] = value;
  642. tileRequests.push(value);
  643. }
  644. }
  645. }
  646. // Send request for each required tile
  647. const tilePromises = [];
  648. for (let i = 0; i < tileRequests.length; ++i) {
  649. const tileRequest = tileRequests[i];
  650. const requestPromise = tileRequest.terrainProvider.requestTileGeometry(
  651. tileRequest.x,
  652. tileRequest.y,
  653. tileRequest.level,
  654. );
  655. tilePromises.push(requestPromise);
  656. }
  657. return Promise.all(tilePromises).then(function (heightMapBuffers) {
  658. const heightMaps = [];
  659. for (let i = 0; i < heightMapBuffers.length; i++) {
  660. const options = {
  661. tilingScheme: tilingScheme,
  662. x: tileRequests[i].x,
  663. y: tileRequests[i].y,
  664. level: tileRequests[i].level,
  665. };
  666. const heightMap = heightMapBuffers[i];
  667. let projectionType = "Geographic";
  668. if (tilingScheme._projection instanceof WebMercatorProjection) {
  669. projectionType = "WebMercator";
  670. }
  671. const heightMapData = {
  672. projectionType: projectionType,
  673. projection: tilingScheme._projection,
  674. nativeExtent: tilingScheme.tileXYToNativeRectangle(
  675. options.x,
  676. options.y,
  677. options.level,
  678. ),
  679. height: heightMap._height,
  680. width: heightMap._width,
  681. scale: heightMap._structure.heightScale,
  682. offset: heightMap._structure.heightOffset,
  683. };
  684. if (heightMap._encoding === HeightmapEncoding.LERC) {
  685. const result = Lerc.decode(heightMap._buffer);
  686. heightMapData.buffer = result.pixels[0];
  687. } else {
  688. heightMapData.buffer = heightMap._buffer;
  689. }
  690. heightMaps.push(heightMapData);
  691. }
  692. return heightMaps;
  693. });
  694. }
  695. async function loadGeoidData(provider) {
  696. // Load tiles from arcgis
  697. const geoidTerrainProvider = provider._geoidTiledTerrainProvider;
  698. if (!defined(geoidTerrainProvider)) {
  699. return;
  700. }
  701. try {
  702. const heightMaps = await getCoveredTiles(
  703. geoidTerrainProvider,
  704. provider._extent,
  705. );
  706. provider._geoidDataList = heightMaps;
  707. } catch (error) {
  708. console.log(
  709. "Error retrieving Geoid Terrain tiles - no geoid conversion will be performed.",
  710. );
  711. }
  712. }
  713. /**
  714. * @private
  715. */
  716. I3SDataProvider.prototype.loadGeoidData = async function () {
  717. if (defined(this._geoidDataPromise)) {
  718. return this._geoidDataPromise;
  719. }
  720. this._geoidDataPromise = loadGeoidData(this);
  721. return this._geoidDataPromise;
  722. };
  723. /**
  724. * @private
  725. */
  726. I3SDataProvider.prototype._computeExtent = function () {
  727. let rectangle;
  728. // Compute the extent from all layers
  729. for (
  730. let layerIndex = 0;
  731. layerIndex < this._layersExtent.length;
  732. layerIndex++
  733. ) {
  734. const layerExtent = this._layersExtent[layerIndex];
  735. if (!defined(rectangle)) {
  736. rectangle = Rectangle.clone(layerExtent);
  737. } else {
  738. Rectangle.union(rectangle, layerExtent, rectangle);
  739. }
  740. }
  741. this._extent = rectangle;
  742. };
  743. /**
  744. * Returns the collection of names for all available attributes
  745. * @returns {string[]} The collection of attribute names
  746. */
  747. I3SDataProvider.prototype.getAttributeNames = function () {
  748. const attributes = [];
  749. for (let i = 0; i < this._attributeStatistics.length; ++i) {
  750. attributes.push(...this._attributeStatistics[i].names);
  751. }
  752. return attributes;
  753. };
  754. /**
  755. * Returns the collection of values for the attribute with the given name
  756. * @param {string} name The attribute name
  757. * @returns {string[]} The collection of attribute values
  758. */
  759. I3SDataProvider.prototype.getAttributeValues = function (name) {
  760. //>>includeStart('debug', pragmas.debug);
  761. Check.defined("name", name);
  762. //>>includeEnd('debug');
  763. for (let i = 0; i < this._attributeStatistics.length; ++i) {
  764. const values = this._attributeStatistics[i]._getValues(name);
  765. if (defined(values)) {
  766. return values;
  767. }
  768. }
  769. return [];
  770. };
  771. /**
  772. * Filters the drawn elements of a scene to specific attribute names and values
  773. * @param {I3SNode.AttributeFilter[]} [filters=[]] The collection of attribute filters
  774. * @returns {Promise<void>} A promise that is resolved when the filter is applied
  775. */
  776. I3SDataProvider.prototype.filterByAttributes = function (filters) {
  777. const promises = [];
  778. for (let i = 0; i < this._layers.length; i++) {
  779. const promise = this._layers[i].filterByAttributes(filters);
  780. promises.push(promise);
  781. }
  782. return Promise.all(promises);
  783. };
  784. export default I3SDataProvider;