mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Map stacks off the Cesium allow-list: providers move into the Cesium adapter
The map stacks' imagery, terrain and Google 3D factories move into the Cesium adapter (src/render/cesium/mapImagery.js, mapTerrain.js, google3d.js); the ./maps/imagery, ./maps/terrain and ./maps/3d exports point there. The catalog names its ion stacks by asset number, and the map source controller and default sources are Cesium-free: they build providers and switch imagery layers, terrain, tilesets and the globe's visibility through a map engine (src/maps/engine.js) that the Cesium adapter provides as it loads (mapEngine.js), through the application's renderer or the ./render/cesium/unbound export. The controller and createDefaultMapSources also take it as an `engine` option. src/maps/catalog.js, controller.js, imagery.js, terrain.js and google3d.js leave the allow-list.
This commit is contained in:
1 parent
aea5c3acc6
commit
a8a9cc73a4
31 files changed
+364
-140
No files matched your search
@@ -22,6 +22,8 @@ import { CONTRACT_VERSION } from '../contract/index.js';
|
||||
import { bindRenderer } from '../rendererOf.js';
|
||||
import { createCesiumInput } from './input.js';
|
||||
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
|
||||
// The application's map stacks switch through the Cesium map engine.
|
||||
import './mapEngine.js';
|
||||
|
||||
/** @typedef {import('../contract/renderer').Renderer} TransitionalRenderer */
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* the scene has no part for (stars without a sky box, say) is kept as set.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { loadPhotorealisticTileset } from '../../maps/google3d.js';
|
||||
import { loadPhotorealisticTileset } from './google3d.js';
|
||||
import { provideUnboundGlobe } from '../rendererOf.js';
|
||||
import { isBaseTileset, markBaseTileset } from '../baseTilesets.js';
|
||||
import { listenerList, uncaught } from './common.js';
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @module render/cesium/google3d
|
||||
* @description Google Photorealistic 3D Tiles for the Cesium renderer, by
|
||||
* the routes `selectMapStartupRoute` (`src/maps/startupRoute.js`) names.
|
||||
*/
|
||||
export { selectMapStartupRoute } from '../../maps/startupRoute.js';
|
||||
|
||||
const clean = (value) => String(value || '').trim();
|
||||
|
||||
/**
|
||||
* Load Google Photorealistic 3D Tiles through direct Google access when
|
||||
* configured, otherwise through Cesium ion's hosted Google asset. Direct
|
||||
* access uses a browser key, or else short-lived tokens from the app's
|
||||
* server (see googleTokens.js). If direct access fails and an ion token is
|
||||
* available, ion is the recovery path.
|
||||
*
|
||||
* @param {object} Cesium
|
||||
* @param {{googleApiKey?: string, cesiumToken?: string, googleTokens?: {token: Function}|null}} credentials
|
||||
* @returns {Promise<{tileset: object|null, route: 'google-direct'|'google-token'|'google-ion'|'osm', errors: Error[]}>}
|
||||
*/
|
||||
export async function loadPhotorealisticTileset(
|
||||
Cesium,
|
||||
{ googleApiKey = '', cesiumToken = '', googleTokens = null } = {},
|
||||
) {
|
||||
const googleKey = clean(googleApiKey);
|
||||
const ionToken = clean(cesiumToken);
|
||||
const errors = [];
|
||||
|
||||
const attempts = [];
|
||||
if (googleKey)
|
||||
attempts.push({
|
||||
route: 'google-direct',
|
||||
create: () => createGoogleDirectTileset(Cesium, googleKey),
|
||||
});
|
||||
else if (googleTokens)
|
||||
attempts.push({
|
||||
route: 'google-token',
|
||||
create: () => createGoogleTokenTileset(Cesium, googleTokens),
|
||||
});
|
||||
if (ionToken)
|
||||
attempts.push({
|
||||
route: 'google-ion',
|
||||
create: () => createGoogleIonTileset(Cesium, ionToken),
|
||||
});
|
||||
|
||||
for (const attempt of attempts) {
|
||||
try {
|
||||
const tileset = await attempt.create();
|
||||
return { tileset, route: attempt.route, errors };
|
||||
} catch (error) {
|
||||
errors.push(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
|
||||
return { tileset: null, route: 'osm', errors };
|
||||
}
|
||||
|
||||
/** Pass credentials to the source instead of changing SDK-wide defaults. */
|
||||
export function createGoogleDirectTileset(Cesium, key) {
|
||||
key = clean(key);
|
||||
if (!key) throw new Error('Google 3D requires an explicit browser key');
|
||||
// Tiles keep drawing their own texture while draped weather loads.
|
||||
return Cesium.createGooglePhotorealistic3DTileset(
|
||||
{ key, onlyUsingWithGoogleGeocoder: true },
|
||||
{ asynchronouslyLoadImagery: true },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Google 3D with short-lived tokens instead of a key. Every tile request
|
||||
* carries the token as a header; a tile refused for an expired token gets
|
||||
* the renewed one and is tried once more.
|
||||
*/
|
||||
export async function createGoogleTokenTileset(Cesium, tokens) {
|
||||
const token = await tokens.token();
|
||||
if (!token) throw new Error('Google 3D tokens are not offered');
|
||||
const credit = Cesium.GoogleMaps.getDefaultCredit?.();
|
||||
const resource = new Cesium.Resource({
|
||||
url: `${Cesium.GoogleMaps.mapTilesApiEndpoint}v1/3dtiles/root.json`,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
credits: credit ? [credit] : undefined,
|
||||
retryAttempts: 1,
|
||||
async retryCallback(failed, error) {
|
||||
if (![401, 403].includes(error?.statusCode)) return false;
|
||||
const used = failed.headers.Authorization?.replace(/^Bearer /, '');
|
||||
const renewed = await tokens.token({ replacing: used });
|
||||
if (!renewed || renewed === used) return false;
|
||||
failed.headers.Authorization = `Bearer ${renewed}`;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
// The settings Cesium's Google helper applies to the key route.
|
||||
return Cesium.Cesium3DTileset.fromUrl(resource, {
|
||||
cacheBytes: 1536 * 1024 * 1024,
|
||||
maximumCacheOverflowBytes: 1024 * 1024 * 1024,
|
||||
enableCollision: true,
|
||||
// Tiles keep drawing their own texture while draped weather loads.
|
||||
asynchronouslyLoadImagery: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createGoogleIonTileset(
|
||||
Cesium,
|
||||
accessToken,
|
||||
{ signal } = {},
|
||||
) {
|
||||
accessToken = clean(accessToken);
|
||||
if (!accessToken)
|
||||
throw new Error('Google 3D through ion requires an explicit token');
|
||||
signal?.throwIfAborted();
|
||||
const resource = await Cesium.IonResource.fromAssetId(2275207, {
|
||||
accessToken,
|
||||
});
|
||||
signal?.throwIfAborted();
|
||||
// Match the installed SDK's Google helper rendering/cache defaults.
|
||||
return Cesium.Cesium3DTileset.fromUrl(resource, {
|
||||
cacheBytes: 1536 * 1024 * 1024,
|
||||
maximumCacheOverflowBytes: 1024 * 1024 * 1024,
|
||||
enableCollision: true,
|
||||
// Tiles keep drawing their own texture while draped weather loads.
|
||||
asynchronouslyLoadImagery: true,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @module render/cesium/mapEngine
|
||||
* @description The Cesium map engine (`src/maps/engine.js`): the providers
|
||||
* the map stacks' imagery and terrain come from (`mapImagery.js`,
|
||||
* `mapTerrain.js`), and the viewer operations the map source controller
|
||||
* switches stacks with. Provided as this module loads.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { provideMapEngine } from '../../maps/engine.js';
|
||||
import {
|
||||
createEsriImagery,
|
||||
createIonImagery,
|
||||
createOsmImagery,
|
||||
} from './mapImagery.js';
|
||||
import { createKeylessTerrain, createWorldTerrain } from './mapTerrain.js';
|
||||
|
||||
export const cesiumMapEngine = Object.freeze({
|
||||
imagery: Object.freeze({
|
||||
osm: createOsmImagery,
|
||||
esri: createEsriImagery,
|
||||
/** `style`: the ion world imagery asset (`MAP_STACKS`' `style`). */
|
||||
ion: createIonImagery,
|
||||
}),
|
||||
terrain: Object.freeze({
|
||||
world: createWorldTerrain,
|
||||
keyless: createKeylessTerrain,
|
||||
}),
|
||||
/** The layer a globe stack's imagery provider draws through. */
|
||||
createImageryLayer: (provider) => new Cesium.ImageryLayer(provider),
|
||||
requestRender(viewer) {
|
||||
viewer?.scene?.requestRender?.();
|
||||
},
|
||||
globeShown: (viewer) => viewer?.scene?.globe?.show === true,
|
||||
setGlobeShown(viewer, shown) {
|
||||
viewer.scene.globe.show = shown;
|
||||
},
|
||||
addTileset(viewer, tileset) {
|
||||
viewer.scene.primitives.add(tileset);
|
||||
},
|
||||
removeTileset(viewer, tileset) {
|
||||
viewer.scene.primitives.remove(tileset);
|
||||
},
|
||||
tilesetShown: (tileset) => tileset?.show === true,
|
||||
showTileset(tileset, shown) {
|
||||
tileset.show = shown;
|
||||
},
|
||||
/** Below every other imagery layer, at `index`. */
|
||||
addImageryLayer(viewer, layer, index) {
|
||||
viewer.imageryLayers.add(layer, index);
|
||||
},
|
||||
/** Removed and destroyed. */
|
||||
removeImageryLayer(viewer, layer) {
|
||||
viewer.imageryLayers.remove(layer, true);
|
||||
},
|
||||
/** A terrain factory's result: `{terrain}` or `{provider}`. */
|
||||
applyTerrain(viewer, result) {
|
||||
if (result.terrain) viewer.scene.setTerrain(result.terrain);
|
||||
else viewer.terrainProvider = result.provider;
|
||||
},
|
||||
/**
|
||||
* Hear an imagery provider's failed tile requests, each with the times
|
||||
* Cesium retried it; null when the provider reports none.
|
||||
* @returns {(() => void) | null} Stop hearing them.
|
||||
*/
|
||||
onTileError(provider, listener) {
|
||||
const errorEvent = provider?.errorEvent;
|
||||
if (!errorEvent?.addEventListener) return null;
|
||||
return errorEvent.addEventListener((error) =>
|
||||
listener({ timesRetried: error?.timesRetried }),
|
||||
);
|
||||
},
|
||||
isDestroyed: (value) => value?.isDestroyed?.() === true,
|
||||
/** Destroy a provider or tileset unless it is already destroyed. */
|
||||
release(value) {
|
||||
if (typeof value?.destroy === 'function' && !value.isDestroyed?.())
|
||||
value.destroy();
|
||||
},
|
||||
});
|
||||
|
||||
provideMapEngine(cesiumMapEngine);
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @module render/cesium/mapImagery
|
||||
* @description The map stacks' imagery for the Cesium renderer: OSM, Esri
|
||||
* World Imagery and Cesium ion's world imagery (Bing over HTTPS).
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export { ESRI_ATTRIBUTION_HTML } from '../../maps/attribution.js';
|
||||
|
||||
export function createOsmImagery() {
|
||||
return new Cesium.OpenStreetMapImageryProvider({
|
||||
url: 'https://tile.openstreetmap.org/',
|
||||
credit: '© OpenStreetMap contributors',
|
||||
});
|
||||
}
|
||||
|
||||
export function createEsriImagery() {
|
||||
return Cesium.ArcGisMapServerImageryProvider.fromUrl(
|
||||
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
|
||||
{
|
||||
credit:
|
||||
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community',
|
||||
enablePickFeatures: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function createIonImagery(style, accessToken) {
|
||||
accessToken = String(accessToken || '').trim();
|
||||
if (!accessToken) throw new Error('Ion imagery requires an explicit token');
|
||||
if (
|
||||
style === Cesium.IonWorldImageryStyle.AERIAL ||
|
||||
style === Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS
|
||||
) {
|
||||
return createBingIonImagery(style, accessToken);
|
||||
}
|
||||
return Cesium.IonImageryProvider.fromAssetId(style, { accessToken });
|
||||
}
|
||||
|
||||
async function createBingIonImagery(style, accessToken) {
|
||||
const endpoint = await new Cesium.Resource({
|
||||
url: `https://api.cesium.com/v1/assets/${style}/endpoint`,
|
||||
queryParameters: { access_token: accessToken },
|
||||
}).fetchJson();
|
||||
if (
|
||||
endpoint?.type !== 'IMAGERY' ||
|
||||
endpoint.externalType !== 'BING' ||
|
||||
typeof endpoint.options?.url !== 'string'
|
||||
) {
|
||||
throw new Error('Ion world imagery did not return a Bing imagery endpoint');
|
||||
}
|
||||
// Bing otherwise follows the page's HTTP scheme on localhost. Resolve its
|
||||
// ion-issued credentials through public APIs so tiles use HTTPS without
|
||||
// weakening CSP, changing SDK defaults or touching provider internals.
|
||||
const { url, ...options } = endpoint.options;
|
||||
const provider = await Cesium.BingMapsImageryProvider.fromUrl(url, {
|
||||
...options,
|
||||
tileProtocol: 'https',
|
||||
});
|
||||
const ionCredits = (endpoint.attributions ?? []).map(
|
||||
({ html, collapsible }) => new Cesium.Credit(html, collapsible === false),
|
||||
);
|
||||
const getTileCredits = provider.getTileCredits.bind(provider);
|
||||
provider.getTileCredits = (x, y, level) => [
|
||||
...ionCredits,
|
||||
...(getTileCredits(x, y, level) ?? []),
|
||||
];
|
||||
return provider;
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createIonImagery } from './mapImagery.js';
|
||||
import { createWorldTerrain, createKeylessTerrain } from './mapTerrain.js';
|
||||
import { createDefaultMapSources } from '../../maps/defaultSources.js';
|
||||
import { MAP_STACKS } from '../../maps/catalog.js';
|
||||
import { mapEngine } from '../../maps/engine.js';
|
||||
import { cesiumMapEngine } from './mapEngine.js';
|
||||
|
||||
test('loading the Cesium map engine provides it to the map stacks', () => {
|
||||
assert.equal(mapEngine(), cesiumMapEngine);
|
||||
});
|
||||
|
||||
test('ion stacks name the Cesium ion world imagery assets', () => {
|
||||
const styles = Object.fromEntries(
|
||||
MAP_STACKS.filter(({ kind }) => kind === 'ion').map(({ id, style }) => [
|
||||
id,
|
||||
style,
|
||||
]),
|
||||
);
|
||||
assert.deepEqual(styles, {
|
||||
'bing-aerial': Cesium.IonWorldImageryStyle.AERIAL,
|
||||
'bing-labels': Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS,
|
||||
});
|
||||
});
|
||||
|
||||
test('Esri uses Re:Earth without keys and preserves ion terrain when configured', async () => {
|
||||
const originalTerrain = Cesium.CesiumTerrainProvider.fromUrl;
|
||||
const originalResource = Cesium.IonResource.fromAssetId;
|
||||
const calls = [];
|
||||
try {
|
||||
Cesium.CesiumTerrainProvider.fromUrl = async (resource) => {
|
||||
calls.push(resource);
|
||||
return { resource };
|
||||
};
|
||||
Cesium.IonResource.fromAssetId = async () =>
|
||||
assert.fail('keyless mode must not acquire ion terrain');
|
||||
const keyless = createDefaultMapSources();
|
||||
const esri = keyless.sources.find(
|
||||
({ descriptor }) => descriptor.id === 'esri-imagery',
|
||||
);
|
||||
assert.equal(esri.available, true);
|
||||
assert.equal(esri.terrain.id, 'keyless');
|
||||
await esri.terrain.create();
|
||||
// A Resource, not a bare URL: the retry policy rides on it (terrainRetry.js).
|
||||
assert.equal(calls.length, 1);
|
||||
assert.ok(calls[0] instanceof Cesium.Resource);
|
||||
assert.equal(
|
||||
calls[0].url,
|
||||
'https://terrain.reearth.land/cesium-mesh/ellipsoid',
|
||||
);
|
||||
assert.equal(calls[0].retryAttempts, 3);
|
||||
assert.equal(typeof calls[0].retryCallback, 'function');
|
||||
assert.equal(
|
||||
keyless.sources.find(({ descriptor }) => descriptor.id === 'photoreal')
|
||||
.available,
|
||||
false,
|
||||
);
|
||||
for (const credentials of [
|
||||
{ googleApiKey: 'test-key' },
|
||||
{ cesiumToken: 'test-token' },
|
||||
]) {
|
||||
const keyed = createDefaultMapSources({
|
||||
...credentials,
|
||||
googleTileset: { show: true },
|
||||
});
|
||||
assert.equal(
|
||||
keyed.sources.find(({ descriptor }) => descriptor.id === 'photoreal')
|
||||
.available,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
keyed.sources.find(({ descriptor }) => descriptor.id === 'esri-imagery')
|
||||
.terrain.id,
|
||||
credentials.cesiumToken ? 'world' : 'keyless',
|
||||
);
|
||||
const failedTileset = createDefaultMapSources(credentials);
|
||||
assert.equal(
|
||||
failedTileset.sources.find(
|
||||
({ descriptor }) => descriptor.id === 'photoreal',
|
||||
).available,
|
||||
false,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
Cesium.CesiumTerrainProvider.fromUrl = originalTerrain;
|
||||
Cesium.IonResource.fromAssetId = originalResource;
|
||||
}
|
||||
});
|
||||
|
||||
test('imagery and terrain pass their own ion token without relying on SDK defaults', async () => {
|
||||
const originalImagery = Cesium.IonImageryProvider.fromAssetId;
|
||||
const originalResource = Cesium.IonResource.fromAssetId;
|
||||
const originalTerrain = Cesium.CesiumTerrainProvider.fromUrl;
|
||||
const calls = [];
|
||||
const defaultToken = Cesium.Ion.defaultAccessToken;
|
||||
try {
|
||||
Cesium.IonImageryProvider.fromAssetId = async (id, options) => {
|
||||
calls.push({ kind: 'imagery', id, options });
|
||||
return { id };
|
||||
};
|
||||
Cesium.IonResource.fromAssetId = async (id, options) => {
|
||||
calls.push({ kind: 'resource', id, options });
|
||||
return { id };
|
||||
};
|
||||
Cesium.CesiumTerrainProvider.fromUrl = async (resource, options) => {
|
||||
calls.push({ kind: 'terrain', resource, options });
|
||||
return { id: 'terrain' };
|
||||
};
|
||||
await createIonImagery(12345, 'imagery-token');
|
||||
const result = await createWorldTerrain('terrain-token');
|
||||
assert.equal(calls[0].options.accessToken, 'imagery-token');
|
||||
assert.equal(calls[1].options.accessToken, 'terrain-token');
|
||||
assert.equal(calls[1].id, 1);
|
||||
assert.equal(calls[2].options.requestVertexNormals, true);
|
||||
assert.equal(result.provider.id, 'terrain');
|
||||
assert.equal(Cesium.Ion.defaultAccessToken, defaultToken);
|
||||
} finally {
|
||||
Cesium.IonImageryProvider.fromAssetId = originalImagery;
|
||||
Cesium.IonResource.fromAssetId = originalResource;
|
||||
Cesium.CesiumTerrainProvider.fromUrl = originalTerrain;
|
||||
}
|
||||
});
|
||||
|
||||
test('both Bing ion stacks use HTTPS and retain ion and per-tile attribution', async (t) => {
|
||||
const defaultToken = Cesium.Ion.defaultAccessToken;
|
||||
const metadataCalls = [];
|
||||
const bingCalls = [];
|
||||
const perTileCalls = [];
|
||||
const bingCredit = new Cesium.Credit('Bing tile credit', true);
|
||||
const endpoint = {
|
||||
type: 'IMAGERY',
|
||||
externalType: 'BING',
|
||||
options: Object.freeze({
|
||||
url: 'https://dev.virtualearth.net',
|
||||
key: 'ion-issued-bing-fixture',
|
||||
mapStyle: 'Aerial',
|
||||
tileProtocol: 'http',
|
||||
}),
|
||||
attributions: [
|
||||
{ html: 'Ion required credit', collapsible: false },
|
||||
{ html: 'Ion optional credit', collapsible: true },
|
||||
],
|
||||
};
|
||||
t.mock.method(Cesium.Resource.prototype, 'fetchJson', async function () {
|
||||
metadataCalls.push({
|
||||
url: this.url,
|
||||
token: this.queryParameters.access_token,
|
||||
});
|
||||
const mapStyle = this.url.includes(
|
||||
`/assets/${Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS}/`,
|
||||
)
|
||||
? 'AerialWithLabels'
|
||||
: 'Aerial';
|
||||
return {
|
||||
...endpoint,
|
||||
options: Object.freeze({ ...endpoint.options, mapStyle }),
|
||||
};
|
||||
});
|
||||
t.mock.method(Cesium.IonImageryProvider, 'fromAssetId', () =>
|
||||
assert.fail('Bing must not inherit the local HTTP page protocol'),
|
||||
);
|
||||
t.mock.method(
|
||||
Cesium.BingMapsImageryProvider,
|
||||
'fromUrl',
|
||||
async (url, options) => {
|
||||
bingCalls.push({ url, options });
|
||||
const provider = {
|
||||
errorEvent: new Cesium.Event(),
|
||||
getTileCredits(x, y, level) {
|
||||
assert.equal(this, provider);
|
||||
perTileCalls.push([x, y, level]);
|
||||
return level === 0 ? undefined : [bingCredit];
|
||||
},
|
||||
};
|
||||
return provider;
|
||||
},
|
||||
);
|
||||
for (const style of [
|
||||
Cesium.IonWorldImageryStyle.AERIAL,
|
||||
Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS,
|
||||
]) {
|
||||
const provider = await createIonImagery(style, ' own-ion-token ');
|
||||
const credits = provider.getTileCredits(3, 4, 5);
|
||||
assert.deepEqual(
|
||||
credits.map(({ html, showOnScreen }) => ({ html, showOnScreen })),
|
||||
[
|
||||
{ html: 'Ion required credit', showOnScreen: true },
|
||||
{ html: 'Ion optional credit', showOnScreen: false },
|
||||
{ html: 'Bing tile credit', showOnScreen: true },
|
||||
],
|
||||
);
|
||||
assert.equal(credits[2], bingCredit);
|
||||
assert.equal(provider.getTileCredits(0, 0, 0).length, 2);
|
||||
assert.ok(provider.errorEvent instanceof Cesium.Event);
|
||||
assert.equal(metadataCalls.at(-1).token, 'own-ion-token');
|
||||
const requested = new URL(metadataCalls.at(-1).url);
|
||||
assert.equal(requested.origin, 'https://api.cesium.com');
|
||||
assert.equal(requested.pathname, `/v1/assets/${style}/endpoint`);
|
||||
}
|
||||
assert.deepEqual(perTileCalls, [
|
||||
[3, 4, 5],
|
||||
[0, 0, 0],
|
||||
[3, 4, 5],
|
||||
[0, 0, 0],
|
||||
]);
|
||||
assert.equal(bingCalls.length, 2);
|
||||
for (const [index, { url, options }] of bingCalls.entries()) {
|
||||
assert.equal(url, 'https://dev.virtualearth.net');
|
||||
assert.deepEqual(options, {
|
||||
key: 'ion-issued-bing-fixture',
|
||||
mapStyle: index === 0 ? 'Aerial' : 'AerialWithLabels',
|
||||
tileProtocol: 'https',
|
||||
});
|
||||
}
|
||||
assert.equal(endpoint.options.tileProtocol, 'http');
|
||||
assert.equal(Cesium.Ion.defaultAccessToken, defaultToken);
|
||||
});
|
||||
|
||||
test('Bing ion metadata and construction failures propagate without another source', async (t) => {
|
||||
const style = Cesium.IonWorldImageryStyle.AERIAL;
|
||||
const metadataError = new Error('ion metadata fixture failure');
|
||||
const providerError = new Error('Bing construction fixture failure');
|
||||
let metadata = () => {
|
||||
throw metadataError;
|
||||
};
|
||||
let bingCalls = 0;
|
||||
t.mock.method(Cesium.Resource.prototype, 'fetchJson', async () => metadata());
|
||||
t.mock.method(Cesium.BingMapsImageryProvider, 'fromUrl', async () => {
|
||||
bingCalls += 1;
|
||||
throw providerError;
|
||||
});
|
||||
t.mock.method(Cesium.IonImageryProvider, 'fromAssetId', () =>
|
||||
assert.fail('Bing failures must not silently use an alternate provider'),
|
||||
);
|
||||
await assert.rejects(createIonImagery(style, 'test-token'), metadataError);
|
||||
for (const endpoint of [
|
||||
undefined,
|
||||
{
|
||||
type: 'TERRAIN',
|
||||
externalType: 'BING',
|
||||
options: { url: 'https://example.test' },
|
||||
},
|
||||
{
|
||||
type: 'IMAGERY',
|
||||
externalType: 'OTHER',
|
||||
options: { url: 'https://example.test' },
|
||||
},
|
||||
{ type: 'IMAGERY', externalType: 'BING', options: {} },
|
||||
]) {
|
||||
metadata = () => endpoint;
|
||||
await assert.rejects(
|
||||
createIonImagery(style, 'test-token'),
|
||||
/Bing imagery endpoint/,
|
||||
);
|
||||
}
|
||||
assert.equal(bingCalls, 0);
|
||||
metadata = () => ({
|
||||
type: 'IMAGERY',
|
||||
externalType: 'BING',
|
||||
options: { url: 'https://dev.virtualearth.net', key: 'bing-fixture' },
|
||||
});
|
||||
await assert.rejects(createIonImagery(style, 'test-token'), providerError);
|
||||
assert.equal(bingCalls, 1);
|
||||
});
|
||||
|
||||
test('other ion imagery assets keep the standard SDK factory', async (t) => {
|
||||
const expected = {};
|
||||
const calls = [];
|
||||
t.mock.method(Cesium.Resource.prototype, 'fetchJson', () =>
|
||||
assert.fail('generic assets must use the SDK ion factory'),
|
||||
);
|
||||
t.mock.method(Cesium.IonImageryProvider, 'fromAssetId', async (...args) => {
|
||||
calls.push(args);
|
||||
return expected;
|
||||
});
|
||||
assert.equal(await createIonImagery(12345, ' custom-token '), expected);
|
||||
assert.deepEqual(calls, [[12345, { accessToken: 'custom-token' }]]);
|
||||
});
|
||||
|
||||
test('cancellation after ion metadata prevents terrain construction', async () => {
|
||||
const originalResource = Cesium.IonResource.fromAssetId;
|
||||
const originalTerrain = Cesium.CesiumTerrainProvider.fromUrl;
|
||||
const controller = new AbortController();
|
||||
try {
|
||||
Cesium.IonResource.fromAssetId = async () => {
|
||||
controller.abort();
|
||||
return {};
|
||||
};
|
||||
Cesium.CesiumTerrainProvider.fromUrl = () =>
|
||||
assert.fail('cancelled terrain construction');
|
||||
await assert.rejects(
|
||||
createWorldTerrain('test-token', { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
} finally {
|
||||
Cesium.IonResource.fromAssetId = originalResource;
|
||||
Cesium.CesiumTerrainProvider.fromUrl = originalTerrain;
|
||||
}
|
||||
});
|
||||
|
||||
test('credentialed source factories reject an omitted token instead of consuming an SDK default', async () => {
|
||||
assert.throws(
|
||||
() => createIonImagery(Cesium.IonWorldImageryStyle.AERIAL, ''),
|
||||
/explicit token/,
|
||||
);
|
||||
await assert.rejects(createWorldTerrain(' '), /explicit ion token/);
|
||||
});
|
||||
|
||||
test('both Google 3D routes keep tiles drawing while draped imagery loads', async () => {
|
||||
const { createGoogleDirectTileset, createGoogleIonTileset } =
|
||||
await import('./google3d.js');
|
||||
const calls = [];
|
||||
const sdk = {
|
||||
createGooglePhotorealistic3DTileset: async (...args) => {
|
||||
calls.push(args);
|
||||
return 'direct';
|
||||
},
|
||||
IonResource: { fromAssetId: async (id, options) => ({ id, ...options }) },
|
||||
Cesium3DTileset: {
|
||||
fromUrl: async (...args) => {
|
||||
calls.push(args);
|
||||
return 'ion';
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.equal(await createGoogleDirectTileset(sdk, 'key'), 'direct');
|
||||
assert.equal(await createGoogleIonTileset(sdk, 'token'), 'ion');
|
||||
assert.deepEqual(calls[0], [
|
||||
{ key: 'key', onlyUsingWithGoogleGeocoder: true },
|
||||
{ asynchronouslyLoadImagery: true },
|
||||
]);
|
||||
assert.equal(calls[1][0].id, 2275207);
|
||||
assert.equal(calls[1][0].accessToken, 'token');
|
||||
assert.equal(calls[1][1].asynchronouslyLoadImagery, true);
|
||||
assert.equal(calls[1][1].enableCollision, true);
|
||||
});
|
||||
|
||||
test('unreachable keyless terrain falls back to flat terrain marked as a fallback', async (t) => {
|
||||
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async () => {
|
||||
throw new Error('layer.json unreachable');
|
||||
});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const result = await createKeylessTerrain();
|
||||
assert.ok(result.provider instanceof Cesium.EllipsoidTerrainProvider);
|
||||
assert.equal(result.fallback, true);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @module render/cesium/mapTerrain
|
||||
* @description The map stacks' terrain for the Cesium renderer: Cesium
|
||||
* World Terrain through ion, or Re:Earth's keyless terrain with its tile
|
||||
* retry policy (`src/maps/terrainRetry.js`).
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
|
||||
|
||||
/** Re:Earth / Mapterhorn ellipsoidal quantized mesh, CC BY 4.0. */
|
||||
export const KEYLESS_TERRAIN_URL =
|
||||
'https://terrain.reearth.land/cesium-mesh/ellipsoid';
|
||||
|
||||
/** These factories are lazy: a hidden globe must not trigger terrain loading. */
|
||||
export async function createWorldTerrain(accessToken, { signal } = {}) {
|
||||
accessToken = String(accessToken || '').trim();
|
||||
if (!accessToken)
|
||||
throw new Error('World terrain requires an explicit ion token');
|
||||
signal?.throwIfAborted();
|
||||
const resource = await Cesium.IonResource.fromAssetId(1, { accessToken });
|
||||
signal?.throwIfAborted();
|
||||
return {
|
||||
provider: await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: false,
|
||||
ellipsoid: Cesium.Ellipsoid.WGS84,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function logThrottle({ statusCode, delayMs, inWindow }) {
|
||||
// One line per cooldown window, not per tile: a burst throttles dozens.
|
||||
if (inWindow !== 1) return;
|
||||
console.warn(
|
||||
`[MapStack] Re:Earth terrain answered ${statusCode}; retrying throttled tiles after ${Math.round(delayMs)} ms`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Re:Earth resource with the tile retry policy attached. Cesium copies
|
||||
* `retryCallback`/`retryAttempts` onto every derived resource, so layer.json
|
||||
* and each `{z}/{x}/{y}.terrain` fetch inherit it (see `terrainRetry.js`).
|
||||
* @param {ReturnType<typeof createTerrainRetryPolicy>} [policy]
|
||||
* @returns {Cesium.Resource}
|
||||
*/
|
||||
export function createKeylessTerrainResource(
|
||||
policy = createTerrainRetryPolicy({ onThrottle: logThrottle }),
|
||||
) {
|
||||
return new Cesium.Resource({
|
||||
url: KEYLESS_TERRAIN_URL,
|
||||
retryCallback: policy.retryCallback,
|
||||
retryAttempts: policy.retryAttempts,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createKeylessTerrain() {
|
||||
try {
|
||||
return {
|
||||
provider: await Cesium.CesiumTerrainProvider.fromUrl(
|
||||
createKeylessTerrainResource(),
|
||||
),
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain:',
|
||||
error,
|
||||
);
|
||||
return { provider: new Cesium.EllipsoidTerrainProvider(), fallback: true };
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,15 @@
|
||||
* @description What to load, once, before handing the Cesium-free
|
||||
* layers a Cesium viewer with no renderer bound: the factories
|
||||
* that build a camera, credits, effects, draw, frame, globe, input and query
|
||||
* port over such a viewer when code first asks for one, and a click's own
|
||||
* Cesium picks (`rendererOf.js`).
|
||||
* port over such a viewer when code first asks for one, a click's own
|
||||
* Cesium picks (`rendererOf.js`), and the map engine the map stacks switch
|
||||
* through (`src/maps/engine.js`).
|
||||
*/
|
||||
import './camera.js';
|
||||
import './effects.js';
|
||||
import './frame.js';
|
||||
import './globe.js';
|
||||
import './input.js';
|
||||
import './mapEngine.js';
|
||||
import './nativeClick.js';
|
||||
import './query.js';
|
||||
@@ -4,11 +4,6 @@
|
||||
"src/app/scene.js",
|
||||
"src/app/viewer.js",
|
||||
"src/data/geoImportPins.js",
|
||||
"src/maps/catalog.js",
|
||||
"src/maps/controller.js",
|
||||
"src/maps/google3d.js",
|
||||
"src/maps/imagery.js",
|
||||
"src/maps/terrain.js",
|
||||
"src/sky/starrySky.js",
|
||||
"src/ui/applicationShell.js"
|
||||
]
|
||||
@@ -171,6 +171,9 @@ const CAMERA_FROM_CALLER = new Set([
|
||||
// Its ground snap, mesh floor sampler, annotation resolver and location
|
||||
// framing ask the camera, globe and query ports; it loads no factory.
|
||||
'./application/operations',
|
||||
// It shows its source's credit through `findCredits`, and switches stacks
|
||||
// through the map engine that `./render/cesium/unbound` provides too.
|
||||
'./maps/controller',
|
||||
]);
|
||||
|
||||
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||
|
||||
Reference in new issue
Block a user