@spacexr/3d-tiles-runtime 0.0.0-stage → 0.1.0

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 (78) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/chunk-AI6NWGCA.js +316 -0
  4. package/dist/chunk-AI6NWGCA.js.map +1 -0
  5. package/dist/chunk-G7YVZYMR.js +24 -0
  6. package/dist/chunk-G7YVZYMR.js.map +1 -0
  7. package/dist/chunk-PJIVVIOF.js +205 -0
  8. package/dist/chunk-PJIVVIOF.js.map +1 -0
  9. package/dist/chunk-Q2AL6LWU.js +3 -0
  10. package/dist/chunk-Q2AL6LWU.js.map +1 -0
  11. package/dist/chunk-Q35HKP5V.js +249 -0
  12. package/dist/chunk-Q35HKP5V.js.map +1 -0
  13. package/dist/chunk-URZDM4BH.js +488 -0
  14. package/dist/chunk-URZDM4BH.js.map +1 -0
  15. package/dist/implicit/index.d.ts +64 -0
  16. package/dist/implicit/index.js +4 -0
  17. package/dist/implicit/index.js.map +1 -0
  18. package/dist/index-CNnPRQZc.d.ts +350 -0
  19. package/dist/index.d.ts +713 -0
  20. package/dist/index.js +3074 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/metadata/index.d.ts +12 -0
  23. package/dist/metadata/index.js +3 -0
  24. package/dist/metadata/index.js.map +1 -0
  25. package/dist/pipeline/index.d.ts +5 -0
  26. package/dist/pipeline/index.js +3 -0
  27. package/dist/pipeline/index.js.map +1 -0
  28. package/dist/ports/index.d.ts +62 -0
  29. package/dist/ports/index.js +4 -0
  30. package/dist/ports/index.js.map +1 -0
  31. package/dist/resource-DH72MRMN.d.ts +34 -0
  32. package/dist/spatial/index.d.ts +402 -0
  33. package/dist/spatial/index.js +3 -0
  34. package/dist/spatial/index.js.map +1 -0
  35. package/dist/spatial-3IDPbyv4.d.ts +28 -0
  36. package/dist/types-Dn5i8Uqg.d.ts +78 -0
  37. package/dist/types-ri64XfSE.d.ts +237 -0
  38. package/package.json +102 -5
  39. package/src/implicit/availability.ts +55 -0
  40. package/src/implicit/coordinates.ts +193 -0
  41. package/src/implicit/dense-subtree-loader.ts +23 -0
  42. package/src/implicit/index.ts +6 -0
  43. package/src/implicit/standard-subtree-loader.ts +71 -0
  44. package/src/implicit/tile-data-source.ts +120 -0
  45. package/src/implicit/types.ts +156 -0
  46. package/src/index.ts +6 -0
  47. package/src/metadata/index.ts +2 -0
  48. package/src/metadata/metadata-resolver.ts +308 -0
  49. package/src/metadata/types.ts +91 -0
  50. package/src/pipeline/index.ts +4 -0
  51. package/src/pipeline/metadata-store.ts +44 -0
  52. package/src/pipeline/ports.ts +62 -0
  53. package/src/pipeline/states.ts +56 -0
  54. package/src/pipeline/tile-3d.ts +165 -0
  55. package/src/ports/camera.ts +12 -0
  56. package/src/ports/content.ts +71 -0
  57. package/src/ports/glyph.ts +13 -0
  58. package/src/ports/index.ts +32 -0
  59. package/src/ports/resource.ts +54 -0
  60. package/src/ports/spatial.ts +28 -0
  61. package/src/ports/telemetry.ts +44 -0
  62. package/src/runtime/cache.ts +112 -0
  63. package/src/runtime/contracts.ts +77 -0
  64. package/src/runtime/events.ts +57 -0
  65. package/src/runtime/hooks.ts +99 -0
  66. package/src/runtime/index.ts +7 -0
  67. package/src/runtime/instrumentation.ts +163 -0
  68. package/src/runtime/priority-scheduler.ts +88 -0
  69. package/src/runtime/quadtree-balance.ts +215 -0
  70. package/src/runtime/tile-runtime.ts +3508 -0
  71. package/src/spatial/bounding-volumes.ts +159 -0
  72. package/src/spatial/ecef-types.ts +110 -0
  73. package/src/spatial/ecef.ts +196 -0
  74. package/src/spatial/index.ts +6 -0
  75. package/src/spatial/utm-bounds.ts +151 -0
  76. package/src/spatial/utm-types.ts +83 -0
  77. package/src/spatial/vertical-scale.ts +125 -0
  78. package/src/spatial/view-metrics.ts +132 -0
package/dist/index.js ADDED
@@ -0,0 +1,3074 @@
1
+ import { expandImplicitTemplate, computeImplicitTile, LoadedSubtreeAvailability, implicitBranchingFactor, implicitChildCoordinates, implicitLocalCoordinates } from './chunk-AI6NWGCA.js';
2
+ export { DenseImplicitSubtreeLoader, FetchByteResourceLoader, ImplicitTilesetDecorator, LoadedSubtreeAvailability, StandardImplicitSubtreeLoader, SubtreeAvailabilityError, computeImplicitTile, expandImplicitTemplate, implicitAvailabilityIndex, implicitBranchingFactor, implicitChildCoordinates, implicitLevelOffset, implicitLocalCoordinates, implicitMortonIndex, subdivideImplicitBoundingVolume } from './chunk-AI6NWGCA.js';
3
+ import './chunk-Q2AL6LWU.js';
4
+ import { StandardUriResolver } from './chunk-G7YVZYMR.js';
5
+ export { StandardUriResolver } from './chunk-G7YVZYMR.js';
6
+ import { MetadataResolver } from './chunk-Q35HKP5V.js';
7
+ export { DEFAULT_METADATA_SCOPE_ORDER, MetadataResolver } from './chunk-Q35HKP5V.js';
8
+ import { RuntimeMetadataStore, NO_METADATA, Tile3DContent, Tile3D } from './chunk-PJIVVIOF.js';
9
+ export { CameraChangeFlags, NO_METADATA, RuntimeMetadataStore, Tile3D, Tile3DContent, TileContentKind, TileMetadataState, TilePresentationState, TileReadinessState, TileRefinementMode, TileSelectionState } from './chunk-PJIVVIOF.js';
10
+ export { EcefSpatialMetric, VerticalScale, boundsFromUtm, defaultHorizontalDatumResolver, describeView, ellipsoidalHeightRange, geodeticVerticalFrame, metresPerPixel, placeVertically, radialVerticalFrame, verticalDisplacement } from './chunk-URZDM4BH.js';
11
+ import { tileAddressKey, TILE_EDGE_NEIGHBORS, TILE_CORNER_NEIGHBORS, tileNeighborAddress, ancestorTileAddress } from '@spacexr/tiles';
12
+
13
+ // src/runtime/cache.ts
14
+ var DEFAULT_RUNTIME_CACHE_OPTIONS = {
15
+ enabled: true,
16
+ maxMaterializedTiles: 4096,
17
+ // The byte budgets bound the memory; entries only bound the bookkeeping of many small contents.
18
+ maxContentEntries: 4096,
19
+ workingSetFactor: 0,
20
+ maxContentCpuBytes: 512 * 1024 * 1024,
21
+ maxContentGpuBytes: 1024 * 1024 * 1024,
22
+ maxSubtreeEntries: 128,
23
+ maxSubtreeBytes: 64 * 1024 * 1024,
24
+ unusedRetentionMilliseconds: 6e4
25
+ };
26
+ function resolveBudget(value, fallback) {
27
+ if (value === void 0) return fallback;
28
+ if (!Number.isFinite(value)) return value > 0 ? Number.POSITIVE_INFINITY : 0;
29
+ return Math.max(0, Math.floor(value));
30
+ }
31
+ function resolveRuntimeCacheOptions(options) {
32
+ if (options === false) return { ...DEFAULT_RUNTIME_CACHE_OPTIONS, enabled: false };
33
+ return {
34
+ enabled: options?.enabled ?? DEFAULT_RUNTIME_CACHE_OPTIONS.enabled,
35
+ maxMaterializedTiles: resolveBudget(options?.maxMaterializedTiles, DEFAULT_RUNTIME_CACHE_OPTIONS.maxMaterializedTiles),
36
+ maxContentEntries: resolveBudget(options?.maxContentEntries, DEFAULT_RUNTIME_CACHE_OPTIONS.maxContentEntries),
37
+ workingSetFactor: resolveBudget(options?.workingSetFactor, DEFAULT_RUNTIME_CACHE_OPTIONS.workingSetFactor),
38
+ maxContentCpuBytes: resolveBudget(options?.maxContentCpuBytes, DEFAULT_RUNTIME_CACHE_OPTIONS.maxContentCpuBytes),
39
+ maxContentGpuBytes: resolveBudget(options?.maxContentGpuBytes, DEFAULT_RUNTIME_CACHE_OPTIONS.maxContentGpuBytes),
40
+ maxSubtreeEntries: resolveBudget(options?.maxSubtreeEntries, DEFAULT_RUNTIME_CACHE_OPTIONS.maxSubtreeEntries),
41
+ maxSubtreeBytes: resolveBudget(options?.maxSubtreeBytes, DEFAULT_RUNTIME_CACHE_OPTIONS.maxSubtreeBytes),
42
+ unusedRetentionMilliseconds: resolveBudget(
43
+ options?.unusedRetentionMilliseconds,
44
+ DEFAULT_RUNTIME_CACHE_OPTIONS.unusedRetentionMilliseconds
45
+ ),
46
+ ...options?.unusedFrameRetention === void 0 ? {} : { unusedFrameRetention: resolveBudget(options.unusedFrameRetention, Number.POSITIVE_INFINITY) }
47
+ };
48
+ }
49
+
50
+ // src/runtime/events.ts
51
+ var RuntimeEventHub = class {
52
+ listeners = /* @__PURE__ */ new Set();
53
+ subscribe(listener) {
54
+ this.listeners.add(listener);
55
+ return () => this.listeners.delete(listener);
56
+ }
57
+ emit(event) {
58
+ for (const listener of this.listeners) listener(event);
59
+ }
60
+ clear() {
61
+ this.listeners.clear();
62
+ }
63
+ };
64
+
65
+ // src/runtime/instrumentation.ts
66
+ var RuntimeInstrumentation = class {
67
+ constructor(options, runtimeId, stateProvider) {
68
+ this.runtimeId = runtimeId;
69
+ this.stateProvider = stateProvider;
70
+ this.collectionEnabled = typeof options === "boolean" ? options : options?.enabled ?? true;
71
+ }
72
+ runtimeId;
73
+ stateProvider;
74
+ collectionEnabled;
75
+ collectionStartedAt = Date.now();
76
+ aggregates = /* @__PURE__ */ new Map();
77
+ listeners = /* @__PURE__ */ new Set();
78
+ get enabled() {
79
+ return this.collectionEnabled;
80
+ }
81
+ get hasSubscribers() {
82
+ return this.listeners.size > 0;
83
+ }
84
+ setEnabled(enabled) {
85
+ this.collectionEnabled = enabled;
86
+ }
87
+ reset() {
88
+ this.aggregates.clear();
89
+ this.collectionStartedAt = Date.now();
90
+ }
91
+ record(metric) {
92
+ if (!this.collectionEnabled) return;
93
+ const aggregate = this.aggregates.get(metric.name);
94
+ if (!aggregate) {
95
+ this.aggregates.set(metric.name, {
96
+ count: 1,
97
+ sum: metric.value,
98
+ min: metric.value,
99
+ max: metric.value,
100
+ latest: metric.value,
101
+ unit: metric.unit
102
+ });
103
+ return;
104
+ }
105
+ aggregate.count++;
106
+ aggregate.sum += metric.value;
107
+ aggregate.min = Math.min(aggregate.min, metric.value);
108
+ aggregate.max = Math.max(aggregate.max, metric.value);
109
+ aggregate.latest = metric.value;
110
+ aggregate.unit = metric.unit;
111
+ }
112
+ snapshot() {
113
+ const metrics = {};
114
+ for (const [name, aggregate] of this.aggregates) metrics[name] = { ...aggregate };
115
+ return {
116
+ runtimeId: this.runtimeId,
117
+ timestamp: Date.now(),
118
+ collectionStartedAt: this.collectionStartedAt,
119
+ ...this.stateProvider(),
120
+ metrics
121
+ };
122
+ }
123
+ subscribe(listener) {
124
+ this.listeners.add(listener);
125
+ return () => this.listeners.delete(listener);
126
+ }
127
+ publish() {
128
+ if (!this.collectionEnabled || this.listeners.size === 0) return;
129
+ const snapshot = this.snapshot();
130
+ for (const listener of this.listeners) {
131
+ try {
132
+ listener(snapshot);
133
+ } catch {
134
+ }
135
+ }
136
+ }
137
+ clear() {
138
+ this.listeners.clear();
139
+ this.aggregates.clear();
140
+ }
141
+ };
142
+ function edgeNeighbor(location, edge) {
143
+ const { address, topology, wrapX } = location;
144
+ return topology ? topology.neighbor(address, edge)?.address : tileNeighborAddress(address, edge, { wrapX });
145
+ }
146
+ function quadtreeTileKey(namespace, address) {
147
+ return `${namespace}${tileAddressKey(address)}`;
148
+ }
149
+ function quadtreeTouches(location, tiles) {
150
+ if (tiles.size === 0) return false;
151
+ const { address, namespace, topology, wrapX } = location;
152
+ for (const position of [...TILE_EDGE_NEIGHBORS, ...TILE_CORNER_NEIGHBORS]) {
153
+ const neighbor = topology ? topology.neighbor(address, position)?.address : tileNeighborAddress(address, position, { wrapX });
154
+ if (!neighbor) continue;
155
+ if (tiles.has(quadtreeTileKey(namespace, neighbor))) return true;
156
+ for (let levels = 1; levels <= neighbor.lod; levels++) {
157
+ if (tiles.has(quadtreeTileKey(namespace, ancestorTileAddress(neighbor, levels)))) return true;
158
+ }
159
+ }
160
+ return false;
161
+ }
162
+ function quadtreeImbalances(displayed, maxLevelDifference = 1) {
163
+ const entries = [...displayed];
164
+ const keys = new Set(entries.map(({ location }) => quadtreeTileKey(location.namespace, location.address)));
165
+ const imbalances = [];
166
+ for (const { location, value } of entries) {
167
+ const { namespace } = location;
168
+ let coarseLod;
169
+ for (const edge of TILE_EDGE_NEIGHBORS) {
170
+ const neighbor = edgeNeighbor(location, edge);
171
+ if (!neighbor) continue;
172
+ for (let levels = maxLevelDifference + 1; levels <= neighbor.lod; levels++) {
173
+ const ancestor = ancestorTileAddress(neighbor, levels);
174
+ if (!keys.has(quadtreeTileKey(namespace, ancestor))) continue;
175
+ coarseLod = Math.min(coarseLod ?? ancestor.lod, ancestor.lod);
176
+ break;
177
+ }
178
+ }
179
+ if (coarseLod !== void 0) imbalances.push({ fine: value, coarseLod });
180
+ }
181
+ return imbalances;
182
+ }
183
+ function quadtreeBalanceRefinements(displayed, maxLevelDifference = 1) {
184
+ const refinements = /* @__PURE__ */ new Set();
185
+ for (const location of displayed) {
186
+ const { namespace, address } = location;
187
+ if (address.lod <= maxLevelDifference) continue;
188
+ for (const edge of TILE_EDGE_NEIGHBORS) {
189
+ const neighbor = edgeNeighbor(location, edge);
190
+ if (!neighbor) continue;
191
+ for (let levels = maxLevelDifference + 1; levels <= neighbor.lod; levels++) {
192
+ const key = quadtreeTileKey(namespace, ancestorTileAddress(neighbor, levels));
193
+ if (refinements.has(key)) break;
194
+ refinements.add(key);
195
+ }
196
+ }
197
+ }
198
+ return refinements;
199
+ }
200
+ function refineQuadtreeCut(displayed, refine, blocked, maxLevelDifference = 1) {
201
+ const leaves = /* @__PURE__ */ new Map();
202
+ const queue = [];
203
+ const unavailable = /* @__PURE__ */ new Set();
204
+ const origins = /* @__PURE__ */ new Map();
205
+ const keyOf = ({ location }) => quadtreeTileKey(location.namespace, location.address);
206
+ for (const tile of displayed) {
207
+ leaves.set(keyOf(tile), tile);
208
+ queue.push(tile);
209
+ origins.set(tile, [tile]);
210
+ }
211
+ const involved = (fine, coarse) => [
212
+ .../* @__PURE__ */ new Set([...origins.get(fine), ...origins.get(coarse)])
213
+ ];
214
+ const covering = (namespace, address) => {
215
+ for (let levels = 0; levels <= address.lod; levels++) {
216
+ const tile = leaves.get(quadtreeTileKey(namespace, levels === 0 ? address : ancestorTileAddress(address, levels)));
217
+ if (tile) return tile;
218
+ }
219
+ return void 0;
220
+ };
221
+ while (queue.length > 0) {
222
+ const fine = queue.pop();
223
+ if (leaves.get(keyOf(fine)) !== fine) continue;
224
+ let coarse;
225
+ for (const edge of TILE_EDGE_NEIGHBORS) {
226
+ const neighbor = edgeNeighbor(fine.location, edge);
227
+ if (!neighbor) continue;
228
+ const other = covering(fine.location.namespace, neighbor);
229
+ if (other && other.location.address.lod < fine.location.address.lod - maxLevelDifference) {
230
+ coarse = other;
231
+ break;
232
+ }
233
+ }
234
+ if (!coarse) continue;
235
+ if (unavailable.has(keyOf(coarse))) {
236
+ blocked?.(involved(fine, coarse));
237
+ continue;
238
+ }
239
+ const front = refine(coarse);
240
+ if (!front) {
241
+ unavailable.add(keyOf(coarse));
242
+ blocked?.(involved(fine, coarse));
243
+ continue;
244
+ }
245
+ const keys = new Set(front.map(keyOf));
246
+ if (keys.size !== front.length) throw new Error("A quadtree refinement front cannot contain duplicate leaves.");
247
+ for (const child of front) {
248
+ const { namespace, address } = child.location;
249
+ const difference = address.lod - coarse.location.address.lod;
250
+ if (difference <= 0 || namespace !== coarse.location.namespace || quadtreeTileKey(namespace, ancestorTileAddress(address, difference)) !== keyOf(coarse))
251
+ throw new Error("A quadtree refinement must return strict descendants of the coarse leaf in its namespace.");
252
+ for (let levels = 1; levels < difference; levels++) {
253
+ if (keys.has(quadtreeTileKey(namespace, ancestorTileAddress(address, levels))))
254
+ throw new Error("A quadtree refinement front cannot overlap itself.");
255
+ }
256
+ }
257
+ leaves.delete(keyOf(coarse));
258
+ const origin = involved(fine, coarse);
259
+ for (const child of front) {
260
+ leaves.set(keyOf(child), child);
261
+ queue.push(child);
262
+ origins.set(child, origin);
263
+ }
264
+ queue.push(fine);
265
+ }
266
+ return unavailable.size === 0 ? [...leaves.values()] : void 0;
267
+ }
268
+
269
+ // src/runtime/priority-scheduler.ts
270
+ var PriorityScheduler = class {
271
+ concurrency;
272
+ queued = /* @__PURE__ */ new Map();
273
+ running = /* @__PURE__ */ new Map();
274
+ idleWaiters = /* @__PURE__ */ new Set();
275
+ order = 0;
276
+ disposed = false;
277
+ constructor(concurrency) {
278
+ this.concurrency = Math.max(1, Math.floor(concurrency));
279
+ }
280
+ get size() {
281
+ return this.queued.size + this.running.size;
282
+ }
283
+ enqueue(key, priority, run) {
284
+ if (this.disposed || this.running.has(key)) return false;
285
+ const existing = this.queued.get(key);
286
+ if (existing) {
287
+ existing.priority = priority;
288
+ return false;
289
+ }
290
+ this.queued.set(key, { key, priority, order: this.order++, run, controller: new AbortController() });
291
+ this.pump();
292
+ return true;
293
+ }
294
+ /** Changes the priority of a task still waiting, up or down. */
295
+ reprioritize(key, priority) {
296
+ const queued = this.queued.get(key);
297
+ if (queued) queued.priority = priority;
298
+ }
299
+ cancel(key) {
300
+ const queued = this.queued.get(key);
301
+ if (queued) {
302
+ queued.controller.abort();
303
+ this.queued.delete(key);
304
+ this.notifyIdle();
305
+ }
306
+ this.running.get(key)?.controller.abort();
307
+ }
308
+ whenIdle() {
309
+ if (this.size === 0) return Promise.resolve();
310
+ return new Promise((resolve) => this.idleWaiters.add(resolve));
311
+ }
312
+ dispose() {
313
+ this.disposed = true;
314
+ for (const task of this.queued.values()) task.controller.abort();
315
+ for (const task of this.running.values()) task.controller.abort();
316
+ this.queued.clear();
317
+ this.notifyIdle();
318
+ }
319
+ pump() {
320
+ while (!this.disposed && this.running.size < this.concurrency && this.queued.size > 0) {
321
+ const next = [...this.queued.values()].sort((left, right) => right.priority - left.priority || left.order - right.order)[0];
322
+ if (!next) return;
323
+ this.queued.delete(next.key);
324
+ this.running.set(next.key, next);
325
+ void next.run(next.controller.signal).catch(() => void 0).finally(() => {
326
+ this.running.delete(next.key);
327
+ this.pump();
328
+ this.notifyIdle();
329
+ });
330
+ }
331
+ }
332
+ notifyIdle() {
333
+ if (this.size !== 0) return;
334
+ for (const resolve of this.idleWaiters) resolve();
335
+ this.idleWaiters.clear();
336
+ }
337
+ };
338
+
339
+ // src/runtime/tile-runtime.ts
340
+ var MAX_BALANCE_PASSES = 32;
341
+ var PRELOAD_PRIORITY_SCALE = 0.25;
342
+ var BALANCE_LOAD_PRIORITY = Number.MAX_SAFE_INTEGER;
343
+ var TileRuntime = class {
344
+ id;
345
+ uri;
346
+ adapter;
347
+ events = new RuntimeEventHub();
348
+ instrumentation;
349
+ metadataStore = new RuntimeMetadataStore();
350
+ selectionStrategy;
351
+ emptyTileRefinement;
352
+ maxScreenSpaceError;
353
+ maxScreenSpaceErrorForDepth;
354
+ refinementHysteresisRatio;
355
+ refinementThresholdScale;
356
+ stableReplacementCut;
357
+ preloadSiblings;
358
+ coarseningDelayMilliseconds;
359
+ /** Since when each refined tile has no longer required its refinement, and the last frame that saw it so. */
360
+ coarseningSince = /* @__PURE__ */ new Map();
361
+ /** When the first delayed coarsening of the last frame expires. */
362
+ nextCoarseningAt;
363
+ /** Priority asked in the current frame for each queued load, whose passes may ask several. */
364
+ queuedPriorities = /* @__PURE__ */ new Map();
365
+ queuedPrioritiesFrame = -1;
366
+ quadtreeBalance;
367
+ /** Keys of the tiles that must refine to keep the quadtree balanced in the current frame. */
368
+ balanceRefinements = /* @__PURE__ */ new Set();
369
+ /**
370
+ * Refinements the balance of the last published cut required, from which the next frame starts: a tile refined by the
371
+ * balance alone stays required from the first pass, instead of starting a coarsening delay that a later pass cancels.
372
+ */
373
+ publishedBalanceRefinements = /* @__PURE__ */ new Set();
374
+ /** Visible selected quadtree tiles of the last traversal, whose neighbours stay active. */
375
+ visibleTiles = /* @__PURE__ */ new Set();
376
+ /** Tiles whose refinement waits in the current frame, because a neighbour cannot follow yet. */
377
+ balanceHolds = /* @__PURE__ */ new Set();
378
+ unbalancedCount = 0;
379
+ maxLoadAttempts;
380
+ cacheOptions;
381
+ cacheCounters = {
382
+ sweeps: 0,
383
+ contentEvictions: 0,
384
+ subtreeEvictions: 0,
385
+ implicitBranchPrunes: 0,
386
+ prunedNodes: 0,
387
+ releasedCpuBytes: 0,
388
+ releasedGpuBytes: 0
389
+ };
390
+ hooks;
391
+ uriResolver;
392
+ metadataResolver = new MetadataResolver();
393
+ scheduler;
394
+ lifecycleController = new AbortController();
395
+ nodes = /* @__PURE__ */ new Map();
396
+ /** Latest invalidation of each stale content, and the failed reloads since. */
397
+ staleContents = /* @__PURE__ */ new Map();
398
+ refreshes = /* @__PURE__ */ new Map();
399
+ /** Ready contents reported as provisional: stale, and reloaded only while their tile is a leaf of the cut. */
400
+ provisionalContents = /* @__PURE__ */ new Set();
401
+ invalidations = 0;
402
+ refiningNodes = /* @__PURE__ */ new Set();
403
+ replacementFrontNodes = /* @__PURE__ */ new Set();
404
+ activeThisFrame = /* @__PURE__ */ new Set();
405
+ selectedAtFrameStart = [];
406
+ baseReplacementBlocked = false;
407
+ rootNode;
408
+ rootDocument;
409
+ cameraSubscription;
410
+ startPromise;
411
+ updateChain = Promise.resolve();
412
+ lastCamera;
413
+ pendingCamera;
414
+ pendingCameraChanges = 0 /* None */;
415
+ currentCameraChanges = 0 /* None */;
416
+ unsubscribeVerticalScale;
417
+ spatialStale = false;
418
+ cameraDirty = false;
419
+ frame = 0;
420
+ /** Start time of the recent frames, oldest first; older frames are beyond the cache retention. */
421
+ frameTimes = /* @__PURE__ */ new Map();
422
+ clock;
423
+ disposed = false;
424
+ refreshNeeded = false;
425
+ constructor(options) {
426
+ this.id = options.id;
427
+ this.uri = options.uri;
428
+ this.adapter = options.adapter;
429
+ if (!options.adapter.content && !options.adapter.activation) {
430
+ throw new Error("A content adapter or a tile activation adapter is required.");
431
+ }
432
+ if (!options.adapter.content && !options.adapter.presentation) {
433
+ throw new Error("A content adapter or a tile presentation adapter is required.");
434
+ }
435
+ this.selectionStrategy = options.selectionStrategy ?? "active";
436
+ if (this.selectionStrategy !== "base" && this.selectionStrategy !== "active") throw new RangeError("Unknown selection strategy.");
437
+ this.emptyTileRefinement = options.emptyTileRefinement ?? "always";
438
+ if (this.emptyTileRefinement !== "always" && this.emptyTileRefinement !== "geometric-error")
439
+ throw new RangeError("Unknown empty tile refinement.");
440
+ this.maxScreenSpaceError = options.maxScreenSpaceError ?? 16;
441
+ this.maxScreenSpaceErrorForDepth = options.maxScreenSpaceErrorForDepth;
442
+ this.refinementHysteresisRatio = options.refinementHysteresisRatio ?? 0.1;
443
+ if (!Number.isFinite(this.refinementHysteresisRatio) || this.refinementHysteresisRatio < 0 || this.refinementHysteresisRatio >= 1) {
444
+ throw new RangeError("refinementHysteresisRatio must be in the interval [0, 1).");
445
+ }
446
+ this.refinementThresholdScale = options.refinementThresholdScale;
447
+ this.stableReplacementCut = options.stableReplacementCut ?? true;
448
+ this.preloadSiblings = options.preloadSiblings ?? true;
449
+ this.coarseningDelayMilliseconds = Math.max(0, options.coarseningDelayMilliseconds ?? 300);
450
+ this.clock = options.clock ?? (() => performance.now());
451
+ this.frameTimes.set(0, this.clock());
452
+ const balance = typeof options.quadtreeBalance === "object" ? options.quadtreeBalance : {};
453
+ const maxLevelDifference = balance.maxLevelDifference ?? 1;
454
+ if (!Number.isInteger(maxLevelDifference) || maxLevelDifference < 1)
455
+ throw new RangeError("quadtreeBalance.maxLevelDifference must be an integer of at least 1.");
456
+ this.quadtreeBalance = options.quadtreeBalance ? {
457
+ wrapX: balance.wrapX === true,
458
+ maxLevelDifference,
459
+ ...balance.topology ? { topology: balance.topology } : {}
460
+ } : void 0;
461
+ this.maxLoadAttempts = Math.max(1, Math.floor(options.maxLoadAttempts ?? 3));
462
+ this.cacheOptions = resolveRuntimeCacheOptions(options.cache);
463
+ this.hooks = options.hooks ?? [];
464
+ this.uriResolver = options.adapter.uri ?? new StandardUriResolver();
465
+ this.scheduler = new PriorityScheduler(options.maxConcurrentLoads ?? 4);
466
+ this.instrumentation = new RuntimeInstrumentation(options.instrumentation, this.id, () => this.collectStatistics());
467
+ this.unsubscribeVerticalScale = options.verticalScale?.subscribe(() => {
468
+ this.spatialStale = true;
469
+ this.refreshNeeded = true;
470
+ });
471
+ }
472
+ get root() {
473
+ return this.rootNode;
474
+ }
475
+ get document() {
476
+ return this.rootDocument;
477
+ }
478
+ get pendingLoads() {
479
+ return this.scheduler.size;
480
+ }
481
+ /** True when settled asynchronous state still needs a caller-driven frame. */
482
+ get hasPendingWork() {
483
+ return this.refreshNeeded || this.cameraDirty || this.nextCoarseningAt !== void 0 && this.clock() >= this.nextCoarseningAt;
484
+ }
485
+ get selectedTiles() {
486
+ return [...this.nodes.values()].filter((node) => node.selected);
487
+ }
488
+ get cameraChanges() {
489
+ return this.currentCameraChanges;
490
+ }
491
+ /** Immediately applies cache budgets. With force=true, every inactive cache entry is released. */
492
+ trimCache(force = false) {
493
+ const operation = this.updateChain.then(async () => {
494
+ if (this.disposed) return;
495
+ await this.sweepCache(force);
496
+ this.instrumentation.publish();
497
+ });
498
+ this.updateChain = operation.then(
499
+ () => void 0,
500
+ () => void 0
501
+ );
502
+ return operation;
503
+ }
504
+ /**
505
+ * Marks the loaded contents of the tiles a predicate selects as stale, such as the tiles whose region crosses an
506
+ * area whose data changed, and reloads them. Each keeps its current handle presented until its reload is ready:
507
+ * the swap happens between two frames, so the view never shows a hole. Stale contents reload while their tile is
508
+ * in the working set; the others reload when it comes back, and meanwhile still serve as they are.
509
+ *
510
+ * The reload goes through the activation adapter, with `refresh` set, or through the legacy content adapter.
511
+ *
512
+ * @returns The number of tiles invalidated.
513
+ */
514
+ invalidate(predicate) {
515
+ const operation = this.updateChain.then(() => {
516
+ if (this.disposed) return 0;
517
+ const serial = ++this.invalidations;
518
+ let tiles = 0;
519
+ for (const node of this.nodes.values()) {
520
+ const contents = node.contents.filter(
521
+ (content) => (content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */) && (content.status === 3 /* Ready */ || content.status === 2 /* Preparing */)
522
+ );
523
+ if (contents.length === 0 || !predicate(node)) continue;
524
+ tiles++;
525
+ for (const content of contents) {
526
+ content.stale = true;
527
+ this.staleContents.set(content, { serial, failures: 0 });
528
+ this.events.emit({ type: "content-state", tile: node, content });
529
+ }
530
+ }
531
+ if (tiles > 0) this.markDirty();
532
+ return tiles;
533
+ });
534
+ this.updateChain = operation.then(
535
+ () => void 0,
536
+ () => void 0
537
+ );
538
+ return operation;
539
+ }
540
+ async start() {
541
+ if (this.disposed) throw new Error("The runtime has been disposed.");
542
+ if (this.startPromise) return this.startPromise;
543
+ this.startPromise = this.initializeRoot();
544
+ return this.startPromise;
545
+ }
546
+ update(camera) {
547
+ this.pendingCamera = void 0;
548
+ this.pendingCameraChanges = 0 /* None */;
549
+ this.cameraDirty = false;
550
+ return this.enqueueUpdate(camera, 31 /* All */);
551
+ }
552
+ enqueueUpdate(camera, changes) {
553
+ const operation = this.updateChain.then(async () => {
554
+ await this.start();
555
+ this.currentCameraChanges = changes;
556
+ if (this.spatialStale) this.refreshSpatialStates();
557
+ try {
558
+ return await this.performUpdate(camera);
559
+ } finally {
560
+ this.currentCameraChanges = 0 /* None */;
561
+ }
562
+ });
563
+ this.updateChain = operation.then(
564
+ () => void 0,
565
+ () => void 0
566
+ );
567
+ return operation;
568
+ }
569
+ /** Asks for one more frame with the latest camera, when something the selection reads has changed. */
570
+ requestFrame() {
571
+ this.markDirty();
572
+ }
573
+ /** Stores the latest immutable camera frame without starting a traversal. */
574
+ onCameraChanged(camera, changes = 31 /* All */) {
575
+ this.pendingCamera = camera;
576
+ this.pendingCameraChanges |= changes;
577
+ this.cameraDirty = true;
578
+ }
579
+ /** Consumes the latest camera snapshot and runs at most one serialized pipeline frame. */
580
+ processFrame() {
581
+ const camera = this.pendingCamera ?? this.lastCamera;
582
+ if (camera === void 0) throw new Error("A camera frame must be provided before processing the runtime pipeline.");
583
+ const changes = this.pendingCameraChanges;
584
+ this.pendingCamera = void 0;
585
+ this.pendingCameraChanges = 0 /* None */;
586
+ this.cameraDirty = false;
587
+ return this.enqueueUpdate(camera, changes);
588
+ }
589
+ async whenIdle() {
590
+ while (!this.disposed) {
591
+ await this.scheduler.whenIdle();
592
+ await this.updateChain;
593
+ if (this.scheduler.size > 0) continue;
594
+ const camera = this.lastCamera;
595
+ if (!this.refreshNeeded || camera === void 0) return;
596
+ await this.update(camera);
597
+ }
598
+ }
599
+ async dispose() {
600
+ if (this.disposed) return;
601
+ this.disposed = true;
602
+ this.cameraSubscription?.unsubscribe();
603
+ this.cameraSubscription = void 0;
604
+ this.unsubscribeVerticalScale?.();
605
+ this.lifecycleController.abort();
606
+ this.scheduler.dispose();
607
+ await this.updateChain;
608
+ const selected = [...this.nodes.values()].filter((node) => node.selected).sort((left, right) => right.depth - left.depth);
609
+ for (const node of selected) await this.deactivateNode(node);
610
+ for (const node of [...this.nodes.values()].sort((left, right) => right.depth - left.depth)) await this.disposeNodeContent(node);
611
+ this.refreshes.clear();
612
+ this.staleContents.clear();
613
+ this.provisionalContents.clear();
614
+ this.nodes.clear();
615
+ this.refiningNodes.clear();
616
+ this.coarseningSince.clear();
617
+ this.replacementFrontNodes.clear();
618
+ this.selectedAtFrameStart = [];
619
+ this.activeThisFrame.clear();
620
+ this.metadataStore.clear();
621
+ this.events.clear();
622
+ this.instrumentation.clear();
623
+ }
624
+ async performUpdate(camera) {
625
+ if (this.disposed) throw new Error("The runtime has been disposed.");
626
+ const startedAt = this.startTiming();
627
+ const root = this.rootNode;
628
+ if (!root) throw new Error("The root tileset is not initialized.");
629
+ this.lastCamera = camera;
630
+ this.refreshNeeded = false;
631
+ const currentFrame = ++this.frame;
632
+ this.recordFrameTime(currentFrame);
633
+ const beforeContext = {
634
+ runtimeId: this.id,
635
+ frame: currentFrame,
636
+ camera
637
+ };
638
+ await this.invokeHooks("beforeFrame", (hook) => hook.beforeFrame?.(beforeContext));
639
+ await this.applyRefreshes();
640
+ const desired = /* @__PURE__ */ new Map();
641
+ const requested = [];
642
+ const refiningAtFrameStart = new Set(this.refiningNodes);
643
+ this.nextCoarseningAt = void 0;
644
+ this.selectedAtFrameStart = [...this.nodes.values()].filter((node) => node.selected);
645
+ if (this.selectionStrategy === "base") {
646
+ this.baseReplacementBlocked = false;
647
+ this.replacementFrontNodes.clear();
648
+ this.activeThisFrame.clear();
649
+ for (const node of this.nodes.values()) {
650
+ node.visible = false;
651
+ node.active = false;
652
+ }
653
+ this.visitBase(root, camera, desired, requested);
654
+ if (this.baseReplacementBlocked) this.retainBaseCut(camera, desired, requested);
655
+ this.closeBaseQuadtreeCut(camera, desired, requested);
656
+ this.protectBaseCoverageAncestors(desired, requested);
657
+ this.refiningNodes.clear();
658
+ for (const node of desired.values()) {
659
+ for (let parent = node.parent; parent; parent = parent.parent) this.refiningNodes.add(parent.id);
660
+ }
661
+ } else {
662
+ this.balanceRefinements = new Set(this.publishedBalanceRefinements);
663
+ this.balanceHolds.clear();
664
+ this.replacementFrontNodes.clear();
665
+ this.activeThisFrame.clear();
666
+ for (let pass = 1; ; pass++) {
667
+ desired.clear();
668
+ requested.length = 0;
669
+ this.nextCoarseningAt = void 0;
670
+ for (const node of this.nodes.values()) {
671
+ node.visible = false;
672
+ node.active = false;
673
+ }
674
+ this.visit(root, camera, desired, requested);
675
+ if (pass >= MAX_BALANCE_PASSES) break;
676
+ if (this.extendQuadtreeBalance(desired)) continue;
677
+ if (!this.holdUnbalancedRefinements(desired)) break;
678
+ }
679
+ this.updateVisibleTiles(desired);
680
+ this.publishedBalanceRefinements = this.quadtreeBalance ? quadtreeBalanceRefinements(this.visibleQuadtreeLocations(desired), this.quadtreeBalance.maxLevelDifference) : /* @__PURE__ */ new Set();
681
+ }
682
+ await this.deactivatePipelineTilesOutsideWorkingSet();
683
+ const entering = [...desired.values()].filter((node) => !node.selected).sort((left, right) => left.depth - right.depth);
684
+ const staying = [...desired.values()].filter((node) => node.selected);
685
+ for (const node of [...entering, ...staying]) await this.activateNode(node);
686
+ const leaving = [...this.nodes.values()].filter((node) => node.selected && !desired.has(node.id)).sort((left, right) => right.depth - left.depth);
687
+ for (const node of leaving) await this.deactivateNode(node);
688
+ this.recordCutChanges(refiningAtFrameStart, entering.length, leaving.length);
689
+ await this.sweepCache();
690
+ const unbalanced = this.quadtreeBalance ? this.findImbalances(desired).map(({ fine, coarseLod }) => ({ tile: fine, coarseLod })) : [];
691
+ this.unbalancedCount = unbalanced.length;
692
+ const result = {
693
+ frame: currentFrame,
694
+ selected: [...desired.values()],
695
+ requested,
696
+ pendingLoads: this.scheduler.size,
697
+ unbalanced
698
+ };
699
+ if (unbalanced.length > 0) this.events.emit({ type: "quadtree-imbalance", frame: currentFrame, imbalances: unbalanced });
700
+ this.events.emit({ type: "frame", result });
701
+ this.recordMetric({
702
+ name: "frame",
703
+ value: 1,
704
+ unit: "count",
705
+ tags: { runtime: this.id, requested: requested.length, pending: this.scheduler.size }
706
+ });
707
+ this.recordMetric({
708
+ name: "frame.selected",
709
+ value: desired.size,
710
+ unit: "count",
711
+ tags: { runtime: this.id }
712
+ });
713
+ const afterContext = {
714
+ ...beforeContext,
715
+ result
716
+ };
717
+ await this.invokeHooks("afterFrame", (hook) => hook.afterFrame?.(afterContext));
718
+ this.recordDuration("frame.duration", startedAt, { runtime: this.id });
719
+ this.instrumentation.publish();
720
+ return result;
721
+ }
722
+ /** Visible traversal shared by explicit tiles, implicit tiles and both rendering backends. */
723
+ visitBase(node, camera, desired, requested) {
724
+ if (this.hasSelectedReplacementAncestor(node, desired)) return;
725
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
726
+ node.active = node.visible;
727
+ if (!node.visible) {
728
+ this.preloadBasePeriphery(node, camera, requested);
729
+ return;
730
+ }
731
+ this.touchBaseTile(node, camera);
732
+ const potential = node.contents.some(
733
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
734
+ );
735
+ if (potential) {
736
+ this.replacementFrontNodes.add(node.id);
737
+ this.requestNodeContents(node, node.screenSpaceError, requested);
738
+ }
739
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
740
+ this.requestImplicitSubtree(node, node.screenSpaceError);
741
+ this.selectBaseCoverage(node, camera, desired, requested);
742
+ return;
743
+ }
744
+ const wasRefining = this.refiningNodes.has(node.id);
745
+ const effective = this.refinementThreshold(node, wasRefining);
746
+ const required = !potential && !this.obeysGeometricError(node) || node.screenSpaceError > effective || this.isBalanceRefinementRequired(node);
747
+ const delayed = this.isCoarseningDelayed(node, wasRefining, required);
748
+ if (required || delayed) this.materializeImplicitChildren(node);
749
+ const refining = (required || delayed) && node.children.length > 0;
750
+ this.setRefinementState(node, refining);
751
+ if (!refining) {
752
+ if (!potential) return;
753
+ this.selectBaseCoverage(node, camera, desired, requested);
754
+ this.requestRefresh(node, node.screenSpaceError, true);
755
+ return;
756
+ }
757
+ this.cancelProvisionalRefresh(node);
758
+ if (node.refinementMode === 0 /* Add */) {
759
+ if (this.isNodePresentationReady(node)) this.selectBaseTile(node, desired, requested);
760
+ for (const child of node.children) this.visitBase(child, camera, desired, requested);
761
+ return;
762
+ }
763
+ const ready = node.children.map((child) => this.collectBaseReplacementFront(child, camera, requested, node.screenSpaceError)).every(Boolean);
764
+ if (!ready) {
765
+ this.selectBaseCoverage(node, camera, desired, requested, true);
766
+ return;
767
+ }
768
+ for (const child of node.children) this.visitBase(child, camera, desired, requested);
769
+ }
770
+ /**
771
+ * Loads a tile of the periphery of the view, and its descendants down to the threshold, without selecting them: a
772
+ * place that enters the view then finds its tile ready.
773
+ */
774
+ preloadBasePeriphery(node, camera, requested) {
775
+ if (this.adapter.spatial.isInPeriphery?.(node.spatial, camera) !== true) return;
776
+ node.active = true;
777
+ this.touchBaseTile(node, camera);
778
+ const priority = -1 / (1 + node.screenSpaceError);
779
+ const potential = node.contents.some(
780
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
781
+ );
782
+ if (potential) this.requestNodeContents(node, priority, requested);
783
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
784
+ this.requestImplicitSubtree(node, priority);
785
+ return;
786
+ }
787
+ const threshold = this.maxScreenSpaceErrorForDepth?.(node.depth, this.maxScreenSpaceError) ?? this.maxScreenSpaceError;
788
+ if ((potential || this.obeysGeometricError(node)) && node.screenSpaceError <= threshold * Math.max(1, this.refinementThresholdScale?.() ?? 1))
789
+ return;
790
+ this.materializeImplicitChildren(node);
791
+ for (const child of node.children) this.preloadBasePeriphery(child, camera, requested);
792
+ }
793
+ touchBaseTile(node, camera) {
794
+ node.lastTouchedFrame = this.frame;
795
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
796
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
797
+ camera,
798
+ spatial: node.spatial,
799
+ tile: node.source,
800
+ depth: node.depth
801
+ });
802
+ }
803
+ collectBaseReplacementFront(node, camera, requested, priorityFloor) {
804
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
805
+ node.active = node.visible;
806
+ this.touchBaseTile(node, camera);
807
+ const priority = Math.max(node.screenSpaceError, priorityFloor);
808
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
809
+ this.requestImplicitSubtree(node, priority);
810
+ return false;
811
+ }
812
+ const potential = node.contents.some(
813
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
814
+ );
815
+ if (potential) {
816
+ this.replacementFrontNodes.add(node.id);
817
+ this.requestNodeContents(node, priority, requested);
818
+ return this.isNodePresentationReady(node);
819
+ }
820
+ if (this.isSatisfiedEmpty(node)) return true;
821
+ this.materializeImplicitChildren(node);
822
+ return node.children.map((child) => this.collectBaseReplacementFront(child, camera, requested, priority)).every(Boolean);
823
+ }
824
+ hasSelectedReplacementAncestor(node, desired) {
825
+ for (let parent = node.parent; parent; parent = parent.parent) {
826
+ if (parent.refinementMode === 0 /* Add */) return false;
827
+ if (desired.has(parent.id)) return true;
828
+ }
829
+ return false;
830
+ }
831
+ selectBaseTile(node, desired, requested) {
832
+ if (this.hasSelectedReplacementAncestor(node, desired)) return;
833
+ if (node.refinementMode === 1 /* Replace */) {
834
+ for (const tile of desired.values()) if (this.isDescendantOf(tile, node)) desired.delete(tile.id);
835
+ }
836
+ this.selectNode(node, desired, requested);
837
+ }
838
+ selectBaseCoverage(node, camera, desired, requested, retainRefinedCoverage = false) {
839
+ const ready = this.isNodePresentationReady(node);
840
+ if (this.stableReplacementCut && (retainRefinedCoverage || !ready) && this.selectedDescendantsCover(node, camera)) {
841
+ for (const child of this.selectedAtFrameStart) {
842
+ if (!this.isDescendantOf(child, node) || !this.adapter.spatial.isVisible(child.spatial, camera) || !this.isNodePresentationReady(child))
843
+ continue;
844
+ child.visible = true;
845
+ child.active = true;
846
+ this.touchBaseTile(child, camera);
847
+ this.selectBaseTile(child, desired, requested);
848
+ }
849
+ return;
850
+ }
851
+ if (retainRefinedCoverage && this.selectedAtFrameStart.some(
852
+ (child) => this.isDescendantOf(child, node) && this.adapter.spatial.isVisible(child.spatial, camera) && this.isNodePresentationReady(child)
853
+ )) {
854
+ this.baseReplacementBlocked = true;
855
+ return;
856
+ }
857
+ if (ready) {
858
+ this.selectBaseTile(node, desired, requested);
859
+ return;
860
+ }
861
+ if (this.obeysGeometricError(node)) return;
862
+ for (let parent = node.parent; parent; parent = parent.parent) {
863
+ if (parent.refinementMode === 0 /* Add */) break;
864
+ if (!this.isNodePresentationReady(parent)) continue;
865
+ this.selectBaseTile(parent, desired, requested);
866
+ return;
867
+ }
868
+ }
869
+ closeBaseQuadtreeCut(camera, desired, requested) {
870
+ if (!this.quadtreeBalance) return;
871
+ const displayed = new Set(this.selectedAtFrameStart);
872
+ const support = [];
873
+ for (; ; ) {
874
+ const entries = this.baseQuadtreeEntries(desired);
875
+ support.push(...entries);
876
+ const involved = /* @__PURE__ */ new Set();
877
+ const balanced = this.refineBaseQuadtreeCut(camera, entries, support, requested, (tiles) => {
878
+ for (const { value } of tiles) involved.add(value);
879
+ });
880
+ if (balanced) {
881
+ const kept = new Set(balanced.map(({ value }) => value));
882
+ for (const { value } of entries) if (!kept.has(value)) desired.delete(value.id);
883
+ for (const { value } of balanced) this.selectBaseTile(value, desired, requested);
884
+ break;
885
+ }
886
+ const undisplayable = [...involved].filter((node) => !displayed.has(node));
887
+ if (undisplayable.length === 0) {
888
+ this.retainBaseCut(camera, desired, requested);
889
+ support.push(...this.baseQuadtreeEntries(desired));
890
+ break;
891
+ }
892
+ for (const node of undisplayable) this.keepDisplayedInPlaceOf(node, displayed, camera, desired, requested);
893
+ }
894
+ const requirements = quadtreeBalanceRefinements(
895
+ support.map(({ location }) => location),
896
+ this.quadtreeBalance.maxLevelDifference
897
+ );
898
+ if (requirements.size !== this.balanceRefinements.size || [...requirements].some((key) => !this.balanceRefinements.has(key)))
899
+ this.requestFrame();
900
+ this.balanceRefinements = requirements;
901
+ }
902
+ baseQuadtreeEntries(desired) {
903
+ return [...desired.values()].flatMap((value) => {
904
+ const location = value.refinementMode === 1 /* Replace */ ? this.quadtreeLocation(value) : void 0;
905
+ return location ? [{ location, value }] : [];
906
+ });
907
+ }
908
+ refineBaseQuadtreeCut(camera, entries, support, requested, blocked) {
909
+ return refineQuadtreeCut(
910
+ entries,
911
+ (coarse) => {
912
+ this.materializeImplicitChildren(coarse.value);
913
+ if (coarse.value.children.length === 0) return void 0;
914
+ const ready = coarse.value.children.map((child) => this.collectBaseReplacementFront(child, camera, requested, BALANCE_LOAD_PRIORITY)).every(Boolean);
915
+ if (!ready) return void 0;
916
+ const front = [];
917
+ const collect = (node) => {
918
+ if (!node.visible) return true;
919
+ if (this.isNodePresentationReady(node)) {
920
+ const location = node.refinementMode === 1 /* Replace */ ? this.quadtreeLocation(node) : void 0;
921
+ if (!location) return false;
922
+ front.push({ location, value: node });
923
+ return true;
924
+ }
925
+ return node.children.map(collect).every(Boolean);
926
+ };
927
+ if (!coarse.value.children.map(collect).every(Boolean)) return void 0;
928
+ support.push(...front);
929
+ return front;
930
+ },
931
+ blocked,
932
+ this.quadtreeBalance?.maxLevelDifference
933
+ );
934
+ }
935
+ /**
936
+ * Gives back the place of a new tile to what was displayed there: the displayed ancestor that it refines, or the
937
+ * displayed tiles under it that it would coarsen. A place that displayed nothing stays empty until it is ready.
938
+ */
939
+ keepDisplayedInPlaceOf(node, displayed, camera, desired, requested) {
940
+ let place = node;
941
+ for (let parent = node.parent; parent; parent = parent.parent) {
942
+ if (!displayed.has(parent)) continue;
943
+ place = parent;
944
+ break;
945
+ }
946
+ const within = (tile) => tile === place || this.isDescendantOf(tile, place);
947
+ for (const tile of [...desired.values()]) if (within(tile)) desired.delete(tile.id);
948
+ for (const tile of displayed) {
949
+ if (!within(tile) || !this.isNodePresentationReady(tile)) continue;
950
+ tile.visible = this.adapter.spatial.isVisible(tile.spatial, camera);
951
+ tile.active = tile.visible;
952
+ this.touchBaseTile(tile, camera);
953
+ this.selectNode(tile, desired, requested);
954
+ }
955
+ }
956
+ retainBaseCut(camera, desired, requested) {
957
+ desired.clear();
958
+ for (const node of this.selectedAtFrameStart) {
959
+ if (!this.isNodePresentationReady(node)) continue;
960
+ node.visible = this.adapter.spatial.isVisible(node.spatial, camera);
961
+ node.active = node.visible;
962
+ this.touchBaseTile(node, camera);
963
+ this.selectNode(node, desired, requested);
964
+ }
965
+ }
966
+ protectBaseCoverageAncestors(desired, requested) {
967
+ const seen = /* @__PURE__ */ new Set();
968
+ for (const tile of desired.values()) {
969
+ for (let parent = tile.parent; parent && !seen.has(parent.id); parent = parent.parent) {
970
+ seen.add(parent.id);
971
+ this.replacementFrontNodes.add(parent.id);
972
+ parent.lastTouchedFrame = this.frame;
973
+ if (parent.implicit) parent.implicit.subtree.lastTouchedFrame = this.frame;
974
+ this.requestNodeContents(parent, this.loadPriority(parent), requested);
975
+ }
976
+ }
977
+ }
978
+ visit(node, camera, desired, requested) {
979
+ if (!this.updateActivity(node, camera)) return;
980
+ node.lastTouchedFrame = this.frame;
981
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
982
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
983
+ camera,
984
+ spatial: node.spatial,
985
+ tile: node.source,
986
+ depth: node.depth
987
+ });
988
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
989
+ this.requestImplicitSubtree(node, node.screenSpaceError);
990
+ this.selectNode(node, desired, requested);
991
+ return;
992
+ }
993
+ const hasPotentialPresentation = node.contents.some(
994
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
995
+ );
996
+ const wasRefining = this.refiningNodes.has(node.id);
997
+ const effectiveThreshold = this.refinementThreshold(node, wasRefining);
998
+ const balanceRequested = this.isBalanceRefinementRequired(node);
999
+ const held = hasPotentialPresentation && this.balanceHolds.has(node.id);
1000
+ const required = node.screenSpaceError > effectiveThreshold || !hasPotentialPresentation && !this.obeysGeometricError(node) || balanceRequested;
1001
+ const coarseningDelayed = this.isCoarseningDelayed(node, wasRefining, required);
1002
+ const refinementRequested = !held && (required || coarseningDelayed);
1003
+ if (refinementRequested) this.materializeImplicitChildren(node);
1004
+ const wantsRefinement = refinementRequested && node.children.length > 0 && (node.visible || node.children.map((child) => this.updateActivity(child, camera)).some(Boolean));
1005
+ this.setRefinementState(node, wantsRefinement);
1006
+ if (!wantsRefinement) {
1007
+ if (hasPotentialPresentation && !this.isNodePresentationReady(node)) {
1008
+ this.requestNodeContents(node, this.loadPriority(node), requested);
1009
+ if (this.stableReplacementCut && this.retainVisibleSelectedDescendants(node, camera, desired)) return;
1010
+ if (!node.visible) return;
1011
+ if (this.selectReadyCoverageAncestor(node.parent, desired, requested)) return;
1012
+ }
1013
+ this.selectNode(node, desired, requested);
1014
+ this.requestRefresh(node, this.loadPriority(node), true);
1015
+ return;
1016
+ }
1017
+ this.cancelProvisionalRefresh(node);
1018
+ if (node.refinementMode === 0 /* Add */) {
1019
+ this.selectNode(node, desired, requested);
1020
+ for (const child of node.children) this.visit(child, camera, desired, requested);
1021
+ return;
1022
+ }
1023
+ const priorityFloor = balanceRequested ? BALANCE_LOAD_PRIORITY : 0;
1024
+ const replacementReady = node.children.map((child) => this.collectReplacementFront(child, camera, requested, priorityFloor)).every(Boolean);
1025
+ if (replacementReady) {
1026
+ for (const child of node.children) this.visit(child, camera, desired, requested);
1027
+ } else {
1028
+ if (balanceRequested && this.stableReplacementCut && this.selectedDescendantsCover(node, camera) && this.retainVisibleSelectedDescendants(node, camera, desired))
1029
+ return;
1030
+ if (!this.obeysGeometricError(node) && this.selectReadyCoverageAncestor(node, desired, requested)) return;
1031
+ if (this.stableReplacementCut && this.retainVisibleSelectedDescendants(node, camera, desired)) return;
1032
+ this.selectNode(node, desired, requested);
1033
+ }
1034
+ }
1035
+ collectReplacementFront(node, camera, requested, priorityFloor = 0) {
1036
+ this.updateActivity(node, camera);
1037
+ const inMargin = !node.visible && this.adapter.spatial.isInPeriphery?.(node.spatial, camera) === true;
1038
+ if (!node.visible && !inMargin) {
1039
+ if (this.preloadSiblings || node.active) this.preloadSibling(node, camera, requested);
1040
+ return true;
1041
+ }
1042
+ node.lastTouchedFrame = this.frame;
1043
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
1044
+ node.screenSpaceError = this.adapter.spatial.screenSpaceError({
1045
+ camera,
1046
+ spatial: node.spatial,
1047
+ tile: node.source,
1048
+ depth: node.depth
1049
+ });
1050
+ const priority = Math.max(node.screenSpaceError, priorityFloor);
1051
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
1052
+ this.requestImplicitSubtree(node, priority);
1053
+ return false;
1054
+ }
1055
+ const potential = node.contents.filter(
1056
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
1057
+ );
1058
+ if (potential.length > 0) {
1059
+ for (const content of potential) content.lastTouchedFrame = this.frame;
1060
+ this.replacementFrontNodes.add(node.id);
1061
+ this.requestNodeContents(node, priority, requested);
1062
+ return potential.every((content) => content.kind === 1 /* Renderable */ && content.status === 3 /* Ready */);
1063
+ }
1064
+ if (this.isSatisfiedEmpty(node)) return true;
1065
+ this.materializeImplicitChildren(node);
1066
+ if (node.children.length === 0) return true;
1067
+ return node.children.map((child) => this.collectReplacementFront(child, camera, requested, priorityFloor)).every(Boolean);
1068
+ }
1069
+ /**
1070
+ * Loads a child outside the view in the background, so that it is ready when the camera turns towards it. It
1071
+ * never blocks the replacement of its parent, and its descendants are not loaded.
1072
+ */
1073
+ preloadSibling(node, camera, requested) {
1074
+ node.lastTouchedFrame = this.frame;
1075
+ if (node.implicit) node.implicit.subtree.lastTouchedFrame = this.frame;
1076
+ const screenSpaceError = this.adapter.spatial.screenSpaceError({
1077
+ camera,
1078
+ spatial: node.spatial,
1079
+ tile: node.source,
1080
+ depth: node.depth
1081
+ });
1082
+ const priority = screenSpaceError * PRELOAD_PRIORITY_SCALE;
1083
+ if (node.implicit && node.implicit.subtree.status !== 3 /* Ready */) {
1084
+ this.requestImplicitSubtree(node, priority);
1085
+ return;
1086
+ }
1087
+ const potential = node.contents.filter(
1088
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
1089
+ );
1090
+ if (potential.length === 0) return;
1091
+ for (const content of potential) content.lastTouchedFrame = this.frame;
1092
+ this.requestNodeContents(node, priority, requested);
1093
+ }
1094
+ /** Screen-space error above which a tile refines: lowered by the hysteresis once refined, scaled by the factor before. */
1095
+ refinementThreshold(node, wasRefining) {
1096
+ const threshold = this.maxScreenSpaceErrorForDepth?.(node.depth, this.maxScreenSpaceError) ?? this.maxScreenSpaceError;
1097
+ return wasRefining ? threshold * (1 - this.refinementHysteresisRatio) : threshold * Math.max(1, this.refinementThresholdScale?.() ?? 1);
1098
+ }
1099
+ /**
1100
+ * Whether a tile is explicit and every content it has, if any, is known empty and ready. A tile with an external
1101
+ * tileset, with a content not loaded yet, or an implicit tile is not.
1102
+ */
1103
+ isKnownEmpty(node) {
1104
+ return !node.implicit && node.contents.every((content) => content.kind === 3 /* Empty */ && content.status === 3 /* Ready */);
1105
+ }
1106
+ /** Whether a tile with nothing to present refines by its screen-space error, see `emptyTileRefinement`. */
1107
+ obeysGeometricError(node) {
1108
+ return this.emptyTileRefinement === "geometric-error" && this.isKnownEmpty(node);
1109
+ }
1110
+ /** Whether a known empty tile that obeys its error stays under its threshold, with its error of the current frame. */
1111
+ isSatisfiedEmpty(node) {
1112
+ return this.obeysGeometricError(node) && node.screenSpaceError <= this.refinementThreshold(node, this.refiningNodes.has(node.id));
1113
+ }
1114
+ /** Whether a refined tile that no longer requires its refinement still waits before coarsening. */
1115
+ isCoarseningDelayed(node, wasRefining, required) {
1116
+ if (required || !wasRefining || this.coarseningDelayMilliseconds === 0) {
1117
+ this.coarseningSince.delete(node.id);
1118
+ return false;
1119
+ }
1120
+ const now = this.clock();
1121
+ const known = this.coarseningSince.get(node.id);
1122
+ const since = known && known.frame >= this.frame - 1 ? known.since : now;
1123
+ const expires = since + this.coarseningDelayMilliseconds;
1124
+ this.coarseningSince.set(node.id, { since, frame: this.frame });
1125
+ if (now >= expires) return false;
1126
+ this.nextCoarseningAt = Math.min(this.nextCoarseningAt ?? expires, expires);
1127
+ return true;
1128
+ }
1129
+ /** Location of an implicit quadtree tile for balancing, or `undefined` when balancing does not apply. */
1130
+ quadtreeLocation(node) {
1131
+ const implicit = node.implicit;
1132
+ if (!this.quadtreeBalance || !implicit || implicit.context.implicitTiling.subdivisionScheme !== "QUADTREE") return void 0;
1133
+ const { context, coordinates } = implicit;
1134
+ const address = this.implicitResolver(context)?.addressOf?.({
1135
+ documentUri: node.document.uri,
1136
+ rootTile: context.rootTile,
1137
+ implicitTiling: context.implicitTiling,
1138
+ coordinates
1139
+ });
1140
+ if (address) {
1141
+ const { wrapX = false, topology } = this.quadtreeBalance;
1142
+ return { namespace: "", address, wrapX, ...topology ? { topology } : {} };
1143
+ }
1144
+ return { namespace: `${context.id}:`, address: { lod: coordinates.level, x: coordinates.x, y: coordinates.y }, wrapX: false };
1145
+ }
1146
+ isBalanceRefinementRequired(node) {
1147
+ if (this.balanceRefinements.size === 0) return false;
1148
+ const location = this.quadtreeLocation(node);
1149
+ return location !== void 0 && this.balanceRefinements.has(quadtreeTileKey(location.namespace, location.address));
1150
+ }
1151
+ /**
1152
+ * Adds the refinements that balance a selection. Refinements only
1153
+ * accumulate within a frame, so repeating the traversal converges: each
1154
+ * pass can only make the cut finer, and a refinement that unbalances
1155
+ * further neighbours is resolved by the next pass.
1156
+ *
1157
+ * @returns Whether a refinement was added, which requires another pass.
1158
+ */
1159
+ extendQuadtreeBalance(desired) {
1160
+ if (!this.quadtreeBalance) return false;
1161
+ let added = false;
1162
+ for (const key of quadtreeBalanceRefinements(this.visibleQuadtreeLocations(desired), this.quadtreeBalance.maxLevelDifference)) {
1163
+ if (this.balanceRefinements.has(key)) continue;
1164
+ this.balanceRefinements.add(key);
1165
+ added = true;
1166
+ }
1167
+ return added;
1168
+ }
1169
+ /** Visible selected quadtree tiles: a tile outside the view, even active, neither requires nor holds back what the camera sees. */
1170
+ visibleQuadtreeLocations(desired) {
1171
+ const locations = [];
1172
+ for (const node of desired.values()) {
1173
+ if (!node.visible) continue;
1174
+ const location = this.quadtreeLocation(node);
1175
+ if (location) locations.push(location);
1176
+ }
1177
+ return locations;
1178
+ }
1179
+ /** Visible selected quadtree tiles next to a visible selected tile coarser by more than `maxLevelDifference` levels. */
1180
+ findImbalances(desired) {
1181
+ const displayed = [];
1182
+ for (const node of desired.values()) {
1183
+ if (!node.visible) continue;
1184
+ const location = this.quadtreeLocation(node);
1185
+ if (location) displayed.push({ location, value: node });
1186
+ }
1187
+ return quadtreeImbalances(displayed, this.quadtreeBalance?.maxLevelDifference);
1188
+ }
1189
+ /**
1190
+ * Holds the refinement that brought a tile next to a neighbour coarser by
1191
+ * more than `maxLevelDifference` levels, when that neighbour cannot refine
1192
+ * yet. An ancestor of the fine tile stays displayed instead: the finest one
1193
+ * within `maxLevelDifference` levels of the neighbour that is ready. The
1194
+ * refinement resumes once the neighbour's children load.
1195
+ *
1196
+ * Only new refinements are held. A refinement already displayed at the
1197
+ * start of the frame is kept, because coarsening it would flicker: the
1198
+ * neighbour typically comes into view while the camera turns, and its
1199
+ * children load first since the balance requires them. The edge stays
1200
+ * reported as unbalanced meanwhile.
1201
+ *
1202
+ * @returns Whether a refinement was held, which requires another pass.
1203
+ */
1204
+ holdUnbalancedRefinements(desired) {
1205
+ if (!this.quadtreeBalance) return false;
1206
+ let held = false;
1207
+ const refinedAtFrameStart = /* @__PURE__ */ new Set();
1208
+ for (const node of this.selectedAtFrameStart) {
1209
+ for (let ancestor = node.parent; ancestor && !refinedAtFrameStart.has(ancestor.id); ancestor = ancestor.parent)
1210
+ refinedAtFrameStart.add(ancestor.id);
1211
+ }
1212
+ for (const { fine, coarseLod } of this.findImbalances(desired)) {
1213
+ for (let ancestor = fine.parent; ancestor; ancestor = ancestor.parent) {
1214
+ const lod = this.quadtreeLocation(ancestor)?.address.lod;
1215
+ if (lod === void 0 || lod < coarseLod) break;
1216
+ if (lod > coarseLod + this.quadtreeBalance.maxLevelDifference || !this.isNodePresentationReady(ancestor)) continue;
1217
+ if (refinedAtFrameStart.has(ancestor.id)) break;
1218
+ if (!this.balanceHolds.has(ancestor.id)) {
1219
+ this.balanceHolds.add(ancestor.id);
1220
+ held = true;
1221
+ }
1222
+ break;
1223
+ }
1224
+ }
1225
+ return held;
1226
+ }
1227
+ isNodePresentationReady(node) {
1228
+ const potential = node.contents.filter(
1229
+ (content) => content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */
1230
+ );
1231
+ return potential.length > 0 && potential.every(
1232
+ (content) => content.kind === 1 /* Renderable */ && content.status === 3 /* Ready */ && content.handle !== void 0
1233
+ );
1234
+ }
1235
+ selectReadyCoverageAncestor(start, desired, requested) {
1236
+ let candidate = start;
1237
+ while (candidate) {
1238
+ if (this.isNodePresentationReady(candidate)) {
1239
+ this.selectNode(candidate, desired, requested);
1240
+ return true;
1241
+ }
1242
+ candidate = candidate.parent;
1243
+ }
1244
+ return false;
1245
+ }
1246
+ /**
1247
+ * Updates whether a tile is visible and active. A visible tile is always active. An active tile need not be visible: it
1248
+ * may lie in the periphery of the view or, with `preloadSiblings`, be the neighbour of a visible tile. It refines and
1249
+ * merges like a visible one, and stays selected when it leaves the view, so that the selection does not change with
1250
+ * each small move of the camera. The traversal stops at a tile that is not active: its whole hierarchy goes with it,
1251
+ * and its ancestors do not depend on it.
1252
+ *
1253
+ * @returns Whether the tile is active.
1254
+ */
1255
+ updateActivity(node, camera) {
1256
+ const { spatial } = this.adapter;
1257
+ node.visible = spatial.isVisible(node.spatial, camera);
1258
+ node.active = node.visible || spatial.isInPeriphery?.(node.spatial, camera) === true || this.preloadSiblings && this.isNeighbourOfVisible(node);
1259
+ return node.active;
1260
+ }
1261
+ isNeighbourOfVisible(node) {
1262
+ const location = this.quadtreeLocation(node);
1263
+ return location !== void 0 && quadtreeTouches(location, this.visibleTiles);
1264
+ }
1265
+ /** Keeps the visible selected tiles of a frame, for their neighbours in the next one. It asks for that frame when they changed. */
1266
+ updateVisibleTiles(desired) {
1267
+ const tiles = /* @__PURE__ */ new Set();
1268
+ for (const node of desired.values()) {
1269
+ if (!node.visible) continue;
1270
+ const location = this.quadtreeLocation(node);
1271
+ if (location) tiles.add(quadtreeTileKey(location.namespace, location.address));
1272
+ }
1273
+ const changed = tiles.size !== this.visibleTiles.size || [...tiles].some((tile) => !this.visibleTiles.has(tile));
1274
+ this.visibleTiles = tiles;
1275
+ if (changed) this.requestFrame();
1276
+ }
1277
+ /** What the camera sees loads first. */
1278
+ loadPriority(node) {
1279
+ return node.visible ? node.screenSpaceError : node.screenSpaceError * PRELOAD_PRIORITY_SCALE;
1280
+ }
1281
+ /** Whether the tiles selected at the start of the frame cover every visible part of a tile. */
1282
+ selectedDescendantsCover(node, camera) {
1283
+ const selected = new Set(this.selectedAtFrameStart);
1284
+ const covered = (tile) => {
1285
+ if (selected.has(tile) || !this.adapter.spatial.isVisible(tile.spatial, camera)) return true;
1286
+ if (this.selectionStrategy === "base" && tile.children.length === 0 && tile.contents.every((content) => content.kind === 3 /* Empty */ && content.status === 3 /* Ready */) && (!tile.implicit || tile.implicit.subtree.status === 3 /* Ready */ && tile.implicit.childrenMaterialized)) {
1287
+ return true;
1288
+ }
1289
+ if (this.obeysGeometricError(tile) && !this.refiningNodes.has(tile.id)) return true;
1290
+ return tile.children.length > 0 && tile.children.every(covered);
1291
+ };
1292
+ return node.children.length > 0 && node.children.every(covered);
1293
+ }
1294
+ retainVisibleSelectedDescendants(node, camera, desired) {
1295
+ let retained = false;
1296
+ for (const candidate of this.selectedAtFrameStart) {
1297
+ if (!this.isDescendantOf(candidate, node)) continue;
1298
+ if (!this.updateActivity(candidate, camera)) continue;
1299
+ candidate.lastTouchedFrame = this.frame;
1300
+ if (candidate.implicit) candidate.implicit.subtree.lastTouchedFrame = this.frame;
1301
+ candidate.screenSpaceError = this.adapter.spatial.screenSpaceError({
1302
+ camera,
1303
+ spatial: candidate.spatial,
1304
+ tile: candidate.source,
1305
+ depth: candidate.depth
1306
+ });
1307
+ desired.set(candidate.id, candidate);
1308
+ this.activeThisFrame.add(candidate.id);
1309
+ for (const content of candidate.contents) content.lastTouchedFrame = this.frame;
1310
+ retained = true;
1311
+ }
1312
+ return retained;
1313
+ }
1314
+ isDescendantOf(candidate, ancestor) {
1315
+ let parent = candidate.parent;
1316
+ while (parent) {
1317
+ if (parent === ancestor) return true;
1318
+ parent = parent.parent;
1319
+ }
1320
+ return false;
1321
+ }
1322
+ setRefinementState(node, refining) {
1323
+ const wasRefining = this.refiningNodes.has(node.id);
1324
+ if (wasRefining === refining) return;
1325
+ if (refining) this.refiningNodes.add(node.id);
1326
+ else this.refiningNodes.delete(node.id);
1327
+ this.recordMetric({
1328
+ name: refining ? "tile.refine.attempt" : "tile.coarsen.attempt",
1329
+ value: 1,
1330
+ unit: "count",
1331
+ tags: {
1332
+ runtime: this.id,
1333
+ tile: node.id,
1334
+ depth: node.depth,
1335
+ screenSpaceError: node.screenSpaceError
1336
+ }
1337
+ });
1338
+ }
1339
+ /** What a frame really changed: refinements and coarsenings once its passes are over, and tiles of the cut. */
1340
+ recordCutChanges(refiningAtFrameStart, entered, left) {
1341
+ const record = (name, value) => {
1342
+ for (let i = 0; i < value; i++) this.recordMetric({ name, value: 1, unit: "count", tags: { runtime: this.id } });
1343
+ };
1344
+ let refined = 0;
1345
+ for (const id of this.refiningNodes) if (!refiningAtFrameStart.has(id)) refined++;
1346
+ let coarsened = 0;
1347
+ for (const id of refiningAtFrameStart) if (!this.refiningNodes.has(id)) coarsened++;
1348
+ record("tile.refine", refined);
1349
+ record("tile.coarsen", coarsened);
1350
+ record("cut.entered", entered);
1351
+ record("cut.left", left);
1352
+ }
1353
+ selectNode(node, desired, requested) {
1354
+ desired.set(node.id, node);
1355
+ node.lastTouchedFrame = this.frame;
1356
+ for (const content of node.contents) content.lastTouchedFrame = this.frame;
1357
+ this.requestNodeContents(node, this.loadPriority(node), requested);
1358
+ }
1359
+ requestNodeContents(node, priority, requested) {
1360
+ if (node.contents.length === 0) return;
1361
+ this.activeThisFrame.add(node.id);
1362
+ const entering = node.selectionState !== 1 /* Active */;
1363
+ if (entering) {
1364
+ node.selectionState = 1 /* Active */;
1365
+ node.activationId++;
1366
+ this.events.emit({ type: "tile-activated", tile: node });
1367
+ }
1368
+ if (this.adapter.activation) {
1369
+ if (node.contents.some((content) => content.status === 1 /* Queued */))
1370
+ this.followQueuedPriority(this.pipelineActivationKey(node), priority);
1371
+ this.requestPipelineActivation(node, priority, requested, entering);
1372
+ this.requestRefresh(node, priority);
1373
+ return;
1374
+ }
1375
+ for (const content of node.contents) {
1376
+ if (content.kind !== 0 /* Unknown */ && content.kind !== 1 /* Renderable */) continue;
1377
+ if (content.status === 1 /* Queued */) this.followQueuedPriority(content.id, priority);
1378
+ if (content.status !== 0 /* Idle */ && content.status !== 4 /* Failed */ && content.status !== 5 /* Cancelled */)
1379
+ continue;
1380
+ if (content.attempts >= this.maxLoadAttempts) continue;
1381
+ content.status = 1 /* Queued */;
1382
+ const added = this.scheduler.enqueue(content.id, priority, (signal) => this.loadContent(node, content, signal));
1383
+ if (added) {
1384
+ requested.push(content);
1385
+ this.events.emit({ type: "content-state", tile: node, content });
1386
+ }
1387
+ }
1388
+ this.refreshNodeReadiness(node);
1389
+ this.requestRefresh(node, priority);
1390
+ }
1391
+ /** A waiting load follows the priority of the current frame, up or down: the highest its balance passes asked. */
1392
+ followQueuedPriority(key, priority) {
1393
+ if (this.queuedPrioritiesFrame !== this.frame) {
1394
+ this.queuedPriorities.clear();
1395
+ this.queuedPrioritiesFrame = this.frame;
1396
+ }
1397
+ const highest = Math.max(this.queuedPriorities.get(key) ?? priority, priority);
1398
+ this.queuedPriorities.set(key, highest);
1399
+ this.scheduler.reprioritize(key, highest);
1400
+ }
1401
+ requestPipelineActivation(node, priority, requested, notifyEvenWhenReady) {
1402
+ const pending = node.contents.filter(
1403
+ (content) => (content.kind === 0 /* Unknown */ || content.kind === 1 /* Renderable */) && (content.status === 0 /* Idle */ || content.status === 4 /* Failed */ || content.status === 5 /* Cancelled */) && content.attempts < this.maxLoadAttempts
1404
+ );
1405
+ if (pending.length === 0 && !notifyEvenWhenReady) return;
1406
+ const previous = pending.map((content) => content.status);
1407
+ for (const content of pending) content.status = 1 /* Queued */;
1408
+ const key = this.pipelineActivationKey(node);
1409
+ const added = this.scheduler.enqueue(key, priority, (signal) => this.activatePipelineTile(node, pending, priority, signal));
1410
+ if (!added) {
1411
+ pending.forEach((content, index) => content.status = previous[index]);
1412
+ return;
1413
+ }
1414
+ this.refreshNodeReadiness(node);
1415
+ for (const content of pending) {
1416
+ requested.push(content);
1417
+ this.events.emit({ type: "content-state", tile: node, content });
1418
+ }
1419
+ }
1420
+ async activatePipelineTile(node, pending, priority, signal) {
1421
+ const activation = this.adapter.activation;
1422
+ if (!activation) return;
1423
+ const activationId = node.activationId;
1424
+ const unsettled = new Set(pending.map((content) => content.id));
1425
+ let settleActivation;
1426
+ const settled = new Promise((resolve) => {
1427
+ settleActivation = resolve;
1428
+ });
1429
+ const finish = (contentId) => {
1430
+ unsettled.delete(contentId);
1431
+ if (unsettled.size === 0) settleActivation?.();
1432
+ };
1433
+ const findPending = (contentId) => pending.find((content) => content.id === contentId);
1434
+ for (const content of pending) {
1435
+ content.attempts++;
1436
+ content.status = 2 /* Preparing */;
1437
+ content.lastTouchedFrame = this.frame;
1438
+ this.events.emit({ type: "content-state", tile: node, content });
1439
+ }
1440
+ this.refreshNodeReadiness(node);
1441
+ const readiness = {
1442
+ tileId: node.id,
1443
+ activationId,
1444
+ signal,
1445
+ ready: async (contentId, result) => {
1446
+ const content = findPending(contentId);
1447
+ if (!content || !unsettled.has(contentId) || signal.aborted || node.activationId !== activationId) return false;
1448
+ await this.acceptContentResult(node, content, result);
1449
+ content.status = 3 /* Ready */;
1450
+ content.readyFrame = this.frame;
1451
+ content.lastTouchedFrame = this.frame;
1452
+ delete content.error;
1453
+ this.events.emit({ type: "content-state", tile: node, content });
1454
+ this.refreshNodeReadiness(node);
1455
+ finish(contentId);
1456
+ this.markDirty();
1457
+ return true;
1458
+ },
1459
+ failed: async (contentId, error) => {
1460
+ const content = findPending(contentId);
1461
+ if (!content || !unsettled.has(contentId) || node.activationId !== activationId) return;
1462
+ content.error = error;
1463
+ content.status = 4 /* Failed */;
1464
+ this.events.emit({ type: "content-state", tile: node, content });
1465
+ this.refreshNodeReadiness(node);
1466
+ await this.reportError("content.prepare", error, node, content);
1467
+ finish(contentId);
1468
+ this.markDirty();
1469
+ },
1470
+ cancelled: async (contentId) => {
1471
+ const content = findPending(contentId);
1472
+ if (!content || !unsettled.has(contentId)) return;
1473
+ content.attempts = Math.max(0, content.attempts - 1);
1474
+ content.status = 5 /* Cancelled */;
1475
+ this.recordMetric({ name: "content.cancelled", value: 1, unit: "count", tags: { runtime: this.id, tile: node.id } });
1476
+ this.events.emit({ type: "content-state", tile: node, content });
1477
+ this.refreshNodeReadiness(node);
1478
+ finish(contentId);
1479
+ this.markDirty();
1480
+ }
1481
+ };
1482
+ let abandon = () => void 0;
1483
+ const abandoned = new Promise((resolve) => {
1484
+ abandon = resolve;
1485
+ });
1486
+ const abort = () => {
1487
+ for (const contentId of [...unsettled]) void readiness.cancelled(contentId);
1488
+ abandon();
1489
+ };
1490
+ signal.addEventListener("abort", abort, { once: true });
1491
+ try {
1492
+ await Promise.race([
1493
+ activation.activate({
1494
+ runtimeId: this.id,
1495
+ tile: node,
1496
+ pendingContents: pending,
1497
+ priority,
1498
+ activationId,
1499
+ signal,
1500
+ readiness
1501
+ }),
1502
+ abandoned
1503
+ ]);
1504
+ if (unsettled.size > 0) await settled;
1505
+ } catch (error) {
1506
+ for (const contentId of [...unsettled]) await readiness.failed(contentId, error);
1507
+ } finally {
1508
+ signal.removeEventListener("abort", abort);
1509
+ if (signal.aborted) this.markDirty();
1510
+ }
1511
+ }
1512
+ refreshKey(node) {
1513
+ return `refresh:${node.id}`;
1514
+ }
1515
+ /**
1516
+ * Reloads the stale ready contents of a tile of the working set, one reload of a tile at a time. Provisional
1517
+ * contents reload only for a leaf of the cut: a tile the descent goes through never loads its own content.
1518
+ */
1519
+ requestRefresh(node, priority, leaf = false) {
1520
+ const stale = node.contents.filter(
1521
+ (content) => content.stale && content.ready && !this.refreshes.has(content) && (leaf || !this.provisionalContents.has(content))
1522
+ );
1523
+ if (stale.length === 0) return;
1524
+ const records = stale.map((content) => ({ content, refresh: { serial: this.staleContents.get(content)?.serial ?? 0 } }));
1525
+ for (const { content, refresh } of records) this.refreshes.set(content, refresh);
1526
+ const added = this.scheduler.enqueue(
1527
+ this.refreshKey(node),
1528
+ priority,
1529
+ (signal) => this.refreshTile(node, records, priority, signal)
1530
+ );
1531
+ if (!added) for (const { content } of records) this.refreshes.delete(content);
1532
+ }
1533
+ /** Stops the reload of the provisional contents of a tile that refines again: its children replace it. */
1534
+ cancelProvisionalRefresh(node) {
1535
+ const pending = node.contents.some((content) => {
1536
+ const refresh = this.refreshes.get(content);
1537
+ return this.provisionalContents.has(content) && refresh !== void 0 && refresh.result === void 0;
1538
+ });
1539
+ if (pending) this.cancelRefresh(node);
1540
+ }
1541
+ /** Stops the reloads of a tile leaving the working set; the results already reported are still swapped in. */
1542
+ cancelRefresh(node) {
1543
+ this.scheduler.cancel(this.refreshKey(node));
1544
+ for (const content of node.contents) {
1545
+ const refresh = this.refreshes.get(content);
1546
+ if (refresh && !refresh.result) this.refreshes.delete(content);
1547
+ }
1548
+ }
1549
+ async refreshTile(node, records, priority, signal) {
1550
+ const unsettled = new Set(records.map(({ content }) => content.id));
1551
+ const current = (contentId) => {
1552
+ const record = records.find(({ content }) => content.id === contentId);
1553
+ return record && unsettled.has(contentId) && this.refreshes.get(record.content) === record.refresh ? record : void 0;
1554
+ };
1555
+ const settle = (contentId, record, keep) => {
1556
+ unsettled.delete(contentId);
1557
+ if (record && !keep) this.refreshes.delete(record.content);
1558
+ this.markDirty();
1559
+ };
1560
+ const readiness = {
1561
+ tileId: node.id,
1562
+ activationId: node.activationId,
1563
+ signal,
1564
+ ready: async (contentId, result) => {
1565
+ const record = current(contentId);
1566
+ if (!record || signal.aborted) return false;
1567
+ record.refresh.result = result;
1568
+ settle(contentId, record, true);
1569
+ return true;
1570
+ },
1571
+ failed: async (contentId, error) => {
1572
+ const record = current(contentId);
1573
+ if (!record) return;
1574
+ settle(contentId, record, false);
1575
+ const stale = this.staleContents.get(record.content);
1576
+ if (stale && ++stale.failures >= this.maxLoadAttempts) this.markFresh(record.content, stale.serial);
1577
+ await this.reportError("content.refresh", error, node, record.content);
1578
+ },
1579
+ cancelled: async (contentId) => {
1580
+ if (unsettled.has(contentId)) settle(contentId, current(contentId), false);
1581
+ }
1582
+ };
1583
+ const abort = () => {
1584
+ for (const contentId of [...unsettled]) void readiness.cancelled(contentId);
1585
+ };
1586
+ signal.addEventListener("abort", abort, { once: true });
1587
+ try {
1588
+ const activation = this.adapter.activation;
1589
+ if (activation) {
1590
+ await activation.activate({
1591
+ runtimeId: this.id,
1592
+ tile: node,
1593
+ pendingContents: records.map(({ content }) => content),
1594
+ priority,
1595
+ activationId: node.activationId,
1596
+ signal,
1597
+ readiness,
1598
+ refresh: true
1599
+ });
1600
+ } else {
1601
+ const contentAdapter = this.adapter.content;
1602
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
1603
+ for (const { content } of records) {
1604
+ if (signal.aborted) break;
1605
+ try {
1606
+ const result = await contentAdapter.load(this.contentLoadContext(node, content), signal);
1607
+ const accepted = await readiness.ready(content.id, result);
1608
+ if (!accepted && result.kind === "renderable" && result.handle !== content.handle)
1609
+ await this.releaseHandle(node, content, result.handle);
1610
+ } catch (error) {
1611
+ if (signal.aborted) await readiness.cancelled(content.id);
1612
+ else await readiness.failed(content.id, error);
1613
+ }
1614
+ }
1615
+ }
1616
+ } catch (error) {
1617
+ for (const contentId of [...unsettled]) await readiness.failed(contentId, error);
1618
+ } finally {
1619
+ signal.removeEventListener("abort", abort);
1620
+ for (const contentId of [...unsettled]) {
1621
+ if (signal.aborted) await readiness.cancelled(contentId);
1622
+ else await readiness.failed(contentId, new Error("The activation adapter settled no reload of this content."));
1623
+ }
1624
+ }
1625
+ }
1626
+ /** Clears the stale flag, unless the content was invalidated again after its reload started. */
1627
+ markFresh(content, serial) {
1628
+ const stale = this.staleContents.get(content);
1629
+ if (stale && stale.serial > serial) return;
1630
+ this.staleContents.delete(content);
1631
+ content.stale = false;
1632
+ }
1633
+ /** Swaps the reloaded handles in, before the traversal of a frame. */
1634
+ async applyRefreshes() {
1635
+ if (this.refreshes.size === 0) return;
1636
+ for (const node of this.nodes.values()) {
1637
+ for (const content of node.contents) {
1638
+ const refresh = this.refreshes.get(content);
1639
+ if (!refresh?.result) continue;
1640
+ this.refreshes.delete(content);
1641
+ await this.swapContent(node, content, refresh.result, refresh.serial);
1642
+ }
1643
+ }
1644
+ }
1645
+ /**
1646
+ * Replaces the handle of a content with its reload. A presented content is hidden and released, then the tile is
1647
+ * presented again with the new handle, all before the next render: the view never shows a hole.
1648
+ */
1649
+ async swapContent(node, content, result, serial) {
1650
+ const previous = content.handle;
1651
+ if (previous === void 0 || !content.ready) {
1652
+ if (result.kind === "renderable" && result.handle !== previous) await this.releaseHandle(node, content, result.handle);
1653
+ return;
1654
+ }
1655
+ this.markFresh(content, serial);
1656
+ content.lastTouchedFrame = this.frame;
1657
+ if (result.kind !== "renderable") {
1658
+ await this.reportError("content.refresh", new Error("A reloaded content must stay renderable."), node, content);
1659
+ return;
1660
+ }
1661
+ if (result.handle === previous) {
1662
+ this.events.emit({ type: "content-state", tile: node, content });
1663
+ return;
1664
+ }
1665
+ const presented = content.attached && node.selected;
1666
+ const old = content;
1667
+ const presentation = this.adapter.presentation;
1668
+ const contentAdapter = this.adapter.content;
1669
+ try {
1670
+ if (presented) {
1671
+ if (presentation) await presentation.hide(this.pipelinePresentationContext(node, [old]));
1672
+ else await contentAdapter?.detach(this.presentationContext(node, old, await this.contentSnapshot(node, old)));
1673
+ }
1674
+ } catch (error) {
1675
+ await this.reportError("content.hide", error, node, content);
1676
+ }
1677
+ await this.releaseHandle(node, content, previous);
1678
+ content.attached = false;
1679
+ this.metadataStore.release(content.metadataHandle);
1680
+ if (content.featureMetadataHandle !== content.metadataHandle) this.metadataStore.release(content.featureMetadataHandle);
1681
+ content.metadataHandle = NO_METADATA;
1682
+ content.featureMetadataHandle = NO_METADATA;
1683
+ node.metadataSnapshots = node.metadataSnapshots.filter((snapshot) => snapshot.content !== content.descriptor);
1684
+ await this.acceptContentResult(node, content, result);
1685
+ content.readyFrame = this.frame;
1686
+ this.events.emit({ type: "content-state", tile: node, content });
1687
+ if (!presented) return;
1688
+ const fresh = content;
1689
+ try {
1690
+ const snapshot = await this.resolveMetadata(node, fresh.descriptor, fresh.featureMetadata);
1691
+ node.metadataSnapshots = [...node.metadataSnapshots, snapshot];
1692
+ if (presentation) {
1693
+ const ready = node.contents.filter((candidate) => candidate.ready);
1694
+ await presentation.present(this.pipelinePresentationContext(node, ready));
1695
+ for (const candidate of ready) candidate.attached = true;
1696
+ } else if (contentAdapter) {
1697
+ await contentAdapter.attach(this.presentationContext(node, fresh, snapshot));
1698
+ fresh.attached = true;
1699
+ }
1700
+ } catch (error) {
1701
+ await this.reportError("content.present", error, node, content);
1702
+ }
1703
+ }
1704
+ /** Releases a handle of a content that is not, or no longer, its current handle. */
1705
+ async releaseHandle(node, content, handle) {
1706
+ const presentation = this.adapter.presentation;
1707
+ const contentAdapter = this.adapter.content;
1708
+ const resource = Object.assign(
1709
+ Object.create(Object.getPrototypeOf(content)),
1710
+ content,
1711
+ {
1712
+ handle
1713
+ }
1714
+ );
1715
+ try {
1716
+ if (presentation?.release) await presentation.release(this.pipelinePresentationContext(node, [resource]));
1717
+ else if (contentAdapter?.dispose)
1718
+ await contentAdapter.dispose(this.presentationContext(node, resource, await this.contentSnapshot(node, resource)));
1719
+ } catch (error) {
1720
+ await this.reportError("content.dispose", error, node, content);
1721
+ }
1722
+ }
1723
+ async contentSnapshot(node, content) {
1724
+ return node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ?? await this.resolveMetadata(node, content.descriptor);
1725
+ }
1726
+ pipelineActivationKey(node) {
1727
+ return `activation:${node.id}`;
1728
+ }
1729
+ async deactivatePipelineTilesOutsideWorkingSet() {
1730
+ for (const node of this.nodes.values()) {
1731
+ if (node.selectionState !== 1 /* Active */ || this.activeThisFrame.has(node.id)) continue;
1732
+ const activationId = node.activationId;
1733
+ node.activationId++;
1734
+ node.selectionState = 0 /* Inactive */;
1735
+ this.scheduler.cancel(this.pipelineActivationKey(node));
1736
+ this.cancelRefresh(node);
1737
+ let requeue = false;
1738
+ for (const content of node.contents) {
1739
+ if (content.status !== 1 /* Queued */) continue;
1740
+ content.status = 0 /* Idle */;
1741
+ requeue = true;
1742
+ }
1743
+ if (requeue) this.refreshNodeReadiness(node);
1744
+ if (this.adapter.activation) {
1745
+ await this.adapter.activation.deactivate({ runtimeId: this.id, tile: node, activationId });
1746
+ }
1747
+ this.events.emit({ type: "tile-deactivated", tile: node });
1748
+ }
1749
+ }
1750
+ async loadContent(node, content, signal) {
1751
+ const startedAt = this.startTiming();
1752
+ content.attempts++;
1753
+ content.status = 2 /* Preparing */;
1754
+ content.lastTouchedFrame = this.frame;
1755
+ this.refreshNodeReadiness(node);
1756
+ this.events.emit({ type: "content-state", tile: node, content });
1757
+ const hookContext = { runtimeId: this.id, tile: node, content };
1758
+ await this.invokeHooks("beforeContentLoad", (hook) => hook.beforeContentLoad?.(hookContext), node, content);
1759
+ try {
1760
+ const contentAdapter = this.adapter.content;
1761
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
1762
+ const result = await contentAdapter.load(this.contentLoadContext(node, content), signal);
1763
+ if (signal.aborted) {
1764
+ content.attempts = Math.max(0, content.attempts - 1);
1765
+ content.status = 5 /* Cancelled */;
1766
+ return;
1767
+ }
1768
+ await this.acceptContentResult(node, content, result);
1769
+ content.status = 3 /* Ready */;
1770
+ content.readyFrame = this.frame;
1771
+ content.lastTouchedFrame = this.frame;
1772
+ delete content.error;
1773
+ this.recordMetric({
1774
+ name: "content.load",
1775
+ value: 1,
1776
+ unit: "count",
1777
+ tags: { runtime: this.id, tile: node.id, kind: content.kind }
1778
+ });
1779
+ this.recordDuration("content.load.duration", startedAt, {
1780
+ runtime: this.id,
1781
+ tile: node.id,
1782
+ kind: content.kind
1783
+ });
1784
+ if (content.cost?.networkBytes !== void 0) {
1785
+ this.recordMetric({
1786
+ name: "content.load.network-bytes",
1787
+ value: content.cost.networkBytes,
1788
+ unit: "byte",
1789
+ tags: { runtime: this.id, tile: node.id }
1790
+ });
1791
+ }
1792
+ await this.invokeHooks("afterContentLoad", (hook) => hook.afterContentLoad?.({ ...hookContext, result }), node, content);
1793
+ } catch (error) {
1794
+ content.error = error;
1795
+ content.status = signal.aborted ? 5 /* Cancelled */ : 4 /* Failed */;
1796
+ if (signal.aborted) content.attempts = Math.max(0, content.attempts - 1);
1797
+ await this.reportError("content.load", error, node, content);
1798
+ } finally {
1799
+ this.refreshNodeReadiness(node);
1800
+ this.events.emit({ type: "content-state", tile: node, content });
1801
+ this.markDirty();
1802
+ }
1803
+ }
1804
+ async acceptContentResult(node, content, result) {
1805
+ if (result.kind === "renderable") {
1806
+ content.kind = 1 /* Renderable */;
1807
+ content.handle = result.handle;
1808
+ if (result.cacheKey) content.cacheKey = result.cacheKey;
1809
+ else delete content.cacheKey;
1810
+ if (result.cost) content.cost = result.cost;
1811
+ else delete content.cost;
1812
+ if (result.featureMetadata) content.featureMetadata = result.featureMetadata;
1813
+ else delete content.featureMetadata;
1814
+ node.contentHeights = result.tileHeightRange;
1815
+ if (result.tileBoundingVolume) {
1816
+ const measured = result.tileBoundingVolume;
1817
+ this.refineTileBoundingVolume(node, typeof measured === "function" ? measured : () => measured);
1818
+ }
1819
+ this.refreshImplicitChildBounds(node);
1820
+ if (result.provisional) {
1821
+ this.provisionalContents.add(content);
1822
+ content.stale = true;
1823
+ if (!this.staleContents.has(content)) this.staleContents.set(content, { serial: this.invalidations, failures: 0 });
1824
+ } else this.provisionalContents.delete(content);
1825
+ return;
1826
+ }
1827
+ if (result.kind === "external-tileset") {
1828
+ content.kind = 2 /* ExternalTileset */;
1829
+ const documentUri = result.documentUri ?? content.uri;
1830
+ const loaded = {
1831
+ tileset: result.tileset,
1832
+ ...result.baseUri ? { baseUri: result.baseUri } : {}
1833
+ };
1834
+ const document = await this.createDocument(`${node.document.id}/${content.id}`, documentUri, loaded);
1835
+ const child = this.createNode(document.tileset.root, document, node, `external-${node.contents.indexOf(content)}`);
1836
+ node.children.push(child);
1837
+ const hookContext = {
1838
+ runtimeId: this.id,
1839
+ uri: documentUri,
1840
+ parentDocumentUri: node.document.uri,
1841
+ loaded,
1842
+ document
1843
+ };
1844
+ await this.invokeHooks("afterTilesetLoad", (hook) => hook.afterTilesetLoad?.(hookContext), node, content);
1845
+ return;
1846
+ }
1847
+ content.kind = 3 /* Empty */;
1848
+ }
1849
+ /**
1850
+ * Re-derives the spatial state of a tile from a bounding volume measured on its content.
1851
+ * The serialized tile stays unchanged; only the runtime state uses the measured volume.
1852
+ */
1853
+ refineTileBoundingVolume(node, measured) {
1854
+ node.contentBounds = measured;
1855
+ const heightRange = node.contentHeights?.();
1856
+ node.spatial = this.adapter.spatial.derive({
1857
+ tile: { ...node.source, boundingVolume: measured() },
1858
+ ...node.parent ? { parent: node.parent.spatial } : {},
1859
+ ...heightRange ? { heightRange } : {}
1860
+ });
1861
+ node.contentBoundsRefined = true;
1862
+ this.events.emit({ type: "tile-bounds-refined", tile: node, origin: "content" });
1863
+ }
1864
+ /**
1865
+ * Resolves the bounding volumes of materialized implicit children again once their parent content is ready.
1866
+ *
1867
+ * An implicit resolver may derive child volumes from the parent content, for example the quadrant height ranges
1868
+ * of a DEM. Children materialized before that content arrived would otherwise keep their initial volume, be culled
1869
+ * and never load. Children whose own content already reported a measured volume are left unchanged.
1870
+ */
1871
+ refreshImplicitChildBounds(node) {
1872
+ for (const child of node.children) {
1873
+ if (!child.implicit || child.contentBoundsRefined || !this.implicitResolver(child.implicit.context)) continue;
1874
+ const resolved = this.createImplicitTileSource(child.implicit, child.document);
1875
+ child.spatial = this.adapter.spatial.derive({
1876
+ tile: { ...child.source, boundingVolume: resolved.boundingVolume },
1877
+ parent: node.spatial,
1878
+ ...child.implicit.heightRange ? { heightRange: child.implicit.heightRange } : {}
1879
+ });
1880
+ this.events.emit({ type: "tile-bounds-refined", tile: child, origin: "parent-content" });
1881
+ }
1882
+ }
1883
+ /** Derives every tile again, parents first, after a change of the vertical scale. */
1884
+ refreshSpatialStates() {
1885
+ this.spatialStale = false;
1886
+ const visit = (node) => {
1887
+ const boundingVolume = node.contentBounds?.() ?? (node.implicit && this.implicitResolver(node.implicit.context) ? this.createImplicitTileSource(node.implicit, node.document).boundingVolume : node.source.boundingVolume);
1888
+ const heightRange = node.contentHeights?.() ?? node.implicit?.heightRange;
1889
+ node.spatial = this.adapter.spatial.derive({
1890
+ tile: { ...node.source, boundingVolume },
1891
+ ...node.parent ? { parent: node.parent.spatial } : {},
1892
+ ...heightRange ? { heightRange } : {}
1893
+ });
1894
+ this.events.emit({ type: "tile-bounds-refined", tile: node, origin: "vertical-scale" });
1895
+ for (const child of node.children) visit(child);
1896
+ };
1897
+ if (this.root) visit(this.root);
1898
+ }
1899
+ refreshNodeReadiness(node) {
1900
+ if (node.contents.length === 0) {
1901
+ node.readinessState = 0 /* Idle */;
1902
+ return;
1903
+ }
1904
+ if (node.contents.every((content) => content.status === 3 /* Ready */)) {
1905
+ node.readinessState = 3 /* Ready */;
1906
+ return;
1907
+ }
1908
+ if (node.contents.some((content) => content.status === 2 /* Preparing */)) {
1909
+ node.readinessState = 2 /* Preparing */;
1910
+ return;
1911
+ }
1912
+ if (node.contents.some((content) => content.status === 1 /* Queued */)) {
1913
+ node.readinessState = 1 /* Queued */;
1914
+ return;
1915
+ }
1916
+ if (node.contents.every((content) => content.status === 5 /* Cancelled */)) {
1917
+ node.readinessState = 5 /* Cancelled */;
1918
+ return;
1919
+ }
1920
+ if (node.contents.every(
1921
+ (content) => content.status === 4 /* Failed */ || content.status === 5 /* Cancelled */
1922
+ )) {
1923
+ node.readinessState = 4 /* Failed */;
1924
+ return;
1925
+ }
1926
+ node.readinessState = 0 /* Idle */;
1927
+ }
1928
+ async activateNode(node) {
1929
+ const wasSelected = node.selected;
1930
+ const readyContents = node.contents.filter(
1931
+ (content) => content.kind === 1 /* Renderable */ && content.status === 3 /* Ready */ && content.handle !== void 0
1932
+ );
1933
+ const hasNewContent = readyContents.some((content) => !content.attached);
1934
+ if (wasSelected && !hasNewContent) return;
1935
+ const tileSnapshot = await this.resolveMetadata(node);
1936
+ const snapshots = [];
1937
+ for (const content of readyContents) {
1938
+ const snapshot = await this.resolveMetadata(node, content.descriptor, content.featureMetadata);
1939
+ snapshots.push(snapshot);
1940
+ }
1941
+ if (snapshots.length === 0) snapshots.push(tileSnapshot);
1942
+ node.metadataSnapshots = snapshots;
1943
+ if (this.adapter.presentation) {
1944
+ if (!wasSelected || hasNewContent) {
1945
+ node.presentationState = 1 /* Presenting */;
1946
+ try {
1947
+ await this.adapter.presentation.present(this.pipelinePresentationContext(node, readyContents));
1948
+ for (const content of readyContents) {
1949
+ content.attached = true;
1950
+ content.lastTouchedFrame = this.frame;
1951
+ }
1952
+ } catch (error) {
1953
+ node.presentationState = 0 /* Hidden */;
1954
+ await this.reportError("content.present", error, node);
1955
+ return;
1956
+ }
1957
+ }
1958
+ } else {
1959
+ const contentAdapter = this.adapter.content;
1960
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
1961
+ for (const content of readyContents) {
1962
+ if (content.attached) continue;
1963
+ const snapshot = this.metadataStore.get(content.metadataHandle);
1964
+ const presentation = this.presentationContext(node, content, snapshot);
1965
+ const hookContext = {
1966
+ runtimeId: this.id,
1967
+ tile: node,
1968
+ content,
1969
+ metadata: snapshot
1970
+ };
1971
+ await this.invokeHooks("beforeContentAttach", (hook) => hook.beforeContentAttach?.(hookContext), node, content);
1972
+ try {
1973
+ await contentAdapter.attach(presentation);
1974
+ content.attached = true;
1975
+ content.lastTouchedFrame = this.frame;
1976
+ this.recordMetric({
1977
+ name: "tile.attach",
1978
+ value: 1,
1979
+ unit: "count",
1980
+ tags: { runtime: this.id, tile: node.id }
1981
+ });
1982
+ await this.invokeHooks("afterContentAttach", (hook) => hook.afterContentAttach?.(hookContext), node, content);
1983
+ } catch (error) {
1984
+ await this.reportError("content.attach", error, node, content);
1985
+ }
1986
+ }
1987
+ }
1988
+ if (this.adapter.glyphs) {
1989
+ if (node.glyphHandles.length > 0) await this.revokeGlyphs(node);
1990
+ const tileHookContext = { runtimeId: this.id, tile: node };
1991
+ await this.invokeHooks("beforeGlyphPublish", (hook) => hook.beforeGlyphPublish?.(tileHookContext), node);
1992
+ try {
1993
+ const handles = await this.adapter.glyphs.publish(this.glyphContext(node));
1994
+ node.glyphHandles = [...handles];
1995
+ await this.invokeHooks("afterGlyphPublish", (hook) => hook.afterGlyphPublish?.(tileHookContext), node);
1996
+ } catch (error) {
1997
+ await this.reportError("glyph.publish", error, node);
1998
+ }
1999
+ }
2000
+ node.selected = true;
2001
+ if (!wasSelected) {
2002
+ const context = { runtimeId: this.id, tile: node };
2003
+ await this.invokeHooks("onTileSelected", (hook) => hook.onTileSelected?.(context), node);
2004
+ this.events.emit({ type: "tile-selected", tile: node });
2005
+ }
2006
+ }
2007
+ async deactivateNode(node) {
2008
+ if (!node.selected) return;
2009
+ await this.revokeGlyphs(node);
2010
+ const attached = node.contents.filter(
2011
+ (content) => content.attached && content.handle !== void 0
2012
+ );
2013
+ if (this.adapter.presentation) {
2014
+ node.presentationState = 3 /* Hiding */;
2015
+ try {
2016
+ await this.adapter.presentation.hide(this.pipelinePresentationContext(node, attached));
2017
+ for (const content of attached) {
2018
+ content.attached = false;
2019
+ content.lastTouchedFrame = this.frame;
2020
+ }
2021
+ } catch (error) {
2022
+ await this.reportError("content.hide", error, node);
2023
+ }
2024
+ } else {
2025
+ const contentAdapter = this.adapter.content;
2026
+ if (!contentAdapter) throw new Error("The legacy content adapter is not configured.");
2027
+ for (const content of attached) {
2028
+ const snapshot = node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ?? await this.resolveMetadata(node, content.descriptor);
2029
+ const presentation = this.presentationContext(node, content, snapshot);
2030
+ const hookContext = {
2031
+ runtimeId: this.id,
2032
+ tile: node,
2033
+ content,
2034
+ metadata: snapshot
2035
+ };
2036
+ await this.invokeHooks("beforeContentDetach", (hook) => hook.beforeContentDetach?.(hookContext), node, content);
2037
+ try {
2038
+ await contentAdapter.detach(presentation);
2039
+ content.attached = false;
2040
+ content.lastTouchedFrame = this.frame;
2041
+ this.recordMetric({
2042
+ name: "tile.detach",
2043
+ value: 1,
2044
+ unit: "count",
2045
+ tags: { runtime: this.id, tile: node.id }
2046
+ });
2047
+ await this.invokeHooks("afterContentDetach", (hook) => hook.afterContentDetach?.(hookContext), node, content);
2048
+ } catch (error) {
2049
+ await this.reportError("content.detach", error, node, content);
2050
+ }
2051
+ }
2052
+ }
2053
+ node.selected = false;
2054
+ const context = { runtimeId: this.id, tile: node };
2055
+ await this.invokeHooks("onTileDeselected", (hook) => hook.onTileDeselected?.(context), node);
2056
+ this.events.emit({ type: "tile-deselected", tile: node });
2057
+ }
2058
+ async resolveMetadata(node, content, features) {
2059
+ const runtimeContent = content ? node.contents.find((candidate) => candidate.descriptor === content) : void 0;
2060
+ const existingHandle = runtimeContent?.metadataHandle ?? node.metadataHandle;
2061
+ const existing = this.metadataStore.tryGet(existingHandle);
2062
+ if (existing) return existing;
2063
+ node.metadataState = 1 /* Resolving */;
2064
+ const tileContext = { runtimeId: this.id, tile: node };
2065
+ await this.invokeHooks("beforeMetadataResolve", (hook) => hook.beforeMetadataResolve?.(tileContext), node);
2066
+ const ancestors = [];
2067
+ let parent = node.parent;
2068
+ while (parent) {
2069
+ ancestors.unshift({ id: parent.id, tile: parent.source, document: parent.document.metadata });
2070
+ parent = parent.parent;
2071
+ }
2072
+ let snapshot;
2073
+ try {
2074
+ snapshot = this.metadataResolver.resolve({
2075
+ document: node.document.metadata,
2076
+ tileId: node.id,
2077
+ tile: node.source,
2078
+ ancestors,
2079
+ ...node.implicit?.subtree.loaded?.subtree.subtreeMetadata ? {
2080
+ subtree: {
2081
+ id: node.implicit.subtree.uri,
2082
+ entity: node.implicit.subtree.loaded.subtree.subtreeMetadata,
2083
+ documentUri: node.implicit.subtree.uri
2084
+ }
2085
+ } : {},
2086
+ ...content ? { content } : {},
2087
+ ...features ? { features } : {}
2088
+ });
2089
+ } catch (error) {
2090
+ node.metadataState = 3 /* Failed */;
2091
+ throw error;
2092
+ }
2093
+ const metadataHandle = this.metadataStore.register(snapshot);
2094
+ if (content) {
2095
+ if (runtimeContent) {
2096
+ runtimeContent.metadataHandle = metadataHandle;
2097
+ if (features && features.length > 0) runtimeContent.featureMetadataHandle = metadataHandle;
2098
+ }
2099
+ } else {
2100
+ node.metadataHandle = metadataHandle;
2101
+ }
2102
+ node.metadataState = 2 /* Ready */;
2103
+ for (const diagnostic of snapshot.diagnostics) {
2104
+ this.recordMetric({
2105
+ name: "metadata.diagnostic",
2106
+ value: 1,
2107
+ unit: "count",
2108
+ tags: { runtime: this.id, tile: node.id, code: diagnostic.code, severity: diagnostic.severity }
2109
+ });
2110
+ }
2111
+ const hookContext = { ...tileContext, snapshot };
2112
+ await this.invokeHooks("afterMetadataResolve", (hook) => hook.afterMetadataResolve?.(hookContext), node);
2113
+ this.events.emit({ type: "metadata-resolved", tile: node, snapshot });
2114
+ return snapshot;
2115
+ }
2116
+ async initializeRoot() {
2117
+ const hookContext = { runtimeId: this.id, uri: this.uri };
2118
+ await this.invokeHooks("beforeTilesetLoad", (hook) => hook.beforeTilesetLoad?.(hookContext));
2119
+ const startedAt = this.startTiming();
2120
+ try {
2121
+ const loaded = await this.adapter.tilesets.load({ uri: this.uri, signal: this.lifecycleController.signal });
2122
+ const document = await this.createDocument(this.id, this.uri, loaded);
2123
+ this.rootDocument = document;
2124
+ this.rootNode = this.createNode(document.tileset.root, document, void 0, "root");
2125
+ this.recordMetric({
2126
+ name: "tileset.load",
2127
+ value: this.elapsed(startedAt),
2128
+ unit: "millisecond",
2129
+ tags: { runtime: this.id, document: this.uri }
2130
+ });
2131
+ const loadedContext = { ...hookContext, loaded, document };
2132
+ await this.invokeHooks("afterTilesetLoad", (hook) => hook.afterTilesetLoad?.(loadedContext));
2133
+ this.events.emit({ type: "tileset-ready", document });
2134
+ const cameraSubscription = this.adapter.camera?.subscribe((camera) => {
2135
+ this.onCameraChanged(camera);
2136
+ void this.processFrame().catch((error) => this.reportError("camera.update", error));
2137
+ });
2138
+ if (cameraSubscription) this.cameraSubscription = cameraSubscription;
2139
+ const currentCamera = this.adapter.camera?.current?.();
2140
+ if (currentCamera !== void 0)
2141
+ queueMicrotask(() => void this.update(currentCamera).catch((error) => this.reportError("camera.update", error)));
2142
+ } catch (error) {
2143
+ await this.reportError("tileset.load", error);
2144
+ throw error;
2145
+ }
2146
+ }
2147
+ async createDocument(id, uri, loaded) {
2148
+ const baseUri = loaded.baseUri ?? this.uriResolver.baseOf(uri);
2149
+ const diagnostics = [];
2150
+ let schema = loaded.tileset.schema;
2151
+ let schemaUri;
2152
+ if (loaded.tileset.schemaUri) {
2153
+ schemaUri = this.uriResolver.resolve(loaded.tileset.schemaUri, baseUri);
2154
+ if (this.adapter.metadataSchemas) {
2155
+ try {
2156
+ schema = await this.adapter.metadataSchemas.load({
2157
+ uri: schemaUri,
2158
+ documentUri: uri,
2159
+ signal: this.lifecycleController.signal
2160
+ });
2161
+ } catch (error) {
2162
+ diagnostics.push({
2163
+ code: "METADATA_SCHEMA_LOAD_FAILED",
2164
+ severity: "error",
2165
+ message: `Could not load metadata schema "${schemaUri}": ${String(error)}`,
2166
+ path: "$.schemaUri",
2167
+ documentUri: uri
2168
+ });
2169
+ }
2170
+ } else {
2171
+ diagnostics.push({
2172
+ code: "METADATA_SCHEMA_LOADER_MISSING",
2173
+ severity: "warning",
2174
+ message: `A metadata schema loader is required for "${schemaUri}".`,
2175
+ path: "$.schemaUri",
2176
+ documentUri: uri
2177
+ });
2178
+ }
2179
+ }
2180
+ const metadata = {
2181
+ uri,
2182
+ tileset: loaded.tileset,
2183
+ ...schema ? { schema } : {},
2184
+ ...schemaUri ? { schemaUri } : {},
2185
+ diagnostics
2186
+ };
2187
+ return {
2188
+ id,
2189
+ uri,
2190
+ baseUri,
2191
+ tileset: loaded.tileset,
2192
+ metadata
2193
+ };
2194
+ }
2195
+ createNode(tile, document, parent, segment, implicit) {
2196
+ const id = parent ? `${parent.id}/${segment}` : `${this.id}/${segment}`;
2197
+ let source = tile;
2198
+ let implicitState = implicit;
2199
+ if (tile.implicitTiling && !implicitState) {
2200
+ const contentTemplates = tile.contents ? [...tile.contents] : tile.content ? [tile.content] : [];
2201
+ const context = {
2202
+ id,
2203
+ rootTile: tile,
2204
+ implicitTiling: tile.implicitTiling,
2205
+ contentTemplates
2206
+ };
2207
+ const coordinates = {
2208
+ level: 0,
2209
+ x: 0,
2210
+ y: 0,
2211
+ ...tile.implicitTiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}
2212
+ };
2213
+ const subtree = this.createImplicitSubtree(context, coordinates, document);
2214
+ implicitState = {
2215
+ context,
2216
+ coordinates,
2217
+ localCoordinates: coordinates,
2218
+ subtree,
2219
+ childrenMaterialized: false,
2220
+ metadataApplied: false
2221
+ };
2222
+ source = this.createImplicitTileSource(implicitState, document, true);
2223
+ }
2224
+ const spatial = this.adapter.spatial.derive({
2225
+ tile: source,
2226
+ ...parent ? { parent: parent.spatial } : {},
2227
+ ...implicitState?.heightRange ? { heightRange: implicitState.heightRange } : {}
2228
+ });
2229
+ const descriptors = implicitState ? [] : source.contents ? [...source.contents] : source.content ? [source.content] : [];
2230
+ const refinementMode = source.refine === "ADD" ? 0 /* Add */ : source.refine === "REPLACE" ? 1 /* Replace */ : parent?.refinementMode ?? 1 /* Replace */;
2231
+ const contents = descriptors.map(
2232
+ (descriptor, index) => new Tile3DContent(
2233
+ `${id}/content-${index}`,
2234
+ descriptor,
2235
+ this.uriResolver.resolve(descriptor.uri, document.baseUri),
2236
+ this.frame
2237
+ )
2238
+ );
2239
+ const node = new Tile3D({
2240
+ id,
2241
+ source,
2242
+ document,
2243
+ ...parent ? { parent } : {},
2244
+ ...implicitState ? { implicit: implicitState } : {},
2245
+ depth: parent ? parent.depth + 1 : 0,
2246
+ refinementMode,
2247
+ spatial,
2248
+ contents,
2249
+ frame: this.frame
2250
+ });
2251
+ this.nodes.set(id, node);
2252
+ if (implicitState?.subtree.status === 3 /* Ready */) this.applyImplicitContents(node);
2253
+ for (let index = 0; index < (source.children?.length ?? 0); index++) {
2254
+ const child = source.children?.[index];
2255
+ if (child) node.children.push(this.createNode(child, document, node, String(index)));
2256
+ }
2257
+ return node;
2258
+ }
2259
+ createImplicitSubtree(context, coordinates, document) {
2260
+ const reference = expandImplicitTemplate(context.implicitTiling.subtrees.uri, coordinates);
2261
+ return {
2262
+ uri: this.uriResolver.resolve(reference, document.baseUri),
2263
+ coordinates,
2264
+ status: 0 /* Idle */,
2265
+ attempts: 0,
2266
+ estimatedBytes: 0,
2267
+ lastTouchedFrame: this.frame
2268
+ };
2269
+ }
2270
+ createImplicitTileSource(implicit, document, root = false) {
2271
+ const computed = computeImplicitTile(implicit.context.rootTile, implicit.context.implicitTiling, implicit.coordinates);
2272
+ const override = this.implicitResolver(implicit.context)?.resolve({
2273
+ documentUri: document.uri,
2274
+ rootTile: implicit.context.rootTile,
2275
+ implicitTiling: implicit.context.implicitTiling,
2276
+ coordinates: implicit.coordinates,
2277
+ computedBoundingVolume: computed.boundingVolume,
2278
+ computedGeometricError: computed.geometricError,
2279
+ computedContents: computed.contents
2280
+ });
2281
+ if (override?.heightRange) implicit.heightRange = override.heightRange;
2282
+ else delete implicit.heightRange;
2283
+ return {
2284
+ boundingVolume: override?.boundingVolume ?? computed.boundingVolume,
2285
+ geometricError: override?.geometricError ?? computed.geometricError,
2286
+ refine: implicit.context.rootTile.refine ?? "REPLACE",
2287
+ ...root && implicit.context.rootTile.transform ? { transform: implicit.context.rootTile.transform } : {},
2288
+ ...override?.metadata ? { metadata: override.metadata } : {}
2289
+ };
2290
+ }
2291
+ implicitContents(node) {
2292
+ const implicit = node.implicit;
2293
+ if (!implicit) return [];
2294
+ const computed = computeImplicitTile(implicit.context.rootTile, implicit.context.implicitTiling, implicit.coordinates);
2295
+ const override = this.implicitResolver(implicit.context)?.resolve({
2296
+ documentUri: node.document.uri,
2297
+ rootTile: implicit.context.rootTile,
2298
+ implicitTiling: implicit.context.implicitTiling,
2299
+ coordinates: implicit.coordinates,
2300
+ computedBoundingVolume: computed.boundingVolume,
2301
+ computedGeometricError: computed.geometricError,
2302
+ computedContents: computed.contents
2303
+ });
2304
+ return override?.contents ?? computed.contents;
2305
+ }
2306
+ applyImplicitContents(node) {
2307
+ const implicit = node.implicit;
2308
+ const availability = implicit?.subtree.availability;
2309
+ const loaded = implicit?.subtree.loaded;
2310
+ if (!implicit || !availability || !loaded || node.contents.length > 0) return;
2311
+ const decoded = this.adapter.implicitMetadata?.decode({
2312
+ loaded,
2313
+ availability,
2314
+ ...node.document.metadata.schema ? { schema: node.document.metadata.schema } : {},
2315
+ implicitTiling: implicit.context.implicitTiling,
2316
+ coordinates: implicit.coordinates,
2317
+ localCoordinates: implicit.localCoordinates,
2318
+ contentCount: implicit.context.contentTemplates.length
2319
+ });
2320
+ if (!implicit.metadataApplied) {
2321
+ if (decoded?.tileMetadata) node.source.metadata = decoded.tileMetadata;
2322
+ implicit.metadataApplied = true;
2323
+ }
2324
+ const available = this.implicitContents(node).map((descriptor, index) => ({
2325
+ descriptor: decoded?.contentMetadata?.[index] ? { ...descriptor, metadata: decoded.contentMetadata[index] } : descriptor,
2326
+ index
2327
+ })).filter(({ index }) => availability.isContentAvailable(index, implicit.localCoordinates));
2328
+ if (available.length === 0) return;
2329
+ if (implicit.context.contentTemplates.length === 1) node.source.content = available[0].descriptor;
2330
+ else node.source.contents = available.map(({ descriptor }) => descriptor);
2331
+ for (const { descriptor, index } of available) {
2332
+ node.contents.push(
2333
+ new Tile3DContent(
2334
+ `${node.id}/content-${index}`,
2335
+ descriptor,
2336
+ this.uriResolver.resolve(descriptor.uri, node.document.baseUri),
2337
+ this.frame
2338
+ )
2339
+ );
2340
+ }
2341
+ this.refreshNodeReadiness(node);
2342
+ }
2343
+ requestImplicitSubtree(node, priority) {
2344
+ const implicit = node.implicit;
2345
+ if (!implicit) return;
2346
+ const subtree = implicit.subtree;
2347
+ const key = `subtree:${implicit.context.id}:${subtree.coordinates.level}:${subtree.coordinates.x}:${subtree.coordinates.y}:${subtree.coordinates.z ?? 0}`;
2348
+ if (subtree.status === 1 /* Queued */) this.followQueuedPriority(key, priority);
2349
+ if (subtree.status !== 0 /* Idle */ && subtree.status !== 4 /* Failed */ && subtree.status !== 5 /* Cancelled */)
2350
+ return;
2351
+ if (subtree.attempts >= this.maxLoadAttempts) return;
2352
+ subtree.status = 1 /* Queued */;
2353
+ subtree.lastTouchedFrame = this.frame;
2354
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2355
+ this.scheduler.enqueue(key, priority, async (signal) => {
2356
+ const startedAt = this.startTiming();
2357
+ subtree.status = 2 /* Preparing */;
2358
+ subtree.attempts++;
2359
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2360
+ const hookContext = {
2361
+ runtimeId: this.id,
2362
+ tile: node,
2363
+ subtree
2364
+ };
2365
+ try {
2366
+ await this.invokeHooks("beforeSubtreeLoad", (hook) => hook.beforeSubtreeLoad?.(hookContext), node);
2367
+ const loader = implicit.context.subtrees ?? this.adapter.subtrees;
2368
+ if (!loader) throw new Error(`Implicit subtree loader is required for ${subtree.uri}.`);
2369
+ const loaded = await loader.load({
2370
+ uri: subtree.uri,
2371
+ documentUri: node.document.uri,
2372
+ coordinates: subtree.coordinates,
2373
+ implicitTiling: implicit.context.implicitTiling,
2374
+ contentCount: implicit.context.contentTemplates.length,
2375
+ signal
2376
+ });
2377
+ if (signal.aborted) {
2378
+ subtree.status = 5 /* Cancelled */;
2379
+ return;
2380
+ }
2381
+ const availability = new LoadedSubtreeAvailability(loaded, implicit.context.implicitTiling);
2382
+ const rootCoordinates = {
2383
+ level: 0,
2384
+ x: 0,
2385
+ y: 0,
2386
+ ...implicit.context.implicitTiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}
2387
+ };
2388
+ if (!availability.isTileAvailable(rootCoordinates))
2389
+ throw new Error(`Subtree ${subtree.uri} does not make its root tile available.`);
2390
+ subtree.loaded = loaded;
2391
+ subtree.availability = availability;
2392
+ subtree.estimatedBytes = this.estimateSubtreeBytes(loaded);
2393
+ subtree.lastTouchedFrame = this.frame;
2394
+ subtree.status = 3 /* Ready */;
2395
+ delete subtree.error;
2396
+ this.applyImplicitContents(node);
2397
+ await this.invokeHooks("afterSubtreeLoad", (hook) => hook.afterSubtreeLoad?.({ ...hookContext, loaded }), node);
2398
+ this.recordMetric({
2399
+ name: "subtree.load",
2400
+ value: 1,
2401
+ unit: "count",
2402
+ tags: { runtime: this.id, tile: node.id }
2403
+ });
2404
+ this.recordDuration("subtree.load.duration", startedAt, { runtime: this.id, tile: node.id });
2405
+ this.recordMetric({
2406
+ name: "subtree.load.bytes",
2407
+ value: subtree.estimatedBytes,
2408
+ unit: "byte",
2409
+ tags: { runtime: this.id, tile: node.id }
2410
+ });
2411
+ } catch (error) {
2412
+ subtree.error = error;
2413
+ subtree.status = signal.aborted ? 5 /* Cancelled */ : 4 /* Failed */;
2414
+ await this.reportError("subtree.load", error, node);
2415
+ } finally {
2416
+ this.events.emit({ type: "subtree-state", tile: node, subtree });
2417
+ this.markDirty();
2418
+ }
2419
+ });
2420
+ }
2421
+ materializeImplicitChildren(node) {
2422
+ const implicit = node.implicit;
2423
+ if (!implicit || implicit.childrenMaterialized || implicit.subtree.status !== 3 /* Ready */ || !implicit.subtree.availability)
2424
+ return;
2425
+ implicit.subtree.lastTouchedFrame = this.frame;
2426
+ implicit.childrenMaterialized = true;
2427
+ const tiling = implicit.context.implicitTiling;
2428
+ if (implicit.coordinates.level + 1 >= tiling.availableLevels) return;
2429
+ const childCount = implicitBranchingFactor(tiling);
2430
+ for (let index = 0; index < childCount; index++) {
2431
+ const coordinates = implicitChildCoordinates(implicit.coordinates, index, tiling.subdivisionScheme);
2432
+ const localCoordinates = implicitLocalCoordinates(coordinates, implicit.subtree.coordinates);
2433
+ const subtreeRoot = localCoordinates.level >= tiling.subtreeLevels;
2434
+ const available = subtreeRoot ? implicit.subtree.availability.isChildSubtreeAvailable(localCoordinates) : implicit.subtree.availability.isTileAvailable(localCoordinates);
2435
+ if (!available) continue;
2436
+ const graft = this.implicitResolver(implicit.context)?.subtreeAt?.({
2437
+ documentUri: node.document.uri,
2438
+ rootTile: implicit.context.rootTile,
2439
+ implicitTiling: tiling,
2440
+ coordinates
2441
+ });
2442
+ if (graft) {
2443
+ node.children.push(this.createGraftedNode(node, graft, `implicit-${index}`));
2444
+ continue;
2445
+ }
2446
+ let subtree = implicit.subtree;
2447
+ let childLocal = localCoordinates;
2448
+ if (subtreeRoot) {
2449
+ subtree = this.createImplicitSubtree(implicit.context, coordinates, node.document);
2450
+ childLocal = {
2451
+ level: 0,
2452
+ x: 0,
2453
+ y: 0,
2454
+ ...tiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}
2455
+ };
2456
+ }
2457
+ const childImplicit = {
2458
+ context: implicit.context,
2459
+ coordinates,
2460
+ localCoordinates: childLocal,
2461
+ subtree,
2462
+ childrenMaterialized: false,
2463
+ metadataApplied: false
2464
+ };
2465
+ const source = this.createImplicitTileSource(childImplicit, node.document);
2466
+ node.children.push(this.createNode(source, node.document, node, `implicit-${index}`, childImplicit));
2467
+ }
2468
+ }
2469
+ /** Resolver of the tiles of an implicit context: the resolver of its registered subtree, or that of the adapter. */
2470
+ implicitResolver(context) {
2471
+ return context.resolver ?? this.adapter.implicitTiles;
2472
+ }
2473
+ /**
2474
+ * Creates the root of a registered implicit subtree in place of an implicit tile: a new implicit context with
2475
+ * the tiling, contents, resolver and subtree loader of the subtree, rooted at the tile.
2476
+ */
2477
+ createGraftedNode(parent, graft, segment) {
2478
+ const tiling = graft.tile.implicitTiling;
2479
+ if (!tiling) throw new Error(`The subtree registered under ${parent.id} has no implicitTiling.`);
2480
+ const context = {
2481
+ id: `${parent.id}/${segment}`,
2482
+ rootTile: graft.tile,
2483
+ implicitTiling: tiling,
2484
+ contentTemplates: graft.tile.contents ? [...graft.tile.contents] : graft.tile.content ? [graft.tile.content] : [],
2485
+ ...graft.resolver ? { resolver: graft.resolver } : parent.implicit?.context.resolver ? { resolver: parent.implicit.context.resolver } : {},
2486
+ ...graft.subtrees ? { subtrees: graft.subtrees } : parent.implicit?.context.subtrees ? { subtrees: parent.implicit.context.subtrees } : {}
2487
+ };
2488
+ const coordinates = {
2489
+ level: 0,
2490
+ x: 0,
2491
+ y: 0,
2492
+ ...tiling.subdivisionScheme === "OCTREE" ? { z: 0 } : {}
2493
+ };
2494
+ const implicit = {
2495
+ context,
2496
+ coordinates,
2497
+ localCoordinates: coordinates,
2498
+ subtree: this.createImplicitSubtree(context, coordinates, parent.document),
2499
+ childrenMaterialized: false,
2500
+ metadataApplied: false
2501
+ };
2502
+ const source = this.createImplicitTileSource(implicit, parent.document, true);
2503
+ return this.createNode(source, parent.document, parent, segment, implicit);
2504
+ }
2505
+ tileContext(node) {
2506
+ return {
2507
+ runtimeId: this.id,
2508
+ tileId: node.id,
2509
+ depth: node.depth,
2510
+ tile: node.source,
2511
+ document: node.document,
2512
+ spatial: node.spatial,
2513
+ ...node.implicit ? { implicitCoordinates: node.implicit.coordinates } : {}
2514
+ };
2515
+ }
2516
+ contentLoadContext(node, content) {
2517
+ return {
2518
+ ...this.tileContext(node),
2519
+ contentId: content.id,
2520
+ content: content.descriptor,
2521
+ uri: content.uri
2522
+ };
2523
+ }
2524
+ presentationContext(node, content, metadata) {
2525
+ return { ...this.contentLoadContext(node, content), handle: content.handle, metadata };
2526
+ }
2527
+ pipelinePresentationContext(node, contents) {
2528
+ return {
2529
+ runtimeId: this.id,
2530
+ tile: node,
2531
+ resources: contents.map((content) => ({
2532
+ content,
2533
+ handle: content.handle,
2534
+ metadataHandle: content.metadataHandle
2535
+ })),
2536
+ tileMetadataHandle: node.metadataHandle,
2537
+ metadataStore: this.metadataStore
2538
+ };
2539
+ }
2540
+ glyphContext(node) {
2541
+ return {
2542
+ ...this.tileContext(node),
2543
+ metadata: node.metadataSnapshots,
2544
+ contentHandles: node.contents.filter(
2545
+ (content) => content.attached && content.handle !== void 0
2546
+ ).map((content) => content.handle)
2547
+ };
2548
+ }
2549
+ async revokeGlyphs(node) {
2550
+ if (!this.adapter.glyphs || node.glyphHandles.length === 0) return;
2551
+ const context = { runtimeId: this.id, tile: node };
2552
+ await this.invokeHooks("beforeGlyphRevoke", (hook) => hook.beforeGlyphRevoke?.(context), node);
2553
+ try {
2554
+ await this.adapter.glyphs.revoke(node.glyphHandles, this.glyphContext(node));
2555
+ node.glyphHandles = [];
2556
+ await this.invokeHooks("afterGlyphRevoke", (hook) => hook.afterGlyphRevoke?.(context), node);
2557
+ } catch (error) {
2558
+ await this.reportError("glyph.revoke", error, node);
2559
+ }
2560
+ }
2561
+ async sweepCache(force = false) {
2562
+ if (!this.cacheOptions.enabled) return;
2563
+ const startedAt = this.startTiming();
2564
+ this.cacheCounters.sweeps++;
2565
+ await this.sweepContentCache(force);
2566
+ await this.sweepSubtreeCache(force);
2567
+ await this.sweepImplicitBranches(force);
2568
+ if (this.instrumentation.enabled) {
2569
+ const state = this.collectStatistics();
2570
+ this.recordMetric({ name: "cache.content.entries", value: state.contents.cached, unit: "count" });
2571
+ this.recordMetric({ name: "cache.content.cpu-bytes", value: state.contents.cpuBytes, unit: "byte" });
2572
+ this.recordMetric({ name: "cache.content.gpu-bytes", value: state.contents.gpuBytes, unit: "byte" });
2573
+ this.recordMetric({ name: "cache.subtree.entries", value: state.subtrees.cached, unit: "count" });
2574
+ this.recordMetric({ name: "cache.subtree.bytes", value: state.subtrees.bytes, unit: "byte" });
2575
+ }
2576
+ this.recordDuration("cache.sweep.duration", startedAt, { runtime: this.id });
2577
+ }
2578
+ async sweepContentCache(force) {
2579
+ const candidates = [];
2580
+ let entries = 0;
2581
+ let cpuBytes = 0;
2582
+ let gpuBytes = 0;
2583
+ for (const node of this.nodes.values()) {
2584
+ for (const candidate of node.contents) {
2585
+ if (candidate.handle === void 0 || candidate.kind !== 1 /* Renderable */ || candidate.status !== 3 /* Ready */)
2586
+ continue;
2587
+ entries++;
2588
+ cpuBytes += candidate.cost?.cpuBytes ?? 0;
2589
+ gpuBytes += candidate.cost?.gpuBytes ?? 0;
2590
+ if (node.selected || candidate.attached || this.replacementFrontNodes.has(node.id)) continue;
2591
+ if (candidate.readyFrame === this.frame) continue;
2592
+ candidates.push({
2593
+ node,
2594
+ content: candidate
2595
+ });
2596
+ }
2597
+ }
2598
+ candidates.sort((left, right) => left.content.lastTouchedFrame - right.content.lastTouchedFrame);
2599
+ const entryBudget = this.contentEntryBudget();
2600
+ for (const candidate of candidates) {
2601
+ const reason = this.contentEvictionReason(candidate.content, entries, cpuBytes, gpuBytes, force, entryBudget);
2602
+ if (!reason) continue;
2603
+ const releasedCpuBytes = candidate.content.cost?.cpuBytes ?? 0;
2604
+ const releasedGpuBytes = candidate.content.cost?.gpuBytes ?? 0;
2605
+ await this.evictContent(candidate.node, candidate.content, reason);
2606
+ entries--;
2607
+ cpuBytes -= releasedCpuBytes;
2608
+ gpuBytes -= releasedGpuBytes;
2609
+ }
2610
+ }
2611
+ /** Records the start time of a frame and forgets the frames older than the cache retention. */
2612
+ recordFrameTime(frame) {
2613
+ const now = this.clock();
2614
+ this.frameTimes.set(frame, now);
2615
+ for (const [oldFrame, startedAt] of this.frameTimes) {
2616
+ if (now - startedAt <= this.cacheOptions.unusedRetentionMilliseconds) break;
2617
+ this.frameTimes.delete(oldFrame);
2618
+ }
2619
+ }
2620
+ /**
2621
+ * Whether a resource last used in a frame has been unused for longer than the cache retention: the retention time,
2622
+ * or the deprecated frame count when the application set one. A frame no longer recorded is older than the
2623
+ * retention time.
2624
+ */
2625
+ isUnusedTooLong(lastTouchedFrame) {
2626
+ const frames = this.cacheOptions.unusedFrameRetention;
2627
+ if (frames !== void 0) return this.frame - lastTouchedFrame > frames;
2628
+ const touchedAt = this.frameTimes.get(lastTouchedFrame);
2629
+ return touchedAt === void 0 || this.clock() - touchedAt > this.cacheOptions.unusedRetentionMilliseconds;
2630
+ }
2631
+ /** Budget of content entries, grown to what the view selects when the budgets are adaptive. */
2632
+ contentEntryBudget() {
2633
+ const { maxContentEntries, workingSetFactor } = this.cacheOptions;
2634
+ if (workingSetFactor <= 0) return maxContentEntries;
2635
+ let selected = 0;
2636
+ for (const node of this.nodes.values()) if (node.selected) selected++;
2637
+ return Math.max(maxContentEntries, selected * workingSetFactor);
2638
+ }
2639
+ /** Budget of materialized tiles, grown to what the traversal visits when the budgets are adaptive. */
2640
+ materializedTileBudget() {
2641
+ const { maxMaterializedTiles, workingSetFactor } = this.cacheOptions;
2642
+ if (workingSetFactor <= 0) return maxMaterializedTiles;
2643
+ let visited = 0;
2644
+ for (const node of this.nodes.values()) if (node.lastTouchedFrame === this.frame) visited++;
2645
+ return Math.max(maxMaterializedTiles, visited * workingSetFactor);
2646
+ }
2647
+ contentEvictionReason(content, entries, cpuBytes, gpuBytes, force, entryBudget) {
2648
+ if (force || this.isUnusedTooLong(content.lastTouchedFrame)) return "stale";
2649
+ if (entries > entryBudget) return "entry-budget";
2650
+ if (cpuBytes > this.cacheOptions.maxContentCpuBytes) return "cpu-budget";
2651
+ if (gpuBytes > this.cacheOptions.maxContentGpuBytes) return "gpu-budget";
2652
+ return void 0;
2653
+ }
2654
+ async evictContent(node, content, reason) {
2655
+ const eviction = {
2656
+ kind: "content",
2657
+ reason,
2658
+ tileId: node.id,
2659
+ resourceId: content.cacheKey ?? content.uri,
2660
+ releasedCpuBytes: content.cost?.cpuBytes ?? 0,
2661
+ releasedGpuBytes: content.cost?.gpuBytes ?? 0,
2662
+ releasedEntries: 1
2663
+ };
2664
+ const hookContext = {
2665
+ runtimeId: this.id,
2666
+ eviction,
2667
+ tile: node,
2668
+ content
2669
+ };
2670
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), node, content);
2671
+ await this.disposeContentHandle(node, content);
2672
+ node.metadataSnapshots = node.metadataSnapshots.filter((snapshot) => snapshot.content !== content.descriptor);
2673
+ this.cacheCounters.contentEvictions++;
2674
+ this.cacheCounters.releasedCpuBytes += eviction.releasedCpuBytes;
2675
+ this.cacheCounters.releasedGpuBytes += eviction.releasedGpuBytes;
2676
+ this.events.emit({ type: "cache-eviction", eviction });
2677
+ this.recordMetric({
2678
+ name: "content.cache.evict",
2679
+ value: 1,
2680
+ unit: "count",
2681
+ tags: { runtime: this.id, tile: node.id, reason }
2682
+ });
2683
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), node, content);
2684
+ }
2685
+ async sweepSubtreeCache(force) {
2686
+ const bySubtree = /* @__PURE__ */ new Map();
2687
+ for (const node of this.nodes.values()) {
2688
+ const subtree = node.implicit?.subtree;
2689
+ if (!subtree) continue;
2690
+ const existing = bySubtree.get(subtree);
2691
+ if (existing) existing.users.push(node);
2692
+ else bySubtree.set(subtree, { node, subtree, users: [node] });
2693
+ }
2694
+ const loaded = [...bySubtree.values()].filter(
2695
+ (entry) => entry.subtree.status === 3 /* Ready */ && entry.subtree.loaded !== void 0
2696
+ );
2697
+ let entries = loaded.length;
2698
+ let bytes = loaded.reduce((total, entry) => total + entry.subtree.estimatedBytes, 0);
2699
+ const candidates = loaded.filter((entry) => !this.isSubtreeProtected(entry)).sort((left, right) => left.subtree.lastTouchedFrame - right.subtree.lastTouchedFrame);
2700
+ for (const candidate of candidates) {
2701
+ const stale = this.isUnusedTooLong(candidate.subtree.lastTouchedFrame);
2702
+ let reason;
2703
+ if (force || stale) reason = "stale";
2704
+ else if (entries > this.cacheOptions.maxSubtreeEntries) reason = "entry-budget";
2705
+ else if (bytes > this.cacheOptions.maxSubtreeBytes) reason = "byte-budget";
2706
+ if (!reason) continue;
2707
+ const releasedBytes = candidate.subtree.estimatedBytes;
2708
+ await this.evictSubtree(candidate, reason);
2709
+ entries--;
2710
+ bytes -= releasedBytes;
2711
+ }
2712
+ }
2713
+ isSubtreeProtected(entry) {
2714
+ if (entry.subtree.status === 1 /* Queued */ || entry.subtree.status === 2 /* Preparing */) return true;
2715
+ return entry.users.some(
2716
+ (node) => node.selected || node.lastTouchedFrame === this.frame || node.glyphHandles.length > 0 || node.contents.some(
2717
+ (content) => content.attached || content.status === 1 /* Queued */ || content.status === 2 /* Preparing */
2718
+ )
2719
+ );
2720
+ }
2721
+ async evictSubtree(entry, reason) {
2722
+ const eviction = {
2723
+ kind: "subtree",
2724
+ reason,
2725
+ tileId: entry.node.id,
2726
+ resourceId: entry.subtree.uri,
2727
+ releasedCpuBytes: entry.subtree.estimatedBytes,
2728
+ releasedGpuBytes: 0,
2729
+ releasedEntries: 1
2730
+ };
2731
+ const hookContext = {
2732
+ runtimeId: this.id,
2733
+ eviction,
2734
+ tile: entry.node,
2735
+ subtree: entry.subtree
2736
+ };
2737
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), entry.node);
2738
+ delete entry.subtree.loaded;
2739
+ delete entry.subtree.availability;
2740
+ delete entry.subtree.error;
2741
+ entry.subtree.status = 0 /* Idle */;
2742
+ entry.subtree.attempts = 0;
2743
+ entry.subtree.estimatedBytes = 0;
2744
+ this.cacheCounters.subtreeEvictions++;
2745
+ this.cacheCounters.releasedCpuBytes += eviction.releasedCpuBytes;
2746
+ this.events.emit({ type: "cache-eviction", eviction });
2747
+ this.recordMetric({
2748
+ name: "subtree.cache.evict",
2749
+ value: 1,
2750
+ unit: "count",
2751
+ tags: { runtime: this.id, tile: entry.node.id, reason }
2752
+ });
2753
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), entry.node);
2754
+ }
2755
+ async sweepImplicitBranches(force) {
2756
+ const tileBudget = this.materializedTileBudget();
2757
+ const candidates = [...this.nodes.values()].filter((node) => this.isImplicitBranchRoot(node)).sort((left, right) => {
2758
+ const age = this.oldestChildFrame(left) - this.oldestChildFrame(right);
2759
+ return age !== 0 ? age : right.depth - left.depth;
2760
+ });
2761
+ for (const parent of candidates) {
2762
+ if (!this.isImplicitBranchRoot(parent)) continue;
2763
+ const descendants = this.branchDescendants(parent);
2764
+ if (descendants.length === 0 || this.isBranchProtected(descendants)) continue;
2765
+ const stale = descendants.every((node) => this.isUnusedTooLong(node.lastTouchedFrame));
2766
+ let reason;
2767
+ if (force || stale) reason = "stale";
2768
+ else if (this.nodes.size > tileBudget) reason = "node-budget";
2769
+ if (!reason) continue;
2770
+ await this.pruneImplicitBranch(parent, descendants, reason);
2771
+ }
2772
+ }
2773
+ isImplicitBranchRoot(node) {
2774
+ const context = node.implicit?.context;
2775
+ return context !== void 0 && node.implicit?.childrenMaterialized === true && node.children.length > 0 && node.children.every((child) => child.implicit?.context === context);
2776
+ }
2777
+ oldestChildFrame(node) {
2778
+ return node.children.reduce((oldest, child) => Math.min(oldest, child.lastTouchedFrame), Number.POSITIVE_INFINITY);
2779
+ }
2780
+ branchDescendants(parent) {
2781
+ const descendants = [];
2782
+ const pending = [...parent.children];
2783
+ while (pending.length > 0) {
2784
+ const node = pending.pop();
2785
+ if (!node) continue;
2786
+ descendants.push(node);
2787
+ pending.push(...node.children);
2788
+ }
2789
+ return descendants;
2790
+ }
2791
+ isBranchProtected(nodes) {
2792
+ return nodes.some(
2793
+ (node) => node.selected || node.lastTouchedFrame === this.frame || node.glyphHandles.length > 0 || node.contents.some(
2794
+ (content) => content.attached || content.status === 1 /* Queued */ || content.status === 2 /* Preparing */
2795
+ )
2796
+ );
2797
+ }
2798
+ async pruneImplicitBranch(parent, descendants, reason) {
2799
+ const releasedCpuBytes = descendants.reduce(
2800
+ (total, node) => total + node.contents.reduce((sum, content) => sum + (content.cost?.cpuBytes ?? 0), 0),
2801
+ 0
2802
+ );
2803
+ const releasedGpuBytes = descendants.reduce(
2804
+ (total, node) => total + node.contents.reduce((sum, content) => sum + (content.cost?.gpuBytes ?? 0), 0),
2805
+ 0
2806
+ );
2807
+ const eviction = {
2808
+ kind: "implicit-branch",
2809
+ reason,
2810
+ tileId: parent.id,
2811
+ resourceId: `${parent.id}/children`,
2812
+ releasedCpuBytes,
2813
+ releasedGpuBytes,
2814
+ releasedEntries: descendants.length
2815
+ };
2816
+ const hookContext = {
2817
+ runtimeId: this.id,
2818
+ eviction,
2819
+ tile: parent
2820
+ };
2821
+ await this.invokeHooks("beforeCacheEviction", (hook) => hook.beforeCacheEviction?.(hookContext), parent);
2822
+ for (const node of [...descendants].sort((left, right) => right.depth - left.depth)) {
2823
+ await this.disposeNodeContent(node);
2824
+ this.refiningNodes.delete(node.id);
2825
+ this.coarseningSince.delete(node.id);
2826
+ this.replacementFrontNodes.delete(node.id);
2827
+ this.nodes.delete(node.id);
2828
+ }
2829
+ parent.children = [];
2830
+ if (parent.implicit) parent.implicit.childrenMaterialized = false;
2831
+ this.cacheCounters.implicitBranchPrunes++;
2832
+ this.cacheCounters.prunedNodes += descendants.length;
2833
+ this.cacheCounters.releasedCpuBytes += releasedCpuBytes;
2834
+ this.cacheCounters.releasedGpuBytes += releasedGpuBytes;
2835
+ this.events.emit({ type: "cache-eviction", eviction });
2836
+ this.recordMetric({
2837
+ name: "tile.node.prune",
2838
+ value: descendants.length,
2839
+ unit: "count",
2840
+ tags: { runtime: this.id, tile: parent.id, reason }
2841
+ });
2842
+ await this.invokeHooks("afterCacheEviction", (hook) => hook.afterCacheEviction?.(hookContext), parent);
2843
+ }
2844
+ async disposeNodeContent(node) {
2845
+ for (const content of node.contents) {
2846
+ if (content.handle === void 0) continue;
2847
+ await this.disposeContentHandle(node, content);
2848
+ }
2849
+ }
2850
+ async disposeContentHandle(node, content) {
2851
+ const refresh = this.refreshes.get(content);
2852
+ this.refreshes.delete(content);
2853
+ this.staleContents.delete(content);
2854
+ this.provisionalContents.delete(content);
2855
+ content.stale = false;
2856
+ if (refresh?.result?.kind === "renderable" && refresh.result.handle !== content.handle) {
2857
+ await this.releaseHandle(node, content, refresh.result.handle);
2858
+ }
2859
+ try {
2860
+ const presentationAdapter = this.adapter.presentation;
2861
+ const contentAdapter = this.adapter.content;
2862
+ if (presentationAdapter?.release) {
2863
+ await presentationAdapter.release(this.pipelinePresentationContext(node, [content]));
2864
+ } else if (contentAdapter?.dispose) {
2865
+ const snapshot = node.metadataSnapshots.find((candidate) => candidate.content === content.descriptor) ?? await this.resolveMetadata(node, content.descriptor);
2866
+ await contentAdapter.dispose(this.presentationContext(node, content, snapshot));
2867
+ }
2868
+ } catch (error) {
2869
+ await this.reportError("content.dispose", error, node, content);
2870
+ } finally {
2871
+ const releasedContent = content;
2872
+ delete releasedContent.handle;
2873
+ delete releasedContent.featureMetadata;
2874
+ delete releasedContent.cacheKey;
2875
+ delete releasedContent.cost;
2876
+ delete releasedContent.error;
2877
+ this.metadataStore.release(releasedContent.metadataHandle);
2878
+ if (releasedContent.featureMetadataHandle !== releasedContent.metadataHandle) {
2879
+ this.metadataStore.release(releasedContent.featureMetadataHandle);
2880
+ }
2881
+ releasedContent.metadataHandle = NO_METADATA;
2882
+ releasedContent.featureMetadataHandle = NO_METADATA;
2883
+ releasedContent.status = 0 /* Idle */;
2884
+ releasedContent.kind = 0 /* Unknown */;
2885
+ releasedContent.attempts = 0;
2886
+ releasedContent.attached = false;
2887
+ releasedContent.readyFrame = -1;
2888
+ this.refreshNodeReadiness(node);
2889
+ }
2890
+ }
2891
+ estimateSubtreeBytes(loaded) {
2892
+ const bufferBytes = loaded.buffers?.reduce((total, buffer) => total + buffer.byteLength, 0) ?? 0;
2893
+ try {
2894
+ return bufferBytes + new TextEncoder().encode(JSON.stringify(loaded.subtree)).byteLength;
2895
+ } catch {
2896
+ return bufferBytes;
2897
+ }
2898
+ }
2899
+ collectStatistics() {
2900
+ const nodes = [...this.nodes.values()];
2901
+ const nodeStatistics = {
2902
+ total: nodes.length,
2903
+ explicit: nodes.filter((node) => !node.implicit).length,
2904
+ implicit: nodes.filter((node) => node.implicit !== void 0).length,
2905
+ selected: nodes.filter((node) => node.selected).length,
2906
+ visible: nodes.filter((node) => node.visible).length,
2907
+ unbalanced: this.unbalancedCount
2908
+ };
2909
+ const contentStatistics = {
2910
+ total: 0,
2911
+ idle: 0,
2912
+ queued: 0,
2913
+ loading: 0,
2914
+ ready: 0,
2915
+ error: 0,
2916
+ cancelled: 0,
2917
+ attached: 0,
2918
+ cached: 0,
2919
+ cpuBytes: 0,
2920
+ gpuBytes: 0,
2921
+ networkBytes: 0
2922
+ };
2923
+ for (const node of nodes) {
2924
+ for (const content of node.contents) {
2925
+ contentStatistics.total++;
2926
+ switch (content.status) {
2927
+ case 0 /* Idle */:
2928
+ contentStatistics.idle++;
2929
+ break;
2930
+ case 1 /* Queued */:
2931
+ contentStatistics.queued++;
2932
+ break;
2933
+ case 2 /* Preparing */:
2934
+ contentStatistics.loading++;
2935
+ break;
2936
+ case 3 /* Ready */:
2937
+ contentStatistics.ready++;
2938
+ break;
2939
+ case 4 /* Failed */:
2940
+ contentStatistics.error++;
2941
+ break;
2942
+ case 5 /* Cancelled */:
2943
+ contentStatistics.cancelled++;
2944
+ break;
2945
+ }
2946
+ if (content.attached) contentStatistics.attached++;
2947
+ if (content.handle !== void 0) contentStatistics.cached++;
2948
+ contentStatistics.cpuBytes += content.cost?.cpuBytes ?? 0;
2949
+ contentStatistics.gpuBytes += content.cost?.gpuBytes ?? 0;
2950
+ contentStatistics.networkBytes += content.cost?.networkBytes ?? 0;
2951
+ }
2952
+ }
2953
+ const subtrees = /* @__PURE__ */ new Set();
2954
+ for (const node of nodes) if (node.implicit) subtrees.add(node.implicit.subtree);
2955
+ const subtreeStatistics = {
2956
+ total: subtrees.size,
2957
+ idle: 0,
2958
+ queued: 0,
2959
+ loading: 0,
2960
+ ready: 0,
2961
+ error: 0,
2962
+ cancelled: 0,
2963
+ cached: 0,
2964
+ bytes: 0
2965
+ };
2966
+ for (const subtree of subtrees) {
2967
+ switch (subtree.status) {
2968
+ case 0 /* Idle */:
2969
+ subtreeStatistics.idle++;
2970
+ break;
2971
+ case 1 /* Queued */:
2972
+ subtreeStatistics.queued++;
2973
+ break;
2974
+ case 2 /* Preparing */:
2975
+ subtreeStatistics.loading++;
2976
+ break;
2977
+ case 3 /* Ready */:
2978
+ subtreeStatistics.ready++;
2979
+ break;
2980
+ case 4 /* Failed */:
2981
+ subtreeStatistics.error++;
2982
+ break;
2983
+ case 5 /* Cancelled */:
2984
+ subtreeStatistics.cancelled++;
2985
+ break;
2986
+ }
2987
+ if (subtree.loaded) subtreeStatistics.cached++;
2988
+ subtreeStatistics.bytes += subtree.estimatedBytes;
2989
+ }
2990
+ return {
2991
+ frame: this.frame,
2992
+ pendingLoads: this.scheduler.size,
2993
+ nodes: nodeStatistics,
2994
+ contents: contentStatistics,
2995
+ subtrees: subtreeStatistics,
2996
+ cache: {
2997
+ enabled: this.cacheOptions.enabled,
2998
+ limits: { ...this.cacheOptions },
2999
+ ...this.cacheCounters
3000
+ }
3001
+ };
3002
+ }
3003
+ startTiming() {
3004
+ return this.instrumentation.enabled ? performance.now() : void 0;
3005
+ }
3006
+ elapsed(startedAt) {
3007
+ return startedAt === void 0 ? 0 : performance.now() - startedAt;
3008
+ }
3009
+ recordDuration(name, startedAt, tags) {
3010
+ if (startedAt === void 0) return;
3011
+ this.recordMetric({ name, value: this.elapsed(startedAt), unit: "millisecond", ...tags ? { tags } : {} });
3012
+ }
3013
+ recordMetric(metric) {
3014
+ if (!this.instrumentation.enabled) return;
3015
+ this.instrumentation.record(metric);
3016
+ try {
3017
+ this.adapter.telemetry?.record(metric);
3018
+ } catch {
3019
+ }
3020
+ }
3021
+ markDirty() {
3022
+ if (!this.disposed) this.refreshNeeded = true;
3023
+ }
3024
+ async invokeHooks(phase, invoke, tile, content) {
3025
+ for (const hook of this.hooks) {
3026
+ try {
3027
+ await invoke(hook);
3028
+ } catch (error) {
3029
+ await this.reportError(`hook.${phase}`, error, tile, content, true);
3030
+ }
3031
+ }
3032
+ }
3033
+ async reportError(phase, error, tile, content, fromHook = false) {
3034
+ this.events.emit({
3035
+ type: "error",
3036
+ phase,
3037
+ error,
3038
+ ...tile ? { tileId: tile.id } : {},
3039
+ ...content ? { contentId: content.id } : {}
3040
+ });
3041
+ this.recordMetric({
3042
+ name: "runtime.error",
3043
+ value: 1,
3044
+ unit: "count",
3045
+ tags: { runtime: this.id, phase, ...tile ? { tile: tile.id } : {} }
3046
+ });
3047
+ if (phase.startsWith("content.")) {
3048
+ this.recordMetric({
3049
+ name: "content.error",
3050
+ value: 1,
3051
+ unit: "count",
3052
+ tags: { runtime: this.id, phase, ...tile ? { tile: tile.id } : {} }
3053
+ });
3054
+ }
3055
+ if (fromHook) return;
3056
+ const context = {
3057
+ runtimeId: this.id,
3058
+ phase,
3059
+ error,
3060
+ ...tile ? { tile } : {},
3061
+ ...content ? { content } : {}
3062
+ };
3063
+ for (const hook of this.hooks) {
3064
+ try {
3065
+ await hook.onError?.(context);
3066
+ } catch {
3067
+ }
3068
+ }
3069
+ }
3070
+ };
3071
+
3072
+ export { DEFAULT_RUNTIME_CACHE_OPTIONS, RuntimeEventHub, RuntimeInstrumentation, TileRuntime, quadtreeBalanceRefinements, quadtreeImbalances, quadtreeTileKey, quadtreeTouches, refineQuadtreeCut, resolveRuntimeCacheOptions };
3073
+ //# sourceMappingURL=index.js.map
3074
+ //# sourceMappingURL=index.js.map