mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
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:
1 parent
6eb9ceef46
commit
8bcaced6ad
52 files changed
+1836
-484
No files matched your search
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../render/cesium/input.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
|
||||
@@ -1158,7 +1158,8 @@ test('vessel touch interaction yields to the first nearby flight behind map tile
|
||||
// The click's shared drill: the 14 px touch window, at least 8 deep.
|
||||
assert.deepEqual([width, height], [14, 14]);
|
||||
assert.ok(limit >= 8);
|
||||
return [tile, { id: 'a1b2c3' }];
|
||||
// The flight's icon: a draw-set item.
|
||||
return [tile, { id: { set: 'flights:1', id: 'a1b2c3' } }];
|
||||
};
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
|
||||
@@ -1078,7 +1078,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
assert.equal(cctvEmptyClickDeselects(null, { activeCameraId: null }), false);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ id: 'registered-sibling' },
|
||||
{ set: 'flights:1', id: 'registered-sibling', surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
@@ -1087,7 +1087,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ id: { id: 'unregistered-local-entity' } },
|
||||
{ set: '', id: 'unregistered-local-entity', surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
@@ -1096,7 +1096,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ primitive: { id: 'unregistered-primitive' } },
|
||||
{ set: '', id: 'unregistered-primitive', surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
@@ -1105,7 +1105,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ id: '' },
|
||||
{ set: '', id: '', surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
@@ -1115,13 +1115,13 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ primitive: {} },
|
||||
{ set: '', id: null, surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
),
|
||||
true,
|
||||
'an ID-less surface pick remains true empty space',
|
||||
'something with no id remains true empty space',
|
||||
);
|
||||
|
||||
const initSource = componentFunctionSource(cctvLayer.init);
|
||||
|
||||
@@ -131,21 +131,18 @@ test('two viewers use their supplied contexts and dispose independently', async
|
||||
);
|
||||
// A click picks the feature's stem, as the renderer's pick names it.
|
||||
const viewer = {
|
||||
scene: {
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
pick: () => {
|
||||
const [stem] = fake.set('stems').items.values();
|
||||
return {
|
||||
id: {
|
||||
set: fake.set('stems').spec.id,
|
||||
id: stem.id,
|
||||
meta: stem.meta,
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
scene: { screenSpaceCameraController: { enableInputs: true } },
|
||||
};
|
||||
const fake = bindFakeGroundRenderer(viewer);
|
||||
fake.setPick(() => {
|
||||
const [stem] = fake.set('stems').items.values();
|
||||
return {
|
||||
set: fake.set('stems').spec.id,
|
||||
id: stem.id,
|
||||
meta: stem.meta,
|
||||
surface: false,
|
||||
};
|
||||
});
|
||||
const input = fakeInput(viewer);
|
||||
return { layer, viewer, fake, click: () => input.click({ x: 0, y: 0 }) };
|
||||
});
|
||||
@@ -196,44 +193,33 @@ test('consumer build includes only infrastructure code and resolves assets under
|
||||
const output = result.output;
|
||||
const entry = output.find((item) => item.type === 'chunk' && item.isEntry);
|
||||
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
|
||||
// It draws through the renderer's ports: a viewer of the caller's own
|
||||
// draws once the caller has loaded `./render/cesium/unbound`.
|
||||
// It draws and takes clicks through the renderer's ports: a viewer of the
|
||||
// renderer bound draws once the caller has loaded
|
||||
// `./render/cesium/unbound`.
|
||||
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
|
||||
'cameraControls.js',
|
||||
'cameraInput.js',
|
||||
'color.js',
|
||||
'ctrlWheelZoom.js',
|
||||
'dispatcher.js',
|
||||
'drawHit.js',
|
||||
'ellipsoid.js',
|
||||
'follow.js',
|
||||
'frames.js',
|
||||
'geojsonPins.js',
|
||||
'heights.js',
|
||||
'infrastructure.js',
|
||||
'infrastructureData.js',
|
||||
'infrastructureOverlayEntry.js',
|
||||
'input.js',
|
||||
'inputOwnership.js',
|
||||
'localGeojsonCore.js',
|
||||
'localGeojsonLod.js',
|
||||
'pickRegistry.js',
|
||||
'rendererOf.js',
|
||||
'rhumb.js',
|
||||
'router.js',
|
||||
'scenePick.js',
|
||||
'sensorPick.js',
|
||||
'sphere.js',
|
||||
'stockFollow.js',
|
||||
'styleStages.js',
|
||||
'vector.js',
|
||||
'wheel.js',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
entry.imports,
|
||||
['cesium'],
|
||||
'the viewer supplies the same Cesium dependency',
|
||||
);
|
||||
assert.deepEqual(entry.imports, [], 'it reaches no Cesium of its own');
|
||||
for (const name of ['datacenters', 'dams']) {
|
||||
const asset = output.find(
|
||||
(item) => item.type === 'asset' && item.fileName.includes(name),
|
||||
|
||||
+42
-36
@@ -11,35 +11,34 @@
|
||||
* that belong to someone else and leave them alone.
|
||||
*/
|
||||
|
||||
import { isSurfacePick } from './scenePick.js';
|
||||
/**
|
||||
* A click's hits are the renderer contract's `Hit` (src/render/contract/
|
||||
* query.d.ts), plus, for something drawn outside the draw port, a `Hit`
|
||||
* with no set (`set: ''`, `id` null when it has none) named by the renderer
|
||||
* adapter
|
||||
* (`nativeClickOf`, src/render/rendererOf.js). The raw forms of these
|
||||
* rules, for code that still holds a Cesium pick, are the adapter's
|
||||
* (src/render/cesium/nativeClick.js).
|
||||
*/
|
||||
|
||||
/** Whether a hit is the map itself, or nothing. */
|
||||
const isSurface = (hit) => !hit || hit.surface === true;
|
||||
|
||||
/** @type {Map<string, (pickedId: string) => boolean>} layerId -> ownership predicate */
|
||||
const _owners = new Map();
|
||||
|
||||
/**
|
||||
* Resolves a scene.pick() result to a String pick id for the ownership scan.
|
||||
* A hit's canonical pick id, for the ownership scan: its item's id. Layers'
|
||||
* ids differ (strings, satellites' NORAD catalog numbers as strings), but a
|
||||
* draw-set item's id is always a string.
|
||||
*
|
||||
* Layers use heterogeneous pick ids: flights/military/vessels/bikeshare/CCTV
|
||||
* use strings, satellites use numeric NORAD catalog ids, and entity picks
|
||||
* surface the Cesium Entity (identity = its string `id`). Everything is
|
||||
* coerced to a String so predicates match against one canonical form.
|
||||
*
|
||||
* @param {object|null|undefined} picked - Result of `scene.pick()`.
|
||||
* @returns {string|null} Canonical pick id, or null when the pick carries none.
|
||||
* @param {import('../render/contract/query').Hit|null|undefined} hit
|
||||
* @returns {string|null} Its id (an empty one is still an id); null for the
|
||||
* map, nothing, or something with no id.
|
||||
*/
|
||||
export function resolvePickId(picked) {
|
||||
if (!picked) return null;
|
||||
const unwrap = (id) => {
|
||||
if (id === null || id === undefined) return undefined;
|
||||
if (typeof id === 'object') {
|
||||
// A Cesium Entity (.id string)
|
||||
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);
|
||||
export function resolvePickId(hit) {
|
||||
if (isSurface(hit)) return null;
|
||||
const id = hit.id;
|
||||
return typeof id === 'string' || typeof id === 'number' ? String(id) : null;
|
||||
}
|
||||
|
||||
@@ -103,25 +102,28 @@ export function isOwnedByOtherLayer(layerId, pickedId) {
|
||||
/**
|
||||
* Resolve a moving-contact click without letting map tiles hide a nearby touch
|
||||
* target. Exact picks always win; only a coarse primary pointer may expand a
|
||||
* surface miss. Every consumer uses the same ordered, bounded scene hits, so sibling layers
|
||||
* do not each choose their own contact under one tap.
|
||||
* Unowned non-surface objects remain barriers, not permission to pick through.
|
||||
* surface miss. Every consumer uses the same ordered, bounded hits, so sibling
|
||||
* layers do not each choose their own contact under one tap.
|
||||
* Unowned items remain barriers, not permission to pick through.
|
||||
*
|
||||
* @param {object} scene Cesium scene with pick and optional drillPick.
|
||||
* @param {import('../render/contract/query').QueryPort} query
|
||||
* @param {{x: number, y: number}} position Screen position in CSS pixels.
|
||||
* @param {{picked?: object|null, drill?: (limit: number, width: number, height: number) => object[]}} [options]
|
||||
* @param {{picked?: import('../render/contract/query').Hit|null, drill?: (limit: number, width: number, height: number) => import('../render/contract/query').Hit[]}} [options]
|
||||
* The click's own passes when the caller has them, so a click is picked
|
||||
* once: `picked` is `scene.pick(position)` (a miss is passed as `undefined`
|
||||
* too, so the key's presence counts), `drill` a shared `scene.drillPick`.
|
||||
* @returns {object|null|undefined} Original pick or the first registered touch hit.
|
||||
* once: `picked` is `query.pick(position)` (a miss is passed as `null`
|
||||
* too, so the key's presence counts), `drill` a shared `query.drillPick`.
|
||||
* @returns {import('../render/contract/query').Hit|null} The pick, or the
|
||||
* first registered touch hit.
|
||||
*/
|
||||
export function pickContact(scene, position, options = {}) {
|
||||
const picked = 'picked' in options ? options.picked : scene.pick(position);
|
||||
export function pickContact(query, position, options = {}) {
|
||||
const picked =
|
||||
'picked' in options
|
||||
? options.picked
|
||||
: (query.pick(position.x, position.y) ?? null);
|
||||
if (
|
||||
!globalThis.matchMedia?.('(pointer: coarse)').matches ||
|
||||
findPickOwner(resolvePickId(picked)) ||
|
||||
!isSurfacePick(picked) ||
|
||||
typeof scene.drillPick !== 'function'
|
||||
!isSurface(picked)
|
||||
)
|
||||
return picked;
|
||||
let hits;
|
||||
@@ -129,13 +131,17 @@ export function pickContact(scene, position, options = {}) {
|
||||
hits =
|
||||
(options.drill
|
||||
? options.drill(8, 14, 14)
|
||||
: scene.drillPick(position, 8, 14, 14)) || [];
|
||||
: query.drillPick(position.x, position.y, {
|
||||
width: 14,
|
||||
height: 14,
|
||||
limit: 8,
|
||||
})) || [];
|
||||
} catch {
|
||||
return picked;
|
||||
}
|
||||
for (const hit of hits.slice(0, 8)) {
|
||||
if (findPickOwner(resolvePickId(hit))) return hit;
|
||||
if (!isSurfacePick(hit)) break;
|
||||
if (!isSurface(hit)) break;
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
* Pick-ownership contract tests (pre-ship audit H2).
|
||||
*
|
||||
* Locks the cross-layer pick coercion rules:
|
||||
* - resolvePickId reduces every layer's pick shape (string icao/station ids,
|
||||
* numeric NORAD ids, AIS vessel record objects, Cesium Entity objects) to
|
||||
* ONE canonical String id.
|
||||
* - resolvePickId reads a click's hit (the contract's `Hit`, or one with no
|
||||
* set for something drawn outside the draw port) as ONE canonical String
|
||||
* id: its item's id.
|
||||
* - isOwnedByOtherLayer consults sibling predicates only, never the asker's,
|
||||
* and never throws on a broken predicate.
|
||||
*/
|
||||
@@ -23,27 +23,25 @@ import {
|
||||
// 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');
|
||||
const item = (set, id) => ({ set, id, surface: false });
|
||||
const SURFACE = { set: '', id: '', surface: true };
|
||||
|
||||
test("resolvePickId: a draw-set item's hit → its item id", () => {
|
||||
assert.equal(resolvePickId(item('flights:1', 'aaa001')), 'aaa001');
|
||||
assert.equal(resolvePickId(item('satellites:1:dots', '25544')), '25544');
|
||||
});
|
||||
|
||||
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: something drawn outside the draw port → its own id', () => {
|
||||
assert.equal(resolvePickId(item('', 'transit:bus-1')), 'transit:bus-1');
|
||||
assert.equal(resolvePickId(item('', null)), null, 'it has none');
|
||||
assert.equal(resolvePickId(item('', '')), '', 'an empty id is still an id');
|
||||
});
|
||||
|
||||
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: unresolvable picks → null', () => {
|
||||
test('resolvePickId: the map and nothing → 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);
|
||||
assert.equal(resolvePickId(SURFACE), null);
|
||||
assert.equal(resolvePickId({ ...SURFACE, id: 'tile' }), null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -60,9 +58,9 @@ test('ownership: sibling layers recognize each other via String-coerced ids', ()
|
||||
registerPickOwner('ais-live-vessels', (pickedId) => vessels.has(pickedId));
|
||||
try {
|
||||
// Flights asking about a satellite pick (raw numeric id → String upstream)
|
||||
assert.equal(isOwnedByOtherLayer('flights', resolvePickId({ id: 25544 })), true);
|
||||
assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('sat:1', '25544'))), true);
|
||||
// Flights asking about a vessel pick (an icon row id: the mmsi)
|
||||
assert.equal(isOwnedByOtherLayer('flights', resolvePickId({ id: '367123450' })), true);
|
||||
assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('ais:1', '367123450'))), true);
|
||||
// A layer never owns its own pick via the sibling scan
|
||||
assert.equal(isOwnedByOtherLayer('satellites', '25544'), false);
|
||||
// Unknown ids belong to nobody
|
||||
@@ -115,38 +113,48 @@ function contactOwners(t) {
|
||||
});
|
||||
}
|
||||
|
||||
const mapTile = { primitive: { isCesium3DTileset: true } };
|
||||
/** A query port double: one pick, and a drill that records its asks. */
|
||||
function query(picked, drillPick = () => assert.fail('must not drill')) {
|
||||
return {
|
||||
pick: () => picked,
|
||||
drillPick,
|
||||
};
|
||||
}
|
||||
|
||||
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' } };
|
||||
const contact = item('flights:1', '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);
|
||||
const port = query(SURFACE, (...args) => {
|
||||
drills++;
|
||||
assert.deepEqual(args, [30, 50, { width: 14, height: 14, limit: 8 }]);
|
||||
return [contact];
|
||||
});
|
||||
assert.equal(pickContact(port, position), contact);
|
||||
assert.equal(drills, 1);
|
||||
});
|
||||
|
||||
test("touch contact pick uses the click's own pick and drill", (t) => {
|
||||
primaryPointer(t, true);
|
||||
contactOwners(t);
|
||||
const contact = item('flights:1', 'civil');
|
||||
const asked = [];
|
||||
const found = pickContact(query(null), { x: 1, y: 1 }, {
|
||||
picked: null,
|
||||
drill: (...args) => (asked.push(args), [contact]),
|
||||
});
|
||||
assert.equal(found, contact);
|
||||
assert.deepEqual(asked, [[8, 14, 14]]);
|
||||
});
|
||||
|
||||
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);
|
||||
for (const first of [item('mil:1', 'military'), item('ais:1', '123456789')]) {
|
||||
const port = query(SURFACE, () => [first, item('flights:1', 'civil')]);
|
||||
assert.equal(pickContact(port, { x: 1, y: 1 }), first);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -154,60 +162,38 @@ test('touch contact pick does not drill through exact registered or unregistered
|
||||
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);
|
||||
}
|
||||
item('mil:1', 'military'),
|
||||
item('notes:1', 'custom-annotation'),
|
||||
item('', 'custom-gizmo'),
|
||||
])
|
||||
assert.equal(pickContact(query(exact), { x: 1, y: 1 }), exact);
|
||||
});
|
||||
|
||||
test('touch expansion stops at a non-surface object and respects the drill bound', (t) => {
|
||||
test('touch expansion stops at an unowned item 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,
|
||||
);
|
||||
}
|
||||
[item('notes:1', 'custom-annotation'), item('flights:1', 'civil')],
|
||||
[...Array(8).fill(item('notes:1', 'x')), item('flights:1', 'civil')],
|
||||
[],
|
||||
])
|
||||
assert.equal(pickContact(query(SURFACE, () => hits), { x: 1, y: 1 }), SURFACE);
|
||||
});
|
||||
|
||||
test('fine primary pointers keep the existing exact mouse pick without a drill', (t) => {
|
||||
test('fine primary pointers keep the 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);
|
||||
assert.equal(pickContact(query(SURFACE), { x: 1, y: 1 }), SURFACE);
|
||||
});
|
||||
|
||||
test('touch picking tolerates unavailable or failing drill support and preserves empty sky', (t) => {
|
||||
test('touch picking tolerates a failing drill 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,
|
||||
);
|
||||
}
|
||||
])
|
||||
assert.equal(pickContact(query(null, drillPick), { x: 1, y: 1 }), null);
|
||||
});
|
||||
+16
-33
@@ -3,17 +3,17 @@ import { readEntityRecord } from './entityRecords.js';
|
||||
import { findPickOwner, resolvePickId } from './pickRegistry.js';
|
||||
|
||||
/**
|
||||
* Resolve a `scene.pick()` result to the identity a person would name: which
|
||||
* layer, which record, and its display label.
|
||||
* Resolve a pick (the contract's `Hit`, as `pickAt` in
|
||||
* src/input/dispatcher.js gives it) to the identity a person would name:
|
||||
* which layer, which record, and its display label.
|
||||
*
|
||||
* Two lanes, in order:
|
||||
* 1. Context-store carriers. Entity-backed layers (selected vessels, fires,
|
||||
* installations) write a `contextId` into the picked object's entity
|
||||
* record, and layers drawing through the draw port (infrastructure
|
||||
* GeoJSON) into a draw item's `meta`; the store record already carries
|
||||
* the label and position voice uses everywhere else.
|
||||
* 2. Pick owners. Primitive-backed layers (aircraft, satellites, vessels)
|
||||
* register an ownership predicate in `pickRegistry`; the owning layer's
|
||||
* 1. Context-store carriers. Layers drawing through the draw port
|
||||
* (infrastructure GeoJSON, ALPR) write a `contextId` into a draw item's
|
||||
* `meta`; the store record already carries the label and position voice
|
||||
* uses everywhere else.
|
||||
* 2. Pick owners. Layers (aircraft, satellites, vessels) register an
|
||||
* ownership predicate in `pickRegistry`; the owning layer's
|
||||
* `findByQuery` turns the pick id into a live descriptor.
|
||||
*
|
||||
* Trails claim their pick ids only to make clicks inert, so they never
|
||||
@@ -47,28 +47,11 @@ export function pickedKindForLayer(layerId) {
|
||||
return KIND_BY_LAYER[layerId] || 'feature';
|
||||
}
|
||||
|
||||
/** A pick of a draw-set item (its id is `{set, id, meta}`): the item's `meta`. */
|
||||
function drawItemMeta(picked) {
|
||||
const id = picked?.id;
|
||||
return id && typeof id.set === 'string' && typeof id.id === 'string'
|
||||
? id.meta
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function contextCarrierRecord(picked, dataManager) {
|
||||
const store = getContextStore();
|
||||
for (const carrier of [
|
||||
picked?.id,
|
||||
picked?.primitive?.id,
|
||||
picked?.primitive,
|
||||
drawItemMeta(picked),
|
||||
]) {
|
||||
const contextId = readEntityRecord(carrier)?.contextId;
|
||||
if (!contextId) continue;
|
||||
const record = store.entities.get(contextId);
|
||||
if (record && isContextRecordActive(record, dataManager)) return record;
|
||||
}
|
||||
return null;
|
||||
function contextCarrierRecord(hit, dataManager) {
|
||||
const contextId = readEntityRecord(hit?.meta)?.contextId;
|
||||
if (!contextId) return null;
|
||||
const record = getContextStore().entities.get(contextId);
|
||||
return record && isContextRecordActive(record, dataManager) ? record : null;
|
||||
}
|
||||
|
||||
function fromRecord(record) {
|
||||
@@ -104,13 +87,13 @@ function descriptorLabel(found, fallback) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} picked Result of `scene.pick()`.
|
||||
* @param {import('../render/contract/query').Hit|null} picked
|
||||
* @param {object} [options]
|
||||
* @param {object} [options.dataManager] Layer lifecycle (enabled state, modules).
|
||||
* @returns {{layerId: string, id: string, label: string, kind: string, lat: number|null, lon: number|null, altitudeM?: number|null}|null}
|
||||
*/
|
||||
export function resolvePickedContext(picked, { dataManager = null } = {}) {
|
||||
if (!picked) return null;
|
||||
if (!picked || picked.surface) return null;
|
||||
const record = contextCarrierRecord(picked, dataManager);
|
||||
if (record) return fromRecord(record);
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ test('an aircraft billboard resolves through its pick owner to a live label', ()
|
||||
},
|
||||
},
|
||||
});
|
||||
const picked = { id: 'a1b2c3', primitive: {} };
|
||||
const picked = { set: 'flights:1', id: 'a1b2c3', surface: false };
|
||||
assert.equal(findPickOwner('a1b2c3'), 'flights');
|
||||
assert.deepEqual(resolvePickedContext(picked, { dataManager }), {
|
||||
layerId: 'flights',
|
||||
@@ -44,26 +44,6 @@ test('an aircraft billboard resolves through its pick owner to a live label', ()
|
||||
unregisterPickOwner('flights');
|
||||
});
|
||||
|
||||
test('an entity-backed feature resolves through the context store', () => {
|
||||
const entity = { show: true };
|
||||
registerEntityContext(entity, {
|
||||
id: 'local-datacenters:7',
|
||||
layerId: 'local-datacenters',
|
||||
label: 'Data Center 7',
|
||||
latitude: 30.1,
|
||||
longitude: -97.6,
|
||||
});
|
||||
const out = resolvePickedContext({ id: entity }, { dataManager: manager() });
|
||||
assert.deepEqual(out, {
|
||||
layerId: 'local-datacenters',
|
||||
id: 'local-datacenters:7',
|
||||
label: 'Data Center 7',
|
||||
kind: 'feature',
|
||||
lat: 30.1,
|
||||
lon: -97.6,
|
||||
});
|
||||
});
|
||||
|
||||
test('a draw-set item resolves through the context record its meta carries', () => {
|
||||
const carrier = { show: true };
|
||||
registerEntityContext(carrier, {
|
||||
@@ -73,8 +53,8 @@ test('a draw-set item resolves through the context record its meta carries', ()
|
||||
latitude: 30.3,
|
||||
longitude: -97.5,
|
||||
});
|
||||
// A Cesium pick of a draw-set item: its id is the item's pick id.
|
||||
const picked = { id: { set: 'local-datacenters#1:fills', id: '8', meta: carrier }, primitive: {} };
|
||||
// A draw-set item's hit carries the item's meta as it was given.
|
||||
const picked = { set: 'local-datacenters#1:fills', id: '8', meta: carrier, surface: false };
|
||||
assert.deepEqual(resolvePickedContext(picked, { dataManager: manager() }), {
|
||||
layerId: 'local-datacenters',
|
||||
id: 'local-datacenters:8',
|
||||
@@ -88,12 +68,22 @@ test('a draw-set item resolves through the context record its meta carries', ()
|
||||
assert.equal(resolvePickedContext(picked, { dataManager: manager() }), null);
|
||||
});
|
||||
|
||||
test('something drawn outside the draw port resolves through its pick owner', () => {
|
||||
registerPickOwner('flights', (id) => id === 'z9');
|
||||
const out = resolvePickedContext({ set: '', id: 'z9', surface: false }, { dataManager: manager() });
|
||||
assert.equal(out?.layerId, 'flights');
|
||||
assert.equal(out?.id, 'z9');
|
||||
unregisterPickOwner('flights');
|
||||
});
|
||||
|
||||
test('disabled layers, trails and empty picks never resolve', () => {
|
||||
registerPickOwner('military', (id) => id === 'm1');
|
||||
assert.equal(resolvePickedContext({ id: 'm1' }, { dataManager: manager() }), null, 'military is disabled');
|
||||
const hit = (id) => ({ set: 'x:1', id, surface: false });
|
||||
assert.equal(resolvePickedContext(hit('m1'), { dataManager: manager() }), null, 'military is disabled');
|
||||
unregisterPickOwner('military');
|
||||
assert.equal(resolvePickedContext({ id: 'gev-trail:1' }, { dataManager: manager() }), null);
|
||||
assert.equal(resolvePickedContext(hit('gev-trail:1'), { dataManager: manager() }), null);
|
||||
assert.equal(resolvePickedContext(null), null);
|
||||
assert.equal(resolvePickedContext({ id: 'unknown' }, { dataManager: manager() }), null);
|
||||
assert.equal(resolvePickedContext({ set: '', id: '', surface: true }), null);
|
||||
assert.equal(resolvePickedContext(hit('unknown'), { dataManager: manager() }), null);
|
||||
assert.equal(pickedKindForLayer('ais-live-vessels'), 'vessel');
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../render/cesium/input.js';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
@@ -164,16 +164,22 @@ test('the guard rejects each way Cesium mishandles a degenerate pick', () => {
|
||||
|
||||
test('the ground under a click: the rendered surface, else the ellipsoid, never the sky', async () => {
|
||||
const { pickGroundPosition } = await import('../input/dispatcher.js');
|
||||
const { bindRenderer } = await import('../render/rendererOf.js');
|
||||
const ground = { x: 6378137, y: 0, z: 0 };
|
||||
const sky = { x: 500, y: 0, z: 0 };
|
||||
const viewer = (picked, ellipsoid) => ({
|
||||
scene: { pickPositionSupported: true, pickPosition: () => picked },
|
||||
camera: { pickEllipsoid: () => ellipsoid },
|
||||
});
|
||||
// Through the renderer's query port.
|
||||
const viewer = (picked, ellipsoid) => {
|
||||
const host = {};
|
||||
bindRenderer(host, {
|
||||
query: { pickPosition: () => picked, pickEllipsoid: () => ellipsoid },
|
||||
});
|
||||
return host;
|
||||
};
|
||||
assert.equal(pickGroundPosition(viewer(ground, null), {}), ground);
|
||||
assert.equal(pickGroundPosition(viewer(sky, ground), {}), ground);
|
||||
assert.equal(pickGroundPosition(viewer(undefined, undefined), {}), null);
|
||||
assert.equal(pickGroundPosition(null, {}), null);
|
||||
assert.equal(pickGroundPosition({}, {}), null, 'no query port');
|
||||
});
|
||||
|
||||
test('a surface pick is nothing, or Google 3D tile content without an id', async () => {
|
||||
|
||||
+240
-157
@@ -1,17 +1,18 @@
|
||||
/**
|
||||
* @module input/dispatcher
|
||||
* @description The one place the application's layers and tools take
|
||||
* pointer input over the globe: the scene's input port
|
||||
* (src/render/cesium/input.js), a click picked once and handed to every
|
||||
* subscriber, and the camera-input and stock-click holds tools take. Each
|
||||
* layer family moves onto the renderer's own `input` port as it is ported;
|
||||
* until then it subscribes here, with the events and shapes it always had.
|
||||
* pointer input over the globe: the renderer's input port
|
||||
* (src/render/contract/input.d.ts, `findInput`), a click picked once through
|
||||
* the renderer's query port and handed to every subscriber, and the
|
||||
* camera-input and stock-click holds tools take. Each layer family moves
|
||||
* onto the renderer's own `input` port as it is ported; until then it
|
||||
* subscribes here, with the events and shapes it always had.
|
||||
*
|
||||
* Layers used to bind a handler each and pick the same click again, so one
|
||||
* click with the usual layers on cost about 25 `scene.pick` passes (each one
|
||||
* redraws the scene for the pick buffer). Now the dispatcher picks lazily on
|
||||
* first read and every subscriber reads the same {@link ClickEvent}; what a
|
||||
* layer does with a click that is not its own stays the layer's decision.
|
||||
* click with the usual layers on cost about 25 picks (each one redraws the
|
||||
* scene for the pick buffer). Now the dispatcher picks lazily on first read
|
||||
* and every subscriber reads the same {@link ClickEvent}; what a layer does
|
||||
* with a click that is not its own stays the layer's decision.
|
||||
*
|
||||
* Who gets the pointer:
|
||||
* - Ambient subscribers ({@link InputDispatcher.onClick}, and `onPointer`
|
||||
@@ -25,26 +26,33 @@
|
||||
* free still ends (and gives its camera hold back).
|
||||
* - Tool subscribers pass their lease and run only while it is current.
|
||||
*
|
||||
* Camera input is suspended by the scene's counted holds
|
||||
* (src/render/cesium/cameraInput.js), which own the controller's
|
||||
* `enableInputs`, so a camera flight that ends cannot re-enable input under
|
||||
* a drag or the cockpit.
|
||||
* Camera input is suspended through the input port's counted holds
|
||||
* (`suspendCameraControls`), so a camera flight that ends cannot re-enable
|
||||
* input under a drag or the cockpit.
|
||||
*
|
||||
* A dispatcher is made per scene on first use ({@link inputFor}) and lives
|
||||
* until {@link InputDispatcher.destroy}; the application scene owns it.
|
||||
* Positions are plain `{x, y}` CSS pixels. What the renderer's picks cannot
|
||||
* name, something still drawn outside the draw port, comes from the
|
||||
* renderer adapter's own picks of the click (`nativeClickOf`), which also
|
||||
* hangs them on the click as `native` for code still bound to them.
|
||||
*
|
||||
* A dispatcher is made per scene object on first use ({@link inputFor}) and
|
||||
* lives until {@link InputDispatcher.destroy}; the application scene owns
|
||||
* it.
|
||||
*/
|
||||
import { pickThroughFollowHelper } from '../render/cesium/follow.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { isLeaseCurrent, isPointerFree } from '../data/inputOwnership.js';
|
||||
import { acquireCameraInput } from '../render/cesium/cameraInput.js';
|
||||
import { cesiumInputOf, createCesiumInput } from '../render/cesium/input.js';
|
||||
import { drawHitOf } from '../render/cesium/drawHit.js';
|
||||
import {
|
||||
findPickOwner,
|
||||
pickContact,
|
||||
resolvePickId,
|
||||
} from '../data/pickRegistry.js';
|
||||
import { isPickedWorldPosition, isSurfacePick } from '../data/scenePick.js';
|
||||
import { isPickedWorldPosition } from '../data/scenePick.js';
|
||||
import {
|
||||
canvasOf,
|
||||
findInput,
|
||||
findQuery,
|
||||
nativeClickOf,
|
||||
releaseUnboundInput,
|
||||
} from '../render/rendererOf.js';
|
||||
import { sensorPickPosition } from './sensorPick.js';
|
||||
|
||||
// A tool takes the pointer with a lease before it subscribes with one.
|
||||
@@ -60,29 +68,26 @@ export {
|
||||
* The world position under a screen point: the rendered surface where the
|
||||
* depth buffer has it, else the ellipsoid; null over the sky.
|
||||
*
|
||||
* @param {object} viewer A Cesium viewer.
|
||||
* @param {object} viewer The scene object.
|
||||
* @param {{x: number, y: number}} screenPosition
|
||||
* @returns {{x: number, y: number, z: number}|null} A Cartesian3.
|
||||
* @returns {{x: number, y: number, z: number}|null} ECEF metres.
|
||||
*/
|
||||
export function pickGroundPosition(viewer, screenPosition) {
|
||||
const scene = viewer?.scene;
|
||||
return groundAt(findQuery(viewer), screenPosition);
|
||||
}
|
||||
|
||||
/** `pickGroundPosition` through a query port. */
|
||||
function groundAt(query, { x, y }) {
|
||||
if (!query) return null;
|
||||
let position = null;
|
||||
if (
|
||||
scene?.pickPositionSupported &&
|
||||
typeof scene.pickPosition === 'function'
|
||||
) {
|
||||
try {
|
||||
position = scene.pickPosition(screenPosition);
|
||||
} catch {
|
||||
position = null;
|
||||
}
|
||||
try {
|
||||
position = query.pickPosition(x, y);
|
||||
} catch {
|
||||
position = null;
|
||||
}
|
||||
if (
|
||||
!isPickedWorldPosition(position) &&
|
||||
typeof viewer?.camera?.pickEllipsoid === 'function'
|
||||
) {
|
||||
if (!isPickedWorldPosition(position)) {
|
||||
try {
|
||||
position = viewer.camera.pickEllipsoid(screenPosition);
|
||||
position = query.pickEllipsoid(x, y);
|
||||
} catch {
|
||||
position = null;
|
||||
}
|
||||
@@ -90,13 +95,6 @@ export function pickGroundPosition(viewer, screenPosition) {
|
||||
return isPickedWorldPosition(position) ? position : null;
|
||||
}
|
||||
|
||||
/** The handler event types the scene's input port binds, for test doubles. */
|
||||
export const HANDLER_EVENT_TYPES = Cesium.ScreenSpaceEventType;
|
||||
|
||||
/** 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;
|
||||
|
||||
const POINTER_TYPES = ['down', 'move', 'up', 'click', 'dblclick'];
|
||||
|
||||
/**
|
||||
@@ -111,9 +109,24 @@ const unmodifiedLeft = (ev) => ev.button === 0 && unmodified(ev);
|
||||
const leaseOf = (entry) =>
|
||||
typeof entry.lease === 'function' ? entry.lease() : entry.lease;
|
||||
|
||||
/** @type {WeakMap<object, InputDispatcher>} scene -> dispatcher */
|
||||
/** @type {WeakMap<object, InputDispatcher>} scene object -> dispatcher */
|
||||
const dispatchers = new WeakMap();
|
||||
|
||||
const xy = (p) => ({ x: p.x, y: p.y });
|
||||
|
||||
/**
|
||||
* A draw-set item's hit, or, from what the adapter's own pick found
|
||||
* (`foreign`), a hit with no set for something drawn outside the draw port
|
||||
* or the hit of a draw-set item the renderer's sets do not hold; null for
|
||||
* the map itself or nothing.
|
||||
*/
|
||||
function topHitOf(hit, foreign) {
|
||||
if (hit && !hit.surface) return hit;
|
||||
const other = foreign();
|
||||
if (!other) return null;
|
||||
return other.set ? other : { set: '', id: other.id, surface: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} ClickGesture
|
||||
* @property {number} travelPx Pointer travel during the press, summed per
|
||||
@@ -121,34 +134,48 @@ const dispatchers = new WeakMap();
|
||||
* @property {number} durationMs Press time.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {import('../render/contract/query').Hit} Hit
|
||||
*/
|
||||
|
||||
/**
|
||||
* One left click, picked at most once per kind of query. Every getter and
|
||||
* method is memoized, so subscribers share the passes.
|
||||
* method is memoized, so subscribers share the passes. Hits are the
|
||||
* contract's `Hit`; one with `set: ''` is something drawn outside the draw
|
||||
* port, named by the renderer adapter (its id null when it has none).
|
||||
* @typedef {object} ClickEvent
|
||||
* @property {{x: number, y: number}} screenPosition Where the user clicked.
|
||||
* @property {{x: number, y: number}} position Where that lands in the pick buffer
|
||||
* (corrected for sensor styles; see sensorPick.js).
|
||||
* @property {ClickGesture} gesture
|
||||
* @property {object|undefined} pick `scene.pick` at `position`.
|
||||
* @property {import('../render/contract/query').Hit|null} drawHit `pick` as
|
||||
* the contract's `Hit`, when it is an item of a renderer draw set; null
|
||||
* for anything else. What layers on the draw port read a click by.
|
||||
* @property {object|undefined} hit `pick`, or on a coarse pointer the first
|
||||
* registered contact under a surface pick (`pickContact`).
|
||||
* @property {Hit|null} topHit What is on top under the click: a draw-set
|
||||
* item, or something drawn outside the draw port; null for the map itself
|
||||
* (the globe, tiles) or nothing.
|
||||
* @property {Hit|null} drawHit `topHit` when it is an item of a renderer draw
|
||||
* set; null for anything else. What layers on the draw port read a click
|
||||
* by.
|
||||
* @property {Hit|null} hit `topHit`, or on a coarse pointer the first
|
||||
* registered contact under the map (`pickContact`).
|
||||
* @property {string|null} id The hit's canonical pick id.
|
||||
* @property {string|null} ownerId The layer that registered the hit.
|
||||
* @property {object|undefined} meta The hit's own metadata, when its pick
|
||||
* carries any (icon-set rows do).
|
||||
* @property {boolean} surface Whether the hit is the map itself.
|
||||
* @property {(width: number, height: number) => object|undefined} pickWindow
|
||||
* `scene.pick` with a wider window.
|
||||
* @property {(width: number, height: number) => {id: string|null, drawHit: import('../render/contract/query').Hit|null, surface: boolean}} windowHit
|
||||
* `pickWindow` read as `id`, `drawHit` and `surface` are: for layers that
|
||||
* pick wider than the click without reading the renderer's pick.
|
||||
* @property {(limit?: number, width?: number, height?: number) => object[]} drill
|
||||
* `scene.drillPick`, at most `limit` hits.
|
||||
* @property {() => Cesium.Cartesian3|null} ground The world position under
|
||||
* the click: rendered surface, else ellipsoid; null over the sky.
|
||||
* @property {object|undefined} meta The hit's own metadata, when it has any.
|
||||
* @property {boolean} surface Whether the hit is the map itself, or nothing.
|
||||
* @property {(width: number, height: number) => {id: string|null, drawHit: Hit|null, surface: boolean}} windowHit
|
||||
* A pick with a wider window, read as `id`, `drawHit` and `surface` are.
|
||||
* @property {(limit?: number, width?: number, height?: number) => Hit[]} drill
|
||||
* The draw-set items under the click, nearest first, at most `limit`
|
||||
* (`query.drillPick`).
|
||||
* @property {() => {x: number, y: number, z: number}|null} ground The world
|
||||
* position under the click: rendered surface, else ellipsoid; null over
|
||||
* the sky.
|
||||
* @property {import('../render/rendererOf.js').NativeClick['native']|undefined} native
|
||||
* The renderer adapter's own picks of the click (`pick`, `pickWindow`,
|
||||
* `drill`), for code still bound to the engine's pick objects; undefined
|
||||
* when the adapter has none.
|
||||
* @property {unknown} pick `native.pick`, for code still bound to the
|
||||
* engine's pick objects that reads it here.
|
||||
* @property {(width: number, height: number) => unknown} pickWindow
|
||||
* `native.pickWindow`, the same.
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -157,38 +184,41 @@ const dispatchers = new WeakMap();
|
||||
* Ambient click subscription. Returns its unsubscribe.
|
||||
* @property {(type: 'down'|'move'|'up'|'click'|'dblclick', fn: Function, options?: {lease?: object|(() => object|null)}) => () => void} onPointer
|
||||
* Raw pointer subscription: `click` gets the {@link ClickEvent}, the others
|
||||
* Cesium's event; `move`'s also carries `pickPosition`, its `endPosition`
|
||||
* corrected for sensor styles as a click's `position` is. With a lease, runs only while that lease is current;
|
||||
* `{position}` (`move`: `{startPosition, endPosition, pickPosition}`, its
|
||||
* `pickPosition` its `endPosition` corrected for sensor styles as a
|
||||
* click's `position` is). With a lease, runs only while that lease is current;
|
||||
* without one, only while the pointer is free (`move` and `up` always run).
|
||||
* @property {(reason: string) => () => void} suspendCamera Hold camera input
|
||||
* off; returns this hold's release.
|
||||
* @property {() => () => void} suppressStockClicks Take the viewer's stock
|
||||
* select and double-click-track actions off; returns this hold's release.
|
||||
* @property {() => () => void} suppressStockClicks Take the renderer's stock
|
||||
* select and double-click follow off; returns this hold's release.
|
||||
* @property {(name: 'select'|'dblclickFollow') => boolean} stockEnabled
|
||||
* Whether the viewer's stock select or follow runs now: it does unless a
|
||||
* hold is out (or the viewer has none).
|
||||
* Whether the renderer's stock select or follow runs now: it does unless a
|
||||
* hold is out (or the renderer has none).
|
||||
* @property {() => number} subscriberCount Live click and pointer
|
||||
* subscriptions, for leak checks.
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
|
||||
/**
|
||||
* What is under canvas CSS pixel `x, y` now, as a click would see it (a hit
|
||||
* on the follow's helper is a hit on its target), for a reader that is not
|
||||
* handed a click (point-and-ask). Null when nothing is there or the pick
|
||||
* fails.
|
||||
* @param {object} viewer
|
||||
* What is under canvas CSS pixel `x, y` now, as a click's `topHit` would
|
||||
* see it (a hit on the follow's helper is a hit on its target), for a reader
|
||||
* that is not handed a click (point-and-ask). Null when nothing but the map
|
||||
* is there, or the pick fails.
|
||||
* @param {object} viewer The scene object.
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @returns {object|null}
|
||||
* @returns {Hit|null}
|
||||
*/
|
||||
export function pickAt(viewer, x, y) {
|
||||
try {
|
||||
if (!viewer || viewer.isDestroyed?.()) return null;
|
||||
const scene = viewer.scene;
|
||||
if (typeof scene?.pick !== 'function') return null;
|
||||
return (
|
||||
pickThroughFollowHelper(scene.pick(new Cesium.Cartesian2(x, y))) ?? null
|
||||
const query = findQuery(viewer);
|
||||
if (!query) return null;
|
||||
const position = { x, y };
|
||||
return topHitOf(
|
||||
query.pick(x, y),
|
||||
() => nativeClickOf(viewer, position)?.foreign() ?? null,
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
@@ -196,40 +226,37 @@ export function pickAt(viewer, x, y) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The scene's dispatcher, made on first use.
|
||||
* @param {object} viewer A Cesium viewer (or a test double with `scene`).
|
||||
* @param {{createHandler?: (canvas: object) => object, now?: () => number, document?: object|null}} [options]
|
||||
* For the input port it makes when the scene has none (tests pass a fake
|
||||
* handler); used only by the call that makes it.
|
||||
* The scene object's dispatcher, made on first use.
|
||||
* @param {object} viewer The scene object (a Cesium viewer, or a test
|
||||
* double).
|
||||
* @param {{createHandler?: (canvas: object) => object, now?: () => number,
|
||||
* document?: object|null, query?: import('../render/contract/query').QueryPort}} [options]
|
||||
* For a dispatcher over a viewer with no renderer bound: the input port's
|
||||
* (`findInput`) when this call builds it, and the query port its clicks
|
||||
* pick through (tests pass doubles). Used only by the call that makes the
|
||||
* dispatcher.
|
||||
* @returns {InputDispatcher}
|
||||
*/
|
||||
export function inputFor(viewer, options = {}) {
|
||||
const scene = viewer.scene;
|
||||
let dispatcher = dispatchers.get(scene);
|
||||
let dispatcher = dispatchers.get(viewer);
|
||||
if (!dispatcher) {
|
||||
dispatcher = createDispatcher(viewer, options);
|
||||
dispatchers.set(scene, dispatcher);
|
||||
dispatchers.set(viewer, dispatcher);
|
||||
}
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
const scene = viewer.scene;
|
||||
// The renderer's port when the application made one; a viewer of the
|
||||
// caller's own gets one for as long as this dispatcher lives.
|
||||
const shared = cesiumInputOf(scene);
|
||||
const cesiumInput =
|
||||
shared ??
|
||||
createCesiumInput(viewer, {
|
||||
report: (error) => console.error('Pointer input failed', error),
|
||||
// The viewer is its owner's: its stock actions stay on its handler.
|
||||
takeStock: false,
|
||||
...(createHandler ? { createHandler } : {}),
|
||||
...(now ? { now } : {}),
|
||||
...(document !== undefined ? { document } : {}),
|
||||
});
|
||||
const { port } = cesiumInput;
|
||||
const cameraInput = acquireCameraInput(scene);
|
||||
function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
|
||||
const port = findInput(viewer, portOptions);
|
||||
if (!port)
|
||||
throw new Error(
|
||||
viewer?.isDestroyed?.()
|
||||
? 'This scene has been destroyed'
|
||||
: 'This scene has no renderer to take input with: bind one, or load ' +
|
||||
"the Cesium adapter's factories (the ./render/cesium/unbound export) " +
|
||||
'for a viewer with no renderer bound',
|
||||
);
|
||||
const queryOf = () => givenQuery ?? findQuery(viewer);
|
||||
/** @type {Array<{fn: Function}>} */
|
||||
const clickSubscribers = [];
|
||||
/** @type {Record<string, Array<{fn: Function, lease: object|null}>>} */
|
||||
@@ -237,6 +264,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
POINTER_TYPES.map((type) => [type, []]),
|
||||
);
|
||||
const stockHolds = new Set();
|
||||
const cameraHolds = new Set();
|
||||
let destroyed = false;
|
||||
|
||||
const run = (list, free, arg) => {
|
||||
@@ -250,30 +278,29 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
}
|
||||
};
|
||||
|
||||
const cartesian = (p) => new Cesium.Cartesian2(p.x, p.y);
|
||||
// Each type is one port listener; the pointer's owner is read once per
|
||||
// event, before any subscriber runs.
|
||||
const offPort = [
|
||||
port.on('down', (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.down, isPointerFree(), {
|
||||
position: cartesian(ev.position),
|
||||
position: xy(ev.position),
|
||||
});
|
||||
}),
|
||||
port.on('move', (ev) => {
|
||||
if (!unmodified(ev)) return;
|
||||
const endPosition = cartesian(ev.endPosition ?? ev.position);
|
||||
const endPosition = xy(ev.endPosition ?? ev.position);
|
||||
let pickPosition;
|
||||
run(pointerSubscribers.move, true, {
|
||||
startPosition: cartesian(ev.position),
|
||||
startPosition: xy(ev.position),
|
||||
endPosition,
|
||||
// Where the pointer lands in the pick buffer, as a click's
|
||||
// `position` is (corrected for sensor styles); made on first read.
|
||||
get pickPosition() {
|
||||
pickPosition ??= sensorPickPosition(
|
||||
viewer.scene,
|
||||
viewer,
|
||||
endPosition,
|
||||
viewer.scene.canvas,
|
||||
canvasOf(viewer),
|
||||
);
|
||||
return pickPosition;
|
||||
},
|
||||
@@ -281,14 +308,15 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
}),
|
||||
port.on('up', (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.up, true, { position: cartesian(ev.position) });
|
||||
run(pointerSubscribers.up, true, { position: xy(ev.position) });
|
||||
}),
|
||||
port.on('click', (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
const free = isPointerFree();
|
||||
const event = createClickEvent(
|
||||
viewer,
|
||||
{ position: cartesian(ev.position) },
|
||||
queryOf,
|
||||
xy(ev.position),
|
||||
ev.gesture ?? { travelPx: 0, durationMs: 0 },
|
||||
);
|
||||
run(pointerSubscribers.click, free, event);
|
||||
@@ -297,7 +325,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
port.on('dblclick', (ev) => {
|
||||
if (!unmodifiedLeft(ev)) return;
|
||||
run(pointerSubscribers.dblclick, isPointerFree(), {
|
||||
position: cartesian(ev.position),
|
||||
position: xy(ev.position),
|
||||
});
|
||||
}),
|
||||
];
|
||||
@@ -311,7 +339,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
const self = {
|
||||
onClick(fn) {
|
||||
return subscribe(clickSubscribers, { fn, lease: null });
|
||||
},
|
||||
@@ -324,13 +352,19 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
|
||||
suspendCamera(reason) {
|
||||
if (destroyed) return () => {};
|
||||
return cameraInput.suspend(reason);
|
||||
const release = port.suspendCameraControls(reason);
|
||||
const hold = () => {
|
||||
if (!cameraHolds.delete(hold)) return;
|
||||
release();
|
||||
};
|
||||
cameraHolds.add(hold);
|
||||
return hold;
|
||||
},
|
||||
|
||||
suppressStockClicks() {
|
||||
if (destroyed) return () => {};
|
||||
// Cesium's own select and double-click-track never see the pointer
|
||||
// lease; the port runs them, and holds them off here.
|
||||
// The renderer's own select and double-click follow never see the
|
||||
// pointer lease; the port runs them, and holds them off here.
|
||||
const releases = [
|
||||
port.behaviours.select.suppress(),
|
||||
port.behaviours.dblclickFollow.suppress(),
|
||||
@@ -355,51 +389,84 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
dispatchers.delete(scene);
|
||||
if (dispatchers.get(viewer) === self) dispatchers.delete(viewer);
|
||||
clickSubscribers.length = 0;
|
||||
for (const type of POINTER_TYPES) pointerSubscribers[type].length = 0;
|
||||
for (const off of offPort) off();
|
||||
for (const hold of [...stockHolds]) hold();
|
||||
cameraInput.release();
|
||||
if (!shared) cesiumInput.dispose();
|
||||
for (const hold of [...cameraHolds]) hold();
|
||||
// A port built for this viewer goes with its dispatcher; a
|
||||
// renderer's own stays.
|
||||
releaseUnboundInput(viewer, port);
|
||||
},
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
|
||||
/**
|
||||
* @param {object} viewer
|
||||
* @param {{position: {x: number, y: number}}} click
|
||||
* @param {() => import('../render/contract/query').QueryPort|null} queryOf
|
||||
* @param {{x: number, y: number}} at Where the click is, CSS pixels.
|
||||
* @param {ClickGesture} gesture
|
||||
* @returns {ClickEvent}
|
||||
*/
|
||||
function createClickEvent(viewer, click, gesture) {
|
||||
const scene = viewer.scene;
|
||||
const position = sensorPickPosition(scene, click.position, scene.canvas);
|
||||
function createClickEvent(viewer, queryOf, at, gesture) {
|
||||
const position = sensorPickPosition(viewer, at, canvasOf(viewer));
|
||||
const { x, y } = position;
|
||||
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 native = () => once('native', () => nativeClickOf(viewer, position));
|
||||
const query = () => once('query', queryOf);
|
||||
/** The renderer's pick, with a window or not; null without a query port. */
|
||||
const pick = (window) => {
|
||||
const q = query();
|
||||
return q ? (q.pick(x, y, window) ?? null) : null;
|
||||
};
|
||||
/** @type {Map<string, {limit: number, hits: Hit[]}>} */
|
||||
const drills = new Map();
|
||||
|
||||
return {
|
||||
screenPosition: click.position,
|
||||
screenPosition: at,
|
||||
position,
|
||||
gesture,
|
||||
get pick() {
|
||||
return once('pick', () => pickThroughFollowHelper(scene.pick(position)));
|
||||
get topHit() {
|
||||
return once('top', () => {
|
||||
const hit = pick();
|
||||
// The adapter's own pick of this click is the renderer's pass, held
|
||||
// now: read later, it would be another, of a scene drawn since.
|
||||
void native()?.native.pick;
|
||||
return topHitOf(hit, () => native()?.foreign() ?? null);
|
||||
});
|
||||
},
|
||||
get drawHit() {
|
||||
return once('drawHit', () => drawHitOf(this.pick));
|
||||
const hit = this.topHit;
|
||||
return hit?.set ? hit : null;
|
||||
},
|
||||
get hit() {
|
||||
return once('hit', () =>
|
||||
pickContact(scene, position, {
|
||||
picked: this.pick,
|
||||
drill: (limit, width, height) => this.drill(limit, width, height),
|
||||
}),
|
||||
);
|
||||
return once('hit', () => {
|
||||
const q = query();
|
||||
if (!q) return this.topHit;
|
||||
return pickContact(q, position, {
|
||||
picked: this.topHit,
|
||||
// Everything drawn there, as the adapter sees it, so a contact
|
||||
// search stops at what is drawn over a contact outside the draw
|
||||
// port and finds a contact drawn there; the draw-set items alone
|
||||
// without one.
|
||||
drill: (limit, width, height) => {
|
||||
const click = native();
|
||||
return click
|
||||
? click.drillHits(limit, width, height)
|
||||
: this.drill(limit, width, height);
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
get id() {
|
||||
return once('id', () => resolvePickId(this.hit));
|
||||
@@ -408,47 +475,63 @@ function createClickEvent(viewer, click, gesture) {
|
||||
return once('ownerId', () => findPickOwner(this.id));
|
||||
},
|
||||
get meta() {
|
||||
const hit = this.hit;
|
||||
return hit?.id?.meta ?? hit?.meta;
|
||||
return this.hit?.meta;
|
||||
},
|
||||
get surface() {
|
||||
return isSurfacePick(this.hit);
|
||||
},
|
||||
pickWindow(width, height) {
|
||||
return once(`window:${width}x${height}`, () =>
|
||||
pickThroughFollowHelper(scene.pick(position, width, height)),
|
||||
);
|
||||
return !this.hit;
|
||||
},
|
||||
windowHit(width, height) {
|
||||
return once(`windowHit:${width}x${height}`, () => {
|
||||
const picked = this.pickWindow(width, height);
|
||||
const picked = pick({ width, height });
|
||||
void native()?.native.pickWindow(width, height);
|
||||
const hit = topHitOf(
|
||||
picked,
|
||||
() => native()?.foreign(width, height) ?? null,
|
||||
);
|
||||
return {
|
||||
id: resolvePickId(picked),
|
||||
drawHit: drawHitOf(picked),
|
||||
surface: isSurfacePick(picked),
|
||||
id: resolvePickId(hit),
|
||||
drawHit: hit?.set ? hit : null,
|
||||
surface: !hit,
|
||||
};
|
||||
});
|
||||
},
|
||||
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 [];
|
||||
// A deeper pass already made holds these. (One that came back short
|
||||
// may not hold every hit: it drops what is not a draw-set item.)
|
||||
if (done && limit <= done.limit) return done.hits.slice(0, limit);
|
||||
const q = query();
|
||||
if (!q) return [];
|
||||
// Only the default window is shared between layers; 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);
|
||||
const hits = q.drillPick(x, y, {
|
||||
...(width === undefined ? {} : { width }),
|
||||
...(height === undefined ? {} : { height }),
|
||||
limit: depth,
|
||||
});
|
||||
drills.set(key, { limit: depth, hits });
|
||||
return hits.slice(0, limit);
|
||||
},
|
||||
ground() {
|
||||
return once('ground', () => pickGroundPosition(viewer, position));
|
||||
return once('ground', () => groundAt(query(), position));
|
||||
},
|
||||
get native() {
|
||||
// After the renderer's pick, whose pass the adapter's reuses.
|
||||
void this.topHit;
|
||||
return native()?.native;
|
||||
},
|
||||
get pick() {
|
||||
// After the renderer's pick, whose pass the adapter's reuses.
|
||||
void this.topHit;
|
||||
return native()?.native.pick;
|
||||
},
|
||||
pickWindow(width, height) {
|
||||
void this.windowHit(width, height);
|
||||
return native()?.native.pickWindow(width, height);
|
||||
},
|
||||
};
|
||||
}
|
||||
+227
-10
@@ -1,7 +1,8 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { inputFor } from './dispatcher.js';
|
||||
import { inputFor, pickAt } from './dispatcher.js';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import {
|
||||
FAKE_EVENT_TYPES,
|
||||
FakeScreenSpaceEventHandler as FakeHandler,
|
||||
@@ -26,6 +27,7 @@ function harness({ pick = () => undefined, drillPick = () => [] } = {}) {
|
||||
stock.setInputAction(stockDouble, TYPES.LEFT_DOUBLE_CLICK);
|
||||
let clock = 0;
|
||||
const viewer = {
|
||||
isDestroyed: () => false,
|
||||
screenSpaceEventHandler: stock,
|
||||
camera: { pickEllipsoid: () => null },
|
||||
scene: {
|
||||
@@ -331,7 +333,9 @@ test('stock clicks come back by identity after the last hold', (t) => {
|
||||
});
|
||||
|
||||
test('drills of different depths on one click share a pass', (t) => {
|
||||
const hits = Array.from({ length: 20 }, (_, i) => ({ id: `hit-${i}` }));
|
||||
const hits = Array.from({ length: 20 }, (_, i) => ({
|
||||
id: { set: 'test:1', id: `hit-${i}` },
|
||||
}));
|
||||
const h = harness({ drillPick: (_p, limit) => hits.slice(0, limit) });
|
||||
t.after(() => h.input.destroy());
|
||||
const lengths = [];
|
||||
@@ -343,7 +347,7 @@ test('drills of different depths on one click share a pass', (t) => {
|
||||
assert.equal(h.calls.drillPick, 1);
|
||||
});
|
||||
|
||||
test('a touch tap’s contact search is the click’s own drill', (t) => {
|
||||
function coarsePointer(t) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');
|
||||
Object.defineProperty(globalThis, 'matchMedia', {
|
||||
configurable: true,
|
||||
@@ -353,26 +357,72 @@ test('a touch tap’s contact search is the click’s own drill', (t) => {
|
||||
if (previous) Object.defineProperty(globalThis, 'matchMedia', previous);
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
}
|
||||
|
||||
test('a touch tap finds the contact under the map, in one drill of its own', (t) => {
|
||||
coarsePointer(t);
|
||||
registerPickOwner('test-owner', (id) => id === 'plane-1');
|
||||
t.after(() => unregisterPickOwner('test-owner'));
|
||||
const tile = { primitive: { isCesium3DTileset: true } };
|
||||
const h = harness({ pick: () => tile, drillPick: () => [{ id: 'plane-1' }] });
|
||||
const drills = [];
|
||||
const h = harness({
|
||||
pick: () => tile,
|
||||
drillPick: (_p, limit, width, height) => {
|
||||
drills.push([limit, width, height]);
|
||||
return [tile, { id: { set: 'test:1', id: 'plane-1' } }];
|
||||
},
|
||||
});
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onClick((event) => seen.push(event.id, event.drawHit));
|
||||
h.click();
|
||||
assert.deepEqual(seen, ['plane-1', null]);
|
||||
assert.deepEqual(drills, [[8, 14, 14]], 'eight deep, as before');
|
||||
});
|
||||
|
||||
test('a touch tap finds a contact drawn outside the draw port', (t) => {
|
||||
coarsePointer(t);
|
||||
registerPickOwner('test-owner', (id) => id === 'bus-1');
|
||||
t.after(() => unregisterPickOwner('test-owner'));
|
||||
const h = harness({
|
||||
pick: () => undefined,
|
||||
drillPick: () => [{ primitive: { id: 'bus-1' } }],
|
||||
});
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onClick((event) => seen.push(event.id, event.ownerId));
|
||||
h.click();
|
||||
assert.deepEqual(seen, ['bus-1', 'test-owner']);
|
||||
});
|
||||
|
||||
test('a touch tap stops at something drawn outside the draw port over a contact', (t) => {
|
||||
coarsePointer(t);
|
||||
registerPickOwner('test-owner', (id) => id === 'plane-1');
|
||||
t.after(() => unregisterPickOwner('test-owner'));
|
||||
const h = harness({
|
||||
pick: () => undefined,
|
||||
drillPick: () => [
|
||||
{ primitive: { id: 'unowned' } },
|
||||
{ id: { set: 'test:1', id: 'plane-1' } },
|
||||
],
|
||||
});
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onClick((event) => seen.push(event.id));
|
||||
h.input.onClick((event) => seen.push(event.drill(8, 14, 14).length));
|
||||
h.click();
|
||||
assert.deepEqual(seen, ['plane-1', 1]);
|
||||
assert.equal(h.calls.drillPick, 1);
|
||||
assert.deepEqual(seen, [null], 'the map under the tap, as before');
|
||||
});
|
||||
|
||||
test('a short drill answers deeper asks without another pass', (t) => {
|
||||
const h = harness({ drillPick: () => [{ id: 'only' }] });
|
||||
test('a deeper ask than a short drill looks again: it held draw-set items only', (t) => {
|
||||
const h = harness({
|
||||
drillPick: () => [{ id: { set: 'test:1', id: 'only' } }],
|
||||
});
|
||||
t.after(() => h.input.destroy());
|
||||
h.input.onClick((event) => event.drill(8));
|
||||
h.input.onClick((event) => event.drill(12));
|
||||
h.input.onClick((event) => event.drill(40));
|
||||
h.click();
|
||||
assert.equal(h.calls.drillPick, 1);
|
||||
assert.equal(h.calls.drillPick, 2, '16 deep, then 40');
|
||||
});
|
||||
|
||||
test('one failing subscriber does not stop the rest', (t) => {
|
||||
@@ -456,3 +506,170 @@ test('the dispatcher is the package input export', async () => {
|
||||
const exported = await import('gods-eye-view/input');
|
||||
assert.equal(exported.inputFor, inputFor);
|
||||
});
|
||||
|
||||
test('something drawn outside the draw port is the top hit, with no set, and never a draw hit', (t) => {
|
||||
registerPickOwner('test-owner', (id) => id === 'bus-1');
|
||||
t.after(() => unregisterPickOwner('test-owner'));
|
||||
let picked = { primitive: { id: 'bus-1' } };
|
||||
const h = harness({ pick: () => picked });
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onClick((event) =>
|
||||
seen.push({
|
||||
top: event.topHit,
|
||||
draw: event.drawHit,
|
||||
id: event.id,
|
||||
owner: event.ownerId,
|
||||
surface: event.surface,
|
||||
native: event.native.pick,
|
||||
}),
|
||||
);
|
||||
h.click();
|
||||
assert.equal(h.calls.pick, 1, "the adapter's own pick reuses the renderer's");
|
||||
assert.deepEqual(seen[0].top, { set: '', id: 'bus-1', surface: false });
|
||||
assert.equal(seen[0].draw, null);
|
||||
assert.equal(seen[0].id, 'bus-1');
|
||||
assert.equal(seen[0].owner, 'test-owner');
|
||||
assert.equal(seen[0].surface, false);
|
||||
assert.equal(
|
||||
seen[0].native,
|
||||
picked,
|
||||
"the engine's own pick, for code bound to it",
|
||||
);
|
||||
picked = { primitive: { isCesium3DTileset: true } };
|
||||
h.click();
|
||||
assert.equal(seen[1].top, null, 'tiles are the map');
|
||||
assert.equal(seen[1].surface, true);
|
||||
assert.equal(seen[1].id, null);
|
||||
});
|
||||
|
||||
test('pick and pickWindow still hand over the engine pick objects, one pass each', (t) => {
|
||||
const picked = { primitive: { id: 'bus-1' } };
|
||||
const h = harness({ pick: () => picked });
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onClick((event) =>
|
||||
seen.push({
|
||||
pick: event.pick,
|
||||
window: event.pickWindow(9, 9),
|
||||
windowId: event.windowHit(9, 9).id,
|
||||
}),
|
||||
);
|
||||
h.click();
|
||||
assert.equal(seen[0].pick, picked);
|
||||
assert.equal(seen[0].window, picked);
|
||||
assert.equal(seen[0].windowId, 'bus-1');
|
||||
assert.equal(h.calls.pick, 2, 'one pass at 3x3 and one at 9x9');
|
||||
});
|
||||
|
||||
test("a draw-set item the renderer's sets do not hold is still the click's draw hit", (t) => {
|
||||
const picked = { id: { set: 'kept:1', id: 'a', meta: { k: 1 } } };
|
||||
const h = harness({ pick: () => picked });
|
||||
t.after(() => h.input.destroy());
|
||||
// The renderer's pick names nothing there: its sets do not hold `kept:1`.
|
||||
t.after(bindRenderer(h.viewer, { query: { pick: () => null } }));
|
||||
const seen = [];
|
||||
h.input.onClick((event) => seen.push(event.drawHit?.id, event.meta?.k));
|
||||
h.click();
|
||||
assert.deepEqual(seen, ['a', 1]);
|
||||
});
|
||||
|
||||
test("a click's engine pick is the renderer's pass, even when read later", async (t) => {
|
||||
let picked = { primitive: { id: 'bus-1' } };
|
||||
const h = harness({ pick: () => picked });
|
||||
t.after(() => h.input.destroy());
|
||||
const events = [];
|
||||
h.input.onClick((event) => events.push(event) && event.topHit);
|
||||
h.click();
|
||||
picked = { primitive: { id: 'bus-2' } };
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.equal(events[0].topHit.id, 'bus-1');
|
||||
assert.equal(events[0].pick.primitive.id, 'bus-1');
|
||||
assert.equal(events[0].native.pick.primitive.id, 'bus-1');
|
||||
assert.equal(h.calls.pick, 1);
|
||||
});
|
||||
|
||||
test('positions are plain CSS pixels', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onPointer('down', (event) => seen.push(event.position));
|
||||
h.input.onPointer('move', (event) => seen.push(event.endPosition));
|
||||
h.input.onClick((event) => seen.push(event.screenPosition, event.position));
|
||||
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 3, y: 4 } });
|
||||
h.click(5, 6);
|
||||
for (const position of seen) {
|
||||
assert.equal(Object.getPrototypeOf(position), Object.prototype);
|
||||
assert.deepEqual(Object.keys(position), ['x', 'y']);
|
||||
}
|
||||
assert.deepEqual(seen.at(-1), { x: 5, y: 6 });
|
||||
});
|
||||
|
||||
test("a viewer's renderer gives the dispatcher its input and query ports", (t) => {
|
||||
const listeners = new Map();
|
||||
const holds = [];
|
||||
const port = {
|
||||
on(type, cb) {
|
||||
listeners.set(type, cb);
|
||||
return () => listeners.delete(type);
|
||||
},
|
||||
suspendCameraControls(reason) {
|
||||
holds.push(reason);
|
||||
return () => holds.splice(holds.indexOf(reason), 1);
|
||||
},
|
||||
behaviours: {
|
||||
select: { enabled: true, suppress: () => () => {} },
|
||||
dblclickFollow: { enabled: false, suppress: () => () => {} },
|
||||
},
|
||||
};
|
||||
const hit = { set: 'quakes:1', id: 'quake:a', surface: false };
|
||||
const asked = [];
|
||||
const query = {
|
||||
pick: (x, y, window) => (asked.push(['pick', x, y, window]), hit),
|
||||
drillPick: () => [],
|
||||
pickPosition: () => ({ x: 6378137, y: 0, z: 0 }),
|
||||
pickEllipsoid: () => null,
|
||||
};
|
||||
const viewer = {};
|
||||
const unbind = bindRenderer(viewer, { input: port, query });
|
||||
t.after(unbind);
|
||||
const input = inputFor(viewer);
|
||||
t.after(() => input.destroy());
|
||||
assert.equal(input.stockEnabled('select'), true);
|
||||
assert.equal(input.stockEnabled('dblclickFollow'), false);
|
||||
input.suspendCamera('drag');
|
||||
assert.deepEqual(holds, ['drag']);
|
||||
const seen = [];
|
||||
input.onClick((event) => seen.push([event.drawHit, event.ground()]));
|
||||
listeners.get('click')({
|
||||
type: 'click',
|
||||
position: { x: 7, y: 8 },
|
||||
button: 0,
|
||||
modifiers: { shift: false, ctrl: false, alt: false, meta: false },
|
||||
});
|
||||
assert.equal(seen[0][0], hit);
|
||||
assert.deepEqual(seen[0][1], { x: 6378137, y: 0, z: 0 });
|
||||
assert.deepEqual(asked, [['pick', 7, 8, undefined]]);
|
||||
assert.equal(pickAt(viewer, 1, 2), hit, 'point-and-ask picks the same way');
|
||||
input.destroy();
|
||||
assert.deepEqual(holds, [], "destroy gives back the dispatcher's holds");
|
||||
assert.equal(listeners.size, 0);
|
||||
});
|
||||
|
||||
test('a viewer with no renderer and no adapter factory cannot take input', () => {
|
||||
// The adapter's factory builds over anything with a scene: this has none.
|
||||
assert.throws(() => inputFor({}), /no renderer to take input with/);
|
||||
});
|
||||
|
||||
test('point-and-ask: nothing but the map is no hit; a failing pick is none', (t) => {
|
||||
const surface = { set: '', id: '', surface: true };
|
||||
const viewer = {};
|
||||
let pick = () => surface;
|
||||
t.after(bindRenderer(viewer, { query: { pick: (...a) => pick(...a) } }));
|
||||
assert.equal(pickAt(viewer, 0, 0), null);
|
||||
pick = () => {
|
||||
throw new Error('context lost');
|
||||
};
|
||||
assert.equal(pickAt(viewer, 0, 0), null);
|
||||
assert.equal(pickAt(null, 0, 0), null);
|
||||
});
|
||||
@@ -12,17 +12,18 @@ const SENSOR_STYLES = ['thermal', 'surveillance'];
|
||||
|
||||
/**
|
||||
* The pick-buffer position for a screen click.
|
||||
* @param {object} scene The scene object the styles are recorded on.
|
||||
* @param {object} host The scene object the styles are recorded on (the
|
||||
* viewer the application's visual effects are made for).
|
||||
* @param {{x: number, y: number}} position CSS pixels on the canvas.
|
||||
* @param {{width: number, height: number, clientWidth: number,
|
||||
* clientHeight: number}} canvas The canvas the scene draws in.
|
||||
* @returns {{x: number, y: number}} A new position; the click's own is left
|
||||
* alone.
|
||||
*/
|
||||
export function sensorPickPosition(scene, position, canvas) {
|
||||
export function sensorPickPosition(host, position, canvas) {
|
||||
const out = { x: position.x, y: position.y };
|
||||
const stages = styleStagesOf(scene);
|
||||
if (!stages) return out;
|
||||
const stages = styleStagesOf(host);
|
||||
if (!stages || !canvas) return out;
|
||||
for (const style of SENSOR_STYLES) {
|
||||
const stage = stages[style];
|
||||
if (!stage?.enabled) continue;
|
||||
|
||||
@@ -1,12 +1,71 @@
|
||||
/**
|
||||
* Test doubles for the input dispatcher: a stand-in for Cesium's
|
||||
* `ScreenSpaceEventHandler`, and a dispatcher made on it ahead of the code
|
||||
* under test, so that code's `inputFor(viewer)` gets the fake.
|
||||
* under test, so that code's `inputFor(viewer)` gets the fake. Imported by
|
||||
* tests only.
|
||||
*
|
||||
* The dispatcher's input port is the Cesium adapter's (`findInput`, over the
|
||||
* fake handler), and its clicks pick through {@link sceneQuery}: the
|
||||
* viewer's renderer's query port where it has one that picks, else the
|
||||
* viewer double's own `scene.pick` and `drillPick`, read as the renderer's
|
||||
* picks are.
|
||||
*/
|
||||
import { HANDLER_EVENT_TYPES, inputFor } from './dispatcher.js';
|
||||
import * as Cesium from 'cesium';
|
||||
// The adapter's unbound input port and a click's own Cesium picks.
|
||||
import '../render/cesium/input.js';
|
||||
import '../render/cesium/nativeClick.js';
|
||||
import { rendererOf } from '../render/rendererOf.js';
|
||||
import { fakeScenePicks } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { provideStyleStageAlias } from '../styles/styleStages.js';
|
||||
import { inputFor } from './dispatcher.js';
|
||||
|
||||
/** Cesium's own event types, the ones the input port binds. */
|
||||
export const FAKE_EVENT_TYPES = HANDLER_EVENT_TYPES;
|
||||
export const FAKE_EVENT_TYPES = Cesium.ScreenSpaceEventType;
|
||||
|
||||
// Tests record sensor styles on the viewer double's scene, as the code under
|
||||
// them once did: the dispatcher, which looks them up by the viewer, finds
|
||||
// them there too.
|
||||
provideStyleStageAlias((viewer) => viewer?.scene ?? null);
|
||||
|
||||
/**
|
||||
* A query port for a viewer double's clicks: its renderer's, where that
|
||||
* picks; else one over the double's scene (`fakeScenePicks`), with its depth
|
||||
* and ellipsoid picks.
|
||||
* @param {object} viewer
|
||||
*/
|
||||
export function sceneQuery(viewer) {
|
||||
const bound = () => {
|
||||
const query = rendererOf(viewer)?.query;
|
||||
return typeof query?.pick === 'function' ? query : null;
|
||||
};
|
||||
const at = (x, y) => new Cesium.Cartesian2(x, y);
|
||||
const own = {
|
||||
...fakeScenePicks(viewer),
|
||||
pickPosition(x, y) {
|
||||
const scene = viewer.scene;
|
||||
if (
|
||||
!scene?.pickPositionSupported ||
|
||||
typeof scene.pickPosition !== 'function'
|
||||
)
|
||||
return null;
|
||||
return scene.pickPosition(at(x, y)) ?? null;
|
||||
},
|
||||
pickEllipsoid(x, y) {
|
||||
const camera = viewer.camera ?? viewer.scene?.camera;
|
||||
return camera?.pickEllipsoid?.(at(x, y)) ?? null;
|
||||
},
|
||||
};
|
||||
return new Proxy(own, {
|
||||
get(target, key) {
|
||||
const query = bound();
|
||||
if (query) {
|
||||
const value = query[key];
|
||||
return typeof value === 'function' ? value.bind(query) : value;
|
||||
}
|
||||
return target[key];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export class FakeScreenSpaceEventHandler {
|
||||
constructor() {
|
||||
@@ -45,9 +104,16 @@ export class FakeScreenSpaceEventHandler {
|
||||
*/
|
||||
export function fakeInput(viewer, { now } = {}) {
|
||||
const handler = new FakeScreenSpaceEventHandler();
|
||||
// A Cesium viewer's canvas is its scene's.
|
||||
if (!('canvas' in viewer))
|
||||
Object.defineProperty(viewer, 'canvas', {
|
||||
configurable: true,
|
||||
get: () => viewer.scene?.canvas,
|
||||
});
|
||||
const input = inputFor(viewer, {
|
||||
createHandler: () => handler,
|
||||
document: null,
|
||||
query: sceneQuery(viewer),
|
||||
...(now ? { now } : {}),
|
||||
});
|
||||
const T = FAKE_EVENT_TYPES;
|
||||
|
||||
@@ -395,7 +395,7 @@ export function createLifecycle({
|
||||
input,
|
||||
(event) => {
|
||||
if (!layerState._enabled) return;
|
||||
const picked = event.pick;
|
||||
const picked = event.topHit;
|
||||
const cameraId = parts.selection.extractPickedCameraId(
|
||||
event.drawHit ?? null,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
|
||||
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isSurfacePick } from '../../data/scenePick.js';
|
||||
import {
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
@@ -167,11 +166,11 @@ export function createCyclonesLayer({
|
||||
if (id) layer.setParams({ stormId: id });
|
||||
return;
|
||||
}
|
||||
// A storm's own drawing names it; empty map (the globe, or 3D tiles,
|
||||
// which pick as tileset content without an id) clears the selection.
|
||||
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
|
||||
// clears the selection.
|
||||
const id = rendering?.pickStorm(event.drawHit);
|
||||
if (id) layer.setParams({ stormId: id });
|
||||
else if (isSurfacePick(event.pick)) layer.setParams({ clear: true });
|
||||
else if (!event.topHit) layer.setParams({ clear: true });
|
||||
});
|
||||
owner.unsubscribe = unsubscribe;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export function createSelection({
|
||||
if (layerState._clickSubscription || !layerState._viewer) return;
|
||||
const input = inputFor(layerState._viewer);
|
||||
layerState._clickSubscription = input.onClick((event) => {
|
||||
const picked = event.pick;
|
||||
const picked = event.topHit;
|
||||
const fire = pickedFire(event.drawHit);
|
||||
if (fire) {
|
||||
selectAndFocusFire(fire);
|
||||
|
||||
@@ -46,15 +46,14 @@ import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
/**
|
||||
* The icao a pick carries: a draw-set item's id (the icon and model sets'
|
||||
* rows), a string pick id, or a primitive's id.
|
||||
* The icao a click's hit carries (`event.hit`, the contract's `Hit`): a
|
||||
* draw-set item's id (the icon and model sets' rows), or the id of
|
||||
* something drawn outside the draw port (a hit with no set).
|
||||
*/
|
||||
function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
if (typeof id === 'string') return id;
|
||||
if (id && typeof id.set === 'string' && typeof id.id === 'string')
|
||||
return isOtherTrackedIconSet(id.set, 'flights') ? undefined : id.id;
|
||||
return picked?.primitive?.id;
|
||||
function aircraftPickId(hit) {
|
||||
if (!hit || hit.surface) return undefined;
|
||||
if (!hit.set) return hit.id || undefined;
|
||||
return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
export function createTracking({
|
||||
|
||||
@@ -615,7 +615,7 @@ export function createGhostMapsLayer({
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.pick;
|
||||
const picked = event.topHit;
|
||||
const key = picked ? hitKey(event.drawHit) : null;
|
||||
if (key) {
|
||||
_selectedKey = key;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../../render/cesium/input.js';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
|
||||
@@ -45,15 +45,14 @@ import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
/**
|
||||
* The icao a pick carries: a draw-set item's id (the icon and model sets'
|
||||
* rows), a string pick id, or a primitive's id.
|
||||
* The icao a click's hit carries (`event.hit`, the contract's `Hit`): a
|
||||
* draw-set item's id (the icon and model sets' rows), or the id of
|
||||
* something drawn outside the draw port (a hit with no set).
|
||||
*/
|
||||
function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
if (typeof id === 'string') return id;
|
||||
if (id && typeof id.set === 'string' && typeof id.id === 'string')
|
||||
return isOtherTrackedIconSet(id.set, 'military') ? undefined : id.id;
|
||||
return picked?.primitive?.id;
|
||||
function aircraftPickId(hit) {
|
||||
if (!hit || hit.surface) return undefined;
|
||||
if (!hit.set) return hit.id || undefined;
|
||||
return isOtherTrackedIconSet(hit.set, 'military') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
export function createTracking({
|
||||
|
||||
@@ -227,7 +227,7 @@ export function createFirePerimetersLayer({
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.pick;
|
||||
const picked = event.topHit;
|
||||
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
|
||||
if (incidentId) {
|
||||
abortLinkVerification();
|
||||
|
||||
@@ -36,7 +36,7 @@ export function createInteraction({
|
||||
? stationId
|
||||
: null;
|
||||
};
|
||||
const primaryPick = event.pick;
|
||||
const primaryPick = event.topHit;
|
||||
const primaryStationId = stationFromPick(primaryPick);
|
||||
if (primaryStationId) return primaryStationId;
|
||||
const primaryId = resolvePickId(primaryPick);
|
||||
|
||||
@@ -21,12 +21,15 @@ function interaction() {
|
||||
});
|
||||
}
|
||||
|
||||
/** A draw-set item's hit. */
|
||||
const hit = (id, set = 'radio:1:stations') => ({ set, id, surface: false });
|
||||
|
||||
/** A click event whose drill answers only with the window it is asked for. */
|
||||
function clickEvent({ pick, windowHits = [] }) {
|
||||
const drills = [];
|
||||
return {
|
||||
drills,
|
||||
pick,
|
||||
topHit: pick ?? null,
|
||||
drill(limit, width, height) {
|
||||
drills.push([limit, width, height]);
|
||||
return width === RADIO_PICK_WINDOW_PX && height === RADIO_PICK_WINDOW_PX
|
||||
@@ -40,7 +43,7 @@ test('a near miss finds the station through one windowed drill', () => {
|
||||
const { pickedRadioStationAt } = interaction();
|
||||
const event = clickEvent({
|
||||
pick: undefined,
|
||||
windowHits: [{ id: 'tile' }, { id: 'radio:kexp' }],
|
||||
windowHits: [hit('notes:1', 'notes:1'), hit('radio:kexp')],
|
||||
});
|
||||
assert.equal(pickedRadioStationAt(event), 'kexp');
|
||||
assert.deepEqual(event.drills, [
|
||||
@@ -50,12 +53,12 @@ test('a near miss finds the station through one windowed drill', () => {
|
||||
|
||||
test('a direct hit needs no drill, and another layer’s contact keeps its click', () => {
|
||||
const { pickedRadioStationAt } = interaction();
|
||||
const direct = clickEvent({ pick: { id: 'radio:kexp' } });
|
||||
const direct = clickEvent({ pick: hit('radio:kexp') });
|
||||
assert.equal(pickedRadioStationAt(direct), 'kexp');
|
||||
assert.deepEqual(direct.drills, []);
|
||||
const other = clickEvent({
|
||||
pick: { id: 'flight-1' },
|
||||
windowHits: [{ id: 'radio:kexp' }],
|
||||
pick: hit('flight-1', 'flights:1'),
|
||||
windowHits: [hit('radio:kexp')],
|
||||
});
|
||||
assert.equal(pickedRadioStationAt(other), null);
|
||||
});
|
||||
@@ -45,7 +45,7 @@ export function createInteraction({
|
||||
|
||||
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!layerState._enabled) return;
|
||||
const picked = event.pick;
|
||||
const picked = event.topHit;
|
||||
const hit = event.drawHit;
|
||||
|
||||
// Clicking the tracked satellite's own dot — ignore
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../../render/cesium/input.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { EventEmitter, once } from 'node:events';
|
||||
|
||||
@@ -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';
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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';
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// src/scenes/interactionsView.test.mjs — the Scene actions panel renders in
|
||||
// the viewer's container from what the scene interactions owner presents.
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../render/cesium/input.js';
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @module styles/styleStages
|
||||
* @description The app's record of each visual style on a scene: its
|
||||
* @description The app's record of each visual style on a scene object (the
|
||||
* viewer the application's visual effects are made for): its
|
||||
* intensity, parameter values and whether it draws, as the application set
|
||||
* them. Code that must follow a style's picture (sensor picks) reads it here
|
||||
* rather than asking the renderer.
|
||||
@@ -9,7 +10,22 @@
|
||||
const records = new WeakMap();
|
||||
|
||||
/**
|
||||
* @param {object} scene
|
||||
* Another object a scene object's styles may be recorded on, for test
|
||||
* doubles whose tests record them on the engine's own scene.
|
||||
*/
|
||||
let aliasOf = null;
|
||||
|
||||
/**
|
||||
* Let `styleStagesOf` also find records made on `alias(host)`; a later call
|
||||
* replaces it. For test doubles (src/input/testDoubles.mjs).
|
||||
* @param {((host: object) => object|null|undefined) | null} alias
|
||||
*/
|
||||
export function provideStyleStageAlias(alias) {
|
||||
aliasOf = alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} scene The scene object.
|
||||
* @param {Record<string, {enabled: boolean, uniforms: Record<string, number>}>} stages
|
||||
* @returns {() => void} Forgets them, if they are still the scene's.
|
||||
*/
|
||||
@@ -25,5 +41,10 @@ export function registerStyleStages(scene, stages) {
|
||||
* @param {object} scene
|
||||
* @returns {Record<string, {enabled: boolean, uniforms: Record<string, number>}> | null}
|
||||
*/
|
||||
export const styleStagesOf = (scene) =>
|
||||
(scene && typeof scene === 'object' && records.get(scene)) || null;
|
||||
export function styleStagesOf(scene) {
|
||||
if (!scene || typeof scene !== 'object') return null;
|
||||
const own = records.get(scene);
|
||||
if (own) return own;
|
||||
const alias = aliasOf?.(scene);
|
||||
return (alias && typeof alias === 'object' && records.get(alias)) || null;
|
||||
}
|
||||
@@ -10,7 +10,10 @@
|
||||
* `frustum.projectionMatrix`; `viewRectangle()` from its
|
||||
* `computeViewRectangle()`, in degrees; events from its own `moveEnd`,
|
||||
* `moveStart` and `changed`.
|
||||
* - query: `sampleHeightNow` through the scene's height service;
|
||||
* - query: `pick` and `drillPick` through the scene's own, naming a pick of
|
||||
* a draw-set item (its pick id `{set, id}`) as the renderer does and
|
||||
* anything else as the map (`drillPick`: draw-set items only);
|
||||
* `sampleHeightNow` through the scene's height service;
|
||||
* `pickPosition` through the scene's, where `pickPositionSupported`;
|
||||
* `pickRay` and `pickEllipsoid` through the double camera's, when it has
|
||||
* them; `pickGlobe` through the scene's globe; `project`
|
||||
@@ -25,6 +28,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { heightsFor } from '../render/cesium/heights.js';
|
||||
import { drawHitOf } from '../render/cesium/drawHit.js';
|
||||
import { rememberPick } from '../render/cesium/pickMemo.js';
|
||||
import { fakeDrawPort } from './fakeDrawPort.mjs';
|
||||
|
||||
const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z);
|
||||
@@ -43,6 +48,46 @@ const cameraOfDouble = (viewer) =>
|
||||
? viewer.camera
|
||||
: viewer.scene.camera;
|
||||
|
||||
/**
|
||||
* A query port's `pick` and `drillPick` over a viewer double's own
|
||||
* `scene.pick` and `drillPick`: a pick of a draw-set item (its pick id
|
||||
* `{set, id}`) is that item's `Hit`, anything else the map; a drill names
|
||||
* draw-set items only. A pick is noted as the Cesium query port notes its
|
||||
* own, so a click's own Cesium picks reuse it.
|
||||
* @param {object} viewer
|
||||
*/
|
||||
export function fakeScenePicks(viewer) {
|
||||
const at = (x, y) => new Cesium.Cartesian2(x, y);
|
||||
return {
|
||||
pick(x, y, window = {}) {
|
||||
const width = window.width ?? 3;
|
||||
const height = window.height ?? 3;
|
||||
const scene = viewer.scene;
|
||||
if (typeof scene?.pick !== 'function') return null;
|
||||
const picked = scene.pick(at(x, y), width, height);
|
||||
rememberPick(scene, x, y, width, height, picked);
|
||||
return drawHitOf(picked) ?? { set: '', id: '', surface: true };
|
||||
},
|
||||
drillPick(x, y, { width, height, limit } = {}) {
|
||||
const scene = viewer.scene;
|
||||
if (typeof scene?.drillPick !== 'function' || limit === 0) return [];
|
||||
const hits = [];
|
||||
for (const picked of scene.drillPick(
|
||||
at(x, y),
|
||||
limit === undefined ? undefined : Math.max(limit, 16),
|
||||
width,
|
||||
height,
|
||||
) ?? []) {
|
||||
const hit = drawHitOf(picked);
|
||||
if (!hit) continue;
|
||||
hits.push(hit);
|
||||
if (limit !== undefined && hits.length >= limit) break;
|
||||
}
|
||||
return hits;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The query port `bindFakeCesiumScene` binds, on its own, for a test that
|
||||
* binds its other ports another way (`bindFakeCesiumCamera`'s `ports`).
|
||||
@@ -50,6 +95,7 @@ const cameraOfDouble = (viewer) =>
|
||||
*/
|
||||
export function fakeSceneQuery(viewer) {
|
||||
return {
|
||||
...fakeScenePicks(viewer),
|
||||
project(position) {
|
||||
// The position itself, so a stub can tell positions apart by identity.
|
||||
const s = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
|
||||
@@ -77,6 +77,7 @@ export const SCENE_MEMBERS = new Set([
|
||||
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',
|
||||
|
||||
@@ -94,7 +94,7 @@ export class VisualEffects {
|
||||
this.stages[name] = this.styleRecord(name, definition);
|
||||
}
|
||||
this.stageEntries = Object.entries(this.stages);
|
||||
this.forgetStages = registerStyleStages(this.viewer?.scene, this.stages);
|
||||
this.forgetStages = registerStyleStages(this.viewer, this.stages);
|
||||
}
|
||||
|
||||
/** A style's record, its uniforms written through to the renderer. */
|
||||
|
||||
@@ -128,9 +128,9 @@ test('construction is inert and initialization creates one owned pipeline', () =
|
||||
f.effects.initPostProcess();
|
||||
assert.equal(f.stages.size, 6);
|
||||
assert.ok([...f.stages].every((stage) => !stage.enabled));
|
||||
assert.equal(styleStagesOf(f.effects.viewer.scene), f.effects.stages);
|
||||
assert.equal(styleStagesOf(f.effects.viewer), f.effects.stages);
|
||||
f.effects.destroy();
|
||||
assert.equal(styleStagesOf(f.effects.viewer.scene), null);
|
||||
assert.equal(styleStagesOf(f.effects.viewer), null);
|
||||
});
|
||||
|
||||
test('crossfade uses the established 500ms easing and settles without idle frames', () => {
|
||||
|
||||
Reference in new issue
Block a user