feat(render): the Cesium renderer passes every conformance check a page can run

- Cesium's own tweens (its flights) step on the renderer's clock, so the
  flight traces compare frame by frame; dispose gives the scene its own
  clock back.
- moveStart and moveEnd are measured each tick on that clock, by the
  shared move detection, a change of the field of view or aspect
  included; Cesium's own events timed them by the system clock.
- A follow of a drawn item tracks where the draw port draws it.
- Pick rays are summed from the eye's axes: Cesium's lose about 1e-9 of
  direction at a near plane of 0.1 m. Ellipsoid picks and the view
  rectangle use them; a canvas with no size has none, as in Cesium.
- The harness always runs the virtual clock and claims 120 checks: 119
  pass on the page and query.heights skips. The five pointer traces
  need a camera controller there, and are recorded from Cesium's own
  controller in Node.
- The package boundaries list the cesium plugin export and the modules
  its groups now import.
This commit is contained in:
Sameh Khamis committed 2026-11-12 14:59:45 -08:00
1 parent 720932e1f9
commit e9085e8df3
13 files changed
+545 -95

No files matched your search

+10 -3
View File
@@ -34,13 +34,15 @@ const angleDelta = (a, b) => {
};
/**
* Whether two world views are the same: the same position, and directions
* and ups whose dot products are each one's own.
* Whether two world views are the same: the same position, directions and
* ups whose dot products are each one's own, and the same `lens` (a
* renderer's key for its field of view and aspect, where it gives one).
*/
function sameView(a, b) {
return (
a &&
b &&
a.lens === b.lens &&
distance(a.position, b.position) === 0 &&
dot(a.direction, b.direction) === dot(a.direction, a.direction) &&
dot(a.up, b.up) === dot(a.up, a.up)
@@ -152,7 +154,12 @@ export function createCameraEvents({
*/
function stepMoveDetection(now) {
const v = world();
const current = { position: v.position, direction: v.direction, up: v.up };
const current = {
position: v.position,
direction: v.direction,
up: v.up,
lens: v.lens,
};
const changed = lastView && !sameView(lastView, current);
lastView = current;
if (changed) {
+70 -20
View File
@@ -7,7 +7,14 @@
*/
import * as Cesium from 'cesium';
import { createCameraEvents } from '../camera/events.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import {
listenerList,
pickEllipsoidAt,
sameEye,
toCartesian,
uncaught,
} from './common.js';
import { computeViewRectangle } from '../stub/viewRectangle.js';
import { cameraFlightActive } from './internals.js';
import { createCesiumFollow } from './follow.js';
import { createCesiumControls } from './cameraControls.js';
@@ -73,13 +80,18 @@ function matrixArray(matrix) {
/**
* @param {{scene: object, camera: object, report: (error: unknown) => void,
* widget?: object, capabilities?: ReadonlySet<string>}} options `scene`
* 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
* `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).
* @returns {{port: import('../contract/camera').CameraPort, dispose: () => void}}
* 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).
*/
export function createCesiumCamera({
scene,
@@ -87,15 +99,40 @@ export function createCesiumCamera({
report,
widget,
capabilities,
now = () => performance.now(),
itemPosition,
}) {
const removers = [];
// Camera events: Cesium's own moveStart and moveEnd (500 ms after the
// last change, never while following), and `changed` measured per
// listener on every tick, where Cesium measures its single threshold
// (`camera.percentageChanged`, which this leaves as it is for everyone
// else listening to Cesium's own event).
let lastWorld = 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`, never
// while following), 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.
const cameraEvents = createCameraEvents({
pose: () => cameraPort.pose(),
world: () => {
// Copies (Cesium updates its own vectors in place), and the last one
// again while Cesium's stand within rounding of it.
const f = camera.frustum;
const current = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction: Cesium.Cartesian3.clone(camera.directionWC),
up: Cesium.Cartesian3.clone(camera.upWC),
// A new field of view or aspect (a resize) is a move too, as
// Cesium's own camera events count it.
lens: `${f.fovy} ${f.aspectRatio}`,
};
if (
!lastWorld ||
current.lens !== lastWorld.lens ||
!sameEye(current, lastWorld)
)
lastWorld = current;
return lastWorld;
},
following: () => Boolean(following?.followed),
report,
thresholds: capabilities?.has('cameraChangeThreshold') ?? true,
});
@@ -103,9 +140,8 @@ export function createCesiumCamera({
scene.postUpdate.addEventListener(() => {
applyFov();
cameraEvents.stepChanged();
cameraEvents.stepMoveDetection(now());
}),
camera.moveStart.addEventListener(() => cameraEvents.emit('moveStart')),
camera.moveEnd.addEventListener(() => cameraEvents.emit('moveEnd')),
);
const following = widget?.trackedEntityChanged
@@ -114,6 +150,7 @@ export function createCesiumCamera({
scene,
camera,
onChanged: () => cameraEvents.emit('followChanged'),
itemPosition,
})
: null;
@@ -366,16 +403,28 @@ export function createCesiumCamera({
projection: matrixArray(camera.frustum.projectionMatrix),
};
},
// Cesium's own corner picks (`computeViewRectangle`), on rays that
// keep their precision (`pickRayAt`).
viewRectangle() {
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
if (!rect) return null;
const deg = Cesium.Math.toDegrees;
return {
west: deg(rect.west),
south: deg(rect.south),
east: deg(rect.east),
north: deg(rect.north),
};
if (scene.mode !== Cesium.SceneMode.SCENE3D) {
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
if (!rect) return null;
const deg = Cesium.Math.toDegrees;
return {
west: deg(rect.west),
south: deg(rect.south),
east: deg(rect.east),
north: deg(rect.north),
};
}
return computeViewRectangle(
cameraPort.pose(),
{
width: scene.canvas.clientWidth,
height: scene.canvas.clientHeight,
},
(x, y) => pickEllipsoidAt(scene, camera, x, y) ?? null,
);
},
pose() {
// An unmoved camera answers from the pose last read: a frame reads
@@ -531,6 +580,7 @@ export function createCesiumCamera({
return {
port: cameraPort,
emit: (event) => cameraEvents.emit(event),
dispose() {
following?.dispose();
controlsPart.dispose();
+91
View File
@@ -93,3 +93,94 @@ export function createBlobUrls(Registry = globalThis.FinalizationRegistry) {
/** A blob's object URL: the same one every time it is drawn. */
export const blobUrl = createBlobUrls();
/**
* How far Cesium's camera may stand from an eye and still be that eye: its
* world vectors are derived again in floating point (a unit vector's
* component off by 2e-16 now and then), and a camera that counts any
* difference as a move would put off `moveEnd` with nothing moving. Metres
* per metre of distance from the Earth's centre, and the cosine's shortfall
* from 1 for the unit vectors.
*/
export const ROUNDING = 1e-12;
/** Whether Cesium's `world` vectors are the `written` eye, up to rounding. */
export function sameEye(world, written) {
const p = world.position;
const q = written.position;
const scale = Math.max(1, Math.hypot(q.x, q.y, q.z));
if (Math.hypot(p.x - q.x, p.y - q.y, p.z - q.z) > ROUNDING * scale)
return false;
for (const key of ['direction', 'up']) {
const a = world[key];
const b = written[key];
if (a.x * b.x + a.y * b.y + a.z * b.z < 1 - ROUNDING) return false;
}
return true;
}
/**
* The pick ray through a canvas point (CSS pixels), as Cesium's
* `camera.getPickRay` gives it in 3D, without its loss of precision: Cesium
* adds the near-plane offset to the eye's position (some 6e6 m from the
* Earth's centre) and takes the position off again, which leaves the
* direction off by about 1e-9 at a near plane of 0.1 m. Other frustums go
* to Cesium's own.
* @param {object} scene
* @param {object} camera
* @param {number} x
* @param {number} y
* @returns {Cesium.Ray|undefined} Undefined on a canvas with no size.
*/
export function pickRayAt(scene, camera, x, y) {
const frustum = camera.frustum;
if (
scene.mode !== Cesium.SceneMode.SCENE3D ||
!(frustum instanceof Cesium.PerspectiveFrustum) ||
frustum.xOffset ||
frustum.yOffset
)
return camera.getPickRay(new Cesium.Cartesian2(x, y));
const width = scene.canvas.clientWidth;
const height = scene.canvas.clientHeight;
// A canvas with no size (hidden, not laid out yet) has no rays, as in
// Cesium.
if (!(width > 0 && height > 0)) return undefined;
const tanPhi = Math.tan(frustum.fovy * 0.5);
const tanTheta = frustum.aspectRatio * tanPhi;
const nx = (2 / width) * x - 1;
const ny = (2 / height) * (height - y) - 1;
const d = camera.directionWC;
const r = camera.rightWC;
const u = camera.upWC;
const a = nx * tanTheta;
const b = ny * tanPhi;
const direction = Cesium.Cartesian3.normalize(
new Cesium.Cartesian3(
d.x + r.x * a + u.x * b,
d.y + r.y * a + u.y * b,
d.z + r.z * a + u.z * b,
),
new Cesium.Cartesian3(),
);
return new Cesium.Ray(Cesium.Cartesian3.clone(camera.positionWC), direction);
}
/**
* Where the pick ray through a canvas point meets the WGS84 ellipsoid, as
* Cesium's `camera.pickEllipsoid` finds it in 3D, on `pickRayAt`'s ray.
* @returns {Cesium.Cartesian3|undefined}
*/
export function pickEllipsoidAt(scene, camera, x, y) {
if (scene.mode !== Cesium.SceneMode.SCENE3D)
return camera.pickEllipsoid(new Cesium.Cartesian2(x, y));
const ray = pickRayAt(scene, camera, x, y);
if (!ray) return undefined;
const hit = Cesium.IntersectionTests.rayEllipsoid(
ray,
Cesium.Ellipsoid.WGS84,
);
if (!hit) return undefined;
const t = hit.start > 0 ? hit.start : hit.stop;
return Cesium.Ray.getPoint(ray, t, new Cesium.Cartesian3());
}
+71 -1
View File
@@ -1,6 +1,12 @@
import assert from 'node:assert/strict';
import test, { mock } from 'node:test';
import { blobUrl, createBlobUrls } from './common.js';
import * as Cesium from 'cesium';
import {
blobUrl,
createBlobUrls,
pickEllipsoidAt,
pickRayAt,
} from './common.js';
test('a blob keeps one object URL, revoked only once the blob is collected', () => {
const made = [];
@@ -62,3 +68,67 @@ test('a blob’s URL is not revoked by time: one undrawn for an hour still loads
revoke.mock.restore();
}
});
/** A Cesium camera over a 1280 × 720 canvas, 600 m over Austin. */
function cityCamera(near) {
const scene = {
canvas: { clientWidth: 1280, clientHeight: 720 },
drawingBufferWidth: 1280,
drawingBufferHeight: 720,
mapProjection: new Cesium.GeographicProjection(),
mode: Cesium.SceneMode.SCENE3D,
};
const camera = new Cesium.Camera(scene);
camera.frustum.aspectRatio = 1280 / 720;
camera.frustum.near = near;
camera.setView({
destination: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 600),
orientation: { heading: 0.3, pitch: -0.6, roll: 0 },
});
scene.camera = camera;
return { scene, camera };
}
const gap = (a, b) => Cesium.Cartesian3.distance(a, b);
test('the centre ray is the eye’s direction, where Cesium’s own is off by its position’s rounding', () => {
const { scene, camera } = cityCamera(0.1);
const ray = pickRayAt(scene, camera, 640, 360);
assert.ok(gap(ray.direction, camera.directionWC) < 1e-15);
assert.deepEqual(ray.origin, camera.positionWC);
// Cesium's: near-plane point minus a position some 6e6 m out.
const cesium = camera.getPickRay(new Cesium.Cartesian2(640, 360));
assert.ok(gap(cesium.direction, camera.directionWC) > 1e-10);
});
test('off centre, the ray is Cesium’s up to that rounding', () => {
const { scene, camera } = cityCamera(1);
for (const [x, y] of [
[10, 10],
[1270, 710],
[320, 540],
]) {
const ours = pickRayAt(scene, camera, x, y).direction;
const cesium = camera.getPickRay(new Cesium.Cartesian2(x, y)).direction;
assert.ok(gap(ours, cesium) < 5e-9, `${x},${y}`);
}
});
test('the ellipsoid pick is where that ray meets WGS84, and none off the globe', () => {
const { scene, camera } = cityCamera(0.1);
const hit = pickEllipsoidAt(scene, camera, 640, 600);
const cesium = camera.pickEllipsoid(new Cesium.Cartesian2(640, 600));
assert.ok(gap(hit, cesium) < 1e-3);
const carto = Cesium.Cartographic.fromCartesian(hit);
assert.ok(Math.abs(carto.height) < 1e-6);
// Looking up, over the horizon.
camera.setView({ orientation: { heading: 0, pitch: 0.5, roll: 0 } });
assert.equal(pickEllipsoidAt(scene, camera, 640, 100), undefined);
});
test('a canvas with no size has no ray and no ellipsoid pick, as in Cesium', () => {
const { scene, camera } = cityCamera(0.1);
scene.canvas = { clientWidth: 0, clientHeight: 0 };
assert.equal(pickRayAt(scene, camera, 0, 0), undefined);
assert.equal(pickEllipsoidAt(scene, camera, 0, 0), undefined);
});
+1 -25
View File
@@ -27,6 +27,7 @@
*/
import * as Cesium from 'cesium';
import { acquireCameraInput } from './cameraInput.js';
import { sameEye } from './common.js';
/**
* The input port's events for a controller made before the port: listeners
@@ -57,31 +58,6 @@ function inputRelay() {
const plain = (v) => ({ x: v.x, y: v.y, z: v.z });
/**
* How far Cesium's camera may stand from the eye last written and still be
* that eye: its world vectors are derived again in floating point (a unit
* vector's component off by 2e-16 now and then), and the controller counts
* any difference as a move, which would put off `moveEnd` with nothing
* moving. Metres per metre of distance from the Earth's centre, and the
* cosine's shortfall from 1 for the unit vectors.
*/
const ROUNDING = 1e-12;
/** Whether Cesium's `world` vectors are the `written` eye, up to rounding. */
function sameEye(world, written) {
const p = world.position;
const q = written.position;
const scale = Math.max(1, Math.hypot(q.x, q.y, q.z));
if (Math.hypot(p.x - q.x, p.y - q.y, p.z - q.z) > ROUNDING * scale)
return false;
for (const key of ['direction', 'up']) {
const a = world[key];
const b = written[key];
if (a.x * b.x + a.y * b.y + a.z * b.z < 1 - ROUNDING) return false;
}
return true;
}
/**
* @param {{
* scene: object,
+21 -6
View File
@@ -189,11 +189,26 @@ function startOffset(target, viewFrom, result) {
/**
* @param {{widget: object, scene: object, camera: object,
* onChanged: () => void}} options `widget` is the Viewer or CesiumWidget
* whose `trackedEntity` this follows with; `onChanged` runs on every
* change of what it tracks.
* onChanged: () => void,
* itemPosition?: (item: {set: string, id: string|number},
* time: Cesium.JulianDate) => object|null}} options `widget` is the
* Viewer or CesiumWidget whose `trackedEntity` this follows with;
* `onChanged` runs on every change of what it tracks; `itemPosition`,
* where the draw port draws an item at a scene time (null when it does
* not), which a target naming a drawn `item` is followed at.
*/
export function createCesiumFollow({ widget, scene, camera, onChanged }) {
export function createCesiumFollow({
widget,
scene,
camera,
onChanged,
itemPosition,
}) {
/** Where a target is at a scene time: its drawn item, else `position`. */
const positionOf = (target, time) =>
(target.item && itemPosition?.(target.item, time)) ??
target.position(msOf(time));
/** @type {null | {target: object, helper: object, framed: boolean,
* attempts: number, previous: Cesium.Cartesian3, releaseZoom: () => void}} */
let current = null;
@@ -238,7 +253,7 @@ export function createCesiumFollow({ widget, scene, camera, onChanged }) {
function helperFor(target) {
const helper = widget.entities.add({
position: new Cesium.CallbackProperty((time, result) => {
const p = target.position(msOf(time));
const p = positionOf(target, time);
return p ? Cesium.Cartesian3.fromElements(p.x, p.y, p.z, result) : p;
}, false),
// EntityView tracks an entity only once its bounding sphere is
@@ -289,7 +304,7 @@ export function createCesiumFollow({ widget, scene, camera, onChanged }) {
const { target } = entry;
entry.attempts += 1;
const time = widget.clock.currentTime;
const at = target.position(msOf(time));
const at = positionOf(target, time);
if (target.frame !== 'enu') {
// Framed once Cesium's EntityView has taken the helper on: until
// then the camera may still ride the previous tracking's frame.
+27 -20
View File
@@ -6,9 +6,10 @@
* `CESIUM_CHECKS` lists the checks of the ports the Cesium renderer has.
* Each migration adds the checks of the members it brings, so the suite
* shows how far the renderer is through the contract; every other check is
* left out of the run rather than failed. Camera flights are checked in
* Node instead (`cameraPort.test.mjs`): a page's frames come on the real
* clock at the display's rate, where the reference traces step 1/60 s.
* left out of the run rather than failed. Each renderer's clock moves on
* 1/60 s a frame, as the reference traces step, whatever the display's
* rate. The pointer traces need a camera controller: without one, they are
* checked in Node (`cameraGoldens.js` records them from Cesium's own).
*/
import { DEFAULT_TOLERANCE } from '../conformance/index.js';
import { toEcef } from '../stub/math.js';
@@ -32,6 +33,16 @@ export const CESIUM_CHECKS = new Set([
'camera.flight.callbacks',
'camera.onCommand',
'camera.rect',
'camera.trace.flyTo from orbit, default orientation and duration',
'camera.trace.flyTo with duration and orientation',
'camera.trace.flyTo with a height cap, pitch adjustment and named easings',
'camera.trace.rectangle destinations',
'camera.trace.flyToBounds default offset and explicit offset',
'camera.trace.flyToBounds easing',
'camera.trace.flyTo sineInOut',
'camera.trace.view rectangles',
'camera.trace.projection, picks and the horizon',
'camera.followItem',
'camera.trace.flyTo with a duration of 0 completes inside the call',
'camera.trace.flyTo where the camera already is completes inside the call',
'camera.setView.exact',
@@ -116,10 +127,12 @@ export const CESIUM_CHECKS = new Set([
'query.projectMany',
'query.rays',
'query.withoutCapability',
'query.occlusionTest',
'quality',
'quality.signals',
'quality.signals.gpuTiming',
'renderer.listeners',
'renderer.listenerRules',
'renderer.shape',
'renderer.readPixels',
'renderer.releaseUnused',
@@ -163,12 +176,10 @@ export function createCesiumHarness({
missingModel,
cameraController,
} = {}) {
// With a camera controller, each renderer's ticks read a clock of its
// own that each frame moves on by 1/60 s: the controller's flights then
// step as the reference traces do, frame by frame (Cesium's own flights
// keep Cesium's clock, so they are checked in Node instead).
// Each renderer's ticks, tweens and camera events read a clock of its
// 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 virtual = Boolean(cameraController);
return {
name,
// A camera controller hears the pointer events sent through `pointer`
@@ -185,7 +196,7 @@ export function createCesiumHarness({
container,
capabilities,
...(cameraController ? { cameraController } : {}),
...(virtual ? { now: () => clock.ms } : {}),
now: () => clock.ms,
});
} catch (error) {
container.remove();
@@ -208,24 +219,20 @@ export function createCesiumHarness({
clocks.set(renderer, clock);
return renderer;
},
frame: virtual
? (r) => {
const clock = clocks.get(r);
if (clock) clock.ms += 1000 / 60;
return nextFrame();
}
: nextFrame,
frame: (r) => {
const clock = clocks.get(r);
if (clock) clock.ms += 1000 / 60;
return nextFrame();
},
// Events as the renderer's handler delivers them: the checks send ones
// no real pointer can (a click with no press), so not DOM events.
pointer: (r, type, x, y, extra) => pointerFeedOf(r)(type, x, y, extra),
now: virtual
? (r) => clocks.get(r)?.ms ?? performance.now()
: () => performance.now(),
now: (r) => clocks.get(r)?.ms ?? performance.now(),
// What a live motion clock reads.
wallTime: () => Date.now(),
toEcef,
tolerance: DEFAULT_TOLERANCE,
flightPaths: virtual ? 'trace' : 'endpoints',
flightPaths: 'trace',
...(model ? { assets: { model, missingModel } } : {}),
};
}
+17
View File
@@ -132,6 +132,13 @@ export function createCesiumPorts(
) {
const scene = widget.scene;
const camera = scene.camera;
// Cesium's own tweens (its flights) step on the same clock as the ticks:
// a scene's tweens read the system clock unless given a time.
const tweens = scene.tweens;
const updateTweens = tweens?.update;
const clockedTweens = (time) =>
updateTweens.call(tweens, time ?? clockNow() / 1000);
if (updateTweens) tweens.update = clockedTweens;
// An error listener's own throw is uncaught, never reported again.
const rendererListeners = {
@@ -421,6 +428,13 @@ export function createCesiumPorts(
report,
widget,
capabilities,
now: clockNow,
...(capabilities.has('motionSegments')
? {
itemPosition: (item, time) =>
drawPart.drawnPosition(item, 0, time),
}
: {}),
});
const cameraPort = cameraPart.port;
const effectsPart = createCesiumEffects(scene, {
@@ -736,6 +750,9 @@ export function createCesiumPorts(
settleTick(false);
for (const off of removers) off();
scene.canvas?.removeEventListener?.('webglcontextlost', contextLost);
// Cesium's own tween clock back, unless another set wrapped it since.
if (updateTweens && tweens.update === clockedTweens)
tweens.update = updateTweens;
// A listener that disposes the renderer stops the rest of its event.
for (const list of Object.values(rendererListeners)) list.clear();
for (const list of Object.values(frameListeners)) list.clear();
+93 -13
View File
@@ -393,6 +393,7 @@ function tickingWidget() {
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
primitives: { add() {}, remove() {} },
tweens: new Cesium.TweenCollection(),
requestRender() {
requested += 1;
scene._renderRequested = true;
@@ -704,10 +705,14 @@ test('without cameraChangeThreshold every changed listener fires at 0.5', () =>
ports.dispose();
});
test('camera events: Cesium’s moves relayed, a throw reported, off and dispose stop them', () => {
test('camera events: moves measured each tick by the given clock, a throw reported, off and dispose stop them', () => {
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const ports = createCesiumPorts(widget, { capabilities: all });
const clock = { ms: 0 };
const ports = createCesiumPorts(widget, {
capabilities: all,
now: () => clock.ms,
});
const errors = [];
ports.on('error', (e) => errors.push(e.message));
const seen = [];
@@ -716,25 +721,94 @@ test('camera events: Cesium’s moves relayed, a throw reported, off and dispose
});
const off = ports.camera.on('moveStart', () => seen.push('start'));
ports.camera.on('moveEnd', () => seen.push('end'));
ports.camera.on('changed', () => seen.push('changed'), { threshold: 0.01 });
scene.camera.moveStart.raiseEvent();
scene.camera.moveEnd.raiseEvent();
assert.deepEqual(seen, ['start', 'end']);
const tick = (ms) => {
clock.ms += ms;
raise('postUpdate');
};
tick(16);
scene.camera.lookRight(0.01);
tick(16);
assert.deepEqual(seen, ['start']);
assert.deepEqual(errors, ['first']);
// Cesium's own events are not relayed: it times them by the system clock.
scene.camera.moveEnd.raiseEvent();
tick(499);
assert.deepEqual(seen, ['start'], 'still within 500 ms of the move');
tick(1);
assert.deepEqual(seen, ['start', 'end']);
off();
scene.camera.moveStart.raiseEvent();
scene.camera.lookRight(0.01);
tick(16);
assert.deepEqual(seen, ['start', 'end']);
assert.throws(
() => ports.camera.on('turned', () => {}),
/Unknown camera event/,
);
ports.dispose();
scene.camera.moveEnd.raiseEvent();
tick(600);
scene.camera.lookRight(1);
raise('postUpdate');
tick(16);
tick(600);
assert.deepEqual(seen, ['start', 'end'], 'nothing after dispose');
});
test('a new field of view is a move: moveStart, then moveEnd 500 ms on', () => {
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const clock = { ms: 0 };
const ports = createCesiumPorts(widget, {
capabilities: all,
now: () => clock.ms,
});
const seen = [];
ports.camera.on('moveStart', () => seen.push('start'));
ports.camera.on('moveEnd', () => seen.push('end'));
raise('postUpdate');
// A resize: the eye stays where it is.
scene.camera.frustum.aspectRatio = 2;
clock.ms += 16;
raise('postUpdate');
assert.deepEqual(seen, ['start']);
clock.ms += 500;
raise('postUpdate');
assert.deepEqual(seen, ['start', 'end']);
ports.dispose();
});
test('dispose gives the scene back Cesium’s own tween clock', () => {
const { widget, scene } = tickingWidget();
const own = scene.tweens.update;
const ports = createCesiumPorts(widget, { capabilities: all });
assert.notEqual(scene.tweens.update, own);
ports.dispose();
assert.equal(scene.tweens.update, own);
});
test('moveEnd waits for a still camera: rounding in Cesium’s vectors is no move', () => {
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const clock = { ms: 0 };
const ports = createCesiumPorts(widget, {
capabilities: all,
now: () => clock.ms,
});
const seen = [];
ports.camera.on('moveEnd', () => seen.push('end'));
raise('postUpdate');
scene.camera.lookRight(0.01);
raise('postUpdate');
for (let i = 0; i < 40; i++) {
// The same view, derived again: off in the last bits.
const d = scene.camera.direction;
const nudge = (i % 2 ? 1 : -1) * 4 * Number.EPSILON * Math.abs(d.x);
scene.camera.direction = new Cesium.Cartesian3(d.x + nudge, d.y, d.z);
clock.ms += 16;
raise('postUpdate');
}
assert.deepEqual(seen, ['end']);
ports.dispose();
});
test('pose: degrees, and NaN where Cesium has no cartographic position', () => {
const { widget, scene } = tickingWidget();
cityView(scene.camera);
@@ -751,13 +825,19 @@ test('pose: degrees, and NaN where Cesium has no cartographic position', () => {
});
test('a camera listener that disposes the port stops the rest of its event', () => {
const { widget, scene } = tickingWidget();
const { widget, scene, raise } = tickingWidget();
cityView(scene.camera);
const ports = createCesiumPorts(widget, { capabilities: all });
const seen = [];
ports.camera.on('moveStart', () => ports.dispose());
ports.camera.on('moveStart', () => {
seen.push('first');
ports.dispose();
});
ports.camera.on('moveStart', () => seen.push('second'));
scene.camera.moveStart.raiseEvent();
assert.deepEqual(seen, []);
raise('postUpdate');
scene.camera.lookRight(0.01);
raise('postUpdate');
assert.deepEqual(seen, ['first']);
});
test('viewRectangle is in degrees, around the point below a downward eye', () => {
+3 -3
View File
@@ -14,7 +14,7 @@
import * as Cesium from 'cesium';
import { heightsFor } from './heights.js';
import { findDraw, provideUnboundQuery } from '../rendererOf.js';
import { toCartesian } from './common.js';
import { pickEllipsoidAt, pickRayAt, toCartesian } from './common.js';
import { unboundDrawPart } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { rememberPick } from './pickMemo.js';
@@ -366,13 +366,13 @@ export function createCesiumQuery({
return ecef(scene.pickPosition(screen(x, y)));
},
pickEllipsoid(x, y) {
return ecef(camera.pickEllipsoid(screen(x, y)));
return ecef(pickEllipsoidAt(scene, camera, x, y));
},
pickGlobe(ray) {
return ecef(scene.globe?.pick(cesiumRay(ray), scene));
},
pickRay(x, y) {
const ray = camera.getPickRay(screen(x, y));
const ray = pickRayAt(scene, camera, x, y);
return { origin: ecef(ray.origin), direction: ecef(ray.direction) };
},
project(position) {