diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 3e4378fe2..c8cdf742b 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -505,6 +505,15 @@ perform no network requests and discover no additional modules. standard sources and their setup/fallback policy. The standalone facade wires these to the application's render governor. +`maps/imagery`, `maps/terrain` and `maps/3d` are the Cesium renderer's +(`src/render/cesium/`). `maps/controller` and `maps/defaults` are +Cesium-free: they make their scene changes and build their providers +through the map engine the renderer provides as it loads +(`src/maps/engine.js`). The application's renderer provides it; with a +viewer with no renderer bound, load `./render/cesium/unbound` once first, or pass the +engine as the controller's and `createDefaultMapSources`' `engine` option. +Without one, constructing a controller throws, naming that export. + A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`. Each source has a user-facing `descriptor`, availability/reason, and either an `imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f765849d7..8987bd96e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -558,7 +558,7 @@ Keyless terrain tiles retry when Re:Earth throttles them. The browser fetches `terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no proxy in this repository sees those requests (`/api/terrain/heights` is the separate point-height endpoint), and the upstream edge answers zoom-out bursts -with HTTP 429 under load. `src/maps/terrain.js` hands Cesium a `Resource` +with HTTP 429 under load. `src/render/cesium/mapTerrain.js` hands Cesium a `Resource` whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms doubling to a 15 s cap, with every retry waiting behind one shared cooldown @@ -6650,6 +6650,17 @@ 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 viewer operations a +switch makes (imagery layers, terrain, the globe's visibility, tilesets), +through the map engine (`src/maps/engine.js`), which the Cesium renderer +provides as it loads (`src/render/cesium/mapEngine.js`). A viewer with no +renderer bound gets it, 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 releases imagery layers/listeners on replacement. Destroy invalidates pending diff --git a/package.json b/package.json index 89ef24474..b3869d6cd 100644 --- a/package.json +++ b/package.json @@ -197,9 +197,9 @@ "./geography/neighborhoods": "./src/data/neighborhoodPolygons.js", "./maps/controller": "./src/maps/controller.js", "./maps/catalog": "./src/maps/catalog.js", - "./maps/imagery": "./src/maps/imagery.js", - "./maps/terrain": "./src/maps/terrain.js", - "./maps/3d": "./src/maps/google3d.js", + "./maps/imagery": "./src/render/cesium/mapImagery.js", + "./maps/terrain": "./src/render/cesium/mapTerrain.js", + "./maps/3d": "./src/render/cesium/google3d.js", "./maps/defaults": "./src/maps/defaultSources.js", "./voice/controller": "./src/voice/realtimeController.js", "./voice/control": "./src/voice/control.js", diff --git a/scripts/format-scope.json b/scripts/format-scope.json index e998893e2..7a27f1494 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -665,10 +665,14 @@ "src/maps/imageryComparison.js", "src/maps/credits.js", "src/maps/defaultSources.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", + "src/maps/engine.js", + "src/maps/startupRoute.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js", "src/maps/terrainRetry.js", "src/maps/terrainRetry.test.mjs", "src/mapStackController.js", @@ -676,7 +680,7 @@ "src/mapStackChips.test.mjs", "src/mapStackUnavailableReason.test.mjs", "src/mapStartup.test.mjs", - "src/maps/sourceFactories.test.mjs", + "src/render/cesium/mapSources.test.mjs", "src/search/geospatial.js", "src/search/http.js", "src/search/defaults.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 1a4e5ca21..dbe74defb 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1052,7 +1052,8 @@ "src/render/baseTilesets.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", - "src/maps/google3d.js", + "src/render/cesium/google3d.js", + "src/maps/startupRoute.js", "src/sky/stars.js", "src/renderGovernor.js", "src/data/bundledJson.js", @@ -1839,7 +1840,7 @@ "src/render/cesium/unbound.js", "src/render/cesium/globe.js", "src/render/baseTilesets.js", - "src/maps/google3d.js", + "src/render/cesium/google3d.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", "src/render/cesium/iconSetPrimitive.js", @@ -1892,7 +1893,14 @@ "src/render/cesium/nativeClick.js", "src/render/input/router.js", "src/render/input/wheel.js", - "src/render/cesium/input.js" + "src/render/cesium/input.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/render/cesium/mapImagery.js", + "src/maps/terrainRetry.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/mapEngine.js" ], "external": ["cesium"] }, @@ -2398,7 +2406,7 @@ "src/layers/traffic/lifecycle.js", "src/render/cesium/globe.js", "src/render/baseTilesets.js", - "src/maps/google3d.js", + "src/render/cesium/google3d.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", "src/layers/traffic/model.js", @@ -2538,7 +2546,7 @@ "cctv-layer": { "exports": ["./layers/cctv"], "modules": [ - "src/maps/google3d.js", + "src/render/cesium/google3d.js", "src/render/cesium/globe.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", @@ -3092,10 +3100,10 @@ "src/render/creditMarkup.js", "src/maps/defaultSources.js", "src/render/cesium/imagery.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/keySetupCore.mjs", "src/localRequestGate.mjs", @@ -3120,7 +3128,10 @@ "src/data/pickRegistry.js", "src/render/cesium/input.js", "src/render/cesium/pickMemo.js", - "src/render/cesium/nativeClick.js" + "src/render/cesium/nativeClick.js", + "src/maps/attribution.js", + "src/maps/startupRoute.js", + "src/maps/engine.js" ], "external": ["cesium"] }, @@ -3733,10 +3744,10 @@ "src/maps/credits.js", "src/maps/defaultSources.js", "src/render/cesium/imagery.js", - "src/maps/google3d.js", - "src/maps/imagery.js", + "src/render/cesium/google3d.js", + "src/render/cesium/mapImagery.js", "src/maps/registry.js", - "src/maps/terrain.js", + "src/render/cesium/mapTerrain.js", "src/maps/terrainRetry.js", "src/navigationPolicy.js", "src/orbit.js", @@ -4273,7 +4284,11 @@ "src/render/cesium/internals.js", "src/render/cesium/tileRequests.js", "src/render/cesium/nativeClick.js", - "src/render/cesium/pickMemo.js" + "src/render/cesium/pickMemo.js", + "src/maps/startupRoute.js", + "src/maps/engine.js", + "src/maps/attribution.js", + "src/render/cesium/mapEngine.js" ], "external": [ "hls.js", @@ -4331,7 +4346,7 @@ "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/render/cesium/imagery.js", - "src/maps/google3d.js", + "src/render/cesium/google3d.js", "src/render/cesium/cameraControls.js", "src/render/cesium/follow.js", "src/data/bhoteKoshiIncidentPlaces.js", diff --git a/scripts/qa-terrain-429.mjs b/scripts/qa-terrain-429.mjs index 8164e34b5..8db513d2c 100644 --- a/scripts/qa-terrain-429.mjs +++ b/scripts/qa-terrain-429.mjs @@ -8,7 +8,7 @@ * answers HTTP 429 for most of them. This harness drives that burst, counts the * throttled responses, keeps the first 429's headers as evidence, and then * checks whether every throttled tile eventually loaded — the contract the - * client-side retry in `src/maps/terrain.js` provides. + * client-side retry in `src/render/cesium/mapTerrain.js` provides. * * Run against a keyless dev server (no Google or ion credentials): * env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180 diff --git a/src/app/mapLifecycle.test.mjs b/src/app/mapLifecycle.test.mjs index 0ab2e7f39..6286ca71d 100644 --- a/src/app/mapLifecycle.test.mjs +++ b/src/app/mapLifecycle.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { MapStackController } from '../mapStackController.js'; +import '../render/cesium/mapEngine.js'; import { installRenderGovernor, uninstallRenderGovernor, diff --git a/src/app/scene.js b/src/app/scene.js index b4a397013..00057f3e4 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -8,7 +8,7 @@ import { trimStaleSceneCommands } from '../render/cesium/sceneCommandRelease.js' import { registerDataCredits } from '../data/dataCredits.js'; import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; import { MapStackController } from '../mapStackController.js'; -import { loadPhotorealisticTileset } from '../mapStartup.js'; +import { loadPhotorealisticTileset } from '../render/cesium/google3d.js'; import { initLogoGaze } from '../logoGaze.js'; import { inputFor } from '../input/dispatcher.js'; import { diff --git a/src/data/telegeographySubmarineCables.test.mjs b/src/data/telegeographySubmarineCables.test.mjs index 16ddc73d4..870b5a925 100644 --- a/src/data/telegeographySubmarineCables.test.mjs +++ b/src/data/telegeographySubmarineCables.test.mjs @@ -5,6 +5,8 @@ import * as Cesium from 'cesium'; import { MAP_STACKS } from '../mapStackController.js'; import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; import { bindRenderer } from '../render/rendererOf.js'; +// A viewer with no renderer bound reads its globe through the unbound port. +import '../render/cesium/globe.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs'; diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 71cc71f4a..54f5145b3 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -4,6 +4,7 @@ import assert from 'node:assert/strict'; import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js'; import { acquireImageryComparison } from '../../maps/imageryComparison.js'; import { MapSourceController } from '../../maps/controller.js'; +import '../../render/cesium/mapEngine.js'; import { createDefaultMapSources } from '../../maps/defaultSources.js'; import { resetPointerOwnership } from '../../data/inputOwnership.js'; import { initImageryBoxTool } from '../../ui/imageryBoxTool.js'; diff --git a/src/mapStartup.js b/src/mapStartup.js index 48f56b125..dc5c1ac0f 100644 --- a/src/mapStartup.js +++ b/src/mapStartup.js @@ -1,4 +1 @@ -export { - selectMapStartupRoute, - loadPhotorealisticTileset, -} from './maps/google3d.js'; +export { selectMapStartupRoute } from './maps/startupRoute.js'; diff --git a/src/mapStartup.test.mjs b/src/mapStartup.test.mjs index 9d438643d..f95d09780 100644 --- a/src/mapStartup.test.mjs +++ b/src/mapStartup.test.mjs @@ -3,10 +3,8 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import { createGoogleTokenSource } from './maps/googleTokens.js'; -import { - loadPhotorealisticTileset, - selectMapStartupRoute, -} from './mapStartup.js'; +import { selectMapStartupRoute } from './mapStartup.js'; +import { loadPhotorealisticTileset } from './render/cesium/google3d.js'; function fakeCesium(outcomes = []) { const calls = []; diff --git a/src/maps/attribution.js b/src/maps/attribution.js new file mode 100644 index 000000000..71f5a201e --- /dev/null +++ b/src/maps/attribution.js @@ -0,0 +1,8 @@ +/** + * @module maps/attribution + * @description The on-map credits of the map stacks' sources. + */ + +// Attribution and service rights are documented in DATA_SOURCES.md. +export const ESRI_ATTRIBUTION_HTML = + 'Powered by Esri'; diff --git a/src/maps/catalog.js b/src/maps/catalog.js index 238263ba9..d437d7134 100644 --- a/src/maps/catalog.js +++ b/src/maps/catalog.js @@ -1,4 +1,8 @@ -import * as Cesium from 'cesium'; +/** + * The map stacks the maps panel offers, free of renderer code: an `ion` stack's + * `style` is the Cesium ion world imagery asset it shows (2, aerial; 3, + * aerial with labels), the values of Cesium's `IonWorldImageryStyle`. + */ export const MAP_STACKS = [ { id: 'photoreal', @@ -12,7 +16,7 @@ export const MAP_STACKS = [ label: 'Bing Aerial', // i18n-ignore: imagery product name shortLabel: 'Aerial', kind: 'ion', - style: Cesium.IonWorldImageryStyle.AERIAL, + style: 2, requiresIon: true, }, { @@ -20,7 +24,7 @@ export const MAP_STACKS = [ label: 'Bing Labels', // i18n-ignore: imagery product name shortLabel: 'Labels', kind: 'ion', - style: Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS, + style: 3, requiresIon: true, }, { diff --git a/src/maps/controller.js b/src/maps/controller.js index 2b43de4ee..97aa9ceb7 100644 --- a/src/maps/controller.js +++ b/src/maps/controller.js @@ -1,10 +1,7 @@ import { indexMapSources } from './registry.js'; -import * as Cesium from 'cesium'; import { createMapCredits } from './credits.js'; -// A viewer of a caller's own gets its credits port (and camera) from the -// factories this loads. -import '../render/cesium/camera.js'; -import { markBaseTileset } from '../render/cesium/globe.js'; +import { mapEngine } from './engine.js'; +import { markBaseTileset } from '../render/baseTilesets.js'; import { acquireImageryComparison } from './imageryComparison.js'; /** @@ -25,7 +22,12 @@ const resolved = (provider, effectiveStackId) => ({ fallbackMessage: null, }); -/** Coordinate source lifetimes and scene changes; the registry owns provider choices. */ +/** + * Coordinate source lifetimes and scene changes; the registry owns provider + * choices. The scene changes go through the renderer's map engine + * (`engine.js`), which a viewer with no renderer bound gets once its owner + * has loaded the package's `./render/cesium/unbound` export. + */ export class MapSourceController { constructor( viewer, @@ -34,11 +36,13 @@ export class MapSourceController { initialStack, onChange = null, onError = null, - requestRender = () => viewer?.scene?.requestRender?.(), - createImageryLayer = (provider) => new Cesium.ImageryLayer(provider), + engine = mapEngine(), + requestRender = () => engine.requestRender(viewer), + createImageryLayer = (provider) => engine.createImageryLayer(provider), }, ) { this.viewer = viewer; + this._engine = engine; this._registry = registry; this._sources = indexMapSources(registry.sources); this._activeId = this.isStackAvailable(initialStack) @@ -110,10 +114,11 @@ export class MapSourceController { /** Return the shown supplied or controller-owned tileset, if any. */ getImageryHostTileset() { if (this._destroyed) return null; + const shown = this._engine.tilesetShown; for (const source of this._sources.values()) - if (source.tileset?.show === true) return source.tileset; + if (shown(source.tileset)) return source.tileset; for (const tileset of this._ownedTilesets) - if (tileset.show === true) return tileset; + if (shown(tileset)) return tileset; return null; } /** @@ -124,9 +129,9 @@ export class MapSourceController { */ getDrapeSurface() { if (this._destroyed) return null; - if (this.viewer?.scene?.globe?.show === true) return 'globe'; + if (this._engine.globeShown(this.viewer)) return 'globe'; const tileset = this.getImageryHostTileset(); - return tileset && !tileset.isDestroyed?.() ? 'tileset' : 'none'; + return tileset && !this._engine.isDestroyed(tileset) ? 'tileset' : 'none'; } getActiveId() { return this._activeId; @@ -285,23 +290,24 @@ export class MapSourceController { } if (gen !== this._switchGen) return; if (!source.tileset && !this._ownedTilesets.has(tileset)) { - tileset.show = false; + this._engine.showTileset(tileset, false); markBaseTileset(tileset); - this.viewer.scene.primitives.add(tileset); + this._engine.addTileset(this.viewer, tileset); this._ownedTilesets.add(tileset); } this._removeImageryLayer(); this._credits.show(source.credit || null); this._showTileset(tileset); - this.viewer.scene.globe.show = false; + this._engine.setGlobeShown(this.viewer, false); // Terrain is intentionally untouched while the globe is hidden. } _showTileset(active) { + const show = this._engine.showTileset; for (const source of this._sources.values()) - if (source.tileset) source.tileset.show = source.tileset === active; + if (source.tileset) show(source.tileset, source.tileset === active); for (const tileset of this._ownedTilesets) - tileset.show = tileset === active; + show(tileset, tileset === active); } async _activateGlobeStack(stack, gen) { @@ -317,7 +323,7 @@ export class MapSourceController { this._removeImageryLayer(); this._imageryLayer = this._createImageryLayer(resolution.provider); this._activeImageryProvider = resolution.provider; - this.viewer.imageryLayers.add(this._imageryLayer, 0); + this._engine.addImageryLayer(this.viewer, this._imageryLayer, 0); } const source = this._sources.get(resolution.effectiveStackId); this._credits.show(source?.credit || null); @@ -327,7 +333,7 @@ export class MapSourceController { this._removeImageryErrorListener = null; this._watchProvider(resolution, gen); this._showTileset(null); - this.viewer.scene.globe.show = true; + this._engine.setGlobeShown(this.viewer, true); this._activeId = resolution.effectiveStackId; this._activeResolution = resolution; if (source?.terrain && source.terrain.id !== this._terrainMode) { @@ -349,8 +355,7 @@ export class MapSourceController { } _applyTerrain(result) { - if (result.terrain) this.viewer.scene.setTerrain(result.terrain); - else this.viewer.terrainProvider = result.provider; + this._engine.applyTerrain(this.viewer, result); this._terrainFallback = result.fallback ? result : null; if (this._replacedTerrain && this._replacedTerrain !== result) { this._dispose(this._replacedTerrain.provider); @@ -379,7 +384,9 @@ export class MapSourceController { async _retryFallbacks() { const resolution = this._activeResolution; - const flat = this.viewer.scene.globe.show ? this._terrainFallback : null; + const flat = this._engine.globeShown(this.viewer) + ? this._terrainFallback + : null; const id = resolution?.fallbackFor; let terrain = flat && this._sources.get(this._activeId)?.terrain; if (terrain?.id !== this._terrainMode) terrain = null; @@ -460,7 +467,10 @@ export class MapSourceController { return Boolean(real && !real.fallback); } this._terrainProviders.set(terrain.id, Promise.resolve(real)); - if (this._terrainFallback === flat && this.viewer.scene.globe.show) { + if ( + this._terrainFallback === flat && + this._engine.globeShown(this.viewer) + ) { this._applyTerrain(real); this._dispose(flat.provider); this._requestRender('map-stack'); @@ -540,50 +550,52 @@ export class MapSourceController { const fallback = this._sources.get( resolution.effectiveStackId, )?.tileFailureFallback; - const errorEvent = resolution.provider?.errorEvent; - if (!fallback || !errorEvent?.addEventListener) return; + if (!fallback) return; let failures = 0; let pending = false; - this._removeImageryErrorListener = errorEvent.addEventListener((error) => { - if ( - gen !== this._switchGen || - this._activeImageryProvider !== resolution.provider - ) - return; - const retryCount = Number(error?.timesRetried); - failures = - Number.isInteger(retryCount) && retryCount >= 0 - ? Math.max(failures + 1, retryCount + 1) - : failures + 1; - if (failures < fallback.threshold || pending) return; - pending = true; - this._onError?.( - fallback.message, - this.getStack(resolution.effectiveStackId), - ); - const expectedGen = this._switchGen + 1; - void this.setStack(fallback.id, { silent: true, [AUTOMATIC]: true }) - .then((state) => { - if ( - !this._destroyed && - this._switchGen === expectedGen && - state?.activeId === fallback.id - ) { - this._lastError = fallback.message; - this._emitChange('error'); - } - }) - .finally(() => { - pending = false; - }); - }); + this._removeImageryErrorListener = this._engine.onTileError( + resolution.provider, + (error) => { + if ( + gen !== this._switchGen || + this._activeImageryProvider !== resolution.provider + ) + return; + const retryCount = Number(error?.timesRetried); + failures = + Number.isInteger(retryCount) && retryCount >= 0 + ? Math.max(failures + 1, retryCount + 1) + : failures + 1; + if (failures < fallback.threshold || pending) return; + pending = true; + this._onError?.( + fallback.message, + this.getStack(resolution.effectiveStackId), + ); + const expectedGen = this._switchGen + 1; + void this.setStack(fallback.id, { silent: true, [AUTOMATIC]: true }) + .then((state) => { + if ( + !this._destroyed && + this._switchGen === expectedGen && + state?.activeId === fallback.id + ) { + this._lastError = fallback.message; + this._emitChange('error'); + } + }) + .finally(() => { + pending = false; + }); + }, + ); } _removeImageryLayer() { this._removeImageryErrorListener?.(); this._removeImageryErrorListener = null; if (this._imageryLayer) - this.viewer.imageryLayers.remove(this._imageryLayer, true); + this._engine.removeImageryLayer(this.viewer, this._imageryLayer); this._imageryLayer = null; this._activeImageryProvider = null; this._activeResolution = null; @@ -591,8 +603,7 @@ export class MapSourceController { _dispose(value) { if (!value || this._disposed.has(value)) return; this._disposed.add(value); - if (typeof value.destroy === 'function' && !value.isDestroyed?.()) - value.destroy(); + this._engine.release(value); } destroy() { if (this._destroyed) return; @@ -620,7 +631,7 @@ export class MapSourceController { () => {}, ); for (const tileset of this._ownedTilesets) { - this.viewer.scene.primitives.remove(tileset); + this._engine.removeTileset(this.viewer, tileset); this._dispose(tileset); } for (const promise of this._tilesets.values()) diff --git a/src/maps/controller.test.mjs b/src/maps/controller.test.mjs index 657257b6a..ccd9ba673 100644 --- a/src/maps/controller.test.mjs +++ b/src/maps/controller.test.mjs @@ -1,6 +1,8 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { MapSourceController } from './controller.js'; +// The controller switches stacks through the Cesium map engine. +import '../render/cesium/mapEngine.js'; import { createDefaultMapSources } from './defaultSources.js'; import { bindRenderer } from '../render/rendererOf.js'; diff --git a/src/maps/defaultSources.js b/src/maps/defaultSources.js index a12aea29a..75b14d78a 100644 --- a/src/maps/defaultSources.js +++ b/src/maps/defaultSources.js @@ -2,28 +2,31 @@ import { MAP_STACKS } from './catalog.js'; import { photorealUnavailableReason } from './availability.js'; import { keySetupRequirementEnvVars } from '../keySetupCore.mjs'; import { t } from '../i18n/index.js'; -import { - createOsmImagery, - createEsriImagery, - createIonImagery, - ESRI_ATTRIBUTION_HTML, -} from './imagery.js'; -import { createWorldTerrain, createKeylessTerrain } from './terrain.js'; +import { mapEngine } from './engine.js'; +import { ESRI_ATTRIBUTION_HTML } from './attribution.js'; -/** Select sources and setup guidance without putting provider branches in the controller. */ +/** + * Select sources and setup guidance without putting provider branches in the + * controller. Each source builds its imagery and terrain through the + * renderer's map engine (`engine.js`), or the `engine` given, when it is + * first shown. + */ export function createDefaultMapSources({ googleTileset = null, cesiumToken = '', googleApiKey = '', + engine = null, } = {}) { + // The engine given, else the one the renderer provided, read when used. + const engineOf = () => engine ?? mapEngine(); const ionToken = String(cesiumToken || '').trim(); const hasIon = Boolean(ionToken); const hasGoogle = Boolean(String(googleApiKey || '').trim()); const terrain = { id: hasIon ? 'world' : 'keyless', create: hasIon - ? (request) => createWorldTerrain(ionToken, request) - : createKeylessTerrain, + ? (request) => engineOf().terrain.world(ionToken, request) + : () => engineOf().terrain.keyless(), }; return { defaultId: googleTileset ? 'photoreal' : 'esri-imagery', @@ -52,10 +55,10 @@ export function createDefaultMapSources({ }; const imagery = descriptor.kind === 'ion' - ? () => createIonImagery(descriptor.style, ionToken) + ? () => engineOf().imagery.ion(descriptor.style, ionToken) : descriptor.id === 'osm' - ? createOsmImagery - : createEsriImagery; + ? () => engineOf().imagery.osm() + : () => engineOf().imagery.esri(); return { ...common, imagery, diff --git a/src/maps/engine.js b/src/maps/engine.js new file mode 100644 index 000000000..73530852f --- /dev/null +++ b/src/maps/engine.js @@ -0,0 +1,33 @@ +/** + * @module maps/engine + * @description What the map stacks need from the renderer that no contract + * port gives yet: the providers each stack's imagery and terrain come from, + * and the scene operations the map source controller (`controller.js`) + * switches stacks with. Cesium-free: the renderer adapter provides it + * as it loads (the Cesium one in `src/render/cesium/mapEngine.js`, loaded by + * the application's renderer and by the package's `./render/cesium/unbound` + * export), and the map code asks for it when it first needs it. + */ + +let provided = null; + +/** + * Provide the map engine; a later call replaces it. + * @param {object} engine + */ +export function provideMapEngine(engine) { + provided = engine; +} + +/** + * The map engine the renderer adapter provided. + * @returns {object} + * @throws {Error} When no adapter has provided one yet. + */ +export function mapEngine() { + if (!provided) + throw new Error( + 'No map engine: load the renderer, or the package export ./render/cesium/unbound, first', + ); + return provided; +} diff --git a/src/maps/map-subscription-ownership.test.mjs b/src/maps/map-subscription-ownership.test.mjs index bd10cce60..943d67ce6 100644 --- a/src/maps/map-subscription-ownership.test.mjs +++ b/src/maps/map-subscription-ownership.test.mjs @@ -1,6 +1,8 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { MapSourceController } from './controller.js'; +// The controller switches stacks through the Cesium map engine. +import '../render/cesium/mapEngine.js'; function fixture() { return new MapSourceController( { diff --git a/src/maps/startupRoute.js b/src/maps/startupRoute.js new file mode 100644 index 000000000..6a175f2b4 --- /dev/null +++ b/src/maps/startupRoute.js @@ -0,0 +1,20 @@ +/** + * @module maps/startupRoute + * @description Which route the photoreal base starts on, from the + * credentials configured; Cesium-free. + */ +const clean = (value) => String(value || '').trim(); + +/** + * Decide which map provider can deliver the best startup experience. + * @param {{googleApiKey?: string, cesiumToken?: string}} credentials + * @returns {'google-direct'|'google-ion'|'osm'} + */ +export function selectMapStartupRoute({ + googleApiKey = '', + cesiumToken = '', +} = {}) { + if (clean(googleApiKey)) return 'google-direct'; + if (clean(cesiumToken)) return 'google-ion'; + return 'osm'; +} diff --git a/src/maps/terrainRetry.test.mjs b/src/maps/terrainRetry.test.mjs index 69ed532b6..297dc2eed 100644 --- a/src/maps/terrainRetry.test.mjs +++ b/src/maps/terrainRetry.test.mjs @@ -12,7 +12,7 @@ import { import { KEYLESS_TERRAIN_URL, createKeylessTerrainResource, -} from './terrain.js'; +} from '../render/cesium/mapTerrain.js'; const START = 1_700_000_000_000; diff --git a/src/render/cesium/appRenderer.js b/src/render/cesium/appRenderer.js index 05c7a2acf..6d4bdd6ce 100644 --- a/src/render/cesium/appRenderer.js +++ b/src/render/cesium/appRenderer.js @@ -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 */ diff --git a/src/render/cesium/globe.js b/src/render/cesium/globe.js index 00ef48dd7..9b35cd495 100644 --- a/src/render/cesium/globe.js +++ b/src/render/cesium/globe.js @@ -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'; diff --git a/src/maps/google3d.js b/src/render/cesium/google3d.js similarity index 91% rename from src/maps/google3d.js rename to src/render/cesium/google3d.js index aab45ea35..fc578ec56 100644 --- a/src/maps/google3d.js +++ b/src/render/cesium/google3d.js @@ -1,18 +1,11 @@ -const clean = (value) => String(value || '').trim(); - /** - * Decide which map provider can deliver the best startup experience. - * @param {{googleApiKey?: string, cesiumToken?: string}} credentials - * @returns {'google-direct'|'google-ion'|'osm'} + * @module render/cesium/google3d + * @description Google Photorealistic 3D Tiles for the Cesium renderer, by + * the routes `selectMapStartupRoute` (`src/maps/startupRoute.js`) names. */ -export function selectMapStartupRoute({ - googleApiKey = '', - cesiumToken = '', -} = {}) { - if (clean(googleApiKey)) return 'google-direct'; - if (clean(cesiumToken)) return 'google-ion'; - return 'osm'; -} +export { selectMapStartupRoute } from '../../maps/startupRoute.js'; + +const clean = (value) => String(value || '').trim(); /** * Load Google Photorealistic 3D Tiles through direct Google access when diff --git a/src/render/cesium/mapEngine.js b/src/render/cesium/mapEngine.js new file mode 100644 index 000000000..490a14556 --- /dev/null +++ b/src/render/cesium/mapEngine.js @@ -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); diff --git a/src/maps/imagery.js b/src/render/cesium/mapImagery.js similarity index 89% rename from src/maps/imagery.js rename to src/render/cesium/mapImagery.js index d151b6ce6..bd07a4ea4 100644 --- a/src/maps/imagery.js +++ b/src/render/cesium/mapImagery.js @@ -1,8 +1,11 @@ +/** + * @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'; -// Attribution and service rights are documented in DATA_SOURCES.md. -export const ESRI_ATTRIBUTION_HTML = - 'Powered by Esri'; +export { ESRI_ATTRIBUTION_HTML } from '../../maps/attribution.js'; export function createOsmImagery() { return new Cesium.OpenStreetMapImageryProvider({ diff --git a/src/maps/sourceFactories.test.mjs b/src/render/cesium/mapSources.test.mjs similarity index 93% rename from src/maps/sourceFactories.test.mjs rename to src/render/cesium/mapSources.test.mjs index 3f1edc7ba..6aeb9d546 100644 --- a/src/maps/sourceFactories.test.mjs +++ b/src/render/cesium/mapSources.test.mjs @@ -1,9 +1,29 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { createIonImagery } from './imagery.js'; -import { createWorldTerrain, createKeylessTerrain } from './terrain.js'; -import { createDefaultMapSources } from './defaultSources.js'; +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; @@ -22,7 +42,6 @@ test('Esri uses Re:Earth without keys and preserves ion terrain when configured' ); assert.equal(esri.available, true); assert.equal(esri.terrain.id, 'keyless'); - assert.equal(esri.terrain.create, createKeylessTerrain); await esri.terrain.create(); // A Resource, not a bare URL: the retry policy rides on it (terrainRetry.js). assert.equal(calls.length, 1); diff --git a/src/maps/terrain.js b/src/render/cesium/mapTerrain.js similarity index 87% rename from src/maps/terrain.js rename to src/render/cesium/mapTerrain.js index d2f214700..d062655cd 100644 --- a/src/maps/terrain.js +++ b/src/render/cesium/mapTerrain.js @@ -1,5 +1,11 @@ +/** + * @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 './terrainRetry.js'; +import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js'; /** Re:Earth / Mapterhorn ellipsoidal quantized mesh, CC BY 4.0. */ export const KEYLESS_TERRAIN_URL = diff --git a/src/render/cesium/unbound.js b/src/render/cesium/unbound.js index e308bb488..b05d0be6b 100644 --- a/src/render/cesium/unbound.js +++ b/src/render/cesium/unbound.js @@ -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'; diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 727c91d18..1e84430f1 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -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" ] diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 30d38452f..0fe6536dc 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -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'));