Socket
Socket
Sign inDemoInstall

@loaders.gl/tiles

Package Overview
Dependencies
15
Maintainers
9
Versions
250
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.2.0-alpha.4 to 4.2.0-alpha.5

dist/dist.min.js

66

dist/constants.js

@@ -0,36 +1,38 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
export const TILE_CONTENT_STATE = {
UNLOADED: 0,
LOADING: 1,
PROCESSING: 2,
READY: 3,
EXPIRED: 4,
FAILED: 5
UNLOADED: 0, // Has never been requested
LOADING: 1, // Is waiting on a pending request
PROCESSING: 2, // Request received. Contents are being processed for rendering. Depending on the content, it might make its own requests for external data.
READY: 3, // Ready to render.
EXPIRED: 4, // Is expired and will be unloaded once new content is loaded.
FAILED: 5 // Request failed.
};
export let TILE_REFINEMENT = function (TILE_REFINEMENT) {
TILE_REFINEMENT[TILE_REFINEMENT["ADD"] = 1] = "ADD";
TILE_REFINEMENT[TILE_REFINEMENT["REPLACE"] = 2] = "REPLACE";
return TILE_REFINEMENT;
}({});
export let TILE_TYPE = function (TILE_TYPE) {
TILE_TYPE["EMPTY"] = "empty";
TILE_TYPE["SCENEGRAPH"] = "scenegraph";
TILE_TYPE["POINTCLOUD"] = "pointcloud";
TILE_TYPE["MESH"] = "mesh";
return TILE_TYPE;
}({});
export let TILESET_TYPE = function (TILESET_TYPE) {
TILESET_TYPE["I3S"] = "I3S";
TILESET_TYPE["TILES3D"] = "TILES3D";
return TILESET_TYPE;
}({});
export let LOD_METRIC_TYPE = function (LOD_METRIC_TYPE) {
LOD_METRIC_TYPE["GEOMETRIC_ERROR"] = "geometricError";
LOD_METRIC_TYPE["MAX_SCREEN_THRESHOLD"] = "maxScreenThreshold";
return LOD_METRIC_TYPE;
}({});
export var TILE_REFINEMENT;
(function (TILE_REFINEMENT) {
TILE_REFINEMENT[TILE_REFINEMENT["ADD"] = 1] = "ADD";
TILE_REFINEMENT[TILE_REFINEMENT["REPLACE"] = 2] = "REPLACE"; // Render tile or, if screen space error exceeded, refine to its descendants instead.
})(TILE_REFINEMENT || (TILE_REFINEMENT = {}));
export var TILE_TYPE;
(function (TILE_TYPE) {
TILE_TYPE["EMPTY"] = "empty";
TILE_TYPE["SCENEGRAPH"] = "scenegraph";
TILE_TYPE["POINTCLOUD"] = "pointcloud";
TILE_TYPE["MESH"] = "mesh";
})(TILE_TYPE || (TILE_TYPE = {}));
export var TILESET_TYPE;
(function (TILESET_TYPE) {
TILESET_TYPE["I3S"] = "I3S";
TILESET_TYPE["TILES3D"] = "TILES3D";
})(TILESET_TYPE || (TILESET_TYPE = {}));
export var LOD_METRIC_TYPE;
(function (LOD_METRIC_TYPE) {
LOD_METRIC_TYPE["GEOMETRIC_ERROR"] = "geometricError";
LOD_METRIC_TYPE["MAX_SCREEN_THRESHOLD"] = "maxScreenThreshold";
})(LOD_METRIC_TYPE || (LOD_METRIC_TYPE = {}));
export const TILE3D_OPTIMIZATION_HINT = {
NOT_COMPUTED: -1,
USE_OPTIMIZATION: 1,
SKIP_OPTIMIZATION: 0
NOT_COMPUTED: -1,
USE_OPTIMIZATION: 1,
SKIP_OPTIMIZATION: 0
};
//# sourceMappingURL=constants.js.map

@@ -1,11 +0,11 @@

export type { Tileset3DProps } from './tileset/tileset-3d';
export { Tileset3D } from './tileset/tileset-3d';
export { Tile3D } from './tileset/tile-3d';
export { TilesetTraverser } from './tileset/tileset-traverser';
export { TilesetCache } from './tileset/tileset-cache';
export { createBoundingVolume } from './tileset/helpers/bounding-volume';
export { calculateTransformProps } from './tileset/helpers/transform-utils';
export { getFrameState } from './tileset/helpers/frame-state';
export { getLodStatus } from './tileset/helpers/i3s-lod';
export { TILE_CONTENT_STATE, TILE_REFINEMENT, TILE_TYPE, TILESET_TYPE, LOD_METRIC_TYPE } from './constants';
export type { Tileset3DProps } from "./tileset/tileset-3d.js";
export { Tileset3D } from "./tileset/tileset-3d.js";
export { Tile3D } from "./tileset/tile-3d.js";
export { TilesetTraverser } from "./tileset/tileset-traverser.js";
export { TilesetCache } from "./tileset/tileset-cache.js";
export { createBoundingVolume } from "./tileset/helpers/bounding-volume.js";
export { calculateTransformProps } from "./tileset/helpers/transform-utils.js";
export { getFrameState } from "./tileset/helpers/frame-state.js";
export { getLodStatus } from "./tileset/helpers/i3s-lod.js";
export { TILE_CONTENT_STATE, TILE_REFINEMENT, TILE_TYPE, TILESET_TYPE, LOD_METRIC_TYPE } from "./constants.js";
//# sourceMappingURL=index.d.ts.map

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
export { Tileset3D } from "./tileset/tileset-3d.js";

@@ -10,2 +13,1 @@ export { Tile3D } from "./tileset/tile-3d.js";

export { TILE_CONTENT_STATE, TILE_REFINEMENT, TILE_TYPE, TILESET_TYPE, LOD_METRIC_TYPE } from "./constants.js";
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import { TilesetTraverser } from '../tileset-traverser';
import { TilesetTraverser } from "../tileset-traverser.js";
export declare class Tileset3DTraverser extends TilesetTraverser {

@@ -3,0 +3,0 @@ compareDistanceToCamera(a: any, b: any): number;

@@ -0,42 +1,52 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
import { TILE3D_OPTIMIZATION_HINT, TILE_REFINEMENT } from "../../constants.js";
import { TilesetTraverser } from "../tileset-traverser.js";
export class Tileset3DTraverser extends TilesetTraverser {
compareDistanceToCamera(a, b) {
return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
}
updateTileVisibility(tile, frameState) {
super.updateTileVisibility(tile, frameState);
if (!tile.isVisibleAndInRequestVolume) {
return;
compareDistanceToCamera(a, b) {
// Sort by farthest child first since this is going on a stack
return b._distanceToCamera === 0 && a._distanceToCamera === 0
? b._centerZDepth - a._centerZDepth
: b._distanceToCamera - a._distanceToCamera;
}
const hasChildren = tile.children.length > 0;
if (tile.hasTilesetContent && hasChildren) {
const firstChild = tile.children[0];
this.updateTileVisibility(firstChild, frameState);
tile._visible = firstChild._visible;
return;
updateTileVisibility(tile, frameState) {
super.updateTileVisibility(tile, frameState);
// Optimization - if none of the tile's children are visible then this tile isn't visible
if (!tile.isVisibleAndInRequestVolume) {
return;
}
const hasChildren = tile.children.length > 0;
if (tile.hasTilesetContent && hasChildren) {
// Use the root tile's visibility instead of this tile's visibility.
// The root tile may be culled by the children bounds optimization in which
// case this tile should also be culled.
const firstChild = tile.children[0];
this.updateTileVisibility(firstChild, frameState);
tile._visible = firstChild._visible;
return;
}
if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
tile._visible = false;
return;
}
const replace = tile.refine === TILE_REFINEMENT.REPLACE;
const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
if (replace && useOptimization && hasChildren) {
if (!this.anyChildrenVisible(tile, frameState)) {
tile._visible = false;
return;
}
}
}
if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
tile._visible = false;
return;
meetsScreenSpaceErrorEarly(tile, frameState) {
const { parent } = tile;
if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
return false;
}
// Use parent's geometric error with child's box to see if the tile already meet the SSE
return !this.shouldRefine(tile, frameState, true);
}
const replace = tile.refine === TILE_REFINEMENT.REPLACE;
const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
if (replace && useOptimization && hasChildren) {
if (!this.anyChildrenVisible(tile, frameState)) {
tile._visible = false;
return;
}
}
}
meetsScreenSpaceErrorEarly(tile, frameState) {
const {
parent
} = tile;
if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
return false;
}
return !this.shouldRefine(tile, frameState, true);
}
}
//# sourceMappingURL=tileset-3d-traverser.js.map

@@ -0,25 +1,43 @@

/**
* Counter to register pending tile headers for the particular frameNumber
* Until all tiles are loaded we won't call `onTraversalEnd` callback
*/
export class I3SPendingTilesRegister {
constructor() {
this.frameNumberMap = new Map();
}
register(viewportId, frameNumber) {
const viewportMap = this.frameNumberMap.get(viewportId) || new Map();
const oldCount = viewportMap.get(frameNumber) || 0;
viewportMap.set(frameNumber, oldCount + 1);
this.frameNumberMap.set(viewportId, viewportMap);
}
deregister(viewportId, frameNumber) {
const viewportMap = this.frameNumberMap.get(viewportId);
if (!viewportMap) {
return;
constructor() {
this.frameNumberMap = new Map();
}
const oldCount = viewportMap.get(frameNumber) || 1;
viewportMap.set(frameNumber, oldCount - 1);
}
isZero(viewportId, frameNumber) {
var _this$frameNumberMap$;
const count = ((_this$frameNumberMap$ = this.frameNumberMap.get(viewportId)) === null || _this$frameNumberMap$ === void 0 ? void 0 : _this$frameNumberMap$.get(frameNumber)) || 0;
return count === 0;
}
/**
* Register a new pending tile header for the particular frameNumber
* @param viewportId
* @param frameNumber
*/
register(viewportId, frameNumber) {
const viewportMap = this.frameNumberMap.get(viewportId) || new Map();
const oldCount = viewportMap.get(frameNumber) || 0;
viewportMap.set(frameNumber, oldCount + 1);
this.frameNumberMap.set(viewportId, viewportMap);
}
/**
* Deregister a pending tile header for the particular frameNumber
* @param viewportId
* @param frameNumber
*/
deregister(viewportId, frameNumber) {
const viewportMap = this.frameNumberMap.get(viewportId);
if (!viewportMap) {
return;
}
const oldCount = viewportMap.get(frameNumber) || 1;
viewportMap.set(frameNumber, oldCount - 1);
}
/**
* Check is there are no pending tile headers registered for the particular frameNumber
* @param viewportId
* @param frameNumber
* @returns
*/
isZero(viewportId, frameNumber) {
const count = this.frameNumberMap.get(viewportId)?.get(frameNumber) || 0;
return count === 0;
}
}
//# sourceMappingURL=i3s-pending-tiles-register.js.map

@@ -1,2 +0,2 @@

import { FrameState } from '../helpers/frame-state';
import { FrameState } from "../helpers/frame-state.js";
export declare class I3STileManager {

@@ -3,0 +3,0 @@ private _statusMap;

import { I3SPendingTilesRegister } from "./i3s-pending-tiles-register.js";
const STATUS = {
REQUESTED: 'REQUESTED',
COMPLETED: 'COMPLETED',
ERROR: 'ERROR'
REQUESTED: 'REQUESTED',
COMPLETED: 'COMPLETED',
ERROR: 'ERROR'
};
// A helper class to manage tile metadata fetching
export class I3STileManager {
constructor() {
this._statusMap = void 0;
this.pendingTilesRegister = new I3SPendingTilesRegister();
this._statusMap = {};
}
add(request, key, callback, frameState) {
if (!this._statusMap[key]) {
const {
frameNumber,
viewport: {
id
constructor() {
this.pendingTilesRegister = new I3SPendingTilesRegister();
this._statusMap = {};
}
/**
* Add request to map
* @param request - node metadata request
* @param key - unique key
* @param callback - callback after request completed
* @param frameState - frameState data
*/
add(request, key, callback, frameState) {
if (!this._statusMap[key]) {
const { frameNumber, viewport: { id } } = frameState;
this._statusMap[key] = { request, callback, key, frameState, status: STATUS.REQUESTED };
// Register pending request for the frameNumber
this.pendingTilesRegister.register(id, frameNumber);
request()
.then((data) => {
this._statusMap[key].status = STATUS.COMPLETED;
const { frameNumber: actualFrameNumber, viewport: { id } } = this._statusMap[key].frameState;
// Deregister pending request for the frameNumber
this.pendingTilesRegister.deregister(id, actualFrameNumber);
this._statusMap[key].callback(data, frameState);
})
.catch((error) => {
this._statusMap[key].status = STATUS.ERROR;
const { frameNumber: actualFrameNumber, viewport: { id } } = this._statusMap[key].frameState;
// Deregister pending request for the frameNumber
this.pendingTilesRegister.deregister(id, actualFrameNumber);
callback(error);
});
}
} = frameState;
this._statusMap[key] = {
request,
callback,
key,
frameState,
status: STATUS.REQUESTED
};
this.pendingTilesRegister.register(id, frameNumber);
request().then(data => {
this._statusMap[key].status = STATUS.COMPLETED;
const {
frameNumber: actualFrameNumber,
viewport: {
id
}
} = this._statusMap[key].frameState;
this.pendingTilesRegister.deregister(id, actualFrameNumber);
this._statusMap[key].callback(data, frameState);
}).catch(error => {
this._statusMap[key].status = STATUS.ERROR;
const {
frameNumber: actualFrameNumber,
viewport: {
id
}
} = this._statusMap[key].frameState;
this.pendingTilesRegister.deregister(id, actualFrameNumber);
callback(error);
});
}
}
update(key, frameState) {
if (this._statusMap[key]) {
const {
frameNumber,
viewport: {
id
/**
* Update request if it is still actual for the new frameState
* @param key - unique key
* @param frameState - frameState data
*/
update(key, frameState) {
if (this._statusMap[key]) {
// Deregister pending request for the old frameNumber
const { frameNumber, viewport: { id } } = this._statusMap[key].frameState;
this.pendingTilesRegister.deregister(id, frameNumber);
// Register pending request for the new frameNumber
const { frameNumber: newFrameNumber, viewport: { id: newViewportId } } = frameState;
this.pendingTilesRegister.register(newViewportId, newFrameNumber);
this._statusMap[key].frameState = frameState;
}
} = this._statusMap[key].frameState;
this.pendingTilesRegister.deregister(id, frameNumber);
const {
frameNumber: newFrameNumber,
viewport: {
id: newViewportId
}
} = frameState;
this.pendingTilesRegister.register(newViewportId, newFrameNumber);
this._statusMap[key].frameState = frameState;
}
}
find(key) {
return this._statusMap[key];
}
hasPendingTiles(viewportId, frameNumber) {
return !this.pendingTilesRegister.isZero(viewportId, frameNumber);
}
/**
* Find request in the map
* @param key - unique key
* @returns
*/
find(key) {
return this._statusMap[key];
}
/**
* Check it there are pending tile headers for the particular frameNumber
* @param viewportId
* @param frameNumber
* @returns
*/
hasPendingTiles(viewportId, frameNumber) {
return !this.pendingTilesRegister.isZero(viewportId, frameNumber);
}
}
//# sourceMappingURL=i3s-tile-manager.js.map

@@ -1,3 +0,3 @@

import { TilesetTraverser } from '../tileset-traverser';
import { FrameState } from '../helpers/frame-state';
import { TilesetTraverser } from "../tileset-traverser.js";
import { FrameState } from "../helpers/frame-state.js";
export declare class I3STilesetTraverser extends TilesetTraverser {

@@ -4,0 +4,0 @@ private _tileManager;

@@ -7,62 +7,83 @@ import { load } from '@loaders.gl/core';

export class I3STilesetTraverser extends TilesetTraverser {
constructor(options) {
super(options);
this._tileManager = void 0;
this._tileManager = new I3STileManager();
}
traversalFinished(frameState) {
return !this._tileManager.hasPendingTiles(frameState.viewport.id, this._frameNumber || 0);
}
shouldRefine(tile, frameState) {
tile._lodJudge = getLodStatus(tile, frameState);
return tile._lodJudge === 'DIG';
}
updateChildTiles(tile, frameState) {
const children = tile.header.children || [];
const childTiles = tile.children;
const tileset = tile.tileset;
for (const child of children) {
const extendedId = `${child.id}-${frameState.viewport.id}`;
const childTile = childTiles && childTiles.find(t => t.id === extendedId);
if (!childTile) {
let request = () => this._loadTile(child.id, tileset);
const cachedRequest = this._tileManager.find(extendedId);
if (!cachedRequest) {
if (tileset.tileset.nodePages) {
request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
}
this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
} else {
this._tileManager.update(extendedId, frameState);
constructor(options) {
super(options);
this._tileManager = new I3STileManager();
}
/**
* Check if there are no penging tile header requests,
* that means the traversal is finished and we can call
* following-up callbacks.
*/
traversalFinished(frameState) {
return !this._tileManager.hasPendingTiles(frameState.viewport.id, this._frameNumber || 0);
}
shouldRefine(tile, frameState) {
tile._lodJudge = getLodStatus(tile, frameState);
return tile._lodJudge === 'DIG';
}
updateChildTiles(tile, frameState) {
const children = tile.header.children || [];
// children which are already fetched and constructed as Tile3D instances
const childTiles = tile.children;
const tileset = tile.tileset;
for (const child of children) {
const extendedId = `${child.id}-${frameState.viewport.id}`;
// if child tile is not fetched
const childTile = childTiles && childTiles.find((t) => t.id === extendedId);
if (!childTile) {
let request = () => this._loadTile(child.id, tileset);
const cachedRequest = this._tileManager.find(extendedId);
if (!cachedRequest) {
// eslint-disable-next-line max-depth
if (tileset.tileset.nodePages) {
request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
}
this._tileManager.add(request, extendedId, (header) => this._onTileLoad(header, tile, extendedId), frameState);
}
else {
// update frameNumber since it is still needed in current frame
this._tileManager.update(extendedId, frameState);
}
}
else if (childTile) {
// if child tile is fetched and available
this.updateTile(childTile, frameState);
}
}
} else if (childTile) {
return false;
}
async _loadTile(nodeId, tileset) {
const { loader } = tileset;
const nodeUrl = tileset.getTileUrl(`${tileset.url}/nodes/${nodeId}`);
// load metadata
const options = {
...tileset.loadOptions,
i3s: {
...tileset.loadOptions.i3s,
isTileHeader: true
}
};
return await load(nodeUrl, loader, options);
}
/**
* The callback to init Tile3D instance after loading the tile JSON
* @param {Object} header - the tile JSON from a dataset
* @param {Tile3D} tile - the parent Tile3D instance
* @param {string} extendedId - optional ID to separate copies of a tile for different viewports.
* const extendedId = `${tile.id}-${frameState.viewport.id}`;
* @return {void}
*/
_onTileLoad(header, tile, extendedId) {
// after child tile is fetched
const childTile = new Tile3D(tile.tileset, header, tile, extendedId);
tile.children.push(childTile);
const frameState = this._tileManager.find(childTile.id).frameState;
this.updateTile(childTile, frameState);
}
// after tile fetched, resume traversal if still in current update/traversal frame
if (this._frameNumber === frameState.frameNumber &&
(this.traversalFinished(frameState) ||
new Date().getTime() - this.lastUpdate > this.updateDebounceTime)) {
this.executeTraversal(childTile, frameState);
}
}
return false;
}
async _loadTile(nodeId, tileset) {
const {
loader
} = tileset;
const nodeUrl = tileset.getTileUrl(`${tileset.url}/nodes/${nodeId}`);
const options = {
...tileset.loadOptions,
i3s: {
...tileset.loadOptions.i3s,
isTileHeader: true
}
};
return await load(nodeUrl, loader, options);
}
_onTileLoad(header, tile, extendedId) {
const childTile = new Tile3D(tile.tileset, header, tile, extendedId);
tile.children.push(childTile);
const frameState = this._tileManager.find(childTile.id).frameState;
this.updateTile(childTile, frameState);
if (this._frameNumber === frameState.frameNumber && (this.traversalFinished(frameState) || new Date().getTime() - this.lastUpdate > this.updateDebounceTime)) {
this.executeTraversal(childTile, frameState);
}
}
}
//# sourceMappingURL=i3s-tileset-traverser.js.map

@@ -1,2 +0,2 @@

import type { Tileset3D } from '../tileset-3d';
import type { Tileset3D } from "../tileset-3d.js";
export declare function get3dTilesOptions(tileset: Tileset3D): {

@@ -3,0 +3,0 @@ assetGltfUpAxis: 'X' | 'Y' | 'Z';

export function get3dTilesOptions(tileset) {
return {
assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
};
return {
assetGltfUpAxis: (tileset.asset && tileset.asset.gltfUpAxis) || 'Y'
};
}
//# sourceMappingURL=3d-tiles-options.js.map

@@ -0,1 +1,4 @@

// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
/* eslint-disable */
import { Quaternion, Vector3, Matrix3, Matrix4, degrees } from '@math.gl/core';

@@ -5,5 +8,7 @@ import { BoundingSphere, OrientedBoundingBox } from '@math.gl/culling';

import { assert } from '@loaders.gl/loader-utils';
// const scratchProjectedBoundingSphere = new BoundingSphere();
function defined(x) {
return x !== undefined && x !== null;
return x !== undefined && x !== null;
}
// const scratchMatrix = new Matrix3();
const scratchPoint = new Vector3();

@@ -17,151 +22,287 @@ const scratchScale = new Vector3();

const scratchZAxis = new Vector3();
// const scratchRectangle = new Rectangle();
// const scratchOrientedBoundingBox = new OrientedBoundingBox();
// const scratchTransform = new Matrix4();
/**
* Create a bounding volume from the tile's bounding volume header.
* @param {Object} boundingVolumeHeader The tile's bounding volume header.
* @param {Matrix4} transform The transform to apply to the bounding volume.
* @param [result] The object onto which to store the result.
* @returns The modified result parameter or a new TileBoundingVolume instance if none was provided.
*/
export function createBoundingVolume(boundingVolumeHeader, transform, result) {
assert(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
if (boundingVolumeHeader.box) {
return createBox(boundingVolumeHeader.box, transform, result);
}
if (boundingVolumeHeader.region) {
return createObbFromRegion(boundingVolumeHeader.region);
}
if (boundingVolumeHeader.sphere) {
return createSphere(boundingVolumeHeader.sphere, transform, result);
}
throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
assert(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
// boundingVolume schema:
// https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json
if (boundingVolumeHeader.box) {
return createBox(boundingVolumeHeader.box, transform, result);
}
if (boundingVolumeHeader.region) {
return createObbFromRegion(boundingVolumeHeader.region);
}
if (boundingVolumeHeader.sphere) {
return createSphere(boundingVolumeHeader.sphere, transform, result);
}
throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
}
/**
* Calculate the cartographic bounding box the tile's bounding volume.
* @param {Object} boundingVolumeHeader The tile's bounding volume header.
* @param {BoundingVolume} boundingVolume The bounding volume.
* @returns {CartographicBounds}
*/
export function getCartographicBounds(boundingVolumeHeader, boundingVolume) {
if (boundingVolumeHeader.box) {
return orientedBoundingBoxToCartographicBounds(boundingVolume);
}
if (boundingVolumeHeader.region) {
const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
return [[degrees(west), degrees(south), minHeight], [degrees(east), degrees(north), maxHeight]];
}
if (boundingVolumeHeader.sphere) {
return boundingSphereToCartographicBounds(boundingVolume);
}
throw new Error('Unkown boundingVolume type');
// boundingVolume schema:
// https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json
if (boundingVolumeHeader.box) {
return orientedBoundingBoxToCartographicBounds(boundingVolume);
}
if (boundingVolumeHeader.region) {
// [west, south, east, north, minimum height, maximum height]
// Latitudes and longitudes are in the WGS 84 datum as defined in EPSG 4979 and are in radians.
// Heights are in meters above (or below) the WGS 84 ellipsoid.
const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
return [
[degrees(west), degrees(south), minHeight],
[degrees(east), degrees(north), maxHeight]
];
}
if (boundingVolumeHeader.sphere) {
return boundingSphereToCartographicBounds(boundingVolume);
}
throw new Error('Unkown boundingVolume type');
}
function createBox(box, transform, result) {
const center = new Vector3(box[0], box[1], box[2]);
transform.transform(center, center);
let origin = [];
if (box.length === 10) {
const halfSize = box.slice(3, 6);
const quaternion = new Quaternion();
quaternion.fromArray(box, 6);
const x = new Vector3([1, 0, 0]);
const y = new Vector3([0, 1, 0]);
const z = new Vector3([0, 0, 1]);
x.transformByQuaternion(quaternion);
x.scale(halfSize[0]);
y.transformByQuaternion(quaternion);
y.scale(halfSize[1]);
z.transformByQuaternion(quaternion);
z.scale(halfSize[2]);
origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
} else {
origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
}
const xAxis = transform.transformAsVector(origin.slice(0, 3));
const yAxis = transform.transformAsVector(origin.slice(3, 6));
const zAxis = transform.transformAsVector(origin.slice(6, 9));
const halfAxes = new Matrix3([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
if (defined(result)) {
result.center = center;
result.halfAxes = halfAxes;
// https://math.gl/modules/culling/docs/api-reference/oriented-bounding-box
// 1. A half-axes based representation.
// box: An array of 12 numbers that define an oriented bounding box.
// The first three elements define the x, y, and z values for the center of the box.
// The next three elements (with indices 3, 4, and 5) define the x axis direction and half-length.
// The next three elements (indices 6, 7, and 8) define the y axis direction and half-length.
// The last three elements (indices 9, 10, and 11) define the z axis direction and half-length.
// 2. A half-size-quaternion based representation.
// box: An array of 10 numbers that define an oriented bounding box.
// The first three elements define the x, y, and z values for the center of the box in a right-handed 3-axis (x, y, z) Cartesian coordinate system where the z-axis is up.
// The next three elements (with indices 3, 4, and 5) define the halfSize.
// The last four elements (indices 6, 7, 8 and 10) define the quaternion.
const center = new Vector3(box[0], box[1], box[2]);
transform.transform(center, center);
let origin = [];
if (box.length === 10) {
const halfSize = box.slice(3, 6);
const quaternion = new Quaternion();
quaternion.fromArray(box, 6);
const x = new Vector3([1, 0, 0]);
const y = new Vector3([0, 1, 0]);
const z = new Vector3([0, 0, 1]);
x.transformByQuaternion(quaternion);
x.scale(halfSize[0]);
y.transformByQuaternion(quaternion);
y.scale(halfSize[1]);
z.transformByQuaternion(quaternion);
z.scale(halfSize[2]);
origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
}
else {
origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
}
const xAxis = transform.transformAsVector(origin.slice(0, 3));
const yAxis = transform.transformAsVector(origin.slice(3, 6));
const zAxis = transform.transformAsVector(origin.slice(6, 9));
const halfAxes = new Matrix3([
xAxis[0],
xAxis[1],
xAxis[2],
yAxis[0],
yAxis[1],
yAxis[2],
zAxis[0],
zAxis[1],
zAxis[2]
]);
if (defined(result)) {
result.center = center;
result.halfAxes = halfAxes;
return result;
}
return new OrientedBoundingBox(center, halfAxes);
}
/*
function createBoxFromTransformedRegion(region, transform, initialTransform, result) {
const rectangle = Rectangle.unpack(region, 0, scratchRectangle);
const minimumHeight = region[4];
const maximumHeight = region[5];
const orientedBoundingBox = OrientedBoundingBox.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
Ellipsoid.WGS84,
scratchOrientedBoundingBox
);
const center = orientedBoundingBox.center;
const halfAxes = orientedBoundingBox.halfAxes;
// A region bounding volume is not transformed by the transform in the tileset JSON,
// but may be transformed by additional transforms applied in Cesium.
// This is why the transform is calculated as the difference between the initial transform and the current transform.
transform = Matrix4.multiplyTransformation(
transform,
Matrix4.inverseTransformation(initialTransform, scratchTransform),
scratchTransform
);
center = Matrix4.multiplyByPoint(transform, center, center);
const rotationScale = Matrix4.getRotation(transform, scratchMatrix);
halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes);
if (defined(result) && result instanceof TileOrientedBoundingBox) {
result.update(center, halfAxes);
return result;
}
return new OrientedBoundingBox(center, halfAxes);
return new TileOrientedBoundingBox(center, halfAxes);
}
function createSphere(sphere, transform, result) {
const center = new Vector3(sphere[0], sphere[1], sphere[2]);
transform.transform(center, center);
const scale = transform.getScale(scratchScale);
const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
const radius = sphere[3] * uniformScale;
function createRegion(region, transform, initialTransform, result) {
if (!Matrix4.equalsEpsilon(transform, initialTransform, CesiumMath.EPSILON8)) {
return createBoxFromTransformedRegion(region, transform, initialTransform, result);
}
if (defined(result)) {
result.center = center;
result.radius = radius;
return result;
}
return new BoundingSphere(center, radius);
const rectangleRegion = Rectangle.unpack(region, 0, scratchRectangle);
return new TileBoundingRegion({
rectangle: rectangleRegion,
minimumHeight: region[4],
maximumHeight: region[5]
});
}
*/
function createSphere(sphere, transform, result) {
// Find the transformed center
const center = new Vector3(sphere[0], sphere[1], sphere[2]);
transform.transform(center, center);
const scale = transform.getScale(scratchScale);
const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
const radius = sphere[3] * uniformScale;
if (defined(result)) {
result.center = center;
result.radius = radius;
return result;
}
return new BoundingSphere(center, radius);
}
/**
* Create OrientedBoundingBox instance from region 3D tiles bounding volume
* @param region - region 3D tiles bounding volume
* @returns OrientedBoundingBox instance
*/
function createObbFromRegion(region) {
const [west, south, east, north, minHeight, maxHeight] = region;
const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyByScalar(0.5);
Ellipsoid.WGS84.cartesianToCartographic(centerInCartesian, scratchCenter);
Ellipsoid.WGS84.cartographicToCartesian([degrees(east), scratchCenter[1], scratchCenter[2]], scratchXAxis);
Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], degrees(north), scratchCenter[2]], scratchYAxis);
Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], scratchCenter[1], maxHeight], scratchZAxis);
return createBox([...centerInCartesian, ...scratchXAxis.subtract(centerInCartesian), ...scratchYAxis.subtract(centerInCartesian), ...scratchZAxis.subtract(centerInCartesian)], new Matrix4());
// [west, south, east, north, minimum height, maximum height]
// Latitudes and longitudes are in the WGS 84 datum as defined in EPSG 4979 and are in radians.
// Heights are in meters above (or below) the WGS 84 ellipsoid.
const [west, south, east, north, minHeight, maxHeight] = region;
const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyByScalar(0.5);
Ellipsoid.WGS84.cartesianToCartographic(centerInCartesian, scratchCenter);
Ellipsoid.WGS84.cartographicToCartesian([degrees(east), scratchCenter[1], scratchCenter[2]], scratchXAxis);
Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], degrees(north), scratchCenter[2]], scratchYAxis);
Ellipsoid.WGS84.cartographicToCartesian([scratchCenter[0], scratchCenter[1], maxHeight], scratchZAxis);
return createBox([
...centerInCartesian,
...scratchXAxis.subtract(centerInCartesian),
...scratchYAxis.subtract(centerInCartesian),
...scratchZAxis.subtract(centerInCartesian)
], new Matrix4());
}
/**
* Convert a bounding volume defined by OrientedBoundingBox to cartographic bounds
* @returns {CartographicBounds}
*/
function orientedBoundingBoxToCartographicBounds(boundingVolume) {
const result = emptyCartographicBounds();
const {
halfAxes
} = boundingVolume;
const xAxis = new Vector3(halfAxes.getColumn(0));
const yAxis = new Vector3(halfAxes.getColumn(1));
const zAxis = new Vector3(halfAxes.getColumn(2));
for (let x = 0; x < 2; x++) {
for (let y = 0; y < 2; y++) {
for (let z = 0; z < 2; z++) {
scratchPoint.copy(boundingVolume.center);
scratchPoint.add(xAxis);
scratchPoint.add(yAxis);
scratchPoint.add(zAxis);
addToCartographicBounds(result, scratchPoint);
zAxis.negate();
}
yAxis.negate();
const result = emptyCartographicBounds();
const { halfAxes } = boundingVolume;
const xAxis = new Vector3(halfAxes.getColumn(0));
const yAxis = new Vector3(halfAxes.getColumn(1));
const zAxis = new Vector3(halfAxes.getColumn(2));
// Test all 8 corners of the box
for (let x = 0; x < 2; x++) {
for (let y = 0; y < 2; y++) {
for (let z = 0; z < 2; z++) {
scratchPoint.copy(boundingVolume.center);
scratchPoint.add(xAxis);
scratchPoint.add(yAxis);
scratchPoint.add(zAxis);
addToCartographicBounds(result, scratchPoint);
zAxis.negate();
}
yAxis.negate();
}
xAxis.negate();
}
xAxis.negate();
}
return result;
return result;
}
/**
* Convert a bounding volume defined by BoundingSphere to cartographic bounds
* @returns {CartographicBounds}
*/
function boundingSphereToCartographicBounds(boundingVolume) {
const result = emptyCartographicBounds();
const {
center,
radius
} = boundingVolume;
const point = Ellipsoid.WGS84.scaleToGeodeticSurface(center, scratchPoint);
let zAxis;
if (point) {
zAxis = Ellipsoid.WGS84.geodeticSurfaceNormal(point);
} else {
zAxis = new Vector3(0, 0, 1);
}
let xAxis = new Vector3(zAxis[2], -zAxis[1], 0);
if (xAxis.len() > 0) {
xAxis.normalize();
} else {
xAxis = new Vector3(0, 1, 0);
}
const yAxis = xAxis.clone().cross(zAxis);
for (const axis of [xAxis, yAxis, zAxis]) {
scratchScale.copy(axis).scale(radius);
for (let dir = 0; dir < 2; dir++) {
scratchPoint.copy(center);
scratchPoint.add(scratchScale);
addToCartographicBounds(result, scratchPoint);
scratchScale.negate();
const result = emptyCartographicBounds();
const { center, radius } = boundingVolume;
const point = Ellipsoid.WGS84.scaleToGeodeticSurface(center, scratchPoint);
let zAxis;
if (point) {
zAxis = Ellipsoid.WGS84.geodeticSurfaceNormal(point);
}
}
return result;
else {
zAxis = new Vector3(0, 0, 1);
}
let xAxis = new Vector3(zAxis[2], -zAxis[1], 0);
if (xAxis.len() > 0) {
xAxis.normalize();
}
else {
xAxis = new Vector3(0, 1, 0);
}
const yAxis = xAxis.clone().cross(zAxis);
// Test 6 end points of the 3 axes
for (const axis of [xAxis, yAxis, zAxis]) {
scratchScale.copy(axis).scale(radius);
for (let dir = 0; dir < 2; dir++) {
scratchPoint.copy(center);
scratchPoint.add(scratchScale);
addToCartographicBounds(result, scratchPoint);
// Flip the axis
scratchScale.negate();
}
}
return result;
}
/**
* Create a new cartographic bounds that contains no points
* @returns {CartographicBounds}
*/
function emptyCartographicBounds() {
return [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
return [
[Infinity, Infinity, Infinity],
[-Infinity, -Infinity, -Infinity]
];
}
/**
* Add a point to the target cartographic bounds
* @param {CartographicBounds} target
* @param {Vector3} cartesian coordinates of the point to add
*/
function addToCartographicBounds(target, cartesian) {
Ellipsoid.WGS84.cartesianToCartographic(cartesian, scratchPoint);
target[0][0] = Math.min(target[0][0], scratchPoint[0]);
target[0][1] = Math.min(target[0][1], scratchPoint[1]);
target[0][2] = Math.min(target[0][2], scratchPoint[2]);
target[1][0] = Math.max(target[1][0], scratchPoint[0]);
target[1][1] = Math.max(target[1][1], scratchPoint[1]);
target[1][2] = Math.max(target[1][2], scratchPoint[2]);
Ellipsoid.WGS84.cartesianToCartographic(cartesian, scratchPoint);
target[0][0] = Math.min(target[0][0], scratchPoint[0]);
target[0][1] = Math.min(target[0][1], scratchPoint[1]);
target[0][2] = Math.min(target[0][2], scratchPoint[2]);
target[1][0] = Math.max(target[1][0], scratchPoint[0]);
target[1][1] = Math.max(target[1][1], scratchPoint[1]);
target[1][2] = Math.max(target[1][2], scratchPoint[2]);
}
//# sourceMappingURL=bounding-volume.js.map
import { Tile3D } from '@loaders.gl/tiles';
import { CullingVolume } from '@math.gl/culling';
import { GeospatialViewport } from '../../types';
import { GeospatialViewport } from "../../types.js";
export type FrameState = {

@@ -5,0 +5,0 @@ camera: {

@@ -6,105 +6,124 @@ import { Vector3 } from '@math.gl/core';

const scratchPosition = new Vector3();
const cullingVolume = new CullingVolume([new Plane(), new Plane(), new Plane(), new Plane(), new Plane(), new Plane()]);
const cullingVolume = new CullingVolume([
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane(),
new Plane()
]);
// Extracts a frame state appropriate for tile culling from a deck.gl viewport
// TODO - this could likely be generalized and merged back into deck.gl for other culling scenarios
export function getFrameState(viewport, frameNumber) {
const {
cameraDirection,
cameraUp,
height
} = viewport;
const {
metersPerUnit
} = viewport.distanceScales;
const viewportCenterCartesian = worldToCartesian(viewport, viewport.center);
const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
const cameraDirectionCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
const cameraUpCartesian = new Vector3(enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
commonSpacePlanesToWGS84(viewport);
const ViewportClass = viewport.constructor;
const {
longitude,
latitude,
width,
bearing,
zoom
} = viewport;
const topDownViewport = new ViewportClass({
longitude,
latitude,
height,
width,
bearing,
zoom,
pitch: 0
});
return {
camera: {
position: cameraPositionCartesian,
direction: cameraDirectionCartesian,
up: cameraUpCartesian
},
viewport,
topDownViewport,
height,
cullingVolume,
frameNumber,
sseDenominator: 1.15
};
// Traverse and and request. Update _selectedTiles so that we know what to render.
// Traverse and and request. Update _selectedTiles so that we know what to render.
const { cameraDirection, cameraUp, height } = viewport;
const { metersPerUnit } = viewport.distanceScales;
// TODO - Ellipsoid.eastNorthUpToFixedFrame() breaks on raw array, create a Vector.
// TODO - Ellipsoid.eastNorthUpToFixedFrame() takes a cartesian, is that intuitive?
const viewportCenterCartesian = worldToCartesian(viewport, viewport.center);
const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3());
// These should still be normalized as the transform has scale 1 (goes from meters to meters)
const cameraDirectionCartesian = new Vector3(
// @ts-ignore
enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))).normalize();
const cameraUpCartesian = new Vector3(
// @ts-ignore
enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))).normalize();
commonSpacePlanesToWGS84(viewport);
const ViewportClass = viewport.constructor;
const { longitude, latitude, width, bearing, zoom } = viewport;
// @ts-ignore
const topDownViewport = new ViewportClass({
longitude,
latitude,
height,
width,
bearing,
zoom,
pitch: 0
});
// TODO: make a file/class for frameState and document what needs to be attached to this so that traversal can function
return {
camera: {
position: cameraPositionCartesian,
direction: cameraDirectionCartesian,
up: cameraUpCartesian
},
viewport,
topDownViewport,
height,
cullingVolume,
frameNumber, // TODO: This can be the same between updates, what number is unique for between updates?
sseDenominator: 1.15 // Assumes fovy = 60 degrees
};
}
/**
* Limit `tiles` array length with `maximumTilesSelected` number.
* The criteria for this filtering is distance of a tile center
* to the `frameState.viewport`'s longitude and latitude
* @param tiles - tiles array to filter
* @param frameState - frameState to calculate distances
* @param maximumTilesSelected - maximal amount of tiles in the output array
* @returns new tiles array
*/
export function limitSelectedTiles(tiles, frameState, maximumTilesSelected) {
if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) {
return [tiles, []];
}
const tuples = [];
const {
longitude: viewportLongitude,
latitude: viewportLatitude
} = frameState.viewport;
for (const [index, tile] of tiles.entries()) {
const [longitude, latitude] = tile.header.mbs;
const deltaLon = Math.abs(viewportLongitude - longitude);
const deltaLat = Math.abs(viewportLatitude - latitude);
const distance = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon);
tuples.push([index, distance]);
}
const tuplesSorted = tuples.sort((a, b) => a[1] - b[1]);
const selectedTiles = [];
for (let i = 0; i < maximumTilesSelected; i++) {
selectedTiles.push(tiles[tuplesSorted[i][0]]);
}
const unselectedTiles = [];
for (let i = maximumTilesSelected; i < tuplesSorted.length; i++) {
unselectedTiles.push(tiles[tuplesSorted[i][0]]);
}
return [selectedTiles, unselectedTiles];
if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) {
return [tiles, []];
}
// Accumulate distances in couples array: [tileIndex: number, distanceToViewport: number]
const tuples = [];
const { longitude: viewportLongitude, latitude: viewportLatitude } = frameState.viewport;
for (const [index, tile] of tiles.entries()) {
const [longitude, latitude] = tile.header.mbs;
const deltaLon = Math.abs(viewportLongitude - longitude);
const deltaLat = Math.abs(viewportLatitude - latitude);
const distance = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon);
tuples.push([index, distance]);
}
const tuplesSorted = tuples.sort((a, b) => a[1] - b[1]);
const selectedTiles = [];
for (let i = 0; i < maximumTilesSelected; i++) {
selectedTiles.push(tiles[tuplesSorted[i][0]]);
}
const unselectedTiles = [];
for (let i = maximumTilesSelected; i < tuplesSorted.length; i++) {
unselectedTiles.push(tiles[tuplesSorted[i][0]]);
}
return [selectedTiles, unselectedTiles];
}
function commonSpacePlanesToWGS84(viewport) {
const frustumPlanes = viewport.getFrustumPlanes();
const nearCenterCommon = closestPointOnPlane(frustumPlanes.near, viewport.cameraPosition);
const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon);
const cameraCartesian = worldToCartesian(viewport, viewport.cameraPosition, scratchPosition);
let i = 0;
cullingVolume.planes[i++].fromPointNormal(nearCenterCartesian, scratchVector.copy(nearCenterCartesian).subtract(cameraCartesian));
for (const dir in frustumPlanes) {
if (dir === 'near') {
continue;
// Extract frustum planes based on current view.
const frustumPlanes = viewport.getFrustumPlanes();
// Get the near/far plane centers
const nearCenterCommon = closestPointOnPlane(frustumPlanes.near, viewport.cameraPosition);
const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon);
const cameraCartesian = worldToCartesian(viewport, viewport.cameraPosition, scratchPosition);
let i = 0;
cullingVolume.planes[i++].fromPointNormal(nearCenterCartesian, scratchVector.copy(nearCenterCartesian).subtract(cameraCartesian));
for (const dir in frustumPlanes) {
if (dir === 'near') {
continue; // eslint-disable-line no-continue
}
const plane = frustumPlanes[dir];
const posCommon = closestPointOnPlane(plane, nearCenterCommon, scratchPosition);
const cartesianPos = worldToCartesian(viewport, posCommon, scratchPosition);
cullingVolume.planes[i++].fromPointNormal(cartesianPos,
// Want the normal to point into the frustum since that's what culling expects
scratchVector.copy(nearCenterCartesian).subtract(cartesianPos));
}
const plane = frustumPlanes[dir];
const posCommon = closestPointOnPlane(plane, nearCenterCommon, scratchPosition);
const cartesianPos = worldToCartesian(viewport, posCommon, scratchPosition);
cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector.copy(nearCenterCartesian).subtract(cartesianPos));
}
}
function closestPointOnPlane(plane, refPoint) {
let out = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Vector3();
const distanceToRef = plane.normal.dot(refPoint);
out.copy(plane.normal).scale(plane.distance - distanceToRef).add(refPoint);
return out;
function closestPointOnPlane(plane, refPoint, out = new Vector3()) {
const distanceToRef = plane.normal.dot(refPoint);
out
.copy(plane.normal)
.scale(plane.distance - distanceToRef)
.add(refPoint);
return out;
}
function worldToCartesian(viewport, point) {
let out = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Vector3();
const cartographicPos = viewport.unprojectPosition(point);
return Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, out);
function worldToCartesian(viewport, point, out = new Vector3()) {
const cartographicPos = viewport.unprojectPosition(point);
return Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, out);
}
//# sourceMappingURL=frame-state.js.map

@@ -1,3 +0,3 @@

import { Tile3D } from '../tile-3d';
import { FrameState } from './frame-state';
import { Tile3D } from "../tile-3d.js";
import { FrameState } from "./frame-state.js";
/**

@@ -4,0 +4,0 @@ * For the maxScreenThreshold error metric, maxError means that you should replace the node with it's children

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { Matrix4, Vector3 } from '@math.gl/core';

@@ -10,45 +13,71 @@ import { Ellipsoid } from '@math.gl/geospatial';

const cartesianToEnuMatrix = new Matrix4();
/**
* For the maxScreenThreshold error metric, maxError means that you should replace the node with it's children
as soon as the nodes bounding sphere has a screen radius larger than maxError pixels.
In this sense a value of 0 means you should always load it's children,
or if it's a leaf node, you should always display it.
* @param tile
* @param frameState
* @returns
*/
export function getLodStatus(tile, frameState) {
if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
return 'DIG';
}
const screenSize = 2 * getProjectedRadius(tile, frameState);
if (screenSize < 2) {
if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
return 'DIG';
}
const screenSize = 2 * getProjectedRadius(tile, frameState);
if (screenSize < 2) {
return 'OUT';
}
if (!tile.header.children || screenSize <= tile.lodMetricValue) {
return 'DRAW';
}
else if (tile.header.children) {
return 'DIG';
}
return 'OUT';
}
if (!tile.header.children || screenSize <= tile.lodMetricValue) {
return 'DRAW';
} else if (tile.header.children) {
return 'DIG';
}
return 'OUT';
}
/**
* Calculate size of MBS radius projected on the screen plane
* @param tile
* @param frameState
* @returns
*/
// eslint-disable-next-line max-statements
export function getProjectedRadius(tile, frameState) {
const {
topDownViewport: viewport
} = frameState;
const mbsLat = tile.header.mbs[1];
const mbsLon = tile.header.mbs[0];
const mbsZ = tile.header.mbs[2];
const mbsR = tile.header.mbs[3];
const mbsCenterCartesian = [...tile.boundingVolume.center];
const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian);
toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert();
cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix);
const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
const extraZ = projection * projection / cameraPositionEnu[2];
extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize();
const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian);
const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
const projectedRadius = projectedOriginVector.copy(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
return projectedRadius;
const { topDownViewport: viewport } = frameState;
const mbsLat = tile.header.mbs[1];
const mbsLon = tile.header.mbs[0];
const mbsZ = tile.header.mbs[2];
const mbsR = tile.header.mbs[3];
const mbsCenterCartesian = [...tile.boundingVolume.center];
const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian);
// ---------------------------
// Calculate mbs border vertex
// ---------------------------
toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
// Add extra vector to form plane
Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert();
cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix);
// Mean Proportionals in Right Triangles - Altitude rule
// https://mathbitsnotebook.com/Geometry/RightTriangles/RTmeanRight.html
const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
const extraZ = (projection * projection) / cameraPositionEnu[2];
extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize();
// We need radius vector orthogonal to toEye vector
const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian);
const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
// ---------------------------
// Project center vertex and border vertex and calculate projected radius of MBS
const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
const projectedRadius = projectedOriginVector
.copy(projectedOrigin)
.subtract(projectedMbsBorderVertex)
.magnitude();
return projectedRadius;
}
//# sourceMappingURL=i3s-lod.js.map

@@ -0,1 +1,10 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
// TODO - Dynamic screen space error provides an optimization when looking at
// tilesets from above
/* eslint-disable */
// @ts-nocheck
import { Matrix4, Vector3, clamp } from '@math.gl/core';

@@ -8,94 +17,97 @@ const scratchPositionNormal = new Vector3();

const scratchDirection = new Vector3();
export function calculateDynamicScreenSpaceError(root, _ref) {
let {
camera,
mapProjection
} = _ref;
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
dynamicScreenSpaceErrorHeightFalloff = 0.25,
dynamicScreenSpaceErrorDensity = 0.00278
} = options;
let up;
let direction;
let height;
let minimumHeight;
let maximumHeight;
const tileBoundingVolume = root.contentBoundingVolume;
if (tileBoundingVolume instanceof TileBoundingRegion) {
up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
direction = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = tileBoundingVolume.minimumHeight;
maximumHeight = tileBoundingVolume.maximumHeight;
} else {
const transformLocal = Matrix4.inverseTransformation(root.computedTransform, scratchMatrix);
const ellipsoid = mapProjection.ellipsoid;
const boundingVolume = tileBoundingVolume.boundingVolume;
const centerLocal = Matrix4.multiplyByPoint(transformLocal, boundingVolume.center, scratchCenter);
if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {
const centerCartographic = Cartographic.fromCartesian(centerLocal, ellipsoid, scratchCartographic);
up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
direction = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = 0.0;
maximumHeight = centerCartographic.height * 2.0;
} else {
const positionLocal = Matrix4.multiplyByPoint(transformLocal, camera.positionWC, scratchPosition);
up = Cartesian3.UNIT_Z;
direction = Matrix4.multiplyByPointAsVector(transformLocal, camera.directionWC, scratchDirection);
direction = Cartesian3.normalize(direction, direction);
height = positionLocal.z;
if (tileBoundingVolume instanceof TileOrientedBoundingBox) {
const boxHeight = root._header.boundingVolume.box[11];
minimumHeight = centerLocal.z - boxHeight;
maximumHeight = centerLocal.z + boxHeight;
} else if (tileBoundingVolume instanceof TileBoundingSphere) {
const radius = boundingVolume.radius;
minimumHeight = centerLocal.z - radius;
maximumHeight = centerLocal.z + radius;
}
// eslint-disable-next-line max-statements, complexity
export function calculateDynamicScreenSpaceError(root, { camera, mapProjection }, options = {}) {
const { dynamicScreenSpaceErrorHeightFalloff = 0.25, dynamicScreenSpaceErrorDensity = 0.00278 } = options;
let up;
let direction;
let height;
let minimumHeight;
let maximumHeight;
const tileBoundingVolume = root.contentBoundingVolume;
if (tileBoundingVolume instanceof TileBoundingRegion) {
up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
direction = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = tileBoundingVolume.minimumHeight;
maximumHeight = tileBoundingVolume.maximumHeight;
}
}
const heightFalloff = dynamicScreenSpaceErrorHeightFalloff;
const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
const heightFar = maximumHeight;
const t = clamp((height - heightClose) / (heightFar - heightClose), 0.0, 1.0);
const dot = Math.abs(Cartesian3.dot(direction, up));
let horizonFactor = 1.0 - dot;
horizonFactor = horizonFactor * (1.0 - t);
return dynamicScreenSpaceErrorDensity * horizonFactor;
else {
// Transform camera position and direction into the local coordinate system of the tileset
const transformLocal = Matrix4.inverseTransformation(root.computedTransform, scratchMatrix);
const ellipsoid = mapProjection.ellipsoid;
const boundingVolume = tileBoundingVolume.boundingVolume;
const centerLocal = Matrix4.multiplyByPoint(transformLocal, boundingVolume.center, scratchCenter);
if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {
// The tileset is defined in WGS84. Approximate the minimum and maximum height.
const centerCartographic = Cartographic.fromCartesian(centerLocal, ellipsoid, scratchCartographic);
up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
direction = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = 0.0;
maximumHeight = centerCartographic.height * 2.0;
}
else {
// The tileset is defined in local coordinates (z-up)
const positionLocal = Matrix4.multiplyByPoint(transformLocal, camera.positionWC, scratchPosition);
up = Cartesian3.UNIT_Z;
direction = Matrix4.multiplyByPointAsVector(transformLocal, camera.directionWC, scratchDirection);
direction = Cartesian3.normalize(direction, direction);
height = positionLocal.z;
if (tileBoundingVolume instanceof TileOrientedBoundingBox) {
// Assuming z-up, the last component stores the half-height of the box
const boxHeight = root._header.boundingVolume.box[11];
minimumHeight = centerLocal.z - boxHeight;
maximumHeight = centerLocal.z + boxHeight;
}
else if (tileBoundingVolume instanceof TileBoundingSphere) {
const radius = boundingVolume.radius;
minimumHeight = centerLocal.z - radius;
maximumHeight = centerLocal.z + radius;
}
}
}
// The range where the density starts to lessen. Start at the quarter height of the tileset.
const heightFalloff = dynamicScreenSpaceErrorHeightFalloff;
const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
const heightFar = maximumHeight;
const t = clamp((height - heightClose) / (heightFar - heightClose), 0.0, 1.0);
// Increase density as the camera tilts towards the horizon
const dot = Math.abs(Cartesian3.dot(direction, up));
let horizonFactor = 1.0 - dot;
// Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.
// The goal is to increase density for the "street view", not when viewing the tileset from a distance.
horizonFactor = horizonFactor * (1.0 - t);
return dynamicScreenSpaceErrorDensity * horizonFactor;
}
export function fog(distanceToCamera, density) {
const scalar = distanceToCamera * density;
return 1.0 - Math.exp(-(scalar * scalar));
const scalar = distanceToCamera * density;
return 1.0 - Math.exp(-(scalar * scalar));
}
export function getDynamicScreenSpaceError(tileset, distanceToCamera) {
if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
const density = tileset.dynamicScreenSpaceErrorComputedDensity;
const factor = tileset.dynamicScreenSpaceErrorFactor;
const dynamicError = fog(distanceToCamera, density) * factor;
return dynamicError;
}
return 0;
if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
const density = tileset.dynamicScreenSpaceErrorComputedDensity;
const factor = tileset.dynamicScreenSpaceErrorFactor;
// TODO: Refined screen space error that minimizes tiles in non-first-person
const dynamicError = fog(distanceToCamera, density) * factor;
return dynamicError;
}
return 0;
}
export function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
const tileset = tile.tileset;
const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
if (lodMetricValue === 0.0) {
return 0.0;
}
const distance = Math.max(tile._distanceToCamera, 1e-7);
const {
height,
sseDenominator
} = frameState;
const {
viewDistanceScale
} = tileset.options;
let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
error -= getDynamicScreenSpaceError(tileset, distance);
return error;
const tileset = tile.tileset;
const parentLodMetricValue = (tile.parent && tile.parent.lodMetricValue) || tile.lodMetricValue;
const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
// Leaf tiles do not have any error so save the computation
if (lodMetricValue === 0.0) {
return 0.0;
}
// TODO: Orthographic Frustum needs special treatment?
// this._getOrthograhicScreenSpaceError();
// Avoid divide by zero when viewer is inside the tile
const distance = Math.max(tile._distanceToCamera, 1e-7);
const { height, sseDenominator } = frameState;
const { viewDistanceScale } = tileset.options;
let error = (lodMetricValue * height * (viewDistanceScale || 1.0)) / (distance * sseDenominator);
error -= getDynamicScreenSpaceError(tileset, distance);
return error;
}
//# sourceMappingURL=tiles-3d-lod.js.map

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { Ellipsoid } from '@math.gl/geospatial';

@@ -5,47 +8,45 @@ import { Matrix4, Vector3 } from '@math.gl/core';

export function calculateTransformProps(tileHeader, tile) {
assert(tileHeader);
assert(tile);
const {
rtcCenter,
gltfUpAxis
} = tile;
const {
computedTransform,
boundingVolume: {
center
assert(tileHeader);
assert(tile);
const { rtcCenter, gltfUpAxis } = tile;
const { computedTransform, boundingVolume: { center } } = tileHeader;
let modelMatrix = new Matrix4(computedTransform);
// Translate if appropriate
if (rtcCenter) {
modelMatrix.translate(rtcCenter);
}
} = tileHeader;
let modelMatrix = new Matrix4(computedTransform);
if (rtcCenter) {
modelMatrix.translate(rtcCenter);
}
switch (gltfUpAxis) {
case 'Z':
break;
case 'Y':
const rotationY = new Matrix4().rotateX(Math.PI / 2);
modelMatrix = modelMatrix.multiplyRight(rotationY);
break;
case 'X':
const rotationX = new Matrix4().rotateY(-Math.PI / 2);
modelMatrix = modelMatrix.multiplyRight(rotationX);
break;
default:
break;
}
if (tile.isQuantized) {
modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
}
const cartesianOrigin = new Vector3(center);
tile.cartesianModelMatrix = modelMatrix;
tile.cartesianOrigin = cartesianOrigin;
const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
tile.cartographicOrigin = cartographicOrigin;
if (!tile.coordinateSystem) {
tile.modelMatrix = tile.cartographicModelMatrix;
}
// glTF models need to be rotated from Y to Z up
// https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#y-up-to-z-up
switch (gltfUpAxis) {
case 'Z':
break;
case 'Y':
const rotationY = new Matrix4().rotateX(Math.PI / 2);
modelMatrix = modelMatrix.multiplyRight(rotationY);
break;
case 'X':
const rotationX = new Matrix4().rotateY(-Math.PI / 2);
modelMatrix = modelMatrix.multiplyRight(rotationX);
break;
default:
break;
}
// Scale/offset positions if normalized integers
if (tile.isQuantized) {
modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
}
// Option 1: Cartesian matrix and origin
const cartesianOrigin = new Vector3(center);
tile.cartesianModelMatrix = modelMatrix;
tile.cartesianOrigin = cartesianOrigin;
// Option 2: Cartographic matrix and origin
const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3());
const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
tile.cartographicOrigin = cartographicOrigin;
// Deprecated, drop
if (!tile.coordinateSystem) {
tile.modelMatrix = tile.cartographicModelMatrix;
}
}
//# sourceMappingURL=transform-utils.js.map
import { Vector3 } from '@math.gl/core';
import { BoundingSphere, OrientedBoundingBox } from '@math.gl/culling';
import { BoundingRectangle } from '../../types';
import { BoundingRectangle } from "../../types.js";
/**

@@ -5,0 +5,0 @@ * Calculate appropriate zoom value for a particular boundingVolume

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { Vector3 } from '@math.gl/core';

@@ -8,49 +11,76 @@ import { BoundingSphere, OrientedBoundingBox } from '@math.gl/culling';

const scratchVector = new Vector3();
/**
* Calculate appropriate zoom value for a particular boundingVolume
* @param boundingVolume - the instance of bounding volume
* @param cartorgraphicCenter - cartographic center of the bounding volume
* @returns {number} - zoom value
*/
export function getZoomFromBoundingVolume(boundingVolume, cartorgraphicCenter) {
if (boundingVolume instanceof OrientedBoundingBox) {
const {
halfAxes
} = boundingVolume;
const obbSize = getObbSize(halfAxes);
return Math.log2(WGS84_RADIUS_Z / (obbSize + cartorgraphicCenter[2]));
} else if (boundingVolume instanceof BoundingSphere) {
const {
radius
} = boundingVolume;
return Math.log2(WGS84_RADIUS_Z / (radius + cartorgraphicCenter[2]));
} else if (boundingVolume.width && boundingVolume.height) {
const {
width,
height
} = boundingVolume;
const zoomX = Math.log2(WGS84_RADIUS_X / width);
const zoomY = Math.log2(WGS84_RADIUS_Y / height);
return (zoomX + zoomY) / 2;
}
return 1;
if (boundingVolume instanceof OrientedBoundingBox) {
// OrientedBoundingBox
const { halfAxes } = boundingVolume;
const obbSize = getObbSize(halfAxes);
// Use WGS84_RADIUS_Z to allign with BoundingSphere algorithm
// Add the tile elevation value for correct zooming to elevated tiles
return Math.log2(WGS84_RADIUS_Z / (obbSize + cartorgraphicCenter[2]));
}
else if (boundingVolume instanceof BoundingSphere) {
// BoundingSphere
const { radius } = boundingVolume;
// Add the tile elevation value for correct zooming to elevated tiles
return Math.log2(WGS84_RADIUS_Z / (radius + cartorgraphicCenter[2]));
}
else if (boundingVolume.width && boundingVolume.height) {
// BoundingRectangle
const { width, height } = boundingVolume;
const zoomX = Math.log2(WGS84_RADIUS_X / width);
const zoomY = Math.log2(WGS84_RADIUS_Y / height);
return (zoomX + zoomY) / 2;
}
return 1;
}
/**
* Calculate initial zoom for the tileset from 3D `fullExtent` defined in
* the tileset metadata
* @param fullExtent - 3D extent of the tileset
* @param fullExtent.xmin - minimal longitude in decimal degrees
* @param fullExtent.xmax - maximal longitude in decimal degrees
* @param fullExtent.ymin - minimal latitude in decimal degrees
* @param fullExtent.ymax - maximal latitude in decimal degrees
* @param fullExtent.zmin - minimal elevation in meters
* @param fullExtent.zmax - maximal elevation in meters
* @param cartorgraphicCenter - tileset center in cartographic coordinate system
* @param cartesianCenter - tileset center in cartesian coordinate system
* @returns - initial zoom for the tileset
*/
export function getZoomFromFullExtent(fullExtent, cartorgraphicCenter, cartesianCenter) {
Ellipsoid.WGS84.cartographicToCartesian([fullExtent.xmax, fullExtent.ymax, fullExtent.zmax], scratchVector);
const extentSize = Math.sqrt(Math.pow(scratchVector[0] - cartesianCenter[0], 2) + Math.pow(scratchVector[1] - cartesianCenter[1], 2) + Math.pow(scratchVector[2] - cartesianCenter[2], 2));
return Math.log2(WGS84_RADIUS_Z / (extentSize + cartorgraphicCenter[2]));
Ellipsoid.WGS84.cartographicToCartesian([fullExtent.xmax, fullExtent.ymax, fullExtent.zmax], scratchVector);
const extentSize = Math.sqrt(Math.pow(scratchVector[0] - cartesianCenter[0], 2) +
Math.pow(scratchVector[1] - cartesianCenter[1], 2) +
Math.pow(scratchVector[2] - cartesianCenter[2], 2));
return Math.log2(WGS84_RADIUS_Z / (extentSize + cartorgraphicCenter[2]));
}
/**
* Calculate initial zoom for the tileset from 2D `extent` defined in
* the tileset metadata
* @param extent - 2D extent of the tileset. It is array of 4 elements [xmin, ymin, xmax, ymax]
* @param extent[0] - minimal longitude in decimal degrees
* @param extent[1] - minimal latitude in decimal degrees
* @param extent[2] - maximal longitude in decimal degrees
* @param extent[3] - maximal latitude in decimal degrees
* @param cartorgraphicCenter - tileset center in cartographic coordinate system
* @param cartesianCenter - tileset center in cartesian coordinate system
* @returns - initial zoom for the tileset
*/
export function getZoomFromExtent(extent, cartorgraphicCenter, cartesianCenter) {
const [xmin, ymin, xmax, ymax] = extent;
return getZoomFromFullExtent({
xmin,
xmax,
ymin,
ymax,
zmin: 0,
zmax: 0
}, cartorgraphicCenter, cartesianCenter);
const [xmin, ymin, xmax, ymax] = extent;
return getZoomFromFullExtent({ xmin, xmax, ymin, ymax, zmin: 0, zmax: 0 }, cartorgraphicCenter, cartesianCenter);
}
function getObbSize(halfAxes) {
halfAxes.getColumn(0, scratchVector);
const axeY = halfAxes.getColumn(1);
const axeZ = halfAxes.getColumn(2);
const farthestVertex = scratchVector.add(axeY).add(axeZ);
const size = farthestVertex.len();
return size;
halfAxes.getColumn(0, scratchVector);
const axeY = halfAxes.getColumn(1);
const axeZ = halfAxes.getColumn(2);
const farthestVertex = scratchVector.add(axeY).add(axeZ);
const size = farthestVertex.len();
return size;
}
//# sourceMappingURL=zoom.js.map
import { Matrix4 } from '@math.gl/core';
import type { Tileset3D } from './tileset-3d';
import type { DoublyLinkedListNode } from '../utils/doubly-linked-list-node';
import { FrameState } from './helpers/frame-state';
import { CartographicBounds } from './helpers/bounding-volume';
import { TilesetTraverser } from './tileset-traverser';
import type { Tileset3D } from "./tileset-3d.js";
import type { DoublyLinkedListNode } from "../utils/doubly-linked-list-node.js";
import { FrameState } from "./helpers/frame-state.js";
import { CartographicBounds } from "./helpers/bounding-volume.js";
import { TilesetTraverser } from "./tileset-traverser.js";
/**

@@ -8,0 +8,0 @@ * @param tileset - Tileset3D instance

@@ -0,1 +1,6 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
import { Vector3, Matrix4 } from '@math.gl/core';

@@ -12,403 +17,594 @@ import { CullingVolume } from '@math.gl/culling';

function defined(x) {
return x !== undefined && x !== null;
return x !== undefined && x !== null;
}
/**
* A Tile3DHeader represents a tile as Tileset3D. When a tile is first created, its content is not loaded;
* the content is loaded on-demand when needed based on the view.
* Do not construct this directly, instead access tiles through {@link Tileset3D#tileVisible}.
*/
export class Tile3D {
constructor(tileset, header, parentHeader) {
let extendedId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
this.tileset = void 0;
this.header = void 0;
this.id = void 0;
this.url = void 0;
this.parent = void 0;
this.refine = void 0;
this.type = void 0;
this.contentUrl = void 0;
this.lodMetricType = 'geometricError';
this.lodMetricValue = 0;
this.boundingVolume = null;
this.content = null;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
this.gpuMemoryUsageInBytes = 0;
this.children = [];
this.depth = 0;
this.viewportIds = [];
this.transform = new Matrix4();
this.extensions = null;
this.implicitTiling = null;
this.userData = {};
this.computedTransform = void 0;
this.hasEmptyContent = false;
this.hasTilesetContent = false;
this.traverser = new TilesetTraverser({});
this._cacheNode = null;
this._frameNumber = null;
this._expireDate = null;
this._expiredContent = null;
this._boundingBox = undefined;
this._distanceToCamera = 0;
this._screenSpaceError = 0;
this._visibilityPlaneMask = void 0;
this._visible = undefined;
this._contentBoundingVolume = void 0;
this._viewerRequestVolume = void 0;
this._initialTransform = new Matrix4();
this._priority = 0;
this._selectedFrame = 0;
this._requestedFrame = 0;
this._selectionDepth = 0;
this._touchedFrame = 0;
this._centerZDepth = 0;
this._shouldRefine = false;
this._stackLength = 0;
this._visitedFrame = 0;
this._inRequestVolume = false;
this._lodJudge = null;
this.header = header;
this.tileset = tileset;
this.id = extendedId || header.id;
this.url = header.url;
this.parent = parentHeader;
this.refine = this._getRefine(header.refine);
this.type = header.type;
this.contentUrl = header.contentUrl;
this._initializeLodMetric(header);
this._initializeTransforms(header);
this._initializeBoundingVolumes(header);
this._initializeContent(header);
this._initializeRenderingState(header);
Object.seal(this);
}
destroy() {
this.header = null;
}
isDestroyed() {
return this.header === null;
}
get selected() {
return this._selectedFrame === this.tileset._frameNumber;
}
get isVisible() {
return this._visible;
}
get isVisibleAndInRequestVolume() {
return this._visible && this._inRequestVolume;
}
get hasRenderContent() {
return !this.hasEmptyContent && !this.hasTilesetContent;
}
get hasChildren() {
return this.children.length > 0 || this.header.children && this.header.children.length > 0;
}
get contentReady() {
return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
}
get contentAvailable() {
return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
}
get hasUnloadedContent() {
return this.hasRenderContent && this.contentUnloaded;
}
get contentUnloaded() {
return this.contentState === TILE_CONTENT_STATE.UNLOADED;
}
get contentExpired() {
return this.contentState === TILE_CONTENT_STATE.EXPIRED;
}
get contentFailed() {
return this.contentState === TILE_CONTENT_STATE.FAILED;
}
get distanceToCamera() {
return this._distanceToCamera;
}
get screenSpaceError() {
return this._screenSpaceError;
}
get boundingBox() {
if (!this._boundingBox) {
this._boundingBox = getCartographicBounds(this.header.boundingVolume, this.boundingVolume);
/**
* @constructs
* Create a Tile3D instance
* @param tileset - Tileset3D instance
* @param header - tile header - JSON loaded from a dataset
* @param parentHeader - parent Tile3D instance
* @param extendedId - optional ID to separate copies of a tile for different viewports.
* const extendedId = `${tile.id}-${frameState.viewport.id}`;
*/
// eslint-disable-next-line max-statements
constructor(tileset, header, parentHeader, extendedId = '') {
/** Different refinement algorithms used by I3S and 3D tiles */
this.lodMetricType = 'geometricError';
/** The error, in meters, introduced if this tile is rendered and its children are not. */
this.lodMetricValue = 0;
/** @todo math.gl is not exporting BoundingVolume base type? */
this.boundingVolume = null;
/**
* The tile's content. This represents the actual tile's payload,
* not the content's metadata in the tileset JSON file.
*/
this.content = null;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
this.gpuMemoryUsageInBytes = 0;
/** The tile's children - an array of Tile3D objects. */
this.children = [];
this.depth = 0;
this.viewportIds = [];
this.transform = new Matrix4();
this.extensions = null;
/** TODO Cesium 3d tiles specific */
this.implicitTiling = null;
/** Container to store application specific data */
this.userData = {};
this.hasEmptyContent = false;
this.hasTilesetContent = false;
this.traverser = new TilesetTraverser({});
/** Used by TilesetCache */
this._cacheNode = null;
this._frameNumber = null;
// TODO Cesium 3d tiles specific
this._expireDate = null;
this._expiredContent = null;
this._boundingBox = undefined;
/** updated every frame for tree traversal and rendering optimizations: */
this._distanceToCamera = 0;
this._screenSpaceError = 0;
this._visible = undefined;
this._initialTransform = new Matrix4();
// Used by traverser, cannot be marked private
this._priority = 0;
this._selectedFrame = 0;
this._requestedFrame = 0;
this._selectionDepth = 0;
this._touchedFrame = 0;
this._centerZDepth = 0;
this._shouldRefine = false;
this._stackLength = 0;
this._visitedFrame = 0;
this._inRequestVolume = false;
this._lodJudge = null; // TODO i3s specific, needs to remove
// PUBLIC MEMBERS
// original tile data
this.header = header;
// The tileset containing this tile.
this.tileset = tileset;
this.id = extendedId || header.id;
this.url = header.url;
// This tile's parent or `undefined` if this tile is the root.
// @ts-ignore
this.parent = parentHeader;
this.refine = this._getRefine(header.refine);
this.type = header.type;
this.contentUrl = header.contentUrl;
this._initializeLodMetric(header);
this._initializeTransforms(header);
this._initializeBoundingVolumes(header);
this._initializeContent(header);
this._initializeRenderingState(header);
Object.seal(this);
}
return this._boundingBox;
}
getScreenSpaceError(frameState, useParentLodMetric) {
switch (this.tileset.type) {
case TILESET_TYPE.I3S:
return getProjectedRadius(this, frameState);
case TILESET_TYPE.TILES3D:
return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
default:
throw new Error('Unsupported tileset type');
destroy() {
this.header = null;
}
}
unselect() {
this._selectedFrame = 0;
}
_getGpuMemoryUsageInBytes() {
return this.content.gpuMemoryUsageInBytes || this.content.byteLength || 0;
}
_getPriority() {
const traverser = this.tileset._traverser;
const {
skipLevelOfDetail
} = traverser.options;
const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
if (maySkipTile && !this.isVisible && this._visible !== undefined) {
return -1;
isDestroyed() {
return this.header === null;
}
if (this.tileset._frameNumber - this._touchedFrame >= 1) {
return -1;
get selected() {
return this._selectedFrame === this.tileset._frameNumber;
}
if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
return -1;
get isVisible() {
return this._visible;
}
const parent = this.parent;
const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
return Math.max(rootScreenSpaceError - screenSpaceError, 0);
}
async loadContent() {
if (this.hasEmptyContent) {
return false;
get isVisibleAndInRequestVolume() {
return this._visible && this._inRequestVolume;
}
if (this.content) {
return true;
/** Returns true if tile is not an empty tile and not an external tileset */
get hasRenderContent() {
return !this.hasEmptyContent && !this.hasTilesetContent;
}
const expired = this.contentExpired;
if (expired) {
this._expireDate = null;
/** Returns true if tile has children */
get hasChildren() {
return this.children.length > 0 || (this.header.children && this.header.children.length > 0);
}
this.contentState = TILE_CONTENT_STATE.LOADING;
const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
if (!requestToken) {
this.contentState = TILE_CONTENT_STATE.UNLOADED;
return false;
/**
* Determines if the tile's content is ready. This is automatically `true` for
* tiles with empty content.
*/
get contentReady() {
return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
}
try {
const contentUrl = this.tileset.getTileUrl(this.contentUrl);
const loader = this.tileset.loader;
const options = {
...this.tileset.loadOptions,
[loader.id]: {
...this.tileset.loadOptions[loader.id],
isTileset: this.type === 'json',
...this._getLoaderSpecificOptions(loader.id)
/**
* Determines if the tile has available content to render. `true` if the tile's
* content is ready or if it has expired content this renders while new content loads; otherwise,
*/
get contentAvailable() {
return Boolean((this.contentReady && this.hasRenderContent) || (this._expiredContent && !this.contentFailed));
}
/** Returns true if tile has renderable content but it's unloaded */
get hasUnloadedContent() {
return this.hasRenderContent && this.contentUnloaded;
}
/**
* Determines if the tile's content has not be requested. `true` if tile's
* content has not be requested; otherwise, `false`.
*/
get contentUnloaded() {
return this.contentState === TILE_CONTENT_STATE.UNLOADED;
}
/**
* Determines if the tile's content is expired. `true` if tile's
* content is expired; otherwise, `false`.
*/
get contentExpired() {
return this.contentState === TILE_CONTENT_STATE.EXPIRED;
}
// Determines if the tile's content failed to load. `true` if the tile's
// content failed to load; otherwise, `false`.
get contentFailed() {
return this.contentState === TILE_CONTENT_STATE.FAILED;
}
/**
* Distance from the tile's bounding volume center to the camera
*/
get distanceToCamera() {
return this._distanceToCamera;
}
/**
* Screen space error for LOD selection
*/
get screenSpaceError() {
return this._screenSpaceError;
}
/**
* Get bounding box in cartographic coordinates
* @returns [min, max] each in [longitude, latitude, altitude]
*/
get boundingBox() {
if (!this._boundingBox) {
this._boundingBox = getCartographicBounds(this.header.boundingVolume, this.boundingVolume);
}
};
this.content = await load(contentUrl, loader, options);
if (this.tileset.options.contentLoader) {
await this.tileset.options.contentLoader(this);
}
if (this._isTileset()) {
this.tileset._initializeTileHeaders(this.content, this);
}
this.contentState = TILE_CONTENT_STATE.READY;
this._onContentLoaded();
return true;
} catch (error) {
this.contentState = TILE_CONTENT_STATE.FAILED;
throw error;
} finally {
requestToken.done();
return this._boundingBox;
}
}
unloadContent() {
if (this.content && this.content.destroy) {
this.content.destroy();
/** Get the tile's screen space error. */
getScreenSpaceError(frameState, useParentLodMetric) {
switch (this.tileset.type) {
case TILESET_TYPE.I3S:
return getProjectedRadius(this, frameState);
case TILESET_TYPE.TILES3D:
return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
default:
// eslint-disable-next-line
throw new Error('Unsupported tileset type');
}
}
this.content = null;
if (this.header.content && this.header.content.destroy) {
this.header.content.destroy();
/**
* Make tile unselected than means it won't be shown
* but it can be still loaded in memory
*/
unselect() {
this._selectedFrame = 0;
}
this.header.content = null;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
return true;
}
updateVisibility(frameState, viewportIds) {
if (this._frameNumber === frameState.frameNumber) {
return;
/**
* Memory usage of tile on GPU
*/
_getGpuMemoryUsageInBytes() {
return this.content.gpuMemoryUsageInBytes || this.content.byteLength || 0;
}
const parent = this.parent;
const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
if (this.tileset._traverser.options.updateTransforms) {
const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;
this._updateTransform(parentTransform);
/*
* If skipLevelOfDetail is off try to load child tiles as soon as possible so that their parent can refine sooner.
* Tiles are prioritized by screen space error.
*/
// eslint-disable-next-line complexity
_getPriority() {
const traverser = this.tileset._traverser;
const { skipLevelOfDetail } = traverser.options;
/*
* Tiles that are outside of the camera's frustum could be skipped if we are in 'ADD' mode
* or if we are using 'Skip Traversal' in 'REPLACE' mode.
* Otherewise, all 'touched' child tiles have to be loaded and displayed,
* this may include tiles that are outide of the camera frustum (so that we can hide the parent tile).
*/
const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
// Check if any reason to abort
if (maySkipTile && !this.isVisible && this._visible !== undefined) {
return -1;
}
// Condition used in `cancelOutOfViewRequests` function in CesiumJS/Cesium3DTileset.js
if (this.tileset._frameNumber - this._touchedFrame >= 1) {
return -1;
}
if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
return -1;
}
// Based on the priority function `getPriorityReverseScreenSpaceError` in CesiumJS. Scheduling priority is based on the parent's screen space error when possible.
const parent = this.parent;
const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
const screenSpaceError = useParentScreenSpaceError
? parent._screenSpaceError
: this._screenSpaceError;
const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
// Map higher SSE to lower values (e.g. root tile is highest priority)
return Math.max(rootScreenSpaceError - screenSpaceError, 0);
}
this._distanceToCamera = this.distanceToTile(frameState);
this._screenSpaceError = this.getScreenSpaceError(frameState, false);
this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
this._inRequestVolume = this.insideViewerRequestVolume(frameState);
this._frameNumber = frameState.frameNumber;
this.viewportIds = viewportIds;
}
visibility(frameState, parentVisibilityPlaneMask) {
const {
cullingVolume
} = frameState;
const {
boundingVolume
} = this;
return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
}
contentVisibility() {
return true;
}
distanceToTile(frameState) {
const boundingVolume = this.boundingVolume;
return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
}
cameraSpaceZDepth(_ref) {
let {
camera
} = _ref;
const boundingVolume = this.boundingVolume;
scratchVector.subVectors(boundingVolume.center, camera.position);
return camera.direction.dot(scratchVector);
}
insideViewerRequestVolume(frameState) {
const viewerRequestVolume = this._viewerRequestVolume;
return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
}
updateExpiration() {
if (defined(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
const now = Date.now();
if (Date.lessThan(this._expireDate, now)) {
this.contentState = TILE_CONTENT_STATE.EXPIRED;
this._expiredContent = this.content;
}
/**
* Requests the tile's content.
* The request may not be made if the Request Scheduler can't prioritize it.
*/
// eslint-disable-next-line max-statements, complexity
async loadContent() {
if (this.hasEmptyContent) {
return false;
}
if (this.content) {
return true;
}
const expired = this.contentExpired;
if (expired) {
this._expireDate = null;
}
this.contentState = TILE_CONTENT_STATE.LOADING;
const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
if (!requestToken) {
// cancelled
this.contentState = TILE_CONTENT_STATE.UNLOADED;
return false;
}
try {
const contentUrl = this.tileset.getTileUrl(this.contentUrl);
// The content can be a binary tile ot a JSON tileset
const loader = this.tileset.loader;
const options = {
...this.tileset.loadOptions,
[loader.id]: {
// @ts-expect-error
...this.tileset.loadOptions[loader.id],
isTileset: this.type === 'json',
...this._getLoaderSpecificOptions(loader.id)
}
};
this.content = await load(contentUrl, loader, options);
if (this.tileset.options.contentLoader) {
await this.tileset.options.contentLoader(this);
}
if (this._isTileset()) {
// Add tile headers for the nested tilset's subtree
// Async update of the tree should be fine since there would never be edits to the same node
// TODO - we need to capture the child tileset's URL
this.tileset._initializeTileHeaders(this.content, this);
}
this.contentState = TILE_CONTENT_STATE.READY;
this._onContentLoaded();
return true;
}
catch (error) {
// Tile is unloaded before the content finishes loading
this.contentState = TILE_CONTENT_STATE.FAILED;
throw error;
}
finally {
requestToken.done();
}
}
}
get extras() {
return this.header.extras;
}
_initializeLodMetric(header) {
if ('lodMetricType' in header) {
this.lodMetricType = header.lodMetricType;
} else {
this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
console.warn(`3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType`);
// Unloads the tile's content.
unloadContent() {
if (this.content && this.content.destroy) {
this.content.destroy();
}
this.content = null;
if (this.header.content && this.header.content.destroy) {
this.header.content.destroy();
}
this.header.content = null;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
return true;
}
if ('lodMetricValue' in header) {
this.lodMetricValue = header.lodMetricValue;
} else {
this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
/**
* Update the tile's visibility
* @param {Object} frameState - frame state for tile culling
* @param {string[]} viewportIds - a list of viewport ids that show this tile
* @return {void}
*/
updateVisibility(frameState, viewportIds) {
if (this._frameNumber === frameState.frameNumber) {
// Return early if visibility has already been checked during the traversal.
// The visibility may have already been checked if the cullWithChildrenBounds optimization is used.
return;
}
const parent = this.parent;
const parentVisibilityPlaneMask = parent
? parent._visibilityPlaneMask
: CullingVolume.MASK_INDETERMINATE;
if (this.tileset._traverser.options.updateTransforms) {
const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;
this._updateTransform(parentTransform);
}
this._distanceToCamera = this.distanceToTile(frameState);
this._screenSpaceError = this.getScreenSpaceError(frameState, false);
this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask); // Use parent's plane mask to speed up visibility test
this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
this._inRequestVolume = this.insideViewerRequestVolume(frameState);
this._frameNumber = frameState.frameNumber;
this.viewportIds = viewportIds;
}
}
_initializeTransforms(tileHeader) {
this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
const parent = this.parent;
const tileset = this.tileset;
const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : tileset.modelMatrix.clone();
this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
}
_initializeBoundingVolumes(tileHeader) {
this._contentBoundingVolume = null;
this._viewerRequestVolume = null;
this._updateBoundingVolume(tileHeader);
}
_initializeContent(tileHeader) {
this.content = {
_tileset: this.tileset,
_tile: this
};
this.hasEmptyContent = true;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
this.hasTilesetContent = false;
if (tileHeader.contentUrl) {
this.content = null;
this.hasEmptyContent = false;
// Determines whether the tile's bounding volume intersects the culling volume.
// @param {FrameState} frameState The frame state.
// @param {Number} parentVisibilityPlaneMask The parent's plane mask to speed up the visibility check.
// @returns {Number} A plane mask as described above in {@link CullingVolume#computeVisibilityWithPlaneMask}.
visibility(frameState, parentVisibilityPlaneMask) {
const { cullingVolume } = frameState;
const { boundingVolume } = this;
// TODO Cesium specific - restore clippingPlanes
// const {clippingPlanes, clippingPlanesOriginMatrix} = tileset;
// if (clippingPlanes && clippingPlanes.enabled) {
// const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
// boundingVolume,
// clippingPlanesOriginMatrix
// );
// this._isClipped = intersection !== Intersect.INSIDE;
// if (intersection === Intersect.OUTSIDE) {
// return CullingVolume.MASK_OUTSIDE;
// }
// }
// return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
}
}
_initializeRenderingState(header) {
this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
this._shouldRefine = false;
this._distanceToCamera = 0;
this._centerZDepth = 0;
this._screenSpaceError = 0;
this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
this._visible = undefined;
this._inRequestVolume = false;
this._stackLength = 0;
this._selectionDepth = 0;
this._frameNumber = 0;
this._touchedFrame = 0;
this._visitedFrame = 0;
this._selectedFrame = 0;
this._requestedFrame = 0;
this._priority = 0.0;
}
_getRefine(refine) {
return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
}
_isTileset() {
return this.contentUrl.indexOf('.json') !== -1;
}
_onContentLoaded() {
switch (this.content && this.content.type) {
case 'vctr':
case 'geom':
this.tileset._traverser.disableSkipLevelOfDetail = true;
break;
default:
// Assuming the tile's bounding volume intersects the culling volume, determines
// whether the tile's content's bounding volume intersects the culling volume.
// @param {FrameState} frameState The frame state.
// @returns {Intersect} The result of the intersection: the tile's content is completely outside, completely inside, or intersecting the culling volume.
contentVisibility() {
return true;
// TODO restore
/*
// Assumes the tile's bounding volume intersects the culling volume already, so
// just return Intersect.INSIDE if there is no content bounding volume.
if (!defined(this.contentBoundingVolume)) {
return Intersect.INSIDE;
}
if (this._visibilityPlaneMask === CullingVolume.MASK_INSIDE) {
// The tile's bounding volume is completely inside the culling volume so
// the content bounding volume must also be inside.
return Intersect.INSIDE;
}
// PERFORMANCE_IDEA: is it possible to burn less CPU on this test since we know the
// tile's (not the content's) bounding volume intersects the culling volume?
const cullingVolume = frameState.cullingVolume;
const boundingVolume = tile.contentBoundingVolume;
const tileset = this.tileset;
const clippingPlanes = tileset.clippingPlanes;
if (defined(clippingPlanes) && clippingPlanes.enabled) {
const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume,
tileset.clippingPlanesOriginMatrix
);
this._isClipped = intersection !== Intersect.INSIDE;
if (intersection === Intersect.OUTSIDE) {
return Intersect.OUTSIDE;
}
}
return cullingVolume.computeVisibility(boundingVolume);
*/
}
if (this._isTileset()) {
this.hasTilesetContent = true;
} else {
this.gpuMemoryUsageInBytes = this._getGpuMemoryUsageInBytes();
/**
* Computes the (potentially approximate) distance from the closest point of the tile's bounding volume to the camera.
* @param frameState The frame state.
* @returns {Number} The distance, in meters, or zero if the camera is inside the bounding volume.
*/
distanceToTile(frameState) {
const boundingVolume = this.boundingVolume;
return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
}
}
_updateBoundingVolume(header) {
this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume);
const content = header.content;
if (!content) {
return;
/**
* Computes the tile's camera-space z-depth.
* @param frameState The frame state.
* @returns The distance, in meters.
*/
cameraSpaceZDepth({ camera }) {
const boundingVolume = this.boundingVolume; // Gets the underlying OrientedBoundingBox or BoundingSphere
scratchVector.subVectors(boundingVolume.center, camera.position);
return camera.direction.dot(scratchVector);
}
if (content.boundingVolume) {
this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume);
/**
* Checks if the camera is inside the viewer request volume.
* @param {FrameState} frameState The frame state.
* @returns {Boolean} Whether the camera is inside the volume.
*/
insideViewerRequestVolume(frameState) {
const viewerRequestVolume = this._viewerRequestVolume;
return (!viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0);
}
if (header.viewerRequestVolume) {
this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume);
// TODO Cesium specific
// Update whether the tile has expired.
updateExpiration() {
if (defined(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
const now = Date.now();
// @ts-ignore Date.lessThan - replace with ms compare?
if (Date.lessThan(this._expireDate, now)) {
this.contentState = TILE_CONTENT_STATE.EXPIRED;
this._expiredContent = this.content;
}
}
}
}
_updateTransform() {
let parentTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Matrix4();
const computedTransform = parentTransform.clone().multiplyRight(this.transform);
const didTransformChange = !computedTransform.equals(this.computedTransform);
if (!didTransformChange) {
return;
get extras() {
return this.header.extras;
}
this.computedTransform = computedTransform;
this._updateBoundingVolume(this.header);
}
_getLoaderSpecificOptions(loaderId) {
switch (loaderId) {
case 'i3s':
return {
...this.tileset.options.i3s,
_tileOptions: {
attributeUrls: this.header.attributeUrls,
textureUrl: this.header.textureUrl,
textureFormat: this.header.textureFormat,
textureLoaderOptions: this.header.textureLoaderOptions,
materialDefinition: this.header.materialDefinition,
isDracoGeometry: this.header.isDracoGeometry,
mbs: this.header.mbs
},
_tilesetOptions: {
store: this.tileset.tileset.store,
attributeStorageInfo: this.tileset.tileset.attributeStorageInfo,
fields: this.tileset.tileset.fields
},
isTileHeader: false
};
case '3d-tiles':
case 'cesium-ion':
default:
return get3dTilesOptions(this.tileset.tileset);
// INTERNAL METHODS
_initializeLodMetric(header) {
if ('lodMetricType' in header) {
this.lodMetricType = header.lodMetricType;
}
else {
this.lodMetricType = (this.parent && this.parent.lodMetricType) || this.tileset.lodMetricType;
// eslint-disable-next-line
console.warn(`3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType`);
}
// This is used to compute screen space error, i.e., the error measured in pixels.
if ('lodMetricValue' in header) {
this.lodMetricValue = header.lodMetricValue;
}
else {
this.lodMetricValue =
(this.parent && this.parent.lodMetricValue) || this.tileset.lodMetricValue;
// eslint-disable-next-line
console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
}
}
}
_initializeTransforms(tileHeader) {
// The local transform of this tile.
this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();
const parent = this.parent;
const tileset = this.tileset;
const parentTransform = parent && parent.computedTransform
? parent.computedTransform.clone()
: tileset.modelMatrix.clone();
this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);
const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();
this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);
}
_initializeBoundingVolumes(tileHeader) {
this._contentBoundingVolume = null;
this._viewerRequestVolume = null;
this._updateBoundingVolume(tileHeader);
}
_initializeContent(tileHeader) {
// Empty tile by default
this.content = { _tileset: this.tileset, _tile: this };
this.hasEmptyContent = true;
this.contentState = TILE_CONTENT_STATE.UNLOADED;
// When `true`, the tile's content points to an external tileset.
// This is `false` until the tile's content is loaded.
this.hasTilesetContent = false;
if (tileHeader.contentUrl) {
this.content = null;
this.hasEmptyContent = false;
}
}
// TODO - remove anything not related to basic visibility detection
_initializeRenderingState(header) {
this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
this._shouldRefine = false;
// Members this are updated every frame for tree traversal and rendering optimizations:
this._distanceToCamera = 0;
this._centerZDepth = 0;
this._screenSpaceError = 0;
this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
this._visible = undefined;
this._inRequestVolume = false;
this._stackLength = 0;
this._selectionDepth = 0;
this._frameNumber = 0;
this._touchedFrame = 0;
this._visitedFrame = 0;
this._selectedFrame = 0;
this._requestedFrame = 0;
this._priority = 0.0;
}
_getRefine(refine) {
// Inherit from parent tile if omitted.
return refine || (this.parent && this.parent.refine) || TILE_REFINEMENT.REPLACE;
}
_isTileset() {
return this.contentUrl.indexOf('.json') !== -1;
}
_onContentLoaded() {
// Vector and Geometry tile rendering do not support the skip LOD optimization.
switch (this.content && this.content.type) {
case 'vctr':
case 'geom':
// @ts-ignore
this.tileset._traverser.disableSkipLevelOfDetail = true;
break;
default:
}
// The content may be tileset json
if (this._isTileset()) {
this.hasTilesetContent = true;
}
else {
this.gpuMemoryUsageInBytes = this._getGpuMemoryUsageInBytes();
}
}
_updateBoundingVolume(header) {
// Update the bounding volumes
this.boundingVolume = createBoundingVolume(header.boundingVolume, this.computedTransform, this.boundingVolume);
const content = header.content;
if (!content) {
return;
}
// TODO Cesium specific
// Non-leaf tiles may have a content bounding-volume, which is a tight-fit bounding volume
// around only the features in the tile. This box is useful for culling for rendering,
// but not for culling for traversing the tree since it does not guarantee spatial coherence, i.e.,
// since it only bounds features in the tile, not the entire tile, children may be
// outside of this box.
if (content.boundingVolume) {
this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, this.computedTransform, this._contentBoundingVolume);
}
if (header.viewerRequestVolume) {
this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, this.computedTransform, this._viewerRequestVolume);
}
}
// Update the tile's transform. The transform is applied to the tile's bounding volumes.
_updateTransform(parentTransform = new Matrix4()) {
const computedTransform = parentTransform.clone().multiplyRight(this.transform);
const didTransformChange = !computedTransform.equals(this.computedTransform);
if (!didTransformChange) {
return;
}
this.computedTransform = computedTransform;
this._updateBoundingVolume(this.header);
}
// Get options which are applicable only for the particular loader
_getLoaderSpecificOptions(loaderId) {
switch (loaderId) {
case 'i3s':
return {
...this.tileset.options.i3s,
_tileOptions: {
attributeUrls: this.header.attributeUrls,
textureUrl: this.header.textureUrl,
textureFormat: this.header.textureFormat,
textureLoaderOptions: this.header.textureLoaderOptions,
materialDefinition: this.header.materialDefinition,
isDracoGeometry: this.header.isDracoGeometry,
mbs: this.header.mbs
},
_tilesetOptions: {
store: this.tileset.tileset.store,
attributeStorageInfo: this.tileset.tileset.attributeStorageInfo,
fields: this.tileset.tileset.fields
},
isTileHeader: false
};
case '3d-tiles':
case 'cesium-ion':
default:
return get3dTilesOptions(this.tileset.tileset);
}
}
}
//# sourceMappingURL=tile-3d.js.map
import { Matrix4, Vector3 } from '@math.gl/core';
import { Stats } from '@probe.gl/stats';
import { RequestScheduler, LoaderWithParser, LoaderOptions } from '@loaders.gl/loader-utils';
import { TilesetCache } from './tileset-cache';
import { FrameState } from './helpers/frame-state';
import type { Viewport } from '../types';
import { Tile3D } from './tile-3d';
import { TilesetTraverser } from './tileset-traverser';
import { TilesetCache } from "./tileset-cache.js";
import { FrameState } from "./helpers/frame-state.js";
import type { Viewport } from "../types.js";
import { Tile3D } from "./tile-3d.js";
import { TilesetTraverser } from "./tileset-traverser.js";
export type TilesetJSON = any;

@@ -10,0 +10,0 @@ export type Tileset3DProps = {

@@ -0,1 +1,5 @@

// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
import { Matrix4, Vector3 } from '@math.gl/core';

@@ -12,32 +16,33 @@ import { Ellipsoid } from '@math.gl/geospatial';

import { TilesetTraverser } from "./tileset-traverser.js";
// TODO - these should be moved into their respective modules
import { Tileset3DTraverser } from "./format-3d-tiles/tileset-3d-traverser.js";
import { I3STilesetTraverser } from "./format-i3s/i3s-tileset-traverser.js";
const DEFAULT_PROPS = {
description: '',
ellipsoid: Ellipsoid.WGS84,
modelMatrix: new Matrix4(),
throttleRequests: true,
maxRequests: 64,
maximumMemoryUsage: 32,
memoryCacheOverflow: 1,
maximumTilesSelected: 0,
debounceTime: 0,
onTileLoad: () => {},
onTileUnload: () => {},
onTileError: () => {},
onTraversalComplete: selectedTiles => selectedTiles,
contentLoader: undefined,
viewDistanceScale: 1.0,
maximumScreenSpaceError: 8,
memoryAdjustedScreenSpaceError: false,
loadTiles: true,
updateTransforms: true,
viewportTraversersMap: null,
loadOptions: {
fetch: {}
},
attributions: [],
basePath: '',
i3s: {}
description: '',
ellipsoid: Ellipsoid.WGS84,
modelMatrix: new Matrix4(),
throttleRequests: true,
maxRequests: 64,
/** Default memory values optimized for viewing mesh-based 3D Tiles on both mobile and desktop devices */
maximumMemoryUsage: 32,
memoryCacheOverflow: 1,
maximumTilesSelected: 0,
debounceTime: 0,
onTileLoad: () => { },
onTileUnload: () => { },
onTileError: () => { },
onTraversalComplete: (selectedTiles) => selectedTiles,
contentLoader: undefined,
viewDistanceScale: 1.0,
maximumScreenSpaceError: 8,
memoryAdjustedScreenSpaceError: false,
loadTiles: true,
updateTransforms: true,
viewportTraversersMap: null,
loadOptions: { fetch: {} },
attributions: [],
basePath: '',
i3s: {}
};
// Tracked Stats
const TILES_TOTAL = 'Tiles In Tileset(s)';

@@ -54,576 +59,695 @@ const TILES_IN_MEMORY = 'Tiles In Memory';

const MAXIMUM_SSE = 'Maximum Screen Space Error';
/**
* The Tileset loading and rendering flow is as below,
* A rendered (i.e. deck.gl `Tile3DLayer`) triggers `tileset.update()` after a `tileset` is loaded
* `tileset` starts traversing the tile tree and update `requestTiles` (tiles of which content need
* to be fetched) and `selectedTiles` (tiles ready for rendering under the current viewport).
* `Tile3DLayer` will update rendering based on `selectedTiles`.
* `Tile3DLayer` also listens to `onTileLoad` callback and trigger another round of `update and then traversal`
* when new tiles are loaded.
* As I3S tileset have stored `tileHeader` file (metadata) and tile content files (geometry, texture, ...) separately.
* During each traversal, it issues `tilHeader` requests if that `tileHeader` is not yet fetched,
* after the tile header is fulfilled, it will resume the traversal starting from the tile just fetched (not root).
* Tile3DLayer
* |
* await load(tileset)
* |
* tileset.update()
* | async load tileHeader
* tileset.traverse() -------------------------- Queued
* | resume traversal after fetched |
* |----------------------------------------|
* |
* | async load tile content
* tilset.requestedTiles ----------------------------- RequestScheduler
* |
* tilset.selectedTiles (ready for rendering) |
* | Listen to |
* Tile3DLayer ----------- onTileLoad ----------------------|
* | | notify new tile is available
* updateLayers |
* tileset.update // trigger another round of update
*/
export class Tileset3D {
constructor(tileset, options) {
this.options = void 0;
this.loadOptions = void 0;
this.type = void 0;
this.tileset = void 0;
this.loader = void 0;
this.url = void 0;
this.basePath = void 0;
this.modelMatrix = void 0;
this.ellipsoid = void 0;
this.lodMetricType = void 0;
this.lodMetricValue = void 0;
this.refine = void 0;
this.root = null;
this.roots = {};
this.asset = {};
this.description = '';
this.properties = void 0;
this.extras = null;
this.attributions = {};
this.credits = {};
this.stats = void 0;
this.contentFormats = {
draco: false,
meshopt: false,
dds: false,
ktx2: false
};
this.cartographicCenter = null;
this.cartesianCenter = null;
this.zoom = 1;
this.boundingVolume = null;
this.dynamicScreenSpaceErrorComputedDensity = 0.0;
this.maximumMemoryUsage = 32;
this.gpuMemoryUsageInBytes = 0;
this.memoryAdjustedScreenSpaceError = 0.0;
this._cacheBytes = 0;
this._cacheOverflowBytes = 0;
this._frameNumber = 0;
this._queryParams = {};
this._extensionsUsed = [];
this._tiles = {};
this._pendingCount = 0;
this.selectedTiles = [];
this.traverseCounter = 0;
this.geometricError = 0;
this.lastUpdatedVieports = null;
this._requestedTiles = [];
this._emptyTiles = [];
this.frameStateData = {};
this._traverser = void 0;
this._cache = new TilesetCache();
this._requestScheduler = void 0;
this.updatePromise = null;
this.tilesetInitializationPromise = void 0;
this.options = {
...DEFAULT_PROPS,
...options
};
this.tileset = tileset;
this.loader = tileset.loader;
this.type = tileset.type;
this.url = tileset.url;
this.basePath = tileset.basePath || path.dirname(this.url);
this.modelMatrix = this.options.modelMatrix;
this.ellipsoid = this.options.ellipsoid;
this.lodMetricType = tileset.lodMetricType;
this.lodMetricValue = tileset.lodMetricValue;
this.refine = tileset.root.refine;
this.loadOptions = this.options.loadOptions || {};
this._traverser = this._initializeTraverser();
this._requestScheduler = new RequestScheduler({
throttleRequests: this.options.throttleRequests,
maxRequests: this.options.maxRequests
});
this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
this.stats = new Stats({
id: this.url
});
this._initializeStats();
this.tilesetInitializationPromise = this._initializeTileSet(tileset);
}
destroy() {
this._destroy();
}
isLoaded() {
return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
}
get tiles() {
return Object.values(this._tiles);
}
get frameNumber() {
return this._frameNumber;
}
get queryParams() {
return new URLSearchParams(this._queryParams).toString();
}
setProps(props) {
this.options = {
...this.options,
...props
};
}
getTileUrl(tilePath) {
const isDataUrl = tilePath.startsWith('data:');
if (isDataUrl) {
return tilePath;
/**
* Create a new Tileset3D
* @param json
* @param props
*/
// eslint-disable-next-line max-statements
constructor(tileset, options) {
this.root = null;
this.roots = {};
/** @todo any->unknown */
this.asset = {};
// Metadata for the entire tileset
this.description = '';
this.extras = null;
this.attributions = {};
this.credits = {};
/** flags that contain information about data types in nested tiles */
this.contentFormats = { draco: false, meshopt: false, dds: false, ktx2: false };
// view props
this.cartographicCenter = null;
this.cartesianCenter = null;
this.zoom = 1;
this.boundingVolume = null;
/** Updated based on the camera position and direction */
this.dynamicScreenSpaceErrorComputedDensity = 0.0;
// METRICS
/**
* The maximum amount of GPU memory (in MB) that may be used to cache tiles
* Tiles not in view are unloaded to enforce private
*/
this.maximumMemoryUsage = 32;
/** The total amount of GPU memory in bytes used by the tileset. */
this.gpuMemoryUsageInBytes = 0;
/**
* If loading the level of detail required by maximumScreenSpaceError
* results in the memory usage exceeding maximumMemoryUsage (GPU), level of detail refinement
* will instead use this (larger) adjusted screen space error to achieve the
* best possible visual quality within the available memory.
*/
this.memoryAdjustedScreenSpaceError = 0.0;
this._cacheBytes = 0;
this._cacheOverflowBytes = 0;
/** Update tracker. increase in each update cycle. */
this._frameNumber = 0;
this._queryParams = {};
this._extensionsUsed = [];
this._tiles = {};
/** counter for tracking tiles requests */
this._pendingCount = 0;
/** Hold traversal results */
this.selectedTiles = [];
// TRAVERSAL
this.traverseCounter = 0;
this.geometricError = 0;
this.lastUpdatedVieports = null;
this._requestedTiles = [];
this._emptyTiles = [];
this.frameStateData = {};
this._cache = new TilesetCache();
// Promise tracking
this.updatePromise = null;
// PUBLIC MEMBERS
this.options = { ...DEFAULT_PROPS, ...options };
// raw data
this.tileset = tileset;
this.loader = tileset.loader;
// could be 3d tiles, i3s
this.type = tileset.type;
// The url to a tileset JSON file.
this.url = tileset.url;
this.basePath = tileset.basePath || path.dirname(this.url);
this.modelMatrix = this.options.modelMatrix;
this.ellipsoid = this.options.ellipsoid;
// Geometric error when the tree is not rendered at all
this.lodMetricType = tileset.lodMetricType;
this.lodMetricValue = tileset.lodMetricValue;
this.refine = tileset.root.refine;
this.loadOptions = this.options.loadOptions || {};
// TRAVERSAL
this._traverser = this._initializeTraverser();
this._requestScheduler = new RequestScheduler({
throttleRequests: this.options.throttleRequests,
maxRequests: this.options.maxRequests
});
this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;
this._cacheBytes = this.options.maximumMemoryUsage * 1024 * 1024;
this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;
// METRICS
// The total amount of GPU memory in bytes used by the tileset.
this.stats = new Stats({ id: this.url });
this._initializeStats();
this.tilesetInitializationPromise = this._initializeTileSet(tileset);
}
let tileUrl = tilePath;
if (this.queryParams.length) {
tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
/** Release resources */
destroy() {
this._destroy();
}
return tileUrl;
}
hasExtension(extensionName) {
return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
}
update() {
let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
this.tilesetInitializationPromise.then(() => {
if (!viewports && this.lastUpdatedVieports) {
viewports = this.lastUpdatedVieports;
} else {
this.lastUpdatedVieports = viewports;
}
if (viewports) {
this.doUpdate(viewports);
}
});
}
async selectTiles() {
let viewports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
await this.tilesetInitializationPromise;
if (viewports) {
this.lastUpdatedVieports = viewports;
/** Is the tileset loaded (update needs to have been called at least once) */
isLoaded() {
// Check that `_frameNumber !== 0` which means that update was called at least once
return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;
}
if (!this.updatePromise) {
this.updatePromise = new Promise(resolve => {
setTimeout(() => {
if (this.lastUpdatedVieports) {
this.doUpdate(this.lastUpdatedVieports);
}
resolve(this._frameNumber);
this.updatePromise = null;
}, this.options.debounceTime);
});
get tiles() {
return Object.values(this._tiles);
}
return this.updatePromise;
}
adjustScreenSpaceError() {
if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
} else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
this.memoryAdjustedScreenSpaceError *= 1.02;
get frameNumber() {
return this._frameNumber;
}
}
doUpdate(viewports) {
if ('loadTiles' in this.options && !this.options.loadTiles) {
return;
get queryParams() {
return new URLSearchParams(this._queryParams).toString();
}
if (this.traverseCounter > 0) {
return;
setProps(props) {
this.options = { ...this.options, ...props };
}
const preparedViewports = viewports instanceof Array ? viewports : [viewports];
this._cache.reset();
this._frameNumber++;
this.traverseCounter = preparedViewports.length;
const viewportsToTraverse = [];
for (const viewport of preparedViewports) {
const id = viewport.id;
if (this._needTraverse(id)) {
viewportsToTraverse.push(id);
} else {
this.traverseCounter--;
}
/** @deprecated */
// setOptions(options: Tileset3DProps): void {
// this.options = {...this.options, ...options};
// }
/**
* Return a loadable tile url for a specific tile subpath
* @param tilePath a tile subpath
*/
getTileUrl(tilePath) {
const isDataUrl = tilePath.startsWith('data:');
if (isDataUrl) {
return tilePath;
}
let tileUrl = tilePath;
if (this.queryParams.length) {
tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;
}
return tileUrl;
}
for (const viewport of preparedViewports) {
const id = viewport.id;
if (!this.roots[id]) {
this.roots[id] = this._initializeTileHeaders(this.tileset, null);
}
if (!viewportsToTraverse.includes(id)) {
continue;
}
const frameState = getFrameState(viewport, this._frameNumber);
this._traverser.traverse(this.roots[id], frameState, this.options);
// TODO CESIUM specific
hasExtension(extensionName) {
return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);
}
}
_needTraverse(viewportId) {
let traverserId = viewportId;
if (this.options.viewportTraversersMap) {
traverserId = this.options.viewportTraversersMap[viewportId];
/**
* Update visible tiles relying on a list of viewports
* @param viewports - list of viewports
* @deprecated
*/
update(viewports = null) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.tilesetInitializationPromise.then(() => {
if (!viewports && this.lastUpdatedVieports) {
viewports = this.lastUpdatedVieports;
}
else {
this.lastUpdatedVieports = viewports;
}
if (viewports) {
this.doUpdate(viewports);
}
});
}
if (traverserId !== viewportId) {
return false;
/**
* Update visible tiles relying on a list of viewports.
* Do it with debounce delay to prevent update spam
* @param viewports viewports
* @returns Promise of new frameNumber
*/
async selectTiles(viewports = null) {
await this.tilesetInitializationPromise;
if (viewports) {
this.lastUpdatedVieports = viewports;
}
if (!this.updatePromise) {
this.updatePromise = new Promise((resolve) => {
setTimeout(() => {
if (this.lastUpdatedVieports) {
this.doUpdate(this.lastUpdatedVieports);
}
resolve(this._frameNumber);
this.updatePromise = null;
}, this.options.debounceTime);
});
}
return this.updatePromise;
}
return true;
}
_onTraversalEnd(frameState) {
const id = frameState.viewport.id;
if (!this.frameStateData[id]) {
this.frameStateData[id] = {
selectedTiles: [],
_requestedTiles: [],
_emptyTiles: []
};
adjustScreenSpaceError() {
if (this.gpuMemoryUsageInBytes < this._cacheBytes) {
this.memoryAdjustedScreenSpaceError = Math.max(this.memoryAdjustedScreenSpaceError / 1.02, this.options.maximumScreenSpaceError);
}
else if (this.gpuMemoryUsageInBytes > this._cacheBytes + this._cacheOverflowBytes) {
this.memoryAdjustedScreenSpaceError *= 1.02;
}
}
const currentFrameStateData = this.frameStateData[id];
const selectedTiles = Object.values(this._traverser.selectedTiles);
const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
currentFrameStateData.selectedTiles = filteredSelectedTiles;
for (const tile of unselectedTiles) {
tile.unselect();
/**
* Update visible tiles relying on a list of viewports
* @param viewports viewports
*/
// eslint-disable-next-line max-statements, complexity
doUpdate(viewports) {
if ('loadTiles' in this.options && !this.options.loadTiles) {
return;
}
if (this.traverseCounter > 0) {
return;
}
const preparedViewports = viewports instanceof Array ? viewports : [viewports];
this._cache.reset();
this._frameNumber++;
this.traverseCounter = preparedViewports.length;
const viewportsToTraverse = [];
// First loop to decrement traverseCounter
for (const viewport of preparedViewports) {
const id = viewport.id;
if (this._needTraverse(id)) {
viewportsToTraverse.push(id);
}
else {
this.traverseCounter--;
}
}
// Second loop to traverse
for (const viewport of preparedViewports) {
const id = viewport.id;
if (!this.roots[id]) {
this.roots[id] = this._initializeTileHeaders(this.tileset, null);
}
if (!viewportsToTraverse.includes(id)) {
continue; // eslint-disable-line no-continue
}
const frameState = getFrameState(viewport, this._frameNumber);
this._traverser.traverse(this.roots[id], frameState, this.options);
}
}
currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
this.traverseCounter--;
if (this.traverseCounter > 0) {
return;
/**
* Check if traversal is needed for particular viewport
* @param {string} viewportId - id of a viewport
* @return {boolean}
*/
_needTraverse(viewportId) {
let traverserId = viewportId;
if (this.options.viewportTraversersMap) {
traverserId = this.options.viewportTraversersMap[viewportId];
}
if (traverserId !== viewportId) {
return false;
}
return true;
}
this._updateTiles();
}
_updateTiles() {
this.selectedTiles = [];
this._requestedTiles = [];
this._emptyTiles = [];
for (const frameStateKey in this.frameStateData) {
const frameStateDataValue = this.frameStateData[frameStateKey];
this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
/**
* The callback to post-process tiles after traversal procedure
* @param frameState - frame state for tile culling
*/
_onTraversalEnd(frameState) {
const id = frameState.viewport.id;
if (!this.frameStateData[id]) {
this.frameStateData[id] = { selectedTiles: [], _requestedTiles: [], _emptyTiles: [] };
}
const currentFrameStateData = this.frameStateData[id];
const selectedTiles = Object.values(this._traverser.selectedTiles);
const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(selectedTiles, frameState, this.options.maximumTilesSelected);
currentFrameStateData.selectedTiles = filteredSelectedTiles;
for (const tile of unselectedTiles) {
tile.unselect();
}
currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
this.traverseCounter--;
if (this.traverseCounter > 0) {
return;
}
this._updateTiles();
}
this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
for (const tile of this.selectedTiles) {
this._tiles[tile.id] = tile;
/**
* Update tiles relying on data from all traversers
*/
_updateTiles() {
this.selectedTiles = [];
this._requestedTiles = [];
this._emptyTiles = [];
for (const frameStateKey in this.frameStateData) {
const frameStateDataValue = this.frameStateData[frameStateKey];
this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
}
this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
for (const tile of this.selectedTiles) {
this._tiles[tile.id] = tile;
}
this._loadTiles();
this._unloadTiles();
this._updateStats();
}
this._loadTiles();
this._unloadTiles();
this._updateStats();
}
_tilesChanged(oldSelectedTiles, selectedTiles) {
if (oldSelectedTiles.length !== selectedTiles.length) {
return true;
_tilesChanged(oldSelectedTiles, selectedTiles) {
if (oldSelectedTiles.length !== selectedTiles.length) {
return true;
}
const set1 = new Set(oldSelectedTiles.map((t) => t.id));
const set2 = new Set(selectedTiles.map((t) => t.id));
let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0;
changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0;
return changed;
}
const set1 = new Set(oldSelectedTiles.map(t => t.id));
const set2 = new Set(selectedTiles.map(t => t.id));
let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
return changed;
}
_loadTiles() {
for (const tile of this._requestedTiles) {
if (tile.contentUnloaded) {
this._loadTile(tile);
}
}
}
_unloadTiles() {
this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
}
_updateStats() {
let tilesRenderable = 0;
let pointsRenderable = 0;
for (const tile of this.selectedTiles) {
if (tile.contentAvailable && tile.content) {
tilesRenderable++;
if (tile.content.pointCount) {
pointsRenderable += tile.content.pointCount;
} else {
pointsRenderable += tile.content.vertexCount;
_loadTiles() {
// Sort requests by priority before making any requests.
// This makes it less likely this requests will be cancelled after being issued.
// requestedTiles.sort((a, b) => a._priority - b._priority);
for (const tile of this._requestedTiles) {
if (tile.contentUnloaded) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this._loadTile(tile);
}
}
}
}
this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
this.stats.get(POINTS_COUNT).count = pointsRenderable;
this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
}
async _initializeTileSet(tilesetJson) {
if (this.type === TILESET_TYPE.I3S) {
this.calculateViewPropsI3S();
tilesetJson.root = await tilesetJson.root;
_unloadTiles() {
// unload tiles from cache when hit maximumMemoryUsage
this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
}
this.root = this._initializeTileHeaders(tilesetJson, null);
if (this.type === TILESET_TYPE.TILES3D) {
this._initializeTiles3DTileset(tilesetJson);
this.calculateViewPropsTiles3D();
_updateStats() {
let tilesRenderable = 0;
let pointsRenderable = 0;
for (const tile of this.selectedTiles) {
if (tile.contentAvailable && tile.content) {
tilesRenderable++;
if (tile.content.pointCount) {
pointsRenderable += tile.content.pointCount;
}
else {
// Calculate vertices for non point cloud tiles.
pointsRenderable += tile.content.vertexCount;
}
}
}
this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
this.stats.get(POINTS_COUNT).count = pointsRenderable;
this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;
}
if (this.type === TILESET_TYPE.I3S) {
this._initializeI3STileset();
async _initializeTileSet(tilesetJson) {
if (this.type === TILESET_TYPE.I3S) {
this.calculateViewPropsI3S();
tilesetJson.root = await tilesetJson.root;
}
this.root = this._initializeTileHeaders(tilesetJson, null);
if (this.type === TILESET_TYPE.TILES3D) {
this._initializeTiles3DTileset(tilesetJson);
this.calculateViewPropsTiles3D();
}
if (this.type === TILESET_TYPE.I3S) {
this._initializeI3STileset();
}
}
}
calculateViewPropsI3S() {
var _this$tileset$store;
const fullExtent = this.tileset.fullExtent;
if (fullExtent) {
const {
xmin,
xmax,
ymin,
ymax,
zmin,
zmax
} = fullExtent;
this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
this.cartesianCenter = new Vector3();
Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
return;
/**
* Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
* These metrics help apps center view on tileset
* For I3S there is extent (<1.8 version) or fullExtent (>=1.8 version) to calculate view props
* @returns
*/
calculateViewPropsI3S() {
// for I3S 1.8 try to calculate with fullExtent
const fullExtent = this.tileset.fullExtent;
if (fullExtent) {
const { xmin, xmax, ymin, ymax, zmin, zmax } = fullExtent;
this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin + (zmax - zmin) / 2);
this.cartesianCenter = new Vector3();
Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);
return;
}
// for I3S 1.6-1.7 try to calculate with extent
const extent = this.tileset.store?.extent;
if (extent) {
const [xmin, ymin, xmax, ymax] = extent;
this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
this.cartesianCenter = new Vector3();
Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
return;
}
// eslint-disable-next-line no-console
console.warn('Extent is not defined in the tileset header');
this.cartographicCenter = new Vector3();
this.zoom = 1;
return;
}
const extent = (_this$tileset$store = this.tileset.store) === null || _this$tileset$store === void 0 ? void 0 : _this$tileset$store.extent;
if (extent) {
const [xmin, ymin, xmax, ymax] = extent;
this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);
this.cartesianCenter = new Vector3();
Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);
this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);
return;
/**
* Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.
* These metrics help apps center view on tileset.
* For 3DTiles the root tile data is used to calculate view props.
* @returns
*/
calculateViewPropsTiles3D() {
const root = this.root;
const { center } = root.boundingVolume;
// TODO - handle all cases
if (!center) {
// eslint-disable-next-line no-console
console.warn('center was not pre-calculated for the root tile');
this.cartographicCenter = new Vector3();
this.zoom = 1;
return;
}
// cartographic coordinates are undefined at the center of the ellipsoid
if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
this.cartographicCenter = new Vector3();
Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
}
else {
this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
}
this.cartesianCenter = center;
this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
}
console.warn('Extent is not defined in the tileset header');
this.cartographicCenter = new Vector3();
this.zoom = 1;
return;
}
calculateViewPropsTiles3D() {
const root = this.root;
const {
center
} = root.boundingVolume;
if (!center) {
console.warn('center was not pre-calculated for the root tile');
this.cartographicCenter = new Vector3();
this.zoom = 1;
return;
_initializeStats() {
this.stats.get(TILES_TOTAL);
this.stats.get(TILES_LOADING);
this.stats.get(TILES_IN_MEMORY);
this.stats.get(TILES_IN_VIEW);
this.stats.get(TILES_RENDERABLE);
this.stats.get(TILES_LOADED);
this.stats.get(TILES_UNLOADED);
this.stats.get(TILES_LOAD_FAILED);
this.stats.get(POINTS_COUNT);
this.stats.get(TILES_GPU_MEMORY, 'memory');
this.stats.get(MAXIMUM_SSE);
}
if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {
this.cartographicCenter = new Vector3();
Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);
} else {
this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);
}
this.cartesianCenter = center;
this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);
}
_initializeStats() {
this.stats.get(TILES_TOTAL);
this.stats.get(TILES_LOADING);
this.stats.get(TILES_IN_MEMORY);
this.stats.get(TILES_IN_VIEW);
this.stats.get(TILES_RENDERABLE);
this.stats.get(TILES_LOADED);
this.stats.get(TILES_UNLOADED);
this.stats.get(TILES_LOAD_FAILED);
this.stats.get(POINTS_COUNT);
this.stats.get(TILES_GPU_MEMORY, 'memory');
this.stats.get(MAXIMUM_SSE);
}
_initializeTileHeaders(tilesetJson, parentTileHeader) {
const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader);
if (parentTileHeader) {
parentTileHeader.children.push(rootTile);
rootTile.depth = parentTileHeader.depth + 1;
}
if (this.type === TILESET_TYPE.TILES3D) {
const stack = [];
stack.push(rootTile);
while (stack.length > 0) {
const tile = stack.pop();
this.stats.get(TILES_TOTAL).incrementCount();
const children = tile.header.children || [];
for (const childHeader of children) {
var _childTile$contentUrl;
const childTile = new Tile3D(this, childHeader, tile);
if ((_childTile$contentUrl = childTile.contentUrl) !== null && _childTile$contentUrl !== void 0 && _childTile$contentUrl.includes('?session=')) {
const url = new URL(childTile.contentUrl);
const session = url.searchParams.get('session');
if (session) {
this._queryParams.session = session;
// Installs the main tileset JSON file or a tileset JSON file referenced from a tile.
// eslint-disable-next-line max-statements
_initializeTileHeaders(tilesetJson, parentTileHeader) {
// A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
// Get the basePath relative to the external tileset.
const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource
// If there is a parentTileHeader, add the root of the currently loading tileset
// to parentTileHeader's children, and update its depth.
if (parentTileHeader) {
parentTileHeader.children.push(rootTile);
rootTile.depth = parentTileHeader.depth + 1;
}
// 3DTiles knows the hierarchy beforehand
if (this.type === TILESET_TYPE.TILES3D) {
const stack = [];
stack.push(rootTile);
while (stack.length > 0) {
const tile = stack.pop();
this.stats.get(TILES_TOTAL).incrementCount();
const children = tile.header.children || [];
for (const childHeader of children) {
const childTile = new Tile3D(this, childHeader, tile);
// Special handling for Google
// A session key must be used for all tile requests
if (childTile.contentUrl?.includes('?session=')) {
const url = new URL(childTile.contentUrl);
const session = url.searchParams.get('session');
// eslint-disable-next-line max-depth
if (session) {
this._queryParams.session = session;
}
}
tile.children.push(childTile);
childTile.depth = tile.depth + 1;
stack.push(childTile);
}
}
}
tile.children.push(childTile);
childTile.depth = tile.depth + 1;
stack.push(childTile);
}
}
return rootTile;
}
return rootTile;
}
_initializeTraverser() {
let TraverserClass;
const type = this.type;
switch (type) {
case TILESET_TYPE.TILES3D:
TraverserClass = Tileset3DTraverser;
break;
case TILESET_TYPE.I3S:
TraverserClass = I3STilesetTraverser;
break;
default:
TraverserClass = TilesetTraverser;
_initializeTraverser() {
let TraverserClass;
const type = this.type;
switch (type) {
case TILESET_TYPE.TILES3D:
TraverserClass = Tileset3DTraverser;
break;
case TILESET_TYPE.I3S:
TraverserClass = I3STilesetTraverser;
break;
default:
TraverserClass = TilesetTraverser;
}
return new TraverserClass({
basePath: this.basePath,
onTraversalEnd: this._onTraversalEnd.bind(this)
});
}
return new TraverserClass({
basePath: this.basePath,
onTraversalEnd: this._onTraversalEnd.bind(this)
});
}
_destroyTileHeaders(parentTile) {
this._destroySubtree(parentTile);
}
async _loadTile(tile) {
let loaded;
try {
this._onStartTileLoading();
loaded = await tile.loadContent();
} catch (error) {
this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
} finally {
this._onEndTileLoading();
this._onTileLoad(tile, loaded);
_destroyTileHeaders(parentTile) {
this._destroySubtree(parentTile);
}
}
_onTileLoadError(tile, error) {
this.stats.get(TILES_LOAD_FAILED).incrementCount();
const message = error.message || error.toString();
const url = tile.url;
console.error(`A 3D tile failed to load: ${tile.url} ${message}`);
this.options.onTileError(tile, message, url);
}
_onTileLoad(tile, loaded) {
if (!loaded) {
return;
async _loadTile(tile) {
let loaded;
try {
this._onStartTileLoading();
loaded = await tile.loadContent();
}
catch (error) {
this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));
}
finally {
this._onEndTileLoading();
this._onTileLoad(tile, loaded);
}
}
if (this.type === TILESET_TYPE.I3S) {
var _this$tileset, _this$tileset$nodePag;
const nodesInNodePages = ((_this$tileset = this.tileset) === null || _this$tileset === void 0 ? void 0 : (_this$tileset$nodePag = _this$tileset.nodePagesTile) === null || _this$tileset$nodePag === void 0 ? void 0 : _this$tileset$nodePag.nodesInNodePages) || 0;
this.stats.get(TILES_TOTAL).reset();
this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
_onTileLoadError(tile, error) {
this.stats.get(TILES_LOAD_FAILED).incrementCount();
const message = error.message || error.toString();
const url = tile.url;
// TODO - Allow for probe log to be injected instead of console?
console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line
this.options.onTileError(tile, message, url);
}
if (tile && tile.content) {
calculateTransformProps(tile, tile.content);
_onTileLoad(tile, loaded) {
if (!loaded) {
return;
}
if (this.type === TILESET_TYPE.I3S) {
// We can't calculate tiles total in I3S in advance so we calculate it dynamically.
const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0;
this.stats.get(TILES_TOTAL).reset();
this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);
}
// add coordinateOrigin and modelMatrix to tile
if (tile && tile.content) {
calculateTransformProps(tile, tile.content);
}
this.updateContentTypes(tile);
this._addTileToCache(tile);
this.options.onTileLoad(tile);
}
this.updateContentTypes(tile);
this._addTileToCache(tile);
this.options.onTileLoad(tile);
}
updateContentTypes(tile) {
if (this.type === TILESET_TYPE.I3S) {
if (tile.header.isDracoGeometry) {
this.contentFormats.draco = true;
}
switch (tile.header.textureFormat) {
case 'dds':
this.contentFormats.dds = true;
break;
case 'ktx2':
this.contentFormats.ktx2 = true;
break;
default:
}
} else if (this.type === TILESET_TYPE.TILES3D) {
var _tile$content;
const {
extensionsRemoved = []
} = ((_tile$content = tile.content) === null || _tile$content === void 0 ? void 0 : _tile$content.gltf) || {};
if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
this.contentFormats.draco = true;
}
if (extensionsRemoved.includes('EXT_meshopt_compression')) {
this.contentFormats.meshopt = true;
}
if (extensionsRemoved.includes('KHR_texture_basisu')) {
this.contentFormats.ktx2 = true;
}
/**
* Update information about data types in nested tiles
* @param tile instance of a nested Tile3D
*/
updateContentTypes(tile) {
if (this.type === TILESET_TYPE.I3S) {
if (tile.header.isDracoGeometry) {
this.contentFormats.draco = true;
}
switch (tile.header.textureFormat) {
case 'dds':
this.contentFormats.dds = true;
break;
case 'ktx2':
this.contentFormats.ktx2 = true;
break;
default:
}
}
else if (this.type === TILESET_TYPE.TILES3D) {
const { extensionsRemoved = [] } = tile.content?.gltf || {};
if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {
this.contentFormats.draco = true;
}
if (extensionsRemoved.includes('EXT_meshopt_compression')) {
this.contentFormats.meshopt = true;
}
if (extensionsRemoved.includes('KHR_texture_basisu')) {
this.contentFormats.ktx2 = true;
}
}
}
}
_onStartTileLoading() {
this._pendingCount++;
this.stats.get(TILES_LOADING).incrementCount();
}
_onEndTileLoading() {
this._pendingCount--;
this.stats.get(TILES_LOADING).decrementCount();
}
_addTileToCache(tile) {
this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
}
_updateCacheStats(tile) {
this.stats.get(TILES_LOADED).incrementCount();
this.stats.get(TILES_IN_MEMORY).incrementCount();
this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
if (this.options.memoryAdjustedScreenSpaceError) {
this.adjustScreenSpaceError();
_onStartTileLoading() {
this._pendingCount++;
this.stats.get(TILES_LOADING).incrementCount();
}
}
_unloadTile(tile) {
this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
this.stats.get(TILES_IN_MEMORY).decrementCount();
this.stats.get(TILES_UNLOADED).incrementCount();
this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
this.options.onTileUnload(tile);
tile.unloadContent();
}
_destroy() {
const stack = [];
if (this.root) {
stack.push(this.root);
_onEndTileLoading() {
this._pendingCount--;
this.stats.get(TILES_LOADING).decrementCount();
}
while (stack.length > 0) {
const tile = stack.pop();
for (const child of tile.children) {
stack.push(child);
}
this._destroyTile(tile);
_addTileToCache(tile) {
this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile));
}
this.root = null;
}
_destroySubtree(tile) {
const root = tile;
const stack = [];
stack.push(root);
while (stack.length > 0) {
tile = stack.pop();
for (const child of tile.children) {
stack.push(child);
}
if (tile !== root) {
this._destroyTile(tile);
}
_updateCacheStats(tile) {
this.stats.get(TILES_LOADED).incrementCount();
this.stats.get(TILES_IN_MEMORY).incrementCount();
// TODO: Calculate GPU memory usage statistics for a tile.
this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;
this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
// Adjust SSE based on cache limits
if (this.options.memoryAdjustedScreenSpaceError) {
this.adjustScreenSpaceError();
}
}
root.children = [];
}
_destroyTile(tile) {
this._cache.unloadTile(this, tile);
this._unloadTile(tile);
tile.destroy();
}
_initializeTiles3DTileset(tilesetJson) {
if (tilesetJson.queryString) {
const searchParams = new URLSearchParams(tilesetJson.queryString);
const queryParams = Object.fromEntries(searchParams.entries());
this._queryParams = {
...this._queryParams,
...queryParams
};
_unloadTile(tile) {
this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;
this.stats.get(TILES_IN_MEMORY).decrementCount();
this.stats.get(TILES_UNLOADED).incrementCount();
this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
this.options.onTileUnload(tile);
tile.unloadContent();
}
this.asset = tilesetJson.asset;
if (!this.asset) {
throw new Error('Tileset must have an asset property.');
// Traverse the tree and destroy all tiles
_destroy() {
const stack = [];
if (this.root) {
stack.push(this.root);
}
while (stack.length > 0) {
const tile = stack.pop();
for (const child of tile.children) {
stack.push(child);
}
this._destroyTile(tile);
}
this.root = null;
}
if (this.asset.version !== '0.0' && this.asset.version !== '1.0' && this.asset.version !== '1.1') {
throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
// Traverse the tree and destroy all sub tiles
_destroySubtree(tile) {
const root = tile;
const stack = [];
stack.push(root);
while (stack.length > 0) {
tile = stack.pop();
for (const child of tile.children) {
stack.push(child);
}
if (tile !== root) {
this._destroyTile(tile);
}
}
root.children = [];
}
if ('tilesetVersion' in this.asset) {
this._queryParams.v = this.asset.tilesetVersion;
_destroyTile(tile) {
this._cache.unloadTile(this, tile);
this._unloadTile(tile);
tile.destroy();
}
this.credits = {
attributions: this.options.attributions || []
};
this.description = this.options.description || '';
this.properties = tilesetJson.properties;
this.geometricError = tilesetJson.geometricError;
this._extensionsUsed = tilesetJson.extensionsUsed || [];
this.extras = tilesetJson.extras;
}
_initializeI3STileset() {
if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
this._queryParams.token = this.loadOptions.i3s.token;
_initializeTiles3DTileset(tilesetJson) {
if (tilesetJson.queryString) {
const searchParams = new URLSearchParams(tilesetJson.queryString);
const queryParams = Object.fromEntries(searchParams.entries());
this._queryParams = { ...this._queryParams, ...queryParams };
}
this.asset = tilesetJson.asset;
if (!this.asset) {
throw new Error('Tileset must have an asset property.');
}
if (this.asset.version !== '0.0' &&
this.asset.version !== '1.0' &&
this.asset.version !== '1.1') {
throw new Error('The tileset must be 3D Tiles version either 0.0 or 1.0 or 1.1.');
}
// Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard)
// We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version
if ('tilesetVersion' in this.asset) {
this._queryParams.v = this.asset.tilesetVersion;
}
// TODO - ion resources have a credits property we can use for additional attribution.
this.credits = {
attributions: this.options.attributions || []
};
this.description = this.options.description || '';
// Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
this.properties = tilesetJson.properties;
this.geometricError = tilesetJson.geometricError;
this._extensionsUsed = tilesetJson.extensionsUsed || [];
// Returns the extras property at the top of the tileset JSON (application specific metadata).
this.extras = tilesetJson.extras;
}
}
_initializeI3STileset() {
// @ts-expect-error
if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
// @ts-ignore
this._queryParams.token = this.loadOptions.i3s.token;
}
}
}
//# sourceMappingURL=tileset-3d.js.map

@@ -1,3 +0,3 @@

import type { Tileset3D } from './tileset-3d';
import type { Tile3D } from './tile-3d';
import type { Tileset3D } from "./tileset-3d.js";
import type { Tile3D } from "./tile-3d.js";
/**

@@ -4,0 +4,0 @@ * Stores tiles with content loaded.

@@ -0,56 +1,70 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { DoublyLinkedList } from "../utils/doubly-linked-list.js";
/**
* Stores tiles with content loaded.
* @private
*/
export class TilesetCache {
constructor() {
this._list = void 0;
this._sentinel = void 0;
this._trimTiles = void 0;
this._list = new DoublyLinkedList();
this._sentinel = this._list.add('sentinel');
this._trimTiles = false;
}
reset() {
this._list.splice(this._list.tail, this._sentinel);
}
touch(tile) {
const node = tile._cacheNode;
if (node) {
this._list.splice(this._sentinel, node);
constructor() {
// [head, sentinel) -> tiles that weren't selected this frame and may be removed from the cache
// (sentinel, tail] -> tiles that were selected this frame
this._list = new DoublyLinkedList();
this._sentinel = this._list.add('sentinel');
this._trimTiles = false;
}
}
add(tileset, tile, addCallback) {
if (!tile._cacheNode) {
tile._cacheNode = this._list.add(tile);
if (addCallback) {
addCallback(tileset, tile);
}
reset() {
// Move sentinel node to the tail so, at the start of the frame, all tiles
// may be potentially replaced. Tiles are moved to the right of the sentinel
// when they are selected so they will not be replaced.
this._list.splice(this._list.tail, this._sentinel);
}
}
unloadTile(tileset, tile, unloadCallback) {
const node = tile._cacheNode;
if (!node) {
return;
touch(tile) {
const node = tile._cacheNode;
if (node) {
this._list.splice(this._sentinel, node);
}
}
this._list.remove(node);
tile._cacheNode = null;
if (unloadCallback) {
unloadCallback(tileset, tile);
add(tileset, tile, addCallback) {
if (!tile._cacheNode) {
tile._cacheNode = this._list.add(tile);
if (addCallback) {
addCallback(tileset, tile);
}
}
}
}
unloadTiles(tileset, unloadCallback) {
const trimTiles = this._trimTiles;
this._trimTiles = false;
const list = this._list;
const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
const sentinel = this._sentinel;
let node = list.head;
while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
const tile = node.item;
node = node.next;
this.unloadTile(tileset, tile, unloadCallback);
unloadTile(tileset, tile, unloadCallback) {
const node = tile._cacheNode;
if (!node) {
return;
}
this._list.remove(node);
tile._cacheNode = null;
if (unloadCallback) {
unloadCallback(tileset, tile);
}
}
}
trim() {
this._trimTiles = true;
}
unloadTiles(tileset, unloadCallback) {
const trimTiles = this._trimTiles;
this._trimTiles = false;
const list = this._list;
const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;
// Traverse the list only to the sentinel since tiles/nodes to the
// right of the sentinel were used this frame.
// The sub-list to the left of the sentinel is ordered from LRU to MRU.
const sentinel = this._sentinel;
let node = list.head;
while (node !== sentinel &&
(tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
// @ts-expect-error
const tile = node.item;
// @ts-expect-error
node = node.next;
this.unloadTile(tileset, tile, unloadCallback);
}
}
trim() {
this._trimTiles = true;
}
}
//# sourceMappingURL=tileset-cache.js.map

@@ -1,4 +0,4 @@

import type { Tile3D } from './tile-3d';
import { ManagedArray } from '../utils/managed-array';
import { FrameState } from './helpers/frame-state';
import type { Tile3D } from "./tile-3d.js";
import { ManagedArray } from "../utils/managed-array.js";
import { FrameState } from "./helpers/frame-state.js";
export type TilesetTraverserProps = {

@@ -5,0 +5,0 @@ loadSiblings?: boolean;

@@ -0,234 +1,295 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { ManagedArray } from "../utils/managed-array.js";
import { TILE_REFINEMENT } from "../constants.js";
export const DEFAULT_PROPS = {
loadSiblings: false,
skipLevelOfDetail: false,
updateTransforms: true,
onTraversalEnd: () => {},
viewportTraversersMap: {},
basePath: ''
loadSiblings: false,
skipLevelOfDetail: false,
updateTransforms: true,
onTraversalEnd: () => { },
viewportTraversersMap: {},
basePath: ''
};
export class TilesetTraverser {
traversalFinished(frameState) {
return true;
}
constructor(options) {
this.options = void 0;
this.root = null;
this.selectedTiles = {};
this.requestedTiles = {};
this.emptyTiles = {};
this.lastUpdate = new Date().getTime();
this.updateDebounceTime = 1000;
this._traversalStack = new ManagedArray();
this._emptyTraversalStack = new ManagedArray();
this._frameNumber = null;
this.options = {
...DEFAULT_PROPS,
...options
};
}
traverse(root, frameState, options) {
this.root = root;
this.options = {
...this.options,
...options
};
this.reset();
this.updateTile(root, frameState);
this._frameNumber = frameState.frameNumber;
this.executeTraversal(root, frameState);
}
reset() {
this.requestedTiles = {};
this.selectedTiles = {};
this.emptyTiles = {};
this._traversalStack.reset();
this._emptyTraversalStack.reset();
}
executeTraversal(root, frameState) {
const stack = this._traversalStack;
root._selectionDepth = 1;
stack.push(root);
while (stack.length > 0) {
const tile = stack.pop();
let shouldRefine = false;
if (this.canTraverse(tile, frameState)) {
this.updateChildTiles(tile, frameState);
shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
}
const parent = tile.parent;
const parentRefines = Boolean(!parent || parent._shouldRefine);
const stoppedRefining = !shouldRefine;
if (!tile.hasRenderContent) {
this.emptyTiles[tile.id] = tile;
this.loadTile(tile, frameState);
if (stoppedRefining) {
this.selectTile(tile, frameState);
}
} else if (tile.refine === TILE_REFINEMENT.ADD) {
this.loadTile(tile, frameState);
this.selectTile(tile, frameState);
} else if (tile.refine === TILE_REFINEMENT.REPLACE) {
this.loadTile(tile, frameState);
if (stoppedRefining) {
this.selectTile(tile, frameState);
}
}
this.touchTile(tile, frameState);
tile._shouldRefine = shouldRefine && parentRefines;
// RESULT
traversalFinished(frameState) {
return true;
}
const newTime = new Date().getTime();
if (this.traversalFinished(frameState) || newTime - this.lastUpdate > this.updateDebounceTime) {
this.lastUpdate = newTime;
this.options.onTraversalEnd(frameState);
// TODO nested props
constructor(options) {
// fulfill in traverse call
this.root = null;
// tiles should be rendered
this.selectedTiles = {};
// tiles should be loaded from server
this.requestedTiles = {};
// tiles does not have render content
this.emptyTiles = {};
this.lastUpdate = new Date().getTime();
this.updateDebounceTime = 1000;
/** temporary storage to hold the traversed tiles during a traversal */
this._traversalStack = new ManagedArray();
this._emptyTraversalStack = new ManagedArray();
/** set in every traverse cycle */
this._frameNumber = null;
this.options = { ...DEFAULT_PROPS, ...options };
}
}
updateChildTiles(tile, frameState) {
const children = tile.children;
for (const child of children) {
this.updateTile(child, frameState);
// tiles should be visible
traverse(root, frameState, options) {
this.root = root; // for root screen space error
this.options = { ...this.options, ...options };
// reset result
this.reset();
// update tile (visibility and expiration)
this.updateTile(root, frameState);
this._frameNumber = frameState.frameNumber;
this.executeTraversal(root, frameState);
}
}
updateAndPushChildren(tile, frameState, stack, depth) {
const {
loadSiblings,
skipLevelOfDetail
} = this.options;
const children = tile.children;
children.sort(this.compareDistanceToCamera.bind(this));
const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
let hasVisibleChild = false;
let refines = true;
for (const child of children) {
child._selectionDepth = depth;
if (child.isVisibleAndInRequestVolume) {
if (stack.find(child)) {
stack.delete(child);
reset() {
this.requestedTiles = {};
this.selectedTiles = {};
this.emptyTiles = {};
this._traversalStack.reset();
this._emptyTraversalStack.reset();
}
/**
* Execute traverse
* Depth-first traversal that traverses all visible tiles and marks tiles for selection.
* If skipLevelOfDetail is off then a tile does not refine until all children are loaded.
* This is the traditional replacement refinement approach and is called the base traversal.
* Tiles that have a greater screen space error than the base screen space error are part of the base traversal,
* all other tiles are part of the skip traversal. The skip traversal allows for skipping levels of the tree
* and rendering children and parent tiles simultaneously.
*/
/* eslint-disable-next-line complexity, max-statements */
executeTraversal(root, frameState) {
// stack to store traversed tiles, only visible tiles should be added to stack
// visible: visible in the current view frustum
const stack = this._traversalStack;
root._selectionDepth = 1;
stack.push(root);
while (stack.length > 0) {
// 1. pop tile
const tile = stack.pop();
// 2. check if tile needs to be refine, needs refine if a tile's LoD is not sufficient and tile has available children (available content)
let shouldRefine = false;
if (this.canTraverse(tile, frameState)) {
this.updateChildTiles(tile, frameState);
shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
}
// 3. decide if should render (select) this tile
// - tile does not have render content
// - tile has render content and tile is `add` type (pointcloud)
// - tile has render content and tile is `replace` type (photogrammetry) and can't refine any further
const parent = tile.parent;
const parentRefines = Boolean(!parent || parent._shouldRefine);
const stoppedRefining = !shouldRefine;
if (!tile.hasRenderContent) {
this.emptyTiles[tile.id] = tile;
this.loadTile(tile, frameState);
if (stoppedRefining) {
this.selectTile(tile, frameState);
}
// additive tiles
}
else if (tile.refine === TILE_REFINEMENT.ADD) {
// Additive tiles are always loaded and selected
this.loadTile(tile, frameState);
this.selectTile(tile, frameState);
// replace tiles
}
else if (tile.refine === TILE_REFINEMENT.REPLACE) {
// Always load tiles in the base traversal
// Select tiles that can't refine further
this.loadTile(tile, frameState);
if (stoppedRefining) {
this.selectTile(tile, frameState);
}
}
// 3. update cache, most recent touched tiles have higher priority to be fetched from server
this.touchTile(tile, frameState);
// 4. update tile refine prop and parent refinement status to trickle down to the descendants
tile._shouldRefine = shouldRefine && parentRefines;
}
stack.push(child);
hasVisibleChild = true;
} else if (checkRefines || loadSiblings) {
this.loadTile(child, frameState);
this.touchTile(child, frameState);
}
if (checkRefines) {
let childRefines;
if (!child._inRequestVolume) {
childRefines = false;
} else if (!child.hasRenderContent) {
childRefines = this.executeEmptyTraversal(child, frameState);
} else {
childRefines = child.contentAvailable;
const newTime = new Date().getTime();
if (this.traversalFinished(frameState) || newTime - this.lastUpdate > this.updateDebounceTime) {
this.lastUpdate = newTime;
this.options.onTraversalEnd(frameState);
}
refines = refines && childRefines;
if (!refines) {
return false;
}
updateChildTiles(tile, frameState) {
const children = tile.children;
for (const child of children) {
this.updateTile(child, frameState);
}
}
}
if (!hasVisibleChild) {
refines = false;
/* eslint-disable complexity, max-statements */
updateAndPushChildren(tile, frameState, stack, depth) {
const { loadSiblings, skipLevelOfDetail } = this.options;
const children = tile.children;
// sort children tiles
children.sort(this.compareDistanceToCamera.bind(this));
// For traditional replacement refinement only refine if all children are loaded.
// Empty tiles are exempt since it looks better if children stream in as they are loaded to fill the empty space.
const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
let hasVisibleChild = false;
let refines = true;
for (const child of children) {
child._selectionDepth = depth;
if (child.isVisibleAndInRequestVolume) {
if (stack.find(child)) {
stack.delete(child);
}
stack.push(child);
hasVisibleChild = true;
}
else if (checkRefines || loadSiblings) {
// Keep non-visible children loaded since they are still needed before the parent can refine.
// Or loadSiblings is true so always load tiles regardless of visibility.
this.loadTile(child, frameState);
this.touchTile(child, frameState);
}
if (checkRefines) {
let childRefines;
if (!child._inRequestVolume) {
childRefines = false;
}
else if (!child.hasRenderContent) {
childRefines = this.executeEmptyTraversal(child, frameState);
}
else {
childRefines = child.contentAvailable;
}
refines = refines && childRefines;
if (!refines) {
return false;
}
}
}
if (!hasVisibleChild) {
refines = false;
}
return refines;
}
return refines;
}
updateTile(tile, frameState) {
this.updateTileVisibility(tile, frameState);
}
selectTile(tile, frameState) {
if (this.shouldSelectTile(tile)) {
tile._selectedFrame = frameState.frameNumber;
this.selectedTiles[tile.id] = tile;
/* eslint-enable complexity, max-statements */
updateTile(tile, frameState) {
this.updateTileVisibility(tile, frameState);
}
}
loadTile(tile, frameState) {
if (this.shouldLoadTile(tile)) {
tile._requestedFrame = frameState.frameNumber;
tile._priority = tile._getPriority();
this.requestedTiles[tile.id] = tile;
// tile to render in the browser
selectTile(tile, frameState) {
if (this.shouldSelectTile(tile)) {
// The tile can be selected right away and does not require traverseAndSelect
tile._selectedFrame = frameState.frameNumber;
this.selectedTiles[tile.id] = tile;
}
}
}
touchTile(tile, frameState) {
tile.tileset._cache.touch(tile);
tile._touchedFrame = frameState.frameNumber;
}
canTraverse(tile, frameState) {
let useParentMetric = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
let ignoreVisibility = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (!tile.hasChildren) {
return false;
// tile to load from server
loadTile(tile, frameState) {
if (this.shouldLoadTile(tile)) {
tile._requestedFrame = frameState.frameNumber;
tile._priority = tile._getPriority();
this.requestedTiles[tile.id] = tile;
}
}
if (tile.hasTilesetContent) {
return !tile.contentExpired;
// cache tile
touchTile(tile, frameState) {
tile.tileset._cache.touch(tile);
tile._touchedFrame = frameState.frameNumber;
}
if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
return false;
// tile should be visible
// tile should have children
// tile LoD (level of detail) is not sufficient under current viewport
canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
if (!tile.hasChildren) {
return false;
}
// cesium specific
if (tile.hasTilesetContent) {
// Traverse external this to visit its root tile
// Don't traverse if the subtree is expired because it will be destroyed
return !tile.contentExpired;
}
if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
return false;
}
return this.shouldRefine(tile, frameState, useParentMetric);
}
return this.shouldRefine(tile, frameState, useParentMetric);
}
shouldLoadTile(tile) {
return tile.hasUnloadedContent || tile.contentExpired;
}
shouldSelectTile(tile) {
return tile.contentAvailable && !this.options.skipLevelOfDetail;
}
shouldRefine(tile, frameState) {
let useParentMetric = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
let screenSpaceError = tile._screenSpaceError;
if (useParentMetric) {
screenSpaceError = tile.getScreenSpaceError(frameState, true);
shouldLoadTile(tile) {
// if request tile is in current frame
// and has unexpired render content
return tile.hasUnloadedContent || tile.contentExpired;
}
return screenSpaceError > tile.tileset.memoryAdjustedScreenSpaceError;
}
updateTileVisibility(tile, frameState) {
const viewportIds = [];
if (this.options.viewportTraversersMap) {
for (const key in this.options.viewportTraversersMap) {
const value = this.options.viewportTraversersMap[key];
if (value === frameState.viewport.id) {
viewportIds.push(key);
shouldSelectTile(tile) {
// if select tile is in current frame
// and content available
return tile.contentAvailable && !this.options.skipLevelOfDetail;
}
/** Decide if tile LoD (level of detail) is not sufficient under current viewport */
shouldRefine(tile, frameState, useParentMetric = false) {
let screenSpaceError = tile._screenSpaceError;
if (useParentMetric) {
screenSpaceError = tile.getScreenSpaceError(frameState, true);
}
}
} else {
viewportIds.push(frameState.viewport.id);
return screenSpaceError > tile.tileset.memoryAdjustedScreenSpaceError;
}
tile.updateVisibility(frameState, viewportIds);
}
compareDistanceToCamera(b, a) {
return b._distanceToCamera - a._distanceToCamera;
}
anyChildrenVisible(tile, frameState) {
let anyVisible = false;
for (const child of tile.children) {
child.updateVisibility(frameState);
anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
updateTileVisibility(tile, frameState) {
const viewportIds = [];
if (this.options.viewportTraversersMap) {
for (const key in this.options.viewportTraversersMap) {
const value = this.options.viewportTraversersMap[key];
if (value === frameState.viewport.id) {
viewportIds.push(key);
}
}
}
else {
viewportIds.push(frameState.viewport.id);
}
tile.updateVisibility(frameState, viewportIds);
}
return anyVisible;
}
executeEmptyTraversal(root, frameState) {
let allDescendantsLoaded = true;
const stack = this._emptyTraversalStack;
stack.push(root);
while (stack.length > 0) {
const tile = stack.pop();
const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, false);
const emptyLeaf = !tile.hasRenderContent && tile.children.length === 0;
if (!traverse && !tile.contentAvailable && !emptyLeaf) {
allDescendantsLoaded = false;
}
this.updateTile(tile, frameState);
if (!tile.isVisibleAndInRequestVolume) {
this.loadTile(tile, frameState);
this.touchTile(tile, frameState);
}
if (traverse) {
const children = tile.children;
for (const child of children) {
stack.push(child);
// UTILITIES
compareDistanceToCamera(b, a) {
return b._distanceToCamera - a._distanceToCamera;
}
anyChildrenVisible(tile, frameState) {
let anyVisible = false;
for (const child of tile.children) {
// @ts-expect-error
child.updateVisibility(frameState);
// @ts-expect-error
anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
}
}
return anyVisible;
}
return allDescendantsLoaded;
}
// Depth-first traversal that checks if all nearest descendants with content are loaded.
// Ignores visibility.
executeEmptyTraversal(root, frameState) {
let allDescendantsLoaded = true;
const stack = this._emptyTraversalStack;
stack.push(root);
while (stack.length > 0) {
const tile = stack.pop();
const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, false);
const emptyLeaf = !tile.hasRenderContent && tile.children.length === 0;
// Traversal stops but the tile does not have content yet
// There will be holes if the parent tries to refine to its children, so don't refine
// One exception: a parent may refine even if one of its descendants is an empty leaf
if (!traverse && !tile.contentAvailable && !emptyLeaf) {
allDescendantsLoaded = false;
}
this.updateTile(tile, frameState);
if (!tile.isVisibleAndInRequestVolume) {
this.loadTile(tile, frameState);
this.touchTile(tile, frameState);
}
if (traverse) {
const children = tile.children;
for (const child of children) {
stack.push(child);
}
}
}
return allDescendantsLoaded;
}
}
//# sourceMappingURL=tileset-traverser.js.map
export {};
//# sourceMappingURL=types.js.map

@@ -0,11 +1,16 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
/**
* Doubly linked list node
* @private
*/
export class DoublyLinkedListNode {
constructor(item, previous, next) {
this.item = void 0;
this.previous = void 0;
this.next = void 0;
this.item = item;
this.previous = previous;
this.next = next;
}
constructor(item, previous, next) {
this.item = item;
this.previous = previous;
this.next = next;
}
}
//# sourceMappingURL=doubly-linked-list-node.js.map

@@ -1,2 +0,2 @@

import { DoublyLinkedListNode } from './doubly-linked-list-node';
import { DoublyLinkedListNode } from "./doubly-linked-list-node.js";
/**

@@ -3,0 +3,0 @@ * Doubly linked list

@@ -0,64 +1,93 @@

// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
import { DoublyLinkedListNode } from "./doubly-linked-list-node.js";
/**
* Doubly linked list
* @private
*/
export class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this._length = 0;
}
get length() {
return this._length;
}
add(item) {
const node = new DoublyLinkedListNode(item, this.tail, null);
if (this.tail) {
this.tail.next = node;
this.tail = node;
} else {
this.head = node;
this.tail = node;
constructor() {
this.head = null;
this.tail = null;
this._length = 0;
}
++this._length;
return node;
}
remove(node) {
if (!node) {
return;
get length() {
return this._length;
}
if (node.previous && node.next) {
node.previous.next = node.next;
node.next.previous = node.previous;
} else if (node.previous) {
node.previous.next = null;
this.tail = node.previous;
} else if (node.next) {
node.next.previous = null;
this.head = node.next;
} else {
this.head = null;
this.tail = null;
/**
* Adds the item to the end of the list
* @param {*} [item]
* @return {DoublyLinkedListNode}
*/
add(item) {
const node = new DoublyLinkedListNode(item, this.tail, null);
if (this.tail) {
this.tail.next = node;
this.tail = node;
}
else {
this.head = node;
this.tail = node;
}
++this._length;
return node;
}
node.next = null;
node.previous = null;
--this._length;
}
splice(node, nextNode) {
if (node === nextNode) {
return;
/**
* Removes the given node from the list
* @param {DoublyLinkedListNode} node
*/
remove(node) {
if (!node) {
return;
}
if (node.previous && node.next) {
node.previous.next = node.next;
node.next.previous = node.previous;
}
else if (node.previous) {
// Remove last node
node.previous.next = null;
this.tail = node.previous;
}
else if (node.next) {
// Remove first node
node.next.previous = null;
this.head = node.next;
}
else {
// Remove last node in the linked list
this.head = null;
this.tail = null;
}
node.next = null;
node.previous = null;
--this._length;
}
this.remove(nextNode);
this._insert(node, nextNode);
}
_insert(node, nextNode) {
const oldNodeNext = node.next;
node.next = nextNode;
if (this.tail === node) {
this.tail = nextNode;
} else {
oldNodeNext.previous = nextNode;
/**
* Moves nextNode after node
* @param {DoublyLinkedListNode} node
* @param {DoublyLinkedListNode} nextNode
*/
splice(node, nextNode) {
if (node === nextNode) {
return;
}
// Remove nextNode, then insert after node
this.remove(nextNode);
this._insert(node, nextNode);
}
nextNode.next = oldNodeNext;
nextNode.previous = node;
++this._length;
}
_insert(node, nextNode) {
const oldNodeNext = node.next;
node.next = nextNode;
// nextNode is the new tail
if (this.tail === node) {
this.tail = nextNode;
}
else {
oldNodeNext.previous = nextNode;
}
nextNode.next = oldNodeNext;
nextNode.previous = node;
++this._length;
}
}
//# sourceMappingURL=doubly-linked-list.js.map

@@ -0,86 +1,148 @@

// This file is derived from the Cesium code base under Apache 2 license
// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md
import { assert } from '@loaders.gl/loader-utils';
/**
* A wrapper around arrays so that the internal length of the array can be manually managed.
*
* @alias ManagedArray
* @constructor
* @private
*
* @param {Number} [length=0] The initial length of the array.
*/
export class ManagedArray {
constructor() {
let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
this._map = new Map();
this._array = void 0;
this._length = void 0;
this._array = new Array(length);
this._length = length;
}
get length() {
return this._length;
}
set length(length) {
this._length = length;
if (length > this._array.length) {
this._array.length = length;
constructor(length = 0) {
this._map = new Map();
this._array = new Array(length);
this._length = length;
}
}
get values() {
return this._array;
}
get(index) {
assert(index < this._array.length);
return this._array[index];
}
set(index, element) {
assert(index >= 0);
if (index >= this.length) {
this.length = index + 1;
/**
* Gets or sets the length of the array.
* If the set length is greater than the length of the internal array, the internal array is resized.
*
* @memberof ManagedArray.prototype
* @type Number
*/
get length() {
return this._length;
}
if (this._map.has(this._array[index])) {
this._map.delete(this._array[index]);
set length(length) {
this._length = length;
if (length > this._array.length) {
this._array.length = length;
}
}
this._array[index] = element;
this._map.set(element, index);
}
delete(element) {
const index = this._map.get(element);
if (index >= 0) {
this._array.splice(index, 1);
this._map.delete(element);
this.length--;
/**
* Gets the internal array.
*
* @memberof ManagedArray.prototype
* @type Array
* @readonly
*/
get values() {
return this._array;
}
}
peek() {
return this._array[this._length - 1];
}
push(element) {
if (!this._map.has(element)) {
const index = this.length++;
this._array[index] = element;
this._map.set(element, index);
/**
* Gets the element at an index.
*
* @param {Number} index The index to get.
*/
get(index) {
assert(index < this._array.length);
return this._array[index];
}
}
pop() {
const element = this._array[--this.length];
this._map.delete(element);
return element;
}
reserve(length) {
assert(length >= 0);
if (length > this._array.length) {
this._array.length = length;
/**
* Sets the element at an index. Resizes the array if index is greater than the length of the array.
*
* @param {Number} index The index to set.
* @param {*} element The element to set at index.
*/
set(index, element) {
assert(index >= 0);
if (index >= this.length) {
this.length = index + 1;
}
if (this._map.has(this._array[index])) {
this._map.delete(this._array[index]);
}
this._array[index] = element;
this._map.set(element, index);
}
}
resize(length) {
assert(length >= 0);
this.length = length;
}
trim(length) {
if (length === null || length === undefined) {
length = this.length;
delete(element) {
const index = this._map.get(element);
if (index >= 0) {
this._array.splice(index, 1);
this._map.delete(element);
this.length--;
}
}
this._array.length = length;
}
reset() {
this._array = [];
this._map = new Map();
this._length = 0;
}
find(target) {
return this._map.has(target);
}
/**
* Returns the last element in the array without modifying the array.
*
* @returns {*} The last element in the array.
*/
peek() {
return this._array[this._length - 1];
}
/**
* Push an element into the array.
*
* @param {*} element The element to push.
*/
push(element) {
if (!this._map.has(element)) {
const index = this.length++;
this._array[index] = element;
this._map.set(element, index);
}
}
/**
* Pop an element from the array.
*
* @returns {*} The last element in the array.
*/
pop() {
const element = this._array[--this.length];
this._map.delete(element);
return element;
}
/**
* Resize the internal array if length > _array.length.
*
* @param {Number} length The length.
*/
reserve(length) {
assert(length >= 0);
if (length > this._array.length) {
this._array.length = length;
}
}
/**
* Resize the array.
*
* @param {Number} length The length.
*/
resize(length) {
assert(length >= 0);
this.length = length;
}
/**
* Trim the internal array to the specified length. Defaults to the current length.
*
* @param {Number} [length] The length.
*/
trim(length) {
if (length === null || length === undefined) {
length = this.length;
}
this._array.length = length;
}
reset() {
this._array = [];
this._map = new Map();
this._length = 0;
}
find(target) {
return this._map.has(target);
}
}
//# sourceMappingURL=managed-array.js.map
{
"name": "@loaders.gl/tiles",
"version": "4.2.0-alpha.4",
"version": "4.2.0-alpha.5",
"description": "Common components for different tiles loaders.",

@@ -40,8 +40,9 @@ "license": "MIT",

"scripts": {
"pre-build": "npm run build-bundle && npm run build-bundle -- --env=dev",
"build-bundle": "ocular-bundle ./src/index.ts"
"pre-build": "npm run build-bundle && npm run build-bundle-dev",
"build-bundle": "ocular-bundle ./bundle.ts --output=dist/dist.min.js",
"build-bundle-dev": "ocular-bundle ./bundle.ts --env=dev --output=dist/dist.dev.js"
},
"dependencies": {
"@loaders.gl/loader-utils": "4.2.0-alpha.4",
"@loaders.gl/math": "4.2.0-alpha.4",
"@loaders.gl/loader-utils": "4.2.0-alpha.5",
"@loaders.gl/math": "4.2.0-alpha.5",
"@math.gl/core": "^4.0.0",

@@ -53,9 +54,9 @@ "@math.gl/culling": "^4.0.0",

},
"devDependencies": {
"@deck.gl/core": "^8.9.0"
},
"peerDependencies": {
"@loaders.gl/core": "^4.0.0"
},
"devDependencies": {
"@deck.gl/core": "^8.9.0"
},
"gitHead": "6c52dee5c3f005648a394cc4aee7fc37005c8e83"
"gitHead": "32d95a81971f104e4dfeb88ab57065f05321a76a"
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc