The renderer seam: clicks go to the newest tool, recession and display groups through the contract, drawing at parity with Cesium

- Clicks: when two tools want the globe's clicks, the newest takes them and the older is told and turns itself off; a click is decided when it arrives, and ambient selection fires only when no tool holds the pointer. The "map is busy" paths and their strings are removed.
- Recession: the limb fade is shared (src/render/recession.js) and reaches icon and model sets through SetSpec.recede; tuning applies on the next frame.
- Display panel groups are published through src/ui/displayGroups.js; the Weather group and src/viewWeather.js are removed.
- Draw port: a set whose icons only move is moved in place, and models that did not change are not restyled each frame, so moving fleets cost what they did when drawn directly; an untinted, fully opaque model is drawn without a colour.
- Conformance: input.lease.lost checks the new lease inside onLost and reports a throwing onLost; draw.sets.recede covers model sets.
- QA scripts read the renderer host instead of internals the seam replaced.
This commit is contained in:
Sameh Khamis committed 2026-11-15 17:03:09 -08:00
1 parent a0d299523d
commit 0ab31d4fb8
130 files changed
+5438 -1674

No files matched your search

+20 -1
View File
@@ -23,6 +23,7 @@
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
* engine type crosses the contract.
*/
import * as Cesium from 'cesium';
import { createApplicationViewer } from './applicationViewer.js';
import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js';
@@ -80,7 +81,13 @@ export function createCesiumRendererPlugin({
id: 'cesium',
/**
* The credentials are the globe port's, for a base set through it; the
* scene still loads the application's own base itself.
* scene still loads the application's own base itself. `msaa` makes
* the viewer (4 when not given);
* `sky` and `time` are set before the first frame; `clock.now` is what
* the frame ticks, the camera's `moveEnd` wait, input and flights (the
* scene's tweens step on it) read, `clock.date` what a `live` motion
* clock reads. Inertia keeps Cesium's own timing: its camera controls
* time a release by the system clock.
* @param {import('../contract/renderer').CreateOptions} options
* @returns {Promise<TransitionalRenderer>}
*/
@@ -90,6 +97,10 @@ export function createCesiumRendererPlugin({
googleApiKey,
googleTokens,
worldDataToken,
msaa,
sky,
time,
clock,
}) {
signal?.throwIfAborted();
// Provider attribution stays visible, including clean-view and recording.
@@ -109,7 +120,11 @@ export function createCesiumRendererPlugin({
// The application's notice (`renderFailureNotice`) replaces
// Cesium's dead-end panel when rendering stops.
showRenderLoopErrors: false,
msaa,
});
if (Number.isFinite(time))
viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date(time));
const now = clock ? () => clock.now() : undefined;
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
ports = createCesiumPorts(viewer, {
capabilities,
@@ -117,6 +132,7 @@ export function createCesiumRendererPlugin({
idleFps: IDLE_FRAME_RATE,
credentials: { googleApiKey, googleTokens, worldDataToken },
...(cameraController ? { cameraController } : {}),
...(clock ? { now, date: () => clock.date() } : {}),
});
input = createCesiumInput(viewer, {
query: ports.query,
@@ -124,7 +140,10 @@ export function createCesiumRendererPlugin({
...(ports.suspendCamera
? { suspendCamera: ports.suspendCamera }
: {}),
...(clock ? { now } : {}),
});
// Before the first frame, so nothing draws in the wrong sky.
if (sky) ports.globe.sky.set(sky);
ports.attachInput?.(input.port);
// Free look is limited to low heights from the start, on Cesium's
// own controls (the controller keeps its own limits).
+62 -3
View File
@@ -193,7 +193,7 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a
renderer.destroy();
});
test('work pending at destroy settles and lets go of the scene', async (t) => {
test('work pending at destroy is rejected and lets go of the scene', async (t) => {
withDocument(t, fakeDocument());
const viewers = [];
const plugin = createCesiumRendererPlugin({
@@ -207,9 +207,10 @@ test('work pending at destroy settles and lets go of the scene', async (t) => {
const renderer = await plugin.create({ container: {} });
const rendered = renderer.frame.renderOnce();
renderer.destroy();
await rendered;
await assert.rejects(rendered, /renderer destroyed/, 'the one waiting');
assert.equal(viewers[0].listeners.size, 0, 'no one-shot render stays');
await renderer.frame.renderOnce();
await assert.rejects(renderer.frame.renderOnce(), /renderer destroyed/);
await assert.rejects(renderer.capture(), /renderer destroyed/);
const waiting = await plugin.create({ container: {} });
const standing = viewers[1].listeners.size;
@@ -325,3 +326,61 @@ test('only renderers this plugin made reach a Cesium viewer', () => {
});
const EXPECTED_MISSING = [];
test('the plugin makes its viewer with the creation options, and sets the sky, time and clock before the first frame', async (t) => {
const doc = fakeDocument();
withDocument(t, doc);
const log = [];
let given;
let viewer;
const plugin = createCesiumRendererPlugin({
createViewer(options) {
given = options;
viewer = fakeViewer(log);
for (const phase of [
'preUpdate',
'postUpdate',
'preRender',
'postRender',
])
viewer.scene[phase] = new Cesium.Event();
viewer.scene.skyAtmosphere = { show: true };
viewer.scene.fog = { enabled: true };
viewer.clock = { currentTime: Cesium.JulianDate.now() };
return viewer;
},
});
const time = Date.UTC(2030, 5, 21, 12);
const clock = { now: () => 1234.5, date: () => time + 60_000 };
const renderer = await plugin.create({
container: { tag: 'container' },
signal: new AbortController().signal,
msaa: 2,
sky: { atmosphere: false, fog: false },
time,
clock,
});
assert.equal(given.msaa, 2, 'multisampling');
assert.equal(viewer.scene.skyAtmosphere.show, false, 'the sky, set');
assert.equal(viewer.scene.fog.enabled, false);
assert.equal(renderer.globe.sky.get().fog, false);
assert.equal(
Cesium.JulianDate.toDate(viewer.clock.currentTime).getTime(),
time,
'the scene time',
);
const ticks = [];
renderer.frame.on('preUpdate', (tick) => ticks.push(tick.now));
viewer.scene.preUpdate.raiseEvent(viewer.scene, viewer.clock.currentTime);
assert.deepEqual(ticks, [1234.5], 'ticks read the clock given');
renderer.destroy();
// Not given, the viewer is made as it always was.
await plugin
.create({
container: { tag: 'container' },
signal: new AbortController().signal,
})
.then((r) => r.destroy());
assert.equal(given.msaa, undefined);
});
+15 -5
View File
@@ -54,11 +54,13 @@ if (typeof window !== 'undefined' && !window.__CESIUM__)
/**
* Cesium.Viewer options of the standard globe viewer. `showRenderLoopErrors`
* false leaves render errors to the caller's own notice instead of Cesium's
* panel.
* panel; `msaa` is the multisampling to start with (0 off, 4 by default).
* The drawing buffer is kept after presenting, for `capture` and
* `readPixels` to read the frame drawn.
*/
export function applicationViewerOptions(
creditContainer,
{ showRenderLoopErrors = true } = {},
{ showRenderLoopErrors = true, msaa = 4 } = {},
) {
return {
timeline: false,
@@ -77,23 +79,31 @@ export function applicationViewerOptions(
// which would also stop CesiumWidget from creating the Sun and Moon.
skyBox: new StarrySky(),
creditContainer,
msaaSamples: 4,
// Cesium's 1 is no multisampling.
msaaSamples: msaa || 1,
contextOptions: { webgl: { preserveDrawingBuffer: true } },
showRenderLoopErrors,
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
/**
* Create the standard globe viewer in caller-owned, visible containers;
* `msaa` as `applicationViewerOptions` takes it.
*/
export function createApplicationViewer({
container,
creditContainer,
showRenderLoopErrors,
msaa,
}) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
applicationViewerOptions(creditContainer, {
showRenderLoopErrors,
msaa,
}),
);
try {
// Until the frame port takes over (appRenderer.js), tick at the idle
@@ -74,3 +74,15 @@ test('flat maps keep zooming out unlimited', () => {
viewer.scene.preRender.raiseEvent();
assert.equal(controller.maximumZoomDistance, Infinity);
});
test('the viewer options take multisampling, by default 4, and keep the drawing buffer', async () => {
const { applicationViewerOptions } = await import('./applicationViewer.js');
const credits = {};
const plain = applicationViewerOptions(credits);
assert.equal(plain.msaaSamples, 4);
assert.equal(plain.contextOptions.webgl.preserveDrawingBuffer, true);
const given = applicationViewerOptions(credits, { msaa: 0 });
assert.equal(given.msaaSamples, 1, 'Cesium’s 1 is off');
assert.equal(given.contextOptions.webgl.preserveDrawingBuffer, true);
assert.equal(applicationViewerOptions(credits, { msaa: 8 }).msaaSamples, 8);
});
+130 -44
View File
@@ -79,20 +79,31 @@ function matrixArray(matrix) {
return out;
}
/** Whether `array` holds a Cesium matrix's 16 values, each the same. */
function sameMatrix(array, matrix) {
for (let i = 0; i < 16; i++)
if (!Object.is(array[i], matrix[i])) return false;
return true;
}
/**
* @param {{scene: object, camera: object, report: (error: unknown) => void,
* widget?: object, capabilities?: ReadonlySet<string>,
* now?: () => number, itemPosition?: Function}} options `scene`
* gives `requestRender` and the `postUpdate` tick `changed` is measured
* on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
* gives `requestRender`, the `preUpdate` a frame drawn without the
* clock's tick measures `changed` at, and the `postUpdate` move detection
* runs on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
* `follow` runs on (without it the camera cannot follow);
* `capabilities`, the renderer's, gates the optional members (a camera
* with none given has them all); `now`, the clock moveEnd waits by,
* ms (`performance.now` by default); `itemPosition`, where the draw port
* draws an item at a scene time, which a follow of a drawn item tracks.
* @returns {{port: import('../contract/camera').CameraPort,
* emit: (event: string) => void, dispose: () => void}} `emit` raises
* one of the port's events (a test's fake camera that raises its own).
* measureChanged: () => void, emit: (event: string) => void,
* dispose: () => void}} `measureChanged` measures this frame's `changed`
* if nothing has yet, for a frame loop to run before its own `preUpdate`
* listeners; `emit` raises one of the port's events (a test's fake camera
* that raises its own).
*/
export function createCesiumCamera({
scene,
@@ -105,42 +116,92 @@ export function createCesiumCamera({
}) {
const removers = [];
let lastWorld = null;
let lastMatrices = null;
let lastFollowFrame = null;
// Camera events, measured on every tick: moveStart and moveEnd (500 ms
// after the last change of the eye or its field of view, by `now`,
// following or not, as Cesium's own), and `changed` per listener, where Cesium measures its
// single threshold (`camera.percentageChanged`, which this leaves as it
// is for everyone else listening to Cesium's own event). Cesium's own
// moveStart and moveEnd are left out: it times them by the system clock.
// What the events read Cesium's camera through while it stands: the
// camera's own vectors, compared in place.
const eye = { position: null, direction: null, up: null };
const cameraEvents = createCameraEvents({
pose: () => cameraPort.pose(),
// The memoised pose itself: the events only read it.
pose: () => sharedPose(),
world: () => {
// Copies (Cesium updates its own vectors in place), and the last one
// again while Cesium's stand within rounding of it.
// The last view again while Cesium's vectors stand within rounding of
// it; copies once they move (Cesium updates its own in place).
const f = camera.frustum;
const current = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction: Cesium.Cartesian3.clone(camera.directionWC),
up: Cesium.Cartesian3.clone(camera.upWC),
eye.position = camera.positionWC;
eye.direction = camera.directionWC;
eye.up = camera.upWC;
if (
lastWorld &&
// A new field of view or aspect (a resize) is a move too, as
// Cesium's own camera events count it.
Object.is(lastWorld.fovy, f.fovy) &&
Object.is(lastWorld.aspectRatio, f.aspectRatio) &&
sameEye(eye, lastWorld)
)
return lastWorld;
lastWorld = {
position: Cesium.Cartesian3.clone(eye.position),
direction: Cesium.Cartesian3.clone(eye.direction),
up: Cesium.Cartesian3.clone(eye.up),
fovy: f.fovy,
aspectRatio: f.aspectRatio,
lens: `${f.fovy} ${f.aspectRatio}`,
};
if (
!lastWorld ||
current.lens !== lastWorld.lens ||
!sameEye(current, lastWorld)
)
lastWorld = current;
return lastWorld;
},
report,
thresholds: capabilities?.has('cameraChangeThreshold') ?? true,
});
// `changed` is measured once a frame where the contract's frame order
// puts it: after the flight and input (Cesium's `initializeFrame`), before
// follow and `preUpdate` move the camera. Cesium moves a followed target's
// camera in its clock's tick, so a frame of the loop is measured as that
// tick starts; a frame drawn with no tick (a forced render), as
// `preUpdate` starts. Move detection runs after `preUpdate`.
let measured = false;
const measureChanged = () => {
if (measured) return;
measured = true;
applyFov();
cameraEvents.stepChanged();
};
const clock = widget?.clock;
if (typeof clock?.tick === 'function') {
const ownTick = clock.tick;
let wrapping = true;
const tick = function (...args) {
if (wrapping) {
measured = false;
measureChanged();
}
return ownTick.apply(this, args);
};
clock.tick = tick;
// Disposed, the clock gets its own tick back; if something has wrapped
// it since, that wrapper stays and this part of it only passes through.
removers.push(() => {
wrapping = false;
if (clock.tick !== tick) return;
if (Object.getPrototypeOf(clock)?.tick === ownTick) delete clock.tick;
else clock.tick = ownTick;
});
}
const offPreUpdate = scene.preUpdate?.addEventListener(measureChanged);
if (offPreUpdate) removers.push(offPreUpdate);
removers.push(
scene.postUpdate.addEventListener(() => {
applyFov();
cameraEvents.stepChanged();
// Measured already, unless the scene has no `preUpdate`.
measureChanged();
cameraEvents.stepMoveDetection(now());
measured = false;
}),
);
@@ -413,10 +474,19 @@ export function createCesiumCamera({
// The scene's own frame: ECEF in 3D, the only mode the app runs (Cesium's
// 2D and Columbus view frames are projected map coordinates).
matrices() {
return {
view: matrixArray(camera.viewMatrix),
projection: matrixArray(camera.frustum.projectionMatrix),
};
// The last ones again while Cesium's stand, new ones once they move.
const view = camera.viewMatrix;
const projection = camera.frustum.projectionMatrix;
if (
!lastMatrices ||
!sameMatrix(lastMatrices.view, view) ||
!sameMatrix(lastMatrices.projection, projection)
)
lastMatrices = {
view: matrixArray(view),
projection: matrixArray(projection),
};
return lastMatrices;
},
// Cesium's own corner picks (`computeViewRectangle`), on rays that
// keep their precision (`pickRayAt`).
@@ -442,18 +512,24 @@ export function createCesiumCamera({
);
},
pose() {
// An unmoved camera answers from the pose last read: a frame reads
// the pose many times over. Each caller gets objects of its own.
if (!poseKeyHolds() || !poseMemo) {
poseMemo = readPose();
// Outside 3D, Cesium measures heading, pitch and roll by moving the
// camera into the eye's frame and back, which can change its last
// bits: keyed as it is left.
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
}
return copyPose(poseMemo);
// Each caller gets objects of its own.
return copyPose(sharedPose());
},
};
/**
* The pose, read again only when the camera has moved: a frame reads the
* pose many times over. Shared: never changed once read.
*/
function sharedPose() {
if (!poseKeyHolds() || !poseMemo) {
poseMemo = readPose();
// Outside 3D, Cesium measures heading, pitch and roll by moving the
// camera into the eye's frame and back, which can change its last
// bits: keyed as it is left.
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
}
return poseMemo;
}
// The camera as the memoised pose was read: eye, axes, transform,
// frustum and mode, compared value for value.
const poseKey = new Float64Array(37);
@@ -469,15 +545,8 @@ export function createCesiumCamera({
const r = camera.rightWC;
const f = camera.frustum;
const t = camera.transform;
let same = true;
let at = 0;
const put = (value) => {
if (!Object.is(poseKey[at], value)) {
same = false;
poseKey[at] = value;
}
at += 1;
};
keySame = true;
keyAt = 0;
put(p.x);
put(p.y);
put(p.z);
@@ -502,7 +571,17 @@ export function createCesiumCamera({
put(f.bottom ?? NaN);
put(scene.mode ?? NaN);
for (let i = 0; i < 16; i++) put(t[i]);
return same;
return keySame;
}
// Where `poseKeyHolds` writes next, and whether all it wrote held.
let keyAt = 0;
let keySame = true;
function put(value) {
if (!Object.is(poseKey[keyAt], value)) {
keySame = false;
poseKey[keyAt] = value;
}
keyAt += 1;
}
const enuScratch = new Cesium.Matrix4();
/**
@@ -591,10 +670,15 @@ export function createCesiumCamera({
// Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a
// `lookAt` target's, or the identity.
if (!capabilities || capabilities.has('followFrame'))
cameraPort.followFrame = () => matrixArray(camera.transform);
cameraPort.followFrame = () => {
if (!lastFollowFrame || !sameMatrix(lastFollowFrame, camera.transform))
lastFollowFrame = matrixArray(camera.transform);
return lastFollowFrame;
};
return {
port: cameraPort,
measureChanged,
emit: (event) => cameraEvents.emit(event),
dispose() {
following?.dispose();
@@ -607,7 +691,9 @@ export function createCesiumCamera({
}
// A Cesium viewer with no renderer bound to it gets a
// camera port over its camera when code first asks `cameraOf` for one.
// camera port over its camera when code first asks `cameraOf` for one. The
// port wraps the viewer's `clock.tick` to measure `changed`, and gives it
// back when a renderer is bound to the viewer.
provideUnboundCamera((viewer) =>
// By shape, not `instanceof`: the viewer may come from another
// copy of Cesium.
+51 -1
View File
@@ -21,7 +21,7 @@ import {
} from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { cameraOf } from '../rendererOf.js';
import { bindRenderer, cameraOf } from '../rendererOf.js';
/** Records the headless scene cannot answer: they need the query port. */
const QUERY_RECORDS = new Set([
@@ -78,6 +78,7 @@ function headlessHarness(clock, { input = false } = {}) {
clock.now += FRAME_MS;
scene.tweens.update();
if (input) scene.screenSpaceCameraController.update();
scene.preUpdate.raiseEvent(scene);
scene.postUpdate.raiseEvent(scene);
},
scene,
@@ -287,6 +288,55 @@ test('a Cesium viewer with no renderer bound gets a camera port over its own cam
});
});
test('the camera port gives the clock its own tick back as it goes', () => {
const ownTick = Cesium.Clock.prototype.tick;
// A viewer with no renderer bound: its port goes when a renderer is bound.
{
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
scene.requestRender = () => {};
const viewer = { scene, camera, clock: new Cesium.Clock() };
cameraOf(viewer);
assert.notEqual(viewer.clock.tick, ownTick, 'measured as the tick starts');
bindRenderer(viewer, {});
assert.equal(viewer.clock.tick, ownTick, 'its own tick once unbound');
assert.equal(Object.hasOwn(viewer.clock, 'tick'), false);
}
// Wrapped again after the port: disposing leaves the later wrapper, and
// the port's own part of the tick measures nothing more.
{
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
scene.requestRender = () => {};
const clock = new Cesium.Clock();
const part = createCesiumCamera({
scene,
camera,
report: () => {},
widget: { clock },
});
const wrapped = clock.tick;
let later = 0;
clock.tick = function (...args) {
later += 1;
return wrapped.apply(this, args);
};
part.dispose();
let reads = 0;
const frustum = camera.frustum;
Object.defineProperty(camera, 'frustum', {
get: () => {
reads += 1;
return frustum;
},
configurable: true,
});
clock.tick();
assert.equal(later, 1, 'the later wrapper still runs');
assert.equal(reads, 0, 'the disposed port reads nothing');
}
});
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
+8 -6
View File
@@ -14,22 +14,24 @@ import * as Cesium from 'cesium';
* @param {(error: unknown) => void} onThrow
*/
export function listenerList(onThrow) {
const entries = [];
// Copied on change, not on delivery: a delivery runs over the list as it
// stood, and a change made during it makes a new one.
let entries = [];
return {
get size() {
return entries.length;
},
on(cb) {
const entry = { cb, live: true };
entries.push(entry);
entries = [...entries, entry];
return () => {
if (!entry.live) return;
entry.live = false;
const i = entries.indexOf(entry);
if (i >= 0) entries.splice(i, 1);
entries = entries.filter((e) => e !== entry);
};
},
fire(...args) {
for (const entry of entries.slice()) {
for (const entry of entries) {
if (!entry.live) continue;
try {
entry.cb(...args);
@@ -40,7 +42,7 @@ export function listenerList(onThrow) {
},
clear() {
for (const entry of entries) entry.live = false;
entries.length = 0;
entries = [];
},
};
}
+1 -1
View File
@@ -61,7 +61,7 @@ const plain = (v) => ({ x: v.x, y: v.y, z: v.z });
/**
* @param {{
* scene: object,
* controller: Function,
* controller: import('../contract/camera').CameraControllerFactory,
* query: {pickPosition?: Function, sampleHeightNow?: Function},
* itemPosition?: (item: {set: string, id: string|number}, aheadMs?: number) => object|null,
* requestRender: (reason: string) => void,
+21 -18
View File
@@ -207,23 +207,8 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
const { statics, screen, lightbox, logo } = creditDisplayContents(
displayLive() ? display : undefined,
);
let same = true;
let at = 0;
const put = (value) => {
if (!Object.is(lastInputs[at], value)) {
same = false;
lastInputs[at] = value;
}
at += 1;
};
const putElements = (elements) => {
put(elements.length);
for (const element of elements) {
put(element.credit);
put(element.count);
put(element.credit?.showOnScreen);
}
};
inputsSame = true;
inputAt = 0;
put(coreVersion);
put(logo);
put(logo?.showOnScreen);
@@ -234,7 +219,25 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
}
putElements(screen);
putElements(lightbox);
return same;
return inputsSame;
}
// Where `inputsHeld` writes next, and whether all it wrote held.
let inputAt = 0;
let inputsSame = true;
function put(value) {
if (!Object.is(lastInputs[inputAt], value)) {
inputsSame = false;
lastInputs[inputAt] = value;
}
inputAt += 1;
}
function putElements(elements) {
put(elements.length);
for (const element of elements) {
put(element.credit);
put(element.count);
put(element.credit?.showOnScreen);
}
}
inputsHeld();
+158 -47
View File
@@ -24,7 +24,7 @@
* settle into static batches that cost nothing until they change, and a
* line that moves again goes back to the collection (`settleLines`).
*
* Icon sets whose items move, glide, recede, pick by proxy or switch images
* Icon sets that recede, or whose items move, glide, pick by proxy or switch images
* by size, or that take columns, draw on the GPU instead (`gpuIcons.js`).
*
* Built over a scene by `createCesiumPorts`, and on its own over a Cesium
@@ -441,6 +441,9 @@ const ICONS_KEPT = 'kept';
const POINTS_ADDED = 'added';
const POINTS_KEPT = 'kept';
/** Whether a set's GPU icons move on in the frames that follow. */
const animating = (record) => record.gpu?.animating();
/**
* The draw port over `scene`, and what the other ports read of it: the live
* sets by id, a version that changes with what height queries see through
@@ -448,17 +451,20 @@ const POINTS_KEPT = 'kept';
* the clamp-state watch the frame loop runs after each draw.
* @param {{scene: object, report: (error: unknown) => void,
* capabilities?: ReadonlySet<string>,
* requestRender?: (reason: string) => void}} options `capabilities` gate
* requestRender?: (reason: string) => void,
* date?: () => 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).
* scene's, with no reason); `date`, the epoch ms a `live` motion clock
* reads (by default the system clock's).
*/
export function createCesiumDraw({
scene,
report,
capabilities = new Set(GPU_ICON_CAPABILITIES),
requestRender: requestFrame = null,
date = null,
}) {
const sets = new Map();
// Fields share the sets' ids.
@@ -481,6 +487,15 @@ export function createCesiumDraw({
const requestRender = () => {
if (live()) scene.requestRender();
};
// Once the port is disposed (its renderer destroyed), every set does
// nothing, and so does a set asked for after that.
let portDisposed = false;
/** A disposed set's listeners hear nothing more, even mid-delivery. */
function silence(record) {
record.listeners.ready.clear();
record.listeners.loadFailed.clear();
}
function makeSet(kind, spec, build) {
if (sets.has(spec.id) || fieldPart.has(spec.id))
@@ -569,6 +584,9 @@ export function createCesiumDraw({
record.gpu.write(list);
return patched();
}
// Icons drawn already, with the images they are drawn with, each
// changed where it is.
if (patchDrawnIcons(record, list)) return iconsPatched(ICONS_KEPT);
// Points restyled, moved or added keep the pick ids they had, so
// only points added change what height queries see through.
const points = patchPoints(record, list);
@@ -578,13 +596,22 @@ export function createCesiumDraw({
requestRender();
return;
}
// Models are changed where they are; moved or restyled they keep
// their pick ids, so only models added change what height queries
// see through.
if (kind === 'models') {
const added = modelSets.upsert(record, list);
for (const item of list) items.set(item.id, item);
if (added) setsVersion += 1;
requestRender();
return;
}
// Lines that only change how they show or where an undraped one
// runs, and clamped shapes that only show or hide, or a few colour
// fills that only move (`moveShape`), are changed where they are.
if (
patchLines(record, list) ||
patchShapes(record, list) ||
(kind === 'models' && modelSets.upsert(record, list)) ||
(kind === 'quads' && quadSets.upsert(record, list)) ||
(kind === 'meshes' && meshSets.upsert(record, list))
) {
@@ -639,8 +666,12 @@ export function createCesiumDraw({
requestRender();
return;
}
// Refused, changing nothing, where icons on the GPU cannot take it.
// Refused, changing nothing, where icons on the GPU cannot take it
// (all of them, for billboards told to recede, which go onto it).
const toGpu =
kind === 'icons' && !record.gpu && Boolean(options.recede);
if (record.gpu) gpu.check([], { ...spec, ...options });
else if (toGpu) gpu.check(items.values(), { ...spec, ...options });
const culled = spec.horizonCull;
const clampTo = spec.clampTo;
const blend = spec.blend;
@@ -666,6 +697,10 @@ export function createCesiumDraw({
// A set that stops picking lets its old ground go now: still drawn
// while the new builds, it would keep hiding the ground from picks.
if (pickable && spec.pickable === false) retire(record);
if (toGpu) {
onGpu(record, [], true, true);
record.gpu.sync();
}
record.gpu?.restyle();
if (kind === 'models') modelSets.restyle(record);
setsVersion += 1;
@@ -784,6 +819,42 @@ export function createCesiumDraw({
handle.upsert([...record.inertialDraped.values()]);
};
}
// A disposed set does nothing on later calls: one would draw what
// nothing removes.
record.disposed = portDisposed;
for (const name of [
'set',
'upsert',
'remove',
'clear',
'setOptions',
'setColumns',
]) {
const call = handle[name];
if (!call) continue;
handle[name] = (...args) => {
if (!record.disposed) return call(...args);
};
}
const { set: showSet } = Object.getOwnPropertyDescriptor(handle, 'show');
Object.defineProperty(handle, 'show', {
get: () => spec.show !== false,
set(value) {
if (!record.disposed) showSet.call(handle, value);
},
enumerable: true,
});
const on = handle.on;
handle.on = (event, cb) => (record.disposed ? () => {} : on(event, cb));
const disposeOnce = handle.dispose;
handle.dispose = () => {
if (record.disposed) return;
record.disposed = true;
// A listener that disposes the set stops the rest of that delivery.
silence(record);
disposeOnce();
};
if (record.disposed) return handle;
sets.set(spec.id, record);
setsVersion += 1;
return handle;
@@ -792,6 +863,7 @@ export function createCesiumDraw({
const gpu = createGpuIcons({
scene,
capabilities,
date,
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
@@ -811,7 +883,7 @@ export function createCesiumDraw({
*/
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
if (!record.gpu && !force && !gpu.wants(list)) return false;
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
gpu.check(list, record.spec);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec);
@@ -1073,11 +1145,6 @@ export function createCesiumDraw({
*/
function clusterIcons(frameState = scene.frameState) {
let pose;
const poseNow = () => {
const eye = scene.camera?.positionWC;
const dir = scene.camera?.directionWC;
return `${eye?.x},${eye?.y},${eye?.z},${dir?.x},${dir?.y},${dir?.z},${scene.canvas?.clientWidth},${scene.canvas?.clientHeight}`;
};
for (const record of sets.values()) {
if (!clusters(record)) {
if (record.clusterHost || record.clusterState) {
@@ -1095,21 +1162,54 @@ export function createCesiumDraw({
record.clusterKey = null;
record.clusteredHost = host;
}
pose ??= poseNow();
// Rows still moving on their segments cluster again every frame.
const key = record.gpu?.moving(frameState)
? `${pose}@${frameState?.frameNumber ?? Math.random()}`
: pose;
if (record.clusterKey === key) {
pose ??= clusterPoseNow();
// Rows still moving on their segments cluster again every frame (NaN,
// a frame with no number, is never the last).
const frameKey = record.gpu?.moving(frameState)
? (frameState?.frameNumber ?? NaN)
: null;
if (record.clusterKey === pose && record.clusterFrame === frameKey) {
if (record.clusterHost)
record.clusterHost.show = record.spec.show !== false;
continue;
}
record.clusterKey = key;
record.clusterKey = pose;
record.clusterFrame = frameKey;
reclusterIcons(record, frameState);
}
}
// The eye and canvas the clusters were last measured at, and a count of
// their changes: a set clusters again when the count it clustered at is
// not the count now.
const clusterPose = new Float64Array(8).fill(NaN);
let clusterPoseVersion = 0;
let clusterPoseAt = 0;
let clusterPoseSame = true;
function putClusterPose(value) {
if (!Object.is(clusterPose[clusterPoseAt], value)) {
clusterPoseSame = false;
clusterPose[clusterPoseAt] = value;
}
clusterPoseAt += 1;
}
function clusterPoseNow() {
const eye = scene.camera?.positionWC;
const dir = scene.camera?.directionWC;
clusterPoseAt = 0;
clusterPoseSame = true;
putClusterPose(eye?.x ?? NaN);
putClusterPose(eye?.y ?? NaN);
putClusterPose(eye?.z ?? NaN);
putClusterPose(dir?.x ?? NaN);
putClusterPose(dir?.y ?? NaN);
putClusterPose(dir?.z ?? NaN);
putClusterPose(scene.canvas?.clientWidth ?? NaN);
putClusterPose(scene.canvas?.clientHeight ?? NaN);
if (!clusterPoseSame) clusterPoseVersion += 1;
return clusterPoseVersion;
}
/** The points a GPU set clusters: its shown rows where they are drawn. */
function gpuClusterPoints(record, frameState, horizon) {
const points = [];
@@ -1274,9 +1374,13 @@ export function createCesiumDraw({
/** Whether a shown set shows flow lines, which draw on in later frames. */
const flowing = () =>
[...sets.values()].some(
(record) => record.spec.show !== false && record.flowShown,
);
anySet((record) => record.spec.show !== false && record.flowShown);
/** Whether any set passes `test`, without copying the sets (per frame). */
function anySet(test) {
for (const record of sets.values()) if (test(record)) return true;
return false;
}
/** Note whether a line set shows any flow line, once its lines change. */
function noteFlows(record) {
@@ -1621,37 +1725,48 @@ export function createCesiumDraw({
}
/**
* `syncIcons`' quick case: every item is drawn, every touched one keeps
* the image it is drawn with, and nothing drawn has gone, so each touched
* one is changed where it is and nothing is added, removed or reordered.
* False, changing nothing, otherwise.
* `upsert`'s quick case for an icon set on billboards: every item is
* drawn, every one of `list` keeps the image it is drawn with, and
* nothing drawn has gone, so each of `list` is changed where it is
* (`patchIcon`: only moved, when that is all that changed) and nothing is
* added, removed or reordered. Each item is read once: a layer moves its
* icons every frame. The items are taken as the set's. False, changing
* nothing, otherwise.
* @param {object} record
* @param {readonly string[]} touched
* @param {readonly object[]} list
*/
function patchDrawnIcons(record, touched) {
function patchDrawnIcons(record, list) {
const drawn = record.billboards;
const host = record.billboardHost;
// Nothing to remove: every item drawn, and nothing drawn but items.
if (
!Array.isArray(touched) ||
touched.length === 0 ||
record.kind !== 'icons' ||
!drawn ||
!host ||
record.host !== host ||
host.isDestroyed() ||
list.length === 0 ||
drawn.size !== record.items.size
)
return false;
for (const id of touched) {
const entry = drawn.get(id);
const item = record.items.get(id);
if (!entry || !item) return false;
const image = iconImage(record, item.image);
const entries = new Array(list.length);
const images = new Array(list.length);
for (let i = 0; i < list.length; i++) {
const entry = drawn.get(list[i].id);
if (!entry) return false;
const image = iconImage(record, list[i].image);
if (
image === undefined ||
imageKeyOf(image) !== entry.image ||
(isKeyed(image) && image.canvas !== entry.canvas)
)
return false;
entries[i] = entry;
images[i] = image;
}
for (const id of touched) {
const item = record.items.get(id);
patchIcon(record, drawn.get(id), item, iconImage(record, item.image));
for (let i = 0; i < list.length; i++) {
record.items.set(list[i].id, list[i]);
patchIcon(record, entries[i], list[i], images[i]);
}
return true;
}
@@ -1685,7 +1800,6 @@ export function createCesiumDraw({
host.isDestroyed()
)
return false;
if (!reordered && patchDrawnIcons(record, touched)) return ICONS_KEPT;
const images = new Map();
for (const id of touched) {
const item = record.items.get(id);
@@ -2467,7 +2581,7 @@ export function createCesiumDraw({
? Cesium.JulianDate.toDate(
scene.frameState?.time ?? Cesium.JulianDate.now(),
).getTime()
: Date.now() - (clock?.delayMs ?? 0);
: (date ? date() : Date.now()) - (clock?.delayMs ?? 0);
}
/**
@@ -5300,7 +5414,7 @@ export function createCesiumDraw({
return record.gpu.drawnAt(ref.id, aheadMs, time ? { time } : undefined);
},
/** Whether a set's ground primitives are still being built. */
building: () => [...sets.values()].some((record) => record.pending),
building: () => anySet((record) => record.pending),
/** Each frame, before it draws: the horizon cull. */
beforeRender() {
pulsing = runPulses();
@@ -5343,19 +5457,14 @@ export function createCesiumDraw({
// Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow.
const playing = quadSets.afterRender(sets.values());
if (
[...sets.values()].some((record) => record.gpu?.animating()) ||
flowing() ||
pulsing ||
playing
)
requestRender();
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
},
/**
* Let go of the sets; with `removeHosts`, take what they draw out of
* the scene too (a scene the port does not own outlives it).
*/
dispose({ removeHosts = false } = {}) {
portDisposed = true;
clampListeners.clear();
// Fields go with the port, and their frame listeners with them.
fieldPart.dispose();
@@ -5366,6 +5475,8 @@ export function createCesiumDraw({
retire(record);
}
record.host = null;
record.disposed = true;
silence(record);
}
sets.clear();
},
+404 -1
View File
@@ -4394,6 +4394,22 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del
assert.equal(flags & ICON_RECEDES, ICON_RECEDES);
assert.equal(flags & ICON_CULL_LIFT, ICON_CULL_LIFT);
assert.ok(set.depthTestDistance(row) >= 1e30, 'over depth everywhere');
// The set recedes by the aircraft tuning, and follows it when it changes.
const recession = await import('../../data/aircraftRecession.js');
assert.equal(
part.sets.get(setId).spec.recede,
recession.aircraftRecedeSpec(),
);
assert.equal('recede' in part.sets.get(setId).items.get('abc123'), false);
try {
recession.setAircraftRecessionParams({ scaleFloor: 0.6 });
icons._syncRecede();
assert.equal(host._recedeParams().scaleFloor, 0.6);
} finally {
recession.resetAircraftRecessionParams();
icons._syncRecede();
}
assert.equal(host._recedeParams().scaleFloor, 0.45);
// Drawn where the layer reads it, between its two fixes.
const t = Date.now() - delayMs;
@@ -6674,7 +6690,7 @@ test('models re-pose and restyle in place; only a new url loads again', async ()
Cesium.ColorBlendMode.HIGHLIGHT,
'no tint to blend in: its own colour',
);
assert.equal(model.color.alpha, 1);
assert.equal(model.color, undefined, 'and no colour of its own');
set.upsert([plane({ show: false })]);
assert.equal(model.show, false, 'hidden in place');
@@ -6911,6 +6927,193 @@ test('a model past its pixel cap is scaled down each frame; fades and culls too'
}
});
test('an untinted model drawn fully opaque is given no colour; a fade gives one, and full opacity takes it away again', async () => {
// A colour on a Cesium model adds a colour stage to every draw of it.
const { loads, restore } = fakeModelLoads();
try {
const scene = fakeScene();
let metresPerPixel = 0.1;
scene.camera.getPixelSize = () => metresPerPixel;
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'm' });
const eye = scene.camera.positionWC;
const at = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
const distance = Cesium.Cartesian3.distance(eye, at);
const item = (extra = {}) => ({
id: 'a',
pos: { lon: 0, lat: 0, height: 1000 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
...extra,
});
set.set([item()]);
loads[0].resolve();
await settle();
const model = loads[0].model;
loads[0].ready();
part.beforeRender();
assert.equal(model.color, undefined, 'opaque, untinted: no colour');
set.upsert([
item({
fadeByDistance: {
near: distance - 10,
nearValue: 1,
far: distance + 10,
farValue: 0,
},
}),
]);
part.beforeRender();
assert.ok(model.color, 'faded: a colour');
assert.ok(Math.abs(model.color.alpha - 0.5) < 1e-6, 'faded halfway');
set.upsert([item()]);
part.beforeRender();
assert.equal(model.color, undefined, 'opaque again: no colour');
set.dispose();
} finally {
restore();
}
});
test('models moved every frame keep their shader and pick ids: only a new look or a new model changes them', async () => {
// A fleet re-poses every model each frame with the same look.
const { loads, restore } = fakeModelLoads();
const toCss = Cesium.Color.prototype.toCssHexString;
let shaderLookups = 0;
Cesium.Color.prototype.toCssHexString = function () {
shaderLookups += 1;
return toCss.call(this);
};
try {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'fleet' });
const item = (id, lon, extra = {}) => ({
id,
pos: { lon, lat: 0, height: 10 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
maskColor: '#ff8800',
...extra,
});
set.set([item('a', 0), item('b', 1)]);
for (const load of loads) load.resolve();
await settle();
for (const load of loads) load.ready();
const [a, b] = loads.map((load) => load.model);
const shader = a.customShader;
assert.ok(shader instanceof Cesium.CustomShader, 'the mask shader');
const version = part.version();
shaderLookups = 0;
for (let frame = 1; frame <= 5; frame++) {
set.upsert([item('a', frame * 1e-5), item('b', 1 + frame * 1e-5)]);
part.beforeRender();
}
const moved = Cesium.Matrix4.getTranslation(
a.modelMatrix,
new Cesium.Cartesian3(),
);
assert.ok(
Cesium.Cartesian3.distance(
moved,
Cesium.Cartesian3.fromDegrees(5e-5, 0, 10),
) < 1e-6,
'moved',
);
assert.equal(a.customShader, shader, 'the same shader');
assert.equal(shaderLookups, 0, 'not looked up again');
assert.equal(part.version(), version, 'no pick id added or gone');
// A new mask colour, a new shading and the mask again: each drawn.
set.upsert([item('a', 0, { maskColor: '#0000ff' })]);
assert.notEqual(a.customShader, shader, 'a new colour, a new shader');
assert.equal(b.customShader, shader, 'the other keeps its own');
set.upsert([item('a', 0, { maskColor: '#0000ff', shading: 'thermal' })]);
const thermal = a.customShader;
assert.ok(thermal instanceof Cesium.CustomShader);
assert.notEqual(thermal, shader);
set.upsert([item('a', 0)]);
assert.equal(a.customShader, shader, 'its mask again');
set.upsert([item('a', 0, { maskColor: undefined })]);
assert.equal(a.customShader, undefined, 'no mask: lit as it is');
// A model added changes what height queries see through.
set.upsert([item('c', 2)]);
assert.notEqual(part.version(), version, 'a pick id added');
set.dispose();
} finally {
Cesium.Color.prototype.toCssHexString = toCss;
restore();
}
});
test('a model set that recedes fades its models toward the limb with their focus; focus alone dims', async () => {
const { recedeFactors, recedeFrame, recedeParams, recededAlpha } =
await import('../recession.js');
const { loads, restore } = fakeModelLoads();
try {
const scene = fakeScene();
const heightM = 1_000_000;
scene.camera.positionWC = new Cesium.Cartesian3(6_378_137 + heightM, 0, 0);
scene.camera.positionCartographic = { height: heightM };
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'm', recede: {} });
const item = (extra = {}) => ({
id: 'a',
pos: { lon: 25, lat: 0, height: 0 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
tint: [1, 0, 0, 0.8],
focus: 0.5,
...extra,
});
set.set([item()]);
loads[0].resolve();
await settle();
const model = loads[0].model;
loads[0].ready();
part.beforeRender();
const params = recedeParams({});
const d = Cesium.Cartesian3.distance(
scene.camera.positionWC,
Cesium.Cartesian3.fromDegrees(25, 0, 0),
);
const haze = recedeFactors(d, recedeFrame(heightM, params), params).alpha;
assert.ok(haze < 0.9, `receding: ${haze}`);
const want = 0.8 * recededAlpha(0.5, haze, params);
assert.ok(
Math.abs(model.color.alpha - want) < 1e-6,
`${model.color.alpha} vs ${want}`,
);
assert.equal(model.color.red, 1, 'the tint kept');
// Not receding: the tint's alpha times the focus.
set.setOptions({ recede: null });
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.4) < 1e-6, `${model.color.alpha}`);
set.upsert([item({ focus: undefined })]);
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.8) < 1e-6);
// Receding again, over the blend band: only the combined floor holds.
set.setOptions({ recede: {} });
scene.camera.positionCartographic = { height: 9_000_000 };
set.upsert([item({ focus: 0.1 })]);
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.8 * 0.2) < 1e-6);
set.dispose();
} finally {
restore();
}
});
test('a raised polygon outlines its holes as well as its outer ring', () =>
withImageClasses(() => {
const { scene, draw } = drawOver();
@@ -7894,6 +8097,70 @@ test('icons that only move are moved on the billboards they have, and still rest
set.dispose();
});
test('icons moved every frame are each read once, and a new image or a new icon still draws', () => {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.icons({ id: 'icons:fleet' });
// Reads of each item's image: what a moved icon is drawn with is
// looked up once an update.
let imageReads = 0;
const icon = (id, lon) => {
let image = 'a.png';
return {
id,
pos: { ...Cesium.Cartesian3.fromDegrees(lon, 10) },
get image() {
imageReads += 1;
return image;
},
set image(value) {
image = value;
},
size: [20, 20],
color: '#33ccff',
rotationMode: 'screen',
rotation: 0,
disableDepthTest: Infinity,
meta: { id },
};
};
const items = [icon('a', 0), icon('b', 1), icon('c', 2)];
set.set(items);
const [host] = scene.added;
const billboards = [0, 1, 2].map((i) => host.get(i));
const version = part.version();
imageReads = 0;
for (let frame = 1; frame <= 4; frame++) {
for (const item of items) item.pos.x += 1;
set.upsert(items);
}
assert.equal(imageReads, 4 * items.length, 'each image read once a frame');
assert.equal(scene.added[0], host, 'the same collection');
billboards.forEach((billboard, i) => {
assert.equal(host.get(i), billboard, 'the same billboards');
assert.equal(billboard.position.x, items[i].pos.x, 'moved');
});
assert.equal(part.version(), version, 'nothing added or removed');
// Only some moved: the others stay where they are.
items[1].pos.x += 1;
set.upsert([items[1]]);
assert.equal(billboards[1].position.x, items[1].pos.x);
// A new image is drawn on the billboard it has.
items[0].image = 'b.png';
set.upsert(items);
assert.equal(host.get(0), billboards[0], 'the same billboard');
assert.equal(billboards[0].image, 'b.png');
// An icon added joins after the others.
set.upsert([...items, icon('d', 3)]);
assert.equal(host.length, 4);
assert.notEqual(part.version(), version, 'an icon added');
set.dispose();
});
test('the transit layer draws its vehicles as two icon sets, moving a marker between them, on a viewer of its own', async () => {
const { createRendering } = await import('../../layers/transit/rendering.js');
const { createState } = await import('../../layers/transit/state.js');
@@ -8361,3 +8628,139 @@ test('a quad that moves from a blob to a URL lets the blob go once its old mater
names.forEach((name, i) => (globalThis[name] = real[i]));
}
});
test('a set disposed by one of its listeners tells the later ones nothing more', async () => {
const { loads, restore } = fakeModelLoads();
try {
const plane = (id) => ({
id,
pos: { lon: 0, lat: 0, height: 10 },
url: 'a.glb',
});
const loaded = async (load) => {
load.resolve();
await settle();
load.ready();
};
// Disposed by its handle, from its first ready listener.
const part = createCesiumDraw({
scene: fakeScene(),
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'planes' });
const heard = [];
set.on('ready', () => set.dispose());
set.on('ready', (id) => heard.push(id));
set.on('loadFailed', (id) => heard.push(`failed ${id}`));
set.set([plane('p')]);
await loaded(loads[0]);
assert.deepEqual(heard, [], 'the second listener does not run');
// Every set, when the port is disposed from a ready listener.
const gone = createCesiumDraw({
scene: fakeScene(),
report: (error) => assert.fail(error),
});
const other = gone.port.models({ id: 'planes' });
const late = [];
other.on('ready', () => gone.dispose({ removeHosts: true }));
other.on('ready', (id) => late.push(id));
other.set([plane('q')]);
await loaded(loads[1]);
assert.deepEqual(late, [], 'nothing after the port is gone');
} finally {
restore();
}
});
test('a disposed set, and every set once the port is disposed, does nothing on later calls', async () => {
const { loads, restore } = fakeModelLoads();
try {
const items = {
points: { id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' },
lines: {
id: 'a',
positions: [
{ lon: 0, lat: 0 },
{ lon: 1, lat: 1 },
],
widthPx: 2,
style: { kind: 'solid', color: '#fff' },
},
icons: {
id: 'a',
pos: { lon: 0, lat: 0 },
image: 'data:image/png;base64,iVBORw0KGgo=',
},
shapes: {
id: 'a',
geometry: {
kind: 'ellipse',
center: { lon: 0, lat: 0 },
semiMajor: 1000,
semiMinor: 1000,
},
fill: [1, 0, 0, 0.5],
},
models: { id: 'a', pos: { lon: 0, lat: 0, height: 10 }, url: 'a.glb' },
};
const lateCalls = (set, item) => {
set.set([item]);
set.upsert([{ ...item, id: 'b' }]);
set.show = true;
set.setOptions({ clampTo: 'terrain', pickable: false, drawOrder: 3 });
set.setOptions({ show: true });
set.setColumns?.({
ids: ['c'],
positions: new Float64Array([6378137, 0, 0]),
});
set.remove(['a']);
set.clear();
assert.equal(typeof set.on('ready', () => {}), 'function');
};
// Disposed by its handle.
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
for (const [kind, item] of Object.entries(items)) {
const set = part.port[kind]({ id: kind });
set.dispose();
lateCalls(set, item);
assert.equal(scene.added.length, 0, `${kind}: nothing drawn`);
assert.equal(part.sets.size, 0, `${kind}: no set live`);
set.dispose();
}
// A newer set under the same id is not changed by the old handle.
const old = part.port.points({ id: 'same' });
old.dispose();
const newer = part.port.points({ id: 'same' });
old.set([items.points]);
assert.equal(newer.size(), 0, 'the newer set keeps its items');
newer.dispose();
// Every set, once the port is disposed (its renderer destroyed), and a
// set asked for after that.
const held = fakeScene();
const gone = createCesiumDraw({
scene: held,
report: (error) => assert.fail(error),
});
const before = Object.keys(items).map((kind) => [
kind,
gone.port[kind]({ id: kind }),
]);
gone.dispose({ removeHosts: true });
for (const [kind, set] of before) lateCalls(set, items[kind]);
for (const [kind, item] of Object.entries(items))
lateCalls(gone.port[kind]({ id: `${kind}:late` }), item);
assert.equal(held.added.length, 0, 'nothing drawn after the port is gone');
assert.equal(gone.sets.size, 0, 'no set live after the port is gone');
assert.equal(loads.length, 0, 'no model loads');
} finally {
restore();
}
});
+13
View File
@@ -664,8 +664,20 @@ export function createCesiumFields({
return handle;
}
// Once the fields are disposed (their renderer destroyed), a field asked
// for draws nothing and does nothing.
let gone = false;
const inert = (spec) => ({
id: spec?.id,
show: true,
update() {},
on: () => () => {},
dispose() {},
});
return {
field(spec) {
if (gone) return inert(spec);
if (fields.has(spec?.id))
throw new Error(`a field with id ${spec.id} is live`);
if (spec?.kind === 'rasterShell') return rasterShell(spec);
@@ -688,6 +700,7 @@ export function createCesiumFields({
},
has: (id) => fields.has(id),
dispose() {
gone = true;
for (const handle of [...fields.values()]) handle.dispose();
},
};
+29
View File
@@ -691,3 +691,32 @@ test('the Cesium fields refuse kinds they cannot draw and live ids', () => {
field.dispose();
h.fields.field(spec).dispose();
});
test('once the fields are disposed, a field asked for draws nothing and does nothing', () => {
const h = fieldHarness();
const field = h.fields.field({
kind: 'rasterShell',
id: 'shell',
image: h.image(),
rectangle: RECT,
heightM: 1,
});
h.fields.dispose();
assert.equal(h.live().length, 0, 'the live field went');
field.update({ alpha: 0.5 });
field.show = true;
const late = h.fields.field({
kind: 'rasterShell',
id: 'late',
image: h.image(),
rectangle: RECT,
heightM: 1,
});
late.update({ heightM: 2 });
late.show = true;
assert.equal(typeof late.on('drawn', () => {}), 'function');
h.render();
assert.equal(h.live().length, 0, 'nothing drawn after');
assert.equal(h.fields.has('late'), false);
late.dispose();
});
+101 -13
View File
@@ -14,7 +14,10 @@
* `maxPixelSize` (the scale capped so the bounding sphere spans at most that
* many drawing-buffer pixels at its distance from the eye, as Cesium
* measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's
* alpha) and the set's `horizonCull`.
* alpha), the set's `horizonCull`, and its `recede`: the tint's alpha times
* the focus and haze (`render/recession.js`), written again once that moves
* by more than `RECEDE_WRITE_EPSILON`. A model of a set that does not
* recede draws at its tint's alpha times its `focus`.
*
* A failed load fires `loadFailed` (after the frame Cesium reported it in,
* so a listener may change the set), and is tried again when its item is
@@ -25,6 +28,12 @@
* them. Heights are absolute: models clamp nothing.
*/
import * as Cesium from 'cesium';
import {
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../recession.js';
const BLEND_MODES = {
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
@@ -39,6 +48,13 @@ const BLEND_MODES = {
*/
export const MODEL_RETRY_MS = 5000;
/**
* How far a receding model's emphasis (focus and haze) moves before its
* colour is written again: an eye in motion would otherwise write every
* model's colour every frame.
*/
export const RECEDE_WRITE_EPSILON = 0.005;
/** Cesium's own blend amount, for a `mix` that names none. */
const DEFAULT_MIX = 0.5;
@@ -85,9 +101,17 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
*/
function entryShader(entry) {
const shading = entry.item.shading;
if (entry.mask && shading !== 'thermal')
return maskShaderOf(shading, entry.mask);
return shaderOf(shading);
// Kept while its shading and mask colour are: a fleet re-poses every
// frame with the same look.
if (entry.shaderShading === shading && entry.shaderMask === entry.mask)
return entry.shader;
entry.shader =
entry.mask && shading !== 'thermal'
? maskShaderOf(shading, entry.mask)
: shaderOf(shading);
entry.shaderShading = shading;
entry.shaderMask = entry.mask;
return entry.shader;
}
/**
@@ -151,8 +175,12 @@ const scratchAxes = new Cesium.Cartesian3();
const scratchMatrix = new Cesium.Matrix4();
const scratchSphere = new Cesium.BoundingSphere();
const scratchColor = new Cesium.Color();
const scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
const scratchFrame = { active: false, limbM: 1, strength: 0 };
/** The colour last written to each model. */
const writtenColors = new WeakMap();
/** Written to a model drawn in its own colours: no colour at all. */
const NO_COLOR = Symbol('drawModels.noColor');
/** What the per-frame pass found, for a model it does not run on. */
const STILL = Object.freeze({ scale: 1, alpha: 1, shown: true });
@@ -189,7 +217,12 @@ const needsFrame = (item, spec) =>
item.maxPixelSize > 0 ||
Boolean(item.scaleByDistance) ||
Boolean(item.fadeByDistance) ||
Boolean(spec.horizonCull);
Boolean(spec.horizonCull) ||
Boolean(spec.recede);
/** An item's focus, 0..1. */
const focusOf = (item) =>
Number.isFinite(item.focus) ? Math.min(1, Math.max(0, item.focus)) : 1;
/**
* The models part of a Cesium draw port.
@@ -421,12 +454,27 @@ export function createModelSets({
entry.tint ?? Cesium.Color.WHITE,
scratchColor,
);
color.alpha *= frame.alpha;
color.alpha *= frame.alpha * (entry.emphasis ?? focusOf(item));
// An untinted model at full opacity is drawn without a colour: a colour
// adds a colour stage to every draw of the model.
const plain = !entry.tint && color.alpha === 1;
// Written only when what is asked changes, so a theme's own write to a
// model's colour stands until then.
const written = writtenColors.get(model);
if (!written || !Cesium.Color.equals(written, color)) {
writtenColors.set(model, Cesium.Color.clone(color, written));
if (plain) {
if (written !== NO_COLOR) {
writtenColors.set(model, NO_COLOR);
model.color = undefined;
}
} else if (
!written ||
written === NO_COLOR ||
!Cesium.Color.equals(written, color)
) {
writtenColors.set(
model,
Cesium.Color.clone(color, written === NO_COLOR ? undefined : written),
);
model.color = color;
}
const show =
@@ -434,17 +482,24 @@ export function createModelSets({
if (model.show !== show) model.show = show;
}
/** Add or change items, by id; true once handled (always, for models). */
/**
* Add or change items, by id. Whether any was added: models moved or
* restyled keep their pick ids, so only one added changes what height
* queries see through.
*/
function upsert(record, list) {
hostOf(record);
for (const item of list) put(record, item);
notePickIds(record);
let added = false;
for (const item of list) if (put(record, item)) added = true;
if (added) notePickIds(record);
requestRender();
return true;
return added;
}
/** Draw `item` on its entry, made when it has none; true when made. */
function put(record, item) {
let entry = record.models.get(item.id);
const made = !entry;
if (!entry) {
entry = {
item,
@@ -463,8 +518,15 @@ export function createModelSets({
failedAt: 0,
settleLoad: null,
styled: null,
// The custom shader drawn with, for the shading and mask it is of
// (`entryShader`).
shader: undefined,
shaderShading: null,
shaderMask: null,
dynamic: false,
frame: null,
// Focus and haze in a set that recedes, else null (focus alone).
emphasis: null,
pickId: pickId(record, item),
};
record.models.set(item.id, entry);
@@ -495,6 +557,7 @@ export function createModelSets({
if (model) style(record, entry, model);
const retry = entry.failed && Date.now() - entry.failedAt >= MODEL_RETRY_MS;
if (entry.url !== item.url || retry) load(record, entry);
return made;
}
/** Stop the entry's load in flight, keeping the model it draws. */
@@ -527,8 +590,17 @@ export function createModelSets({
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
let horizon;
const eyeHeight = scene.camera.positionCartographic?.height;
for (const record of sets) {
if (record.kind !== 'models' || !record.models) continue;
if (record.recedeFrom !== record.spec.recede) {
record.recedeFrom = record.spec.recede;
record.recede = recedeParams(record.spec.recede);
}
const recede = record.recede;
const recedeNow = recede
? recedeFrame(eyeHeight, recede, scratchFrame)
: null;
for (const entry of record.models.values()) {
if (!entry.dynamic) {
if (entry.frame) {
@@ -548,6 +620,20 @@ export function createModelSets({
Math.max(0, nearFarValue(item.fadeByDistance, distance)),
)
: 1;
if (recede) {
const haze = recedeFactors(
distance,
recedeNow,
recede,
scratchFactors,
).alpha;
const emphasis = recededAlpha(focusOf(item), haze, recede);
if (
entry.emphasis === null ||
Math.abs(entry.emphasis - emphasis) > RECEDE_WRITE_EPSILON
)
entry.emphasis = emphasis;
} else entry.emphasis = null;
let shown = frame.alpha > 0;
if (record.spec.horizonCull) {
horizon ??= horizonNow();
@@ -609,8 +695,10 @@ export function createModelSets({
/** The set's options changed: whether models need the frame pass. */
function restyle(record) {
if (!record.models) return;
for (const entry of record.models.values())
for (const entry of record.models.values()) {
entry.dynamic = needsFrame(entry.item, record.spec);
if (!record.spec.recede) entry.emphasis = null;
}
}
return { build, upsert, beforeRender, restyle };
+3 -2
View File
@@ -150,7 +150,7 @@ export function createCesiumEffects(
onChange: () => {
if (gone() || modulation.draws() === modulationListed) return;
modulationListed = modulation.draws();
listeners.fire(port.diagnostics());
if (listeners.size) listeners.fire(port.diagnostics());
},
})
: null;
@@ -223,7 +223,8 @@ export function createCesiumEffects(
if (gone()) return;
apply();
frame.requestRender(reason);
listeners.fire(port.diagnostics());
// A fade changes every frame: its diagnostics are listed only for ears.
if (listeners.size) listeners.fire(port.diagnostics());
}
/** Whether `id` names a style; changes to unknown ones are ignored. */
+12 -8
View File
@@ -144,9 +144,12 @@ export function createCesiumGlobe(
// The vector base's sources' credits.
const vectorCredits = [];
/** Every 3D tileset the scene holds. */
function tilesets() {
const found = [];
/**
* Every 3D tileset the scene holds, into `found` (emptied first): the
* per-frame readers pass `scratchTilesets` rather than make a list.
*/
function tilesets(found = []) {
found.length = 0;
const primitives = scene.primitives;
const n = primitives?.length ?? 0;
for (let i = 0; i < n; i++) {
@@ -155,12 +158,13 @@ export function createCesiumGlobe(
}
return found;
}
const scratchTilesets = [];
/** The base tileset drawn now, which `objects` imagery drapes on. */
function drawnBase() {
if (photoreal && !photoreal.isDestroyed() && photoreal.show)
return photoreal;
for (const tileset of tilesets())
for (const tileset of tilesets(scratchTilesets))
if (isBaseTileset(tileset) && tileset.show && !tileset.isDestroyed())
return tileset;
return null;
@@ -401,7 +405,7 @@ export function createCesiumGlobe(
function surfaceLoaded() {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
let found = false;
for (const tileset of tilesets()) {
for (const tileset of tilesets(scratchTilesets)) {
if (!tileset.show || tileset.isDestroyed?.()) continue;
found = true;
if (tileset.tilesLoaded === false) return false;
@@ -423,7 +427,7 @@ export function createCesiumGlobe(
// The shown tilesets as a set: their order among the primitives is no
// change to the surface.
let count = 0;
for (const tileset of tilesets()) {
for (const tileset of tilesets(scratchTilesets)) {
if (!tileset.show || tileset.isDestroyed?.()) continue;
count += 1;
if (!surfaceSeen.tiles.has(tileset)) changed = true;
@@ -433,7 +437,7 @@ export function createCesiumGlobe(
surfaceSeen.globe = globe;
surfaceSeen.terrain = terrain;
surfaceSeen.tiles.clear();
for (const tileset of tilesets())
for (const tileset of scratchTilesets)
if (tileset.show && !tileset.isDestroyed?.())
surfaceSeen.tiles.add(tileset);
surfaceVersion = ++surfaceVersions;
@@ -480,7 +484,7 @@ export function createCesiumGlobe(
applyShading();
requestRender('base');
}
if (imagery.list().length) imagery.sync();
if (imagery.size) imagery.sync();
if (progressListeners.size === 0) return;
const base = drawnBase();
progress.tilesPending = base && !base.tilesLoaded ? 1 : 0;
+20 -9
View File
@@ -2,7 +2,7 @@
* @module render/cesium/gpuIcons
* @description The Cesium draw port's GPU icon sets: an icon set whose items
* move (`motionSegments`), glide their course (`courseGlide`), recede
* toward the limb, pick through a larger proxy,
* toward the limb (`recede`, the set's), pick through a larger proxy,
* switch images by drawn size, or that takes columns (`columns`), draws as
* one instanced primitive (`IconSetPrimitive`) over an icon set's typed
* columns (`iconSet.js`) instead of a billboard collection. Each item is one
@@ -200,16 +200,19 @@ function rasterPxOf(url, item) {
/**
* @param {{scene: object, capabilities: ReadonlySet<string>,
* date?: (() => number)|null,
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* requestRender: (reason: string) => void}} options `imageOf` reads an atlas slot
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it.
*/
export function createGpuIcons({
scene,
capabilities,
date = null,
toColor,
imageOf,
peekImage,
@@ -217,13 +220,13 @@ export function createGpuIcons({
}) {
const can = (capability) => capabilities.has(capability);
/** Whether drawing these items needs a GPU icon set. */
function wants(items) {
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
if (spec.recede) return true;
for (const item of items) {
if (
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.recede ||
item.pickProxy ||
item.imageLod
)
@@ -293,7 +296,9 @@ export function createGpuIcons({
result,
);
return Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(result),
date
? Cesium.JulianDate.fromDate(new Date(date()), result)
: Cesium.JulianDate.now(result),
-(clock?.delayMs ?? 0) / 1000,
result,
);
@@ -309,6 +314,7 @@ export function createGpuIcons({
clockTime(frameState, new Cesium.JulianDate()),
requestRender: () => requestRender(`icons:${spec.id}`),
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
@@ -423,7 +429,7 @@ export function createGpuIcons({
isCurve(item.scaleByDistance) ? item.scaleByDistance : undefined,
);
set.setFlag(row, ICON_ROTATES, item.rotationMode === 'course');
set.setFlag(row, ICON_RECEDES, item.recede === true);
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
set.setPickProxy(
row,
@@ -727,10 +733,15 @@ export function createGpuIcons({
}
columnIds = ids;
},
/** After `setOptions`: the cull lift follows `horizonCull`. */
/**
* After `setOptions`: the cull lift follows `horizonCull`, and every
* row recedes while the set does.
*/
restyle() {
for (let row = 0; row < set.count; row++)
for (let row = 0; row < set.count; row++) {
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
}
},
/** Rewrite the rows drawing from atlas `id`. */
reatlas(id) {
+62 -2
View File
@@ -221,9 +221,45 @@ test('rows moving on a live clock keep frames coming until their segments end',
assert.equal(scene.renders, onScene);
});
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
const { scene, part, draw } = drawOver();
// An item's own `recede` is not the contract's: it changes nothing.
const still = draw.icons({ id: 'gpu:still' });
still.set([icon('a', { recede: true })]);
assert.ok(
!(scene.added.at(-1) instanceof IconSetPrimitive),
'still icons stay billboards',
);
const set = draw.icons({
id: 'gpu:recede',
recede: { scaleFloor: 0.6 },
});
set.set([icon('a'), icon('b')]);
const host = scene.added.at(-1);
assert.ok(host instanceof IconSetPrimitive, 'on the GPU, though still');
const { set: s } = rows(part, 'gpu:recede');
for (const id of ['a', 'b'])
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, ICON_RECEDES, id);
assert.equal(host._recedeParams().scaleFloor, 0.6);
assert.equal(host._recedeParams().alphaFloor, 0.35, 'the rest the defaults');
set.setOptions({ recede: null });
for (const id of ['a', 'b'])
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, 0, `${id} no longer`);
assert.equal(host._recedeParams(), null);
// A billboard set told to recede goes onto the GPU, its icons with it.
still.setOptions({ recede: {} });
const moved = part.sets.get('gpu:still').gpu;
assert.ok(moved, 'on the GPU now');
assert.equal(moved.set.count, 1);
assert.equal(
moved.set.flags(moved.set.row('a')) & ICON_RECEDES,
ICON_RECEDES,
);
});
test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy, depth and images', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:look', horizonCull: true });
const set = draw.icons({ id: 'gpu:look', horizonCull: true, recede: {} });
set.set([
icon('a', {
motion: { kind: 'hold', courseDeg: 10 },
@@ -232,7 +268,6 @@ test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy
alpha: 0.5,
color: [1, 0, 0, 1],
focus: 0.25,
recede: true,
rotationMode: 'course',
pickProxy: { size: [48, 40] },
disableDepthTest: Infinity,
@@ -1127,3 +1162,28 @@ test('a GPU icon set asks the frame port for its atlas frames, under its own rea
iconAtlas.onChange = onChange;
}
});
test('a live motion clock reads the date the draw port is given', () => {
const t0 = Date.UTC(2031, 0, 2, 3, 4, 5);
let date = t0 + 4000;
const { part, draw } = drawOver({ date: () => date });
const set = draw.icons({
id: 'gpu:dated',
motionClock: { kind: 'live', delayMs: 1000 },
});
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
const item = icon('a', {
motion: { kind: 'lerp', from: ecef(AT), to, t0, t1: t0 + 10_000 },
});
set.set([item]);
const at = (ms) => iconPosition(item, ms);
assert.ok(
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 3000)) <
0.1,
);
date = t0 + 8000;
assert.ok(
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 7000)) <
0.1,
);
});
+25
View File
@@ -24,6 +24,7 @@ export const CESIUM_CHECKS = new Set([
'camera.trace.commands inside a lookAt frame',
'camera.trace.changed fires by each listener’s threshold',
'camera.moveEnd',
'camera.changed.order',
'camera.controls.holds',
'camera.controls.settings',
'camera.follow',
@@ -74,6 +75,9 @@ export const CESIUM_CHECKS = new Set([
'draw.lines.segments',
'draw.lines.segmentStyles',
'draw.sets.blend',
'draw.sets.recede',
'draw.sets.recede.models',
'draw.afterDispose',
'draw.ids',
'draw.models',
'draw.shapes.lit',
@@ -123,6 +127,7 @@ export const CESIUM_CHECKS = new Set([
'input.clickPick',
'input.lease',
'input.lease.grab',
'input.lease.lost',
'input.lease.press',
'query.heights',
'query.pickBeforeStyles',
@@ -134,12 +139,24 @@ export const CESIUM_CHECKS = new Set([
'quality',
'quality.signals',
'quality.signals.gpuTiming',
'renderer.afterDestroy',
'renderer.afterDestroy.frames',
'renderer.listeners',
'renderer.listenerRules',
'renderer.shape',
'renderer.capture',
'renderer.readPixels',
'renderer.releaseUnused',
'renderer.whenSettled',
'renderer.resize',
'frame.setTargetFps',
'globe.setTerrain',
'globe.setPhotoreal',
'globe.progress',
'effects.setStyleParams',
'effects.bloom',
'effects.sharpen',
'quality.probe',
]);
/** A frame fails the check rather than hang it when frames stop. */
@@ -183,6 +200,7 @@ export function createCesiumHarness({
// own that each frame moves on by 1/60 s: flights then step as the
// reference traces do, frame by frame.
const clocks = new WeakMap();
const containers = new WeakMap();
return {
name,
// A camera controller hears the pointer events sent through `pointer`
@@ -220,8 +238,15 @@ export function createCesiumHarness({
}
};
clocks.set(renderer, clock);
containers.set(renderer, container);
return renderer;
},
resizeContainer: (r, { width, height }) => {
const container = containers.get(r);
if (!container) return;
container.style.width = `${width}px`;
container.style.height = `${height}px`;
},
frame: (r) => {
const clock = clocks.get(r);
if (clock) clock.ms += 1000 / 60;
+33 -28
View File
@@ -10,7 +10,8 @@
* (`alignedAxis` zero), depth test disabled at any distance (drawn on the near plane),
* opaque and translucent passes, horizon culling, and per-row picks whose object is
* `{ id, meta, primitive }` (`primitive.show` hides that one row, as drillPick expects).
* Rows flagged to recede also take the aircraft limb recession, composed with focus.
* Rows flagged to recede (the set's `recede`) also take the limb recession
* (`render/recession.js`), composed with focus.
*
* On WebGL 2 each row also reads its extras ({@link module:iconSet}'s
* `extras`) from a float texture by instance: a screen offset and anchor, a
@@ -37,10 +38,10 @@ import {
MIN_ICON_SLOTS,
NEAR_IMAGE_DEVICE_PX,
} from '../../data/iconAtlas.js';
import {
cameraLimbDistanceM,
getAircraftRecessionParams,
} from '../../data/aircraftRecession.js';
import { recedeFrame, recedeParams } from '../recession.js';
/** The parameters the uniforms hold while the set does not recede. */
const NO_RECEDE = recedeParams({});
const ATTRIBUTE_LOCATIONS = Object.freeze({
corner: 0,
@@ -339,12 +340,18 @@ export class IconSetPrimitive {
renderTime,
requestRender,
cull,
recede,
translucent,
pickObject,
}) {
this.set = set;
this.renderTime = renderTime;
this._cull = cull ?? (() => true);
// The set's `recede`, and the parameters last made from it.
this._recede = recede ?? (() => null);
this._recedeFrom = undefined;
this._recedeResolved = null;
this._recedeFrame = { active: false, limbM: 1, strength: 0 };
this._translucent = translucent ?? (() => false);
this._pickObject = pickObject ?? null;
this._pickPass = 0;
@@ -694,31 +701,19 @@ export class IconSetPrimitive {
this._horizon,
);
const tuning = getAircraftRecessionParams();
const height = camera.positionCartographic?.height;
const limb = cameraLimbDistanceM(height, tuning.earthRadiusM);
const active =
Number.isFinite(height) &&
height > 0 &&
height < tuning.globeViewBlendEndM &&
limb > 0;
let strength = 0;
if (active) {
const g = Math.min(
1,
Math.max(
0,
(height - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM),
),
);
strength = 1 - g * g * (3 - 2 * g);
}
// Rows recede only while the set does (their flag says so); its
// parameters, or the defaults' while it does not, fill the uniforms.
const tuning = this._recedeParams() ?? NO_RECEDE;
const frame = recedeFrame(
camera.positionCartographic?.height,
tuning,
this._recedeFrame,
);
Cesium.Cartesian4.fromElements(
active ? limb : 1,
frame.limbM,
tuning.startLimbRatio,
strength,
active ? 1 : 0,
frame.strength,
frame.active ? 1 : 0,
this._recession,
);
Cesium.Cartesian3.fromElements(
@@ -729,6 +724,16 @@ export class IconSetPrimitive {
);
}
/** The set's `recede` as the parameters it draws with; null: it does not recede. */
_recedeParams() {
const spec = this._recede();
if (spec !== this._recedeFrom) {
this._recedeFrom = spec;
this._recedeResolved = recedeParams(spec);
}
return this._recedeResolved;
}
_createCommands(context) {
this._slotCount = contextIconSlots(context);
this._slotUniform = this._slots.slice(0, this._slotCount);
+8
View File
@@ -835,6 +835,10 @@ export function createCesiumImagery(
/** After each frame: each timed layer's shown frame, once it is drawn. */
function announceFrames() {
if (disposed) return;
// Most frames have no timed layer: the copy below is made only for one.
let timedLayers = false;
for (const record of layers) if (record.timed?.at) timedLayers = true;
if (!timedLayers) return;
for (const record of layers.slice()) {
const timed = record.timed;
// A layer removed by another's listener says nothing.
@@ -858,6 +862,10 @@ export function createCesiumImagery(
return {
add,
list: () => layers.map((record) => record.handle),
/** How many layers the port holds, without listing them. */
get size() {
return layers.length;
},
/** Layers whose providers are still being built, as promises. */
ready: (handles) =>
Promise.allSettled(
+29
View File
@@ -94,6 +94,7 @@ function setup({ stock = true, document = null, takeStock = true } = {}) {
handler.fire(T.LEFT_CLICK, { position: at(x, y) }, modifier);
};
return {
widget,
input,
port: input.port,
handler,
@@ -442,3 +443,31 @@ test('not taking the stock, they stay on the viewer’s handler but while held',
'dispose gives a held one back',
);
});
test("a tool that does not hold off stock clicks leaves the viewer's select and double-click follow running; one that does stops them", async (t) => {
const { inputFor } = await import('../../input/dispatcher.js');
const { claimPointer, releasePointer } =
await import('../../data/inputOwnership.js');
const s = setup();
// The dispatcher over this port, as the application's layers take input.
const dispatcher = inputFor(s.widget, {
query: { pick: () => null, drillPick: () => [] },
});
t.after(() => dispatcher.destroy());
const placed = [];
const lease = claimPointer('placing-tool');
t.after(() => releasePointer(lease));
dispatcher.onPointer('click', () => placed.push('tool'), { lease });
s.press(5, 6);
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
assert.deepEqual(placed, ['tool']);
assert.equal(s.selected.length, 1, 'the stock select ran on its click');
assert.equal(s.followed.length, 1, 'and the double-click follow');
const hold = dispatcher.suppressStockClicks();
s.press(5, 6);
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
hold();
assert.deepEqual(placed, ['tool', 'tool']);
assert.equal(s.selected.length, 1, 'held off: no stock select');
assert.equal(s.followed.length, 1, 'nor follow');
});
+110 -46
View File
@@ -108,20 +108,26 @@ export function cesiumCapabilities(scene, only) {
);
}
/** What `renderOnce` and `capture` reject with once the renderer is destroyed. */
const destroyedError = () => new Error('renderer destroyed');
/**
* @param {object} widget A Cesium `CesiumWidget` or `Viewer`.
* @param {{capabilities: ReadonlySet<string>, credentials?: object,
* cameraController?: Function, now?: () => number,
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number,
* date?: () => number,
* idleFps?: 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).
* 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.
* 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
@@ -134,6 +140,7 @@ export function createCesiumPorts(
credentials = {},
cameraController,
now: clockNow = () => performance.now(),
date = null,
idleFps = 0,
},
) {
@@ -187,23 +194,39 @@ export function createCesiumPorts(
});
liveTick = null;
};
// The camera's `changed`, measured before any `preUpdate` listener moves
// the camera, in a frame that had no clock tick to measure it at.
let measureCameraChanged = null;
const settleUndrawn = () => void settleTick(false);
const tick = () => {
measureCameraChanged?.();
settleTick(false);
// A tick that does not draw settles at its end; one that does, at
// preRender, before this runs.
atEndOfTick(scene, () => void settleTick(false));
atEndOfTick(scene, settleUndrawn);
const now = clockNow();
dt = (now - tickNow) / 1000;
tickNow = now;
frames += 1;
};
// A scene time as epoch ms, worked out again only when the time moves:
// the phases of a frame, and the frames of a paused clock, share one.
let msJulian = null;
let msValue = 0;
// What `setTime` reads a time through.
const scratchDate = new Date(0);
const scratchJulian = new Cesium.JulianDate();
const msOf = (time) => {
if (msJulian && Cesium.JulianDate.equals(msJulian, time)) return msValue;
msValue = Cesium.JulianDate.toDate(time).getTime();
msJulian = Cesium.JulianDate.clone(time, msJulian ?? undefined);
return msValue;
};
const onPhase = (phase) => (_scene, time) => {
if (frameListeners[phase].size === 0) return;
const t = {
frame: frames,
time: Cesium.JulianDate.toDate(
time ?? widget.clock.currentTime,
).getTime(),
time: msOf(time ?? widget.clock.currentTime),
now: tickNow,
dt,
rendering: true,
@@ -245,7 +268,7 @@ export function createCesiumPorts(
let controlled = null;
const cameraTick = (time) => ({
now: tickNow,
time: Cesium.JulianDate.toDate(time ?? widget.clock.currentTime).getTime(),
time: msOf(time ?? widget.clock.currentTime),
});
const removers = [
scene.preUpdate.addEventListener(tick),
@@ -289,24 +312,26 @@ export function createCesiumPorts(
idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
if (idleFps > 0) applyRate();
// Pending one-shot renders; disposal settles them rather than leave them
// Pending one-shot renders; disposal rejects them rather than leave them
// attached to a scene that will not render again.
const pendingRenders = new Set();
/** Resolves after the next drawn frame; rejects after `timeoutMs`, if given. */
/**
* Resolves after the next drawn frame; rejects after `timeoutMs`, if
* given, and once the renderer is destroyed.
*/
function nextPostRender({ timeoutMs } = {}) {
if (disposed) return Promise.resolve();
if (disposed) return Promise.reject(destroyedError());
return new Promise((resolve, reject) => {
let timer;
const settle = (error) => {
off();
clearTimeout(timer);
pendingRenders.delete(done);
pendingRenders.delete(settle);
if (error) reject(error);
else resolve();
};
const done = () => settle();
const off = scene.postRender.addEventListener(done);
pendingRenders.add(done);
const off = scene.postRender.addEventListener(() => settle());
pendingRenders.add(settle);
if (timeoutMs !== undefined)
timer = setTimeout(
() => settle(new Error('renderOnce timed out')),
@@ -380,9 +405,11 @@ export function createCesiumPorts(
*/
setTime(ms) {
const clock = widget.clock;
const time = Cesium.JulianDate.fromDate(new Date(ms));
scratchDate.setTime(ms);
const time = Cesium.JulianDate.fromDate(scratchDate, scratchJulian);
const changed = !Cesium.JulianDate.equals(clock.currentTime, time);
clock.currentTime = time;
// The clock keeps the time it is given; it ignores an equal one.
if (changed) clock.currentTime = Cesium.JulianDate.clone(time);
// In `preUpdate` the frame under way draws at it: Cesium stamps the
// frame with this object next.
if (stampTime) {
@@ -391,7 +418,7 @@ export function createCesiumPorts(
if (liveTick) liveTick.time = ms;
} else if (changed) frame.requestRender('time');
},
time: () => Cesium.JulianDate.toDate(widget.clock.currentTime).getTime(),
time: () => msOf(widget.clock.currentTime),
};
// --- Draw ------------------------------------------------------------------
@@ -401,6 +428,7 @@ export function createCesiumPorts(
report,
capabilities,
requestRender: (reason) => frame.requestRender(reason),
date,
});
const { port: draw, sets, tilesets } = drawPart;
@@ -454,6 +482,7 @@ export function createCesiumPorts(
: {}),
});
const cameraPort = cameraPart.port;
measureCameraChanged = cameraPart.measureChanged ?? null;
const effectsPart = createCesiumEffects(scene, {
capabilities,
frame,
@@ -482,10 +511,36 @@ export function createCesiumPorts(
credentials,
});
async function capture({ type = 'png' } = {}) {
scene.render(widget.clock.currentTime);
return new Promise((resolve) =>
scene.canvas.toBlob(resolve, `image/${type}`),
/**
* Whether the canvas still holds the last presented frame: a context that
* keeps its drawing buffer, once a frame has drawn. Otherwise the frame is
* drawn again to be read.
*/
const frameKept = () =>
rendered > 0 &&
webglContext(scene)?.getContextAttributes?.()?.preserveDrawingBuffer ===
true;
/**
* The last presented frame, encoded: `crop` in CSS pixels, `scale`
* relative to the canvas's CSS size, `quality` for JPEG. Read from the
* canvas as it is where it keeps that frame, so a capture draws nothing.
*/
async function capture({ type = 'png', quality, crop, scale = 1 } = {}) {
if (disposed) throw destroyedError();
if (!frameKept()) scene.render(widget.clock.currentTime);
const out = document.createElement('canvas').getContext('2d');
copyFrame(out, crop, scale);
return new Promise((resolve, reject) =>
out.canvas.toBlob(
(blob) => {
out.canvas.width = out.canvas.height = 0;
if (blob) resolve(blob);
else reject(new Error('the frame could not be encoded'));
},
`image/${type}`,
quality,
),
);
}
@@ -493,33 +548,24 @@ export function createCesiumPorts(
let reader = null;
/**
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
* the canvas's CSS size. Read straight off the canvas: the application
* and conformance widgets keep their drawing buffers, and a read right
* after a draw sees it either way.
* Draws the canvas's frame into the 2D context `into`, `crop` in CSS
* pixels and `scale` relative to the canvas's CSS size, sized to it.
* Returns whether there was a frame to draw.
*/
function readPixels({ crop, scale = 1 } = {}) {
function copyFrame(into, crop, scale = 1) {
const canvas = scene.canvas;
const cssWidth = canvas.clientWidth || canvas.width;
const cssHeight = canvas.clientHeight || canvas.height;
const rect = crop ?? { x: 0, y: 0, width: cssWidth, height: cssHeight };
const width = Math.max(1, Math.round(rect.width * scale));
const height = Math.max(1, Math.round(rect.height * scale));
const made =
reader ??
document
.createElement('canvas')
.getContext('2d', { willReadFrequently: true });
// Disposed ports keep nothing to free.
if (!disposed) reader = made;
made.canvas.width = width;
made.canvas.height = height;
// A canvas with no size has drawn nothing: the read is blank.
if (!canvas.width || !canvas.height)
return made.getImageData(0, 0, width, height);
into.canvas.width = width;
into.canvas.height = height;
// A canvas with no size has drawn nothing: the copy is blank.
if (!canvas.width || !canvas.height) return false;
const sx = canvas.width / cssWidth;
const sy = canvas.height / cssHeight;
made.drawImage(
into.drawImage(
canvas,
rect.x * sx,
rect.y * sy,
@@ -530,7 +576,25 @@ export function createCesiumPorts(
width,
height,
);
return made.getImageData(0, 0, width, height);
return true;
}
/**
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
* the canvas's CSS size. Read straight off the canvas: the application
* and conformance widgets keep their drawing buffers, and a read right
* after a draw sees it either way.
*/
function readPixels({ crop, scale = 1 } = {}) {
const made =
reader ??
document
.createElement('canvas')
.getContext('2d', { willReadFrequently: true });
// Disposed ports keep nothing to free.
if (!disposed) reader = made;
copyFrame(made, crop, scale);
return made.getImageData(0, 0, made.canvas.width, made.canvas.height);
}
// A release asked for whose globe trim waits for the next drawn frame.
@@ -779,7 +843,7 @@ export function createCesiumPorts(
effectsPart.dispose();
globePart.dispose();
qualityPart.dispose();
for (const done of [...pendingRenders]) done();
for (const settle of [...pendingRenders]) settle(destroyedError());
},
};
}
+3 -2
View File
@@ -373,6 +373,7 @@ export function createCesiumQuery({
},
pickRay(x, y) {
const ray = pickRayAt(scene, camera, x, y);
if (!ray) return null;
return { origin: ecef(ray.origin), direction: ecef(ray.direction) };
},
project(position) {
@@ -387,8 +388,8 @@ export function createCesiumQuery({
return s ? { x: s.x, y: s.y } : null;
},
projectMany(source, out) {
const p = new Cesium.Cartesian3();
const s = new Cesium.Cartesian2();
const p = projectedPoint;
const s = projectedWindow;
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
p.x = source[i];
p.y = source[i + 1];
+19
View File
@@ -274,3 +274,22 @@ test('hiding the sets seen through answers as seeing through their items did, ne
ground.dispose();
markers.dispose();
});
test('a canvas with no size has no pick ray: null, not a throw', () => {
const viewer = fakeViewer();
const { scene } = viewer;
scene.mode = Cesium.SceneMode.SCENE3D;
scene.canvas = { clientWidth: 0, clientHeight: 0 };
Object.assign(scene.camera, {
frustum: new Cesium.PerspectiveFrustum({ fov: 1, aspectRatio: 1 }),
directionWC: new Cesium.Cartesian3(-1, 0, 0),
rightWC: new Cesium.Cartesian3(0, 1, 0),
upWC: new Cesium.Cartesian3(0, 0, 1),
});
const query = queryOf(viewer);
assert.equal(query.pickRay(0, 0), null);
scene.canvas = { clientWidth: 100, clientHeight: 100 };
const ray = query.pickRay(50, 50);
assert.deepEqual(ray.origin, { x: 2e7, y: 0, z: 0 });
assert.ok(Math.abs(ray.direction.x + 1) < 1e-9);
});
+2 -1
View File
@@ -35,7 +35,8 @@ export const pointerFeedOf = (renderer) => feeds.get(renderer) ?? null;
/**
* @param {{container: HTMLElement, msaa?: number, capabilities?: Iterable<string>,
* cameraController?: Function, now?: () => number}} options
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number}} options
* `capabilities` limits the renderer to those it lists; `cameraController`
* puts the camera port on that controller (`controlledCamera.js`); `now`
* is the clock its ticks and pointer events read (`performance.now` by