Take the input dispatcher off Cesium: pointer input from the renderer's input port, picks from the query port

The dispatcher now builds on renderer.input and the query port, with
positions as plain {x, y}. Its viewer access count is zero and it leaves
the Cesium allow-list. Layers that read the raw engine pick read the Hit,
drawHit or event.native instead, and pickRegistry's resolvePickId and
pickContact take a Hit, with the raw versions kept in the Cesium adapter.

rendererOf gains findInput, provideUnboundInput and provideNativeClick.
event.native carries the engine's pick, drill and pickWindow, and picks
through the follow helper happen inside it. An unbound input port
survives the viewer being bound until it is released.

The query port's pick memo is now per task rather than per frame,
because Cesium's own picks advance the frame number. A click on the sky
skips the depth pass when nothing is on the ray. Touch contact search
keeps its eight-deep drill in a 14x14 window.
This commit is contained in:
Sameh Khamis committed 2026-11-09 00:47:30 -08:00
1 parent 6eb9ceef46
commit 8bcaced6ad
52 files changed
+1836 -484

No files matched your search

+4 -2
View File
@@ -12,11 +12,13 @@ import { cameraFlightActive } from './internals.js';
import { createCesiumFollow } from './follow.js';
import { createCesiumControls } from './cameraControls.js';
import { cameraOf, findCamera, provideUnboundCamera } from '../rendererOf.js';
// Loads the factories an unbound viewer gets its credits, draw, frame and
// query ports from.
// Loads the factories an unbound viewer gets its credits, draw, frame,
// input and query ports from, and a click's own Cesium picks.
import './credits.js';
import './draw.js';
import './frame.js';
import './input.js';
import './nativeClick.js';
import './query.js';
/**
+28 -2
View File
@@ -27,6 +27,7 @@ import { createInputRouter } from '../input/router.js';
import { acquireCameraInput } from './cameraInput.js';
import { installTrackpadPinchZoom } from './ctrlWheelZoom.js';
import { wheelLines } from '../input/wheel.js';
import { provideUnboundInput } from '../rendererOf.js';
const T = Cesium.ScreenSpaceEventType;
const MODIFIERS = [
@@ -94,8 +95,7 @@ function pointerTypeOf(dom, otherwise = 'mouse') {
const inputs = new WeakMap();
/**
* The input port made for a scene, while it lives: the application's
* dispatcher (src/input/dispatcher.js) delivers through it.
* The input port made for a scene, while it lives.
* @param {object} scene
* @returns {ReturnType<typeof createCesiumInput> | null}
*/
@@ -477,3 +477,29 @@ export function createCesiumInput(
inputs.set(scene, self);
return self;
}
// A Cesium viewer with no renderer bound to it gets an
// input port over its canvas when code first asks `findInput` for one (the
// application's dispatcher, src/input/dispatcher.js). Its clicks carry no
// picks: the dispatcher makes its own through `findQuery`. The viewer is its
// owner's, so its stock actions stay on its own handler, taken off only
// while suppressed. `options` are the test doubles' (`createHandler`, `now`,
// `document`).
provideUnboundInput((viewer, options = {}) => {
const scene = viewer?.scene;
if (!scene || typeof scene !== 'object') return null;
// A port someone already made for the scene (a harness's): borrowed.
const made = inputs.get(scene);
if (made) return { port: made.port, dispose() {} };
const { createHandler, now, document } = options;
const input = createCesiumInput(viewer, {
report: (error) => console.error('Pointer input failed', error),
takeStock: false,
...(createHandler ? { createHandler } : {}),
...(now ? { now } : {}),
...(document !== undefined ? { document } : {}),
});
// Kept for its dispatcher when a renderer is bound later, as the
// dispatcher's clicks would otherwise stop.
return { port: input.port, dispose: () => input.dispose(), keep: true };
});
+174
View File
@@ -0,0 +1,174 @@
/**
* @module render/cesium/nativeClick
* @description Cesium's own picks of a click, for what the renderer's picks
* do not name (`rendererOf.js` `nativeClickOf`): things drawn outside the
* draw port, and code still bound to Cesium's pick objects. Each pick is
* made at most once per click, and a hit on the follow's helper entity is a
* hit on its target (`pickThroughFollowHelper`).
*
* Also the raw forms of the shared pick-id and contact rules
* (`src/data/pickRegistry.js`, which reads the contract's `Hit`), for code
* that still holds a Cesium pick.
*/
import * as Cesium from 'cesium';
import { findPickOwner } from '../../data/pickRegistry.js';
import { isSurfacePick } from '../../data/scenePick.js';
import { provideNativeClick } from '../rendererOf.js';
import { drawHitOf } from './drawHit.js';
import { pickThroughFollowHelper } from './follow.js';
import { recentPick } from './pickMemo.js';
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
const DRILL_DEPTH = 16;
/**
* A Cesium pick's canonical pick id: its id, or its primitive's, as a
* String (satellites' numeric NORAD ids, an entity's own `id`); null when it
* carries none.
* @param {object|null|undefined} picked What `scene.pick` gave.
* @returns {string|null}
*/
export function nativePickId(picked) {
if (!picked) return null;
const unwrap = (id) => {
if (id === null || id === undefined) return undefined;
if (typeof id === 'object') {
// A Cesium Entity (.id string), or a draw-set item's pick id.
if (typeof id.id === 'string' || typeof id.id === 'number') return id.id;
return undefined;
}
return id;
};
let id = unwrap(picked.id);
if (id === undefined) id = unwrap(picked.primitive?.id);
return typeof id === 'string' || typeof id === 'number' ? String(id) : null;
}
/**
* `pickContact` (`src/data/pickRegistry.js`) over Cesium's own picks: on a
* coarse pointer, the first registered contact under a surface pick.
* @param {object} scene
* @param {{x: number, y: number}} position
* @param {{picked?: object|null, drill?: (limit: number, width: number, height: number) => object[]}} [options]
* @returns {object|null|undefined}
*/
export function nativePickContact(scene, position, options = {}) {
const picked = 'picked' in options ? options.picked : scene.pick(position);
if (
!globalThis.matchMedia?.('(pointer: coarse)').matches ||
findPickOwner(nativePickId(picked)) ||
!isSurfacePick(picked) ||
typeof scene.drillPick !== 'function'
)
return picked;
let hits;
try {
hits =
(options.drill
? options.drill(8, 14, 14)
: scene.drillPick(position, 8, 14, 14)) || [];
} catch {
return picked;
}
for (const hit of hits.slice(0, 8)) {
if (findPickOwner(nativePickId(hit))) return hit;
if (!isSurfacePick(hit)) break;
}
return picked;
}
/**
* What is on top as Cesium sees it, where the renderer's pick names
* nothing: a draw-set item the renderer's sets do not hold (one drawn by a
* draw port a renderer bound since superseded) as its hit, anything else
* but the map by its id; null for the map or nothing.
*/
const foreignOf = (picked) =>
isSurfacePick(picked)
? null
: (drawHitOf(picked) ?? { id: nativePickId(picked) });
/** A Cesium pick as the contract's `Hit`, a foreign one with no set. */
const hitOf = (picked) =>
drawHitOf(picked) ??
(isSurfacePick(picked)
? { set: '', id: '', surface: true }
: { set: '', id: nativePickId(picked), surface: false });
/**
* A click's Cesium picks at a pick-buffer position.
* @param {object} scene
* @param {{x: number, y: number}} at
* @returns {import('../rendererOf.js').NativeClick}
*/
export function createNativeClick(scene, at) {
const position = new Cesium.Cartesian2(at.x, at.y);
const memo = new Map();
const once = (key, compute) => {
if (!memo.has(key)) memo.set(key, compute());
return memo.get(key);
};
/** @type {Map<string, {limit: number, hits: object[]}>} */
const drills = new Map();
// The query port's pick of this pixel, when it just made one: the click
// reads the renderer's pick first, so its own Cesium pick costs no pass.
const picked = (width, height) => {
const recent = recentPick(scene, at.x, at.y, width ?? 3, height ?? 3);
return recent
? recent.picked
: width === undefined
? scene.pick(position)
: scene.pick(position, width, height);
};
const native = {
/** `scene.pick` at the click. */
get pick() {
return once('pick', () => pickThroughFollowHelper(picked()));
},
/** `scene.pick` with a wider window. */
pickWindow(width, height) {
return once(`window:${width}x${height}`, () =>
pickThroughFollowHelper(picked(width, height)),
);
},
/** `scene.drillPick`, at most `limit` hits. */
drill(limit = DRILL_DEPTH, width, height) {
const key = `${width}x${height}`;
const done = drills.get(key);
// A pass that came back short already holds every hit there is.
if (done && (limit <= done.limit || done.hits.length < done.limit))
return done.hits.slice(0, limit);
if (typeof scene.drillPick !== 'function') return [];
// Only the default window is shared between callers; round that one up.
const depth =
width === undefined && height === undefined
? Math.max(limit, DRILL_DEPTH)
: limit;
const hits = (scene.drillPick(position, depth, width, height) || [])
.map(pickThroughFollowHelper)
.filter(Boolean);
drills.set(key, { limit: depth, hits });
return hits.slice(0, limit);
},
};
return {
native,
drillHits: (limit, width, height) =>
native.drill(limit, width, height).map(hitOf),
foreign: (width, height) =>
foreignOf(
width === undefined && height === undefined
? native.pick
: native.pickWindow(width, height),
),
};
}
// Any Cesium viewer, bound or not, by shape: a caller's may come from
// another copy of Cesium.
provideNativeClick((viewer, at) => {
const scene = viewer?.scene;
if (typeof scene?.pick !== 'function') return null;
return createNativeClick(scene, at);
});
+319
View File
@@ -0,0 +1,319 @@
/**
* The raw forms of the shared pick-id and contact rules, over Cesium's own picks
* (`nativePickId`, `nativePickContact`), and a click's own Cesium picks.
*
* - nativePickId reduces every Cesium pick shape (string ids, numeric NORAD
* ids, Cesium Entity objects, draw-set pick ids) to ONE canonical String id.
*/
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
} from '../../data/pickRegistry.js';
import {
createNativeClick,
nativePickContact as pickContact,
nativePickId as resolvePickId,
} from './nativeClick.js';
import { nativeClickOf } from '../rendererOf.js';
import { rememberPick } from './pickMemo.js';
// ---------------------------------------------------------------------------
// resolvePickId — canonical String coercion for every layer's pick shape
// ---------------------------------------------------------------------------
test('resolvePickId: string pick id (flights/military/bikeshare/cctv billboards)', () => {
assert.equal(resolvePickId({ id: 'aaa001' }), 'aaa001');
assert.equal(
resolvePickId({ id: undefined, primitive: { id: 'station:austin:1' } }),
'station:austin:1',
);
});
test('resolvePickId: numeric pick id (satellite NORAD numbers) → String', () => {
assert.equal(resolvePickId({ id: 25544 }), '25544');
assert.equal(
resolvePickId({ id: undefined, primitive: { id: 43013 } }),
'43013',
);
});
test('resolvePickId: Cesium-Entity-like object → its string id', () => {
const entity = { id: 'cctv-atx-cam-3-center', properties: {} };
assert.equal(resolvePickId({ id: entity }), 'cctv-atx-cam-3-center');
});
test('resolvePickId: a draw-set pick id → its item id', () => {
assert.equal(
resolvePickId({ id: { set: 'quakes:1', id: 'quake:a' } }),
'quake:a',
);
});
test('resolvePickId: unresolvable picks → null', () => {
assert.equal(resolvePickId(null), null);
assert.equal(resolvePickId(undefined), null);
assert.equal(resolvePickId({}), null);
assert.equal(resolvePickId({ id: {} }), null); // object with no id
assert.equal(resolvePickId({ primitive: {} }), null);
});
function primaryPointer(t, coarse) {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');
Object.defineProperty(globalThis, 'matchMedia', {
configurable: true,
value: (query) => ({ matches: query === '(pointer: coarse)' && coarse }),
});
t.after(() => {
if (previous) Object.defineProperty(globalThis, 'matchMedia', previous);
else delete globalThis.matchMedia;
});
}
function contactOwners(t) {
registerPickOwner('flights', (id) => id === 'civil');
registerPickOwner('military', (id) => id === 'military');
registerPickOwner('ais-live-vessels', (id) => id === '123456789');
t.after(() => {
for (const id of ['flights', 'military', 'ais-live-vessels'])
unregisterPickOwner(id);
});
}
const mapTile = { primitive: { isCesium3DTileset: true } };
test('touch contact pick expands only a surface miss, bounded to 8 hits in 14 CSS pixels', (t) => {
primaryPointer(t, true);
contactOwners(t);
const position = { x: 30, y: 50 };
const contact = { primitive: { id: 'civil' } };
let drills = 0;
const scene = {
pick(point) {
assert.equal(point, position);
return mapTile;
},
drillPick(...args) {
drills++;
assert.deepEqual(args, [position, 8, 14, 14]);
return [mapTile, contact];
},
};
assert.equal(pickContact(scene, position), contact);
assert.equal(drills, 1);
});
test('touch contact pick returns the first registered sibling, never a caller-specific preference', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const first of [{ id: 'military' }, { id: '123456789' }]) {
const scene = {
pick: () => mapTile,
drillPick: () => [mapTile, first, { id: 'civil' }],
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), first);
}
});
test('touch contact pick does not drill through exact registered or unregistered interactive picks', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const exact of [
{ id: 'military' },
{ id: 'custom-annotation' },
{ primitive: { id: 'custom-gizmo' } },
{ primitive: { id: 'civil', isCesium3DTileset: true } },
]) {
const scene = {
pick: () => exact,
drillPick: () => assert.fail('must keep exact interactive hit'),
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), exact);
}
});
test('touch expansion stops at a non-surface object and respects the drill bound', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const hits of [
[mapTile, { id: 'custom-annotation' }, { id: 'civil' }],
[...Array(8).fill(mapTile), { id: 'civil' }],
[mapTile],
]) {
assert.equal(
pickContact(
{ pick: () => mapTile, drillPick: () => hits },
{ x: 1, y: 1 },
),
mapTile,
);
}
});
test('fine primary pointers keep the existing exact mouse pick without a drill', (t) => {
primaryPointer(t, false);
contactOwners(t);
const scene = {
pick: () => mapTile,
drillPick: () => assert.fail('mouse must not expand'),
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), mapTile);
});
test('touch picking tolerates unavailable or failing drill support and preserves empty sky', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const drillPick of [
undefined,
() => {
throw new Error('context lost');
},
() => [],
]) {
assert.equal(
pickContact({ pick: () => undefined, drillPick }, { x: 1, y: 1 }),
undefined,
);
}
});
// ---------------------------------------------------------------------------
// A click's own Cesium picks
// ---------------------------------------------------------------------------
function countingScene(picked) {
const calls = { pick: [], drillPick: [] };
return {
calls,
pick(...args) {
calls.pick.push(args);
return typeof picked === 'function' ? picked(...args) : picked;
},
drillPick(...args) {
calls.drillPick.push(args);
return [];
},
};
}
test('a click picks once, at the pick-buffer position, and names what the draw port does not draw', () => {
const scene = countingScene({ id: 'transit:bus-1' });
const click = createNativeClick(scene, { x: 12, y: 34 });
assert.equal(click.native.pick.id, 'transit:bus-1');
assert.equal(click.native.pick, click.native.pick, 'memoized');
assert.deepEqual(click.foreign(), { id: 'transit:bus-1' });
assert.equal(scene.calls.pick.length, 1);
assert.deepEqual(
[scene.calls.pick[0][0].x, scene.calls.pick[0][0].y],
[12, 34],
);
});
test('the map and nothing are not foreign; a draw-set item is its hit', () => {
assert.deepEqual(
createNativeClick(
countingScene({ id: { set: 'quakes:1', id: 'quake:a' } }),
{
x: 0,
y: 0,
},
).foreign(),
{ set: 'quakes:1', id: 'quake:a', surface: false },
'one the renderer pick did not name: drawn by a superseded draw port',
);
for (const picked of [
undefined,
{ primitive: { isCesium3DTileset: true } },
{ content: {} },
])
assert.equal(
createNativeClick(countingScene(picked), { x: 0, y: 0 }).foreign(),
null,
);
assert.deepEqual(
createNativeClick(countingScene({ primitive: {} }), {
x: 0,
y: 0,
}).foreign(),
{ id: null },
'an id-less primitive is something, with no id',
);
});
test("a click's own pick reuses the query port's pass of the same pixel in the same task", async () => {
const picked = { id: 'transit:bus-1' };
const scene = countingScene(picked);
rememberPick(scene, 5, 6, 3, 3, picked);
assert.equal(createNativeClick(scene, { x: 5, y: 6 }).native.pick, picked);
assert.equal(scene.calls.pick.length, 0);
// Another pixel or window picks again.
createNativeClick(scene, { x: 5, y: 7 }).native.pick;
createNativeClick(scene, { x: 5, y: 6 }).native.pickWindow(9, 9);
assert.equal(scene.calls.pick.length, 2);
// So does a later task: the scene may have drawn since.
await Promise.resolve();
createNativeClick(scene, { x: 5, y: 6 }).native.pick;
assert.equal(scene.calls.pick.length, 3);
});
test("the query port's passes of several windows in one task are all reused", () => {
const picked = { id: 'transit:bus-1' };
const wide = { id: 'transit:bus-2' };
const scene = countingScene(picked);
rememberPick(scene, 5, 6, 3, 3, picked);
rememberPick(scene, 5, 6, 9, 9, wide);
const { native } = createNativeClick(scene, { x: 5, y: 6 });
assert.equal(native.pickWindow(9, 9), wide);
assert.equal(native.pick, picked);
assert.equal(scene.calls.pick.length, 0);
});
test("a drill's hits: draw-set items, the map, and the rest with no set", () => {
const scene = countingScene(undefined);
scene.drillPick = () => [
{ id: { set: 'quakes:1', id: 'quake:a' } },
{ primitive: { isCesium3DTileset: true } },
{ primitive: { id: 'bus-1' } },
{ primitive: {} },
];
assert.deepEqual(
createNativeClick(scene, { x: 0, y: 0 })
.drillHits(8, 14, 14)
.map(({ set, id, surface }) => ({ set, id, surface })),
[
{ set: 'quakes:1', id: 'quake:a', surface: false },
{ set: '', id: '', surface: true },
{ set: '', id: 'bus-1', surface: false },
{ set: '', id: null, surface: false },
],
);
});
test('drills of different depths on one click share a pass', () => {
const hits = Array.from({ length: 20 }, (_, i) => ({ id: `hit-${i}` }));
const scene = countingScene(undefined);
scene.drillPick = (...args) => {
scene.calls.drillPick.push(args);
return hits.slice(0, args[1]);
};
const { native } = createNativeClick(scene, { x: 0, y: 0 });
assert.deepEqual(
[native.drill(12).length, native.drill(8).length, native.drill(16).length],
[12, 8, 16],
);
assert.equal(scene.calls.drillPick.length, 1);
});
test('the adapter provides native clicks for a Cesium-shaped viewer only', () => {
const scene = countingScene({ id: 'x' });
assert.equal(nativeClickOf({ scene }, { x: 1, y: 1 }).native.pick.id, 'x');
assert.equal(nativeClickOf({ scene: {} }, { x: 1, y: 1 }), null);
assert.equal(nativeClickOf(null, { x: 1, y: 1 }), null);
assert.equal(
nativeClickOf({ scene, isDestroyed: () => true }, { x: 1, y: 1 }),
null,
);
});
+49
View File
@@ -0,0 +1,49 @@
/**
* @module render/cesium/pickMemo
* @description Each scene's `pick` passes made in the task running now, as
* Cesium gave them, so a click's own Cesium picks (`nativeClick.js`) reuse
* the query port's pick of the same pixel and window rather than draw the
* pick buffer again. Nothing draws between them: they are forgotten once
* the task that made them ends. No imports.
*/
/**
* Each scene's passes in this task, by pixel and window.
* @type {WeakMap<object, Map<string, unknown>>}
*/
let taskPicks = new WeakMap();
let clearing = false;
const keyOf = (x, y, width, height) => `${x},${y},${width},${height}`;
/**
* Note a `pick` pass `scene.pick` just made, for `recentPick`.
* @param {object} scene
*/
export function rememberPick(scene, x, y, width, height, picked) {
let picks = taskPicks.get(scene);
if (!picks) {
picks = new Map();
taskPicks.set(scene, picks);
}
picks.set(keyOf(x, y, width, height), picked);
if (!clearing) {
clearing = true;
queueMicrotask(() => {
clearing = false;
taskPicks = new WeakMap();
});
}
}
/**
* What the query port's `pick` on `scene` found at exactly this pixel and
* window in the task running now; undefined when it made none there.
* @param {object} scene
* @returns {{picked: unknown} | undefined}
*/
export function recentPick(scene, x, y, width = 3, height = 3) {
const picks = taskPicks.get(scene);
const key = keyOf(x, y, width, height);
return picks?.has(key) ? { picked: picks.get(key) } : undefined;
}
+82 -1
View File
@@ -7,6 +7,7 @@ import {
listenerList,
} from './ports.js';
import { updateCameraChanged } from './internals.js';
import { createNativeClick } from './nativeClick.js';
test('capabilities follow what the scene supports', () => {
const effects = [
@@ -121,7 +122,11 @@ function fakeWidget(overrides = {}) {
const calls = [];
const primitives = [];
const scene = {
camera: { moveStart: event(), moveEnd: event() },
camera: {
moveStart: event(),
moveEnd: event(),
pickEllipsoid: () => undefined,
},
primitives: {
add: (p) => primitives.push(p),
remove: (p) => primitives.splice(primitives.indexOf(p), 1),
@@ -221,6 +226,82 @@ test('pick under something unpickable stops at what hides the rest', () => {
ports.dispose();
});
test('a surface hit over the ellipsoid makes its depth pick only when its position is read', () => {
let depthPicks = 0;
const { widget, scene } = fakeWidget({
pickPosition: () => (depthPicks++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => ({ x: 6378137, y: 0, z: 0 });
const ports = createCesiumPorts(widget, { capabilities: all });
const hit = ports.query.pick(1, 1);
assert.equal(hit.surface, true);
assert.equal(depthPicks, 0, 'no depth pass for a click nobody grounds');
assert.equal(hit.position.x, 6378200, 'the rendered surface, once read');
assert.equal(hit.position.x, 6378200);
assert.equal(depthPicks, 1);
// Over the sky the depth pick decides whether there is a surface at all.
scene.camera.pickEllipsoid = () => undefined;
scene.pickPosition = () => undefined;
assert.equal(ports.query.pick(1, 1), null);
ports.dispose();
});
test('a sky pick makes no depth pass unless something may be there', () => {
let depthPicks = 0;
let globeHit = null;
let picked;
const { widget, scene } = fakeWidget({
pick: () => picked,
pickPosition: () => (depthPicks++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => undefined;
scene.camera.getPickRay = () => ({
origin: { x: 7e6, y: 0, z: 0 },
direction: { x: 0, y: 1, z: 0 },
});
scene.globe.pick = () => globeHit;
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.query.pick(1, 1), null, 'nothing there: the sky');
assert.equal(depthPicks, 0);
// A mountain above the horizon: a globe tile on the ray.
globeHit = { x: 6378000, y: 0, z: 0 };
assert.equal(ports.query.pick(1, 1).surface, true);
assert.equal(depthPicks, 1);
// Something drawn outside the sets against the sky.
globeHit = null;
picked = { primitive: {} };
ports.query.pick(1, 1);
assert.equal(depthPicks, 2);
// A failing depth pick finds no surface, so what was picked is still read.
scene.pickPosition = () => {
throw new Error('no depth');
};
assert.equal(ports.query.pick(1, 1), null);
// A throwing camera answers nothing rather than failing the pick.
picked = undefined;
scene.camera.pickEllipsoid = () => {
throw new Error('no camera');
};
assert.equal(ports.query.pick(1, 1), null);
ports.dispose();
});
test("an empty click's renderer pick and its own Cesium pick are one pass", () => {
let passes = 0;
const { widget, scene } = fakeWidget({
pick: () => (passes++, undefined),
pickPosition: () => (passes++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => ({ x: 6378137, y: 0, z: 0 });
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.query.pick(4, 5).surface, true);
const click = createNativeClick(scene, { x: 4, y: 5 });
assert.equal(click.foreign(), null);
assert.equal(click.native.pick, undefined);
assert.equal(passes, 1);
ports.dispose();
});
test('rayCast answers against the surface asked for', async () => {
const seen = [];
const { widget } = fakeWidget({
+46 -8
View File
@@ -17,6 +17,7 @@ import { findDraw, provideUnboundQuery } from '../rendererOf.js';
import { toCartesian } from './common.js';
import { unboundDrawPart } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { rememberPick } from './pickMemo.js';
/** The fewest things a bounded drill looks through (`QueryPort.drillPick`). */
const DRILL_DEPTH = 16;
@@ -73,10 +74,45 @@ export function createCesiumQuery({
const hitOf = ({ id }) => drawHitOf({ id });
/** The globe (or ellipsoid) under a pixel, as a surface hit. */
function surfaceHit(x, y) {
const position = query.pickPosition(x, y) ?? query.pickEllipsoid(x, y);
return position ? { set: '', id: '', surface: true, position } : null;
/** A query that throws answers nothing. */
const quietly = (fn) => {
try {
return fn();
} catch {
return null;
}
};
/**
* The globe (or ellipsoid) under a pixel, as a surface hit. Where the
* ellipsoid is under it, its position is the depth pick's (another pass
* over the scene), made when first read. Where it is not, the depth pick
* decides, unless nothing was picked there and no globe tile is on the
* pixel's ray: the sky, with no pass. A depth pick that throws finds no
* surface, so what was picked there is still read.
*/
function surfaceHit(x, y, picked) {
const ellipsoid = quietly(() => query.pickEllipsoid(x, y));
if (!ellipsoid) {
if (
picked == null &&
!quietly(() => query.pickGlobe(query.pickRay(x, y)))
)
return null;
const position = quietly(() => query.pickPosition(x, y));
return position ? { set: '', id: '', surface: true, position } : null;
}
let position;
const hit = { set: '', id: '', surface: true };
Object.defineProperty(hit, 'position', {
enumerable: true,
configurable: true,
get() {
position ??= quietly(() => query.pickPosition(x, y)) ?? ellipsoid;
return position;
},
});
return hit;
}
/**
@@ -270,9 +306,11 @@ export function createCesiumQuery({
const query = {
pick(x, y, window = {}) {
const owner = ownerOf(
scene.pick(screen(x, y), window.width ?? 3, window.height ?? 3),
);
const width = window.width ?? 3;
const height = window.height ?? 3;
const picked = scene.pick(screen(x, y), width, height);
rememberPick(scene, x, y, width, height, picked);
const owner = ownerOf(picked);
if (owner && pickable(owner)) return hitOf(owner);
// Something unpickable is on top: the first pickable item under it,
// unless something else hides it.
@@ -285,7 +323,7 @@ export function createCesiumQuery({
});
if (under) return under;
}
return surfaceHit(x, y);
return surfaceHit(x, y, picked);
},
drillPick: (x, y, options = {}) =>
drill(x, y, { ...options, untilForeign: false }),
+5 -2
View File
@@ -2,11 +2,14 @@
* @module render/cesium/unbound
* @description What to load, once, before handing the Cesium-free
* layers a Cesium viewer with no renderer bound: the factories
* that build a camera, credits, effects, draw, frame, globe and query port over
* such a viewer when code first asks for one (`rendererOf.js`).
* that build a camera, credits, effects, draw, frame, globe, input and query
* port over such a viewer when code first asks for one, and a click's own
* Cesium picks (`rendererOf.js`).
*/
import './camera.js';
import './effects.js';
import './frame.js';
import './globe.js';
import './input.js';
import './nativeClick.js';
import './query.js';
-1
View File
@@ -7,7 +7,6 @@
"src/cyberSonarGpu.js",
"src/cyberSonarScene.js",
"src/data/geoImportPins.js",
"src/input/dispatcher.js",
"src/layers/traffic/rendering.js",
"src/layers/transit/rendering.js",
"src/layers/weather/shellRendering.js",
@@ -40,6 +40,7 @@ const allowList = JSON.parse(readFileSync(path.join(root, LIST), 'utf8'));
const SCOPES = ['src', 'server', 'dev'];
/** Not runtime code, though not named `.test`: imported by tests only. */
const TEST_ONLY = new Set([
'src/input/testDoubles.mjs',
'src/layers/recentImagery/testDoubles.mjs',
'src/layers/weather/shellFixture.mjs',
'src/overlays/worldOverlayAllocation.worker.mjs',
+108 -7
View File
@@ -16,6 +16,8 @@ const renderers = new WeakMap();
*/
function unboundPorts(member) {
const built = new WeakMap();
/** Ports superseded while their holder still used them (`keep`). */
const keptPorts = new WeakMap();
let build = null;
return {
provide(factory) {
@@ -23,23 +25,36 @@ function unboundPorts(member) {
},
drop(host, port) {
const entry = built.get(host);
if (!entry || (port !== undefined && entry.port !== port)) return;
if (!entry || (port !== undefined && entry.port !== port)) {
// A port a renderer superseded but its holder kept: its holder's to
// let go of.
const kept = port !== undefined && keptPorts.get(port);
if (kept) {
keptPorts.delete(port);
kept.dispose();
}
return;
}
built.delete(host);
entry.dispose();
},
/**
* A renderer bound to `host` supersedes its built port: released when
* it can be (it stops working for new callers but keeps what it did),
* else disposed.
* A renderer bound to `host` supersedes its built port: kept working
* for whoever holds it when it says so (`keep`, an input port a
* dispatcher listens on, let go of through `drop(host, port)`), else
* released when it can be (it stops working for new callers but keeps
* what it did), else disposed.
*/
supersede(host) {
const entry = built.get(host);
if (!entry) return;
built.delete(host);
if (entry.release) entry.release();
if (entry.keep) keptPorts.set(entry.port, entry);
else if (entry.release) entry.release();
else entry.dispose();
},
find(host) {
/** `options` reach `build` only when it is the call that builds. */
find(host, options) {
const port = rendererOf(host)?.[member];
if (port) return port;
if (!host || typeof host !== 'object') return null;
@@ -50,7 +65,7 @@ function unboundPorts(member) {
}
let entry = built.get(host);
if (!entry && build) {
entry = build(host);
entry = build(host, options);
if (entry) built.set(host, entry);
}
return entry?.port ?? null;
@@ -67,6 +82,10 @@ const unboundCredits = unboundPorts('credits');
const unboundDraws = unboundPorts('draw');
const unboundQueries = unboundPorts('query');
const unboundFrames = unboundPorts('frame');
const unboundInputs = unboundPorts('input');
/** What a click's raw engine picks are built with (`provideNativeClick`). */
let nativeClicks = null;
/**
* Provide the factory `cameraOf` builds a camera port with for a scene
@@ -120,6 +139,29 @@ export function provideUnboundFrame(build) {
unboundFrames.provide(build);
}
/**
* Provide the factory `findInput` builds an input port with for a scene
* object no renderer is bound to, as `provideUnboundCamera` does. It is
* given the `options` of the `findInput` call that builds, for test
* doubles. A renderer bound later does not take the port from whoever
* listens on it: it works until `releaseUnboundInput`.
* @param {(host: object, options?: object) => ({port: object, dispose: () => void, keep?: boolean} | null)} build
*/
export function provideUnboundInput(build) {
unboundInputs.provide(build);
}
/**
* Provide what `nativeClickOf` builds a click's raw engine picks with. Not
* part of the renderer contract: the renderer adapter provides it as it
* loads, for what the app still draws outside the draw port and for code that
* still reads the engine's own pick objects; a later call replaces it.
* @param {(host: object, position: {x: number, y: number}) => (NativeClick | null)} build
*/
export function provideNativeClick(build) {
nativeClicks = build;
}
/**
* Provide the factory `findEffects` builds an effects port with for a
* scene object no renderer is bound to, as `provideUnboundCamera` does.
@@ -174,6 +216,7 @@ export function bindRenderer(host, renderer) {
unboundDraws.supersede(host);
unboundQueries.drop(host);
unboundFrames.drop(host);
unboundInputs.supersede(host);
renderers.set(host, renderer);
return () => {
if (renderers.get(host) === renderer) renderers.delete(host);
@@ -341,6 +384,64 @@ export function frameOf(host) {
throw noPort(host, 'run frames with');
}
/**
* The input port of the renderer bound to `host`; with no renderer bound,
* one built over `host` by the provided factory and kept with it while
* `host` lives, as `findCamera` does. Bound later, a renderer's own
* replaces it: its listeners hear nothing more.
* @param {object|null|undefined} host
* @param {object} [options] For the factory, when this call builds the
* port (test doubles: a fake event source, a clock).
* @returns {import('./contract/input').InputPort | null}
*/
export function findInput(host, options) {
return unboundInputs.find(host, options);
}
/**
* Let go of `port`, if it is the input port `findInput` built for `host`
* (even one a renderer bound since superseded): its listeners hear nothing
* more. A renderer's own port, or one built later, is left alone.
* @param {object|null|undefined} host
* @param {object|null|undefined} port
*/
export function releaseUnboundInput(host, port) {
if (host && typeof host === 'object' && port) unboundInputs.drop(host, port);
}
/**
* A click's raw engine picks, built by the adapter's `provideNativeClick`.
* @typedef {object} NativeClick
* @property {{pick: unknown, pickWindow: (width: number, height: number) => unknown,
* drill: (limit?: number, width?: number, height?: number) => unknown[]}} native
* The engine's own picks at the click, each made at most once, for code
* still bound to the engine.
* @property {(limit?: number, width?: number, height?: number) => import('./contract/query').Hit[]} drillHits
* `native.drill` read as hits: draw-set items as the query port gives
* them, the map as surface hits, and anything else as a hit with no set
* (its id null when it has none). For a touch's contact search, which
* stops at whatever is drawn over a contact.
* @property {(width?: number, height?: number) => ({id: string|null} | import('./contract/query').Hit | null)} foreign
* What is on top there as the engine sees it, read where the renderer's
* pick names nothing: something drawn outside the draw port by its id
* (null when it has none), a draw-set item the renderer's sets do not
* hold as its hit; null when the top is the map or nothing.
*/
/**
* The raw engine picks of a click at `position` (CSS pixels, in the pick
* buffer), from the factory the renderer adapter provided; null when there
* is none, or it has nothing for `host`.
* @param {object|null|undefined} host
* @param {{x: number, y: number}} position
* @returns {NativeClick | null}
*/
export function nativeClickOf(host, position) {
if (!nativeClicks || !host || typeof host !== 'object') return null;
if (host.isDestroyed?.()) return null;
return nativeClicks(host, position) ?? null;
}
/**
* `findCamera`, for code that needs the camera.
* @param {object} host
+78
View File
@@ -9,7 +9,12 @@ import {
findCredits,
findDraw,
findEffects,
findInput,
nativeClickOf,
provideNativeClick,
provideUnboundCamera,
provideUnboundInput,
releaseUnboundInput,
provideUnboundCredits,
provideUnboundDraw,
provideUnboundEffects,
@@ -215,3 +220,76 @@ test('with no renderer bound, findDraw builds one draw port per scene; a rendere
assert.throws(() => drawOf(gone), /destroyed/);
assert.equal(built.find((entry) => entry.port === port).disposed, 1);
});
test("with no renderer bound, findInput builds one input port per scene, given the building call's options; a renderer replaces it", (t) => {
t.after(() => provideUnboundInput(null));
const built = [];
provideUnboundInput((host, options) => {
if (!host.scene) return null;
const entry = { port: { id: built.length }, options, disposed: 0 };
entry.dispose = () => (entry.disposed += 1);
built.push(entry);
return entry;
});
const viewer = { scene: {} };
const options = { now: () => 0 };
assert.equal(findInput(viewer, options), built[0].port);
assert.equal(built[0].options, options);
assert.equal(findInput(viewer, { other: true }), built[0].port, 'kept');
assert.equal(findInput({}), null);
releaseUnboundInput(viewer, { not: 'it' });
assert.equal(built[0].disposed, 0, 'another port is left alone');
releaseUnboundInput(viewer, built[0].port);
assert.equal(built[0].disposed, 1);
assert.equal(findInput(viewer), built[1].port, 'a new one after release');
const input = { on() {} };
const unbind = bindRenderer(viewer, { input });
assert.equal(built[1].disposed, 1, "the renderer's supersedes it");
assert.equal(findInput(viewer), input);
releaseUnboundInput(viewer, input);
assert.equal(findInput(viewer), input, "a renderer's own stays");
unbind();
});
test('a renderer bound later leaves a kept input port working for its holder until released', (t) => {
t.after(() => provideUnboundInput(null));
const built = [];
provideUnboundInput(() => {
const entry = { port: { id: built.length }, disposed: 0, keep: true };
entry.dispose = () => (entry.disposed += 1);
built.push(entry);
return entry;
});
const viewer = { scene: {} };
const held = findInput(viewer);
const input = { on() {} };
const unbind = bindRenderer(viewer, { input });
t.after(unbind);
assert.equal(built[0].disposed, 0, 'its holder still listens on it');
assert.equal(findInput(viewer), input, 'new callers get the renderer’s');
releaseUnboundInput(viewer, held);
assert.equal(built[0].disposed, 1, 'let go of by its holder');
releaseUnboundInput(viewer, held);
assert.equal(built[0].disposed, 1, 'once');
});
test("nativeClickOf answers from the adapter's factory, never for a destroyed scene", (t) => {
t.after(() => provideNativeClick(null));
assert.equal(
nativeClickOf({ scene: {} }, { x: 0, y: 0 }),
null,
'none provided',
);
const asked = [];
provideNativeClick((host, at) => {
asked.push([host, at]);
return host.scene ? { native: { pick: 'raw' }, foreign: () => null } : null;
});
const viewer = { scene: {} };
const at = { x: 1, y: 2 };
assert.equal(nativeClickOf(viewer, at).native.pick, 'raw');
assert.deepEqual(asked, [[viewer, at]]);
assert.equal(nativeClickOf({}, at), null);
assert.equal(nativeClickOf(null, at), null);
assert.equal(nativeClickOf({ scene: {}, isDestroyed: () => true }, at), null);
});
+21 -9
View File
@@ -42,6 +42,8 @@ const GLOBE_FACTORY = 'src/render/cesium/globe.js';
const DRAW_FACTORY = 'src/render/cesium/draw.js';
const QUERY_FACTORY = 'src/render/cesium/query.js';
const FRAME_FACTORY = 'src/render/cesium/frame.js';
const INPUT_FACTORY = 'src/render/cesium/input.js';
const NATIVE_CLICK = 'src/render/cesium/nativeClick.js';
const UNBOUND = 'src/render/cesium/unbound.js';
/**
@@ -106,16 +108,14 @@ const DRAW_FROM_CALLER = new Set([
// Asks `findQuery` instead, and answers null rather than throw until the
// caller has loaded the factory.
'./queries/heights',
// Their fleet icons draw through `drawOf`. Not wholly Cesium-free (pointer
// input still is), but none of their modules loads a factory.
// Their fleet icons draw through `drawOf`; they take clicks through the
// dispatcher (`findInput`, `findQuery`).
'./layers/flights',
'./layers/military',
// Not wholly Cesium-free (its pointer input still is), but its layers
// draw, size and fly through the ports alone.
// Its layers draw, size, fly and take clicks through the ports alone.
'./infrastructure',
'./infrastructure/geojson',
// Not wholly Cesium-free (its pointer input still is), but its missions
// draw, pick and fly through the ports alone.
// Its missions draw, pick and fly through the ports alone.
'./layers/launches',
// Its pins, footprints and outlines draw through `drawOf`; its horizon
// cull reads the camera and frame ports.
@@ -129,8 +129,11 @@ const DRAW_FROM_CALLER = new Set([
* `./render/cesium/unbound`.
*/
const CAMERA_FROM_CALLER = new Set([
// Not wholly Cesium-free (its pointer input still is), but it loads no
// factory: Cockpit moves the camera on the frame port's preUpdate, and
// The click dispatcher: it takes input, picks and grounds through
// `findInput`, `findQuery` and the adapter's native clicks.
'./input',
// It loads no factory: Cockpit moves the camera on the frame port's
// preUpdate, and
// `frameOf` throws, naming the export, until the caller has loaded it.
'./ui/cockpit',
'./ui/navigation',
@@ -341,10 +344,17 @@ test('every public entry that reaches a findFrame or frameOf caller loads the un
});
});
test('the unbound camera factory loads the unbound query and frame factories', () => {
test('every public entry that reaches a findInput or nativeClickOf caller loads the unbound input factory and native clicks, or its caller can', () => {
checkLookupFactory('findInput', INPUT_FACTORY, { fromCaller: true });
checkLookupFactory('nativeClickOf', NATIVE_CLICK, { fromCaller: true });
});
test('the unbound camera factory loads the unbound query, frame and input factories and native clicks', () => {
const loaded = reachable(FACTORY, { eager: true });
assert.ok(loaded.has(QUERY_FACTORY));
assert.ok(loaded.has(FRAME_FACTORY));
assert.ok(loaded.has(INPUT_FACTORY));
assert.ok(loaded.has(NATIVE_CLICK));
});
test('the unbound export brings every unbound factory', () => {
@@ -355,6 +365,8 @@ test('the unbound export brings every unbound factory', () => {
DRAW_FACTORY,
QUERY_FACTORY,
FRAME_FACTORY,
INPUT_FACTORY,
NATIVE_CLICK,
'src/render/cesium/credits.js',
])
assert.ok(loaded.has(factory), factory);
-2
View File
@@ -7,7 +7,6 @@
"src/celestialRing.js": 1,
"src/data/bhoteKoshiEmbeddedMedia.js": 1,
"src/data/followed.js": 5,
"src/data/pickRegistry.js": 3,
"src/data/spriteOrder.js": 2,
"src/layers/flights/motion.js": 1,
"src/layers/military/motion.js": 1,
@@ -17,6 +16,5 @@
"src/maps/imageryHost.js": 4,
"src/overlays/worldOverlay.js": 1,
"src/ui/shareRestoration.js": 4,
"src/ui/visualEffects.js": 1,
"src/voice/gevActions.js": 1
}