From ef616b79056e79e23fd09db523a70cd40c9dc494 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 19:22:42 -0800 Subject: [PATCH 1/4] Share the camera events and the stub's drawn positions with other cameras The geo export now has geodesicAt and horizonFrom. The camera events module is a public export (./render/camera/events) and holds move detection and the command hooks as well as the per-listener changed measure; the stub camera uses them. Each onCommand registration is now its own, so removing one twin leaves the other. The stub's testing.drawnPosition says where it draws an item, so a camera that is not the stub's can follow drawn items. --- docs/RENDERER-CONTRACT.md | 21 ++++-- package.json | 1 + scripts/package-boundaries.json | 24 +++++- src/geo/index.js | 7 +- src/render/camera/events.js | 119 ++++++++++++++++++++++++++++-- src/render/camera/events.test.mjs | 90 ++++++++++++++++++++++ src/render/stub/camera.js | 67 ++++------------- src/render/stub/index.js | 8 ++ src/render/stub/stub.test.mjs | 53 +++++++++++++ 9 files changed, 320 insertions(+), 70 deletions(-) create mode 100644 src/render/camera/events.test.mjs diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index ef692e542..bbe0c0e36 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -6,13 +6,19 @@ it meets the contract. The contract is version `0`. Today the application still drives Cesium directly; later work moves the layers onto the contract one family at a time. -The package exports three modules: +The package exports four modules: -| Export | What it is | -| ---------------------------------- | ------------------------------------------------------------------------------ | -| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | -| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | -| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | +| Export | What it is | +| ------------------------------------ | -------------------------------------------------------------------------------------- | +| `gods-eye-view/render/contract` | The types, one `.d.ts` per port, plus the run-time member list and shape check | +| `gods-eye-view/render/stub` | A renderer that draws nothing, for tests | +| `gods-eye-view/render/camera/events` | The camera port's events: `changed` per listener, `moveStart`/`moveEnd`, command hooks | +| `gods-eye-view/render/conformance` | The conformance suite, reference scenes and visual comparison | + +A camera of its own (a camera controller over a renderer without one) can +take the camera events from `render/camera/events` and the geodesy it needs +(`geodesicAt`, `horizonFrom` and the rest) from `gods-eye-view/geo`, so it +measures and fires exactly as the stub does. ## Ports @@ -179,6 +185,9 @@ in memory and draws nothing. It has: `renderer.testing` drives it with `tick()`, `advance(ms)`, `pointer(type, x, y)`, `scriptPicks`, `setHeights` and `cacheHeight`, and records its calls. +`testing.drawnPosition({ set, id }, aheadMs)` is where it draws an item now +(or `aheadMs` from now), so a +camera that is not the stub's own can follow drawn items there. A listener that throws with nothing subscribed to `error` goes to `reportError`; Node has none, so the stub rethrows it on a microtask and `node:test` fails the running test. A test that expects a throw subscribes diff --git a/package.json b/package.json index cd98ee3f7..89ef24474 100644 --- a/package.json +++ b/package.json @@ -298,6 +298,7 @@ "./geo": "./src/geo/index.js", "./render/contract": "./src/render/contract/index.js", "./render/stub": "./src/render/stub/index.js", + "./render/camera/events": "./src/render/camera/events.js", "./render/cesium/unbound": "./src/render/cesium/unbound.js", "./render/conformance": "./src/render/conformance/index.js" } diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a88788895..c32a26926 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -888,6 +888,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/ui/cockpitBriefPages.js", "src/ui/cockpitContextState.js", @@ -1177,6 +1178,7 @@ "src/ui/visualSettings.js", "src/worldFocus.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", @@ -1848,6 +1850,7 @@ "src/render/cesium/camera.js", "src/render/camera/events.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/celestial.js", "src/geo/ellipsoid.js", "src/geo/quaternion.js", @@ -1996,6 +1999,7 @@ "modules": [ "src/data/satelliteClass.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/data/satellitePass.js", "src/sources/tle.js", @@ -2279,6 +2283,8 @@ "src/render/camera/poseSignature.js", "src/data/militaryAwarenessEngine.js", "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", "src/geo/julian.js", "src/data/installationNames.js", "src/layers/awareness/controls.js", @@ -2348,6 +2354,7 @@ "src/layers/traffic/animation.js", "src/layers/traffic/controls.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/traffic/flow.js", "src/layers/traffic/flowDecode.js", @@ -2629,6 +2636,7 @@ "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/layers/streetLevel/credits.js", "src/render/creditMarkup.js", "src/layers/streetLevel/providers/mapillary/index.js", @@ -2724,6 +2732,7 @@ "src/layers/alpr/index.js", "src/data/followed.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", @@ -2989,6 +2998,7 @@ "src/i18n/marker.js", "src/maps/availability.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/maps/catalog.js", "src/maps/controller.js", @@ -4958,6 +4968,7 @@ "src/render/rendererOf.js", "src/render/camera/events.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/celestial.js", "src/geo/quaternion.js", "src/geo/frames.js", @@ -5664,6 +5675,7 @@ "src/data/terrainHeights.js", "src/data/transit.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/data/transitFeeds.js", "src/data/transitIcons.js", "src/data/transitPresetStyle.js", @@ -5751,6 +5763,7 @@ "src/render/cesium/iconOrientation.js", "src/layers/transit/selection.js", "src/geo/index.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", @@ -6284,6 +6297,8 @@ "exports": ["./agent/world-packet"], "modules": [ "src/geo/index.js", + "src/geo/geodesic.js", + "src/geo/horizon.js", "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", @@ -6314,6 +6329,8 @@ "exports": ["./geo"], "modules": [ "src/geo/index.js", + "src/geo/horizon.js", + "src/geo/geodesic.js", "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", @@ -6324,7 +6341,12 @@ "external": [] }, "render": { - "exports": ["./render/contract", "./render/stub", "./render/conformance"], + "exports": [ + "./render/contract", + "./render/stub", + "./render/camera/events", + "./render/conformance" + ], "modules": [ "src/render/contract/index.js", "src/render/stub/index.js", diff --git a/src/geo/index.js b/src/geo/index.js index c064bd24c..e8fc0111d 100644 --- a/src/geo/index.js +++ b/src/geo/index.js @@ -2,8 +2,9 @@ * @module geo * @description Cesium-free geodesy and vector maths: WGS84, ECEF and * geodetic conversions, east-north-up frames, quaternions, and the sun and - * moon. Plain numbers and `{x, y, z}` objects only, so code that needs - * maths but not a renderer does not import one. + * moon, a point along a geodesic and the ellipsoid's horizon. Plain numbers + * and `{x, y, z}` objects only, so code that needs maths but not a renderer + * does not import one. */ export * from './vector.js'; export * from './ellipsoid.js'; @@ -11,3 +12,5 @@ export * from './frames.js'; export * from './celestial.js'; export * from './julian.js'; export * from './quaternion.js'; +export { geodesicAt } from './geodesic.js'; +export { horizonFrom } from './horizon.js'; diff --git a/src/render/camera/events.js b/src/render/camera/events.js index 9b40fc3cb..e7516960c 100644 --- a/src/render/camera/events.js +++ b/src/render/camera/events.js @@ -1,15 +1,22 @@ /** * @module render/camera/events - * @description The camera port's events, shared by the Cesium port and the stub: the - * listener lists, delivery (a throwing listener is reported, the rest still - * run), and the contract's per-listener `changed` measure. A renderer calls - * `stepChanged()` once per frame and `emit()` for the events its engine + * @description The camera port's events, shared by the renderer, the stub and + * camera controllers (the package's `./render/camera/events` + * export): + * the listener lists, delivery (a throwing listener is reported, the rest + * still run), the contract's per-listener `changed` measure, move detection + * (`moveStart` on a change, `moveEnd` 500 ms after the last one, never + * while following) and the command hooks (`onCommand`). A renderer calls + * `stepChanged()` and `stepMoveDetection()` once per frame, `command()` + * before each camera command, and `emit()` for the events its engine * raises. */ import { acosClamped, distance, dot } from '../../geo/index.js'; const TWO_PI = Math.PI * 2; +/** `moveEnd` waits this long after the last change, ms, as the reference does. */ +export const MOVE_END_WAIT_MS = 500; /** The contract's camera events. */ export const CAMERA_EVENTS = Object.freeze([ @@ -26,15 +33,43 @@ const angleDelta = (a, b) => { return (d > Math.PI ? TWO_PI - d : d) / Math.PI; }; +/** + * Whether two world views are the same: the same position, and directions + * and ups whose dot products are each one's own. + */ +function sameView(a, b) { + return ( + a && + b && + 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) + ); +} + /** * @param {{pose: () => import('../contract/camera').CameraPose, + * world?: () => {position: object, direction: object, up: object}, + * following?: () => boolean, * report: (error: unknown) => void, thresholds?: boolean}} options `pose` - * is read only while a `changed` listener is registered; `thresholds` + * is read only while a `changed` listener is registered; `world` (the + * eye in world coordinates; `pose()` when omitted) and `following` (no + * `moveEnd` while true) are read by `stepMoveDetection`; `thresholds` * false (a renderer without `cameraChangeThreshold`) ignores a listener's * own threshold, so every listener fires at 0.5. */ -export function createCameraEvents({ pose, report, thresholds = true }) { +export function createCameraEvents({ + pose, + world = pose, + following = () => false, + report, + thresholds = true, +}) { const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []])); + const commandHooks = []; + let lastView = null; + let moving = false; + let lastMovedAt = 0; function deliver(entry) { if (!entry.live) return; @@ -109,13 +144,81 @@ export function createCameraEvents({ pose, report, thresholds = true }) { } } - /** Drop every listener, including those of an event under way. */ + /** + * Once a frame, after `preUpdate`: `moveStart` when the eye changed since + * the last frame, `moveEnd` once it has not for 500 ms (`now`, ms) and + * nothing is followed. + * @param {number} now + */ + function stepMoveDetection(now) { + const v = world(); + const current = { position: v.position, direction: v.direction, up: v.up }; + const changed = lastView && !sameView(lastView, current); + lastView = current; + if (changed) { + lastMovedAt = now; + if (!moving) { + moving = true; + emit('moveStart'); + } + } else if ( + moving && + !following() && + now - lastMovedAt >= MOVE_END_WAIT_MS + ) { + moving = false; + emit('moveEnd'); + } + } + + /** + * Tell every command hook about a command before it runs. + * @param {import('../contract/camera').CameraCommand['kind']} kind + */ + function command(kind) { + for (const entry of commandHooks.slice()) { + if (!entry.live) continue; + try { + entry.cb({ kind }); + } catch (error) { + report(error); + } + } + } + + /** + * The contract's `onCommand`. Each registration is its own: its `Off` + * removes only it, once. + * @param {(command: import('../contract/camera').CameraCommand) => void} cb + * @returns {() => void} + */ + function onCommand(cb) { + const entry = { cb, live: true }; + commandHooks.push(entry); + return () => { + entry.live = false; + const i = commandHooks.indexOf(entry); + if (i >= 0) commandHooks.splice(i, 1); + }; + } + + /** Drop every listener and hook, including those of an event under way. */ function clear() { for (const list of Object.values(listeners)) { for (const entry of list) entry.live = false; list.length = 0; } + for (const entry of commandHooks) entry.live = false; + commandHooks.length = 0; } - return { on, emit, stepChanged, clear }; + return { + on, + emit, + stepChanged, + stepMoveDetection, + command, + onCommand, + clear, + }; } diff --git a/src/render/camera/events.test.mjs b/src/render/camera/events.test.mjs new file mode 100644 index 000000000..d2e81750d --- /dev/null +++ b/src/render/camera/events.test.mjs @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createCameraEvents, MOVE_END_WAIT_MS } from './events.js'; +import { geodesicAt, horizonFrom } from '../../geo/index.js'; + +const view = (x) => ({ + position: { x, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, + up: { x: 0, y: 0, z: 1 }, +}); + +test('moveStart on a change, moveEnd once nothing moved for 500 ms and nothing is followed', () => { + let eye = view(7e6); + let following = false; + const seen = []; + const events = createCameraEvents({ + pose: () => eye, + world: () => eye, + following: () => following, + report: (error) => assert.fail(error), + }); + events.on('moveStart', () => seen.push('start')); + events.on('moveEnd', () => seen.push('end')); + events.stepMoveDetection(0); + eye = view(7e6 + 1); + events.stepMoveDetection(16); + assert.deepEqual(seen, ['start']); + events.stepMoveDetection(16 + MOVE_END_WAIT_MS - 1); + assert.deepEqual(seen, ['start']); + // A later change starts the wait again, and moveStart is not repeated. + eye = view(7e6 + 2); + events.stepMoveDetection(400); + events.stepMoveDetection(16 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start']); + events.stepMoveDetection(400 + MOVE_END_WAIT_MS - 1); + assert.deepEqual(seen, ['start']); + following = true; + events.stepMoveDetection(400 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start'], 'never while following'); + following = false; + events.stepMoveDetection(401 + MOVE_END_WAIT_MS); + assert.deepEqual(seen, ['start', 'end']); +}); + +test('command hooks run before each command, each registration on its own', () => { + const events = createCameraEvents({ pose: () => view(1), report() {} }); + const seen = []; + const hook = (c) => seen.push(c.kind); + const offFirst = events.onCommand(hook); + events.onCommand(hook); + events.command('setView'); + assert.deepEqual(seen, ['setView', 'setView']); + offFirst(); + offFirst(); + events.command('flyTo'); + assert.deepEqual(seen, ['setView', 'setView', 'flyTo'], 'one twin is left'); + // A hook removed by an earlier one in the same delivery does not run. + const order = []; + const removing = createCameraEvents({ pose: () => view(1), report() {} }); + let offSecond = null; + removing.onCommand(() => { + order.push('first'); + offSecond(); + }); + offSecond = removing.onCommand(() => order.push('second')); + removing.command('setView'); + removing.command('setView'); + assert.deepEqual(order, ['first', 'first']); + const reported = []; + const throwing = createCameraEvents({ + pose: () => view(1), + report: (error) => reported.push(error.message), + }); + throwing.onCommand(() => { + throw new Error('boom'); + }); + throwing.onCommand(() => seen.push('after')); + throwing.command('flyTo'); + assert.deepEqual(reported, ['boom']); + assert.equal(seen.at(-1), 'after'); +}); + +test('the geo export has the geodesic point and the horizon test', () => { + const half = geodesicAt(0, 0, Math.PI / 2, 0, 0.5); + assert.ok(Math.abs(half.lon - Math.PI / 4) < 1e-12); + assert.ok(Math.abs(half.lat) < 1e-12); + const horizon = horizonFrom({ x: 7e6, y: 0, z: 0 }); + assert.equal(horizon.isPointVisible({ x: 6378137, y: 0, z: 0 }), true); + assert.equal(horizon.isPointVisible({ x: -6378137, y: 0, z: 0 }), false); +}); diff --git a/src/render/stub/camera.js b/src/render/stub/camera.js index 69f081f4b..d887cba99 100644 --- a/src/render/stub/camera.js +++ b/src/render/stub/camera.js @@ -47,7 +47,6 @@ import { createCameraEvents } from '../camera/events.js'; import { geodesicAt } from '../../geo/geodesic.js'; const DEFAULT_FOV = Math.PI / 3; -const MOVE_END_WAIT_MS = 500; const MINIMUM_ZOOM = 100; const DEFAULT_SPHERE_OFFSET = Object.freeze({ heading: 0, @@ -98,17 +97,23 @@ export function createStubCamera({ const near = 1; const far = 5e8; - const events = createCameraEvents({ pose, report, thresholds }); - const { emit, on, stepChanged } = events; - const commandHooks = []; + const events = createCameraEvents({ + pose, + world: () => ({ + position: positionWC(), + direction: directionWC(), + up: upWC(), + }), + following: () => Boolean(followed), + report, + thresholds, + }); + const { emit, on, stepChanged, command, onCommand } = events; const holds = new Map(); let holdSeq = 0; let flight = null; let followed = null; let followFramed = false; - let lastPose = null; - let moving = false; - let lastMovedAt = 0; let coast = Object.freeze({ drag: 0.4, zoom: 0.2 }); const controls = { @@ -202,17 +207,6 @@ export function createStubCamera({ }; } - function command(kind) { - for (const hook of commandHooks.slice()) { - if (!commandHooks.includes(hook)) continue; - try { - hook({ kind }); - } catch (error) { - report(error); - } - } - } - /** Place the eye at `destination` (world) with `orientation` in its east-north-up frame. */ function placeAt(destination, hpr) { const kept = frame; @@ -727,35 +721,8 @@ export function createStubCamera({ // --- Events ---------------------------------------------------------------- - function sameView(a, b) { - return ( - a && - b && - 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) - ); - } - function stepMoveDetection() { - const current = { - position: positionWC(), - direction: directionWC(), - up: upWC(), - }; - const changed = lastPose && !sameView(lastPose, current); - lastPose = current; - const t = now(); - if (changed) { - lastMovedAt = t; - if (!moving) { - moving = true; - emit('moveStart'); - } - } else if (moving && !followed && t - lastMovedAt >= MOVE_END_WAIT_MS) { - moving = false; - emit('moveEnd'); - } + events.stepMoveDetection(now()); } function matrices() { @@ -844,13 +811,7 @@ export function createStubCamera({ followOffset, controls, on, - onCommand(cb) { - commandHooks.push(cb); - return () => { - const i = commandHooks.indexOf(cb); - if (i >= 0) commandHooks.splice(i, 1); - }; - }, + onCommand, matrices, }; diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 7d02093ae..edfa96b1a 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -1600,6 +1600,13 @@ export function createStubRenderer(options = {}) { canvas.width = viewport.width; canvas.height = viewport.height; }, + /** + * Where a drawn item is drawn now (or `aheadMs` from now), ECEF, or + * null: what the stub's own camera follows for a target's `item`, for + * a camera of someone else's driving the stub (the `camera.followItem` + * conformance check). + */ + drawnPosition: (ref, aheadMs = 0) => drawnPosition(ref, aheadMs), /** What a set holds. */ setRecord: (id) => sets.get(id) ?? null, sets: () => [...sets.keys()], @@ -1624,6 +1631,7 @@ export function createStubRenderer(options = {}) { * @property {(point: object, height: number) => void} cacheHeight * @property {(kind: string, value: boolean) => void} setSettled * @property {(size: {width?: number, height?: number}) => void} setViewport + * @property {(ref: {set: string, id: string|number}, aheadMs?: number) => {x: number, y: number, z: number}|null} drawnPosition * @property {(id: string) => object|null} setRecord * @property {() => string[]} sets * @property {Array<{port: string, member: string, args: unknown[]}>} calls diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 28e78c2e9..547fbc148 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -130,3 +130,56 @@ test('a draped rectangle across the antimeridian picks on both sides of it, turn assert.ok(!picked(179.5, 0), 'and narrows it'); r.destroy(); }); + +test('the stub says where it draws an item, for a camera that is not its own', () => { + const r = createStubRenderer(); + const t0 = r.frame.time(); + const from = toEcef({ lon: -97.74, lat: 30.27, height: 1000 }); + const to = toEcef({ lon: -97.7, lat: 30.27, height: 1000 }); + const set = r.draw.icons({ id: 'drawn', motionClock: { kind: 'scene' } }); + set.set([ + { + id: 'm', + pos: from, + image: 'data:,', + size: [16, 16], + motion: { kind: 'lerp', from, to, t0, t1: t0 + 60000 }, + }, + ]); + const at = (p) => [p.x, p.y, p.z]; + assert.deepEqual( + at(r.testing.drawnPosition({ set: 'drawn', id: 'm' })), + at(from), + ); + r.frame.setTime(t0 + 30000); + const mid = r.testing.drawnPosition({ set: 'drawn', id: 'm' }); + for (const k of ['x', 'y', 'z']) + assert.ok(Math.abs(mid[k] - (from[k] + to[k]) / 2) < 1e-6, k); + const ahead = r.testing.drawnPosition({ set: 'drawn', id: 'm' }, 30000); + for (const k of ['x', 'y', 'z']) + assert.ok(Math.abs(ahead[k] - to[k]) < 1e-6, k); + assert.equal(r.testing.drawnPosition({ set: 'drawn', id: 'gone' }), null); + assert.equal(r.testing.drawnPosition({ set: 'nothing', id: 'm' }), null); + r.destroy(); +}); + +test('the stub camera ends no move while it follows', () => { + const r = createStubRenderer(); + const seen = []; + r.camera.on('moveStart', () => seen.push('start')); + r.camera.on('moveEnd', () => seen.push('end')); + r.testing.tick(); + const target = toEcef({ lon: -97.74, lat: 30.27, height: 0 }); + r.camera.follow({ + key: 'still', + position: () => target, + frame: 'enu', + viewFrom: { x: 0, y: -500, z: 300 }, + }); + r.testing.advance(2000); + assert.deepEqual(seen, ['start'], 'moveEnd waits for the follow to end'); + r.camera.follow(null); + r.testing.advance(1000); + assert.deepEqual(seen, ['start', 'end']); + r.destroy(); +}); From 90499762f541d87610308d458575f659c213704a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 20:08:56 -0800 Subject: [PATCH 2/4] Add pointer-driven camera scripts with Cesium goldens, and count wheel lines as Cesium does Five new camera conformance scripts move the camera by user input: a left drag that coasts, thirty pixel-mode and thirty line-mode wheel notches from 5 km, a middle-drag tilt, and Shift and Ctrl drags held too long to coast. The runner turns input steps into pointer events for a driver: a move starts where the pointer last pressed or moved and carries the held button. The golden recorder now drives Cesium's own screen-space camera controller on a stand-in canvas, with Date on the virtual clock so inertia is deterministic. The existing goldens are unchanged. A harness that answers pointer input sets cameraInput and a pointer hook. Harnesses without it, such as the stub, skip the input scripts. The input port reported a line-mode wheel at 33 1/3 pixels a line. It now counts lines as the reference does, 40 pixels a line and 3 lines a page, so a pixel or line wheel converts back to the same pixels. --- docs/RENDERER-CONTRACT.md | 21 +- scripts/package-boundaries.json | 26 + src/data/infrastructure.test.mjs | 1 + src/render/cesium/cameraGoldens.js | 136 ++++- src/render/cesium/cameraPort.test.mjs | 68 ++- src/render/cesium/input.js | 12 +- src/render/cesium/input.test.mjs | 12 +- src/render/conformance/cameraRunner.js | 65 ++- src/render/conformance/cameraRunner.test.mjs | 50 ++ src/render/conformance/cameraScripts.js | 137 ++++++ src/render/conformance/checks/camera.js | 17 +- src/render/conformance/goldens/camera.json | 490 +++++++++++++++++++ src/render/conformance/index.js | 9 +- src/render/contract/input.d.ts | 7 +- src/render/input/wheel.js | 29 ++ src/render/stub/stub.test.mjs | 13 +- 16 files changed, 1055 insertions(+), 38 deletions(-) create mode 100644 src/render/conformance/cameraRunner.test.mjs create mode 100644 src/render/input/wheel.js diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index bbe0c0e36..5cbaf5e09 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -207,8 +207,9 @@ renderer under test: - `tolerance` and `flightPaths`. Optional members widen what is checked: `pointer` for synthetic input, -`scriptHeights`, `assets.model`, and `assets.missingModel` (a model url -that fails to load, for the `loadFailed` check). +`cameraInput` (the camera answers that input: the drag and wheel traces +run), `scriptHeights`, `assets.model`, and `assets.missingModel` (a model +url that fails to load, for the `loadFailed` check). There are two layers of checks. @@ -232,6 +233,22 @@ match each recorded pose: screen; - with every flight ending within one frame of the recording. +Some scripts move the camera by user input: left, middle, Shift and Ctrl +drags, and wheels in pixel and line mode. The recorder runs those on +Cesium's own `ScreenSpaceCameraController`, fed the DOM events the script +describes, with `Date` on the virtual clock too (its coasting reads it). A +renderer under test gets them through its harness's `pointer`, a wheel as +the input port's lines. Only a harness with `cameraInput` runs them: the +stub's camera takes no gestures, so it skips them; a camera controller +over the stub would run them. `cameraPort.test.mjs` runs them on Cesium's +controls under the Cesium camera port, each wheel sent back as lines. + +A wheel's `delta` is lines as Cesium counts them: a pixel-mode wheel at +40 px a line and a page at 3 lines (`src/render/input/wheel.js`). Turning +lines back into pixels at 40 px a line gives Cesium's own wheel in every +mode, so a controller that does that zooms as Cesium does in Chrome (pixel +mode) and Firefox (line mode) alike. + `src/render/cesium/cameraGoldens.test.mjs` fails when the installed Cesium no longer records the committed traces. After a Cesium upgrade or a script change, run `node scripts/record-camera-goldens.mjs` and review the diff. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index c32a26926..db798ef65 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -49,6 +49,7 @@ "src/render/cesium/common.js", "src/render/cesium/internals.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/input/sensorPick.js", @@ -964,6 +965,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -1273,6 +1275,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -1448,6 +1451,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -1579,6 +1583,7 @@ "src/render/cesium/common.js", "src/render/rendererOf.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/render/cesium/internals.js" @@ -1690,6 +1695,7 @@ "src/render/cesium/common.js", "src/render/rendererOf.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -1812,6 +1818,7 @@ "src/render/cesium/internals.js", "src/render/rendererOf.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js" @@ -1988,6 +1995,7 @@ "src/render/cesium/internals.js", "src/render/cesium/common.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js" @@ -2076,6 +2084,7 @@ "src/render/rendererOf.js", "src/render/cesium/internals.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -2167,6 +2176,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -2266,6 +2276,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -2488,6 +2499,7 @@ "src/render/cesium/internals.js", "src/render/cesium/common.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", @@ -2604,6 +2616,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -2719,6 +2732,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/queries/heights.js" @@ -2792,6 +2806,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/queries/heights.js" @@ -2891,6 +2906,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/render/cesium/internals.js" @@ -2957,6 +2973,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js" ], @@ -4209,6 +4226,7 @@ "src/input/dispatcher.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/input/router.js", "src/queries/heights.js", "src/render/cesium/internals.js", @@ -4891,6 +4909,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/queries/heights.js", @@ -5047,6 +5066,7 @@ "src/render/cesium/internals.js", "src/render/cesium/common.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", @@ -5357,6 +5377,7 @@ "src/render/cesium/common.js", "src/render/cesium/internals.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js" @@ -5733,6 +5754,7 @@ "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/queries/heights.js", @@ -5834,6 +5856,7 @@ "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", @@ -5916,6 +5939,7 @@ "src/render/cesium/common.js", "src/render/cesium/internals.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js" @@ -6064,6 +6088,7 @@ "src/render/rendererOf.js", "src/data/entityRecords.js", "src/render/cesium/input.js", + "src/render/input/wheel.js", "src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/cameraControls.js", "src/render/input/router.js", @@ -6359,6 +6384,7 @@ "src/render/conformance/cameraScripts.js", "src/render/conformance/visual.js", "src/render/conformance/cameraRunner.js", + "src/render/input/wheel.js", "src/render/conformance/expect.js", "src/render/conformance/checks/ports.js", "src/render/stub/math.js", diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 8c2a4ec4c..f41240a05 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -227,6 +227,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'stockFollow.js', 'styleStages.js', 'vector.js', + 'wheel.js', ]); assert.deepEqual( entry.imports, diff --git a/src/render/cesium/cameraGoldens.js b/src/render/cesium/cameraGoldens.js index 1197540d9..4b74e4ff0 100644 --- a/src/render/cesium/cameraGoldens.js +++ b/src/render/cesium/cameraGoldens.js @@ -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 }); diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs index 327e2c842..92fd34773 100644 --- a/src/render/cesium/cameraPort.test.mjs +++ b/src/render/cesium/cameraPort.test.mjs @@ -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(); diff --git a/src/render/cesium/input.js b/src/render/cesium/input.js index 22991cc8e..4caa644b2 100644 --- a/src/render/cesium/input.js +++ b/src/render/cesium/input.js @@ -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, ); }; diff --git a/src/render/cesium/input.test.mjs b/src/render/cesium/input.test.mjs index 2536d2e14..cb6192464 100644 --- a/src/render/cesium/input.test.mjs +++ b/src/render/cesium/input.test.mjs @@ -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', () => { diff --git a/src/render/conformance/cameraRunner.js b/src/render/conformance/cameraRunner.js index ba534c675..400c9d74b 100644 --- a/src/render/conformance/cameraRunner.js +++ b/src/render/conformance/cameraRunner.js @@ -5,6 +5,14 @@ * either a renderer through the contract ({@link contractDriver}) or the * reference recorder's own. */ +import { wheelLines } from '../input/wheel.js'; + +const NO_MODIFIERS = Object.freeze({ + shift: false, + ctrl: false, + alt: false, + meta: false, +}); /** * @typedef {object} CameraDriver @@ -18,6 +26,20 @@ * @property {(position: object) => boolean} occluded * @property {() => boolean} flying * @property {(position: object) => object} toEcef + * @property {(ev: ScriptPointer) => void|Promise} [pointer] For scripts with `input` steps. + */ + +/** + * A script's pointer event: `position` is where it happened (for a move, + * where the pointer was) and `endPosition` where a move went; a wheel has + * the DOM's `deltaY` and `deltaMode`. + * @typedef {object} ScriptPointer + * @property {'down'|'move'|'up'|'wheel'} type + * @property {{x: number, y: number}} position + * @property {{x: number, y: number}} [endPosition] + * @property {0|1|2} button + * @property {{shift: boolean, ctrl: boolean, alt: boolean, meta: boolean}} modifiers + * @property {{deltaY: number, deltaMode: number}} [wheel] */ /** The parts of a pose a trace keeps. */ @@ -47,8 +69,33 @@ export async function runCameraScript(driver, script) { const flights = []; const listeners = []; let frame = 0; + // Where the pointer is, for the next move's start, and the button held + // since the last press (a move carries it, as an input port reports it). + // Only a press or a move puts the pointer somewhere, as in the reference: + // a wheel or a release elsewhere leaves the next move starting where the + // pointer last went. + let pointerAt = null; + let held = null; for (const [index, step] of script.steps.entries()) { - if (step.do === 'frames') { + if (step.input) { + const at = { x: step.x, y: step.y }; + const ev = { + type: step.input, + position: step.input === 'move' ? (pointerAt ?? at) : at, + ...(step.input === 'move' ? { endPosition: at } : {}), + button: step.button ?? (step.input === 'move' ? held : null) ?? 0, + modifiers: { ...NO_MODIFIERS, ...(step.modifiers ?? {}) }, + ...(step.input === 'wheel' + ? { wheel: { deltaY: step.deltaY, deltaMode: step.deltaMode ?? 0 } } + : {}), + }; + if (step.input === 'down' || step.input === 'move') pointerAt = at; + if (step.input === 'down') held = ev.button; + else if (step.input === 'up') held = null; + if (!driver.pointer) + throw new Error('this driver takes no pointer input'); + await driver.pointer(ev); + } else if (step.do === 'frames') { for (let i = 0; i < step.count; i++) { frame += 1; await driver.frame(); @@ -143,7 +190,10 @@ function resolveArgs(driver, name, args) { /** * A driver over a renderer, through the contract only. * @param {import('../contract/renderer').Renderer} renderer - * @param {{frame: () => void|Promise, toEcef: (p: object) => object}} hooks + * `hooks.pointer(type, x, y, extra)` sends a pointer event the way a + * harness's `pointer` does; a wheel goes as the input port's lines. + * @param {{frame: () => void|Promise, toEcef: (p: object) => object, + * pointer?: (type: string, x: number, y: number, extra: object) => void|Promise}} hooks * @returns {CameraDriver} */ export function contractDriver(renderer, hooks) { @@ -167,5 +217,16 @@ export function contractDriver(renderer, hooks) { matrices: () => camera.matrices(), viewRectangle: () => camera.viewRectangle(), toEcef: hooks.toEcef, + ...(hooks.pointer + ? { + pointer: (ev) => + hooks.pointer(ev.type, ev.position.x, ev.position.y, { + button: ev.button, + modifiers: ev.modifiers, + ...(ev.endPosition ? { endPosition: ev.endPosition } : {}), + ...(ev.wheel ? { delta: wheelLines(ev.wheel) } : {}), + }), + } + : {}), }; } diff --git a/src/render/conformance/cameraRunner.test.mjs b/src/render/conformance/cameraRunner.test.mjs new file mode 100644 index 000000000..b5c9505b1 --- /dev/null +++ b/src/render/conformance/cameraRunner.test.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { runCameraScript } from './cameraRunner.js'; + +/** A driver that only keeps the pointer events the runner sends. */ +const pointerDriver = () => { + const events = []; + return { + events, + driver: { + pointer: async (ev) => { + events.push(ev); + }, + frame: async () => {}, + }, + }; +}; + +test('a move starts where the pointer last pressed or moved, not at a wheel or release', async () => { + const { events, driver } = pointerDriver(); + await runCameraScript(driver, { + name: 'origins', + steps: [ + { input: 'down', x: 10, y: 10, button: 1 }, + { input: 'wheel', x: 20, y: 20, deltaY: -100 }, + { input: 'move', x: 30, y: 30 }, + { input: 'up', x: 40, y: 40 }, + { input: 'move', x: 50, y: 50 }, + ], + }); + const [, wheel, held, up, free] = events; + assert.deepEqual(wheel.wheel, { deltaY: -100, deltaMode: 0 }); + assert.deepEqual(held.position, { x: 10, y: 10 }); + assert.deepEqual(held.endPosition, { x: 30, y: 30 }); + assert.equal(held.button, 1, 'a move carries the held button'); + assert.equal(up.button, 0); + assert.deepEqual(free.position, { x: 30, y: 30 }); + assert.equal(free.button, 0, 'nothing is held after the release'); +}); + +test('a first move with no earlier pointer starts where it ends', async () => { + const { events, driver } = pointerDriver(); + await runCameraScript(driver, { + name: 'first', + steps: [{ input: 'move', x: 5, y: 6 }], + }); + assert.deepEqual(events[0].position, { x: 5, y: 6 }); + assert.deepEqual(events[0].endPosition, { x: 5, y: 6 }); +}); diff --git a/src/render/conformance/cameraScripts.js b/src/render/conformance/cameraScripts.js index 31d224110..8aa408c61 100644 --- a/src/render/conformance/cameraScripts.js +++ b/src/render/conformance/cameraScripts.js @@ -19,6 +19,16 @@ * `{ record: 'pickEllipsoid', screen }`, `{ record: 'pickRay', screen }`, * `{ record: 'occluded', points }`, `{ record: 'changed' }`, * `{ record: 'flying' }`, `{ record: 'matrices' }`, `{ record: 'viewRectangle' }`. + * - `{ input: 'down' | 'move' | 'up', x, y, button?, modifiers? }`: the + * pointer, in CSS pixels; a move goes from where the pointer last was. + * - `{ input: 'wheel', x, y, deltaY, deltaMode?, modifiers? }`: a wheel as + * the DOM gives it (`deltaMode` 0 pixels, 1 lines, 2 pages); a renderer + * under test gets it as the input port's lines (`render/input/wheel.js`). + * + * A script with `input` steps moves the camera by user input, so it runs + * only where the renderer's camera answers pointer input (a harness with + * `pointer` and `cameraInput`). It starts with a frame, as a pointer event + * on the reference's clock at 0 would be dropped. */ /** Where the scripts, scenes and checks look: downtown Austin, degrees. */ @@ -60,9 +70,52 @@ const SCREEN_GRID = [ { x: 320, y: 540 }, ]; +/** A drag from `from` to `to` in `moves` moves, a frame after each. */ +const drag = ({ + from, + to, + moves = 10, + button = 0, + modifiers, + holdFrames = 0, +}) => { + const mods = modifiers ? { modifiers } : {}; + const steps = [{ input: 'down', ...from, button, ...mods }]; + for (let i = 1; i <= moves; i++) + steps.push( + { + input: 'move', + x: from.x + ((to.x - from.x) * i) / moves, + y: from.y + ((to.y - from.y) * i) / moves, + ...mods, + }, + { do: 'frames', count: 1 }, + ); + if (holdFrames) steps.push({ do: 'frames', count: holdFrames }); + steps.push({ input: 'up', ...to, button, ...mods }); + return steps; +}; + +/** + * `count` wheel notches at the centre, `frames` frames after each. The + * reference zooms towards where the pointer last moved, not where the wheel + * says it is, so a script moves the pointer to the centre first (`hover`). + */ +const notches = (count, deltaY, deltaMode, frames = 2) => + Array.from({ length: count }, () => [ + { input: 'wheel', x: 640, y: 360, deltaY, deltaMode }, + { do: 'frames', count: frames }, + ]).flat(); + +/** The pointer moves to the centre with nothing held. */ +const hover = { input: 'move', x: 640, y: 360 }; + /** The viewport every script runs in, CSS pixels. */ export const SCRIPT_VIEWPORT = Object.freeze({ width: 1280, height: 720 }); +/** Whether a script moves the camera by user input (`input` steps). */ +export const usesInput = (script) => script.steps.some((step) => step.input); + /** @type {ReadonlyArray<{name: string, steps: object[]}>} */ export const CAMERA_SCRIPTS = Object.freeze([ { @@ -442,6 +495,90 @@ export const CAMERA_SCRIPTS = Object.freeze([ { record: 'changed' }, ], }, + { + name: 'a left drag turns the globe under the pointer, then coasts', + steps: [ + city(5000, 0.2, -1.2), + { do: 'frames', count: 1 }, + ...drag({ from: { x: 640, y: 360 }, to: { x: 760, y: 420 } }), + { record: 'pose' }, + { do: 'frames', count: 20 }, + { record: 'pose' }, + { do: 'frames', count: 60 }, + { record: 'pose' }, + START, + { do: 'frames', count: 1 }, + ...drag({ from: { x: 600, y: 300 }, to: { x: 500, y: 360 } }), + { do: 'frames', count: 60 }, + { record: 'pose' }, + ], + }, + { + name: 'thirty pixel-mode wheel notches from 5 km, then out again', + steps: [ + city(5000, 0.2, -1.2), + { do: 'frames', count: 1 }, + hover, + ...notches(10, -100, 0), + { record: 'pose' }, + ...notches(10, -100, 0), + { record: 'pose' }, + ...notches(10, -100, 0), + { record: 'pose' }, + { do: 'frames', count: 60 }, + { record: 'pose' }, + ...notches(5, 100, 0), + { do: 'frames', count: 60 }, + { record: 'pose' }, + ], + }, + { + name: 'thirty line-mode wheel notches from 5 km', + steps: [ + city(5000, 0.2, -1.2), + { do: 'frames', count: 1 }, + hover, + ...notches(10, -3, 1), + { record: 'pose' }, + ...notches(20, -3, 1), + { do: 'frames', count: 60 }, + { record: 'pose' }, + ], + }, + { + name: 'a middle drag tilts about the centre, then coasts', + steps: [ + city(2000, 0.3, -1.0), + { do: 'frames', count: 1 }, + ...drag({ from: { x: 640, y: 360 }, to: { x: 640, y: 300 }, button: 1 }), + { record: 'pose' }, + { do: 'frames', count: 60 }, + { record: 'pose' }, + ], + }, + { + name: 'modified drags: Shift looks, Ctrl tilts, held too long to coast', + steps: [ + city(2000, 0.3, -0.5), + { do: 'frames', count: 1 }, + ...drag({ + from: { x: 640, y: 360 }, + to: { x: 700, y: 330 }, + modifiers: { shift: true }, + holdFrames: 30, + }), + { do: 'frames', count: 10 }, + { record: 'pose' }, + ...drag({ + from: { x: 640, y: 360 }, + to: { x: 640, y: 320 }, + modifiers: { ctrl: true }, + holdFrames: 30, + }), + { do: 'frames', count: 10 }, + { record: 'pose' }, + ], + }, { name: 'projection, picks and the horizon', steps: [ diff --git a/src/render/conformance/checks/camera.js b/src/render/conformance/checks/camera.js index 3976005a8..6a14d5dd7 100644 --- a/src/render/conformance/checks/camera.js +++ b/src/render/conformance/checks/camera.js @@ -3,7 +3,11 @@ * view rules the traces cannot show. */ import goldens from '../goldens/camera.json' with { type: 'json' }; -import { CAMERA_SCRIPTS, SCRIPT_VIEWPORT } from '../cameraScripts.js'; +import { + CAMERA_SCRIPTS, + SCRIPT_VIEWPORT, + usesInput, +} from '../cameraScripts.js'; import { contractDriver, runCameraScript } from '../cameraRunner.js'; import { deepEqual, equal, near, nearAngle, nearVec, ok } from '../expect.js'; @@ -136,6 +140,11 @@ export function cameraChecks() { async run(h) { const expected = goldens.scripts[script.name]; ok(expected, `no reference trace for ${script.name}`); + const input = usesInput(script); + if (input && h.cameraInput && !h.pointer) + throw new Error('a harness with cameraInput needs pointer'); + if (input && !h.cameraInput) + return { skip: 'the harness has no camera that answers pointer input' }; const r = await fresh(h); try { if (script.capability && !r.capabilities.has(script.capability)) @@ -144,6 +153,12 @@ export function cameraChecks() { contractDriver(r, { frame: () => h.frame(r), toEcef: lonLatToEcef(h), + ...(input + ? { + pointer: (type, x, y, extra) => + h.pointer(r, type, x, y, extra), + } + : {}), }), script, ); diff --git a/src/render/conformance/goldens/camera.json b/src/render/conformance/goldens/camera.json index a4261d14e..3c14b6a32 100644 --- a/src/render/conformance/goldens/camera.json +++ b/src/render/conformance/goldens/camera.json @@ -2312,6 +2312,496 @@ ], "flights": [] }, + "a left drag turns the globe under the pointer, then coasts": { + "records": [ + { + "step": 24, + "kind": "pose", + "value": { + "position": { + "x": -743874.2827583898, + "y": -5467123.5663921, + "z": 3198867.771901153 + }, + "direction": { + "x": 0.20397712796409123, + "y": 0.9652906415976404, + "z": -0.1631174684438692 + }, + "up": { + "x": 0.2033249113752558, + "y": 0.12121518562266298, + "z": 0.9715790545234638 + }, + "right": { + "x": 0.9576284831195057, + "y": -0.2313457499468691, + "z": -0.17154250872525903 + }, + "heading": 0.19995498090715547, + "pitch": -1.1999997631348354, + "roll": 6.283185067768231, + "height": 5001.202022602089, + "frameIsIdentity": true + } + }, + { + "step": 26, + "kind": "pose", + "value": { + "position": { + "x": -744179.2414489042, + "y": -5466945.298349385, + "z": 3199101.5023454726 + }, + "direction": { + "x": 0.2040230499283474, + "y": 0.9652742041266187, + "z": -0.1631573042975954 + }, + "up": { + "x": 0.20331111154933998, + "y": 0.12125033636499621, + "z": 0.971577556272245 + }, + "right": { + "x": 0.9576216304044657, + "y": -0.231395909166732, + "z": -0.1715131079608628 + }, + "heading": 0.199925453927559, + "pitch": -1.199999607856077, + "roll": 6.2831849106714515, + "height": 5001.990172385319, + "frameIsIdentity": true + } + }, + { + "step": 28, + "kind": "pose", + "value": { + "position": { + "x": -744372.9914909918, + "y": -5466832.025336116, + "z": 3199249.992913194 + }, + "direction": { + "x": 0.20405222591363384, + "y": 0.9652637587817955, + "z": -0.1631826126832485 + }, + "up": { + "x": 0.20330234482603304, + "y": 0.1212726692625212, + "z": 0.9715766034020066 + }, + "right": { + "x": 0.9576172751616003, + "y": -0.23142777636313006, + "z": -0.171494427430424 + }, + "heading": 0.19990669247367698, + "pitch": -1.19999950921419, + "roll": 6.283184810827273, + "height": 5002.490919151834, + "frameIsIdentity": true + } + }, + { + "step": 54, + "kind": "pose", + "value": { + "position": { + "x": 7805906.904869736, + "y": -14670498.917206015, + "z": 13440141.433819043 + }, + "direction": { + "x": -0.3655537074410778, + "y": 0.6843524703919436, + "z": -0.6308979182439318 + }, + "up": { + "x": 0.110917768366866, + "y": 0.7050070428413021, + "z": 0.7004729246763767 + }, + "right": { + "x": 0.9241578521208361, + "y": 0.18608268541862594, + "z": -0.3336247870749348 + }, + "heading": 0.443475027365972, + "pitch": -1.5693855130982848, + "roll": 0, + "height": 15003040.278641503, + "frameIsIdentity": true + } + } + ], + "flights": [] + }, + "thirty pixel-mode wheel notches from 5 km, then out again": { + "records": [ + { + "step": 23, + "kind": "pose", + "value": { + "position": { + "x": -742628.7924789503, + "y": -5463700.648822847, + "z": 3197887.172893453 + }, + "direction": { + "x": 0.20390710151866062, + "y": 0.9653157014443385, + "z": -0.1630567094457735 + }, + "up": { + "x": 0.2033459565896657, + "y": 0.12116157542641381, + "z": 0.971581337088575 + }, + "right": { + "x": 0.9576389277221831, + "y": -0.23126925689597005, + "z": -0.17158733906058854 + }, + "heading": 0.20002548249494634, + "pitch": -1.1997833418598227, + "roll": 6.283184995415831, + "height": 1432.7693523452285, + "frameIsIdentity": true + } + }, + { + "step": 44, + "kind": "pose", + "value": { + "position": { + "x": -742405.2309695639, + "y": -5462642.287276622, + "z": 3197708.399305835 + }, + "direction": { + "x": 0.20390710151866057, + "y": 0.9653157014443385, + "z": -0.1630567094457731 + }, + "up": { + "x": 0.20334595658966526, + "y": 0.12116157542641454, + "z": 0.9715813370885751 + }, + "right": { + "x": 0.9576389277221832, + "y": -0.2312692568959699, + "z": -0.17158733906058796 + }, + "heading": 0.20003278999578278, + "pitch": -1.1997212353912805, + "roll": 6.283184906110748, + "height": 410.9902001027421, + "frameIsIdentity": true + } + }, + { + "step": 65, + "kind": "pose", + "value": { + "position": { + "x": -742341.2056470874, + "y": -5462339.185282548, + "z": 3197657.2007044787 + }, + "direction": { + "x": 0.20390710151866076, + "y": 0.9653157014443386, + "z": -0.16305670944577244 + }, + "up": { + "x": 0.20334595658966534, + "y": 0.121161575426415, + "z": 0.971581337088575 + }, + "right": { + "x": 0.9576389277221832, + "y": -0.23126925689596994, + "z": -0.17158733906058796 + }, + "heading": 0.20003488343521703, + "pitch": -1.199703445182633, + "roll": 6.28318488053483, + "height": 118.36954505315934, + "frameIsIdentity": true + } + }, + { + "step": 67, + "kind": "pose", + "value": { + "position": { + "x": -742333.1507133974, + "y": -5462301.052456831, + "z": 3197650.759482114 + }, + "direction": { + "x": 0.20390710151866143, + "y": 0.9653157014443386, + "z": -0.16305670944577194 + }, + "up": { + "x": 0.20334595658966512, + "y": 0.12116157542641479, + "z": 0.9715813370885751 + }, + "right": { + "x": 0.9576389277221832, + "y": -0.23126925689597047, + "z": -0.1715873390605877 + }, + "heading": 0.20003514682861567, + "pitch": -1.199701206906512, + "roll": 6.283184877317159, + "height": 81.55550603363947, + "frameIsIdentity": true + } + }, + { + "step": 79, + "kind": "pose", + "value": { + "position": { + "x": -742361.5559644367, + "y": -5462435.52562931, + "z": 3197673.474074843 + }, + "direction": { + "x": 0.2039071015186621, + "y": 0.9653157014443386, + "z": -0.1630567094457709 + }, + "up": { + "x": 0.2033459565896656, + "y": 0.12116157542641448, + "z": 0.971581337088575 + }, + "right": { + "x": 0.957638927722183, + "y": -0.23126925689597097, + "z": -0.17158733906058815 + }, + "heading": 0.2000342180079615, + "pitch": -1.199709099940855, + "roll": 6.283184888664081, + "height": 211.37819848930863, + "frameIsIdentity": true + } + } + ], + "flights": [] + }, + "thirty line-mode wheel notches from 5 km": { + "records": [ + { + "step": 23, + "kind": "pose", + "value": { + "position": { + "x": -742556.7099509701, + "y": -5463359.40324807, + "z": 3197829.5312530524 + }, + "direction": { + "x": 0.20390710151866023, + "y": 0.9653157014443386, + "z": -0.1630567094457732 + }, + "up": { + "x": 0.203345956589666, + "y": 0.12116157542641305, + "z": 0.9715813370885751 + }, + "right": { + "x": 0.9576389277221831, + "y": -0.2312692568959697, + "z": -0.17158733906058904 + }, + "heading": 0.20002783824820192, + "pitch": -1.1997633191576402, + "roll": 6.283184966621368, + "height": 1103.3162549917931, + "frameIsIdentity": true + } + }, + { + "step": 65, + "kind": "pose", + "value": { + "position": { + "x": -742322.8917203792, + "y": -5462252.485403653, + "z": 3197642.555757815 + }, + "direction": { + "x": 0.20390710151865987, + "y": 0.9653157014443383, + "z": -0.16305670944577555 + }, + "up": { + "x": 0.20334595658966786, + "y": 0.12116157542641243, + "z": 0.9715813370885749 + }, + "right": { + "x": 0.9576389277221826, + "y": -0.23126925689597005, + "z": -0.17158733906059095 + }, + "heading": 0.20003548230067558, + "pitch": -1.1996983561368815, + "roll": 6.2831848732190485, + "height": 34.668143935951555, + "frameIsIdentity": true + } + } + ], + "flights": [] + }, + "a middle drag tilts about the centre, then coasts": { + "records": [ + { + "step": 24, + "kind": "pose", + "value": { + "position": { + "x": -743241.7317811222, + "y": -5464487.455673964, + "z": 3195978.047404553 + }, + "direction": { + "x": 0.3675783291212823, + "y": 0.81316539817522, + "z": 0.4512739823776041 + }, + "up": { + "x": 0.08270178763465089, + "y": -0.5119037171950899, + "z": 0.8550526291661131 + }, + "right": { + "x": 0.9263080407091582, + "y": -0.27697765168400346, + "z": -0.2554149451092779 + }, + "heading": 0.3008134433902425, + "pitch": -0.5367351449364697, + "roll": 6.282589696577563, + "height": 1215.0821198795002, + "frameIsIdentity": true + } + }, + { + "step": 26, + "kind": "pose", + "value": { + "position": { + "x": -743241.80671276, + "y": -5463765.475245942, + "z": 3195201.3342659683 + }, + "direction": { + "x": 0.36760985348731867, + "y": 0.5094221457939676, + "z": 0.7780437474806298 + }, + "up": { + "x": -0.0855345107763599, + "y": -0.8145571574843389, + "z": 0.5737425247071049 + }, + "right": { + "x": 0.9260382514158263, + "y": -0.2774629967503845, + "z": -0.2558660633007341 + }, + "heading": 0.3012445916881008, + "pitch": -0.08686439532730006, + "roll": 6.282451156320272, + "height": 205.77116965382524, + "frameIsIdentity": true + } + } + ], + "flights": [] + }, + "modified drags: Shift looks, Ctrl tilts, held too long to coast": { + "records": [ + { + "step": 26, + "kind": "pose", + "value": { + "position": { + "x": -743060.1500720647, + "y": -5464827.966102482, + "z": 3196999.1724985815 + }, + "direction": { + "x": 0.3198554534385449, + "y": 0.8196936321897058, + "z": 0.4751787434779361 + }, + "up": { + "x": 0.07739593213172483, + "y": -0.5224541754567694, + "z": 0.8491475161815223 + }, + "right": { + "x": 0.9442999304220479, + "y": -0.2348275620437983, + "z": -0.23055076991734758 + }, + "heading": 0.2406372218166659, + "pitch": -0.5226924574159404, + "roll": 0.028997148507913906, + "height": 2000.0000000013995, + "frameIsIdentity": true + } + }, + { + "step": 51, + "kind": "pose", + "value": { + "position": { + "x": -743061.3004932855, + "y": -5464044.082279529, + "z": 3196047.0359984883 + }, + "direction": { + "x": 0.3201424713636519, + "y": 0.6241229075555551, + "z": 0.712726731849994 + }, + "up": { + "x": -0.02221334720207947, + "y": -0.7471697869219248, + "z": 0.66426190370751 + }, + "right": { + "x": 0.9471089510902393, + "y": -0.22849049384043377, + "z": -0.22533692327113536 + }, + "heading": 0.2408776874059173, + "pitch": -0.21383964601254024, + "roll": 0.028905924656936755, + "height": 849.3858537714274, + "frameIsIdentity": true + } + } + ], + "flights": [] + }, "projection, picks and the horizon": { "records": [ { diff --git a/src/render/conformance/index.js b/src/render/conformance/index.js index c071b121a..810a62167 100644 --- a/src/render/conformance/index.js +++ b/src/render/conformance/index.js @@ -19,7 +19,8 @@ * ``` * * Optional harness members widen what is checked: `pointer(r, type, x, y)` - * (synthetic input), `scriptHeights(r, fn)` (heights from a function), + * (synthetic input; with `cameraInput`, the camera scripts' drags and + * wheels too), `scriptHeights(r, fn)` (heights from a function), * `wallTime(r)` (the wall clock a `live` motion clock reads), * `assets.model` (a glTF URL). `create` may return null when it cannot * make a renderer with fewer capabilities; those checks are then skipped. @@ -46,6 +47,10 @@ import { portChecks } from './checks/ports.js'; * @property {ConformanceTolerance} tolerance * @property {'trace'|'endpoints'} flightPaths Whether flight paths are compared frame by frame, or only where flights end. * @property {(r: object, type: string, x: number, y: number, extra?: object) => void|Promise} [pointer] + * A move's `x, y` is where it started and `extra.endPosition` where it + * went; `extra` also has `button` (a move's the one held), `modifiers` + * and, for a wheel, `delta` in the input port's lines. + * @property {boolean} [cameraInput] The renderer's camera moves on pointer input sent through `pointer` (its own gestures, or a camera controller's): the camera scripts with `input` steps run. * @property {(r: object, fn: (point: {lon: number, lat: number}, against?: string) => number|null) => void} [scriptHeights] * @property {(r: object) => number} [wallTime] Epoch ms the renderer's `live` motion clock reads. * @property {{model?: string}} [assets] @@ -111,7 +116,7 @@ export async function runConformance(harness, options = {}) { }; } -export { CAMERA_SCRIPTS, SCRIPT_VIEWPORT } from './cameraScripts.js'; +export { CAMERA_SCRIPTS, SCRIPT_VIEWPORT, usesInput } from './cameraScripts.js'; export { CALIBRATION_PATH, REFERENCE_SCENES, sceneSupport } from './scenes.js'; export { VISUAL_TOLERANCE, diff --git a/src/render/contract/input.d.ts b/src/render/contract/input.d.ts index 742377581..c2dd8b6ea 100644 --- a/src/render/contract/input.d.ts +++ b/src/render/contract/input.d.ts @@ -57,7 +57,12 @@ export interface PointerEv { pointerType: 'mouse' | 'touch' | 'pen'; /** `click`: how far the pointer travelled and how long the press lasted. */ gesture?: { travelPx: number; durationMs: number }; - /** `wheel`: lines scrolled; `pinch`: scale since the last event. */ + /** + * `wheel`: lines scrolled, down positive, counted as the reference + * renderer counts them: a pixel-mode wheel at 40 px a line, a page at 3 + * lines (so 40 px a line turns either back into the reference's pixels); + * `pinch`: scale since the last event. + */ delta?: number; /** `click` and `dblclick`: the hit under the pointer, picked once for every subscriber. */ pick?(): Hit | null; diff --git a/src/render/input/wheel.js b/src/render/input/wheel.js new file mode 100644 index 000000000..41e0eed4c --- /dev/null +++ b/src/render/input/wheel.js @@ -0,0 +1,29 @@ +/** + * @module render/input/wheel + * @description A DOM wheel event as the input port's `wheel` delta: lines + * scrolled, counted as the reference renderer counts them, so a camera + * controller that turns lines back into pixels at `WHEEL_PX_PER_LINE` + * zooms exactly as the reference does in every browser. + * + * The reference takes a pixel-mode wheel as its pixels, a line-mode one at + * 40 px a line and a page-mode one at 120 px a page. Lines are those + * pixels over 40: a line-mode wheel is its own lines, a page is 3 lines, + * and a pixel-mode wheel (Chrome's notch is 100 px) is its pixels over 40 + * (2.5 lines a notch). + */ + +/** Pixels a wheel line stands for: the reference renderer's own count. */ +export const WHEEL_PX_PER_LINE = 40; +/** Lines a wheel page stands for: the reference's 120 px a page. */ +export const WHEEL_LINES_PER_PAGE = 3; + +/** + * Lines scrolled by a DOM wheel event, down positive (as `deltaY`). + * @param {{deltaY: number, deltaMode?: number}} event + * @returns {number} + */ +export function wheelLines({ deltaY, deltaMode = 0 }) { + if (deltaMode === 1) return deltaY; + if (deltaMode === 2) return deltaY * WHEEL_LINES_PER_PAGE; + return deltaY / WHEEL_PX_PER_LINE; +} diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 547fbc148..09b34b0fd 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -2,7 +2,11 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createStubRenderer } from './index.js'; import { createStubHarness } from './harness.js'; -import { runConformance } from '../conformance/index.js'; +import { + CAMERA_SCRIPTS, + runConformance, + usesInput, +} from '../conformance/index.js'; import { toEcef } from './math.js'; test('the stub passes the conformance suite', async () => { @@ -15,7 +19,12 @@ test('the stub passes the conformance suite', async () => { const skipped = report.results .filter((r) => r.status === 'skip') .map((r) => r.id); - assert.deepEqual(skipped, []); + // Its camera takes no user gestures: the drag and wheel scripts are for + // a camera that does (a controller over it, say). + assert.deepEqual( + skipped, + CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`), + ); }); test('a frame runs the contract’s steps in order', () => { From 3276a3346ece319dfd901bac70843f9817b4e8e3 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 20:49:08 -0800 Subject: [PATCH 3/4] Draw a moving clamped fill every frame in the Cesium draw port A clamped colour fill (a polygon, a fixed-radius ellipse or a rectangle) whose upsert changed only its geometry rebuilt its set's ground primitive batches asynchronously, and each upsert dropped the build in flight, so a shape dragged every frame never drew. Once Cesium's terrain heights are loaded, such a fill is now drawn alone where it now is, on a ground primitive built in the same frame with the same pick id, and hidden in its batch and in a host still retiring. That mirrors how a moved draped line is drawn. A set draws at most MOVING_SHAPES fills alone, counting those a retiring host still draws; an upsert that would draw more rebuilds as before. A set whose moved fills have been still for SETTLE_FRAMES drawn frames rebuilds once, so they go back into its batches. If a second rebuild drops the host drawing a fill alone before that host is ready, the fill shows again where the retiring host draws it, unless it is hidden or gone. --- src/render/cesium/draw.js | 216 +++++++++++++++++++- src/render/cesium/draw.test.mjs | 339 ++++++++++++++++++++++++++++++++ 2 files changed, 545 insertions(+), 10 deletions(-) diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 210db8ec4..abb161b80 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -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; } /** @@ -2625,7 +2639,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 && @@ -2634,6 +2651,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); @@ -2869,6 +2887,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) @@ -3084,29 +3105,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) && @@ -3395,6 +3585,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()); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 85963d727..50846e25d 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -6,6 +6,7 @@ import { createCesiumDraw, FEW_LOOSE_LINES, LONG_SETTLE_FRAMES, + MOVING_SHAPES, revealUniform, SETTLE_FRAMES, unboundDrawPart, @@ -5917,3 +5918,341 @@ 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(); + })); From 04a764ed86d53ff43215bd2a5e7b408198b3662a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 21:18:56 -0800 Subject: [PATCH 4/4] Draw the Recent Imagery box preview through the draw port, off the Cesium list The box being dragged was two Cesium entities on a data source of its own. It is now a clamped colour rectangle in a shapes set and a draped dashed outline in a lines set, both unpickable, with the same colour, alpha, width and dash length. The Cesium draw port now redraws a moved clamped fill in the frame it moves, so the box shows on every frame of the drag. The fill shows once the box has an area. The outline shows once the box has any extent, so a drag along one axis still draws a line. The last box is kept hidden between drags, and the next drag moves it. markBaseTileset moves to a Cesium-free module, src/render/baseTilesets.js. The globe port reads it and re-exports it, so a tileset a caller marks as its base is still draped on. rendering.js no longer imports Cesium or reaches the viewer and leaves the Cesium allow-list. The application's tools loaded the globe factory only through it, so embed.js now loads it. --- scripts/package-boundaries.json | 6 + src/app/embed.js | 4 + src/layers/recentImagery/index.test.mjs | 3 +- src/layers/recentImagery/rendering.js | 192 ++++++++++++-------- src/layers/recentImagery/rendering.test.mjs | 68 +++++++ src/render/baseTilesets.js | 24 +++ src/render/cesium/draw.test.mjs | 46 +++++ src/render/cesium/globe.js | 24 +-- src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 5 +- src/ui/imageryBoxTool.test.mjs | 38 +++- 11 files changed, 307 insertions(+), 104 deletions(-) create mode 100644 src/render/baseTilesets.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index db798ef65..b8acca88b 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1048,6 +1048,7 @@ "src/sky/starrySky.js", "src/render/cesium/effects.js", "src/render/cesium/globe.js", + "src/render/baseTilesets.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", "src/maps/google3d.js", @@ -1830,6 +1831,7 @@ "modules": [ "src/render/cesium/unbound.js", "src/render/cesium/globe.js", + "src/render/baseTilesets.js", "src/maps/google3d.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", @@ -2376,6 +2378,7 @@ "src/sources/requestDeadline.js", "src/layers/traffic/lifecycle.js", "src/render/cesium/globe.js", + "src/render/baseTilesets.js", "src/maps/google3d.js", "src/render/cesium/imagery.js", "src/render/cesium/tileRequests.js", @@ -3020,6 +3023,7 @@ "src/maps/catalog.js", "src/maps/controller.js", "src/render/cesium/globe.js", + "src/render/baseTilesets.js", "src/render/cesium/iconSetPrimitive.js", "src/data/aircraftRecession.js", "src/data/iconSet.js", @@ -3265,6 +3269,7 @@ "src/render/motion/iconMotion.js", "src/render/cesium/query.js", "src/render/cesium/globe.js", + "src/render/baseTilesets.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", "src/render/cesium/drawMeshes.js", @@ -4795,6 +4800,7 @@ "src/layers/recentImagery/model.js", "src/layers/recentImagery/catalog.js", "src/layers/recentImagery/rendering.js", + "src/render/baseTilesets.js", "src/render/cesium/globe.js", "src/layers/recentImagery/thumbnails.js", "src/maps/imageryHost.js", diff --git a/src/app/embed.js b/src/app/embed.js index 897453f40..6cf272584 100644 --- a/src/app/embed.js +++ b/src/app/embed.js @@ -14,6 +14,10 @@ import * as Cesium from 'cesium'; import { announceNavigationAuthority } from '../navigationPolicy.js'; import { cameraOf } from '../render/cesium/camera.js'; +// The application's tools reach `findGlobe` callers too (the Recent Imagery +// panel, Import and others): a viewer with no renderer bound gets its globe +// port from here, as it gets its camera. +import '../render/cesium/globe.js'; import { annotationsFromParams, createView } from '../view/index.js'; const EMBED_VIEW_MESSAGE = 'gev:view'; diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 6e5be08f7..71cc71f4a 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -14,6 +14,7 @@ import { createRecentImageryLayer, } from './index.js'; import { createImageryBoxPreview } from './rendering.js'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; import { BOX, CANDIDATES, @@ -1408,7 +1409,7 @@ test('with SELECT BOX armed, Escape clears the preview first and the next Escape const tool = initImageryBoxTool({ viewer: fakes.viewer, createPreview: (viewer, dragBox) => - createImageryBoxPreview(viewer, dragBox, { cesium: fakes.cesium }), + createImageryBoxPreview(viewer, dragBox, { draw: fakeDrawPort() }), pickWorld: fakes.pickWorld, documentRef: fakes.documentRef, onBox: (box) => f.layer.setBox(box), diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index da5c0bb1d..6edf44ab2 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -7,13 +7,14 @@ * each layer's admission hook; the renderer's own request limits stay * untouched. */ -// The layer flies through `cameraOf` and drapes through `findGlobe`; this -// renderer is its Cesium side, so it brings the factories a viewer with no -// renderer bound gets those ports from, and marks a tileset host as a base -// the globe port drapes on. -import * as Cesium from 'cesium'; -import '../../render/cesium/camera.js'; -import { markBaseTileset } from '../../render/cesium/globe.js'; +// The imagery drapes through the globe port and the box preview draws +// through `drawOf`, both on the renderer's ports: a viewer with no renderer +// bound gets them once its owner has loaded the package's +// `./render/cesium/unbound` export. A tileset host is marked as a base the +// globe port drapes on (`markBaseTileset`). +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { markBaseTileset } from '../../render/baseTilesets.js'; +import { drawOf } from '../../render/rendererOf.js'; import { PRODUCTS, gibsTemplate } from './model.js'; const SLOT_IDS = ['a', 'b']; @@ -237,96 +238,127 @@ export function createRecentImageryRenderer({ }; } +const PREVIEW_STROKE = Object.freeze([139 / 255, 233 / 255, 1]); +/** Fill alpha and outline alpha of the box being dragged. */ +const PREVIEW_FILL_ALPHA = 0.12; +const PREVIEW_LINE_ALPHA = 0.95; +/** Each preview's draw sets have ids of their own. */ +let previewSeq = 0; + +/** A box with no area has no fill: a press, or a drag along one axis. */ +const hasArea = (box) => + Boolean(box) && box.east > box.west && box.north > box.south; + +/** A box with no extent draws nothing: a press that has not moved yet. */ +const hasExtent = (box) => + Boolean(box) && (box.east > box.west || box.north > box.south); + /** * The box tool's preview: the box being dragged, a translucent fill and a - * dashed outline on the ground (the draw port draws no dashed draped - * lines), read from `dragBox()` each frame it draws. + * dashed outline on the ground, drawn through the draw port. Each change + * moves them where they are (the port draws a moved ground fill and a moved + * draped line in the frame they move), so the box shows every frame of a + * drag. * @param {object} viewer * @param {() => ({west: number, south: number, east: number, north: number}|null)} dragBox * Degrees, or null while no drag is live. - * @param {{cesium?: object}} [options] The Cesium namespace (tests pass a double). + * @param {{draw?: import('../../render/contract/draw').DrawPort}} [options] + * The draw port (tests pass a double); the viewer's by default. * @returns {{setVisible: (visible: boolean) => void, changed: () => void, destroy: () => Promise}} */ export function createImageryBoxPreview( viewer, dragBox, - { cesium = Cesium } = {}, + { draw = drawOf(viewer) } = {}, ) { - const dataSource = new cesium.CustomDataSource( - 'gev-recent-imagery-box-preview', - ); - let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch( - () => null, - ); + previewSeq += 1; + const fills = draw.shapes({ + id: `recent-imagery-box:${previewSeq}:fill`, + pickable: false, + }); + const outlines = draw.lines({ + id: `recent-imagery-box:${previewSeq}:outline`, + pickable: false, + }); + let visible = false; let destroyed = false; - const stroke = cesium.Color.fromCssColorString('#8be9ff'); - const previewRectangle = () => { - const box = dragBox(); - return box - ? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north) - : undefined; - }; - const previewOutline = () => { - const box = dragBox(); - if (!box) return []; - return cesium.Cartesian3.fromDegreesArray([ - box.west, - box.south, - box.east, - box.south, - box.east, - box.north, - box.west, - box.north, - box.west, - box.south, + // The sets go at once; every caller gets the same settled promise. + const gone = Promise.resolve(); + // The last box drawn, and the last with an area: a box without one keeps + // it, hidden, so the next one moves it rather than draw it anew. + let drawn = null; + let filled = null; + + function drawFill(box, show) { + const { west, south, east, north } = box; + fills.upsert([ + { + id: 'box', + geometry: { kind: 'rectangle', rect: { west, south, east, north } }, + fill: [...PREVIEW_STROKE, PREVIEW_FILL_ALPHA], + height: 'clampGround', + clampTo: 'both', + show, + }, ]); - }; - const fill = dataSource.entities.add({ - show: false, - rectangle: { - coordinates: new cesium.CallbackProperty(previewRectangle, false), - material: stroke.withAlpha(0.12), - classificationType: cesium.ClassificationType.BOTH, - }, - }); - // A rectangle graphic cannot draw a dashed edge on the ground, so the - // outline is its own draped polyline traced round the same corners. - const outline = dataSource.entities.add({ - show: false, - polyline: { - positions: new cesium.CallbackProperty(previewOutline, false), - width: 2, - clampToGround: true, - classificationType: cesium.ClassificationType.BOTH, - material: new cesium.PolylineDashMaterialProperty({ - color: stroke.withAlpha(0.95), - dashLength: 12, - }), - }, - }); - const requestRender = () => viewer.scene.requestRender?.(); + } + + function drawEdge(box, show) { + const { west, south, east, north } = box; + // A rectangle has no dashed edge on the ground, so the outline is a + // draped line traced round the same corners; a drag along one axis + // draws it as a line along the drag, as the fill has no area. + outlines.upsert([ + { + id: 'edge', + positions: [ + fromDegrees(west, south), + fromDegrees(east, south), + fromDegrees(east, north), + fromDegrees(west, north), + fromDegrees(west, south), + ], + widthPx: 2, + mode: 'draped', + clampTo: 'both', + style: { + kind: 'dash', + color: [...PREVIEW_STROKE, PREVIEW_LINE_ALPHA], + length: 12, + }, + show, + }, + ]); + } + + function update() { + if (destroyed) return; + const box = visible ? dragBox() : null; + if (hasArea(box)) { + filled = { ...box }; + drawFill(filled, true); + } else if (filled) drawFill(filled, false); + if (hasExtent(box)) { + drawn = { ...box }; + drawEdge(drawn, true); + } else if (drawn) drawEdge(drawn, false); + } + return { - setVisible(visible) { - fill.show = visible; - outline.show = visible; - requestRender(); + setVisible(on) { + visible = Boolean(on); + update(); }, /** The box moved: draw it again. */ - changed: requestRender, - /** Detach the preview; resolves once it is gone. */ + changed: update, + /** Take the preview away; resolves once it is gone. */ destroy() { - if (destroyed) return attaching; - destroyed = true; - dataSource.entities.removeAll(); - attaching = attaching.then(() => { - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* viewer already disposed */ - } - }); - return attaching; + if (!destroyed) { + destroyed = true; + fills.dispose(); + outlines.dispose(); + } + return gone; }, }; } diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index d75c0414b..70028d43e 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -2,10 +2,12 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { TILE_RENDER_REASON, + createImageryBoxPreview, createRecentImageryRenderer, } from './rendering.js'; import { BOX } from './testDoubles.mjs'; import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; const S30 = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' }; const L30 = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' }; @@ -203,3 +205,69 @@ test('replacement imagery uses source-owned tile URLs and credit and tears down assert.equal(globe.layers.length, 0); assert.equal(layer.removed, true); }); + +test('the box preview draws a ground fill and a draped dashed edge, hidden rather than dropped between drags', async () => { + const draw = fakeDrawPort(); + let box = null; + const preview = createImageryBoxPreview({}, () => box, { draw }); + const sets = [...draw.sets.values()]; + assert.deepEqual( + sets.map((r) => [r.kind, r.spec.pickable]), + [ + ['shapes', false], + ['lines', false], + ], + ); + const [fills, lines] = sets; + preview.setVisible(true); + assert.equal(fills.items.size, 0, 'no box yet'); + box = { west: -98, south: 30, east: -98, north: 30 }; + preview.changed(); + assert.equal(fills.items.size, 0, 'a press draws nothing'); + assert.equal(lines.items.size, 0); + // Dragged along one axis: the edge draws as a line, the fill has no area. + box = { west: -98, south: 30, east: -97.9, north: 30 }; + preview.changed(); + assert.equal(fills.items.size, 0, 'no fill without an area'); + assert.equal(lines.items.get('edge').show, true, 'the edge along the drag'); + box = { west: -98, south: 30, east: -97.9, north: 30.1 }; + preview.changed(); + const fill = fills.items.get('box'); + assert.deepEqual(fill.geometry.rect, box); + assert.equal(fill.height, 'clampGround'); + assert.equal(fill.clampTo, 'both'); + assert.deepEqual(fill.fill, [139 / 255, 233 / 255, 1, 0.12]); + assert.equal(fill.show, true); + const edge = lines.items.get('edge'); + assert.equal(edge.mode, 'draped'); + assert.equal(edge.clampTo, 'both'); + assert.equal(edge.widthPx, 2); + assert.deepEqual(edge.style, { + kind: 'dash', + color: [139 / 255, 233 / 255, 1, 0.95], + length: 12, + }); + assert.equal(edge.positions.length, 5, 'round the corners and back'); + assert.deepEqual(edge.positions[0], edge.positions[4]); + preview.setVisible(false); + assert.equal(fills.items.get('box').show, false, 'hidden, kept to move'); + assert.equal(lines.items.get('edge').show, false); + // The next drag moves it and shows it again. + box = { west: -97, south: 31, east: -96.5, north: 31.5 }; + preview.setVisible(true); + assert.deepEqual(fills.items.get('box').geometry.rect, box); + assert.equal(fills.items.get('box').show, true); + assert.equal(lines.items.get('edge').show, true); + // A press with no extent hides the last box. + box = { west: -97, south: 31, east: -97, north: 31 }; + preview.changed(); + assert.equal(fills.items.get('box').show, false); + assert.equal(lines.items.get('edge').show, false); + const gone = preview.destroy(); + assert.equal(preview.destroy(), gone, 'the same promise every time'); + await gone; + assert.ok(fills.disposed && lines.disposed); + // Gone: changes after do nothing. + box = { west: -96, south: 32, east: -95, north: 33 }; + assert.doesNotThrow(() => preview.changed()); +}); diff --git a/src/render/baseTilesets.js b/src/render/baseTilesets.js new file mode 100644 index 000000000..594373965 --- /dev/null +++ b/src/render/baseTilesets.js @@ -0,0 +1,24 @@ +/** + * @module render/baseTilesets + * @description Tilesets the application draws as its base outside the + * renderer's globe port, marked so the port drapes imagery on them while + * they are shown. Cesium-free: code that loads its own base, or hands + * a layer one (`recentImagery.attachTileset`), marks it here without + * reaching the renderer; the renderer's globe port reads the marks. + */ + +const marked = new WeakSet(); + +/** + * Mark a tileset as a base the application draws outside the port, so + * imagery drapes on it while it is shown. The port's own photoreal tileset + * needs no mark. + * @param {object} tileset The renderer's tileset object. + */ +export function markBaseTileset(tileset) { + if (tileset && typeof tileset === 'object') marked.add(tileset); +} + +/** Whether `tileset` was marked as a base (`markBaseTileset`). */ +export const isBaseTileset = (tileset) => + Boolean(tileset && typeof tileset === 'object' && marked.has(tileset)); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 50846e25d..27371264f 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -6256,3 +6256,49 @@ test('clamped fills drawn alone by a host still retiring count toward MOVING_SHA ); 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'); +}); diff --git a/src/render/cesium/globe.js b/src/render/cesium/globe.js index 9d5a2c79f..8f59ccd12 100644 --- a/src/render/cesium/globe.js +++ b/src/render/cesium/globe.js @@ -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; } diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 3a34c4189..5fc59d323 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -9,7 +9,6 @@ "src/data/geoImportPins.js", "src/input/dispatcher.js", "src/layers/installations/rendering.js", - "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", "src/layers/traffic/rendering.js", "src/layers/transit/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index c9946b6b9..1a68d1269 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -52,7 +52,6 @@ const UNBOUND = 'src/render/cesium/unbound.js'; * both factories; without it, their styles keep records and draw nothing. */ const INJECTED = { - './layers/recent-imagery': 'src/layers/recentImagery/rendering.js', './ui/visual-settings': 'src/ui/applicationShell.js', }; @@ -135,6 +134,10 @@ const CAMERA_FROM_CALLER = new Set([ // constant from. './voice/actions', './voice/realtime-session', + // It flies through `findCamera` and drapes through `findGlobe`; the + // renderer the application gives it (`rendering.js`, which draws the box + // preview through `drawOf`) is Cesium-free too. + './layers/recent-imagery', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/ui/imageryBoxTool.test.mjs b/src/ui/imageryBoxTool.test.mjs index 4aa5eea97..2ac5041a7 100644 --- a/src/ui/imageryBoxTool.test.mjs +++ b/src/ui/imageryBoxTool.test.mjs @@ -12,17 +12,19 @@ import { } from './imageryBoxTool.js'; import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs'; import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; function fixture(options = {}) { resetPointerOwnership(); const fakes = boxToolFakes(); + const draw = fakeDrawPort(); const boxes = []; const cancels = []; const actives = []; const tool = initImageryBoxTool({ viewer: fakes.viewer, createPreview: (viewer, dragBox) => - createImageryBoxPreview(viewer, dragBox, { cesium: fakes.cesium }), + createImageryBoxPreview(viewer, dragBox, { draw }), pickWorld: fakes.pickWorld, documentRef: fakes.documentRef, onBox: (box) => boxes.push(box), @@ -39,10 +41,27 @@ function fixture(options = {}) { ? fakes.originalClick : fakes.originalDouble : undefined; + // The preview's fill or outline set, while it is live. + const previewSet = (part) => + [...draw.sets.values()].find( + (r) => + !r.disposed && + r.spec.id.startsWith('recent-imagery-box:') && + r.spec.id.endsWith(`:${part}`), + ); + // Whether the box shows: its fill and its outline, drawn and shown. const preview = () => - fakes.viewer.dataSources.sources[0]?.entities.values.every((e) => e.show); + ['fill', 'outline'].every((part) => { + const set = previewSet(part); + return ( + Boolean(set?.items.size) && + [...set.items.values()].every((item) => item.show !== false) + ); + }); return { ...fakes, + draw, + previewSet, tool, boxes, cancels, @@ -63,8 +82,16 @@ test('a session claims the pointer, borrows the stock clicks, freezes the camera assert.equal(f.camera.enableInputs, true, 'not frozen before the press'); f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } }); assert.equal(f.camera.enableInputs, false); - assert.equal(f.preview(), true); + assert.equal(f.preview(), false, 'a press alone has no box to draw'); f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } }); + assert.equal(f.preview(), true, 'the box shows as it is dragged'); + const rect = () => f.previewSet('fill').items.get('box').geometry.rect; + assert.deepEqual( + Object.values(rect()).map((v) => Math.round(v * 1e6) / 1e6), + [-97.85, 30.3, -97.8, 30.35], + ); + assert.equal(f.previewSet('outline').items.get('edge').style.kind, 'dash'); + assert.equal(f.previewSet('outline').items.get('edge').mode, 'draped'); f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 10 } }); // sky: ignored f.fire('LEFT_UP', { position: { x: 500, y: 250 } }); assert.equal(f.boxes.length, 1); @@ -151,13 +178,14 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the const f = fixture(); f.tool.start(); f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } }); - assert.equal(f.viewer.dataSources.sources.length, 1); + assert.ok(f.previewSet('fill') && f.previewSet('outline')); const destroying = f.tool.destroy(); assert.equal(f.tool.destroy(), destroying); await destroying; assert.equal(f.camera.enableInputs, true); assert.equal(pointerOwner(), null); - assert.equal(f.viewer.dataSources.sources.length, 0); + assert.equal(f.previewSet('fill'), undefined, 'the preview is gone'); + assert.equal(f.previewSet('outline'), undefined); assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick); assert.equal(f.tool.start(), false); assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);