From e9085e8df3ff526bc8ac70718db66169ffcef0be Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 12 Nov 2026 14:59:45 -0800 Subject: [PATCH] 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. --- scripts/package-boundaries.json | 128 ++++++++++++++++++++++ src/render/camera/events.js | 13 ++- src/render/cesium/camera.js | 90 +++++++++++---- src/render/cesium/common.js | 91 +++++++++++++++ src/render/cesium/common.test.mjs | 72 +++++++++++- src/render/cesium/controlledCamera.js | 26 +---- src/render/cesium/follow.js | 27 ++++- src/render/cesium/harness.js | 47 ++++---- src/render/cesium/ports.js | 17 +++ src/render/cesium/ports.test.mjs | 106 +++++++++++++++--- src/render/cesium/query.js | 6 +- src/testSupport/fakeCameraPort.mjs | 9 +- src/ui/cameraOrientationControls.test.mjs | 8 +- 13 files changed, 545 insertions(+), 95 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ca9c7700a..88d037862 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2121,9 +2121,134 @@ ], "external": ["cesium"] }, + "render-cesium-plugin": { + "exports": ["./render/cesium/plugin"], + "modules": [ + "src/render/cesium/plugin.js", + "src/render/cesium/appRenderer.js", + "src/render/cesium/applicationViewer.js", + "src/render/rendererOf.js", + "src/globeInView.js", + "src/render/cesium/mapEngine.js", + "src/render/contract/index.js", + "src/render/cesium/freeLookLimit.js", + "src/render/cesium/sceneCommandRelease.js", + "src/render/cesium/ports.js", + "src/render/cesium/creditKeyboard.js", + "src/render/cesium/viewers.js", + "src/render/cesium/input.js", + "src/i18n/index.js", + "src/app/atmosphereCompat.js", + "src/render/cesium/imageryLookAhead.js", + "src/render/cesium/starrySky.js", + "src/geo/ellipsoid.js", + "src/data/followed.js", + "src/geo/frames.js", + "src/geo/vector.js", + "src/maps/engine.js", + "src/render/cesium/mapImagery.js", + "src/render/cesium/mapTerrain.js", + "src/render/cesium/google3d.js", + "src/render/cesium/internals.js", + "src/render/cesium/controlledCamera.js", + "src/render/cesium/common.js", + "src/render/cesium/camera.js", + "src/render/cesium/credits.js", + "src/render/cesium/frame.js", + "src/render/cesium/gpuIcons.js", + "src/render/cesium/effects.js", + "src/render/cesium/globe.js", + "src/render/cesium/query.js", + "src/render/cesium/quality.js", + "src/render/input/wheel.js", + "src/render/input/router.js", + "src/render/cesium/cameraInput.js", + "src/render/cesium/screenModulation.js", + "src/render/cesium/draw.js", + "src/i18n/locale.js", + "src/i18n/locales/ar.json", + "src/i18n/locales/es.json", + "src/i18n/locales/de.json", + "src/i18n/locales/fr.json", + "src/i18n/locales/he.json", + "src/i18n/locales/ja.json", + "src/i18n/locales/it.json", + "src/i18n/locales/pt.json", + "src/i18n/locales/sv.json", + "src/i18n/locales/ru.json", + "src/i18n/locales/zh-CN.json", + "src/i18n/locales/zh-Hant.json", + "src/i18n/locales/uk.json", + "src/cockpitOrbital.js", + "src/data/bundledJson.js", + "src/renderGovernor.js", + "src/sky/stars.js", + "src/data/entityRecords.js", + "src/sky/icrf.js", + "src/render/applicationHooks.js", + "src/maps/attribution.js", + "src/maps/globeEngine.js", + "src/maps/terrainRetry.js", + "src/maps/startupRoute.js", + "src/maps/keylessTerrain.js", + "src/render/stub/viewRectangle.js", + "src/render/cesium/follow.js", + "src/render/cesium/cameraControls.js", + "src/render/camera/events.js", + "src/render/creditMarkup.js", + "src/render/cesium/nativeClick.js", + "src/data/iconSegment.js", + "src/data/iconSet.js", + "src/data/iconAtlas.js", + "src/render/cesium/iconSetPrimitive.js", + "src/render/motion/iconMotion.js", + "src/render/cesium/heights.js", + "src/render/baseTilesets.js", + "src/render/cesium/pickMemo.js", + "src/render/cesium/vectorBase.js", + "src/render/cesium/imagery.js", + "src/render/cesium/sceneOcclusionProbe.js", + "src/render/vectorBase/index.js", + "src/render/cesium/drawHit.js", + "src/geo/polyline.js", + "src/geo/screenCluster.js", + "src/geo/celestial.js", + "src/render/cesium/setBlend.js", + "src/render/cesium/drawMeshes.js", + "src/render/cesium/drawQuads.js", + "src/render/cesium/drawModels.js", + "src/render/cesium/drawFields.js", + "src/render/stub/math.js", + "src/render/cesium/ctrlWheelZoom.js", + "src/render/cesium/zoomOutGuard.js", + "src/geo/index.js", + "src/data/pickRegistry.js", + "src/data/scenePick.js", + "src/geo/horizon.js", + "src/data/motionModel.js", + "src/geo/julian.js", + "src/data/aircraftRecession.js", + "src/render/cesium/tileRequests.js", + "src/render/cesium/imageryFrames.js", + "src/render/occlusion/depthProbe.js", + "src/render/vectorBase/style.js", + "src/render/cesium/drawStreamlines.js", + "src/render/vectorBase/expressions.js", + "src/geo/quaternion.js", + "src/geo/geodesic.js", + "src/data/detectionOcclusion.js", + "src/render/vectorBase/paint.js", + "src/layers/wind/streamlines.js", + "src/layers/wind/model.js", + "src/sky/assets.js" + ], + "external": ["cesium", "pbf", "@mapbox/vector-tile"] + }, "render-cesium-unbound": { "exports": ["./render/cesium/unbound"], "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", "src/render/cesium/unbound.js", "src/render/cesium/globe.js", "src/render/baseTilesets.js", @@ -3709,6 +3834,9 @@ "./standalone/catalog" ], "modules": [ + "src/render/stub/viewRectangle.js", + "src/render/stub/math.js", + "src/render/cesium/controlledCamera.js", "src/geo/index.js", "src/geo/julian.js", "src/geo/vector.js", diff --git a/src/render/camera/events.js b/src/render/camera/events.js index e7516960c..df5e15479 100644 --- a/src/render/camera/events.js +++ b/src/render/camera/events.js @@ -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) { diff --git a/src/render/cesium/camera.js b/src/render/cesium/camera.js index 96528f28c..2cb7af7d7 100644 --- a/src/render/cesium/camera.js +++ b/src/render/cesium/camera.js @@ -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}} options `scene` + * widget?: object, capabilities?: ReadonlySet, + * 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(); diff --git a/src/render/cesium/common.js b/src/render/cesium/common.js index 280e36c8f..b16d387e5 100644 --- a/src/render/cesium/common.js +++ b/src/render/cesium/common.js @@ -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()); +} diff --git a/src/render/cesium/common.test.mjs b/src/render/cesium/common.test.mjs index 14d45bbda..24cecc151 100644 --- a/src/render/cesium/common.test.mjs +++ b/src/render/cesium/common.test.mjs @@ -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); +}); diff --git a/src/render/cesium/controlledCamera.js b/src/render/cesium/controlledCamera.js index fe4e288c6..072ff132f 100644 --- a/src/render/cesium/controlledCamera.js +++ b/src/render/cesium/controlledCamera.js @@ -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, diff --git a/src/render/cesium/follow.js b/src/render/cesium/follow.js index 7a570b553..43c10b72e 100644 --- a/src/render/cesium/follow.js +++ b/src/render/cesium/follow.js @@ -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. diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 0a2b99ac6..45bdd8358 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -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 } } : {}), }; } diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index dbf9a9feb..3d448a357 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -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(); diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index cba7217df..5bf8ab170 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -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', () => { diff --git a/src/render/cesium/query.js b/src/render/cesium/query.js index f38029e72..b9327d56b 100644 --- a/src/render/cesium/query.js +++ b/src/render/cesium/query.js @@ -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) { diff --git a/src/testSupport/fakeCameraPort.mjs b/src/testSupport/fakeCameraPort.mjs index 6aa372136..98332cdae 100644 --- a/src/testSupport/fakeCameraPort.mjs +++ b/src/testSupport/fakeCameraPort.mjs @@ -206,14 +206,19 @@ export function bindFakeCesiumCamera(viewer, ports = {}) { tracks && typeof viewer.entities.add !== 'function' ? trackingWidget(viewer) : viewer; - const real = createCesiumCamera({ + const made = createCesiumCamera({ scene, camera, ...(tracks ? { widget } : {}), report: (error) => { throw error; }, - }).port; + }); + const real = made.port; + // The fake's own moveStart and moveEnd, which a test raises, are the + // port's: with no ticks, the port measures no moves of its own. + for (const event of ['moveStart', 'moveEnd']) + fake[event]?.addEventListener?.(() => made.emit(event)); const port = Object.create(real, { pose: { value() { diff --git a/src/ui/cameraOrientationControls.test.mjs b/src/ui/cameraOrientationControls.test.mjs index 6fd73d9c5..c61c6c149 100644 --- a/src/ui/cameraOrientationControls.test.mjs +++ b/src/ui/cameraOrientationControls.test.mjs @@ -453,8 +453,12 @@ test('a sky-facing camera yields no frame and both actions decline', () => { scene.pickPosition = () => null; scene.globe.pick = () => undefined; scene.requestRender = () => {}; - camera.getPickRay = () => new Cesium.Ray(); - camera.pickEllipsoid = () => undefined; + // 1000 km up, looking above the horizon: no ray from the centre meets + // the ellipsoid. + camera.setView({ + destination: Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 1_000_000), + orientation: { heading: 0, pitch: Cesium.Math.toRadians(30), roll: 0 }, + }); const viewer = withPorts({ camera, scene }); assert.equal(readCameraTargetFrame(viewer), null);