Merge branch 'sameh/renderer-camera-support' into sameh/renderer-seam

# Conflicts:
#	src/render/cesiumAllowList.json
This commit is contained in:
Sameh Khamis committed 2026-11-08 21:23:46 -08:00
commit 6eb9ceef46
33 files changed
+2227 -222

No files matched your search

+129 -7
View File
@@ -10,11 +10,20 @@
* Cesium has one `changed` threshold per camera, where the contract has one
* per listener, so a script that listens at several thresholds is run once
* per threshold and each count is taken from its own run.
*
* A script with `input` steps runs a real `ScreenSpaceCameraController`
* over a stand-in canvas: its pointer and wheel events go to the
* controller's own event handler as the DOM would give them (mouse events,
* Cesium's choice where there are no pointer events), and the controller
* updates each frame where Cesium's scene updates it, after the tweens.
* `Date`, which the controller's inertia reads, runs on the virtual clock
* too.
*/
import * as Cesium from 'cesium';
import {
CAMERA_SCRIPTS,
SCRIPT_VIEWPORT,
usesInput,
} from '../conformance/cameraScripts.js';
import { runCameraScript } from '../conformance/cameraRunner.js';
import { updateCameraChanged } from './internals.js';
@@ -36,23 +45,79 @@ const EASINGS = {
/** One frame of the virtual clock, ms. */
export const FRAME_MS = 1000 / 60;
/** Run `fn` with `performance.now()` reading the virtual clock. */
/** The epoch `Date` reads at virtual time 0. */
const VIRTUAL_EPOCH_MS = Date.UTC(2026, 0, 1);
/** Run `fn` with `performance.now()` and `Date` reading the virtual clock. */
export async function withVirtualClock(fn) {
const real = Object.getOwnPropertyDescriptor(globalThis, 'performance');
const RealDate = globalThis.Date;
const clock = { now: 0 };
Object.defineProperty(globalThis, 'performance', {
configurable: true,
value: { now: () => clock.now, mark() {}, measure() {} },
});
// A function, not a subclass: `Date()` called plainly still gives a
// string, and dates made before stay `instanceof Date`.
function VirtualDate(...args) {
if (!new.target)
return new RealDate(VIRTUAL_EPOCH_MS + clock.now).toString();
return args.length
? new RealDate(...args)
: new RealDate(VIRTUAL_EPOCH_MS + clock.now);
}
Object.setPrototypeOf(VirtualDate, RealDate);
VirtualDate.prototype = RealDate.prototype;
VirtualDate.now = () => VIRTUAL_EPOCH_MS + clock.now;
globalThis.Date = VirtualDate;
try {
return await fn(clock);
} finally {
globalThis.Date = RealDate;
if (real) Object.defineProperty(globalThis, 'performance', real);
}
}
/** A Cesium camera on a scene with no globe, sized as the scripts' viewport. */
export function headlessCamera() {
/**
* A canvas for a controller's event handler: it keeps the listeners the
* handler adds, and `dispatch` calls them as the DOM would. Its root
* events stay on it (`disableRootEvents`), as there is no document; the
* handler still compares its element with one, so a `document` stands in
* while an event is handled, where there is none.
*/
function standInCanvas() {
const listeners = new Map();
return {
clientWidth: SCRIPT_VIEWPORT.width,
clientHeight: SCRIPT_VIEWPORT.height,
disableRootEvents: true,
onwheel: null,
getBoundingClientRect: () => ({ left: 0, top: 0 }),
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, new Set());
listeners.get(type).add(fn);
},
removeEventListener(type, fn) {
listeners.get(type)?.delete(fn);
},
dispatch(type, event) {
const own = typeof globalThis.document === 'undefined';
if (own) globalThis.document = {};
try {
for (const fn of [...(listeners.get(type) ?? [])]) fn(event);
} finally {
if (own) delete globalThis.document;
}
},
};
}
/**
* A Cesium camera on a scene with no globe, sized as the scripts' viewport.
* With `input`, the scene has a real controller over a stand-in canvas.
* @param {{input?: boolean}} [options]
*/
export function headlessCamera({ input = false } = {}) {
const scene = {
canvas: {
clientWidth: SCRIPT_VIEWPORT.width,
@@ -75,9 +140,58 @@ export function headlessCamera() {
const camera = new Cesium.Camera(scene);
scene.camera = camera;
camera.frustum.aspectRatio = SCRIPT_VIEWPORT.width / SCRIPT_VIEWPORT.height;
if (input) {
scene.canvas = standInCanvas();
// What the controller's update reads off a real scene.
scene.verticalExaggeration = 1;
scene.verticalExaggerationRelativeHeight = 0;
scene.screenSpaceCameraController = new Cesium.ScreenSpaceCameraController(
scene,
);
}
return { scene, camera };
}
/**
* Send a script pointer event (`ScriptPointer`, `cameraRunner.js`) to a
* scene made by `headlessCamera({ input: true })`, as the DOM mouse or
* wheel event Cesium reads.
*/
export function dispatchPointer(scene, ev) {
scene.canvas.dispatch(DOM_TYPES[ev.type], domEvent(ev));
}
function domEvent(ev) {
const at = ev.endPosition ?? ev.position;
return {
button: ev.button,
clientX: at.x,
clientY: at.y,
shiftKey: ev.modifiers.shift,
ctrlKey: ev.modifiers.ctrl,
altKey: ev.modifiers.alt,
metaKey: ev.modifiers.meta,
...(ev.wheel
? {
deltaX: 0,
deltaY: ev.wheel.deltaY,
deltaMode: ev.wheel.deltaMode,
DOM_DELTA_PIXEL: 0,
DOM_DELTA_LINE: 1,
DOM_DELTA_PAGE: 2,
}
: {}),
preventDefault() {},
};
}
const DOM_TYPES = {
down: 'mousedown',
move: 'mousemove',
up: 'mouseup',
wheel: 'wheel',
};
const cart = (p) => new Cesium.Cartesian3(p.x, p.y, p.z);
const toEcef = (p) =>
'lon' in p
@@ -101,8 +215,9 @@ function orientationOf(orientation) {
}
/** A driver for {@link runCameraScript} over a headless Cesium camera. */
function cesiumDriver(clock, threshold) {
const { scene, camera } = headlessCamera();
function cesiumDriver(clock, threshold, input = false) {
const { scene, camera } = headlessCamera({ input });
const controller = input ? scene.screenSpaceCameraController : null;
let flying = false;
let changedCount = 0;
camera.percentageChanged = threshold ?? 0.5;
@@ -223,8 +338,14 @@ function cesiumDriver(clock, threshold) {
frame() {
clock.now += FRAME_MS;
scene.tweens.update();
controller?.update();
updateCameraChanged(camera);
},
...(input
? {
pointer: (ev) => dispatchPointer(scene, ev),
}
: {}),
listen: () => () => changedCount,
pose() {
const c = camera.positionCartographic;
@@ -295,14 +416,15 @@ async function recordScript(script) {
const thresholds = script.steps
.filter((step) => step.do === 'listen')
.map((step) => step.threshold);
const input = usesInput(script);
const base = await withVirtualClock((clock) =>
runCameraScript(cesiumDriver(clock, undefined), script),
runCameraScript(cesiumDriver(clock, undefined, input), script),
);
if (!thresholds.length) return base;
const counts = [];
for (const threshold of thresholds) {
const run = await withVirtualClock((clock) =>
runCameraScript(cesiumDriver(clock, threshold), script),
runCameraScript(cesiumDriver(clock, threshold, input), script),
);
const changed = run.records.find((r) => r.kind === 'changed');
counts.push({ threshold, count: changed.value[0].count });
+58 -10
View File
@@ -11,8 +11,14 @@ import {
CAMERA_SCRIPTS,
DEFAULT_TOLERANCE,
runConformance,
usesInput,
} from '../conformance/index.js';
import { FRAME_MS, headlessCamera, withVirtualClock } from './cameraGoldens.js';
import {
FRAME_MS,
dispatchPointer,
headlessCamera,
withVirtualClock,
} from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { cameraOf } from '../rendererOf.js';
@@ -27,14 +33,20 @@ const QUERY_RECORDS = new Set([
/** Commands and records the port does not have yet. */
const MISSING = new Set([]);
const runnable = CAMERA_SCRIPTS.filter((script) =>
script.steps.every(
(step) =>
!MISSING.has(step.do) &&
!MISSING.has(step.record) &&
!QUERY_RECORDS.has(step.record),
),
const runnable = CAMERA_SCRIPTS.filter(
(script) =>
!usesInput(script) &&
script.steps.every(
(step) =>
!MISSING.has(step.do) &&
!MISSING.has(step.record) &&
!QUERY_RECORDS.has(step.record),
),
).map((script) => `camera.trace.${script.name}`);
/** The scripts that drive the camera by pointer and wheel. */
const INPUT_CHECKS = new Set(
CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`),
);
const CHECKS = new Set([
...runnable,
@@ -42,11 +54,11 @@ const CHECKS = new Set([
'camera.controls.settings',
]);
function headlessHarness(clock) {
function headlessHarness(clock, { input = false } = {}) {
return {
name: 'cesium (headless camera)',
async create() {
const { scene } = headlessCamera();
const { scene } = headlessCamera({ input });
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
scene[name] = new Cesium.Event();
scene.primitives = { add() {}, remove() {} };
@@ -65,10 +77,30 @@ function headlessHarness(clock) {
frameScene() {
clock.now += FRAME_MS;
scene.tweens.update();
if (input) scene.screenSpaceCameraController.update();
scene.postUpdate.raiseEvent(scene);
},
scene,
};
},
...(input
? {
cameraInput: true,
// The contract's event back as the DOM's, a wheel in lines: at 40
// px a line, Cesium reads the pixels the script scrolled.
pointer: (r, type, x, y, extra) =>
dispatchPointer(r.scene, {
type,
position: { x, y },
endPosition: extra.endPosition,
button: extra.button ?? 0,
modifiers: extra.modifiers,
...(type === 'wheel'
? { wheel: { deltaY: extra.delta, deltaMode: 1 } }
: {}),
}),
}
: {}),
frame: async (r) => r.frameScene(),
now: () => clock.now,
toEcef: (p) => {
@@ -96,6 +128,22 @@ test('the camera port retraces the reference flights, views and frames', async (
assert.equal(report.passed, CHECKS.size);
});
test('Cesium’s own controls under the camera port retrace the drags and wheels, each wheel sent back in the input port’s lines', async () => {
assert.ok(INPUT_CHECKS.size >= 4, `only ${INPUT_CHECKS.size} input scripts`);
const report = await withVirtualClock((clock) =>
runConformance(headlessHarness(clock, { input: true }), {
only: (id) => INPUT_CHECKS.has(id),
}),
);
assert.deepEqual(
report.results
.filter((r) => r.status !== 'pass')
.map((r) => `${r.id}: ${r.status} ${r.detail}`),
[],
);
assert.equal(report.passed, INPUT_CHECKS.size);
});
test('a cancelled flight has let go before its callbacks, so they can fly again', async () => {
await withVirtualClock(async (clock) => {
const { scene, camera } = headlessCamera();
+206 -10
View File
@@ -323,6 +323,13 @@ export const SETTLE_FRAMES = 30;
export const FEW_LOOSE_LINES = 64;
export const LONG_SETTLE_FRAMES = 300;
/**
* Clamped fills a set draws alone at most, each where it last moved
* (`moveShape`): an upsert that would draw more alone rebuilds the set's
* batches instead, as each costs a primitive and is built in the frame.
*/
export const MOVING_SHAPES = 16;
/** What `syncIcons` did: icons added or removed, or only changed in place. */
const ICONS_CHANGED = 'changed';
const ICONS_KEPT = 'kept';
@@ -446,8 +453,8 @@ export function createCesiumDraw({
return;
}
// Lines that only change how they show or where an undraped one
// runs, and clamped shapes that only show or hide, are changed
// where they are.
// 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) ||
@@ -661,7 +668,12 @@ export function createCesiumDraw({
) {
record.retiring = old;
if (record.own) old.remove(record.own);
} else if (old) scene.primitives.remove(old);
} else if (old) {
scene.primitives.remove(old);
// Shapes drawn alone in the host that goes show again where the host
// still retiring draws them, until the new one is ready.
showRetiringShapes(record);
}
if (!waiting || !groundShown) retire(record);
// Hidden one by one: a hidden collection would not build them.
if (waiting) for (const primitive of waiting) primitive.show = false;
@@ -754,6 +766,8 @@ export function createCesiumDraw({
record.retiring = null;
record.retiringFlows = null;
record.retiringParts = null;
record.retiringShapeParts = null;
record.retiringHiddenShapes = null;
}
/**
@@ -2627,7 +2641,10 @@ export function createCesiumDraw({
* and the lines drawn alone since, hidden in their batches.
*/
function showPending(record) {
for (const part of record.shapeParts?.values() ?? [])
for (const part of record.shapeParts?.values() ?? []) {
// A shape drawn alone since it moved stays hidden in its batch.
if (part.batchHidden && part.batch && !part.batch.isDestroyed())
showOn(part.batch, part.id, false);
if (
part.pendingShow !== undefined &&
part.ground &&
@@ -2636,6 +2653,7 @@ export function createCesiumDraw({
showOn(part.ground, part.id, part.pendingShow);
part.pendingShow = undefined;
}
}
for (const part of record.lineParts?.values() ?? []) {
if (part.batchHidden && part.batch && !part.batch.isDestroyed())
showOn(part.batch, part.id, false);
@@ -2871,6 +2889,9 @@ export function createCesiumDraw({
// Each clamped item as drawn, for upserts that only show or hide it;
// the set keeps them once every one is built.
const parts = new Map();
// The shapes as the host this build replaces draws them, while it
// still draws; a host already retiring keeps its own.
if (!record.retiring) record.retiringShapeParts = record.shapeParts ?? null;
record.shapeParts = null;
for (const item of items) {
if (item.outline)
@@ -3086,29 +3107,198 @@ export function createCesiumDraw({
* Upsert clamped shapes in place, without a rebuild, when every item is
* drawn now and looks the same: then only whether it shows and its
* `meta` change. A ground primitive still building takes the show once
* it is ready (`swapReady`). False, changing nothing, otherwise.
* it is ready (`swapReady`). A plain colour fill whose geometry alone
* changed is drawn alone where it now is (`moveShape`), while no more
* than `MOVING_SHAPES` would be. False, changing nothing, otherwise.
*/
function patchShapes(record, list) {
const parts = record.shapeParts;
if (record.kind !== 'shapes' || !parts) return false;
// Each item's way in: `true` moves it (`moveShape`), else it only
// shows, hides or takes its `meta`.
const moves = [];
for (const item of list) {
const was = parts.get(item.id);
if (!was || !sameLook(was, item)) return false;
if (was.ground?.isDestroyed()) return false;
if (!was) return false;
if (was.ground?.isDestroyed() || was.batch?.isDestroyed()) return false;
if (sameLook(was, item)) {
moves.push(false);
continue;
}
if (!movable(record, was, item)) return false;
moves.push(true);
}
for (const item of list) {
// Drawn alone after this upsert: a few at most, or the batches rebuild.
const alone = new Set();
for (const [id, part] of parts) if (part.solo) alone.add(id);
list.forEach((item, k) => moves[k] && alone.add(item.id));
// Those the host still retiring draws alone count too, until it goes.
let retiringAlone = 0;
if (record.retiring)
for (const part of record.retiringShapeParts?.values() ?? [])
if (part.solo && part.ground && !part.ground.isDestroyed())
retiringAlone += 1;
if (alone.size + retiringAlone > MOVING_SHAPES) return false;
list.forEach((item, k) => {
const was = parts.get(item.id);
if (!was.ground) continue;
if (moves[k]) return moveShape(record, was, item);
if (!was.ground) return;
was.id.meta = item.meta;
const show = item.show !== false;
if (was.ground.ready) {
showOn(was.ground, was.id, show);
was.pendingShow = undefined;
} else if (was.solo) {
// Not yet drawn, it is built again showing as asked.
moveShape(record, was, item);
} else was.pendingShow = show;
}
});
return true;
}
/** Whether a clamped item is a plain colour fill, drawn in a batch. */
const colourFill = (item) =>
item.height === 'clampGround' &&
Boolean(item.fill) &&
!item.outlineOnly &&
!item.outline &&
item.extrudeHeight === undefined &&
(typeof item.fill !== 'object' || Array.isArray(item.fill));
/** How a clamped shape draws, but for its geometry, show and `meta`. */
const placedLookOf = (item) => {
const { show, meta, geometry, ...look } = item;
return plainCopy(look);
};
/**
* Whether a clamped colour fill's upsert moves or reshapes it and nothing
* else: then it is drawn alone where it now is, built in this frame,
* which needs Cesium's terrain heights loaded.
*/
function movable(record, was, item) {
if (!was.id || !was.ground || !colourFill(item)) return false;
if (!colourFill(was.look)) return false;
if (!sameValues(placedLookOf(was.look), placedLookOf(item))) return false;
// Refused geometry (an ellipse radius by camera height) rebuilds, to throw.
const g = item.geometry;
if (
g?.kind === 'ellipse' &&
(typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number')
)
return false;
if (!['polygon', 'ellipse', 'rectangle'].includes(g?.kind)) return false;
return groundSyncs() && typeof record.host?.add === 'function';
}
/**
* Draw a clamped colour fill where it now is, in this frame: on a ground
* primitive of its own built at once, in place of its own one (or of its
* place in its batch, hidden there), as a moved draped line is drawn
* (`moveDraped`). A shape dragged every frame draws every frame, where a
* rebuild would build its batch anew each time and never finish.
*/
function moveShape(record, part, item) {
const host = record.host;
if (part.solo) {
if (part.ground && !part.ground.isDestroyed()) host.remove(part.ground);
} else {
part.batch = part.ground;
part.batchHidden = true;
// Its batch draws on without it, hidden now or once it is ready.
if (part.batch.ready) showOn(part.batch, part.id, false);
}
hideRetiringShape(record, item.id);
record.shapesStill = 0;
part.solo = true;
part.pendingShow = undefined;
part.look = lookOf(item);
part.id.meta = item.meta;
const pickable = record.spec.pickable !== false;
const Ground = pickable
? Cesium.GroundPrimitive
: UnpickableGroundPrimitive;
part.ground = new Ground({
geometryInstances: [
new Cesium.GeometryInstance({
geometry: groundGeometry(item),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
toColor(item.fill),
),
show: new Cesium.ShowGeometryInstanceAttribute(item.show !== false),
},
id: part.id,
}),
],
classificationType: classificationOf(
item.clampTo ?? record.spec.clampTo ?? 'both',
),
allowPicking: pickable,
asynchronous: false,
});
host.add(part.ground);
}
/**
* Hide where the host a set is rebuilding from still draws a clamped
* shape, once it is drawn where it now is: else both would draw (and
* pick) until the rebuild is ready.
*/
function hideRetiringShape(record, id) {
const part = record.retiring && record.retiringShapeParts?.get(id);
const ground = part?.ground;
if (!ground || ground.isDestroyed() || !ground.ready) return;
const hidden = (record.retiringHiddenShapes ??= new Set());
// Only one it drew: one hidden there already stays hidden.
if (!hidden.has(id) && !shownOn(ground, part.id)) return;
showOn(ground, part.id, false);
hidden.add(id);
}
/** Whether the instance under pick id `id` in a ready ground primitive shows. */
const shownOn = (ground, id) =>
ground.getGeometryInstanceAttributes(id).show[0] !== 0;
/**
* Show again the shapes `hideRetiringShape` hid where the retiring host
* draws them: the host that drew them alone is gone before it was ready.
*/
function showRetiringShapes(record) {
const hidden = record.retiringHiddenShapes;
record.retiringHiddenShapes = null;
if (!record.retiring || !hidden) return;
for (const id of hidden) {
const ground = record.retiringShapeParts?.get(id)?.ground;
if (!ground || ground.isDestroyed() || !ground.ready) continue;
// As it is now: one since hidden or removed stays hidden.
const item = record.items.get(id);
if (!item || item.show === false) continue;
showOn(ground, record.retiringShapeParts.get(id).id, true);
}
}
/**
* 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
* batches; the host drawing them alone draws until the rebuild is ready.
*/
function settleShapes(record) {
if (record.pending || !record.shapeParts) return;
let alone = false;
for (const part of record.shapeParts.values())
if (part.solo) {
alone = true;
break;
}
if (!alone) return;
record.shapesStill = (record.shapesStill ?? 0) + 1;
if (record.shapesStill < SETTLE_FRAMES) return;
record.shapesStill = 0;
record.rebuild();
requestRender();
}
/** Whether a hidden clamped item is a plain colour fill `groundFills` builds. */
const hiddenFillBuilds = (item) =>
Boolean(item.fill) &&
@@ -3397,6 +3587,12 @@ export function createCesiumDraw({
record.lineBox = null;
report(error);
}
else if (record.kind === 'shapes')
try {
settleShapes(record);
} catch (error) {
report(error);
}
// Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow.
const playing = quadSets.afterRender(sets.values());
+385
View File
@@ -6,6 +6,7 @@ import {
createCesiumDraw,
FEW_LOOSE_LINES,
LONG_SETTLE_FRAMES,
MOVING_SHAPES,
revealUniform,
SETTLE_FRAMES,
unboundDrawPart,
@@ -6075,3 +6076,387 @@ test('a clamped ellipse filled with a radial rim drapes its material, finely cut
assert.deepEqual([...shows.show], [0]);
set.dispose();
}));
test('a clamped fill that moves or resizes is drawn where it now is in the same frame, once terrain heights are loaded', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'dragged' });
const box = (id, east, extra = {}) => ({
id,
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east, north: 1 },
},
fill: [0.5, 0.9, 1, 0.12],
height: 'clampGround',
...extra,
});
set.set([
box('a', 1),
box('b', 3, {
geometry: {
kind: 'rectangle',
rect: { west: 2, south: 0, east: 3, north: 1 },
},
}),
]);
const host = scene.added[0];
const groundOf = (h) => {
for (let i = 0; i < h.length; i++)
if (h.get(i) instanceof Cesium.GroundPrimitive) return h.get(i);
return null;
};
const batch = groundOf(host);
const shows = new Map();
const attributesOf = (primitive) => {
primitive.getGeometryInstanceAttributes = (id) => {
const key = `${primitive.geometryInstances.length}:${id.id}`;
if (!shows.has(key)) shows.set(key, { show: new Uint8Array([1]) });
return shows.get(key);
};
};
attributesOf(batch);
// Resized while its batch still builds: drawn alone, built at once.
set.upsert([box('a', 1.5, { meta: 'dragged' })]);
assert.equal(scene.added[0], host, 'the set is not rebuilt');
const solo = host.get(host.length - 1);
assert.ok(solo instanceof Cesium.GroundPrimitive);
assert.equal(solo.asynchronous, false, 'built in the frame it is drawn');
const instance = solo.geometryInstances[0];
assert.equal(instance.id.id, 'a');
assert.equal(instance.id.meta, 'dragged');
assert.equal(
instance.id,
batch.geometryInstances.find((i) => i.id.id === 'a').id,
'the same pick id',
);
assert.ok(
Cesium.Rectangle.equalsEpsilon(
instance.geometry._rectangle,
Cesium.Rectangle.fromDegrees(0, 0, 1.5, 1),
1e-12,
),
);
// Its place in the batch is hidden once the batch is ready; the rest draws.
Object.defineProperty(batch, 'ready', { value: true });
frame();
assert.deepEqual([...shows.get('2:a').show], [0], 'hidden in the batch');
assert.equal(shows.get('2:b'), undefined, 'the other untouched');
// Moved again: the one built for it is replaced.
set.upsert([box('a', 2)]);
const again = host.get(host.length - 1);
assert.notEqual(again, solo);
assert.ok(solo.isDestroyed(), 'the old one goes');
// A show change on a ready one is in place; one not yet drawn is built again.
Object.defineProperty(again, 'ready', { value: true });
attributesOf(again);
set.upsert([box('a', 2, { show: false })]);
assert.equal(host.get(host.length - 1), again);
assert.deepEqual([...shows.get('1:a').show], [0]);
// A new colour is a new look: the set rebuilds.
set.upsert([box('a', 2, { fill: [1, 0, 0, 0.5] })]);
assert.notEqual(scene.added.at(-1), host, 'rebuilt');
set.dispose();
assert.equal(scene.added.length, 0);
}));
test('a moved clamped fill is hidden where a rebuild in flight still draws it', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'retiring' });
const box = (id, east, fill = [0.5, 0.9, 1, 0.12]) => ({
id,
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east, north: 1 },
},
fill,
height: 'clampGround',
});
set.set([box('a', 1)]);
const first = scene.added[0];
const groundOf = (h) => {
for (let i = 0; i < h.length; i++)
if (h.get(i) instanceof Cesium.GroundPrimitive) return h.get(i);
return null;
};
const old = groundOf(first);
Object.defineProperty(old, 'ready', { value: true });
frame();
const shown = { show: new Uint8Array([1]) };
old.getGeometryInstanceAttributes = () => shown;
// A new colour rebuilds; the old host draws on until the new is ready.
set.upsert([box('a', 1, [1, 0, 0, 0.5])]);
const second = scene.added.find((p) => p !== first);
assert.ok(
second && scene.added.includes(first),
'both drawn while it builds',
);
// Moved meanwhile: drawn alone in the new host, and gone from the old one.
set.upsert([box('a', 2, [1, 0, 0, 0.5])]);
assert.ok(second.get(second.length - 1).asynchronous === false);
assert.deepEqual(
[...shown.show],
[0],
'hidden where the old host draws it',
);
set.dispose();
}));
/** A clamped colour rectangle from 0° to `east`°, for the move tests. */
const groundBox = (id, east, extra = {}) => ({
id,
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east, north: 1 },
},
fill: [0.5, 0.9, 1, 0.12],
height: 'clampGround',
...extra,
});
/** Every ground primitive in a host built, with a show to read and set. */
const groundsReady = (host) => {
for (let i = 0; i < host.length; i++) {
const ground = host.get(i);
if (!(ground instanceof Cesium.GroundPrimitive)) continue;
Object.defineProperty(ground, 'ready', { value: true });
const show = { show: new Uint8Array([1]) };
ground.getGeometryInstanceAttributes = () => show;
}
};
/** The first ground primitive in a host, or null. */
const firstGround = (host) => {
for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.GroundPrimitive) return host.get(i);
return null;
};
test('moved clamped fills go back into a rebuilt batch once they have been still for a while', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'settling' });
set.set([groundBox('a', 1), groundBox('b', 2)]);
const host = scene.added[0];
groundsReady(host);
frame();
set.upsert([groundBox('a', 1.5)]);
for (let i = 0; i < SETTLE_FRAMES - 1; i++) frame();
// Moved again before it settled: it waits from there.
set.upsert([groundBox('a', 1.6)]);
for (let i = 0; i < SETTLE_FRAMES - 1; i++) frame();
assert.deepEqual(scene.added, [host], 'not rebuilt while it moves');
frame();
assert.equal(scene.added.length, 2, 'rebuilt once still');
const rebuilt = scene.added.find((p) => p !== host);
const instances = [];
for (let i = 0; i < rebuilt.length; i++)
if (rebuilt.get(i) instanceof Cesium.GroundPrimitive)
instances.push(...rebuilt.get(i).geometryInstances);
assert.deepEqual(
instances.map((i) => i.id.id).sort(),
['a', 'b'],
'both in the new batches',
);
assert.ok(
rebuilt.get(0).asynchronous !== false,
'built as a batch, not alone',
);
assert.ok(
Cesium.Rectangle.equalsEpsilon(
instances.find((i) => i.id.id === 'a').geometry._rectangle,
Cesium.Rectangle.fromDegrees(0, 0, 1.6, 1),
1e-12,
),
'where it last moved',
);
// The host drawing it alone draws until the rebuild is ready.
assert.ok(scene.added.includes(host));
for (let i = 0; i < SETTLE_FRAMES * 2; i++) frame();
assert.equal(scene.added.length, 2, 'it settles once');
set.dispose();
}));
test('an upsert that would draw more clamped fills alone than MOVING_SHAPES rebuilds instead', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'many', pickable: false });
const ids = Array.from({ length: MOVING_SHAPES + 1 }, (_, i) => `s${i}`);
set.set(ids.map((id) => groundBox(id, 1)));
const host = scene.added[0];
groundsReady(host);
frame();
// A set that does not pick draws one alone without picking.
set.upsert([groundBox('s0', 1.5)]);
const solo = host.get(host.length - 1);
assert.equal(solo.asynchronous, false);
assert.equal(solo.allowPicking, false);
assert.deepEqual(scene.added, [host]);
set.upsert(ids.slice(1, MOVING_SHAPES).map((id) => groundBox(id, 1.5)));
assert.deepEqual(scene.added, [host], 'MOVING_SHAPES alone at most');
set.upsert([groundBox(ids.at(-1), 1.5)]);
assert.equal(scene.added.length, 2, 'one more rebuilds the set');
set.dispose();
}));
test('a clamped fill moved before terrain heights load rebuilds its set', () => {
const heights = Cesium.ApproximateTerrainHeights;
if (heights.initialized) return;
const { scene, draw } = drawOver();
const set = draw.shapes({ id: 'no-heights' });
set.set([groundBox('a', 1)]);
const host = scene.added[0];
set.upsert([groundBox('a', 1.5)]);
assert.ok(
!scene.added.includes(host) || scene.added.length > 1,
'rebuilt, not drawn alone',
);
set.dispose();
});
test('a moved clamped fill shows again where the retiring host draws it when the host drawing it alone goes unbuilt', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'twice' });
set.set([groundBox('a', 1)]);
const first = scene.added[0];
const old = firstGround(first);
Object.defineProperty(old, 'ready', { value: true });
frame();
const shown = { show: new Uint8Array([1]) };
old.getGeometryInstanceAttributes = () => shown;
set.upsert([groundBox('a', 1, { fill: [1, 0, 0, 0.5] })]);
set.upsert([groundBox('a', 2, { fill: [1, 0, 0, 0.5] })]);
assert.deepEqual([...shown.show], [0], 'hidden while drawn alone');
// A second rebuild drops the host drawing it alone, still building.
set.upsert([groundBox('a', 2, { fill: [0, 1, 0, 0.5] })]);
assert.ok(scene.added.includes(first), 'the retiring host draws on');
assert.equal(scene.added.length, 2);
assert.deepEqual([...shown.show], [1], 'drawn where it was, not gone');
set.dispose();
}));
/** Ground primitives in a host built, each instance's show kept by id. */
const groundsReadyById = (host, shows = new Map()) => {
for (let i = 0; i < host.length; i++) {
const ground = host.get(i);
if (!(ground instanceof Cesium.GroundPrimitive)) continue;
Object.defineProperty(ground, 'ready', { value: true });
ground.getGeometryInstanceAttributes = (id) => {
if (!shows.has(id.id)) {
const shown = ground.geometryInstances.find((g) => g.id === id)
?.attributes.show.value[0];
shows.set(id.id, { show: new Uint8Array([shown ?? 1]) });
}
return shows.get(id.id);
};
}
return shows;
};
test('a hidden clamped fill moved while its set rebuilds stays hidden when a second rebuild comes', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'hidden-twice' });
set.set([
groundBox('a', 1, { show: false }),
groundBox('b', 1, {
geometry: {
kind: 'rectangle',
rect: { west: 5, south: 0, east: 6, north: 1 },
},
}),
]);
const first = scene.added[0];
const shows = groundsReadyById(first);
frame();
const b = (fill) =>
groundBox('b', 1, {
geometry: {
kind: 'rectangle',
rect: { west: 5, south: 0, east: 6, north: 1 },
},
fill,
});
set.upsert([b([1, 0, 0, 0.5])]);
set.upsert([groundBox('a', 2, { show: false })]);
set.upsert([b([0, 1, 0, 0.5])]);
assert.ok(scene.added.includes(first), 'the retiring host draws on');
assert.deepEqual([...shows.get('a').show], [0], 'a stays hidden');
set.dispose();
}));
test('clamped fills drawn alone by a host still retiring count toward MOVING_SHAPES', () =>
withTerrainHeights(() => {
const { scene, draw, frame } = drawOver();
const set = draw.shapes({ id: 'cap-retiring' });
const ids = Array.from(
{ length: MOVING_SHAPES * 2 + 1 },
(_, i) => `s${i}`,
);
set.set(ids.map((id) => groundBox(id, 1)));
const first = scene.added[0];
groundsReady(first);
frame();
// Half the cap moved, then a rebuild while they are drawn alone.
set.upsert(ids.slice(0, MOVING_SHAPES).map((id) => groundBox(id, 1.5)));
set.upsert([groundBox(ids.at(-1), 1, { fill: [1, 0, 0, 0.5] })]);
assert.equal(scene.added.length, 2, 'rebuilding, the old host retiring');
const second = scene.added.find((p) => p !== first);
const before = second.length;
// Others moved while it builds: over the cap counted with the retiring
// host's, so the set rebuilds rather than draw them alone.
set.upsert([groundBox(ids[MOVING_SHAPES], 1.5)]);
assert.ok(
!scene.added.includes(second) || second.length === before,
'nothing more drawn alone',
);
set.dispose();
}));
test('the recent imagery box preview drags its ground fill and dashed edge frame by frame on a viewer of its own', async () => {
const { createImageryBoxPreview } =
await import('../../layers/recentImagery/rendering.js');
const destroyed = withImageClasses(() =>
withTerrainHeights(() => {
const scene = fakeScene();
const viewer = { scene, isDestroyed: () => false };
let box = { west: -98, south: 30, east: -97.95, north: 30.05 };
const preview = createImageryBoxPreview(viewer, () => box);
preview.setVisible(true);
const hosts = scene.added.slice();
assert.equal(hosts.length, 2, 'a fill set and an edge set');
const groundIn = (host) => {
for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.GroundPrimitive) return host.get(i);
return null;
};
const fillHost = hosts.find((h) => groundIn(h));
assert.ok(fillHost, 'the fill is a ground primitive');
// Each move of the drag is drawn in the frame it is made, in place.
for (const east of [-97.9, -97.85, -97.8]) {
box = { ...box, east };
preview.changed();
const solo = fillHost.get(fillHost.length - 1);
assert.ok(solo instanceof Cesium.GroundPrimitive);
assert.equal(solo.asynchronous, false);
assert.ok(
Cesium.Rectangle.equalsEpsilon(
solo.geometryInstances[0].geometry._rectangle,
Cesium.Rectangle.fromDegrees(-98, 30, east, 30.05),
1e-12,
),
);
}
assert.deepEqual(scene.added, hosts, 'no set rebuilt');
const edgeHost = hosts.find((h) => h !== fillHost);
const edge = edgeHost.get(edgeHost.length - 1);
assert.ok(edge instanceof Cesium.GroundPolylinePrimitive);
assert.equal(edge.asynchronous, false);
assert.equal(edge.appearance.material.type, 'PolylineDash');
return preview.destroy().then(() => scene.added.length);
}),
);
assert.equal(await destroyed, 0, 'both sets let go');
});
+8 -16
View File
@@ -7,9 +7,9 @@
*
* Imagery drapes on the globe, or on the drawn base tileset: the photoreal
* tileset this port loaded, or one the application's map stack marked as
* its base (`markBaseTileset`) while it still loads its own. Where each
* layer drapes follows what is drawn, looked at every frame, so a base
* switched outside the port moves the layers with it.
* its base (`markBaseTileset`, `../baseTilesets.js`) while it still loads
* its own. Where each layer drapes follows what is drawn, looked at every
* frame, so a base switched outside the port moves the layers with it.
*
* The sky reads the scene as it was set up and writes through to it; what
* the scene has no part for (stars without a sky box, say) is kept as set.
@@ -17,21 +17,13 @@
import * as Cesium from 'cesium';
import { loadPhotorealisticTileset } from '../../maps/google3d.js';
import { provideUnboundGlobe } from '../rendererOf.js';
import { isBaseTileset, markBaseTileset } from '../baseTilesets.js';
import { listenerList, uncaught } from './common.js';
import { createCesiumImagery } from './imagery.js';
/** Tilesets the application's map stack draws as its base. */
const baseTilesets = new WeakSet();
/**
* Mark a tileset as a base the application draws outside the port, so
* imagery drapes on it while it is shown. For code that still loads its
* own base; the port's own photoreal tileset needs no mark.
* @param {object} tileset Cesium `Cesium3DTileset`.
*/
export function markBaseTileset(tileset) {
if (tileset && typeof tileset === 'object') baseTilesets.add(tileset);
}
// The base marks live outside the adapter, so code that is not Cesium's can
// mark a base; they are re-exported here for the code that still is.
export { markBaseTileset };
/** Ion's world terrain asset. */
const WORLD_TERRAIN_ASSET = 1;
@@ -195,7 +187,7 @@ export function createCesiumGlobe(
if (photoreal && !photoreal.isDestroyed() && photoreal.show)
return photoreal;
for (const tileset of tilesets())
if (baseTilesets.has(tileset) && tileset.show && !tileset.isDestroyed())
if (isBaseTileset(tileset) && tileset.show && !tileset.isDestroyed())
return tileset;
return null;
}
+3 -9
View File
@@ -26,6 +26,7 @@ import * as Cesium from 'cesium';
import { createInputRouter } from '../input/router.js';
import { acquireCameraInput } from './cameraInput.js';
import { installTrackpadPinchZoom } from './ctrlWheelZoom.js';
import { wheelLines } from '../input/wheel.js';
const T = Cesium.ScreenSpaceEventType;
const MODIFIERS = [
@@ -52,8 +53,6 @@ const DOM_EVENTS = [
'touchcancel',
'dblclick',
];
/** A wheel notch scrolls 100 px in Chrome, which it counts as three lines. */
const PX_PER_LINE = 100 / 3;
/** A drill is run at least this deep and sliced, so asks share one pass. */
const DRILL_DEPTH = 16;
const NO_MODIFIERS = Object.freeze({
@@ -440,16 +439,11 @@ export function createCesiumInput(
const onWheel = (event) => {
const rect = canvas.getBoundingClientRect?.() ?? { left: 0, top: 0 };
const lines =
event.deltaMode === 1
? event.deltaY
: event.deltaMode === 2
? (event.deltaY * (canvas.clientHeight || 0)) / PX_PER_LINE
: event.deltaY / PX_PER_LINE;
deliver(
'wheel',
{ x: event.clientX - rect.left, y: event.clientY - rect.top },
{ delta: lines },
// Lines as the reference counts them (`../input/wheel.js`).
{ delta: wheelLines(event) },
event,
);
};
+10 -2
View File
@@ -240,7 +240,7 @@ test('ctrlWheelZoom installs the zoom and takes it out again', () => {
assert.deepEqual(s.wheelZoom, ['on', 'off', 'on', 'off']);
});
test('wheel is in lines, where the pointer is over the canvas', () => {
test('wheel is in lines as the reference counts them, where the pointer is over the canvas', () => {
const s = setup();
const wheels = [];
s.port.on('wheel', (ev) =>
@@ -259,10 +259,18 @@ test('wheel is in lines, where the pointer is over the canvas', () => {
deltaY: -3,
deltaMode: 1,
});
s.canvas.dispatch('wheel', {
clientX: 10,
clientY: 20,
deltaY: 1,
deltaMode: 2,
});
assert.deepEqual(wheels[0][0], { x: 100, y: 200 });
assert.equal(wheels[0][1], 3);
// 40 px a line, 3 lines a page: Cesium's own 40 px a line and 120 a page.
assert.equal(wheels[0][1], 2.5);
assert.equal(wheels[0][2].ctrl, true);
assert.equal(wheels[1][1], -3);
assert.equal(wheels[2][1], 3);
});
test('a pinch is the scale since the last event, at its midpoint', () => {