diff --git a/changelog.d/1775-base-map-globe-port.md b/changelog.d/1775-base-map-globe-port.md new file mode 100644 index 000000000..4817a0145 --- /dev/null +++ b/changelog.d/1775-base-map-globe-port.md @@ -0,0 +1,5 @@ +- Switch the base map through the globe port on Cesium as well: Google 3D + turned off is kept and shown again without reloading, Esri reaches its + deepest level with the parent's imagery where it has none, and keyless + terrain that does not answer falls back to the flat ellipsoid (Sameh + Khamis, @samehkhamis, #1775). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 285ff5a88..4a5d97da6 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8986,24 +8986,35 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security Policy unchanged. Ion attribution and Bing's per-tile credits are preserved; other ion imagery assets continue through the SDK's standard ion factory. -The imagery, terrain and 3D factories are the Cesium renderer's -(`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the -package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point -there). The catalog, the default registry and the controller are -Cesium-free: they reach those factories, and the scene operations a -switch makes (imagery layers, terrain, the globe's visibility, tilesets), -through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The -Cesium plugin hands the application its own engine with each renderer it makes -(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`), -and the application scene loads the photoreal base through it too. A renderer -whose plugin hands none switches through its globe port -(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world -imagery as `world` imagery, photoreal as the port's photoreal base (turned off -while hidden, on again when shown), and world terrain, or without a key -Re:Earth's keyless terrain as `quantizedMesh` terrain at its URL -(`src/maps/keylessTerrain.js`), as the Cesium engine draws it; a renderer -without the `terrain` capability keeps the ellipsoid. A viewer with no renderer bound gets the Cesium engine, with the -other unbound ports, from the package's `./render/cesium/unbound` export. +The catalog, the default registry and the controller are Cesium-free: they +reach the map sources, and the scene operations a switch makes (imagery +layers, terrain, the globe's visibility, the photoreal base), through the +scene's map engine (`mapEngineFor` in `src/maps/engine.js`). Every renderer, +Cesium included, switches through its globe port (`src/maps/globeEngine.js`), +unless its plugin hands the application a map engine of its own +(`src/render/applicationHooks.js`): + +- Esri World Imagery as `xyz` imagery to its deepest level (23); Esri's "Map + data not yet available" picture is answered as a missing tile, so the + parent's imagery stays, and a refused tile counts toward the fallback to + OSM. OSM as `xyz` imagery to level 19. +- Cesium ion's world imagery as `world` imagery; on Cesium that is Bing + through ion, its tiles over HTTPS on any page, with ion's credits + (`src/render/cesium/mapImagery.js`). +- Photoreal as the port's photoreal base, by the same routes as ever (the + Google key, else Google's session tokens, else the ion copy; + `src/render/cesium/google3d.js`). Turned off, Cesium's globe port keeps the + tileset hidden, and the same spec shows it again without loading it anew. + `window.__godsEyeView.tileset` is that Cesium tileset, shown or hidden. +- World terrain through ion, or without an ion token Re:Earth's keyless + terrain as `quantizedMesh` terrain at its URL (`src/maps/keylessTerrain.js`); + while the keyless terrain does not answer, the ellipsoid stands in and the + map stack tries it again behind it. A renderer without the `terrain` + capability keeps the ellipsoid. + +A viewer with no renderer bound gets the Cesium engine +(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the +package's `./render/cesium/unbound` export. The controller accepts other source registries without adding provider branches. Each instance caches source construction, ignores superseded scene changes and diff --git a/src/app/tools.js b/src/app/tools.js index beccc1c6f..bc16a9af0 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -288,24 +288,27 @@ export function createApplicationTools({ // loop burning behind a hidden tab. (perf wave 2 fix) syncVisibilitySuspension(); - window.__godsEyeView = { - viewer, - styleManager, - tileset, - dataManager, - sceneDirector, - mapStackController, - annotations, - weatherEffects, - cockpitCloudEffects, - getRenderGovernorDiagnostics, - surfaceServices: operations.surface, - requestRender: governorRequestRender, - entityRecords: { read: readEntityRecord, write: entityRecord }, - // What the renderer's plugin lets QA scripts read (the Cesium viewer, - // for the default renderer), in place of the scene object above. - ...scene.qaHandles, - }; + window.__godsEyeView = Object.defineProperties( + { + viewer, + styleManager, + tileset, + dataManager, + sceneDirector, + mapStackController, + annotations, + weatherEffects, + cockpitCloudEffects, + getRenderGovernorDiagnostics, + surfaceServices: operations.surface, + requestRender: governorRequestRender, + entityRecords: { read: readEntityRecord, write: entityRecord }, + }, + // What the renderer's plugin lets QA scripts read (the Cesium viewer and + // its photoreal tileset, for the default renderer), in place of the + // scene's objects above; read as they are when asked. + Object.getOwnPropertyDescriptors(scene.qaHandles ?? {}), + ); const debug = window.__godsEyeView; defer(() => { if (window.__godsEyeView === debug) delete window.__godsEyeView; diff --git a/src/maps/defaultSources.js b/src/maps/defaultSources.js index 8848277a9..1f44145c9 100644 --- a/src/maps/defaultSources.js +++ b/src/maps/defaultSources.js @@ -25,7 +25,7 @@ export function createDefaultMapSources({ id: hasIon ? 'world' : 'keyless', create: hasIon ? (request) => engineOf().terrain.world(ionToken, request) - : () => engineOf().terrain.keyless(), + : (request) => engineOf().terrain.keyless(request), }; return { defaultId: googleTileset ? 'photoreal' : 'esri-imagery', diff --git a/src/maps/globeEngine.js b/src/maps/globeEngine.js index 76bad33ef..b16561927 100644 --- a/src/maps/globeEngine.js +++ b/src/maps/globeEngine.js @@ -16,6 +16,15 @@ import { findFrame, findGlobe, rendererOf } from '../render/rendererOf.js'; import { ESRI_IMAGERY_CREDIT, ESRI_TILES } from './attribution.js'; import { KEYLESS_TERRAIN_URL } from './keylessTerrain.js'; +/** Esri World Imagery's deepest level (its tile info lists levels 0–23). */ +const ESRI_MAX_LEVEL = 23; +/** + * A tile Esri has no imagery for: it answers every such tile with this one + * "Map data not yet available" picture, the same bytes each time. + */ +const ESRI_MISSING_TILE = + 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/23/0/0'; +const OSM_MAX_LEVEL = 19; const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'; const OSM_CREDIT = '© OpenStreetMap contributors'; /** Cesium ion's world imagery assets (`MAP_STACKS`' `style`). */ @@ -30,6 +39,90 @@ const shownGlobes = new WeakMap(); const credit = (text) => ({ text }); +/** Esri's "no imagery here" picture's bytes, once read; null if unread. */ +let esriMissing = null; + +/** Read Esri's "no imagery here" picture, once; null while it cannot be. */ +function esriMissingTile() { + esriMissing ??= fetch(ESRI_MISSING_TILE) + .then((response) => (response.ok ? response.arrayBuffer() : null)) + .then((buffer) => (buffer ? new Uint8Array(buffer) : null)) + .catch(() => null) + .then((bytes) => { + // Not read: asked for again with the next tile. + if (!bytes) esriMissing = null; + return bytes; + }); + return esriMissing; +} + +const sameBytes = (a, b) => + a.length === b.length && a.every((byte, i) => byte === b[i]); + +/** + * An Esri tile, fetched. Esri's "no imagery here" picture is a missing tile, + * drawn from its parent, as Cesium's own Esri provider discards it; a + * refused tile is a failed one, which counts toward the Esri source's + * fallback to OSM. + */ +async function fetchEsriTile({ url, signal }) { + const [response, missing] = await Promise.all([ + fetch(url, { signal }), + esriMissingTile(), + ]); + if (!response.ok) { + const error = new Error(`Esri tile answered ${response.status}`); + error.statusCode = response.status; + throw error; + } + const bytes = await response.arrayBuffer(); + if (missing && sameBytes(new Uint8Array(bytes), missing)) + return { missing: true }; + const contentType = response.headers.get('content-type'); + return { bytes, ...(contentType ? { contentType } : {}) }; +} + +/** Cesium World Terrain's ion asset. */ +const ION_WORLD_TERRAIN = 1; + +/** + * Ask Cesium ion for an asset's endpoint, as Cesium does before it draws + * one: a token ion refuses, or no answer, refuses the switch with ion's + * message, so the map stack stays where it was and says why. + * @param {number} asset + * @param {string} token + * @param {AbortSignal} [signal] + */ +async function ionEndpoint(asset, token, signal) { + const response = await fetch( + `https://api.cesium.com/v1/assets/${asset}/endpoint?access_token=${encodeURIComponent(token)}`, + { signal }, + ); + const body = await response.json().catch(() => null); + if (!response.ok) + throw new Error( + body?.message || + `Cesium ion answered ${response.status} for asset ${asset}`, + ); + return body; +} + +/** + * Whether the keyless terrain answers: its `layer.json`, read as any + * quantized-mesh terrain is read before its first tile. + */ +async function keylessTerrainAnswers(signal) { + try { + const response = await fetch(`${KEYLESS_TERRAIN_URL}/layer.json`, { + signal, + }); + return response.ok; + } catch (error) { + if (signal?.aborted) throw error; + return false; + } +} + /** * Turn a photoreal handle's base on or off. Turning it on can fail (the * port answers route `none`, or rejects): the handle is then off again, so @@ -123,7 +216,7 @@ export const globeMapEngine = Object.freeze({ kind: 'xyz', url: OSM_TILES, tiling: 'webMercator', - maxLevel: 19, + maxLevel: OSM_MAX_LEVEL, credit: credit(OSM_CREDIT), }), esri: () => @@ -131,12 +224,18 @@ export const globeMapEngine = Object.freeze({ kind: 'xyz', url: ESRI_TILES, tiling: 'webMercator', - maxLevel: 19, + maxLevel: ESRI_MAX_LEVEL, + fetchTile: fetchEsriTile, credit: credit(ESRI_IMAGERY_CREDIT), }), - ion(style, accessToken) { - if (!String(accessToken || '').trim()) - throw new Error('Ion imagery requires an explicit token'); + async ion(style, accessToken, { signal } = {}) { + const token = String(accessToken || '').trim(); + if (!token) throw new Error('Ion imagery requires an explicit token'); + const endpoint = await ionEndpoint(style, token, signal); + if (endpoint?.type !== 'IMAGERY' || endpoint.externalType !== 'BING') + throw new Error( + 'Ion world imagery did not return a Bing imagery endpoint', + ); return Object.freeze({ kind: 'world', worldStyle: WORLD_STYLES[style] ?? 'aerial', @@ -144,19 +243,31 @@ export const globeMapEngine = Object.freeze({ }, }), terrain: Object.freeze({ - world: async (accessToken) => { - if (!String(accessToken || '').trim()) + world: async (accessToken, { signal } = {}) => { + const token = String(accessToken || '').trim(); + if (!token) throw new Error('World terrain requires an explicit ion token'); + await ionEndpoint(ION_WORLD_TERRAIN, token, signal); return { provider: null, spec: { kind: 'world', requestVertexNormals: true }, }; }, - // Re:Earth's keyless terrain, as the Cesium map engine draws it. - keyless: async () => ({ - provider: null, - spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL }, - }), + /** + * Re:Earth's keyless terrain. While it does not answer, the ellipsoid + * stands in as a fallback the map stack tries the terrain again behind. + */ + keyless: async ({ signal } = {}) => { + if (await keylessTerrainAnswers(signal)) + return { + provider: null, + spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL }, + }; + console.warn( + '[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain', + ); + return { provider: null, spec: { kind: 'ellipsoid' }, fallback: true }; + }, }), createImageryLayer: (spec) => ({ spec, layer: null }), requestRender(host) { diff --git a/src/maps/globeEngine.test.mjs b/src/maps/globeEngine.test.mjs index 228b516eb..35ec7031d 100644 --- a/src/maps/globeEngine.test.mjs +++ b/src/maps/globeEngine.test.mjs @@ -70,6 +70,116 @@ test('the globe is shown and hidden through the port, read back without globe vi assert.equal(engine.globeShown(visible.host), false); }); +/** Answer `fetch` from `answers` (url to response) while `run` runs. */ +async function withFetch(answers, run) { + const real = globalThis.fetch; + const asked = []; + globalThis.fetch = async (url) => { + asked.push(String(url)); + const answer = answers(String(url)); + if (answer instanceof Error) throw answer; + return answer; + }; + try { + return await run(asked); + } finally { + globalThis.fetch = real; + } +} + +const bytesResponse = (bytes, status = 200) => ({ + ok: status >= 200 && status < 300, + status, + headers: { get: (name) => (name === 'content-type' ? 'image/jpeg' : null) }, + arrayBuffer: async () => new Uint8Array(bytes).buffer, + json: async () => JSON.parse(new TextDecoder().decode(new Uint8Array(bytes))), +}); + +const jsonResponse = (body, status = 200) => + bytesResponse([...new TextEncoder().encode(JSON.stringify(body))], status); + +/** Cesium ion's endpoints as a valid token is answered. */ +const ionAnswers = (url) => + /assets\/1\/endpoint/.test(url) + ? jsonResponse({ type: 'TERRAIN', url: 'https://assets.ion.invalid/1/' }) + : jsonResponse({ type: 'IMAGERY', externalType: 'BING', options: {} }); + +// Nothing here reaches the network: ion and the keyless terrain answer, +// offline. +globalThis.fetch = async (url) => + String(url).startsWith('https://api.cesium.com/') + ? ionAnswers(String(url)) + : bytesResponse([1]); + +test('Esri goes to its deepest level, its no-imagery picture drawn from the parent', async () => { + const spec = engine.imagery.esri(); + assert.equal(spec.maxLevel, 23); + const placeholder = [9, 9, 9]; + await withFetch( + (url) => + url.endsWith('/tile/23/0/0') + ? bytesResponse(placeholder) + : url.endsWith('/5/1/2') + ? bytesResponse([1, 2, 3, 4]) + : url.endsWith('/22/7/7') + ? bytesResponse(placeholder) + : bytesResponse([], 503), + async (asked) => { + const signal = new AbortController().signal; + const tile = await spec.fetchTile({ url: `${'x'}/5/1/2`, signal }); + assert.deepEqual([...new Uint8Array(tile.bytes)], [1, 2, 3, 4]); + assert.equal(tile.contentType, 'image/jpeg'); + assert.deepEqual( + await spec.fetchTile({ url: 'x/22/7/7', signal }), + { missing: true }, + 'the no-imagery picture is a missing tile', + ); + await assert.rejects( + spec.fetchTile({ url: 'x/1/1/1', signal }), + (error) => error.statusCode === 503, + 'a refused tile is a failed one', + ); + assert.equal( + asked.filter((url) => url.endsWith('/tile/23/0/0')).length, + 1, + 'the no-imagery picture is read once', + ); + }, + ); +}); + +test('keyless terrain that does not answer is the flat ellipsoid, marked a fallback', async () => { + await withFetch( + () => new TypeError('offline'), + async (asked) => { + const warn = console.warn; + console.warn = () => {}; + try { + assert.deepEqual(await engine.terrain.keyless(), { + provider: null, + spec: { kind: 'ellipsoid' }, + fallback: true, + }); + } finally { + console.warn = warn; + } + assert.deepEqual(asked, [`${KEYLESS_TERRAIN_URL}/layer.json`]); + }, + ); + await withFetch( + () => bytesResponse([], 503), + async () => { + const warn = console.warn; + console.warn = () => {}; + try { + assert.equal((await engine.terrain.keyless()).fallback, true); + } finally { + console.warn = warn; + } + }, + ); +}); + test('terrain is the port’s world terrain, or the keyless quantized mesh without a token', async () => { const { host, renderer } = scene(['terrain']); await assert.rejects(engine.terrain.world(''), /ion token/); @@ -78,20 +188,66 @@ test('terrain is the port’s world terrain, or the keyless quantized mesh witho assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [ { kind: 'world', requestVertexNormals: true }, ]); - engine.applyTerrain(host, await engine.terrain.keyless()); + engine.applyTerrain( + host, + await withFetch( + () => bytesResponse([1]), + () => engine.terrain.keyless(), + ), + ); assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [ { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL }, ]); - assert.throws(() => engine.imagery.ion(2, ''), /token/); - assert.deepEqual(engine.imagery.ion(3, 'token'), { + await assert.rejects(engine.imagery.ion(2, ''), /token/); + assert.deepEqual(await engine.imagery.ion(3, 'token'), { kind: 'world', worldStyle: 'aerialLabels', }); }); +test('a token ion refuses refuses the switch with ion’s message, as Cesium’s own route did', async () => { + await withFetch( + () => + jsonResponse( + { code: 'InvalidCredentials', message: 'Invalid access token' }, + 401, + ), + async (asked) => { + await assert.rejects( + engine.imagery.ion(2, 'bad'), + /Invalid access token/, + ); + await assert.rejects(engine.terrain.world('bad'), /Invalid access token/); + assert.match(asked[0], /\/v1\/assets\/2\/endpoint\?access_token=bad$/); + assert.match(asked[1], /\/v1\/assets\/1\/endpoint\?access_token=bad$/); + }, + ); + await withFetch( + () => jsonResponse({ type: 'IMAGERY', externalType: 'GOOGLE_2D_MAPS' }), + async () => { + await assert.rejects( + engine.imagery.ion(2, 'token'), + /Bing imagery endpoint/, + ); + }, + ); + await withFetch( + () => new TypeError('offline'), + async () => { + await assert.rejects(engine.terrain.world('token'), /offline/); + }, + ); +}); + test('where the renderer draws no terrain the ellipsoid stays', async () => { const { host, renderer } = scene([]); - engine.applyTerrain(host, await engine.terrain.keyless()); + engine.applyTerrain( + host, + await withFetch( + () => bytesResponse([1]), + () => engine.terrain.keyless(), + ), + ); assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [null]); }); diff --git a/src/render/cesium/appRenderer.js b/src/render/cesium/appRenderer.js index 94dfc8afc..a3a51375d 100644 --- a/src/render/cesium/appRenderer.js +++ b/src/render/cesium/appRenderer.js @@ -7,17 +7,15 @@ * The renderer it makes is transitional. Its ports are the shared Cesium * ports (`ports.js`), the ones the conformance renderer is checked with, * and it has every member of the contract. The application's base (the - * photoreal tiles, the map stack's imagery and terrain) is still loaded - * through the Cesium map engine (`mapEngine.js`), which the plugin hands - * the application with the renderer (its `applicationHooks`); the globe - * port drapes its imagery on that base as drawn (see `globe.js`). + * photoreal tiles, the map stack's imagery and terrain) is loaded through + * the globe port, as on any renderer (`src/maps/globeEngine.js`). * `whenSettled` waits for the globe, the scene's 3D tiles and what the draw * sets hold. * * What only this renderer needs at startup is set up here: the free-look * height limit, keyboard access to the credits' expand link (in the page's * language). The plugin's `applicationHooks` are what the application - * uses where a renderer has them: the map engine, stale command trimming, + * uses where a renderer has them: stale command trimming, * whether an entity is the viewer's own, and the viewer QA scripts read. * Adapter code reaches the viewer behind a renderer through * `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no @@ -30,7 +28,6 @@ import { bindRenderer } from '../rendererOf.js'; import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js'; import { createCesiumInput } from './input.js'; import { cesiumCapabilities, createCesiumPorts } from './ports.js'; -import { cesiumMapEngine } from './mapEngine.js'; import { installFreeLookHeightLimit } from './freeLookLimit.js'; import { trimStaleSceneCommands } from './sceneCommandRelease.js'; import { configureCreditKeyboardAccess } from './creditKeyboard.js'; @@ -38,6 +35,7 @@ import { onLocaleChange } from '../../i18n/index.js'; import { cesiumViewerOf, recordViewer } from './viewers.js'; import { installRenderFailureNotice } from './renderFailure.js'; import { cesiumCardPreviews } from './cardPreviews.js'; +import { cesiumPhotorealOf } from './globe.js'; export { cesiumViewerOf }; @@ -212,7 +210,6 @@ export function createCesiumRendererPlugin({ applicationHooks(renderer) { const viewer = cesiumViewerOf(renderer); return { - mapEngine: cesiumMapEngine, // Cesium's credit display (#cesium-credits) shows the credits. ownCreditDisplay: true, // Drops the draw commands the scene keeps after it stops drawing @@ -222,7 +219,13 @@ export function createCesiumRendererPlugin({ // the aircraft it flies still draws). viewerDrawsEntity: (entity) => viewer.entities.contains(entity), // QA scripts drive and read the viewer itself. - qaHandles: { viewer }, + qaHandles: { + viewer, + /** The photoreal tileset the globe holds now, shown or hidden. */ + get tileset() { + return cesiumPhotorealOf(viewer.scene); + }, + }, // A recoverable notice when the globe stops drawing // (renderFailure.js). renderFailureNotice: (options) => diff --git a/src/render/cesium/appRenderer.test.mjs b/src/render/cesium/appRenderer.test.mjs index 53a26ba88..dccc1ff3e 100644 --- a/src/render/cesium/appRenderer.test.mjs +++ b/src/render/cesium/appRenderer.test.mjs @@ -11,7 +11,6 @@ import { releaseContinuousRender, uninstallRenderGovernor, } from '../../renderGovernor.js'; -import { cesiumMapEngine } from './mapEngine.js'; import { ReadonlySet, cesiumRenderer, @@ -150,7 +149,11 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async 'free look is limited to low heights from the start', ); const hooks = plugin.applicationHooks(renderer); - assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium'); + assert.equal( + hooks.mapEngine, + undefined, + 'the map stacks switch through the globe port', + ); assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits'); assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer'); assert.equal(hooks.viewerDrawsEntity({ own: true }), true); diff --git a/src/render/cesium/globe.js b/src/render/cesium/globe.js index c8f2166f6..1ad670111 100644 --- a/src/render/cesium/globe.js +++ b/src/render/cesium/globe.js @@ -59,7 +59,15 @@ async function terrainProvider(spec, { worldDataToken }) { throw new TypeError('Quantized-mesh terrain needs its url'); // Busy hosts are asked again as the keyless terrain is // (`terrainRetry.js`); every tile's resource inherits the policy. - const policy = createTerrainRetryPolicy(); + const policy = createTerrainRetryPolicy({ + // One line per cooldown window, not per tile: a burst throttles dozens. + onThrottle: ({ statusCode, delayMs, inWindow }) => { + if (inWindow === 1) + console.warn( + `[MapStack] terrain answered ${statusCode}; retrying throttled tiles after ${Math.round(delayMs)} ms`, + ); + }, + }); const resource = new Cesium.Resource({ url: spec.url, retryCallback: policy.retryCallback, @@ -104,6 +112,19 @@ czm_material czm_getMaterial(czm_materialInput materialInput) /** The last `surfaceVersion` any globe port handed out. */ let surfaceVersions = 0; +/** Each scene's photoreal tileset as a globe port holds it, shown or hidden. */ +const photorealTilesets = new WeakMap(); + +/** + * The Cesium photoreal tileset a globe port over `scene` holds: shown, or + * hidden and kept to show again; null when it holds none. For QA scripts. + * @param {object} scene + * @returns {object | null} + */ +export function cesiumPhotorealOf(scene) { + return photorealTilesets.get(scene)?.() ?? null; +} + /** * @param {object} widget A Cesium `CesiumWidget` or `Viewer`. * @param {{capabilities: ReadonlySet, @@ -111,7 +132,8 @@ let surfaceVersions = 0; * report?: (error: unknown) => void, * credits?: import('../contract/credits').CreditsPort | null, * credentials?: {googleApiKey?: string, googleTokens?: () => Promise, - * worldDataToken?: string}}} options + * worldDataToken?: string}, + * loadPhotoreal?: typeof loadPhotorealisticTileset}} options * @returns {{port: import('../contract/globe').GlobePort, dispose: () => void}} */ export function createCesiumGlobe( @@ -122,6 +144,8 @@ export function createCesiumGlobe( report = uncaught, credits = null, credentials = {}, + // Tests load their own. + loadPhotoreal = loadPhotorealisticTileset, }, ) { const scene = widget.scene; @@ -130,9 +154,17 @@ export function createCesiumGlobe( // --- Base ------------------------------------------------------------------ - /** The photoreal tileset this port loaded, if any. */ + /** The photoreal tileset this port loaded, if any, and its spec. */ let photoreal = null; + let photorealSpec = null; let photorealStatus = { route: 'none' }; + /** + * The photoreal tileset last turned off, kept hidden with the spec and + * status it loaded with: that same spec shows it again at once, without + * loading it anew (Google counts each load). + */ + let parked = null; + photorealTilesets.set(scene, () => photoreal ?? parked?.tileset ?? null); let photorealGen = 0; let terrainGen = 0; let baseGen = 0; @@ -178,31 +210,74 @@ export function createCesiumGlobe( worldDataToken: () => credentials.worldDataToken, }); - function removePhotoreal() { - if (!photoreal) return; - const tileset = photoreal; - photoreal = null; - // The layers draped on it move off before it takes them with it. - imagery.sync(); + function destroyTileset(tileset) { if (!tileset.isDestroyed() && !scene.primitives.remove(tileset)) tileset.destroy(); } + function removePhotoreal() { + if (!photoreal) return; + const tileset = photoreal; + photoreal = null; + photorealSpec = null; + // The layers draped on it move off before it takes them with it. + imagery.sync(); + destroyTileset(tileset); + } + + /** Hide the photoreal tileset, kept for its spec to show again. */ + function parkPhotoreal() { + if (!photoreal) return; + if (parked) destroyTileset(parked.tileset); + parked = { + spec: photorealSpec, + status: photorealStatus, + tileset: photoreal, + }; + photoreal.show = false; + photoreal = null; + photorealSpec = null; + imagery.sync(); + } + + /** Show the parked tileset again when `spec` is the one it loaded with. */ + function unparkPhotoreal(spec) { + const kept = parked; + if (!kept || kept.spec !== spec || kept.tileset.isDestroyed()) return null; + parked = null; + removePhotoreal(); + photoreal = kept.tileset; + photorealSpec = spec; + photoreal.show = true; + photorealStatus = kept.status; + imagery.sync(); + requestRender('base'); + return photorealStatus; + } + async function setPhotoreal(spec) { const gen = ++photorealGen; - removePhotoreal(); - photorealStatus = { route: 'none' }; if (!spec || !can('photoreal')) { + if (spec) removePhotoreal(); + else parkPhotoreal(); photorealStatus = { route: 'none' }; requestRender('base'); return photorealStatus; } + const shown = unparkPhotoreal(spec); + if (shown) return shown; + removePhotoreal(); + if (parked) { + destroyTileset(parked.tileset); + parked = null; + } + photorealStatus = { route: 'none' }; // The spec's own route first: its key, else its tokens, else the // renderer's credentials. const googleApiKey = spec.key ?? (spec.token ? '' : (credentials.googleApiKey ?? '')); const token = spec.token ?? credentials.googleTokens; - const result = await loadPhotorealisticTileset(Cesium, { + const result = await loadPhotoreal(Cesium, { googleApiKey, // A renewal names the token it replaces. googleTokens: token ? { token: (options) => token(options) } : null, @@ -224,6 +299,7 @@ export function createCesiumGlobe( }; } else { photoreal = scene.primitives.add(result.tileset); + photorealSpec = spec; photorealStatus = { route: ROUTES[result.route] ?? 'google' }; } imagery.sync(); @@ -616,6 +692,10 @@ export function createCesiumGlobe( if (disposed) return; disposed = true; photorealGen += 1; + if (parked) { + destroyTileset(parked.tileset); + parked = null; + } terrainGen += 1; baseGen += 1; baseLoad?.abort(); diff --git a/src/render/cesium/globe.test.mjs b/src/render/cesium/globe.test.mjs index 500bfee27..0a26d810c 100644 --- a/src/render/cesium/globe.test.mjs +++ b/src/render/cesium/globe.test.mjs @@ -1,7 +1,11 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import * as Cesium from 'cesium'; -import { createCesiumGlobe, markBaseTileset } from './globe.js'; +import { + cesiumPhotorealOf, + createCesiumGlobe, + markBaseTileset, +} from './globe.js'; import { hookProvider, TILE_RETRY_DELAY_MS, xyzTileUrl } from './imagery.js'; const ALL = new Set([ @@ -805,3 +809,43 @@ test('hillshade shading owns a free globe material, follows the terrain, gives i assert.equal(scene.globe.material, theirs); dispose(); }); + +test('photoreal turned off is kept hidden, and the same spec shows it without loading it again', async () => { + const scene = fakeScene(); + const loads = []; + const { port } = createCesiumGlobe( + { scene }, + { + capabilities: new Set(['photoreal']), + requestRender: () => {}, + credentials: { worldDataToken: 'ion' }, + loadPhotoreal: async (_sdk, credentials) => { + loads.push(credentials); + return { tileset: fakeTileset(), route: 'direct', errors: [] }; + }, + }, + ); + const spec = { provider: 'google', key: 'key', fallback: true }; + assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' }); + assert.equal(loads.length, 1); + assert.equal(loads[0].googleApiKey, 'key'); + assert.equal(loads[0].cesiumToken, 'ion'); + const first = cesiumPhotorealOf(scene); + assert.equal(first.show, true); + + assert.deepEqual(await port.setPhotoreal(null), { route: 'none' }); + assert.equal(first.isDestroyed(), false, 'kept'); + assert.equal(first.show, false, 'hidden'); + assert.equal(cesiumPhotorealOf(scene), first, 'QA scripts still read it'); + + assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' }); + assert.equal(loads.length, 1, 'not loaded again'); + assert.equal(cesiumPhotorealOf(scene), first); + assert.equal(first.show, true); + + await port.setPhotoreal(null); + await port.setPhotoreal({ provider: 'google', key: 'other' }); + assert.equal(loads.length, 2, 'another spec loads its own'); + assert.equal(first.isDestroyed(), true, 'the kept one goes'); + assert.notEqual(cesiumPhotorealOf(scene), first); +}); diff --git a/src/render/cesium/google3d.js b/src/render/cesium/google3d.js index fc578ec56..59744f0de 100644 --- a/src/render/cesium/google3d.js +++ b/src/render/cesium/google3d.js @@ -59,10 +59,11 @@ export async function loadPhotorealisticTileset( 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. + // Tiles keep drawing their own texture while draped weather loads, and + // clamped marks land on them, as on the token routes' tiles. return Cesium.createGooglePhotorealistic3DTileset( { key, onlyUsingWithGoogleGeocoder: true }, - { asynchronouslyLoadImagery: true }, + { asynchronouslyLoadImagery: true, enableCollision: true }, ); } diff --git a/src/render/cesium/imagery.js b/src/render/cesium/imagery.js index 53ae47989..c70baa8d4 100644 --- a/src/render/cesium/imagery.js +++ b/src/render/cesium/imagery.js @@ -32,6 +32,7 @@ import { videoProvider, } from './imageryFrames.js'; import { withTileRequestHook } from './tileRequests.js'; +import { createIonImagery } from './mapImagery.js'; const SPLITS = { none: 'NONE', left: 'LEFT', right: 'RIGHT' }; const DRAPES = new Set(['surface', 'objects', 'all']); @@ -157,9 +158,11 @@ export function providerFor(spec, { worldDataToken } = {}) { throw new TypeError( 'World imagery needs the renderer’s world data token', ); - return Cesium.IonImageryProvider.fromAssetId( + // Bing through ion, its tiles over HTTPS on any page, with ion's + // credits, as the map stacks have always drawn it. + return createIonImagery( WORLD_ASSETS[spec.worldStyle ?? 'aerial'] ?? WORLD_ASSETS.aerial, - { accessToken }, + accessToken, ); } // The app's own: the vector base's tiles, painted from its style. diff --git a/src/render/cesium/mapSources.test.mjs b/src/render/cesium/mapSources.test.mjs index 6aeb9d546..c520454d2 100644 --- a/src/render/cesium/mapSources.test.mjs +++ b/src/render/cesium/mapSources.test.mjs @@ -329,7 +329,7 @@ test('both Google 3D routes keep tiles drawing while draped imagery loads', asyn assert.equal(await createGoogleIonTileset(sdk, 'token'), 'ion'); assert.deepEqual(calls[0], [ { key: 'key', onlyUsingWithGoogleGeocoder: true }, - { asynchronouslyLoadImagery: true }, + { asynchronouslyLoadImagery: true, enableCollision: true }, ]); assert.equal(calls[1][0].id, 2275207); assert.equal(calls[1][0].accessToken, 'token');