@loaders.gl/tiles 4.2.0-alpha.3 → 4.2.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/constants.js +34 -32
  2. package/dist/dist.dev.js +723 -342
  3. package/dist/dist.min.js +9 -0
  4. package/dist/index.cjs +98 -240
  5. package/dist/index.cjs.map +7 -0
  6. package/dist/index.d.ts +10 -10
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +3 -1
  9. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.d.ts +1 -1
  10. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.d.ts.map +1 -1
  11. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.js +45 -35
  12. package/dist/tileset/format-i3s/i3s-pending-tiles-register.js +40 -22
  13. package/dist/tileset/format-i3s/i3s-tile-manager.d.ts +1 -1
  14. package/dist/tileset/format-i3s/i3s-tile-manager.d.ts.map +1 -1
  15. package/dist/tileset/format-i3s/i3s-tile-manager.js +67 -69
  16. package/dist/tileset/format-i3s/i3s-tileset-traverser.d.ts +2 -2
  17. package/dist/tileset/format-i3s/i3s-tileset-traverser.d.ts.map +1 -1
  18. package/dist/tileset/format-i3s/i3s-tileset-traverser.js +78 -57
  19. package/dist/tileset/helpers/3d-tiles-options.d.ts +1 -1
  20. package/dist/tileset/helpers/3d-tiles-options.d.ts.map +1 -1
  21. package/dist/tileset/helpers/3d-tiles-options.js +3 -4
  22. package/dist/tileset/helpers/bounding-volume.js +269 -128
  23. package/dist/tileset/helpers/frame-state.d.ts +1 -1
  24. package/dist/tileset/helpers/frame-state.d.ts.map +1 -1
  25. package/dist/tileset/helpers/frame-state.js +114 -95
  26. package/dist/tileset/helpers/i3s-lod.d.ts +2 -2
  27. package/dist/tileset/helpers/i3s-lod.d.ts.map +1 -1
  28. package/dist/tileset/helpers/i3s-lod.js +68 -39
  29. package/dist/tileset/helpers/tiles-3d-lod.js +97 -85
  30. package/dist/tileset/helpers/transform-utils.js +45 -44
  31. package/dist/tileset/helpers/zoom.d.ts +1 -1
  32. package/dist/tileset/helpers/zoom.d.ts.map +1 -1
  33. package/dist/tileset/helpers/zoom.js +70 -40
  34. package/dist/tileset/tile-3d.d.ts +5 -5
  35. package/dist/tileset/tile-3d.d.ts.map +1 -1
  36. package/dist/tileset/tile-3d.js +595 -399
  37. package/dist/tileset/tileset-3d.d.ts +5 -5
  38. package/dist/tileset/tileset-3d.d.ts.map +1 -1
  39. package/dist/tileset/tileset-3d.js +721 -597
  40. package/dist/tileset/tileset-cache.d.ts +2 -2
  41. package/dist/tileset/tileset-cache.d.ts.map +1 -1
  42. package/dist/tileset/tileset-cache.js +62 -48
  43. package/dist/tileset/tileset-traverser.d.ts +3 -3
  44. package/dist/tileset/tileset-traverser.d.ts.map +1 -1
  45. package/dist/tileset/tileset-traverser.js +281 -220
  46. package/dist/types.js +0 -1
  47. package/dist/utils/doubly-linked-list-node.js +14 -9
  48. package/dist/utils/doubly-linked-list.d.ts +1 -1
  49. package/dist/utils/doubly-linked-list.d.ts.map +1 -1
  50. package/dist/utils/doubly-linked-list.js +85 -56
  51. package/dist/utils/managed-array.js +138 -76
  52. package/package.json +10 -9
  53. package/dist/constants.js.map +0 -1
  54. package/dist/index.js.map +0 -1
  55. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.js.map +0 -1
  56. package/dist/tileset/format-i3s/i3s-pending-tiles-register.js.map +0 -1
  57. package/dist/tileset/format-i3s/i3s-tile-manager.js.map +0 -1
  58. package/dist/tileset/format-i3s/i3s-tileset-traverser.js.map +0 -1
  59. package/dist/tileset/helpers/3d-tiles-options.js.map +0 -1
  60. package/dist/tileset/helpers/bounding-volume.js.map +0 -1
  61. package/dist/tileset/helpers/frame-state.js.map +0 -1
  62. package/dist/tileset/helpers/i3s-lod.js.map +0 -1
  63. package/dist/tileset/helpers/tiles-3d-lod.js.map +0 -1
  64. package/dist/tileset/helpers/transform-utils.js.map +0 -1
  65. package/dist/tileset/helpers/zoom.js.map +0 -1
  66. package/dist/tileset/tile-3d.js.map +0 -1
  67. package/dist/tileset/tileset-3d.js.map +0 -1
  68. package/dist/tileset/tileset-cache.js.map +0 -1
  69. package/dist/tileset/tileset-traverser.js.map +0 -1
  70. package/dist/types.js.map +0 -1
  71. package/dist/utils/doubly-linked-list-node.js.map +0 -1
  72. package/dist/utils/doubly-linked-list.js.map +0 -1
  73. package/dist/utils/managed-array.js.map +0 -1
@@ -1,3 +1,7 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) vis.gl contributors
3
+ // This file is derived from the Cesium code base under Apache 2 license
4
+ // See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
1
5
  import { Matrix4, Vector3 } from '@math.gl/core';
2
6
  import { Ellipsoid } from '@math.gl/geospatial';
3
7
  import { Stats } from '@probe.gl/stats';
@@ -9,36 +13,37 @@ import { getZoomFromBoundingVolume, getZoomFromExtent, getZoomFromFullExtent } f
9
13
  import { Tile3D } from "./tile-3d.js";
10
14
  import { TILESET_TYPE } from "../constants.js";
11
15
  import { TilesetTraverser } from "./tileset-traverser.js";
16
+ // TODO - these should be moved into their respective modules
12
17
  import { Tileset3DTraverser } from "./format-3d-tiles/tileset-3d-traverser.js";
13
18
  import { I3STilesetTraverser } from "./format-i3s/i3s-tileset-traverser.js";
14
19
  const DEFAULT_PROPS = {
15
- description: '',
16
- ellipsoid: Ellipsoid.WGS84,
17
- modelMatrix: new Matrix4(),
18
- throttleRequests: true,
19
- maxRequests: 64,
20
- maximumMemoryUsage: 32,
21
- memoryCacheOverflow: 1,
22
- maximumTilesSelected: 0,
23
- debounceTime: 0,
24
- onTileLoad: () => {},
25
- onTileUnload: () => {},
26
- onTileError: () => {},
27
- onTraversalComplete: selectedTiles => selectedTiles,
28
- contentLoader: undefined,
29
- viewDistanceScale: 1.0,
30
- maximumScreenSpaceError: 8,
31
- memoryAdjustedScreenSpaceError: false,
32
- loadTiles: true,
33
- updateTransforms: true,
34
- viewportTraversersMap: null,
35
- loadOptions: {
36
- fetch: {}
37
- },
38
- attributions: [],
39
- basePath: '',
40
- i3s: {}
20
+ description: '',
21
+ ellipsoid: Ellipsoid.WGS84,
22
+ modelMatrix: new Matrix4(),
23
+ throttleRequests: true,
24
+ maxRequests: 64,
25
+ /** Default memory values optimized for viewing mesh-based 3D Tiles on both mobile and desktop devices */
26
+ maximumMemoryUsage: 32,
27
+ memoryCacheOverflow: 1,
28
+ maximumTilesSelected: 0,
29
+ debounceTime: 0,
30
+ onTileLoad: () => { },
31
+ onTileUnload: () => { },
32
+ onTileError: () => { },
33
+ onTraversalComplete: (selectedTiles) => selectedTiles,
34
+ contentLoader: undefined,
35
+ viewDistanceScale: 1.0,
36
+ maximumScreenSpaceError: 8,
37
+ memoryAdjustedScreenSpaceError: false,
38
+ loadTiles: true,
39
+ updateTransforms: true,
40
+ viewportTraversersMap: null,
41
+ loadOptions: { fetch: {} },
42
+ attributions: [],
43
+ basePath: '',
44
+ i3s: {}
41
45
  };
46
+ // Tracked Stats
42
47
  const TILES_TOTAL = 'Tiles In Tileset(s)';
43
48
  const TILES_IN_MEMORY = 'Tiles In Memory';
44
49
  const TILES_IN_VIEW = 'Tiles In View';
@@ -50,578 +55,697 @@ const TILES_LOAD_FAILED = 'Failed Tile Loads';
50
55
  const POINTS_COUNT = 'Points/Vertices';
51
56
  const TILES_GPU_MEMORY = 'Tile Memory Use';
52
57
  const MAXIMUM_SSE = 'Maximum Screen Space Error';
58
+ /**
59
+ * The Tileset loading and rendering flow is as below,
60
+ * A rendered (i.e. deck.gl `Tile3DLayer`) triggers `tileset.update()` after a `tileset` is loaded
61
+ * `tileset` starts traversing the tile tree and update `requestTiles` (tiles of which content need
62
+ * to be fetched) and `selectedTiles` (tiles ready for rendering under the current viewport).
63
+ * `Tile3DLayer` will update rendering based on `selectedTiles`.
64
+ * `Tile3DLayer` also listens to `onTileLoad` callback and trigger another round of `update and then traversal`
65
+ * when new tiles are loaded.
66
+
67
+ * As I3S tileset have stored `tileHeader` file (metadata) and tile content files (geometry, texture, ...) separately.
68
+ * During each traversal, it issues `tilHeader` requests if that `tileHeader` is not yet fetched,
69
+ * after the tile header is fulfilled, it will resume the traversal starting from the tile just fetched (not root).
70
+
71
+ * Tile3DLayer
72
+ * |
73
+ * await load(tileset)
74
+ * |
75
+ * tileset.update()
76
+ * | async load tileHeader
77
+ * tileset.traverse() -------------------------- Queued
78
+ * | resume traversal after fetched |
79
+ * |----------------------------------------|
80
+ * |
81
+ * | async load tile content
82
+ * tilset.requestedTiles ----------------------------- RequestScheduler
83
+ * |
84
+ * tilset.selectedTiles (ready for rendering) |
85
+ * | Listen to |
86
+ * Tile3DLayer ----------- onTileLoad ----------------------|
87
+ * | | notify new tile is available
88
+ * updateLayers |
89
+ * tileset.update // trigger another round of update
90
+ */
53
91
  export class Tileset3D {
54
- constructor(tileset, options) {
55
- this.options = void 0;
56
- this.loadOptions = void 0;
57
- this.type = void 0;
58
- this.tileset = void 0;
59
- this.loader = void 0;
60
- this.url = void 0;
61
- this.basePath = void 0;
62
- this.modelMatrix = void 0;
63
- this.ellipsoid = void 0;
64
- this.lodMetricType = void 0;
65
- this.lodMetricValue = void 0;
66
- this.refine = void 0;
67
- this.root = null;
68
- this.roots = {};
69
- this.asset = {};
70
- this.description = '';
71
- this.properties = void 0;
72
- this.extras = null;
73
- this.attributions = {};
74
- this.credits = {};
75
- this.stats = void 0;
76
- this.contentFormats = {
77
- draco: false,
78
- meshopt: false,
79
- dds: false,
80
- ktx2: false
81
- };
82
- this.cartographicCenter = null;
83
- this.cartesianCenter = null;
84
- this.zoom = 1;
85
- this.boundingVolume = null;
86
- this.dynamicScreenSpaceErrorComputedDensity = 0.0;
87
- this.maximumMemoryUsage = 32;
88
- this.gpuMemoryUsageInBytes = 0;
89
- this.memoryAdjustedScreenSpaceError = 0.0;
90
- this._cacheBytes = 0;
91
- this._cacheOverflowBytes = 0;
92
- this._frameNumber = 0;
93
- this._queryParams = {};
94
- this._extensionsUsed = [];
95
- this._tiles = {};
96
- this._pendingCount = 0;
97
- this.selectedTiles = [];
98
- this.traverseCounter = 0;
99
- this.geometricError = 0;
100
- this.lastUpdatedVieports = null;
101
- this._requestedTiles = [];
102
- this._emptyTiles = [];
103
- this.frameStateData = {};
104
- this._traverser = void 0;
105
- this._cache = new TilesetCache();
106
- this._requestScheduler = void 0;
107
- this.updatePromise = null;
108
- this.tilesetInitializationPromise = void 0;
109
- this.options = {
110
- ...DEFAULT_PROPS,
111
- ...options
112
- };
113
- this.tileset = tileset;
114
- this.loader = tileset.loader;
115
- this.type = tileset.type;
116
- this.url = tileset.url;
117
- this.basePath = tileset.basePath || path.dirname(this.url);
118
- this.modelMatrix = this.options.modelMatrix;
119
- this.ellipsoid = this.options.ellipsoid;
120
- this.lodMetricType = tileset.lodMetricType;
121
- this.lodMetricValue = tileset.lodMetricValue;
122
- this.refine = tileset.root.refine;
123
- this.loadOptions = this.options.loadOptions || {};
124
- this._traverser = this._initializeTraverser();
125
- this._requestScheduler = new RequestScheduler({
126
- throttleRequests: this.options.throttleRequests,
127
- maxRequests: this.options.maxRequests
128
- });
129
- this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
130
- this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
131
- this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
132
- this.stats = new Stats({
133
- id: this.url
134
- });
135
- this._initializeStats();
136
- this.tilesetInitializationPromise = this._initializeTileSet(tileset);
137
- }
138
- destroy() {
139
- this._destroy();
140
- }
141
- isLoaded() {
142
- return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
143
- }
144
- get tiles() {
145
- return Object.values(this._tiles);
146
- }
147
- get frameNumber() {
148
- return this._frameNumber;
149
- }
150
- get queryParams() {
151
- return new URLSearchParams(this._queryParams).toString();
152
- }
153
- setProps(props) {
154
- this.options = {
155
- ...this.options,
156
- ...props
157
- };
158
- }
159
- getTileUrl(tilePath) {
160
- const isDataUrl = tilePath.startsWith('data:');
161
- if (isDataUrl) {
162
- return tilePath;
163
- }
164
- let tileUrl = tilePath;
165
- if (this.queryParams.length) {
166
- tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
167
- }
168
- return tileUrl;
169
- }
170
- hasExtension(extensionName) {
171
- return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
172
- }
173
- update() {
174
- let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
175
- this.tilesetInitializationPromise.then(() => {
176
- if (!viewports && this.lastUpdatedVieports) {
177
- viewports = this.lastUpdatedVieports;
178
- } else {
179
- this.lastUpdatedVieports = viewports;
180
- }
181
- if (viewports) {
182
- this.doUpdate(viewports);
183
- }
184
- });
185
- }
186
- async selectTiles() {
187
- let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
188
- await this.tilesetInitializationPromise;
189
- if (viewports) {
190
- this.lastUpdatedVieports = viewports;
191
- }
192
- if (!this.updatePromise) {
193
- this.updatePromise = new Promise(resolve => {
194
- setTimeout(() => {
195
- if (this.lastUpdatedVieports) {
196
- this.doUpdate(this.lastUpdatedVieports);
197
- }
198
- resolve(this._frameNumber);
199
- this.updatePromise = null;
200
- }, this.options.debounceTime);
201
- });
202
- }
203
- return this.updatePromise;
204
- }
205
- adjustScreenSpaceError() {
206
- if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
207
- this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
208
- } else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
209
- this.memoryAdjustedScreenSpaceError *= 1.02;
210
- }
211
- }
212
- doUpdate(viewports) {
213
- if ('loadTiles' in this.options && !this.options.loadTiles) {
214
- return;
215
- }
216
- if (this.traverseCounter > 0) {
217
- return;
218
- }
219
- const preparedViewports = viewports instanceof Array ? viewports : [viewports];
220
- this._cache.reset();
221
- this._frameNumber++;
222
- this.traverseCounter = preparedViewports.length;
223
- const viewportsToTraverse = [];
224
- for (const viewport of preparedViewports) {
225
- const id = viewport.id;
226
- if (this._needTraverse(id)) {
227
- viewportsToTraverse.push(id);
228
- } else {
92
+ /**
93
+ * Create a new Tileset3D
94
+ * @param json
95
+ * @param props
96
+ */
97
+ // eslint-disable-next-line max-statements
98
+ constructor(tileset, options) {
99
+ this.root = null;
100
+ this.roots = {};
101
+ /** @todo any->unknown */
102
+ this.asset = {};
103
+ // Metadata for the entire tileset
104
+ this.description = '';
105
+ this.extras = null;
106
+ this.attributions = {};
107
+ this.credits = {};
108
+ /** flags that contain information about data types in nested tiles */
109
+ this.contentFormats = { draco: false, meshopt: false, dds: false, ktx2: false };
110
+ // view props
111
+ this.cartographicCenter = null;
112
+ this.cartesianCenter = null;
113
+ this.zoom = 1;
114
+ this.boundingVolume = null;
115
+ /** Updated based on the camera position and direction */
116
+ this.dynamicScreenSpaceErrorComputedDensity = 0.0;
117
+ // METRICS
118
+ /**
119
+ * The maximum amount of GPU memory (in MB) that may be used to cache tiles
120
+ * Tiles not in view are unloaded to enforce private
121
+ */
122
+ this.maximumMemoryUsage = 32;
123
+ /** The total amount of GPU memory in bytes used by the tileset. */
124
+ this.gpuMemoryUsageInBytes = 0;
125
+ /**
126
+ * If loading the level of detail required by maximumScreenSpaceError
127
+ * results in the memory usage exceeding maximumMemoryUsage (GPU), level of detail refinement
128
+ * will instead use this (larger) adjusted screen space error to achieve the
129
+ * best possible visual quality within the available memory.
130
+ */
131
+ this.memoryAdjustedScreenSpaceError = 0.0;
132
+ this._cacheBytes = 0;
133
+ this._cacheOverflowBytes = 0;
134
+ /** Update tracker. increase in each update cycle. */
135
+ this._frameNumber = 0;
136
+ this._queryParams = {};
137
+ this._extensionsUsed = [];
138
+ this._tiles = {};
139
+ /** counter for tracking tiles requests */
140
+ this._pendingCount = 0;
141
+ /** Hold traversal results */
142
+ this.selectedTiles = [];
143
+ // TRAVERSAL
144
+ this.traverseCounter = 0;
145
+ this.geometricError = 0;
146
+ this.lastUpdatedVieports = null;
147
+ this._requestedTiles = [];
148
+ this._emptyTiles = [];
149
+ this.frameStateData = {};
150
+ this._cache = new TilesetCache();
151
+ // Promise tracking
152
+ this.updatePromise = null;
153
+ // PUBLIC MEMBERS
154
+ this.options = { ...DEFAULT_PROPS, ...options };
155
+ // raw data
156
+ this.tileset = tileset;
157
+ this.loader = tileset.loader;
158
+ // could be 3d tiles, i3s
159
+ this.type = tileset.type;
160
+ // The url to a tileset JSON file.
161
+ this.url = tileset.url;
162
+ this.basePath = tileset.basePath || path.dirname(this.url);
163
+ this.modelMatrix = this.options.modelMatrix;
164
+ this.ellipsoid = this.options.ellipsoid;
165
+ // Geometric error when the tree is not rendered at all
166
+ this.lodMetricType = tileset.lodMetricType;
167
+ this.lodMetricValue = tileset.lodMetricValue;
168
+ this.refine = tileset.root.refine;
169
+ this.loadOptions = this.options.loadOptions || {};
170
+ // TRAVERSAL
171
+ this._traverser = this._initializeTraverser();
172
+ this._requestScheduler = new RequestScheduler({
173
+ throttleRequests: this.options.throttleRequests,
174
+ maxRequests: this.options.maxRequests
175
+ });
176
+ this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
177
+ this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
178
+ this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
179
+ // METRICS
180
+ // The total amount of GPU memory in bytes used by the tileset.
181
+ this.stats = new Stats({ id: this.url });
182
+ this._initializeStats();
183
+ this.tilesetInitializationPromise = this._initializeTileSet(tileset);
184
+ }
185
+ /** Release resources */
186
+ destroy() {
187
+ this._destroy();
188
+ }
189
+ /** Is the tileset loaded (update needs to have been called at least once) */
190
+ isLoaded() {
191
+ // Check that `_frameNumber !== 0` which means that update was called at least once
192
+ return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
193
+ }
194
+ get tiles() {
195
+ return Object.values(this._tiles);
196
+ }
197
+ get frameNumber() {
198
+ return this._frameNumber;
199
+ }
200
+ get queryParams() {
201
+ return new URLSearchParams(this._queryParams).toString();
202
+ }
203
+ setProps(props) {
204
+ this.options = { ...this.options, ...props };
205
+ }
206
+ /** @deprecated */
207
+ // setOptions(options: Tileset3DProps): void {
208
+ // this.options = {...this.options, ...options};
209
+ // }
210
+ /**
211
+ * Return a loadable tile url for a specific tile subpath
212
+ * @param tilePath a tile subpath
213
+ */
214
+ getTileUrl(tilePath) {
215
+ const isDataUrl = tilePath.startsWith('data:');
216
+ if (isDataUrl) {
217
+ return tilePath;
218
+ }
219
+ let tileUrl = tilePath;
220
+ if (this.queryParams.length) {
221
+ tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
222
+ }
223
+ return tileUrl;
224
+ }
225
+ // TODO CESIUM specific
226
+ hasExtension(extensionName) {
227
+ return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
228
+ }
229
+ /**
230
+ * Update visible tiles relying on a list of viewports
231
+ * @param viewports - list of viewports
232
+ * @deprecated
233
+ */
234
+ update(viewports = null) {
235
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
236
+ this.tilesetInitializationPromise.then(() => {
237
+ if (!viewports && this.lastUpdatedVieports) {
238
+ viewports = this.lastUpdatedVieports;
239
+ }
240
+ else {
241
+ this.lastUpdatedVieports = viewports;
242
+ }
243
+ if (viewports) {
244
+ this.doUpdate(viewports);
245
+ }
246
+ });
247
+ }
248
+ /**
249
+ * Update visible tiles relying on a list of viewports.
250
+ * Do it with debounce delay to prevent update spam
251
+ * @param viewports viewports
252
+ * @returns Promise of new frameNumber
253
+ */
254
+ async selectTiles(viewports = null) {
255
+ await this.tilesetInitializationPromise;
256
+ if (viewports) {
257
+ this.lastUpdatedVieports = viewports;
258
+ }
259
+ if (!this.updatePromise) {
260
+ this.updatePromise = new Promise((resolve) => {
261
+ setTimeout(() => {
262
+ if (this.lastUpdatedVieports) {
263
+ this.doUpdate(this.lastUpdatedVieports);
264
+ }
265
+ resolve(this._frameNumber);
266
+ this.updatePromise = null;
267
+ }, this.options.debounceTime);
268
+ });
269
+ }
270
+ return this.updatePromise;
271
+ }
272
+ adjustScreenSpaceError() {
273
+ if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
274
+ this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
275
+ }
276
+ else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
277
+ this.memoryAdjustedScreenSpaceError *= 1.02;
278
+ }
279
+ }
280
+ /**
281
+ * Update visible tiles relying on a list of viewports
282
+ * @param viewports viewports
283
+ */
284
+ // eslint-disable-next-line max-statements, complexity
285
+ doUpdate(viewports) {
286
+ if ('loadTiles' in this.options && !this.options.loadTiles) {
287
+ return;
288
+ }
289
+ if (this.traverseCounter > 0) {
290
+ return;
291
+ }
292
+ const preparedViewports = viewports instanceof Array ? viewports : [viewports];
293
+ this._cache.reset();
294
+ this._frameNumber++;
295
+ this.traverseCounter = preparedViewports.length;
296
+ const viewportsToTraverse = [];
297
+ // First loop to decrement traverseCounter
298
+ for (const viewport of preparedViewports) {
299
+ const id = viewport.id;
300
+ if (this._needTraverse(id)) {
301
+ viewportsToTraverse.push(id);
302
+ }
303
+ else {
304
+ this.traverseCounter--;
305
+ }
306
+ }
307
+ // Second loop to traverse
308
+ for (const viewport of preparedViewports) {
309
+ const id = viewport.id;
310
+ if (!this.roots[id]) {
311
+ this.roots[id] = this._initializeTileHeaders(this.tileset, null);
312
+ }
313
+ if (!viewportsToTraverse.includes(id)) {
314
+ continue; // eslint-disable-line no-continue
315
+ }
316
+ const frameState = getFrameState(viewport, this._frameNumber);
317
+ this._traverser.traverse(this.roots[id], frameState, this.options);
318
+ }
319
+ }
320
+ /**
321
+ * Check if traversal is needed for particular viewport
322
+ * @param {string} viewportId - id of a viewport
323
+ * @return {boolean}
324
+ */
325
+ _needTraverse(viewportId) {
326
+ let traverserId = viewportId;
327
+ if (this.options.viewportTraversersMap) {
328
+ traverserId = this.options.viewportTraversersMap[viewportId];
329
+ }
330
+ if (traverserId !== viewportId) {
331
+ return false;
332
+ }
333
+ return true;
334
+ }
335
+ /**
336
+ * The callback to post-process tiles after traversal procedure
337
+ * @param frameState - frame state for tile culling
338
+ */
339
+ _onTraversalEnd(frameState) {
340
+ const id = frameState.viewport.id;
341
+ if (!this.frameStateData[id]) {
342
+ this.frameStateData[id] = { selectedTiles: [], _requestedTiles: [], _emptyTiles: [] };
343
+ }
344
+ const currentFrameStateData = this.frameStateData[id];
345
+ const selectedTiles = Object.values(this._traverser.selectedTiles);
346
+ const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
347
+ currentFrameStateData.selectedTiles = filteredSelectedTiles;
348
+ for (const tile of unselectedTiles) {
349
+ tile.unselect();
350
+ }
351
+ currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
352
+ currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
229
353
  this.traverseCounter--;
230
- }
231
- }
232
- for (const viewport of preparedViewports) {
233
- const id = viewport.id;
234
- if (!this.roots[id]) {
235
- this.roots[id] = this._initializeTileHeaders(this.tileset, null);
236
- }
237
- if (!viewportsToTraverse.includes(id)) {
238
- continue;
239
- }
240
- const frameState = getFrameState(viewport, this._frameNumber);
241
- this._traverser.traverse(this.roots[id], frameState, this.options);
242
- }
243
- }
244
- _needTraverse(viewportId) {
245
- let traverserId = viewportId;
246
- if (this.options.viewportTraversersMap) {
247
- traverserId = this.options.viewportTraversersMap[viewportId];
248
- }
249
- if (traverserId !== viewportId) {
250
- return false;
251
- }
252
- return true;
253
- }
254
- _onTraversalEnd(frameState) {
255
- const id = frameState.viewport.id;
256
- if (!this.frameStateData[id]) {
257
- this.frameStateData[id] = {
258
- selectedTiles: [],
259
- _requestedTiles: [],
260
- _emptyTiles: []
261
- };
262
- }
263
- const currentFrameStateData = this.frameStateData[id];
264
- const selectedTiles = Object.values(this._traverser.selectedTiles);
265
- const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
266
- currentFrameStateData.selectedTiles = filteredSelectedTiles;
267
- for (const tile of unselectedTiles) {
268
- tile.unselect();
269
- }
270
- currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
271
- currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
272
- this.traverseCounter--;
273
- if (this.traverseCounter > 0) {
274
- return;
275
- }
276
- this._updateTiles();
277
- }
278
- _updateTiles() {
279
- this.selectedTiles = [];
280
- this._requestedTiles = [];
281
- this._emptyTiles = [];
282
- for (const frameStateKey in this.frameStateData) {
283
- const frameStateDataValue = this.frameStateData[frameStateKey];
284
- this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
285
- this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
286
- this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
287
- }
288
- this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
289
- for (const tile of this.selectedTiles) {
290
- this._tiles[tile.id] = tile;
291
- }
292
- this._loadTiles();
293
- this._unloadTiles();
294
- this._updateStats();
295
- }
296
- _tilesChanged(oldSelectedTiles, selectedTiles) {
297
- if (oldSelectedTiles.length !== selectedTiles.length) {
298
- return true;
299
- }
300
- const set1 = new Set(oldSelectedTiles.map(t => t.id));
301
- const set2 = new Set(selectedTiles.map(t => t.id));
302
- let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
303
- changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
304
- return changed;
305
- }
306
- _loadTiles() {
307
- for (const tile of this._requestedTiles) {
308
- if (tile.contentUnloaded) {
309
- this._loadTile(tile);
310
- }
311
- }
312
- }
313
- _unloadTiles() {
314
- this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
315
- }
316
- _updateStats() {
317
- let tilesRenderable = 0;
318
- let pointsRenderable = 0;
319
- for (const tile of this.selectedTiles) {
320
- if (tile.contentAvailable && tile.content) {
321
- tilesRenderable++;
322
- if (tile.content.pointCount) {
323
- pointsRenderable += tile.content.pointCount;
324
- } else {
325
- pointsRenderable += tile.content.vertexCount;
326
- }
327
- }
328
- }
329
- this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
330
- this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
331
- this.stats.get(POINTS_COUNT).count = pointsRenderable;
332
- this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
333
- }
334
- async _initializeTileSet(tilesetJson) {
335
- if (this.type === TILESET_TYPE.I3S) {
336
- this.calculateViewPropsI3S();
337
- tilesetJson.root = await tilesetJson.root;
338
- }
339
- this.root = this._initializeTileHeaders(tilesetJson, null);
340
- if (this.type === TILESET_TYPE.TILES3D) {
341
- this._initializeTiles3DTileset(tilesetJson);
342
- this.calculateViewPropsTiles3D();
343
- }
344
- if (this.type === TILESET_TYPE.I3S) {
345
- this._initializeI3STileset();
346
- }
347
- }
348
- calculateViewPropsI3S() {
349
- var _this$tileset$store;
350
- const fullExtent = this.tileset.fullExtent;
351
- if (fullExtent) {
352
- const {
353
- xmin,
354
- xmax,
355
- ymin,
356
- ymax,
357
- zmin,
358
- zmax
359
- } = fullExtent;
360
- this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
361
- this.cartesianCenter = new Vector3();
362
- Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
363
- this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
364
- return;
365
- }
366
- const extent = (_this$tileset$store = this.tileset.store) === null || _this$tileset$store === void 0 ? void 0 : _this$tileset$store.extent;
367
- if (extent) {
368
- const [xmin, ymin, xmax, ymax] = extent;
369
- this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
370
- this.cartesianCenter = new Vector3();
371
- Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
372
- this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
373
- return;
374
- }
375
- console.warn('Extent is not defined in the tileset header');
376
- this.cartographicCenter = new Vector3();
377
- this.zoom = 1;
378
- return;
379
- }
380
- calculateViewPropsTiles3D() {
381
- const root = this.root;
382
- const {
383
- center
384
- } = root.boundingVolume;
385
- if (!center) {
386
- console.warn('center was not pre-calculated for the root tile');
387
- this.cartographicCenter = new Vector3();
388
- this.zoom = 1;
389
- return;
390
- }
391
- if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
392
- this.cartographicCenter = new Vector3();
393
- Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
394
- } else {
395
- this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
396
- }
397
- this.cartesianCenter = center;
398
- this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
399
- }
400
- _initializeStats() {
401
- this.stats.get(TILES_TOTAL);
402
- this.stats.get(TILES_LOADING);
403
- this.stats.get(TILES_IN_MEMORY);
404
- this.stats.get(TILES_IN_VIEW);
405
- this.stats.get(TILES_RENDERABLE);
406
- this.stats.get(TILES_LOADED);
407
- this.stats.get(TILES_UNLOADED);
408
- this.stats.get(TILES_LOAD_FAILED);
409
- this.stats.get(POINTS_COUNT);
410
- this.stats.get(TILES_GPU_MEMORY, 'memory');
411
- this.stats.get(MAXIMUM_SSE);
412
- }
413
- _initializeTileHeaders(tilesetJson, parentTileHeader) {
414
- const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader);
415
- if (parentTileHeader) {
416
- parentTileHeader.children.push(rootTile);
417
- rootTile.depth = parentTileHeader.depth + 1;
418
- }
419
- if (this.type === TILESET_TYPE.TILES3D) {
420
- const stack = [];
421
- stack.push(rootTile);
422
- while (stack.length > 0) {
423
- const tile = stack.pop();
424
- this.stats.get(TILES_TOTAL).incrementCount();
425
- const children = tile.header.children || [];
426
- for (const childHeader of children) {
427
- var _childTile$contentUrl;
428
- const childTile = new Tile3D(this, childHeader, tile);
429
- if ((_childTile$contentUrl = childTile.contentUrl) !== null && _childTile$contentUrl !== void 0 && _childTile$contentUrl.includes('?session=')) {
430
- const url = new URL(childTile.contentUrl);
431
- const session = url.searchParams.get('session');
432
- if (session) {
433
- this._queryParams.session = session;
354
+ if (this.traverseCounter > 0) {
355
+ return;
356
+ }
357
+ this._updateTiles();
358
+ }
359
+ /**
360
+ * Update tiles relying on data from all traversers
361
+ */
362
+ _updateTiles() {
363
+ this.selectedTiles = [];
364
+ this._requestedTiles = [];
365
+ this._emptyTiles = [];
366
+ for (const frameStateKey in this.frameStateData) {
367
+ const frameStateDataValue = this.frameStateData[frameStateKey];
368
+ this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
369
+ this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
370
+ this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
371
+ }
372
+ this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
373
+ for (const tile of this.selectedTiles) {
374
+ this._tiles[tile.id] = tile;
375
+ }
376
+ this._loadTiles();
377
+ this._unloadTiles();
378
+ this._updateStats();
379
+ }
380
+ _tilesChanged(oldSelectedTiles, selectedTiles) {
381
+ if (oldSelectedTiles.length !== selectedTiles.length) {
382
+ return true;
383
+ }
384
+ const set1 = new Set(oldSelectedTiles.map((t) => t.id));
385
+ const set2 = new Set(selectedTiles.map((t) => t.id));
386
+ let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0;
387
+ changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0;
388
+ return changed;
389
+ }
390
+ _loadTiles() {
391
+ // Sort requests by priority before making any requests.
392
+ // This makes it less likely this requests will be cancelled after being issued.
393
+ // requestedTiles.sort((a, b) => a._priority - b._priority);
394
+ for (const tile of this._requestedTiles) {
395
+ if (tile.contentUnloaded) {
396
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
397
+ this._loadTile(tile);
434
398
  }
435
- }
436
- tile.children.push(childTile);
437
- childTile.depth = tile.depth + 1;
438
- stack.push(childTile);
439
- }
440
- }
441
- }
442
- return rootTile;
443
- }
444
- _initializeTraverser() {
445
- let TraverserClass;
446
- const type = this.type;
447
- switch (type) {
448
- case TILESET_TYPE.TILES3D:
449
- TraverserClass = Tileset3DTraverser;
450
- break;
451
- case TILESET_TYPE.I3S:
452
- TraverserClass = I3STilesetTraverser;
453
- break;
454
- default:
455
- TraverserClass = TilesetTraverser;
456
- }
457
- return new TraverserClass({
458
- basePath: this.basePath,
459
- onTraversalEnd: this._onTraversalEnd.bind(this)
460
- });
461
- }
462
- _destroyTileHeaders(parentTile) {
463
- this._destroySubtree(parentTile);
464
- }
465
- async _loadTile(tile) {
466
- let loaded;
467
- try {
468
- this._onStartTileLoading();
469
- loaded = await tile.loadContent();
470
- } catch (error) {
471
- this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
472
- } finally {
473
- this._onEndTileLoading();
474
- this._onTileLoad(tile, loaded);
475
- }
476
- }
477
- _onTileLoadError(tile, error) {
478
- this.stats.get(TILES_LOAD_FAILED).incrementCount();
479
- const message = error.message || error.toString();
480
- const url = tile.url;
481
- console.error(`A 3D tile failed to load: ${tile.url} ${message}`);
482
- this.options.onTileError(tile, message, url);
483
- }
484
- _onTileLoad(tile, loaded) {
485
- if (!loaded) {
486
- return;
487
- }
488
- if (this.type === TILESET_TYPE.I3S) {
489
- var _this$tileset, _this$tileset$nodePag;
490
- const nodesInNodePages = ((_this$tileset = this.tileset) === null || _this$tileset === void 0 ? void 0 : (_this$tileset$nodePag = _this$tileset.nodePagesTile) === null || _this$tileset$nodePag === void 0 ? void 0 : _this$tileset$nodePag.nodesInNodePages) || 0;
491
- this.stats.get(TILES_TOTAL).reset();
492
- this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
493
- }
494
- if (tile && tile.content) {
495
- calculateTransformProps(tile, tile.content);
496
- }
497
- this.updateContentTypes(tile);
498
- this._addTileToCache(tile);
499
- this.options.onTileLoad(tile);
500
- }
501
- updateContentTypes(tile) {
502
- if (this.type === TILESET_TYPE.I3S) {
503
- if (tile.header.isDracoGeometry) {
504
- this.contentFormats.draco = true;
505
- }
506
- switch (tile.header.textureFormat) {
507
- case 'dds':
508
- this.contentFormats.dds = true;
509
- break;
510
- case 'ktx2':
511
- this.contentFormats.ktx2 = true;
512
- break;
513
- default:
514
- }
515
- } else if (this.type === TILESET_TYPE.TILES3D) {
516
- var _tile$content;
517
- const {
518
- extensionsRemoved = []
519
- } = ((_tile$content = tile.content) === null || _tile$content === void 0 ? void 0 : _tile$content.gltf) || {};
520
- if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
521
- this.contentFormats.draco = true;
522
- }
523
- if (extensionsRemoved.includes('EXT_meshopt_compression')) {
524
- this.contentFormats.meshopt = true;
525
- }
526
- if (extensionsRemoved.includes('KHR_texture_basisu')) {
527
- this.contentFormats.ktx2 = true;
528
- }
529
- }
530
- }
531
- _onStartTileLoading() {
532
- this._pendingCount++;
533
- this.stats.get(TILES_LOADING).incrementCount();
534
- }
535
- _onEndTileLoading() {
536
- this._pendingCount--;
537
- this.stats.get(TILES_LOADING).decrementCount();
538
- }
539
- _addTileToCache(tile) {
540
- this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
541
- }
542
- _updateCacheStats(tile) {
543
- this.stats.get(TILES_LOADED).incrementCount();
544
- this.stats.get(TILES_IN_MEMORY).incrementCount();
545
- this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
546
- this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
547
- if (this.options.memoryAdjustedScreenSpaceError) {
548
- this.adjustScreenSpaceError();
549
- }
550
- }
551
- _unloadTile(tile) {
552
- this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
553
- this.stats.get(TILES_IN_MEMORY).decrementCount();
554
- this.stats.get(TILES_UNLOADED).incrementCount();
555
- this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
556
- this.options.onTileUnload(tile);
557
- tile.unloadContent();
558
- }
559
- _destroy() {
560
- const stack = [];
561
- if (this.root) {
562
- stack.push(this.root);
563
- }
564
- while (stack.length > 0) {
565
- const tile = stack.pop();
566
- for (const child of tile.children) {
567
- stack.push(child);
568
- }
569
- this._destroyTile(tile);
570
- }
571
- this.root = null;
572
- }
573
- _destroySubtree(tile) {
574
- const root = tile;
575
- const stack = [];
576
- stack.push(root);
577
- while (stack.length > 0) {
578
- tile = stack.pop();
579
- for (const child of tile.children) {
580
- stack.push(child);
581
- }
582
- if (tile !== root) {
583
- this._destroyTile(tile);
584
- }
585
- }
586
- root.children = [];
587
- }
588
- _destroyTile(tile) {
589
- this._cache.unloadTile(this, tile);
590
- this._unloadTile(tile);
591
- tile.destroy();
592
- }
593
- _initializeTiles3DTileset(tilesetJson) {
594
- if (tilesetJson.queryString) {
595
- const searchParams = new URLSearchParams(tilesetJson.queryString);
596
- const queryParams = Object.fromEntries(searchParams.entries());
597
- this._queryParams = {
598
- ...this._queryParams,
599
- ...queryParams
600
- };
601
- }
602
- this.asset = tilesetJson.asset;
603
- if (!this.asset) {
604
- throw new Error('Tileset must have an asset property.');
605
- }
606
- if (this.asset.version !== '0.0' && this.asset.version !== '1.0' && this.asset.version !== '1.1') {
607
- throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
608
- }
609
- if ('tilesetVersion' in this.asset) {
610
- this._queryParams.v = this.asset.tilesetVersion;
611
- }
612
- this.credits = {
613
- attributions: this.options.attributions || []
614
- };
615
- this.description = this.options.description || '';
616
- this.properties = tilesetJson.properties;
617
- this.geometricError = tilesetJson.geometricError;
618
- this._extensionsUsed = tilesetJson.extensionsUsed || [];
619
- this.extras = tilesetJson.extras;
620
- }
621
- _initializeI3STileset() {
622
- if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
623
- this._queryParams.token = this.loadOptions.i3s.token;
624
- }
625
- }
399
+ }
400
+ }
401
+ _unloadTiles() {
402
+ // unload tiles from cache when hit maximumMemoryUsage
403
+ this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
404
+ }
405
+ _updateStats() {
406
+ let tilesRenderable = 0;
407
+ let pointsRenderable = 0;
408
+ for (const tile of this.selectedTiles) {
409
+ if (tile.contentAvailable && tile.content) {
410
+ tilesRenderable++;
411
+ if (tile.content.pointCount) {
412
+ pointsRenderable += tile.content.pointCount;
413
+ }
414
+ else {
415
+ // Calculate vertices for non point cloud tiles.
416
+ pointsRenderable += tile.content.vertexCount;
417
+ }
418
+ }
419
+ }
420
+ this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
421
+ this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
422
+ this.stats.get(POINTS_COUNT).count = pointsRenderable;
423
+ this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
424
+ }
425
+ async _initializeTileSet(tilesetJson) {
426
+ if (this.type === TILESET_TYPE.I3S) {
427
+ this.calculateViewPropsI3S();
428
+ tilesetJson.root = await tilesetJson.root;
429
+ }
430
+ this.root = this._initializeTileHeaders(tilesetJson, null);
431
+ if (this.type === TILESET_TYPE.TILES3D) {
432
+ this._initializeTiles3DTileset(tilesetJson);
433
+ this.calculateViewPropsTiles3D();
434
+ }
435
+ if (this.type === TILESET_TYPE.I3S) {
436
+ this._initializeI3STileset();
437
+ }
438
+ }
439
+ /**
440
+ * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
441
+ * These metrics help apps center view on tileset
442
+ * For I3S there is extent (<1.8 version) or fullExtent (>=1.8 version) to calculate view props
443
+ * @returns
444
+ */
445
+ calculateViewPropsI3S() {
446
+ // for I3S 1.8 try to calculate with fullExtent
447
+ const fullExtent = this.tileset.fullExtent;
448
+ if (fullExtent) {
449
+ const { xmin, xmax, ymin, ymax, zmin, zmax } = fullExtent;
450
+ this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
451
+ this.cartesianCenter = new Vector3();
452
+ Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
453
+ this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
454
+ return;
455
+ }
456
+ // for I3S 1.6-1.7 try to calculate with extent
457
+ const extent = this.tileset.store?.extent;
458
+ if (extent) {
459
+ const [xmin, ymin, xmax, ymax] = extent;
460
+ this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
461
+ this.cartesianCenter = new Vector3();
462
+ Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
463
+ this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
464
+ return;
465
+ }
466
+ // eslint-disable-next-line no-console
467
+ console.warn('Extent is not defined in the tileset header');
468
+ this.cartographicCenter = new Vector3();
469
+ this.zoom = 1;
470
+ return;
471
+ }
472
+ /**
473
+ * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
474
+ * These metrics help apps center view on tileset.
475
+ * For 3DTiles the root tile data is used to calculate view props.
476
+ * @returns
477
+ */
478
+ calculateViewPropsTiles3D() {
479
+ const root = this.root;
480
+ const { center } = root.boundingVolume;
481
+ // TODO - handle all cases
482
+ if (!center) {
483
+ // eslint-disable-next-line no-console
484
+ console.warn('center was not pre-calculated for the root tile');
485
+ this.cartographicCenter = new Vector3();
486
+ this.zoom = 1;
487
+ return;
488
+ }
489
+ // cartographic coordinates are undefined at the center of the ellipsoid
490
+ if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
491
+ this.cartographicCenter = new Vector3();
492
+ Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
493
+ }
494
+ else {
495
+ this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
496
+ }
497
+ this.cartesianCenter = center;
498
+ this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
499
+ }
500
+ _initializeStats() {
501
+ this.stats.get(TILES_TOTAL);
502
+ this.stats.get(TILES_LOADING);
503
+ this.stats.get(TILES_IN_MEMORY);
504
+ this.stats.get(TILES_IN_VIEW);
505
+ this.stats.get(TILES_RENDERABLE);
506
+ this.stats.get(TILES_LOADED);
507
+ this.stats.get(TILES_UNLOADED);
508
+ this.stats.get(TILES_LOAD_FAILED);
509
+ this.stats.get(POINTS_COUNT);
510
+ this.stats.get(TILES_GPU_MEMORY, 'memory');
511
+ this.stats.get(MAXIMUM_SSE);
512
+ }
513
+ // Installs the main tileset JSON file or a tileset JSON file referenced from a tile.
514
+ // eslint-disable-next-line max-statements
515
+ _initializeTileHeaders(tilesetJson, parentTileHeader) {
516
+ // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
517
+ // Get the basePath relative to the external tileset.
518
+ const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource
519
+ // If there is a parentTileHeader, add the root of the currently loading tileset
520
+ // to parentTileHeader's children, and update its depth.
521
+ if (parentTileHeader) {
522
+ parentTileHeader.children.push(rootTile);
523
+ rootTile.depth = parentTileHeader.depth + 1;
524
+ }
525
+ // 3DTiles knows the hierarchy beforehand
526
+ if (this.type === TILESET_TYPE.TILES3D) {
527
+ const stack = [];
528
+ stack.push(rootTile);
529
+ while (stack.length > 0) {
530
+ const tile = stack.pop();
531
+ this.stats.get(TILES_TOTAL).incrementCount();
532
+ const children = tile.header.children || [];
533
+ for (const childHeader of children) {
534
+ const childTile = new Tile3D(this, childHeader, tile);
535
+ // Special handling for Google
536
+ // A session key must be used for all tile requests
537
+ if (childTile.contentUrl?.includes('?session=')) {
538
+ const url = new URL(childTile.contentUrl);
539
+ const session = url.searchParams.get('session');
540
+ // eslint-disable-next-line max-depth
541
+ if (session) {
542
+ this._queryParams.session = session;
543
+ }
544
+ }
545
+ tile.children.push(childTile);
546
+ childTile.depth = tile.depth + 1;
547
+ stack.push(childTile);
548
+ }
549
+ }
550
+ }
551
+ return rootTile;
552
+ }
553
+ _initializeTraverser() {
554
+ let TraverserClass;
555
+ const type = this.type;
556
+ switch (type) {
557
+ case TILESET_TYPE.TILES3D:
558
+ TraverserClass = Tileset3DTraverser;
559
+ break;
560
+ case TILESET_TYPE.I3S:
561
+ TraverserClass = I3STilesetTraverser;
562
+ break;
563
+ default:
564
+ TraverserClass = TilesetTraverser;
565
+ }
566
+ return new TraverserClass({
567
+ basePath: this.basePath,
568
+ onTraversalEnd: this._onTraversalEnd.bind(this)
569
+ });
570
+ }
571
+ _destroyTileHeaders(parentTile) {
572
+ this._destroySubtree(parentTile);
573
+ }
574
+ async _loadTile(tile) {
575
+ let loaded;
576
+ try {
577
+ this._onStartTileLoading();
578
+ loaded = await tile.loadContent();
579
+ }
580
+ catch (error) {
581
+ this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
582
+ }
583
+ finally {
584
+ this._onEndTileLoading();
585
+ this._onTileLoad(tile, loaded);
586
+ }
587
+ }
588
+ _onTileLoadError(tile, error) {
589
+ this.stats.get(TILES_LOAD_FAILED).incrementCount();
590
+ const message = error.message || error.toString();
591
+ const url = tile.url;
592
+ // TODO - Allow for probe log to be injected instead of console?
593
+ console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line
594
+ this.options.onTileError(tile, message, url);
595
+ }
596
+ _onTileLoad(tile, loaded) {
597
+ if (!loaded) {
598
+ return;
599
+ }
600
+ if (this.type === TILESET_TYPE.I3S) {
601
+ // We can't calculate tiles total in I3S in advance so we calculate it dynamically.
602
+ const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0;
603
+ this.stats.get(TILES_TOTAL).reset();
604
+ this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
605
+ }
606
+ // add coordinateOrigin and modelMatrix to tile
607
+ if (tile && tile.content) {
608
+ calculateTransformProps(tile, tile.content);
609
+ }
610
+ this.updateContentTypes(tile);
611
+ this._addTileToCache(tile);
612
+ this.options.onTileLoad(tile);
613
+ }
614
+ /**
615
+ * Update information about data types in nested tiles
616
+ * @param tile instance of a nested Tile3D
617
+ */
618
+ updateContentTypes(tile) {
619
+ if (this.type === TILESET_TYPE.I3S) {
620
+ if (tile.header.isDracoGeometry) {
621
+ this.contentFormats.draco = true;
622
+ }
623
+ switch (tile.header.textureFormat) {
624
+ case 'dds':
625
+ this.contentFormats.dds = true;
626
+ break;
627
+ case 'ktx2':
628
+ this.contentFormats.ktx2 = true;
629
+ break;
630
+ default:
631
+ }
632
+ }
633
+ else if (this.type === TILESET_TYPE.TILES3D) {
634
+ const { extensionsRemoved = [] } = tile.content?.gltf || {};
635
+ if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
636
+ this.contentFormats.draco = true;
637
+ }
638
+ if (extensionsRemoved.includes('EXT_meshopt_compression')) {
639
+ this.contentFormats.meshopt = true;
640
+ }
641
+ if (extensionsRemoved.includes('KHR_texture_basisu')) {
642
+ this.contentFormats.ktx2 = true;
643
+ }
644
+ }
645
+ }
646
+ _onStartTileLoading() {
647
+ this._pendingCount++;
648
+ this.stats.get(TILES_LOADING).incrementCount();
649
+ }
650
+ _onEndTileLoading() {
651
+ this._pendingCount--;
652
+ this.stats.get(TILES_LOADING).decrementCount();
653
+ }
654
+ _addTileToCache(tile) {
655
+ this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile));
656
+ }
657
+ _updateCacheStats(tile) {
658
+ this.stats.get(TILES_LOADED).incrementCount();
659
+ this.stats.get(TILES_IN_MEMORY).incrementCount();
660
+ // TODO: Calculate GPU memory usage statistics for a tile.
661
+ this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
662
+ this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
663
+ // Adjust SSE based on cache limits
664
+ if (this.options.memoryAdjustedScreenSpaceError) {
665
+ this.adjustScreenSpaceError();
666
+ }
667
+ }
668
+ _unloadTile(tile) {
669
+ this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
670
+ this.stats.get(TILES_IN_MEMORY).decrementCount();
671
+ this.stats.get(TILES_UNLOADED).incrementCount();
672
+ this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
673
+ this.options.onTileUnload(tile);
674
+ tile.unloadContent();
675
+ }
676
+ // Traverse the tree and destroy all tiles
677
+ _destroy() {
678
+ const stack = [];
679
+ if (this.root) {
680
+ stack.push(this.root);
681
+ }
682
+ while (stack.length > 0) {
683
+ const tile = stack.pop();
684
+ for (const child of tile.children) {
685
+ stack.push(child);
686
+ }
687
+ this._destroyTile(tile);
688
+ }
689
+ this.root = null;
690
+ }
691
+ // Traverse the tree and destroy all sub tiles
692
+ _destroySubtree(tile) {
693
+ const root = tile;
694
+ const stack = [];
695
+ stack.push(root);
696
+ while (stack.length > 0) {
697
+ tile = stack.pop();
698
+ for (const child of tile.children) {
699
+ stack.push(child);
700
+ }
701
+ if (tile !== root) {
702
+ this._destroyTile(tile);
703
+ }
704
+ }
705
+ root.children = [];
706
+ }
707
+ _destroyTile(tile) {
708
+ this._cache.unloadTile(this, tile);
709
+ this._unloadTile(tile);
710
+ tile.destroy();
711
+ }
712
+ _initializeTiles3DTileset(tilesetJson) {
713
+ if (tilesetJson.queryString) {
714
+ const searchParams = new URLSearchParams(tilesetJson.queryString);
715
+ const queryParams = Object.fromEntries(searchParams.entries());
716
+ this._queryParams = { ...this._queryParams, ...queryParams };
717
+ }
718
+ this.asset = tilesetJson.asset;
719
+ if (!this.asset) {
720
+ throw new Error('Tileset must have an asset property.');
721
+ }
722
+ if (this.asset.version !== '0.0' &&
723
+ this.asset.version !== '1.0' &&
724
+ this.asset.version !== '1.1') {
725
+ throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
726
+ }
727
+ // Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard)
728
+ // We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version
729
+ if ('tilesetVersion' in this.asset) {
730
+ this._queryParams.v = this.asset.tilesetVersion;
731
+ }
732
+ // TODO - ion resources have a credits property we can use for additional attribution.
733
+ this.credits = {
734
+ attributions: this.options.attributions || []
735
+ };
736
+ this.description = this.options.description || '';
737
+ // Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
738
+ this.properties = tilesetJson.properties;
739
+ this.geometricError = tilesetJson.geometricError;
740
+ this._extensionsUsed = tilesetJson.extensionsUsed || [];
741
+ // Returns the extras property at the top of the tileset JSON (application specific metadata).
742
+ this.extras = tilesetJson.extras;
743
+ }
744
+ _initializeI3STileset() {
745
+ // @ts-expect-error
746
+ if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
747
+ // @ts-ignore
748
+ this._queryParams.token = this.loadOptions.i3s.token;
749
+ }
750
+ }
626
751
  }
627
- //# sourceMappingURL=tileset-3d.js.map