15832144755
2022-01-06 7b4c8991dca9cf2a809a95e239d144697d3afb56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Request from "../Core/Request.js";
import RequestScheduler from "../Core/RequestScheduler.js";
import RequestState from "../Core/RequestState.js";
import RequestType from "../Core/RequestType.js";
import RuntimeError from "../Core/RuntimeError.js";
import when from "../ThirdParty/when.js";
import Cesium3DTileContentType from "./Cesium3DTileContentType.js";
import Cesium3DTileContentFactory from "./Cesium3DTileContentFactory.js";
import findGroupMetadata from "./findGroupMetadata.js";
import preprocess3DTileContent from "./preprocess3DTileContent.js";
 
/**
 * A collection of contents for tiles that use the <code>3DTILES_multiple_contents</code> extension.
 * <p>
 * Implements the {@link Cesium3DTileContent} interface.
 * </p>
 *
 * @see {@link https://github.com/CesiumGS/3d-tiles/tree/3d-tiles-next/extensions/3DTILES_multiple_contents|3DTILES_multiple_contents extension}
 *
 * @alias Multiple3DTileContent
 * @constructor
 *
 * @param {Cesium3DTileset} tileset The tileset this content belongs to
 * @param {Cesium3DTile} tile The content this content belongs to
 * @param {Resource} tilesetResource The resource that points to the tileset. This will be used to derive each inner content's resource.
 * @param {Object} extensionJson The <code>3DTILES_multiple_contents</code> extension JSON
 *
 * @private
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 */
export default function Multiple3DTileContent(
  tileset,
  tile,
  tilesetResource,
  extensionJson
) {
  this._tileset = tileset;
  this._tile = tile;
  this._tilesetResource = tilesetResource;
  this._contents = [];
 
  var contentHeaders = extensionJson.content;
  this._innerContentHeaders = contentHeaders;
  this._requestsInFlight = 0;
 
  // How many times cancelPendingRequests() has been called. This is
  // used to help short-circuit computations after a tile was canceled.
  this._cancelCount = 0;
 
  var contentCount = this._innerContentHeaders.length;
  this._arrayFetchPromises = new Array(contentCount);
  this._requests = new Array(contentCount);
 
  this._innerContentResources = new Array(contentCount);
  this._serverKeys = new Array(contentCount);
 
  for (var i = 0; i < contentCount; i++) {
    var contentResource = tilesetResource.getDerivedResource({
      url: contentHeaders[i].uri,
    });
 
    var serverKey = RequestScheduler.getServerKey(
      contentResource.getUrlComponent()
    );
 
    this._innerContentResources[i] = contentResource;
    this._serverKeys[i] = serverKey;
  }
 
  // undefined until the first time requests are scheduled
  this._contentsFetchedPromise = undefined;
  this._readyPromise = when.defer();
}
 
Object.defineProperties(Multiple3DTileContent.prototype, {
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code> checks if any of the inner contents have dirty featurePropertiesDirty.
   * @memberof Multiple3DTileContent.prototype
   *
   * @type {Boolean}
   *
   * @private
   */
  featurePropertiesDirty: {
    get: function () {
      var contents = this._contents;
      var length = contents.length;
      for (var i = 0; i < length; ++i) {
        if (contents[i].featurePropertiesDirty) {
          return true;
        }
      }
 
      return false;
    },
    set: function (value) {
      var contents = this._contents;
      var length = contents.length;
      for (var i = 0; i < length; ++i) {
        contents[i].featurePropertiesDirty = value;
      }
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead call <code>featuresLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  featuresLength: {
    get: function () {
      return 0;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead, call <code>pointsLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  pointsLength: {
    get: function () {
      return 0;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead call <code>trianglesLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  trianglesLength: {
    get: function () {
      return 0;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead call <code>geometryByteLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  geometryByteLength: {
    get: function () {
      return 0;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.   <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead call <code>texturesByteLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  texturesByteLength: {
    get: function () {
      return 0;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
   * always returns <code>0</code>.  Instead call <code>batchTableByteLength</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  batchTableByteLength: {
    get: function () {
      return 0;
    },
  },
 
  innerContents: {
    get: function () {
      return this._contents;
    },
  },
 
  readyPromise: {
    get: function () {
      return this._readyPromise.promise;
    },
  },
 
  tileset: {
    get: function () {
      return this._tileset;
    },
  },
 
  tile: {
    get: function () {
      return this._tile;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface.
   * Unlike other content types, <code>Multiple3DTileContent</code> does not
   * have a single URL, so this returns undefined.
   * @memberof Multiple3DTileContent.prototype
   *
   * @type {String}
   * @readonly
   * @private
   */
  url: {
    get: function () {
      return undefined;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface. <code>Multiple3DTileContent</code>
   * always returns <code>undefined</code>.  Instead call <code>batchTable</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  batchTable: {
    get: function () {
      return undefined;
    },
  },
 
  /**
   * Part of the {@link Cesium3DTileContent} interface. <code>Multiple3DTileContent</code>
   * always returns <code>undefined</code>.  Instead call <code>groupMetadata</code> for a specific inner content.
   * @memberof Multiple3DTileContent.prototype
   * @private
   */
  groupMetadata: {
    get: function () {
      return undefined;
    },
    set: function () {
      throw new DeveloperError(
        "Multiple3DTileContent cannot have group metadata"
      );
    },
  },
 
  /**
   * Get an array of the inner content URLs, regardless of whether they've
   * been fetched or not. This is intended for use with
   * {@link Cesium3DTileset#debugShowUrl}.
   * @memberof Multiple3DTileContent.prototype
   *
   * @type {String[]}
   * @readonly
   * @private
   */
  innerContentUrls: {
    get: function () {
      return this._innerContentHeaders.map(function (contentHeader) {
        return contentHeader.uri;
      });
    },
  },
 
  /**
   * A promise that resolves when all of the inner contents have been fetched.
   * This promise is undefined until the first frame where all array buffer
   * requests have been scheduled.
   * @memberof Multiple3DTileContent.prototype
   *
   * @type {Promise}
   * @private
   */
  contentsFetchedPromise: {
    get: function () {
      if (defined(this._contentsFetchedPromise)) {
        return this._contentsFetchedPromise.promise;
      }
 
      return undefined;
    },
  },
});
 
function updatePendingRequests(multipleContents, deltaRequestCount) {
  multipleContents._requestsInFlight += deltaRequestCount;
  multipleContents.tileset.statistics.numberOfPendingRequests += deltaRequestCount;
}
 
function cancelPendingRequests(multipleContents, originalContentState) {
  multipleContents._cancelCount++;
 
  // reset the tile's content state to try again later.
  multipleContents._tile._contentState = originalContentState;
 
  multipleContents.tileset.statistics.numberOfPendingRequests -=
    multipleContents._requestsInFlight;
  multipleContents._requestsInFlight = 0;
 
  // Discard the request promises.
  var contentCount = multipleContents._innerContentHeaders.length;
  multipleContents._arrayFetchPromises = new Array(contentCount);
}
 
/**
 * Request the inner contents of this <code>Multiple3DTileContent</code>. This must be called once a frame until
 * {@link Multiple3DTileContent#contentsFetchedPromise} is defined. This promise
 * becomes available as soon as all requests are scheduled.
 * <p>
 * This method also updates the tile statistics' pending request count if the
 * requests are successfully scheduled.
 * </p>
 *
 * @return {Number} The number of attempted requests that were unable to be scheduled.
 * @private
 */
Multiple3DTileContent.prototype.requestInnerContents = function () {
  // It's possible for these promises to leak content array buffers if the
  // camera moves before they all are scheduled. To prevent this leak, check
  // if we can schedule all the requests at once. If not, no requests are
  // scheduled
  if (!canScheduleAllRequests(this._serverKeys)) {
    return this._serverKeys.length;
  }
 
  var contentHeaders = this._innerContentHeaders;
  updatePendingRequests(this, contentHeaders.length);
 
  for (var i = 0; i < contentHeaders.length; i++) {
    // The cancel count is needed to avoid a race condition where a content
    // is canceled multiple times.
    this._arrayFetchPromises[i] = requestInnerContent(
      this,
      i,
      this._cancelCount,
      this._tile._contentState
    );
  }
 
  // set up the deferred promise the first time requestInnerContent()
  // is called.
  if (!defined(this._contentsFetchedPromise)) {
    this._contentsFetchedPromise = when.defer();
  }
 
  createInnerContents(this);
  return 0;
};
 
/**
 * Check if all requests for inner contents can be scheduled at once. This is slower, but it avoids a potential memory leak.
 * @param {String[]} serverKeys The server keys for all of the inner contents
 * @return {Boolean} True if the request scheduler has enough open slots for all inner contents
 * @private
 */
function canScheduleAllRequests(serverKeys) {
  var requestCountsByServer = {};
  for (var i = 0; i < serverKeys.length; i++) {
    var serverKey = serverKeys[i];
    if (defined(requestCountsByServer[serverKey])) {
      requestCountsByServer[serverKey]++;
    } else {
      requestCountsByServer[serverKey] = 1;
    }
  }
 
  for (var key in requestCountsByServer) {
    if (
      requestCountsByServer.hasOwnProperty(key) &&
      !RequestScheduler.serverHasOpenSlots(key, requestCountsByServer[key])
    ) {
      return false;
    }
  }
  return RequestScheduler.heapHasOpenSlots(serverKeys.length);
}
 
function requestInnerContent(
  multipleContents,
  index,
  originalCancelCount,
  originalContentState
) {
  // it is important to clone here. The fetchArrayBuffer() below here uses
  // throttling, but other uses of the resources do not.
  var contentResource = multipleContents._innerContentResources[index].clone();
  var tile = multipleContents.tile;
 
  // Always create a new request. If the tile gets canceled, this
  // avoids getting stuck in the canceled state.
  var priorityFunction = function () {
    return tile._priority;
  };
  var serverKey = multipleContents._serverKeys[index];
  var request = new Request({
    throttle: true,
    throttleByServer: true,
    type: RequestType.TILES3D,
    priorityFunction: priorityFunction,
    serverKey: serverKey,
  });
  contentResource.request = request;
  multipleContents._requests[index] = request;
 
  return contentResource
    .fetchArrayBuffer()
    .then(function (arrayBuffer) {
      // Short circuit if another inner content was canceled.
      if (originalCancelCount < multipleContents._cancelCount) {
        return undefined;
      }
 
      updatePendingRequests(multipleContents, -1);
      return arrayBuffer;
    })
    .otherwise(function (error) {
      // Short circuit if another inner content was canceled.
      if (originalCancelCount < multipleContents._cancelCount) {
        return undefined;
      }
 
      if (contentResource.request.state === RequestState.CANCELLED) {
        cancelPendingRequests(multipleContents, originalContentState);
        return undefined;
      }
 
      updatePendingRequests(multipleContents, -1);
      handleInnerContentFailed(multipleContents, index, error);
      return undefined;
    });
}
 
function createInnerContents(multipleContents) {
  var originalCancelCount = multipleContents._cancelCount;
  when
    .all(multipleContents._arrayFetchPromises)
    .then(function (arrayBuffers) {
      if (originalCancelCount < multipleContents._cancelCount) {
        return undefined;
      }
 
      return arrayBuffers.map(function (arrayBuffer, i) {
        if (!defined(arrayBuffer)) {
          // Content was not fetched. The error was handled in
          // the fetch promise
          return undefined;
        }
 
        try {
          return createInnerContent(multipleContents, arrayBuffer, i);
        } catch (error) {
          handleInnerContentFailed(multipleContents, i, error);
          return undefined;
        }
      });
    })
    .then(function (contents) {
      if (!defined(contents)) {
        // request was canceled. resolve the promise (Cesium3DTile will
        // detect that the the content was canceled), then discard the promise
        // so a new one can be created
        if (defined(multipleContents._contentsFetchedPromise)) {
          multipleContents._contentsFetchedPromise.resolve();
          multipleContents._contentsFetchedPromise = undefined;
        }
        return;
      }
 
      multipleContents._contents = contents.filter(defined);
      awaitReadyPromises(multipleContents);
 
      if (defined(multipleContents._contentsFetchedPromise)) {
        multipleContents._contentsFetchedPromise.resolve();
      }
    })
    .otherwise(function (error) {
      if (defined(multipleContents._contentsFetchedPromise)) {
        multipleContents._contentsFetchedPromise.reject(error);
      }
    });
}
 
function createInnerContent(multipleContents, arrayBuffer, index) {
  var preprocessed = preprocess3DTileContent(arrayBuffer);
 
  if (preprocessed.contentType === Cesium3DTileContentType.EXTERNAL_TILESET) {
    throw new RuntimeError(
      "External tilesets are disallowed inside the 3DTILES_multiple_contents extension"
    );
  }
 
  multipleContents._disableSkipLevelOfDetail =
    multipleContents._disableSkipLevelOfDetail ||
    preprocessed.contentType === Cesium3DTileContentType.GEOMETRY ||
    preprocessed.contentType === Cesium3DTileContentType.VECTOR;
 
  var tileset = multipleContents._tileset;
  var resource = multipleContents._innerContentResources[index];
 
  var content;
  var contentFactory = Cesium3DTileContentFactory[preprocessed.contentType];
  if (defined(preprocessed.binaryPayload)) {
    content = contentFactory(
      tileset,
      multipleContents._tile,
      resource,
      preprocessed.binaryPayload.buffer,
      0
    );
  } else {
    // JSON formats
    content = contentFactory(
      tileset,
      multipleContents._tile,
      resource,
      preprocessed.jsonPayload
    );
  }
 
  var contentHeader = multipleContents._innerContentHeaders[index];
  content.groupMetadata = findGroupMetadata(tileset, contentHeader);
  return content;
}
 
function awaitReadyPromises(multipleContents) {
  var readyPromises = multipleContents._contents.map(function (content) {
    return content.readyPromise;
  });
 
  when
    .all(readyPromises)
    .then(function () {
      multipleContents._readyPromise.resolve(multipleContents);
    })
    .otherwise(function (error) {
      multipleContents._readyPromise.reject(error);
    });
}
 
function handleInnerContentFailed(multipleContents, index, error) {
  var tileset = multipleContents._tileset;
  var url = multipleContents._innerContentResources[index].url;
  var message = defined(error.message) ? error.message : error.toString();
  if (tileset.tileFailed.numberOfListeners > 0) {
    tileset.tileFailed.raiseEvent({
      url: url,
      message: message,
    });
  } else {
    console.log("A content failed to load: " + url);
    console.log("Error: " + message);
  }
}
 
/**
 * Cancel all requests for inner contents. This is called by the tile
 * when a tile goes out of view.
 *
 * @private
 */
Multiple3DTileContent.prototype.cancelRequests = function () {
  for (var i = 0; i < this._requests.length; i++) {
    var request = this._requests[i];
    if (defined(request)) {
      request.cancel();
    }
  }
};
 
/**
 * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
 * always returns <code>false</code>.  Instead call <code>hasProperty</code> for a specific inner content
 * @private
 */
Multiple3DTileContent.prototype.hasProperty = function (batchId, name) {
  return false;
};
 
/**
 * Part of the {@link Cesium3DTileContent} interface.  <code>Multiple3DTileContent</code>
 * always returns <code>undefined</code>.  Instead call <code>getFeature</code> for a specific inner content
 * @private
 */
Multiple3DTileContent.prototype.getFeature = function (batchId) {
  return undefined;
};
 
Multiple3DTileContent.prototype.applyDebugSettings = function (enabled, color) {
  var contents = this._contents;
  var length = contents.length;
  for (var i = 0; i < length; ++i) {
    contents[i].applyDebugSettings(enabled, color);
  }
};
 
Multiple3DTileContent.prototype.applyStyle = function (style) {
  var contents = this._contents;
  var length = contents.length;
  for (var i = 0; i < length; ++i) {
    contents[i].applyStyle(style);
  }
};
 
Multiple3DTileContent.prototype.update = function (tileset, frameState) {
  var contents = this._contents;
  var length = contents.length;
  for (var i = 0; i < length; ++i) {
    contents[i].update(tileset, frameState);
  }
};
 
Multiple3DTileContent.prototype.isDestroyed = function () {
  return false;
};
 
Multiple3DTileContent.prototype.destroy = function () {
  var contents = this._contents;
  var length = contents.length;
  for (var i = 0; i < length; ++i) {
    contents[i].destroy();
  }
  return destroyObject(this);
};