Merge origin/main into fix/earthquake-click-details

This commit is contained in:
manjunath22466 committed 2026-11-17 11:49:17 +05:30
commit 4804097ca1
204 files changed
+34669 -680

No files matched your search

+15 -11
View File
@@ -7,17 +7,15 @@
* The renderer it makes is transitional. Its ports are the shared Cesium
* ports (`ports.js`), the ones the conformance renderer is checked with,
* and it has every member of the contract. The application's base (the
* photoreal tiles, the map stack's imagery and terrain) is still loaded
* through the Cesium map engine (`mapEngine.js`), which the plugin hands
* the application with the renderer (its `applicationHooks`); the globe
* port drapes its imagery on that base as drawn (see `globe.js`).
* photoreal tiles, the map stack's imagery and terrain) is loaded through
* the globe port, as on any renderer (`src/maps/globeEngine.js`).
* `whenSettled` waits for the globe, the scene's 3D tiles and what the draw
* sets hold.
*
* What only this renderer needs at startup is set up here: the free-look
* height limit, keyboard access to the credits' expand link (in the page's
* language). The plugin's `applicationHooks` are what the application
* uses where a renderer has them: the map engine, stale command trimming,
* uses where a renderer has them: stale command trimming,
* whether an entity is the viewer's own, and the viewer QA scripts read.
* Adapter code reaches the viewer behind a renderer through
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
@@ -30,14 +28,14 @@ import { bindRenderer } from '../rendererOf.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js';
import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
import { IDLE_FRAME_RATE } from '../../renderGovernor.js';
import { cesiumMapEngine } from './mapEngine.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { onLocaleChange } from '../../i18n/index.js';
import { cesiumViewerOf, recordViewer } from './viewers.js';
import { installRenderFailureNotice } from './renderFailure.js';
import { cesiumCardPreviews } from './cardPreviews.js';
import { cesiumPhotorealOf } from './globe.js';
export { cesiumViewerOf };
@@ -128,8 +126,6 @@ export function createCesiumRendererPlugin({
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
ports = createCesiumPorts(viewer, {
capabilities,
// Ticking at the display's rate only while anything moves.
idleFps: IDLE_FRAME_RATE,
credentials: { googleApiKey, googleTokens, worldDataToken },
...(cameraController ? { cameraController } : {}),
...(clock ? { now, date: () => clock.date() } : {}),
@@ -214,7 +210,6 @@ export function createCesiumRendererPlugin({
applicationHooks(renderer) {
const viewer = cesiumViewerOf(renderer);
return {
mapEngine: cesiumMapEngine,
// Cesium's credit display (#cesium-credits) shows the credits.
ownCreditDisplay: true,
// Drops the draw commands the scene keeps after it stops drawing
@@ -224,11 +219,20 @@ export function createCesiumRendererPlugin({
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// QA scripts drive and read the viewer itself.
qaHandles: { viewer },
qaHandles: {
viewer,
/** The photoreal tileset the globe holds now, shown or hidden. */
get tileset() {
return cesiumPhotorealOf(viewer.scene);
},
},
// A recoverable notice when the globe stops drawing
// (renderFailure.js).
renderFailureNotice: (options) =>
installRenderFailureNotice(viewer, options),
// The Context card's previews, each in a small scene of its own
// (cardPreviews.js).
cardPreviews: cesiumCardPreviews,
};
},
});
+24 -7
View File
@@ -3,8 +3,14 @@ import test from 'node:test';
import * as Cesium from 'cesium';
import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js';
import { rendererOf } from '../rendererOf.js';
import { IDLE_FRAME_RATE } from '../../renderGovernor.js';
import { cesiumMapEngine } from './mapEngine.js';
import {
_resetRenderGovernorForTest,
holdContinuousRender,
IDLE_FRAME_RATE,
installRenderGovernor,
releaseContinuousRender,
uninstallRenderGovernor,
} from '../../renderGovernor.js';
import {
ReadonlySet,
cesiumRenderer,
@@ -143,7 +149,11 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
'free look is limited to low heights from the start',
);
const hooks = plugin.applicationHooks(renderer);
assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium');
assert.equal(
hooks.mapEngine,
undefined,
'the map stacks switch through the globe port',
);
assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits');
assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer');
assert.equal(hooks.viewerDrawsEntity({ own: true }), true);
@@ -169,7 +179,7 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
assert.deepEqual(log, ['resize', 'destroy'], 'destroying twice is safe');
});
test('the application’s loop ticks at the idle rate while nothing moves, and at the display’s while anything does', async (t) => {
test('with the governor installed, the loop ticks at the idle rate while nothing moves, and at the display’s while anything does, the renderer’s own holds included', async (t) => {
withDocument(t, fakeDocument());
let viewer;
const plugin = createCesiumRendererPlugin({
@@ -184,12 +194,19 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a
container: {},
signal: new AbortController().signal,
});
installRenderGovernor(renderer.frame);
t.after(() => _resetRenderGovernorForTest());
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE, 'idle');
holdContinuousRender('flights');
assert.equal(viewer.targetFrameRate, undefined, 'a layer moving');
releaseContinuousRender('flights');
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE);
assert.equal(renderer.frame.diagnostics().targetFps, 0, 'no cap');
const release = renderer.frame.holdContinuous('flights');
assert.equal(viewer.targetFrameRate, undefined);
// As animated visual styles hold it (effects.js).
const release = renderer.frame.holdContinuous('effects:animated');
assert.equal(viewer.targetFrameRate, undefined, 'the renderer’s own hold');
release();
assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE);
uninstallRenderGovernor(renderer.frame);
renderer.destroy();
});
+3 -2
View File
@@ -106,8 +106,9 @@ export function createApplicationViewer({
}),
);
try {
// Until the frame port takes over (appRenderer.js), tick at the idle
// rate so the startup load does not compete with drawing at 240 fps.
// Until the render governor takes over (src/renderGovernor.js, installed
// by src/app/scene.js), tick at the idle rate so the startup load does
// not compete with drawing at 240 fps.
viewer.targetFrameRate = IDLE_FRAME_RATE;
// No double-click follow or zoom: the Viewer's own (it tracked or
// zoomed to the entity picked) is off. Following is a layer's click.
+753
View File
@@ -0,0 +1,753 @@
/**
* @module render/cesium/cardPreviews
* @description The Context card's previews on the Cesium renderer: an
* aircraft's model turning on its own, its route on a small globe, and the
* view ahead from its cockpit. Each draws in a small Cesium scene of its own
* inside the element it is given, and is torn down with the card. The
* application reaches them through the `cardPreviews` application hook
* (`render/applicationHooks.js`); the card's words, figures and HUD stay
* the application's.
*
* Every preview is `{setActive(active), update(values), destroy()}`: a
* hidden one stops drawing and rests on its last frame, and shown again it
* draws once straight away so there is no gap. A preview that cannot be
* made calls its `onFailed`.
*/
import * as Cesium from 'cesium';
import { webglContext } from './internals.js';
import { createEsriImagery } from './mapImagery.js';
/**
* Destroy a preview's widget and free its WebGL context. A browser keeps
* only a handful of contexts open and drops the oldest, the main globe's,
* when there are too many; a destroyed widget's context is otherwise freed
* only when garbage is collected, so flicking through cards could push the
* globe's out.
* @param {Cesium.CesiumWidget|null} widget
*/
function destroyWidget(widget) {
if (!widget || widget.isDestroyed()) return;
let gl = null;
try {
gl = webglContext(widget.scene) ?? null;
} catch {
gl = null;
}
widget.destroy();
try {
gl?.getExtension?.('WEBGL_lose_context')?.loseContext();
} catch {
// Nothing more can be done; the context goes when it is collected.
}
}
/** A small widget with no input, credits or render-loop error panel. */
function createWidget(container, options) {
const widget = new Cesium.CesiumWidget(container, {
skyBox: false,
scene3DOnly: true,
shadows: false,
showRenderLoopErrors: false,
// The globe's own credits already show; a preview's go in its corner.
creditContainer: document.createElement('div'),
...options,
});
widget.scene.screenSpaceCameraController.enableInputs = false;
return widget;
}
/**
* Stops a hidden widget's render loop once `ready()` says it has something
* to rest on; shown again, it draws once at once.
*/
function renderLoopSwitch(widget, ready = () => true) {
let active = true;
const sync = () => {
if (widget.isDestroyed()) return;
const run = active || !ready();
if (run && !widget.useDefaultRenderLoop) {
widget.resize();
widget.render();
}
widget.useDefaultRenderLoop = run;
};
return {
sync,
set(next) {
active = Boolean(next);
sync();
},
};
}
const reducedMotion = () =>
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
// ── The turning model ──────────────────────────────────────────────────
/** How long each look lasts, and each reveal between them, in turns. */
const PLAIN_TURNS = 1;
const SCAN_TURNS = 0.3;
const REVEAL_TURNS = 0.07;
/** How long (ms) the plain model holds after the reveal before a cycle ends. */
const HOLD_MS = 700;
/** How fast the model turns, in radians a millisecond (about 0.3 a second). */
const TURN_PER_MS = 0.0003;
// Model space, normalised so the craft reaches about 1.7 from its centre.
// u_reveal runs 0 to 2: from 0 to 1 the edge grows from the centre and
// leaves wire inside it; at 1 it is all wire; from 1 to 2 it grows again and
// leaves the model inside it. Outside that range the model draws as it is.
const LOOK_SHADER = `
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
if (u_reveal <= 0.0 || u_reveal >= 2.0) return;
vec3 p = fsInput.attributes.positionMC / u_half;
bool entering = u_reveal < 1.0;
float r = length(p);
float front = mix(0.0, 1.8, entering ? u_reveal : u_reveal - 1.0);
float edge = 1.0 - smoothstep(0.0, 0.05, abs(r - front));
vec3 white = vec3(0.9, 0.96, 1.0);
bool wire = entering ? r < front : r > front;
if (!wire) {
material.emissive += white * edge * 1.4;
return;
}
// A fine grid: many small cells, hairline lines.
vec3 q = p * 18.0;
vec3 g = abs(fract(q - 0.5) - 0.5) / max(fwidth(q), vec3(1e-4));
float line = (1.0 - clamp(min(min(g.x, g.y), g.z) * 2.4, 0.0, 1.0)) * 0.7;
vec3 base = material.diffuse;
// Opaque: a near-black body with white lines on it and its own colour
// faintly through, which reads as a wireframe against the dark card (a
// translucent model does not blend onto this scene's transparent canvas).
material.diffuse = base * 0.12 + vec3(0.015, 0.02, 0.03);
material.specular = vec3(0.0);
material.emissive = white * line + base * 0.35 + white * edge * 1.4;
}`;
/**
* An aircraft's model turning slowly, with no globe, sky or imagery. Its
* look changes as it turns: a whole rotation as it is, then a short
* wireframe scan (under a third of a turn), then round again; each change is
* a reveal, a bright ring growing from the craft's centre to its edges. One
* custom shader does it, driven by a uniform, because a shader set on a
* model after it is ready does nothing in this Cesium. Under reduced motion
* there is no scan.
*
* `onPhase('plain'|'scan')` says when the look changes; `onCycle(ms)` when a
* look and its scan end, with the drawing time they took, so the card can
* give another view the same time.
* @param {HTMLElement} container
* @param {{gltf: Uint8Array|ArrayBuffer, basePath?: string, heading?: number,
* viewRange?: number}} model The GLB's bytes; the heading (degrees) it
* starts facing; how far the camera stands, in bounding radii.
* @param {{onPhase?: (phase: string) => void, onCycle?: (ms: number) => void,
* onFailed?: () => void}} [events]
*/
function modelPreview(
container,
{ gltf, basePath, heading = 0, viewRange = 1.9 },
{ onPhase = () => {}, onCycle = () => {}, onFailed = () => {} } = {},
) {
let widget = null;
let model = null;
let loaded = false;
let removeTick = null;
let loop = null;
const fail = () => {
if (!widget) return;
onFailed();
};
try {
widget = createWidget(container, {
globe: false,
skyAtmosphere: false,
baseLayer: false,
contextOptions: { webgl: { alpha: true, antialias: true } },
});
const { scene } = widget;
scene.backgroundColor = Cesium.Color.TRANSPARENT;
scene.light = new Cesium.DirectionalLight({
direction: Cesium.Cartesian3.normalize(
new Cesium.Cartesian3(-0.4, -0.6, -0.7),
new Cesium.Cartesian3(),
),
intensity: 2.4,
});
loop = renderLoopSwitch(widget, () => loaded);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
const shader = new Cesium.CustomShader({
uniforms: {
u_reveal: { type: Cesium.UniformType.FLOAT, value: 0 },
u_half: { type: Cesium.UniformType.FLOAT, value: 20 },
},
fragmentShaderText: LOOK_SHADER,
});
const origin = Cesium.Cartesian3.fromDegrees(0, 0, 0);
const start = (sphere) => {
// The craft reaches about 0.6 of its bounding radius from the centre.
shader.setUniform('u_half', sphere.radius * 0.6);
const first = Cesium.Math.toRadians(heading + 140);
let turn = first;
let phase = 'plain';
let cycleMs = 0;
let lastFrame = performance.now();
let holdMs = null;
const still = reducedMotion();
const range = sphere.radius * viewRange;
const pitch = Cesium.Math.toRadians(-18);
const ease = (x) => x * x * (3 - 2 * x);
const frame = () => {
// Only time spent drawing counts: a hidden preview stops drawing.
const now = performance.now();
const drawn = now - lastFrame < 250 ? now - lastFrame : 0;
lastFrame = now;
// A steady turn whatever the display's refresh rate; still under
// reduced motion.
if (!still) turn += TURN_PER_MS * drawn;
const turns = (turn - first) / (2 * Math.PI);
// Where in the scan it is, and from that how far each reveal has gone.
const into = (turns % (PLAIN_TURNS + SCAN_TURNS)) - PLAIN_TURNS;
let reveal = 0;
if (!still && into >= 0) {
if (into < REVEAL_TURNS) reveal = ease(into / REVEAL_TURNS);
else if (into > SCAN_TURNS - REVEAL_TURNS)
reveal =
1 + ease((into - (SCAN_TURNS - REVEAL_TURNS)) / REVEAL_TURNS);
else reveal = 1;
}
const next = reveal > 0 && reveal < 2 ? 'scan' : 'plain';
cycleMs += drawn;
// The cycle ends once the reveal back to the model has finished and
// the plain model has held a moment, never mid-reveal.
if (phase === 'scan' && next === 'plain') holdMs = 0;
if (holdMs !== null && next === 'plain') {
holdMs += drawn;
if (holdMs >= HOLD_MS) {
onCycle(cycleMs);
cycleMs = 0;
holdMs = null;
}
}
if (next !== phase) {
phase = next;
onPhase(phase);
}
shader.setUniform('u_reveal', reveal);
widget.camera.lookAt(
sphere.center,
new Cesium.HeadingPitchRange(turn, pitch, range),
);
};
frame();
removeTick = widget.scene.preRender.addEventListener(frame);
widget.render();
loaded = true;
loop.sync();
};
Cesium.Model.fromGltfAsync({
gltf,
basePath,
customShader: shader,
modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(origin),
// A light rim so the mesh reads against the dark card.
silhouetteColor: Cesium.Color.WHITE.withAlpha(0.3),
silhouetteSize: 1,
}).then((made) => {
if (!widget) {
made.destroy();
return;
}
model = widget.scene.primitives.add(made);
model.readyEvent.addEventListener(() => {
if (widget) start(model.boundingSphere);
});
model.errorEvent?.addEventListener?.(fail);
}, fail);
function move(atNow) {
const at = onRoute(from, to, atNow);
if (!widget || !at || !plane || flyingIn) return;
pose(plane, at);
if (flownLine) flownLine.polyline.positions = arc(from, at, 48);
if (aheadLine) aheadLine.polyline.positions = arc(at, to);
widget.scene.requestRender();
}
return {
setActive: (active) => loop.set(active),
update() {},
destroy() {
removeTick?.();
removeTick = null;
const gone = widget;
widget = null;
model = null;
destroyWidget(gone);
},
};
}
// ── The route globe ────────────────────────────────────────────────────
const CYAN = Cesium.Color.fromCssColorString('#36dcff');
const AMBER = Cesium.Color.fromCssColorString('#ffb86b');
/** Height (m) the route and the plane are drawn at, clear of the globe. */
const ROUTE_HEIGHT_M = 30_000;
// The plane: the Material "flight" silhouette, nose up (north), white with
// a cyan glow, drawn once as an image.
const PLANE_ICON = `data:image/svg+xml;utf8,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 32 32" width="64" height="64">' +
'<defs><filter id="g" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="1.4"/></filter></defs>' +
'<path filter="url(#g)" fill="#36dcff" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
'<path fill="#ffffff" stroke="#0b1820" stroke-width="0.6" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
'</svg>',
)}`;
/**
* An airport's code as an image, white with a dark outline, at the page's
* pixel ratio. The preview is a small scene of its own, so its two codes are
* drawn into it rather than on the world overlay, which belongs to the globe.
* @param {string} code
* @returns {{image: HTMLCanvasElement, width: number, height: number}}
* the image and its size on screen, CSS pixels
*/
function codeImage(code) {
const ratio = Math.min(3, Math.max(1, globalThis.devicePixelRatio || 1));
const font = `600 ${11 * ratio}px ui-monospace, monospace`;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = font;
const pad = 3 * ratio;
canvas.width = Math.ceil(context.measureText(code).width + pad * 2);
canvas.height = Math.ceil(15 * ratio);
context.font = font;
context.textBaseline = 'middle';
context.lineJoin = 'round';
context.lineWidth = 3 * ratio;
context.strokeStyle = '#000';
context.fillStyle = '#fff';
context.strokeText(code, pad, canvas.height / 2);
context.fillText(code, pad, canvas.height / 2);
return {
image: canvas,
width: canvas.width / ratio,
height: canvas.height / ratio,
};
}
/** The initial bearing (degrees from north) of the great circle a → b. */
function bearing(a, b) {
const rad = Math.PI / 180;
const y = Math.sin((b.lon - a.lon) * rad) * Math.cos(b.lat * rad);
const x =
Math.cos(a.lat * rad) * Math.sin(b.lat * rad) -
Math.sin(a.lat * rad) *
Math.cos(b.lat * rad) *
Math.cos((b.lon - a.lon) * rad);
return (Math.atan2(y, x) / rad + 360) % 360;
}
const geodesic = (a, b) =>
new Cesium.EllipsoidGeodesic(
Cesium.Cartographic.fromDegrees(a.lon, a.lat),
Cesium.Cartographic.fromDegrees(b.lon, b.lat),
);
/** Points along the great circle from a to b, as far as `upTo` (0 to 1). */
function arc(a, b, steps = 64, upTo = 1) {
const line = geodesic(a, b);
const out = [];
const n = Math.max(2, Math.round(steps * upTo));
for (let i = 0; i <= n; i++) {
const c = line.interpolateUsingFraction((i / n) * upTo);
out.push(
Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, ROUTE_HEIGHT_M),
);
}
return out;
}
/**
* The point on the great circle from `from` to `to` nearest the craft. The
* craft is drawn there and the route split there, so the path stays one
* smooth arc: a craft a little off the direct line (vectors, airways, a
* detour) would otherwise bend it into a sharp corner.
*/
function onRoute(from, to, at) {
if (!at || !Number.isFinite(at.lat) || !Number.isFinite(at.lon)) return null;
const route = geodesic(from, to);
const here = Cesium.Cartesian3.fromDegrees(at.lon, at.lat);
const point = new Cesium.Cartesian3();
let best = null;
let bestDistance = Infinity;
const STEPS = 200;
for (let i = 0; i <= STEPS; i++) {
const c = route.interpolateUsingFraction(i / STEPS);
Cesium.Cartesian3.fromRadians(
c.longitude,
c.latitude,
0,
Cesium.Ellipsoid.WGS84,
point,
);
const d = Cesium.Cartesian3.distanceSquared(here, point);
if (d < bestDistance) {
bestDistance = d;
best = {
lat: Cesium.Math.toDegrees(c.latitude),
lon: Cesium.Math.toDegrees(c.longitude),
};
}
}
return best;
}
/**
* The plane's billboard pose, nose along `deg` from north: the icon's up is
* tied to the local north on the globe and turned from there, so it points
* the right way in this tilted view too.
*/
function planePose(at, deg) {
const position = Cesium.Cartesian3.fromDegrees(
at.lon,
at.lat,
ROUTE_HEIGHT_M,
);
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const north = Cesium.Matrix4.getColumn(frame, 1, new Cesium.Cartesian4());
return {
position,
rotation: -Cesium.Math.toRadians(deg),
alignedAxis: new Cesium.Cartesian3(north.x, north.y, north.z),
};
}
/**
* A flight's route on a small globe: the great circle from origin to
* destination, solid where it has flown and dashed ahead, the two airports
* marked with their codes, and a plane where the craft is now, pointing at
* the destination. On opening, the flown part draws out from the origin to
* the craft. The globe uses Cesium's bundled Natural Earth image, so it
* fetches no map tiles. It holds still, north up and framed on the route.
* @param {HTMLElement} container
* @param {{from: {code?: string, lat: number, lon: number},
* to: {code?: string, lat: number, lon: number},
* at?: {lat: number, lon: number}|null}} route
* @param {{onFailed?: () => void}} [events]
*/
function routePreview(container, route, { onFailed = () => {} } = {}) {
let widget = null;
let loop = null;
let { from, to } = route;
let plane = null;
let flownLine = null;
let aheadLine = null;
let removeGrow = null;
/** True while the plane flies in from the origin; moves wait for it. */
let flyingIn = false;
/** The craft's latest position, kept through the fly-in and the load. */
let latest = route.at;
const pose = (entity, where) => {
const next = planePose(where, bearing(where, to));
entity.position = next.position;
entity.billboard.rotation = next.rotation;
entity.billboard.alignedAxis = next.alignedAxis;
};
const draw = (atNow) => {
if (!widget) return;
const at = onRoute(from, to, atNow);
const { entities, scene } = widget;
removeGrow?.();
removeGrow = null;
entities.removeAll();
plane = flownLine = null;
const pin = (place, color) =>
entities.add({
position: Cesium.Cartesian3.fromDegrees(place.lon, place.lat),
point: {
pixelSize: 7,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
outlineWidth: 1,
},
...(place.code
? {
billboard: {
...codeImage(place.code),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -6),
},
}
: {}),
});
pin(from, CYAN.withAlpha(0.9));
pin(to, AMBER);
// Ahead of the craft, dashed; behind it, solid, drawing out on open.
aheadLine = entities.add({
polyline: {
positions: arc(at || from, to),
width: 1.5,
material: new Cesium.PolylineDashMaterialProperty({
color: AMBER.withAlpha(0.8),
dashLength: 10,
}),
arcType: Cesium.ArcType.NONE,
},
});
if (at) {
let progress = 0;
const flown = (flownLine = entities.add({
polyline: {
positions: new Cesium.CallbackProperty(
() => arc(from, at, 48, Math.max(0.02, progress)),
false,
),
width: 2.5,
material: new Cesium.PolylineGlowMaterialProperty({
color: CYAN,
glowPower: 0.25,
}),
arcType: Cesium.ArcType.NONE,
},
}));
// The plane starts at the origin and flies out along the flown line
// as it draws, arriving where the craft is now.
const first = planePose(from, bearing(from, to));
plane = entities.add({
position: first.position,
billboard: {
image: PLANE_ICON,
width: 26,
height: 26,
rotation: first.rotation,
alignedAxis: first.alignedAxis,
},
});
const leg = geodesic(from, at);
const ease = (x) => 1 - (1 - x) ** 3;
// The fly-in waits until the globe has drawn (its imagery loads a
// moment after the card opens), at most 1.5 s, so it is seen from the
// start. Under reduced motion it is there at once.
let began = reducedMotion() ? -Infinity : null;
const opened = performance.now();
flyingIn = true;
const grow = () => {
if (began === null) {
if (!scene.globe.tilesLoaded && performance.now() - opened < 1500)
return;
began = performance.now();
}
const raw = Math.min(1, (performance.now() - began) / 1600);
progress = ease(raw);
const c = leg.interpolateUsingFraction(progress);
pose(plane, {
lat: Cesium.Math.toDegrees(c.latitude),
lon: Cesium.Math.toDegrees(c.longitude),
});
if (raw >= 1) {
flyingIn = false;
flown.polyline.positions = arc(from, at, 48);
removeGrow?.();
removeGrow = null;
// The craft may have moved on while the plane flew in.
move(latest);
}
};
removeGrow = scene.preRender.addEventListener(grow);
}
// Frame the whole route, north up, looking down at a slight tilt; the
// view holds still so the plane and labels keep their bearings.
const points = [from, to, ...(at ? [at] : [])].map((p) =>
Cesium.Cartesian3.fromDegrees(p.lon, p.lat),
);
const sphere = Cesium.BoundingSphere.fromPoints(points);
const range = Math.max(1_800_000, sphere.radius * 3.2);
const center =
Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(sphere.center) ||
sphere.center;
widget.camera.lookAt(
center,
new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-62), range),
);
scene.requestRender();
};
try {
widget = createWidget(container, {
baseLayer: false,
skyAtmosphere: false,
contextOptions: { webgl: { alpha: true, antialias: true } },
});
const { scene } = widget;
scene.backgroundColor = Cesium.Color.TRANSPARENT;
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
scene.globe.showGroundAtmosphere = false;
scene.globe.enableLighting = false;
loop = renderLoopSwitch(widget);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
Cesium.TileMapServiceImageryProvider.fromUrl(
Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII'),
).then(
(imagery) => {
if (!widget) return;
const layer = widget.scene.imageryLayers.addImageryProvider(imagery);
// Dimmed and cooled, so the route reads over it.
layer.brightness = 0.55;
layer.saturation = 0.35;
layer.contrast = 1.1;
draw(latest);
},
() => widget && onFailed(),
);
function move(atNow) {
const at = onRoute(from, to, atNow);
if (!widget || !at || !plane || flyingIn) return;
pose(plane, at);
if (flownLine) flownLine.polyline.positions = arc(from, at, 48);
if (aheadLine) aheadLine.polyline.positions = arc(at, to);
widget.scene.requestRender();
}
return {
setActive: (active) => loop.set(active),
/**
* A new route redraws; the craft moving along it only moves its plane
* and the two lines, without replaying the opening draw.
*/
update(next) {
if (!widget) return;
latest = next.at;
if (next.from?.code !== from.code || next.to?.code !== to.code) {
({ from, to } = next);
draw(latest);
return;
}
move(latest);
},
destroy() {
removeGrow?.();
removeGrow = null;
const gone = widget;
widget = null;
destroyWidget(gone);
},
};
}
// ── The cockpit view ───────────────────────────────────────────────────
/** A floor for the eye, so a landed or taxiing craft is not underground. */
const MIN_EYE_M = 60;
/**
* What the crew sees: the view ahead from the aircraft's own position,
* height and heading, a little nose down, over Esri World Imagery (the
* app's keyless basemap) on a plain ellipsoid with the sky's haze. It draws
* only when asked: a still, moved along with the craft while it shows.
* @param {HTMLElement} container
* @param {{lat: number, lon: number, altitudeM?: number|null,
* heading?: number|null}} craft
* @param {{onFailed?: () => void}} [events]
*/
function cockpitPreview(container, craft, { onFailed = () => {} } = {}) {
let widget = null;
let loop = null;
let active = false;
let at = craft;
const place = () => {
if (!widget || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return;
const height = Math.max(
MIN_EYE_M,
Number.isFinite(at.altitudeM) ? at.altitudeM : 0,
);
widget.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(at.lon, at.lat, height),
orientation: {
heading: Cesium.Math.toRadians(
Number.isFinite(at.heading) ? at.heading : 0,
),
pitch: Cesium.Math.toRadians(-9),
roll: 0,
},
});
widget.scene.requestRender();
};
try {
widget = createWidget(container, {
baseLayer: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
contextOptions: { webgl: { alpha: false, antialias: true } },
});
const { scene } = widget;
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
scene.globe.showGroundAtmosphere = true;
scene.fog.enabled = true;
scene.camera.frustum.fov = Cesium.Math.toRadians(70);
// Tiles arriving ask for a frame, so the still fills in as they load.
scene.globe.tileLoadProgressEvent.addEventListener(() =>
scene.requestRender(),
);
place();
// Hidden, it draws nothing at all, not even as tiles arrive.
loop = renderLoopSwitch(widget);
loop.set(active);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
createEsriImagery().then(
(imagery) => {
if (!widget) return;
widget.scene.imageryLayers.addImageryProvider(imagery);
widget.scene.requestRender();
},
() => widget && onFailed(),
);
return {
setActive(next) {
active = Boolean(next);
if (!widget) return;
loop.set(active);
if (active) place();
},
/** While it shows, the view keeps up with the craft. */
update(next) {
at = next;
if (active) place();
},
destroy() {
const gone = widget;
widget = null;
destroyWidget(gone);
},
};
}
/**
* The card previews, as the `cardPreviews` application hook hands them.
* @type {Readonly<{model: typeof modelPreview, route: typeof routePreview,
* cockpit: typeof cockpitPreview}>}
*/
export const cesiumCardPreviews = Object.freeze({
model: modelPreview,
route: routePreview,
cockpit: cockpitPreview,
});
+38 -28
View File
@@ -413,18 +413,25 @@ function flowTime(speed) {
}
/**
* Drawn frames a line set's lines stay unchanged before the solid ones
* among them settle into a static batch (`settleLines`).
* Milliseconds a line set's lines stay unchanged before the solid ones
* among them settle into a static batch (`settleLines`), and a shape set's
* moved shapes go back into its batches (`settleShapes`). Timed, so a
* batch builds as soon at every refresh rate.
*/
export const SETTLE_FRAMES = 30;
export const SETTLE_MS = 500;
/**
* Fewer lines than this left in the collection beside a static batch wait
* `LONG_SETTLE_FRAMES` to settle, as rebuilding the batch for them costs
* `LONG_SETTLE_MS` to settle, as rebuilding the batch for them costs
* more than drawing them in the collection for a while.
*/
export const FEW_LOOSE_LINES = 64;
export const LONG_SETTLE_FRAMES = 300;
export const LONG_SETTLE_MS = 5000;
/** A line set's settling: waiting the short time, the long one, or done. */
const SETTLE_SHORT = 0;
const SETTLE_LONG = 1;
const SETTLE_DONE = 2;
/**
* Clamped fills a set draws alone at most, each where it last moved
@@ -452,12 +459,14 @@ const animating = (record) => record.gpu?.animating();
* @param {{scene: object, report: (error: unknown) => void,
* capabilities?: ReadonlySet<string>,
* requestRender?: (reason: string) => void,
* date?: () => number}} options `capabilities` gate
* date?: () => number,
* now?: () => number}} options `capabilities` gate
* the GPU icon sets' members (by default they all are); `requestRender`,
* the frame port's, asks for the frames a GPU icon set needs on its own
* (its images packed), under the reason `icons:<set id>` (by default the
* scene's, with no reason); `date`, the epoch ms a `live` motion clock
* reads (by default the system clock's).
* reads (by default the system clock's); `now`, the milliseconds settling
* waits are timed by (`performance.now` by default).
*/
export function createCesiumDraw({
scene,
@@ -465,6 +474,7 @@ export function createCesiumDraw({
capabilities = new Set(GPU_ICON_CAPABILITIES),
requestRender: requestFrame = null,
date = null,
now = () => performance.now(),
}) {
const sets = new Map();
// Fields share the sets' ids.
@@ -3107,7 +3117,8 @@ export function createCesiumDraw({
record.lineBox = settling ? own : null;
record.batch = null;
record.batchPending = null;
record.settled = 0;
record.changedAt = now();
record.settleStage = SETTLE_SHORT;
if (!draped.size && !glows.size && !alone.length && !groundPieces.length) {
noteFlows(record);
return replaceHost(record, own);
@@ -3581,7 +3592,8 @@ export function createCesiumDraw({
* still building drew them as they were, so it is dropped.
*/
function unsettle(record) {
record.settled = 0;
record.changedAt = now();
record.settleStage = SETTLE_SHORT;
const pending = record.batchPending;
if (!pending) return;
record.batchPending = null;
@@ -3736,10 +3748,10 @@ export function createCesiumDraw({
}
/**
* After a draw: a line set whose lines have not changed for
* `SETTLE_FRAMES` drawn frames starts building its static batch, of all
* its lines that `settles`, once some are still in the collection (when
* it has a batch and only a few are, after `LONG_SETTLE_FRAMES`); one
* After a draw: a line set whose lines have not changed for `SETTLE_MS`
* starts building its static batch, of all its lines that `settles`, once
* some are still in the collection (when it has a batch and only a few
* are, after `LONG_SETTLE_MS`); one
* built swaps in for the collection's lines it draws (`swapBatch`).
* Unchanged lines in a polyline collection cost a material id a line
* every frame; in a batch they cost nothing until they change.
@@ -3750,13 +3762,10 @@ export function createCesiumDraw({
swapBatch(record);
return;
}
if (record.settled > LONG_SETTLE_FRAMES) return;
record.settled += 1;
if (
record.settled !== SETTLE_FRAMES &&
record.settled !== LONG_SETTLE_FRAMES
)
return;
if (record.settleStage === SETTLE_DONE) return;
const wait =
record.settleStage === SETTLE_SHORT ? SETTLE_MS : LONG_SETTLE_MS;
if (now() - record.changedAt < wait) return;
// The lines that can settle still in the collection: a batch is
// rebuilt whole for them, so a few wait longer, as a few cost little.
let loose = 0;
@@ -3765,10 +3774,12 @@ export function createCesiumDraw({
if (
record.batch &&
loose < FEW_LOOSE_LINES &&
record.settled < LONG_SETTLE_FRAMES
)
record.settleStage === SETTLE_SHORT
) {
record.settleStage = SETTLE_LONG;
return;
record.settled = LONG_SETTLE_FRAMES + 1;
}
record.settleStage = SETTLE_DONE;
if (!loose) return;
const members = [];
for (const [itemId, part] of record.lineParts) {
@@ -5007,7 +5018,7 @@ export function createCesiumDraw({
if (part.batch.ready) showOn(part.batch, part.id, false);
}
hideRetiringShape(record, item.id);
record.shapesStill = 0;
record.shapesMovedAt = now();
part.solo = true;
part.pendingShow = undefined;
part.look = lookOf(item);
@@ -5081,7 +5092,7 @@ export function createCesiumDraw({
/**
* After a draw: a shape set whose shapes drawn alone have not moved for
* `SETTLE_FRAMES` drawn frames rebuilds, so they go back into its
* `SETTLE_MS` rebuilds, so they go back into its
* batches; the host drawing them alone draws until the rebuild is ready.
*/
function settleShapes(record) {
@@ -5093,9 +5104,8 @@ export function createCesiumDraw({
break;
}
if (!alone) return;
record.shapesStill = (record.shapesStill ?? 0) + 1;
if (record.shapesStill < SETTLE_FRAMES) return;
record.shapesStill = 0;
if (now() - record.shapesMovedAt < SETTLE_MS) return;
record.shapesMovedAt = now();
record.rebuild();
requestRender();
}
+58 -15
View File
@@ -5,10 +5,10 @@ import { bindRenderer, drawOf, findDraw } from '../rendererOf.js';
import {
createCesiumDraw,
FEW_LOOSE_LINES,
LONG_SETTLE_FRAMES,
LONG_SETTLE_MS,
MOVING_SHAPES,
revealUniform,
SETTLE_FRAMES,
SETTLE_MS,
unboundDrawPart,
} from './draw.js';
import { drawHitOf } from './drawHit.js';
@@ -93,6 +93,19 @@ test('nothing to draw into, no port', () => {
});
/** A draw port over a fake scene, with its frame hooks. */
/**
* Settling waits are timed. A test that settles times them by `frameClock`
* (`timeFrames`), which each fake frame moves on by `FRAME_MS`.
*/
const FRAME_MS = 20;
const SETTLE_FRAMES = SETTLE_MS / FRAME_MS;
const LONG_SETTLE_FRAMES = LONG_SETTLE_MS / FRAME_MS;
const frameClock = { ms: 0 };
function timeFrames(t) {
frameClock.ms = 0;
t.mock.method(performance, 'now', () => frameClock.ms);
}
function drawOver(scene = fakeScene()) {
const viewer = { scene };
const draw = drawOf(viewer);
@@ -100,6 +113,7 @@ function drawOver(scene = fakeScene()) {
scene,
draw,
frame() {
frameClock.ms += FRAME_MS;
scene.preRender.raiseEvent();
scene.postRender.raiseEvent();
},
@@ -2978,8 +2992,9 @@ function settlingSet(id = 'stems') {
};
}
test('unchanged solid 3D lines settle into a static batch, changed there in place', () =>
test('unchanged solid 3D lines settle into a static batch, changed there in place', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set, frame } = s;
const stem = settleStem;
@@ -3114,8 +3129,24 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac
set.dispose();
}));
test('many lines left beside a static batch settle as soon as they are unchanged', () =>
test('lines settle after the same time at any refresh rate', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
s.set.set([settleStem('a', 100)]);
const host = s.host();
// Two frames are enough when they are half a second apart.
frameClock.ms = SETTLE_MS - FRAME_MS - 1;
s.frame();
assert.equal(host.length, 1, 'not before the time');
s.frame();
assert.equal(host.length, 2, 'building once it has passed');
s.set.dispose();
}));
test('many lines left beside a static batch settle as soon as they are unchanged', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
const stems = (height) =>
@@ -3134,8 +3165,9 @@ test('many lines left beside a static batch settle as soon as they are unchanged
set.dispose();
}));
test('an outlined solid line draws one outline material, recoloured in place, and never settles', () =>
test('an outlined solid line draws one outline material, recoloured in place, and never settles', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const outlined = (core, halo) =>
settleStem('ring', 100, {
@@ -3177,8 +3209,9 @@ test('an outlined solid line draws one outline material, recoloured in place, an
s.set.dispose();
}));
test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', () =>
test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const style = {
kind: 'solid',
@@ -3232,8 +3265,9 @@ test('a line that moves by as many points is written into the points it draws; b
s.set.dispose();
}));
test('a line under half a pixel wide, which the collection does not draw, never settles', () =>
test('a line under half a pixel wide, which the collection does not draw, never settles', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
s.set.set([
settleStem('thin', 100, { widthPx: 0.25 }),
@@ -3248,8 +3282,9 @@ test('a line under half a pixel wide, which the collection does not draw, never
s.set.dispose();
}));
test('a settling line set keeps what was drawn, not the item a caller changes in place', () =>
test('a settling line set keeps what was drawn, not the item a caller changes in place', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
const a = settleStem('a', 100);
@@ -3276,8 +3311,9 @@ test('a settling line set keeps what was drawn, not the item a caller changes in
set.dispose();
}));
test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', () =>
test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', (t) =>
withImageClasses(() => {
timeFrames(t);
const s = settlingSet();
const { set } = s;
set.set([settleStem('a', 100), settleStem('b', 200)]);
@@ -3308,17 +3344,22 @@ test('a settling line set rebuilt or gone while its batch builds, or after the v
set.dispose();
}));
test('a static batch that fails to build is reported once, and its lines stay in the collection', () =>
test('a static batch that fails to build is reported once, and its lines stay in the collection', (t) =>
withImageClasses(() => {
timeFrames(t);
const scene = fakeScene();
const reported = [];
const part = createCesiumDraw({
scene,
report: (error) => reported.push(error),
});
const afterFrame = () => {
frameClock.ms += FRAME_MS;
part.afterRender();
};
const set = part.port.lines({ id: 'failing' });
set.set([settleStem('a', 100)]);
for (let i = 0; i < SETTLE_FRAMES; i++) part.afterRender();
for (let i = 0; i < SETTLE_FRAMES; i++) afterFrame();
const host = scene.added[0];
const batch = host.get(1);
assert.ok(batch, 'building');
@@ -3326,11 +3367,11 @@ test('a static batch that fails to build is reported once, and its lines stay in
// batch keeps the error rather than throw it every frame.
batch.update({ passes: { render: true }, mode: Cesium.SceneMode.SCENE3D });
assert.ok(batch.failed, 'kept');
part.afterRender();
afterFrame();
assert.deepEqual(reported, [batch.failed]);
assert.equal(host.length, 1, 'the build is gone');
assert.equal(host.get(0).length, 1, 'the collection draws the line');
for (let i = 0; i < SETTLE_FRAMES * 2; i++) part.afterRender();
for (let i = 0; i < SETTLE_FRAMES * 2; i++) afterFrame();
assert.equal(host.length, 1, 'it settles no more');
assert.equal(reported.length, 1);
set.dispose();
@@ -7482,8 +7523,9 @@ test('an inertial line with a depth-fail style draws behind the surface too, tur
set.dispose();
}));
test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', () =>
test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', (t) =>
withImageClasses(() => {
timeFrames(t);
const { scene, draw, frame } = drawOver();
const set = draw.lines({ id: 'orbit-rings' });
const ring = [
@@ -7777,8 +7819,9 @@ const firstGround = (host) => {
return null;
};
test('moved clamped fills go back into a rebuilt batch once they have been still for a while', () =>
test('moved clamped fills go back into a rebuilt batch once they have been still for a while', (t) =>
withTerrainHeights(() => {
timeFrames(t);
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'settling' });
set.set([groundBox('a', 1), groundBox('b', 2)]);
+7
View File
@@ -161,6 +161,8 @@ export function createSceneFrame(viewer) {
liveTick = null;
};
const holds = new Map();
// Told when the first hold is taken and the last released.
const heldListeners = listenerList(uncaught);
const pendingRenders = new Set();
const gone = () => disposed || scene.isDestroyed?.();
const sceneTime = (time) =>
@@ -244,8 +246,10 @@ export function createSceneFrame(viewer) {
},
holdContinuous(reason) {
if (disposed) return () => {};
const first = holds.size === 0;
holds.set(reason, (holds.get(reason) ?? 0) + 1);
if (!gone()) scene.requestRender();
if (first) heldListeners.fire(true);
let released = false;
return () => {
if (released) return;
@@ -255,8 +259,10 @@ export function createSceneFrame(viewer) {
else holds.delete(reason);
// What changed in the last held frame still gets drawn.
if (!gone()) scene.requestRender();
if (holds.size === 0) heldListeners.fire(false);
};
},
onHeldChange: (cb) => heldListeners.on(cb),
mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'),
diagnostics: () => ({
mode: port.mode(),
@@ -324,6 +330,7 @@ export function createSceneFrame(viewer) {
settleTick(false);
for (const off of removers.splice(0)) off();
for (const list of Object.values(listeners)) list.clear();
heldListeners.clear();
holds.clear();
// Waits settle rather than stay attached to a scene gone quiet.
for (const done of [...pendingRenders]) done();
+17
View File
@@ -190,6 +190,23 @@ test('a built frame port counts holds per reason, times out a wait, and settles
unbind();
});
test('a built frame port says when its first hold is taken and its last released', () => {
const viewer = fakeViewer();
viewer.useDefaultRenderLoop = false;
const frame = frameOf(viewer);
const heard = [];
const off = frame.onHeldChange((held) => heard.push(held));
const a = frame.holdContinuous('spin');
const b = frame.holdContinuous('glow');
a();
assert.deepEqual(heard, [true], 'once for the first hold');
b();
assert.deepEqual(heard, [true, false], 'once for the last release');
off();
frame.holdContinuous('spin')();
assert.deepEqual(heard, [true, false], 'nothing once off');
});
test('renderNow throws the error Cesium raises on renderError', () => {
const listeners = new Set();
const failure = new Error('worker failed');
+92 -12
View File
@@ -59,7 +59,15 @@ async function terrainProvider(spec, { worldDataToken }) {
throw new TypeError('Quantized-mesh terrain needs its url');
// Busy hosts are asked again as the keyless terrain is
// (`terrainRetry.js`); every tile's resource inherits the policy.
const policy = createTerrainRetryPolicy();
const policy = createTerrainRetryPolicy({
// One line per cooldown window, not per tile: a burst throttles dozens.
onThrottle: ({ statusCode, delayMs, inWindow }) => {
if (inWindow === 1)
console.warn(
`[MapStack] terrain answered ${statusCode}; retrying throttled tiles after ${Math.round(delayMs)} ms`,
);
},
});
const resource = new Cesium.Resource({
url: spec.url,
retryCallback: policy.retryCallback,
@@ -104,6 +112,19 @@ czm_material czm_getMaterial(czm_materialInput materialInput)
/** The last `surfaceVersion` any globe port handed out. */
let surfaceVersions = 0;
/** Each scene's photoreal tileset as a globe port holds it, shown or hidden. */
const photorealTilesets = new WeakMap();
/**
* The Cesium photoreal tileset a globe port over `scene` holds: shown, or
* hidden and kept to show again; null when it holds none. For QA scripts.
* @param {object} scene
* @returns {object | null}
*/
export function cesiumPhotorealOf(scene) {
return photorealTilesets.get(scene)?.() ?? null;
}
/**
* @param {object} widget A Cesium `CesiumWidget` or `Viewer`.
* @param {{capabilities: ReadonlySet<string>,
@@ -111,7 +132,8 @@ let surfaceVersions = 0;
* report?: (error: unknown) => void,
* credits?: import('../contract/credits').CreditsPort | null,
* credentials?: {googleApiKey?: string, googleTokens?: () => Promise<string>,
* worldDataToken?: string}}} options
* worldDataToken?: string},
* loadPhotoreal?: typeof loadPhotorealisticTileset}} options
* @returns {{port: import('../contract/globe').GlobePort, dispose: () => void}}
*/
export function createCesiumGlobe(
@@ -122,6 +144,8 @@ export function createCesiumGlobe(
report = uncaught,
credits = null,
credentials = {},
// Tests load their own.
loadPhotoreal = loadPhotorealisticTileset,
},
) {
const scene = widget.scene;
@@ -130,9 +154,17 @@ export function createCesiumGlobe(
// --- Base ------------------------------------------------------------------
/** The photoreal tileset this port loaded, if any. */
/** The photoreal tileset this port loaded, if any, and its spec. */
let photoreal = null;
let photorealSpec = null;
let photorealStatus = { route: 'none' };
/**
* The photoreal tileset last turned off, kept hidden with the spec and
* status it loaded with: that same spec shows it again at once, without
* loading it anew (Google counts each load).
*/
let parked = null;
photorealTilesets.set(scene, () => photoreal ?? parked?.tileset ?? null);
let photorealGen = 0;
let terrainGen = 0;
let baseGen = 0;
@@ -178,31 +210,74 @@ export function createCesiumGlobe(
worldDataToken: () => credentials.worldDataToken,
});
function removePhotoreal() {
if (!photoreal) return;
const tileset = photoreal;
photoreal = null;
// The layers draped on it move off before it takes them with it.
imagery.sync();
function destroyTileset(tileset) {
if (!tileset.isDestroyed() && !scene.primitives.remove(tileset))
tileset.destroy();
}
function removePhotoreal() {
if (!photoreal) return;
const tileset = photoreal;
photoreal = null;
photorealSpec = null;
// The layers draped on it move off before it takes them with it.
imagery.sync();
destroyTileset(tileset);
}
/** Hide the photoreal tileset, kept for its spec to show again. */
function parkPhotoreal() {
if (!photoreal) return;
if (parked) destroyTileset(parked.tileset);
parked = {
spec: photorealSpec,
status: photorealStatus,
tileset: photoreal,
};
photoreal.show = false;
photoreal = null;
photorealSpec = null;
imagery.sync();
}
/** Show the parked tileset again when `spec` is the one it loaded with. */
function unparkPhotoreal(spec) {
const kept = parked;
if (!kept || kept.spec !== spec || kept.tileset.isDestroyed()) return null;
parked = null;
removePhotoreal();
photoreal = kept.tileset;
photorealSpec = spec;
photoreal.show = true;
photorealStatus = kept.status;
imagery.sync();
requestRender('base');
return photorealStatus;
}
async function setPhotoreal(spec) {
const gen = ++photorealGen;
removePhotoreal();
photorealStatus = { route: 'none' };
if (!spec || !can('photoreal')) {
if (spec) removePhotoreal();
else parkPhotoreal();
photorealStatus = { route: 'none' };
requestRender('base');
return photorealStatus;
}
const shown = unparkPhotoreal(spec);
if (shown) return shown;
removePhotoreal();
if (parked) {
destroyTileset(parked.tileset);
parked = null;
}
photorealStatus = { route: 'none' };
// The spec's own route first: its key, else its tokens, else the
// renderer's credentials.
const googleApiKey =
spec.key ?? (spec.token ? '' : (credentials.googleApiKey ?? ''));
const token = spec.token ?? credentials.googleTokens;
const result = await loadPhotorealisticTileset(Cesium, {
const result = await loadPhotoreal(Cesium, {
googleApiKey,
// A renewal names the token it replaces.
googleTokens: token ? { token: (options) => token(options) } : null,
@@ -224,6 +299,7 @@ export function createCesiumGlobe(
};
} else {
photoreal = scene.primitives.add(result.tileset);
photorealSpec = spec;
photorealStatus = { route: ROUTES[result.route] ?? 'google' };
}
imagery.sync();
@@ -616,6 +692,10 @@ export function createCesiumGlobe(
if (disposed) return;
disposed = true;
photorealGen += 1;
if (parked) {
destroyTileset(parked.tileset);
parked = null;
}
terrainGen += 1;
baseGen += 1;
baseLoad?.abort();
+45 -1
View File
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createCesiumGlobe, markBaseTileset } from './globe.js';
import {
cesiumPhotorealOf,
createCesiumGlobe,
markBaseTileset,
} from './globe.js';
import { hookProvider, TILE_RETRY_DELAY_MS, xyzTileUrl } from './imagery.js';
const ALL = new Set([
@@ -805,3 +809,43 @@ test('hillshade shading owns a free globe material, follows the terrain, gives i
assert.equal(scene.globe.material, theirs);
dispose();
});
test('photoreal turned off is kept hidden, and the same spec shows it without loading it again', async () => {
const scene = fakeScene();
const loads = [];
const { port } = createCesiumGlobe(
{ scene },
{
capabilities: new Set(['photoreal']),
requestRender: () => {},
credentials: { worldDataToken: 'ion' },
loadPhotoreal: async (_sdk, credentials) => {
loads.push(credentials);
return { tileset: fakeTileset(), route: 'direct', errors: [] };
},
},
);
const spec = { provider: 'google', key: 'key', fallback: true };
assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' });
assert.equal(loads.length, 1);
assert.equal(loads[0].googleApiKey, 'key');
assert.equal(loads[0].cesiumToken, 'ion');
const first = cesiumPhotorealOf(scene);
assert.equal(first.show, true);
assert.deepEqual(await port.setPhotoreal(null), { route: 'none' });
assert.equal(first.isDestroyed(), false, 'kept');
assert.equal(first.show, false, 'hidden');
assert.equal(cesiumPhotorealOf(scene), first, 'QA scripts still read it');
assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' });
assert.equal(loads.length, 1, 'not loaded again');
assert.equal(cesiumPhotorealOf(scene), first);
assert.equal(first.show, true);
await port.setPhotoreal(null);
await port.setPhotoreal({ provider: 'google', key: 'other' });
assert.equal(loads.length, 2, 'another spec loads its own');
assert.equal(first.isDestroyed(), true, 'the kept one goes');
assert.notEqual(cesiumPhotorealOf(scene), first);
});
+3 -2
View File
@@ -59,10 +59,11 @@ export async function loadPhotorealisticTileset(
export function createGoogleDirectTileset(Cesium, key) {
key = clean(key);
if (!key) throw new Error('Google 3D requires an explicit browser key');
// Tiles keep drawing their own texture while draped weather loads.
// Tiles keep drawing their own texture while draped weather loads, and
// clamped marks land on them, as on the token routes' tiles.
return Cesium.createGooglePhotorealistic3DTileset(
{ key, onlyUsingWithGoogleGeocoder: true },
{ asynchronouslyLoadImagery: true },
{ asynchronouslyLoadImagery: true, enableCollision: true },
);
}
+1
View File
@@ -149,6 +149,7 @@ export const CESIUM_CHECKS = new Set([
'renderer.releaseUnused',
'renderer.whenSettled',
'renderer.resize',
'frame.onHeldChange',
'frame.setTargetFps',
'globe.setTerrain',
'globe.setPhotoreal',
+5 -2
View File
@@ -32,6 +32,7 @@ import {
videoProvider,
} from './imageryFrames.js';
import { withTileRequestHook } from './tileRequests.js';
import { createIonImagery } from './mapImagery.js';
const SPLITS = { none: 'NONE', left: 'LEFT', right: 'RIGHT' };
const DRAPES = new Set(['surface', 'objects', 'all']);
@@ -157,9 +158,11 @@ export function providerFor(spec, { worldDataToken } = {}) {
throw new TypeError(
'World imagery needs the renderer’s world data token',
);
return Cesium.IonImageryProvider.fromAssetId(
// Bing through ion, its tiles over HTTPS on any page, with ion's
// credits, as the map stacks have always drawn it.
return createIonImagery(
WORLD_ASSETS[spec.worldStyle ?? 'aerial'] ?? WORLD_ASSETS.aerial,
{ accessToken },
accessToken,
);
}
// The app's own: the vector base's tiles, painted from its style.
+2 -2
View File
@@ -4,6 +4,7 @@
* World Imagery and Cesium ion's world imagery (Bing over HTTPS).
*/
import * as Cesium from 'cesium';
import { ESRI_IMAGERY_CREDIT } from '../../maps/attribution.js';
export { ESRI_ATTRIBUTION_HTML } from '../../maps/attribution.js';
@@ -18,8 +19,7 @@ export function createEsriImagery() {
return Cesium.ArcGisMapServerImageryProvider.fromUrl(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
{
credit:
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community',
credit: ESRI_IMAGERY_CREDIT,
enablePickFeatures: false,
},
);
+1 -1
View File
@@ -329,7 +329,7 @@ test('both Google 3D routes keep tiles drawing while draped imagery loads', asyn
assert.equal(await createGoogleIonTileset(sdk, 'token'), 'ion');
assert.deepEqual(calls[0], [
{ key: 'key', onlyUsingWithGoogleGeocoder: true },
{ asynchronouslyLoadImagery: true },
{ asynchronouslyLoadImagery: true, enableCollision: true },
]);
assert.equal(calls[1][0].id, 2275207);
assert.equal(calls[1][0].accessToken, 'token');
+31 -23
View File
@@ -116,22 +116,18 @@ const destroyedError = () => new Error('renderer destroyed');
* @param {{capabilities: ReadonlySet<string>, credentials?: object,
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number,
* date?: () => number,
* idleFps?: number}} options
* date?: () => number}} options
* The renderer's capabilities, which gate the members that need them, and
* the credentials its globe loads photoreal tiles and world data with
* (`googleApiKey`, `googleTokens`, `worldDataToken`). `now` is the clock
* each tick reads (`performance.now` by default; a test's virtual one);
* `date`, the epoch ms a `live` motion clock reads (the system clock's by
* default). With `idleFps`, the loop ticks at most that often while no
* hold is out (Cesium ticks its clock and every update listener each
* animation frame even when it draws nothing), and at the display's rate
* while one is; `setTargetFps` then caps both, and the loop starts with no
* cap of its own. Without it, the widget's own rate is the cap.
* With
* `cameraController`, the camera port is that controller's over Cesium's
* camera (`controlledCamera.js`); the ports then have `attachInput` and
* `suspendCamera`, which the renderer's input port is wired with.
* default). The loop's rate starts as the widget's own; once set, it is
* the lower of `setTargetFps`'s and the quality port's `targetFps` cap.
* With `cameraController`, the camera port is that controller's over
* Cesium's camera (`controlledCamera.js`); the ports then have
* `attachInput` and `suspendCamera`, which the renderer's input port is
* wired with.
*/
export function createCesiumPorts(
widget,
@@ -141,7 +137,6 @@ export function createCesiumPorts(
cameraController,
now: clockNow = () => performance.now(),
date = null,
idleFps = 0,
},
) {
const scene = widget.scene;
@@ -290,27 +285,30 @@ export function createCesiumPorts(
// Holds keep the loop drawing every frame; counted per reason.
const holds = new Map();
// Told when the first hold is taken and the last released.
const heldListeners = listenerList(report);
function applyHolds() {
const continuous = holds.size > 0;
if (idleFps > 0) applyRate();
if (scene.requestRenderMode === !continuous) return;
scene.requestRenderMode = !continuous;
}
/** The loop's rate: the cap, and at most `idleFps` while nothing holds. */
function applyRate() {
const idle = holds.size === 0 && idleFps > 0;
const rate =
idle && !(targetFps > 0 && targetFps < idleFps) ? idleFps : targetFps;
widget.targetFrameRate = rate || undefined;
heldListeners.fire(continuous);
}
// On demand means drawn when asked, held or the view changed: never
// because scene time moved on by itself. With no holds yet, it starts so.
scene.maximumRenderTimeChange = Infinity;
scene.requestRenderMode = true;
let suspended = false;
let targetFps =
idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
if (idleFps > 0) applyRate();
// The rate `setTargetFps` asks for (the application's), and the quality
// port's cap; the loop draws at the lower of those set.
let targetFps = widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
let qualityFps = 0;
function applyRate() {
const rate =
targetFps > 0 && qualityFps > 0
? Math.min(targetFps, qualityFps)
: targetFps || qualityFps;
widget.targetFrameRate = rate || undefined;
}
// Pending one-shot renders; disposal rejects them rather than leave them
// attached to a scene that will not render again.
@@ -369,6 +367,7 @@ export function createCesiumPorts(
if (holds.size === 0) scene.requestRender();
};
},
onHeldChange: (cb) => heldListeners.on(cb),
/** Cesium can idle, so it draws on demand. */
mode: () => 'demand',
diagnostics: () => ({
@@ -429,6 +428,7 @@ export function createCesiumPorts(
capabilities,
requestRender: (reason) => frame.requestRender(reason),
date,
now: clockNow,
});
const { port: draw, sets, tilesets } = drawPart;
@@ -494,6 +494,13 @@ export function createCesiumPorts(
report,
tickStarted: () => tickNow,
gl: capabilities.has('gpuTiming') ? webglContext(scene) : null,
fpsCap: {
get: () => qualityFps,
set(fps) {
qualityFps = fps > 0 ? fps : 0;
applyRate();
},
},
});
const creditsPart = createCesiumCredits({
@@ -837,6 +844,7 @@ export function createCesiumPorts(
// A listener that disposes the renderer stops the rest of its event.
for (const list of Object.values(rendererListeners)) list.clear();
for (const list of Object.values(frameListeners)) list.clear();
heldListeners.clear();
drawPart.dispose();
cameraPart.dispose();
creditsPart.dispose();
+32 -18
View File
@@ -507,26 +507,40 @@ test('suspend stops the loop at once and resumes it; target fps caps it', () =>
ports.dispose();
});
test('with an idle rate, idle ticks at it and anything held draws at the display rate', () => {
test('the quality cap and the rate setTargetFps asks for draw at the lower, and neither overwrites the other', () => {
const { widget } = tickingWidget();
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.quality.get().targetFps, 0, 'no cap by default');
ports.quality.set({ targetFps: 30 });
ports.frame.setTargetFps(60);
assert.equal(widget.targetFrameRate, 30, 'the cap is lower');
ports.frame.setTargetFps(0);
assert.equal(widget.targetFrameRate, 30, 'the cap holds at the display rate');
assert.equal(ports.quality.get().targetFps, 30, 'the cap reads back');
ports.frame.setTargetFps(24);
assert.equal(widget.targetFrameRate, 24, 'the asked rate is lower');
ports.quality.set({ targetFps: 0 });
assert.equal(widget.targetFrameRate, 24, 'cap lifted');
ports.dispose();
});
test('the loop says when its first hold is taken and its last released, and leaves its rate alone', () => {
const { widget } = tickingWidget();
widget.targetFrameRate = 60;
const ports = createCesiumPorts(widget, { capabilities: all, idleFps: 60 });
assert.equal(widget.targetFrameRate, 60, 'idle: the idle rate');
assert.equal(ports.frame.diagnostics().targetFps, 0, 'no cap of its own');
const release = ports.frame.holdContinuous('flights');
assert.equal(widget.targetFrameRate, undefined, 'held: the display rate');
release();
assert.equal(widget.targetFrameRate, 60);
// A cap holds while held, and idle ticks at the lower of the two.
ports.frame.setTargetFps(30);
assert.equal(widget.targetFrameRate, 30);
const again = ports.frame.holdContinuous('flights');
assert.equal(widget.targetFrameRate, 30);
ports.frame.setTargetFps(120);
assert.equal(widget.targetFrameRate, 120);
again();
assert.equal(widget.targetFrameRate, 60);
assert.equal(ports.frame.diagnostics().targetFps, 120);
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.frame.diagnostics().targetFps, 60, 'the widget’s cap');
const heard = [];
const off = ports.frame.onHeldChange((held) => heard.push(held));
const flights = ports.frame.holdContinuous('flights');
const effects = ports.frame.holdContinuous('effects:animated');
flights();
assert.deepEqual(heard, [true], 'once for the first hold');
effects();
assert.deepEqual(heard, [true, false], 'once for the last release');
assert.equal(widget.targetFrameRate, 60, 'its rate is its caller’s');
off();
ports.frame.holdContinuous('flights')();
assert.deepEqual(heard, [true, false], 'heard no more once off');
ports.dispose();
});
+11 -4
View File
@@ -15,7 +15,10 @@
* at 0. While tile detail is lowered, a tileset added later is brought
* to it on the next drawn frame; an error is written only when it
* changes, since each write resets the tileset's memory-adjusted error.
* - `targetFps`: the frame port's target frame rate, 0 for none.
* - `targetFps`: a cap on the loop's frame rate, 0 for none (`fpsCap`: by
* default the frame port's own `setTargetFps`; the renderer's ports keep
* it apart from the rate the application sets there, and draw at the
* lower of the two).
*
* Building the port changes nothing in the scene; each setting is applied
* when it is first set, and a detail set back to 1 hands each tileset and
@@ -156,6 +159,10 @@ export function createCesiumQuality(
limits = Cesium.ContextLimits,
tickStarted = null,
gl = webglContext(widget.scene),
fpsCap = {
get: () => frame.diagnostics?.().targetFps ?? 0,
set: (fps) => frame.setTargetFps(fps),
},
},
) {
const scene = widget.scene;
@@ -171,7 +178,7 @@ export function createCesiumQuality(
: [];
// What the scene had before the port first changed it: the defaults.
const builtFps = frame.diagnostics?.().targetFps ?? 0;
const builtFps = fpsCap.get();
let msaaAtBuild = null;
let shadowsAtBuild = null;
// Cesium clamps the count to the context's only when it is set.
@@ -334,7 +341,7 @@ export function createCesiumQuality(
},
targetFps(value) {
const fps = inRange(value, 0, MAX_FPS);
if (fps !== null) frame.setTargetFps(fps);
if (fps !== null) fpsCap.set(fps);
},
};
@@ -343,7 +350,7 @@ export function createCesiumQuality(
pixelRatio,
tiles3dDetail: detail.tiles,
terrainDetail: detail.terrain,
targetFps: frame.diagnostics?.().targetFps ?? 0,
targetFps: fpsCap.get(),
};
if (scene.shadowMap) settings.shadows = Boolean(scene.shadowMap.enabled);
if (msaaOptions().length > 1)