Start the application through the contract, not on the Cesium viewer

The application scene takes a renderer plugin and no longer refuses one
without a Cesium viewer. It loads the default (Cesium) plugin only when it
is given none, so a page on the stub never loads Cesium.

- Every layer and tool is handed the application's own scene object
  (createSceneHost): the container and isDestroyed(), bound to the
  renderer, the same on Cesium and the stub.
- What only Cesium needs at startup is done in its plugin's create: the
  free-look height limit, and keyboard access to its credits' expand link
  (creditKeyboard.js moves into the adapter).
- What a plugin may hand the application beside the contract goes through
  provideApplicationHooks, each hook optional: Cesium's map engine, stale
  command trimming, inline panel rendering, viewerDrawsEntity, the zoom-out
  guard, and the viewer QA scripts read from window.__godsEyeView.
- The map stacks, and the photoreal base the scene loads, switch through
  the renderer's own map engine (mapEngineFor), else its globe port
  (globeEngine.js). The Cesium engine takes the scene object and changes
  the viewer behind it.
This commit is contained in:
Sameh Khamis committed 2026-11-10 17:18:48 -08:00
1 parent a72d4c3b1f
commit 6daf63d90c
24 files changed
+825 -241

No files matched your search

+17 -9
View File
@@ -1139,8 +1139,8 @@ Polled layer refreshes and the HUD's camera readout pause while the page is
hidden. An app embedded inline in a panel keeps both running, because the
panel's host can report the page as hidden while it is on screen. This is the
same rule the render loop follows (`keepPanelRendering` in
`render/cesium/panelRendering.js`, which the application scene hands the embed
views).
`render/cesium/panelRendering.js`, which the Cesium plugin hands the
application and the application scene hands the embed views).
Application scene setup owns request services, terrain/floor caches and annotation
lookup state. Controls, layers and voice share those owners, and cancellation
@@ -3167,7 +3167,8 @@ which embeds the MAP_KEY.
> MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`,
> requests one frame through `governorRequestRender` after every layer
> disable and then has `src/render/cesium/sceneCommandRelease.js` (handed
> over by `src/app/scene.js`) trim those arrays. It reads private Cesium
> handed over by the Cesium plugin through `src/app/scene.js`) trim those
> arrays. It reads private Cesium
> fields through `src/render/cesium/internals.js`;
> `src/render/cesium/sceneCommandRelease.test.mjs` pins them and fails if
> Cesium renames them or changes which passes it truncates.
@@ -6530,7 +6531,7 @@ pins and share links already supply complete boxes.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
@@ -7464,12 +7465,19 @@ 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
Cesium-free: they reach those factories, and the scene 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.
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 the ellipsoid where
Cesium uses Re:Earth's keyless terrain (the contract's `TerrainSpec` has no
such kind). A viewer with no renderer bound gets the Cesium engine, 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
+28 -11
View File
@@ -1404,7 +1404,9 @@
"src/ui/ownerFlagSheet.js",
"src/layers/satellites/sensors.js",
"src/data/adminBoundaries.js",
"src/data/retryableLoad.js"
"src/data/retryableLoad.js",
"src/maps/imageryHost.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n"]
},
@@ -2036,7 +2038,10 @@
"src/renderGovernor.js",
"src/sky/icrf.js",
"src/sky/stars.js",
"src/render/cesium/starrySky.js"
"src/render/cesium/starrySky.js",
"src/render/applicationHooks.js",
"src/maps/globeEngine.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium"]
},
@@ -2642,7 +2647,8 @@
"src/render/cesium/nativeClick.js",
"src/render/input/router.js",
"src/render/cesium/ctrlWheelZoom.js",
"src/render/cesium/input.js"
"src/render/cesium/input.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile"]
},
@@ -3293,7 +3299,10 @@
"src/render/cesium/nativeClick.js",
"src/maps/attribution.js",
"src/maps/startupRoute.js",
"src/maps/engine.js"
"src/maps/engine.js",
"src/render/applicationHooks.js",
"src/maps/globeEngine.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium"]
},
@@ -3534,7 +3543,7 @@
"src/cockpitVisionPolicy.js",
"src/contactsDetectionPolicy.js",
"src/contextModePolicy.js",
"src/creditKeyboard.js",
"src/render/cesium/creditKeyboard.js",
"src/data/aircraftClass.js",
"src/data/aircraftEmergency.js",
"src/data/aircraftIcons.js",
@@ -4555,7 +4564,10 @@
"src/layers/satellites/sensors.js",
"src/data/ucsSatellites.js",
"src/data/imagingSensors.js",
"src/render/cesium/imageryLookAhead.js"
"src/render/cesium/imageryLookAhead.js",
"src/render/applicationHooks.js",
"src/maps/globeEngine.js",
"src/render/cesium/viewers.js"
],
"external": [
"hls.js",
@@ -5297,7 +5309,8 @@
"src/layers/satellites/classes.js",
"src/layers/satellites/sensors.js",
"src/data/ucsSatellites.js",
"src/data/imagingSensors.js"
"src/data/imagingSensors.js",
"src/render/cesium/viewers.js"
],
"external": [
"hls.js",
@@ -5431,7 +5444,8 @@
"src/render/cesium/ctrlWheelZoom.js",
"src/render/input/router.js",
"src/render/cesium/nativeClick.js",
"src/render/cesium/input.js"
"src/render/cesium/input.js",
"src/render/cesium/viewers.js"
],
"external": [
"cesium",
@@ -6199,7 +6213,8 @@
"src/render/cesium/nativeClick.js",
"src/data/rioRouteNames.js",
"src/overlays/worldOverlayChrome.js",
"src/time/worldClock.js"
"src/time/worldClock.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium", "egm96-universal", "pbf"]
},
@@ -6306,7 +6321,8 @@
"src/render/cesium/pickMemo.js",
"src/render/cesium/nativeClick.js",
"src/data/rioRouteNames.js",
"src/time/worldClock.js"
"src/time/worldClock.js",
"src/render/cesium/viewers.js"
],
"external": ["cesium", "pbf"]
},
@@ -6845,7 +6861,8 @@
"src/contextModePolicy.js",
"src/loadingFeedback.js",
"src/data/installationFeedback.js",
"src/i18n/marker.js"
"src/i18n/marker.js",
"src/render/rendererOf.js"
],
"external": []
},
+60 -46
View File
@@ -1,17 +1,7 @@
import { createApplicationOperations } from './operations.js';
// The application's composition root: it picks the Cesium renderer, and
// this is the only part of the adapter it imports.
import {
applicationViewerHooks,
cesiumRenderer,
cesiumViewerOf,
loadApplicationPhotoreal,
releaseApplicationPhotoreal,
showApplicationPhotoreal,
} from '../render/cesium/application.js';
import { registerDataCredits } from '../data/dataCredits.js';
import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
import { MapStackController } from '../mapStackController.js';
import { mapEngineFor } from '../maps/engine.js';
import { initLogoGaze } from '../logoGaze.js';
import { inputFor } from '../input/dispatcher.js';
import {
@@ -21,19 +11,32 @@ import {
governorRequestRender,
} from '../renderGovernor.js';
import { describeError } from './errors.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js';
import { worldClock, worldTimeFor } from '../time/worldClock.js';
import { followWorldTime } from '../time/viewerClock.js';
import { onLocaleChange, t } from '../i18n/index.js';
import { t } from '../i18n/index.js';
import { applicationHooksOf } from '../render/applicationHooks.js';
import { createSceneHost } from '../render/rendererOf.js';
/**
* The application's composition root picks the renderer: the one given, else
* the default (Cesium), loaded only then, so a page on the stub never
* loads it. This is the only part of an adapter the application imports.
*/
async function defaultRenderer() {
const { cesiumRenderer } = await import('../render/cesium/application.js');
return cesiumRenderer;
}
/**
* Construct the application globe using the caller's local configuration.
* `renderer` is the `RendererPlugin` that draws it (default: Cesium). The
* application still runs on the Cesium viewer until its layers are ported,
* so a plugin whose renderer has none is refused.
* application runs on a renderer with only the contract's required members:
* what a renderer's plugin hands it beside the contract
* (`src/render/applicationHooks.js`) it uses where given, and does without
* where not.
*/
export async function createApplicationScene({
renderer: rendererPlugin = cesiumRenderer,
renderer: givenPlugin,
requestServices,
googleApiKey,
googleTokens = null,
@@ -60,23 +63,23 @@ export async function createApplicationScene({
});
}
loaderStatus.textContent = t('Configuring viewer...');
// The scene still loads the tiles, so their credentials stay here.
const rendererPlugin = givenPlugin ?? (await defaultRenderer());
signal.throwIfAborted();
const container = document.getElementById('cesiumContainer');
const renderer = await rendererPlugin.create({
container: document.getElementById('cesiumContainer'),
container,
googleApiKey: googleApiKey || undefined,
googleTokens: googleTokens
? (options) => googleTokens.token(options)
: undefined,
worldDataToken: cesiumToken || undefined,
signal,
});
const viewer = cesiumViewerOf(renderer);
if (!viewer) {
const refusal = new Error(
`The ${rendererPlugin.id} renderer cannot run the application yet`,
);
try {
renderer.destroy();
} catch (error) {
console.warn('[Init] Refused renderer failed to destroy:', error);
}
throw refusal;
}
// The scene object every layer and tool is handed: the application's own,
// bound to the renderer.
const scene = createSceneHost(renderer, { container });
const viewer = scene.host;
const hooks = applicationHooksOf(renderer);
// The governor keeps its holds on the renderer's frame port. The loop
// draws every frame until the application's tools are up (they release
// 'boot'), as it did before anything could hold it.
@@ -86,11 +89,15 @@ export async function createApplicationScene({
try {
uninstallRenderGovernor(renderer.frame);
} finally {
renderer.destroy();
try {
renderer.destroy();
} finally {
scene.release();
}
}
});
// Before any layer binds a click: every layer and tool shares this one.
// Deferred after the viewer, so it is released before the viewer goes.
// Deferred after the renderer, so it is released before the renderer goes.
const input = inputFor(viewer);
defer(() => input.destroy());
// Ctrl+wheel and trackpad pinches zoom the globe, not the page.
@@ -103,28 +110,29 @@ export async function createApplicationScene({
requestRender: () => governorRequestRender('world-time'),
}),
);
// What the adapter hands the application about its viewer; free look is
// limited to low heights from the start.
const viewerHooks = applicationViewerHooks(viewer);
defer(viewerHooks.installFreeLookHeightLimit(FREE_LOOK_MAX_HEIGHT_METERS));
registerDataCredits(viewer, credits);
configureCreditKeyboardAccess(document);
defer(onLocaleChange(() => configureCreditKeyboardAccess(document)));
loaderStatus.textContent =
googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...')
: t('Loading the keyless globe...');
const photoreal = await loadApplicationPhotoreal({
// The map stacks, and the photoreal base among them, switch through the
// scene's map engine: the renderer's own, or its globe port.
const engine = mapOptions.engine ?? mapEngineFor(viewer);
const photoreal = (await engine.loadPhotoreal?.(viewer, {
googleApiKey,
googleTokens,
cesiumToken,
});
})) ?? { tileset: null, route: 'none', errors: [] };
const tileset = photoreal.tileset;
// A provider can finish after cancellation; retain ownership of its result.
defer(() => releaseApplicationPhotoreal(viewer, tileset));
defer(() => {
if (!tileset || engine.isDestroyed(tileset)) return;
engine.removeTileset(viewer, tileset);
engine.release(tileset);
});
signal.throwIfAborted();
if (tileset) {
showApplicationPhotoreal(viewer, tileset);
engine.addTileset(viewer, tileset);
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
// Google Photorealistic 3D Tiles provide their own terrain/elevation.
renderer.globe.setGlobeVisible(false);
@@ -152,6 +160,7 @@ export async function createApplicationScene({
const mapStackController = new MapController(viewer, {
requestRender: governorRequestRender,
...mapOptions,
engine,
googleTileset: tileset,
cesiumToken,
initialStack: tileset ? 'photoreal' : 'esri-imagery',
@@ -180,9 +189,14 @@ export async function createApplicationScene({
mapStackController,
operations,
input,
// Trims stale draw commands, keeps an inline panel drawing, says
// whether an entity is the viewer's own, and installs the zoom-out
// guard (render/cesium/application.js).
...viewerHooks,
// What the renderer's plugin hands the application beside the contract,
// each optional: trims stale draw commands, keeps an inline panel
// drawing, says whether an entity is the renderer's own, installs the
// zoom-out guard, and what QA scripts read (render/applicationHooks.js).
trimStaleCommands: hooks.trimStaleCommands,
keepPanelRendering: hooks.keepPanelRendering,
viewerDrawsEntity: hooks.viewerDrawsEntity,
installZoomOutGuard: hooks.installZoomOutGuard,
qaHandles: hooks.qaHandles,
};
}
+108
View File
@@ -0,0 +1,108 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApplicationScene } from './scene.js';
import { createApplicationRequestServices } from '../services/requests.js';
import { createStubRendererPlugin } from '../render/stub/index.js';
import { rendererOf } from '../render/rendererOf.js';
/** Start the scene on a stub renderer with `capabilities`. */
async function startOnStub(t, { capabilities = [], ...rest } = {}) {
document.body.innerHTML = '<div id="cesiumContainer"></div>';
const made = [];
const deferred = [];
t.after(async () => {
for (const fn of deferred.reverse()) await fn();
});
const scene = await createApplicationScene({
renderer: createStubRendererPlugin({ capabilities }, (renderer) =>
made.push(renderer),
),
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
...rest,
});
return { scene, renderer: made[0], deferred };
}
test('the scene runs on a renderer with only the required members', async (t) => {
const { scene, renderer, deferred } = await startOnStub(t);
assert.equal(scene.renderer, renderer);
assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound');
assert.equal(
scene.viewer.container,
document.getElementById('cesiumContainer'),
);
assert.equal(scene.viewer.isDestroyed(), false);
assert.ok(
scene.viewer.container.contains(renderer.canvas),
'the renderer fills the container',
);
// Nothing of the engine on the scene object.
assert.deepEqual(Object.keys(scene.viewer).sort(), [
'container',
'isDestroyed',
]);
// No hooks: each is left out, not faked.
for (const name of [
'trimStaleCommands',
'keepPanelRendering',
'viewerDrawsEntity',
'installZoomOutGuard',
'qaHandles',
])
assert.equal(scene[name], undefined, name);
// Keyless, the map stack shows Esri on the globe through the globe port.
assert.equal(scene.tileset, null);
assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery');
const layers = renderer.globe.imagery.list();
assert.equal(layers.length, 1, 'one base imagery layer');
assert.ok(
renderer.testing.calls.some(
(call) =>
call.port === 'globe' &&
call.member === 'imagery.add' &&
call.args[0]?.url?.includes('World_Imagery'),
),
'Esri imagery through the port',
);
assert.equal(scene.mapStackController.getDrapeSurface(), 'globe');
// Switching stacks goes through the port too.
await scene.mapStackController.setStack('osm');
assert.equal(scene.mapStackController.getActiveId(), 'osm');
assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way');
for (const fn of deferred.splice(0).reverse()) await fn();
assert.equal(scene.viewer.isDestroyed(), true);
assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer');
assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released');
});
test('with credentials, the photoreal base loads through the globe port', async (t) => {
const { scene, renderer } = await startOnStub(t, {
capabilities: ['photoreal', 'globeVisibility'],
googleApiKey: 'stub-key',
});
assert.ok(scene.tileset, 'a photoreal base');
assert.equal(scene.mapStackController.getActiveId(), 'photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden');
const photoreal = renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === 'setPhotoreal',
);
assert.equal(photoreal[0]?.args[0]?.key, 'stub-key');
// A globe stack hides photoreal through the port, and shows the globe.
await scene.mapStackController.setStack('esri-imagery');
assert.equal(renderer.globe.isGlobeVisible(), true);
assert.equal(
renderer.testing.calls
.filter((call) => call.port === 'globe' && call.member === 'setPhotoreal')
.at(-1).args[0],
null,
);
await scene.mapStackController.setStack('photoreal');
assert.equal(renderer.globe.isGlobeVisible(), false);
});
+3
View File
@@ -224,6 +224,9 @@ export function createApplicationTools({
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,
};
const debug = window.__godsEyeView;
defer(() => {
+9 -1
View File
@@ -1,5 +1,6 @@
import { MapSourceController } from './maps/controller.js';
import { createDefaultMapSources } from './maps/defaultSources.js';
import { mapEngineFor } from './maps/engine.js';
import { governorRequestRender } from './renderGovernor.js';
export { MAP_STACKS } from './maps/catalog.js';
export { photorealUnavailableReason } from './maps/availability.js';
@@ -9,9 +10,16 @@ export class MapStackController extends MapSourceController {
constructor(viewer, options = {}) {
const googleApiKey =
typeof window !== 'undefined' ? window.__GOOGLE_MAPS_API_KEY__ : '';
const registry = createDefaultMapSources({ ...options, googleApiKey });
// The scene's map engine, unless the caller names one.
const engine = options.engine ?? mapEngineFor(viewer);
const registry = createDefaultMapSources({
...options,
googleApiKey,
engine,
});
super(viewer, {
registry,
engine,
initialStack: options.googleTileset
? options.initialStack || 'photoreal'
: registry.defaultId,
+6 -5
View File
@@ -1,6 +1,6 @@
import { indexMapSources } from './registry.js';
import { createMapCredits } from './credits.js';
import { mapEngine } from './engine.js';
import { mapEngineFor } from './engine.js';
import { markBaseTileset } from '../render/baseTilesets.js';
import { acquireImageryComparison } from './imageryComparison.js';
@@ -24,9 +24,10 @@ const resolved = (provider, effectiveStackId) => ({
/**
* 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.
* choices. The scene changes go through the map engine of the scene's
* renderer (`engine.js`): its own, or its globe port. A viewer with no
* renderer bound gets one once its owner has loaded the package's
* `./render/cesium/unbound` export.
*/
export class MapSourceController {
constructor(
@@ -36,7 +37,7 @@ export class MapSourceController {
initialStack,
onChange = null,
onError = null,
engine = mapEngine(),
engine = mapEngineFor(viewer),
requestRender = () => engine.requestRender(viewer),
createImageryLayer = (provider) => engine.createImageryLayer(provider),
},
+2 -1
View File
@@ -2,7 +2,7 @@ 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 { cesiumMapEngine } from '../render/cesium/mapEngine.js';
import { createDefaultMapSources } from './defaultSources.js';
import { bindRenderer } from '../render/rendererOf.js';
@@ -61,6 +61,7 @@ function fixture(registry, options = {}) {
});
const controller = new MapSourceController(viewer, {
registry,
engine: cesiumMapEngine,
createImageryLayer: (provider) => ({ provider }),
onChange: (state) => changes.push(state),
...options,
+2 -3
View File
@@ -8,8 +8,8 @@ import { ESRI_ATTRIBUTION_HTML } from './attribution.js';
/**
* 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.
* `engine` given (the scene's map engine, `engine.js`), else the one the
* adapter provided for viewers with no renderer, when it is first shown.
*/
export function createDefaultMapSources({
googleTileset = null,
@@ -17,7 +17,6 @@ export function createDefaultMapSources({
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);
+30 -9
View File
@@ -1,18 +1,25 @@
/**
* @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.
* @description What the map stacks switch through: the providers each
* stack's imagery and terrain come from, and the scene operations the map
* source controller (`controller.js`) switches stacks with.
*
* The renderer's plugin may hand the application a map engine of its own
* (`mapEngine` in `src/render/applicationHooks.js`); when it hands none, the
* renderer switches through its globe port (`globeEngine.js`). A viewer
* with no renderer bound uses the engine its adapter
* provided as it loaded (the Cesium one through the package's
* `./render/cesium/unbound` export).
*/
import { applicationHooksOf } from '../render/applicationHooks.js';
import { rendererOf } from '../render/rendererOf.js';
import { globeMapEngine } from './globeEngine.js';
let provided = null;
/**
* Provide the map engine; a later call replaces it.
* Provide the map engine for viewers no renderer is bound to; a later call
* replaces it.
* @param {object} engine
*/
export function provideMapEngine(engine) {
@@ -20,7 +27,8 @@ export function provideMapEngine(engine) {
}
/**
* The map engine the renderer adapter provided.
* The map engine the renderer adapter provided for viewers no renderer is
* bound to.
* @returns {object}
* @throws {Error} When no adapter has provided one yet.
*/
@@ -31,3 +39,16 @@ export function mapEngine() {
);
return provided;
}
/**
* The map engine the map stacks of `host` switch through: its renderer's
* own, else its renderer's globe port, else (no renderer bound) the one the
* adapter provided.
* @param {object} host The scene object.
* @returns {object}
*/
export function mapEngineFor(host) {
const renderer = rendererOf(host);
if (!renderer) return mapEngine();
return applicationHooksOf(renderer).mapEngine ?? globeMapEngine;
}
+188
View File
@@ -0,0 +1,188 @@
/**
* @module maps/globeEngine
* @description The map engine (`engine.js`) over the renderer contract's
* globe port, for when the renderer's plugin hands the application no map
* engine of its own (`src/render/applicationHooks.js`). The map stacks'
* sources become the port's specs: Esri and OSM as `xyz` imagery, Cesium
* ion's world imagery as `world` imagery, the photoreal stack as the port's
* photoreal base, and terrain as `world` terrain (or the ellipsoid where the
* port has no keyless terrain to offer).
*
* What the map stack holds is what this engine hands it: a spec per imagery
* provider, a handle per imagery layer and photoreal base. A hidden
* photoreal base is turned off through the port and on again when shown.
*/
import { findFrame, findGlobe } from '../render/rendererOf.js';
const ESRI_TILES =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
const ESRI_CREDIT =
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community';
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`). */
const WORLD_STYLES = { 2: 'aerial', 3: 'aerialLabels' };
/** Values this engine released: never used again. */
const released = new WeakSet();
/** The layer an imagery spec is drawn by, while it is drawn. */
const layers = new WeakMap();
/** Whether each globe port's surface is shown, as last set here. */
const shownGlobes = new WeakMap();
const credit = (text) => ({ text });
/** Turn a photoreal handle's base on or off, reporting a failure. */
function applyPhotoreal(handle, shown) {
if (handle.shown === shown || released.has(handle)) return;
handle.shown = shown;
handle.globe
.setPhotoreal(shown ? handle.spec : null)
.catch((error) =>
console.warn('[MapStack] photoreal switch failed', error),
);
}
/**
* Load the photoreal base through `host`'s globe port with the credentials
* the scene holds. The port's own routes decide among them (Google's key or
* session tokens, then the renderer's fallback copy).
* @param {object} host
* @param {{googleApiKey?: string, googleTokens?: {token: Function}|null,
* cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
async function loadPhotoreal(
host,
{ googleApiKey = '', googleTokens = null, cesiumToken = '' } = {},
) {
const globe = findGlobe(host);
const key = String(googleApiKey || '').trim();
const fallback = Boolean(String(cesiumToken || '').trim());
if (!globe || (!key && !googleTokens && !fallback))
return { tileset: null, route: 'none', errors: [] };
const spec = {
provider: 'google',
...(key ? { key } : {}),
...(!key && googleTokens
? { token: (options) => googleTokens.token(options) }
: {}),
fallback,
};
try {
const status = await globe.setPhotoreal(spec);
if (status?.route && status.route !== 'none')
return {
tileset: { spec, globe, shown: true },
route: status.route,
errors: [],
};
const error = status?.error;
return {
tileset: null,
route: 'none',
errors: error ? [new Error(error.message || error.code)] : [],
};
} catch (error) {
return {
tileset: null,
route: 'none',
errors: [error instanceof Error ? error : new Error(String(error))],
};
}
}
export const globeMapEngine = Object.freeze({
imagery: Object.freeze({
osm: () =>
Object.freeze({
kind: 'xyz',
url: OSM_TILES,
tiling: 'webMercator',
maxLevel: 19,
credit: credit(OSM_CREDIT),
}),
esri: () =>
Object.freeze({
kind: 'xyz',
url: ESRI_TILES,
tiling: 'webMercator',
maxLevel: 19,
credit: credit(ESRI_CREDIT),
}),
ion(style, accessToken) {
if (!String(accessToken || '').trim())
throw new Error('Ion imagery requires an explicit token');
return Object.freeze({
kind: 'world',
worldStyle: WORLD_STYLES[style] ?? 'aerial',
});
},
}),
terrain: Object.freeze({
world: async (accessToken) => {
if (!String(accessToken || '').trim())
throw new Error('World terrain requires an explicit ion token');
return {
provider: null,
spec: { kind: 'world', requestVertexNormals: true },
};
},
keyless: async () => ({ provider: null, spec: { kind: 'ellipsoid' } }),
}),
createImageryLayer: (spec) => ({ spec, layer: null }),
requestRender(host) {
findFrame(host)?.requestRender('map-stack');
},
globeShown(host) {
const globe = findGlobe(host);
if (!globe) return false;
return globe.isGlobeVisible?.() ?? shownGlobes.get(globe) ?? true;
},
setGlobeShown(host, shown) {
const globe = findGlobe(host);
if (!globe) return;
globe.setGlobeVisible(shown);
shownGlobes.set(globe, shown);
},
addTileset() {},
removeTileset(host, handle) {
if (handle) applyPhotoreal(handle, false);
},
tilesetShown: (handle) => handle?.shown === true,
showTileset(handle, shown) {
if (handle) applyPhotoreal(handle, shown);
},
addImageryLayer(host, handle, index) {
const globe = findGlobe(host);
if (!globe || released.has(handle)) return;
handle.layer = globe.imagery.add(handle.spec, index);
layers.set(handle.spec, handle.layer);
},
removeImageryLayer(host, handle) {
if (layers.get(handle.spec) === handle.layer) layers.delete(handle.spec);
handle.layer?.remove();
handle.layer = null;
},
applyTerrain(host, result) {
findGlobe(host)
?.setTerrain(result.spec ?? null)
.catch((error) => console.warn('[MapStack] terrain failed', error));
},
/**
* Hear the failed tile requests of the layer drawing `spec`; null while
* none draws it. The port does not say how often a tile was retried.
*/
onTileError(spec, listener) {
const layer = layers.get(spec);
if (!layer) return null;
return layer.on('tileError', () => listener({}));
},
isDestroyed: (value) => Boolean(value) && released.has(value),
release(value) {
if (!value || typeof value !== 'object' || released.has(value)) return;
if (value.globe && value.spec) applyPhotoreal(value, false);
released.add(value);
},
loadPhotoreal,
});
+123
View File
@@ -0,0 +1,123 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { globeMapEngine as engine } from './globeEngine.js';
import { mapEngineFor, provideMapEngine } from './engine.js';
import { bindRenderer } from '../render/rendererOf.js';
import { provideApplicationHooks } from '../render/applicationHooks.js';
import { createStubRenderer } from '../render/stub/index.js';
function scene(capabilities) {
const renderer = createStubRenderer(capabilities ? { capabilities } : {});
const host = {};
bindRenderer(host, renderer);
return { host, renderer };
}
const calls = (renderer, member) =>
renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === member,
);
test('a renderer without a map engine of its own switches through its globe port', () => {
const { host, renderer } = scene();
assert.equal(mapEngineFor(host), engine);
const own = { own: true };
provideApplicationHooks(renderer, { mapEngine: own });
assert.equal(mapEngineFor(host), own, "the plugin's own comes first");
const provided = { provided: true };
provideMapEngine(provided);
assert.equal(mapEngineFor({}), provided, 'a viewer with no renderer');
});
test('imagery layers go through the port, lowest first, and come off again', () => {
const { host, renderer } = scene();
const spec = engine.imagery.esri();
assert.equal(spec.kind, 'xyz');
assert.match(
spec.url,
/World_Imagery\/MapServer\/tile\/\{z\}\/\{y\}\/\{x\}$/,
);
const layer = engine.createImageryLayer(spec);
engine.addImageryLayer(host, layer, 0);
assert.deepEqual(calls(renderer, 'imagery.add')[0].args, [spec, 0]);
assert.equal(renderer.globe.imagery.list().length, 1);
let errors = 0;
const off = engine.onTileError(spec, () => (errors += 1));
assert.equal(typeof off, 'function', 'tile errors are heard');
off();
engine.removeImageryLayer(host, layer);
assert.equal(renderer.globe.imagery.list().length, 0);
assert.equal(
engine.onTileError(spec, () => {}),
null,
'none once removed',
);
assert.equal(errors, 0);
});
test('the globe is shown and hidden through the port, read back without globe visibility', () => {
const { host, renderer } = scene([]);
assert.equal(engine.globeShown(host), true);
engine.setGlobeShown(host, false);
assert.equal(engine.globeShown(host), false);
assert.deepEqual(calls(renderer, 'setGlobeVisible').at(-1).args, [false]);
const visible = scene(['globeVisibility']);
engine.setGlobeShown(visible.host, false);
assert.equal(visible.renderer.globe.isGlobeVisible(), false);
assert.equal(engine.globeShown(visible.host), false);
});
test('terrain is the port’s world terrain, or the ellipsoid without a token', async () => {
const { host, renderer } = scene();
await assert.rejects(engine.terrain.world(''), /ion token/);
const world = await engine.terrain.world('token');
engine.applyTerrain(host, world);
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'world', requestVertexNormals: true },
]);
engine.applyTerrain(host, await engine.terrain.keyless());
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'ellipsoid' },
]);
assert.throws(() => engine.imagery.ion(2, ''), /token/);
assert.deepEqual(engine.imagery.ion(3, 'token'), {
kind: 'world',
worldStyle: 'aerialLabels',
});
});
test('photoreal loads through the port, hides and shows, and is released', async () => {
const { host, renderer } = scene(['photoreal']);
const none = await engine.loadPhotoreal(host, {});
assert.deepEqual(none, { tileset: null, route: 'none', errors: [] });
assert.equal(calls(renderer, 'setPhotoreal').length, 0, 'no credentials');
const tokens = { token: async () => 'session' };
const loaded = await engine.loadPhotoreal(host, { googleTokens: tokens });
assert.equal(loaded.route, 'google');
const handle = loaded.tileset;
assert.equal(engine.tilesetShown(handle), true);
const spec = calls(renderer, 'setPhotoreal')[0].args[0];
assert.equal(spec.provider, 'google');
assert.equal(await spec.token(), 'session');
assert.equal(spec.fallback, false);
engine.showTileset(handle, false);
assert.equal(engine.tilesetShown(handle), false);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], null);
engine.showTileset(handle, true);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], spec);
engine.release(handle);
assert.equal(engine.isDestroyed(handle), true);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], null);
const count = calls(renderer, 'setPhotoreal').length;
engine.showTileset(handle, true);
assert.equal(calls(renderer, 'setPhotoreal').length, count, 'never again');
});
test('a renderer without photoreal reports none, with the reason it gave', async () => {
const { host } = scene([]);
const result = await engine.loadPhotoreal(host, { googleApiKey: 'key' });
assert.equal(result.tileset, null);
assert.equal(result.route, 'none');
});
+43
View File
@@ -0,0 +1,43 @@
/**
* @module render/applicationHooks
* @description What a renderer's plugin may hand the application beside the
* contract: behaviour the application uses where a renderer has it, and does
* without where it has none. Nothing here is part of the renderer contract,
* and the application never asks which renderer it runs on: it reads the
* hooks of the renderer it was given, each of them optional.
*
* - `mapEngine`: the renderer's own map engine (`src/maps/engine.js`), which
* the map stacks switch through in place of the globe port
* (`src/maps/globeEngine.js`).
* - `trimStaleCommands()`: drops the draw commands a renderer keeps for a
* while after it stops drawing them; run after a layer turns off.
* - `keepPanelRendering(options)`: keeps the globe drawing in an inline panel
* whose host stops animation frames (embed mode); returns its disposer.
* - `viewerDrawsEntity(entity)`: whether an entity is one the renderer draws
* itself (Cockpit asks whether the aircraft it flies still draws).
* - `installZoomOutGuard(options)`: keeps outward user zooms bounded and the
* Earth framed; returns its disposer.
* - `qaHandles`: values QA scripts read from `window.__godsEyeView`.
*/
const hooks = new WeakMap();
const NONE = Object.freeze({});
/**
* Hand the application `value`'s hooks for `renderer`. A renderer's plugin
* calls it as it creates the renderer; a later call replaces them.
* @param {object} renderer
* @param {object} value
*/
export function provideApplicationHooks(renderer, value) {
hooks.set(renderer, Object.freeze({ ...value }));
}
/**
* The hooks `renderer`'s plugin provided; an empty object when it provided
* none, or `renderer` is not an object.
* @param {object|null|undefined} renderer
* @returns {Readonly<object>}
*/
export const applicationHooksOf = (renderer) =>
(renderer && hooks.get(renderer)) || NONE;
+60 -21
View File
@@ -8,27 +8,41 @@
* 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 viewer by the scene and the map stack; the globe port drapes
* its imagery on that base as drawn (see `globe.js`). `whenSettled` waits
* for the globe, the scene's 3D tiles and what the draw sets hold, not for
* what layers still draw through the viewer themselves.
* Until a family is ported, its code reaches the Cesium viewer through
* `cesiumViewerOf`, never through a renderer member, so no engine type
* crosses the contract and each call marks code still to port. Ported code
* that still holds the viewer reaches the renderer through `rendererOf`.
* through the Cesium map engine (`mapEngine.js`), which the plugin hands
* the application with the renderer (`../applicationHooks.js`); the globe
* port drapes its imagery on that base as drawn (see `globe.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), and the hooks the application uses where a renderer has
* them (stale command trimming, inline panel rendering, whether an entity
* is the viewer's own, the zoom-out guard, the viewer QA scripts read).
* Adapter code reaches the viewer behind a renderer through
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
* engine type crosses the contract.
*/
import { createApplicationViewer } from './applicationViewer.js';
import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js';
import { provideApplicationHooks } from '../applicationHooks.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.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';
import { cesiumMapEngine } from './mapEngine.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
import { keepPanelRendering } from './panelRendering.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { onLocaleChange } from '../../i18n/index.js';
import { cesiumViewerOf, recordViewer } from './viewers.js';
export { cesiumViewerOf };
/** @typedef {import('../contract/renderer').Renderer} TransitionalRenderer */
const viewers = new WeakMap();
/** A Set no one can change once built, so `capabilities` stays true. */
export class ReadonlySet extends Set {
#sealed;
@@ -51,14 +65,6 @@ export class ReadonlySet extends Set {
}
}
/**
* The Cesium viewer behind a renderer this plugin made, or null for any
* renderer it did not make.
* @param {object} renderer
* @returns {object|null}
*/
export const cesiumViewerOf = (renderer) => viewers.get(renderer) ?? null;
/**
* The Cesium plugin over a viewer factory; tests pass a fake one.
* @param {{createViewer?: typeof createApplicationViewer}} [options]
@@ -90,6 +96,8 @@ export function createCesiumRendererPlugin({
let ports;
let input;
let capabilities;
let releaseFreeLook = () => {};
let offLocale = () => {};
try {
viewer = createViewer({ container, creditContainer });
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
@@ -101,7 +109,19 @@ export function createCesiumRendererPlugin({
query: ports.query,
report: ports.report,
});
// Free look is limited to low heights from the start.
releaseFreeLook = installFreeLookHeightLimit(
viewer,
FREE_LOOK_MAX_HEIGHT_METERS,
);
configureCreditKeyboardAccess(document);
offLocale = onLocaleChange(() =>
configureCreditKeyboardAccess(document),
);
} catch (error) {
offLocale();
releaseFreeLook();
input?.dispose();
ports?.dispose();
if (viewer && !viewer.isDestroyed()) viewer.destroy();
creditContainer.remove();
@@ -132,6 +152,8 @@ export function createCesiumRendererPlugin({
},
destroy() {
try {
offLocale();
releaseFreeLook();
input.dispose();
ports.dispose();
if (!viewer.isDestroyed()) viewer.destroy();
@@ -143,8 +165,25 @@ export function createCesiumRendererPlugin({
}
},
});
viewers.set(renderer, viewer);
recordViewer(renderer, viewer);
unbind = bindRenderer(viewer, renderer);
provideApplicationHooks(renderer, {
mapEngine: cesiumMapEngine,
// Drops the draw commands the scene keeps after it stops drawing
// them; run after a drawn frame (see sceneCommandRelease.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene),
// Keeps the globe drawing in an inline panel whose host stops
// animation frames (embed mode, src/app/embed.js).
keepPanelRendering: (options) => keepPanelRendering(viewer, options),
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// Keeps outward user zooms bounded and the Earth framed; returns its
// disposer (see zoomOutGuard.js).
installZoomOutGuard: (options) => installZoomOutGuard(viewer, options),
// QA scripts drive and read the viewer itself.
qaHandles: { viewer },
});
return renderer;
},
});
+31 -44
View File
@@ -3,6 +3,8 @@ import test from 'node:test';
import * as Cesium from 'cesium';
import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js';
import { rendererOf } from '../rendererOf.js';
import { applicationHooksOf } from '../applicationHooks.js';
import { cesiumMapEngine } from './mapEngine.js';
import {
ReadonlySet,
cesiumRenderer,
@@ -55,12 +57,19 @@ function fakeViewer(log, { failDestroy = false } = {}) {
moveEnd: fakeEvent(listeners),
},
primitives: { add() {}, remove() {} },
// The free-look height limit writes the camera controller's look.
screenSpaceCameraController: {
enableLook: true,
minimumTrackBallHeight: 7_500_000,
},
requestRender() {},
preUpdate: fakeEvent(listeners),
postUpdate: fakeEvent(listeners),
preRender: fakeEvent(listeners),
postRender: fakeEvent(listeners),
},
camera: { positionCartographic: { height: 20_000_000 } },
entities: { contains: (entity) => entity?.own === true },
canvas: {
tag: 'canvas',
// Cesium's input handler binds the canvas's events.
@@ -128,6 +137,23 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
assert.equal(cesiumViewerOf(renderer).canvas, renderer.canvas);
assert.equal(rendererOf(viewer), renderer, 'the viewer finds its renderer');
assert.equal(
viewer.scene.screenSpaceCameraController.enableLook,
false,
'free look is limited to low heights from the start',
);
const hooks = applicationHooksOf(renderer);
assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium');
assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer');
assert.equal(hooks.viewerDrawsEntity({ own: true }), true);
assert.equal(hooks.viewerDrawsEntity({}), false);
for (const name of [
'trimStaleCommands',
'keepPanelRendering',
'installZoomOutGuard',
])
assert.equal(typeof hooks[name], 'function', name);
assert.ok(viewer.listeners.size > 0, 'the ports follow the frame phases');
assert.equal(typeof renderer.draw.icons, 'function');
assert.ok(renderer.capabilities.has('models'), 'draw.models is declared');
@@ -136,6 +162,11 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
renderer.destroy();
assert.equal(viewer.listeners.size, 0, 'and stop on destroy');
assert.equal(rendererOf(viewer), null, 'and lets go of the viewer');
assert.equal(
viewer.scene.screenSpaceCameraController.enableLook,
true,
'and gives free look back',
);
assert.deepEqual(log, ['resize', 'destroy']);
assert.deepEqual(doc.children, [], 'credits leave with the renderer');
renderer.destroy();
@@ -273,48 +304,4 @@ test('only renderers this plugin made reach a Cesium viewer', () => {
assert.equal(cesiumViewerOf({}), null);
});
test('the application refuses a renderer it cannot run on, and destroys it', async (t) => {
const { createApplicationScene } = await import('../../app/scene.js');
const { createApplicationRequestServices } =
await import('../../services/requests.js');
const destroyed = [];
const deferred = [];
const plugin = {
id: 'other',
async create(options) {
assert.ok(options.signal, 'the scene passes its signal');
return {
id: 'other',
destroy: () => {
destroyed.push('other');
throw new Error('and it fails to go');
},
};
},
};
const saved = { document: globalThis.document, window: globalThis.window };
globalThis.document = fakeDocument();
globalThis.window = new EventTarget();
const warn = console.warn;
console.warn = () => {};
t.after(() => {
for (const fn of deferred.reverse()) fn();
console.warn = warn;
globalThis.document = saved.document;
globalThis.window = saved.window;
});
await assert.rejects(
createApplicationScene({
renderer: plugin,
requestServices: createApplicationRequestServices(),
loaderStatus: { textContent: '' },
signal: new AbortController().signal,
defer: (fn) => deferred.push(fn),
}),
/renderer cannot run the application yet/,
'the refusal is not hidden by the failed destroy',
);
assert.deepEqual(destroyed, ['other']);
});
const EXPECTED_MISSING = [];
+6 -65
View File
@@ -1,69 +1,10 @@
/**
* @module render/cesium/application
* @description The Cesium adapter's side of the application scene
* (`src/app/scene.js`), its composition root: the default renderer plugin,
* the viewer behind a renderer it made, the photoreal base tileset the scene
* loads into that viewer, and the viewer hooks the scene hands the
* application (stale command trimming, inline panel rendering, whether an
* entity is the viewer's own, the zoom-out guard, the free-look height
* limit). The scene imports this module and no other
* part of the adapter (`src/render/noCesiumOutsideRender.test.mjs`).
* (`src/app/scene.js`), its composition root: the default renderer plugin.
* Everything else the application needs of this renderer comes with each
* renderer the plugin makes (`appRenderer.js`). The scene imports this
* module, when it is given no renderer of its own, and no other part of the
* adapter (`src/render/noCesiumOutsideRender.test.mjs`).
*/
import * as Cesium from 'cesium';
import { cesiumRenderer, cesiumViewerOf } from './appRenderer.js';
import { loadPhotorealisticTileset } from './google3d.js';
import { keepPanelRendering } from './panelRendering.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { installZoomOutGuard } from './zoomOutGuard.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
export { cesiumRenderer, cesiumViewerOf };
/**
* Load Google Photorealistic 3D Tiles for the application, by the best route
* the credentials allow (`google3d.js`).
* @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
export const loadApplicationPhotoreal = (credentials) =>
loadPhotorealisticTileset(Cesium, credentials);
/** Draw the loaded photoreal tileset in `viewer`. */
export function showApplicationPhotoreal(viewer, tileset) {
viewer.scene.primitives.add(tileset);
}
/**
* Release the photoreal tileset: out of `viewer`, which destroys it, or
* destroyed by itself when the viewer never held it.
*/
export function releaseApplicationPhotoreal(viewer, tileset) {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
}
/**
* What the application scene hands the application about its viewer.
* @param {object} viewer
*/
export function applicationViewerHooks(viewer) {
return {
// Drops the draw commands the scene keeps after it stops drawing them;
// run after a drawn frame (see sceneCommandRelease.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene),
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js).
keepPanelRendering: (options) => keepPanelRendering(viewer, options),
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// Keeps outward user zooms bounded and the Earth framed; returns its
// disposer (see zoomOutGuard.js).
installZoomOutGuard: (options) => installZoomOutGuard(viewer, options),
// Allows the camera controller's free look only near the ground; returns
// its disposer (see freeLookLimit.js).
installFreeLookHeightLimit: (maxHeight) =>
installFreeLookHeightLimit(viewer, maxHeight),
};
}
export { cesiumRenderer } from './appRenderer.js';
@@ -2,7 +2,7 @@
* Adds the keyboard semantics omitted by Cesium's href-less attribution links.
* Cesium retains ownership of showing and hiding its required credit lightbox.
*/
import { t } from './i18n/index.js';
import { t } from '../../i18n/index.js';
export function configureCreditKeyboardAccess(root = document) {
const expand = root?.querySelector?.(
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { setLocale } from './i18n/index.js';
import { setLocale } from '../../i18n/index.js';
function fakeElement() {
const attributes = new Map();
+33 -16
View File
@@ -2,11 +2,17 @@
* @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.
* `mapTerrain.js`), the photoreal base the application scene loads
* (`google3d.js`), and the viewer operations the map source controller
* switches stacks with. Each operation takes the scene object: the viewer
* behind it (`viewers.js`) is the one it changes. Provided as this module
* loads, for viewers with no renderer bound, and handed to the application
* with each renderer the plugin makes (`appRenderer.js`).
*/
import * as Cesium from 'cesium';
import { provideMapEngine } from '../../maps/engine.js';
import { loadPhotorealisticTileset } from './google3d.js';
import { viewerBehind } from './viewers.js';
import {
createEsriImagery,
createIonImagery,
@@ -27,33 +33,35 @@ export const cesiumMapEngine = Object.freeze({
}),
/** The layer a globe stack's imagery provider draws through. */
createImageryLayer: (provider) => new Cesium.ImageryLayer(provider),
requestRender(viewer) {
viewer?.scene?.requestRender?.();
requestRender(host) {
viewerBehind(host)?.scene?.requestRender?.();
},
globeShown: (viewer) => viewer?.scene?.globe?.show === true,
setGlobeShown(viewer, shown) {
viewer.scene.globe.show = shown;
globeShown: (host) => viewerBehind(host)?.scene?.globe?.show === true,
setGlobeShown(host, shown) {
viewerBehind(host).scene.globe.show = shown;
},
addTileset(viewer, tileset) {
viewer.scene.primitives.add(tileset);
addTileset(host, tileset) {
viewerBehind(host).scene.primitives.add(tileset);
},
removeTileset(viewer, tileset) {
viewer.scene.primitives.remove(tileset);
/** Removed, which destroys it. */
removeTileset(host, tileset) {
viewerBehind(host).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);
addImageryLayer(host, layer, index) {
viewerBehind(host).imageryLayers.add(layer, index);
},
/** Removed and destroyed. */
removeImageryLayer(viewer, layer) {
viewer.imageryLayers.remove(layer, true);
removeImageryLayer(host, layer) {
viewerBehind(host).imageryLayers.remove(layer, true);
},
/** A terrain factory's result: `{terrain}` or `{provider}`. */
applyTerrain(viewer, result) {
applyTerrain(host, result) {
const viewer = viewerBehind(host);
if (result.terrain) viewer.scene.setTerrain(result.terrain);
else viewer.terrainProvider = result.provider;
},
@@ -75,6 +83,15 @@ export const cesiumMapEngine = Object.freeze({
if (typeof value?.destroy === 'function' && !value.isDestroyed?.())
value.destroy();
},
/**
* Load Google Photorealistic 3D Tiles by the best route the credentials
* allow (`google3d.js`); the tileset is not yet drawn.
* @param {object} host
* @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
loadPhotoreal: (host, credentials) =>
loadPhotorealisticTileset(Cesium, credentials),
});
provideMapEngine(cesiumMapEngine);
+5 -4
View File
@@ -17,6 +17,7 @@ import { provideNativeClick } from '../rendererOf.js';
import { drawHitOf } from './drawHit.js';
import { pickThroughFollowHelper } from './follow.js';
import { recentPick } from './pickMemo.js';
import { viewerBehind } from './viewers.js';
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
@@ -165,10 +166,10 @@ export function createNativeClick(scene, at) {
};
}
// Any Cesium viewer, bound or not, by shape: a caller's may come from
// another copy of Cesium.
provideNativeClick((viewer, at) => {
const scene = viewer?.scene;
// The viewer behind the scene object, bound or not, by shape: an unbound one
// may come from another copy of Cesium.
provideNativeClick((host, at) => {
const scene = viewerBehind(host)?.scene;
if (typeof scene?.pick !== 'function') return null;
return createNativeClick(scene, at);
});
+36
View File
@@ -0,0 +1,36 @@
/**
* @module render/cesium/viewers
* @description The Cesium viewer behind each renderer the application's
* plugin made (`appRenderer.js`), and the viewer behind a scene object the app
* holds: the one its bound renderer draws with, or the scene object itself
* when it is a viewer with no renderer bound.
*/
import { rendererOf } from '../rendererOf.js';
const viewers = new WeakMap();
/**
* Record `viewer` as the one behind `renderer`.
* @param {object} renderer
* @param {object} viewer
*/
export function recordViewer(renderer, viewer) {
viewers.set(renderer, viewer);
}
/**
* The Cesium viewer behind a renderer the application's plugin made, or
* null for the test stub.
* @param {object} renderer
* @returns {object|null}
*/
export const cesiumViewerOf = (renderer) =>
(renderer && viewers.get(renderer)) || null;
/**
* The Cesium viewer behind the scene object `host`: its bound renderer's,
* else `host` itself (a viewer with no renderer bound, or none at all).
* @param {object|null|undefined} host
* @returns {object|null|undefined}
*/
export const viewerBehind = (host) => cesiumViewerOf(rendererOf(host)) ?? host;
+2 -3
View File
@@ -6,7 +6,6 @@ import {
maxPitchForHeight,
MAXIMUM_ZOOM_DISTANCE_M,
} from './zoomOutGuard.js';
import { applicationViewerHooks } from './application.js';
const deg = Cesium.Math.toDegrees;
const { WHEEL, PINCH, RIGHT_DRAG, LEFT_DRAG, MIDDLE_DRAG } =
@@ -764,7 +763,7 @@ test('a tracked camera cannot climb past the ceiling from its target', () => {
}
});
test("the application scene's viewer hooks install the guard on the viewer and hand back its disposer", () => {
test('the guard installs on the viewer and hands back its disposer', () => {
const controller = { maximumZoomDistance: Infinity };
const scene = {
mode: Cesium.SceneMode.SCENE3D,
@@ -778,7 +777,7 @@ test("the application scene's viewer hooks install the guard on the viewer and h
};
const viewer = { scene, camera, canvas: new EventTarget() };
const handoffs = new Set();
const dispose = applicationViewerHooks(viewer).installZoomOutGuard({
const dispose = installZoomOutGuard(viewer, {
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
+24
View File
@@ -223,6 +223,30 @@ export function bindRenderer(host, renderer) {
};
}
/**
* The scene object the application holds for `renderer`: what every layer
* and tool is handed, and reaches the renderer's ports through. It is the
* application's own: the element the renderer
* fills (`container`) and whether the scene is gone (`isDestroyed()`), and
* nothing of the engine.
* @param {object} renderer
* @param {{container: HTMLElement}} options
* @returns {{host: Readonly<{container: HTMLElement, isDestroyed: () => boolean}>,
* release: () => void}} `release` marks the scene gone and unbinds it.
*/
export function createSceneHost(renderer, { container }) {
let destroyed = false;
const host = Object.freeze({ container, isDestroyed: () => destroyed });
const unbind = bindRenderer(host, renderer);
return {
host,
release() {
destroyed = true;
unbind();
},
};
}
/**
* @param {object|null|undefined} host
* @returns {object|null} The renderer bound to `host`, or null.
+7 -1
View File
@@ -19,8 +19,12 @@ import { createGoogleTokenSource } from '../maps/googleTokens.js';
// The existing controls and layer catalog contain page-scoped state.
let constructed = false;
/** Compose the standalone application once per page. Reload to start again. */
/**
* Compose the standalone application once per page. Reload to start again.
* `renderer` is the renderer plugin it draws with (default: Cesium).
*/
export function createStandaloneApplication({
renderer,
googleApiKey,
cesiumToken,
geospatial = {},
@@ -67,6 +71,8 @@ export function createStandaloneApplication({
});
const scene = await createStandaloneScene({
...context,
// The renderer plugin; the default (Cesium) when none is given.
renderer,
googleApiKey,
// Without a key, Google 3D can still load with tokens from the
// app's server when it offers them.