mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Take pointer input through one dispatcher per scene
Every layer and tool bound its own ScreenSpaceEventHandler and picked the same click again: with the usual layers on, one click ran about 26 scene.pick and 2 drillPick passes (120-215 ms in NYC with 18 layers). Pointer input now comes in through src/input/dispatcher.js, one handler per scene. A click is picked lazily and at most once per kind of query, and every subscriber reads the same ClickEvent (pick, hit, id, ownerId, gesture, drill, ground). The same click now costs 3 picks and 2 drills, 17-70 ms. - Ambient onClick subscribers run only while no tool holds the pointer, checked once per event; tools subscribe with their lease. Moves and releases always reach ambient subscribers, so hover and drags end cleanly. - Camera input and the viewer's stock select/track clicks are ref-counted holds (suspendCamera, suppressStockClicks). The dispatcher owns the controller's enableInputs, so a Cesium flight that ends no longer turns input back on under a drag or the cockpit. - The draw tool, imagery box, CCTV gizmo, cockpit, directions and every selecting layer use it; bindTrackingClickGesture is gone (the gesture is on the event). A source scan forbids new handlers, enableInputs writes and stock-click removal outside the dispatcher. - The sensor-style pick correction transit had now applies to every layer. - Radio's 8-pick near-miss ring is one 17x17 windowed drill. - A missed pick passed to pickContact is no longer picked again, and a touch tap's contact search shares the click's drill. - A gizmo drag whose release Cesium never reported ends on the next press instead of leaving the camera held. The dispatcher is exported as ./input with the pointer-lease functions, and documented in docs/APPLICATION.md.
This commit is contained in:
1 parent
83ec9473b6
commit
02d492a079
97 files changed
+2506
-1307
No files matched your search
@@ -0,0 +1,440 @@
|
||||
/**
|
||||
* @module input/dispatcher
|
||||
* @description The one place pointer input over the globe comes in: a single
|
||||
* `ScreenSpaceEventHandler` per scene, a click picked once and handed to
|
||||
* every subscriber, and the camera-input and stock-click holds tools take.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* Who gets the pointer:
|
||||
* - Ambient subscribers ({@link InputDispatcher.onClick}, and `onPointer`
|
||||
* without a lease) run only while no tool holds the pointer
|
||||
* (src/data/inputOwnership.js). The check is made once per event, before
|
||||
* any subscriber runs, so a tool that releases its lease while handling a
|
||||
* click does not let that same click through to ambient selection. Ambient
|
||||
* `move` and `up` are the exceptions: hover sees every move, so it can drop
|
||||
* its cursor or card when a tool takes the pointer, and a release always
|
||||
* reaches whoever began the press, so a drag started while the pointer was
|
||||
* 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 holds, not by a flag: every suspender gets its
|
||||
* own release, and input comes back when the last one releases. The
|
||||
* dispatcher owns the controller's `enableInputs`: what others write to it
|
||||
* (Cesium's own camera flights turn it off and back on) is kept, and it reads
|
||||
* true only while that is true and no hold is out, so a flight that ends can
|
||||
* no longer 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.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { isLeaseCurrent, isPointerFree } from '../data/inputOwnership.js';
|
||||
import {
|
||||
findPickOwner,
|
||||
pickContact,
|
||||
resolvePickId,
|
||||
} from '../data/pickRegistry.js';
|
||||
import { isSurfacePick, pickGroundPosition } from '../data/scenePick.js';
|
||||
import { sensorPickPosition } from './sensorPick.js';
|
||||
|
||||
// A tool takes the pointer with a lease before it subscribes with one.
|
||||
export {
|
||||
claimPointer,
|
||||
isLeaseCurrent,
|
||||
isPointerFree,
|
||||
pointerOwner,
|
||||
releasePointer,
|
||||
} from '../data/inputOwnership.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;
|
||||
|
||||
const POINTER_TYPES = ['down', 'move', 'up', 'click', 'dblclick'];
|
||||
|
||||
/** A tool that re-arms takes a new lease each time: it may pass a getter. */
|
||||
const leaseOf = (entry) =>
|
||||
typeof entry.lease === 'function' ? entry.lease() : entry.lease;
|
||||
|
||||
/** @type {WeakMap<object, InputDispatcher>} scene -> dispatcher */
|
||||
const dispatchers = new WeakMap();
|
||||
|
||||
/**
|
||||
* @typedef {object} ClickGesture
|
||||
* @property {number} travelPx Pointer travel during the press, summed per
|
||||
* segment (an orbit nudge that comes back is not a zero-distance click).
|
||||
* @property {number} durationMs Press time.
|
||||
*/
|
||||
|
||||
/**
|
||||
* One left click, picked at most once per kind of query. Every getter and
|
||||
* method is memoized, so subscribers share the passes.
|
||||
* @typedef {object} ClickEvent
|
||||
* @property {{x: number, y: number}} screenPosition Where the user clicked.
|
||||
* @property {Cesium.Cartesian2} 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 {object|undefined} hit `pick`, or on a coarse pointer the first
|
||||
* registered contact under a surface pick (`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 {(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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} InputDispatcher
|
||||
* @property {(fn: (event: ClickEvent) => void) => () => void} onClick
|
||||
* 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. 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 {() => number} subscriberCount Live click and pointer
|
||||
* subscriptions, for leak checks.
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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, eventTypes?: object, now?: () => number}} [options]
|
||||
* Used only by the call that makes it.
|
||||
* @returns {InputDispatcher}
|
||||
*/
|
||||
export function inputFor(viewer, options = {}) {
|
||||
const scene = viewer.scene;
|
||||
let dispatcher = dispatchers.get(scene);
|
||||
if (!dispatcher) {
|
||||
dispatcher = createDispatcher(viewer, options);
|
||||
dispatchers.set(scene, dispatcher);
|
||||
}
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take over the controller's `enableInputs`: what others write to it is kept
|
||||
* (through an accessor already there, if any), and it reads true only while
|
||||
* that is true and no hold is out.
|
||||
* @param {object|undefined} controller
|
||||
* @param {Set<object>} holds
|
||||
* @returns {() => void} Gives the controller its own property back.
|
||||
*/
|
||||
function ownCameraInput(controller, holds) {
|
||||
if (!controller) return () => {};
|
||||
const own = Object.getOwnPropertyDescriptor(controller, 'enableInputs');
|
||||
if (own && !own.configurable) {
|
||||
console.warn('Camera input holds are unavailable: enableInputs is fixed');
|
||||
return () => {};
|
||||
}
|
||||
// A class may define it on its prototype; the hold shadows that for a while.
|
||||
let original = own;
|
||||
for (let proto = Object.getPrototypeOf(controller); !original && proto;) {
|
||||
original = Object.getOwnPropertyDescriptor(proto, 'enableInputs');
|
||||
proto = Object.getPrototypeOf(proto);
|
||||
}
|
||||
original ??= { value: true, writable: true, enumerable: true };
|
||||
let written = Boolean(original.get ? true : original.value);
|
||||
const read = () =>
|
||||
original.get ? Boolean(original.get.call(controller)) : written;
|
||||
Object.defineProperty(controller, 'enableInputs', {
|
||||
configurable: true,
|
||||
enumerable: original.enumerable ?? true,
|
||||
get: () => read() && holds.size === 0,
|
||||
set: (value) => {
|
||||
written = Boolean(value);
|
||||
original.set?.call(controller, value);
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
delete controller.enableInputs;
|
||||
if (own?.get || own?.set)
|
||||
Object.defineProperty(controller, 'enableInputs', own);
|
||||
else if (own || !(original.get || original.set))
|
||||
controller.enableInputs = written;
|
||||
};
|
||||
}
|
||||
|
||||
function createDispatcher(
|
||||
viewer,
|
||||
{
|
||||
createHandler = (canvas) => new Cesium.ScreenSpaceEventHandler(canvas),
|
||||
eventTypes = Cesium.ScreenSpaceEventType,
|
||||
now = () => performance.now(),
|
||||
},
|
||||
) {
|
||||
const scene = viewer.scene;
|
||||
const cameraHolds = new Set();
|
||||
// Before the handler, so a controller that cannot be owned leaks nothing.
|
||||
const releaseCameraInput = ownCameraInput(
|
||||
scene.screenSpaceCameraController,
|
||||
cameraHolds,
|
||||
);
|
||||
const handler = createHandler(scene.canvas);
|
||||
/** @type {Array<{fn: Function}>} */
|
||||
const clickSubscribers = [];
|
||||
/** @type {Record<string, Array<{fn: Function, lease: object|null}>>} */
|
||||
const pointerSubscribers = Object.fromEntries(
|
||||
POINTER_TYPES.map((type) => [type, []]),
|
||||
);
|
||||
const stockHolds = new Set();
|
||||
let stockSaved = null;
|
||||
let destroyed = false;
|
||||
|
||||
let pressActive = false;
|
||||
let pressStartedAt = 0;
|
||||
let previousPosition = null;
|
||||
let travelPx = 0;
|
||||
let completedGesture = null;
|
||||
|
||||
const appendTravel = (position) => {
|
||||
if (
|
||||
!pressActive ||
|
||||
!Number.isFinite(position?.x) ||
|
||||
!Number.isFinite(position?.y)
|
||||
)
|
||||
return;
|
||||
if (previousPosition) {
|
||||
travelPx += Math.hypot(
|
||||
position.x - previousPosition.x,
|
||||
position.y - previousPosition.y,
|
||||
);
|
||||
}
|
||||
previousPosition = { x: position.x, y: position.y };
|
||||
};
|
||||
|
||||
const finishPress = (position) => {
|
||||
if (!pressActive) return;
|
||||
appendTravel(position);
|
||||
completedGesture = {
|
||||
travelPx,
|
||||
durationMs: Math.max(0, now() - pressStartedAt),
|
||||
};
|
||||
pressActive = false;
|
||||
previousPosition = null;
|
||||
};
|
||||
|
||||
const run = (list, free, arg) => {
|
||||
for (const entry of [...list]) {
|
||||
if (entry.lease ? !isLeaseCurrent(leaseOf(entry)) : !free) continue;
|
||||
try {
|
||||
entry.fn(arg);
|
||||
} catch (error) {
|
||||
console.error('Pointer input handler failed', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
pressActive = true;
|
||||
pressStartedAt = now();
|
||||
previousPosition = null;
|
||||
travelPx = 0;
|
||||
completedGesture = null;
|
||||
appendTravel(event?.position);
|
||||
run(pointerSubscribers.down, isPointerFree(), event);
|
||||
}, eventTypes.LEFT_DOWN);
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
appendTravel(event?.endPosition ?? event?.position);
|
||||
run(pointerSubscribers.move, true, event);
|
||||
}, eventTypes.MOUSE_MOVE);
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
finishPress(event?.position);
|
||||
run(pointerSubscribers.up, true, event);
|
||||
}, eventTypes.LEFT_UP);
|
||||
|
||||
handler.setInputAction((click) => {
|
||||
if (pressActive) finishPress(click?.position);
|
||||
const gesture = completedGesture || { travelPx: 0, durationMs: 0 };
|
||||
completedGesture = null;
|
||||
const free = isPointerFree();
|
||||
const event = createClickEvent(viewer, click, gesture);
|
||||
run(pointerSubscribers.click, free, event);
|
||||
if (free) run(clickSubscribers, true, event);
|
||||
}, eventTypes.LEFT_CLICK);
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
run(pointerSubscribers.dblclick, isPointerFree(), event);
|
||||
}, eventTypes.LEFT_DOUBLE_CLICK);
|
||||
|
||||
const subscribe = (list, entry) => {
|
||||
if (destroyed) return () => {};
|
||||
list.push(entry);
|
||||
return () => {
|
||||
const at = list.indexOf(entry);
|
||||
if (at >= 0) list.splice(at, 1);
|
||||
};
|
||||
};
|
||||
|
||||
const stockHandler = () => viewer.screenSpaceEventHandler;
|
||||
const stockTypes = () => [
|
||||
eventTypes.LEFT_CLICK,
|
||||
eventTypes.LEFT_DOUBLE_CLICK,
|
||||
];
|
||||
|
||||
const restoreStock = () => {
|
||||
const stock = stockHandler();
|
||||
if (stockSaved && stock && !stock.isDestroyed?.()) {
|
||||
for (const [type, action] of stockSaved) {
|
||||
if (action) stock.setInputAction(action, type);
|
||||
}
|
||||
}
|
||||
stockSaved = null;
|
||||
};
|
||||
|
||||
return {
|
||||
onClick(fn) {
|
||||
return subscribe(clickSubscribers, { fn, lease: null });
|
||||
},
|
||||
|
||||
onPointer(type, fn, { lease = null } = {}) {
|
||||
const list = pointerSubscribers[type];
|
||||
if (!list) throw new TypeError(`Unknown pointer event: ${type}`);
|
||||
return subscribe(list, { fn, lease });
|
||||
},
|
||||
|
||||
suspendCamera(reason) {
|
||||
if (destroyed) return () => {};
|
||||
const hold = { reason };
|
||||
cameraHolds.add(hold);
|
||||
return () => {
|
||||
cameraHolds.delete(hold);
|
||||
};
|
||||
},
|
||||
|
||||
suppressStockClicks() {
|
||||
if (destroyed) return () => {};
|
||||
const hold = {};
|
||||
if (stockHolds.size === 0) {
|
||||
const stock = stockHandler();
|
||||
if (stock) {
|
||||
// Cesium's own select and double-click-track run on the viewer's
|
||||
// handler and never see the pointer lease.
|
||||
stockSaved = stockTypes().map((type) => [
|
||||
type,
|
||||
stock.getInputAction(type),
|
||||
]);
|
||||
for (const type of stockTypes()) stock.removeInputAction(type);
|
||||
}
|
||||
}
|
||||
stockHolds.add(hold);
|
||||
return () => {
|
||||
if (!stockHolds.delete(hold) || stockHolds.size > 0) return;
|
||||
restoreStock();
|
||||
};
|
||||
},
|
||||
|
||||
subscriberCount() {
|
||||
return POINTER_TYPES.reduce(
|
||||
(sum, type) => sum + pointerSubscribers[type].length,
|
||||
clickSubscribers.length,
|
||||
);
|
||||
},
|
||||
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
dispatchers.delete(scene);
|
||||
clickSubscribers.length = 0;
|
||||
for (const type of POINTER_TYPES) pointerSubscribers[type].length = 0;
|
||||
cameraHolds.clear();
|
||||
releaseCameraInput();
|
||||
if (stockHolds.size) {
|
||||
stockHolds.clear();
|
||||
restoreStock();
|
||||
}
|
||||
if (!handler.isDestroyed?.()) handler.destroy?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} viewer
|
||||
* @param {{position: {x: number, y: number}}} click
|
||||
* @param {ClickGesture} gesture
|
||||
* @returns {ClickEvent}
|
||||
*/
|
||||
function createClickEvent(viewer, click, gesture) {
|
||||
const scene = viewer.scene;
|
||||
const position = sensorPickPosition(scene, click.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 drills = new Map();
|
||||
|
||||
return {
|
||||
screenPosition: click.position,
|
||||
position,
|
||||
gesture,
|
||||
get pick() {
|
||||
return once('pick', () => scene.pick(position));
|
||||
},
|
||||
get hit() {
|
||||
return once('hit', () =>
|
||||
pickContact(scene, position, {
|
||||
picked: this.pick,
|
||||
drill: (limit, width, height) => this.drill(limit, width, height),
|
||||
}),
|
||||
);
|
||||
},
|
||||
get id() {
|
||||
return once('id', () => resolvePickId(this.hit));
|
||||
},
|
||||
get ownerId() {
|
||||
return once('ownerId', () => findPickOwner(this.id));
|
||||
},
|
||||
get meta() {
|
||||
const hit = this.hit;
|
||||
return hit?.id?.meta ?? hit?.meta;
|
||||
},
|
||||
get surface() {
|
||||
return isSurfacePick(this.hit);
|
||||
},
|
||||
pickWindow(width, height) {
|
||||
return once(`window:${width}x${height}`, () =>
|
||||
scene.pick(position, width, height),
|
||||
);
|
||||
},
|
||||
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 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) || [];
|
||||
drills.set(key, { limit: depth, hits });
|
||||
return hits.slice(0, limit);
|
||||
},
|
||||
ground() {
|
||||
return once('ground', () => pickGroundPosition(viewer, position));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { inputFor } from './dispatcher.js';
|
||||
import {
|
||||
FAKE_EVENT_TYPES,
|
||||
FakeScreenSpaceEventHandler as FakeHandler,
|
||||
fakeInput,
|
||||
} from './testDoubles.mjs';
|
||||
import { sensorPickPosition } from './sensorPick.js';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import {
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
} from '../data/pickRegistry.js';
|
||||
|
||||
const TYPES = FAKE_EVENT_TYPES;
|
||||
|
||||
function harness({ pick = () => undefined, drillPick = () => [] } = {}) {
|
||||
const calls = { pick: 0, drillPick: 0 };
|
||||
const stock = new FakeHandler();
|
||||
const stockClick = () => {};
|
||||
const stockDouble = () => {};
|
||||
stock.setInputAction(stockClick, TYPES.LEFT_CLICK);
|
||||
stock.setInputAction(stockDouble, TYPES.LEFT_DOUBLE_CLICK);
|
||||
let clock = 0;
|
||||
const viewer = {
|
||||
screenSpaceEventHandler: stock,
|
||||
camera: { pickEllipsoid: () => null },
|
||||
scene: {
|
||||
canvas: {},
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
pick(...args) {
|
||||
calls.pick += 1;
|
||||
return pick(...args);
|
||||
},
|
||||
drillPick(...args) {
|
||||
calls.drillPick += 1;
|
||||
return drillPick(...args);
|
||||
},
|
||||
},
|
||||
};
|
||||
const { input, handler } = fakeInput(viewer, { now: () => clock });
|
||||
return {
|
||||
viewer,
|
||||
input,
|
||||
handler,
|
||||
stock,
|
||||
stockClick,
|
||||
stockDouble,
|
||||
calls,
|
||||
advance(ms) {
|
||||
clock += ms;
|
||||
},
|
||||
click(x = 10, y = 10) {
|
||||
handler.fire(TYPES.LEFT_DOWN, { position: { x, y } });
|
||||
handler.fire(TYPES.LEFT_UP, { position: { x, y } });
|
||||
handler.fire(TYPES.LEFT_CLICK, { position: { x, y } });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('every subscriber reads one pick of the click', (t) => {
|
||||
registerPickOwner('test-owner', (id) => id === 'plane-1');
|
||||
t.after(() => unregisterPickOwner('test-owner'));
|
||||
const h = harness({ pick: () => ({ id: 'plane-1' }) });
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
for (let i = 0; i < 5; i++)
|
||||
h.input.onClick((event) => seen.push([event.id, event.ownerId]));
|
||||
h.click();
|
||||
assert.equal(h.calls.pick, 1);
|
||||
assert.deepEqual(seen, Array(5).fill(['plane-1', 'test-owner']));
|
||||
});
|
||||
|
||||
test('a click on nothing is picked once, however its hit is read', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
h.input.onClick((event) => [event.pick, event.hit, event.id, event.ownerId]);
|
||||
h.click();
|
||||
assert.equal(h.calls.pick, 1);
|
||||
});
|
||||
|
||||
test('a click nobody reads is never picked', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
h.input.onClick(() => {});
|
||||
h.click();
|
||||
assert.equal(h.calls.pick, 0);
|
||||
});
|
||||
|
||||
test('the gesture carries summed travel and press time', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
let gesture;
|
||||
h.input.onClick((event) => (gesture = event.gesture));
|
||||
h.handler.fire(TYPES.LEFT_DOWN, { position: { x: 0, y: 0 } });
|
||||
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 4, y: 0 } });
|
||||
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 0, y: 0 } });
|
||||
h.advance(250);
|
||||
h.handler.fire(TYPES.LEFT_UP, { position: { x: 0, y: 0 } });
|
||||
h.handler.fire(TYPES.LEFT_CLICK, { position: { x: 0, y: 0 } });
|
||||
assert.deepEqual(gesture, { travelPx: 8, durationMs: 250 });
|
||||
});
|
||||
|
||||
test('a held pointer goes to its tool, not to ambient selection', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const lease = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
const order = [];
|
||||
h.input.onClick(() => order.push('ambient'));
|
||||
h.input.onPointer(
|
||||
'click',
|
||||
() => {
|
||||
order.push('tool');
|
||||
// Releasing mid-click must not hand THIS click to ambient selection.
|
||||
releasePointer(lease);
|
||||
},
|
||||
{ lease },
|
||||
);
|
||||
h.click();
|
||||
assert.deepEqual(order, ['tool']);
|
||||
h.click();
|
||||
assert.deepEqual(order, ['tool', 'ambient']);
|
||||
});
|
||||
|
||||
test('moves and releases reach ambient subscribers while a tool holds the pointer; presses do not', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const seen = [];
|
||||
h.input.onPointer('move', () => seen.push('move'));
|
||||
h.input.onPointer('down', () => seen.push('down'));
|
||||
h.input.onPointer('up', () => seen.push('up'));
|
||||
const lease = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(lease));
|
||||
h.handler.fire(TYPES.LEFT_DOWN, { position: { x: 0, y: 0 } });
|
||||
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 1, y: 0 } });
|
||||
h.handler.fire(TYPES.LEFT_UP, { position: { x: 1, y: 0 } });
|
||||
assert.deepEqual(seen, ['move', 'up']);
|
||||
});
|
||||
|
||||
test('a stale lease gets nothing once its successor holds the pointer', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const first = claimPointer('test-tool');
|
||||
let staleRan = 0;
|
||||
h.input.onPointer('down', () => (staleRan += 1), { lease: first });
|
||||
releasePointer(first);
|
||||
const second = claimPointer('test-tool');
|
||||
t.after(() => releasePointer(second));
|
||||
h.click();
|
||||
assert.equal(staleRan, 0);
|
||||
});
|
||||
|
||||
test('camera input returns only when the last hold releases', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const controller = h.viewer.scene.screenSpaceCameraController;
|
||||
const drag = h.input.suspendCamera('drag');
|
||||
const flight = h.input.suspendCamera('flight');
|
||||
assert.equal(controller.enableInputs, false);
|
||||
// The flight ends while the drag still holds the camera.
|
||||
flight();
|
||||
assert.equal(controller.enableInputs, false);
|
||||
flight();
|
||||
assert.equal(controller.enableInputs, false, 'a double release is a no-op');
|
||||
drag();
|
||||
assert.equal(controller.enableInputs, true);
|
||||
});
|
||||
|
||||
test('a camera flight that ends does not give input back under a hold', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const controller = h.viewer.scene.screenSpaceCameraController;
|
||||
// Cesium's CameraFlightPath turns input off for the flight and back on
|
||||
// when it completes or is cancelled, whoever else holds the camera.
|
||||
controller.enableInputs = false;
|
||||
const drag = h.input.suspendCamera('drag');
|
||||
controller.enableInputs = true;
|
||||
assert.equal(controller.enableInputs, false, 'the drag still holds it');
|
||||
drag();
|
||||
assert.equal(controller.enableInputs, true);
|
||||
controller.enableInputs = false;
|
||||
assert.equal(controller.enableInputs, false, 'a flight still turns it off');
|
||||
controller.enableInputs = true;
|
||||
});
|
||||
|
||||
test('a controller with its own enableInputs accessor keeps it', () => {
|
||||
const h = harness();
|
||||
h.input.destroy();
|
||||
const controller = h.viewer.scene.screenSpaceCameraController;
|
||||
let stored = true;
|
||||
const get = () => stored;
|
||||
const set = (value) => (stored = value);
|
||||
Object.defineProperty(controller, 'enableInputs', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get,
|
||||
set,
|
||||
});
|
||||
const input = inputFor(h.viewer, {
|
||||
createHandler: () => new FakeHandler(),
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
const hold = input.suspendCamera('drag');
|
||||
assert.equal(controller.enableInputs, false);
|
||||
controller.enableInputs = false;
|
||||
assert.equal(stored, false, 'writes reach the original setter');
|
||||
controller.enableInputs = true;
|
||||
hold();
|
||||
assert.equal(controller.enableInputs, true);
|
||||
input.destroy();
|
||||
const restored = Object.getOwnPropertyDescriptor(controller, 'enableInputs');
|
||||
assert.equal(restored.get, get);
|
||||
assert.equal(restored.set, set);
|
||||
});
|
||||
|
||||
test('a controller whose enableInputs is inherited keeps its class accessor', () => {
|
||||
class Controller {
|
||||
constructor() {
|
||||
this.stored = false;
|
||||
}
|
||||
get enableInputs() {
|
||||
return this.stored;
|
||||
}
|
||||
set enableInputs(value) {
|
||||
this.stored = value;
|
||||
}
|
||||
}
|
||||
const controller = new Controller();
|
||||
const viewer = {
|
||||
scene: { canvas: {}, screenSpaceCameraController: controller },
|
||||
};
|
||||
const input = inputFor(viewer, {
|
||||
createHandler: () => new FakeHandler(),
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
assert.equal(controller.enableInputs, false, 'the inherited getter is read');
|
||||
controller.enableInputs = true;
|
||||
assert.equal(controller.stored, true, 'and the inherited setter written');
|
||||
const hold = input.suspendCamera('drag');
|
||||
assert.equal(controller.enableInputs, false);
|
||||
hold();
|
||||
assert.equal(controller.enableInputs, true);
|
||||
input.destroy();
|
||||
assert.equal(
|
||||
Object.getOwnPropertyDescriptor(controller, 'enableInputs'),
|
||||
undefined,
|
||||
'nothing is left shadowing the class',
|
||||
);
|
||||
});
|
||||
|
||||
test('a controller whose enableInputs cannot be owned still gets a dispatcher', () => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const controller = {};
|
||||
Object.defineProperty(controller, 'enableInputs', {
|
||||
configurable: false,
|
||||
get: () => true,
|
||||
set() {},
|
||||
});
|
||||
const handler = new FakeHandler();
|
||||
const viewer = {
|
||||
scene: { canvas: {}, screenSpaceCameraController: controller },
|
||||
};
|
||||
const input = inputFor(viewer, {
|
||||
createHandler: () => handler,
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
const hold = input.suspendCamera('drag');
|
||||
hold();
|
||||
input.destroy();
|
||||
assert.equal(handler.destroyed, true);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('stock clicks come back by identity after the last hold', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const a = h.input.suppressStockClicks();
|
||||
const b = h.input.suppressStockClicks();
|
||||
assert.equal(h.stock.getInputAction(TYPES.LEFT_CLICK), undefined);
|
||||
a();
|
||||
assert.equal(h.stock.getInputAction(TYPES.LEFT_DOUBLE_CLICK), undefined);
|
||||
b();
|
||||
assert.equal(h.stock.getInputAction(TYPES.LEFT_CLICK), h.stockClick);
|
||||
assert.equal(h.stock.getInputAction(TYPES.LEFT_DOUBLE_CLICK), h.stockDouble);
|
||||
});
|
||||
|
||||
test('drills of different depths on one click share a pass', (t) => {
|
||||
const hits = Array.from({ length: 20 }, (_, i) => ({ id: `hit-${i}` }));
|
||||
const h = harness({ drillPick: (_p, limit) => hits.slice(0, limit) });
|
||||
t.after(() => h.input.destroy());
|
||||
const lengths = [];
|
||||
h.input.onClick((event) => lengths.push(event.drill(12).length));
|
||||
h.input.onClick((event) => lengths.push(event.drill(8).length));
|
||||
h.input.onClick((event) => lengths.push(event.drill(16).length));
|
||||
h.click();
|
||||
assert.deepEqual(lengths, [12, 8, 16]);
|
||||
assert.equal(h.calls.drillPick, 1);
|
||||
});
|
||||
|
||||
test('a touch tap’s contact search is the click’s own drill', (t) => {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');
|
||||
Object.defineProperty(globalThis, 'matchMedia', {
|
||||
configurable: true,
|
||||
value: (query) => ({ matches: query === '(pointer: coarse)' }),
|
||||
});
|
||||
t.after(() => {
|
||||
if (previous) Object.defineProperty(globalThis, 'matchMedia', previous);
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
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' }] });
|
||||
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);
|
||||
});
|
||||
|
||||
test('a short drill answers deeper asks without another pass', (t) => {
|
||||
const h = harness({ drillPick: () => [{ id: 'only' }] });
|
||||
t.after(() => h.input.destroy());
|
||||
h.input.onClick((event) => event.drill(8));
|
||||
h.input.onClick((event) => event.drill(40));
|
||||
h.click();
|
||||
assert.equal(h.calls.drillPick, 1);
|
||||
});
|
||||
|
||||
test('one failing subscriber does not stop the rest', (t) => {
|
||||
const h = harness();
|
||||
t.after(() => h.input.destroy());
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
t.after(() => (console.error = error));
|
||||
let ran = false;
|
||||
h.input.onClick(() => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
h.input.onClick(() => (ran = true));
|
||||
h.click();
|
||||
assert.equal(ran, true);
|
||||
});
|
||||
|
||||
test('destroy releases holds and the handler, and the scene gets a new one', () => {
|
||||
const h = harness();
|
||||
h.input.suspendCamera('drag');
|
||||
h.input.suppressStockClicks();
|
||||
h.input.destroy();
|
||||
assert.equal(h.handler.destroyed, true);
|
||||
const controller = h.viewer.scene.screenSpaceCameraController;
|
||||
assert.equal(controller.enableInputs, true);
|
||||
assert.ok(
|
||||
Object.getOwnPropertyDescriptor(controller, 'enableInputs').writable,
|
||||
'the controller gets its plain flag back',
|
||||
);
|
||||
assert.equal(h.stock.getInputAction(TYPES.LEFT_CLICK), h.stockClick);
|
||||
const next = inputFor(h.viewer, {
|
||||
createHandler: () => new FakeHandler(),
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
assert.notEqual(next, h.input);
|
||||
next.destroy();
|
||||
});
|
||||
|
||||
test('sensor styles move the pick to where the picture came from', () => {
|
||||
const stage = { enabled: true, uniforms: { intensity: 1, pixelation: 4 } };
|
||||
const scene = {
|
||||
canvas: { clientWidth: 400, clientHeight: 200, width: 400, height: 200 },
|
||||
postProcessStages: {
|
||||
getStageByName: (name) =>
|
||||
name === 'godsEyeView_surveillance' ? stage : undefined,
|
||||
},
|
||||
};
|
||||
const click = { x: 300, y: 50 };
|
||||
const mapped = sensorPickPosition(scene, click);
|
||||
assert.notDeepEqual([mapped.x, mapped.y], [300, 50]);
|
||||
assert.deepEqual(click, { x: 300, y: 50 }, 'the click is left alone');
|
||||
stage.enabled = false;
|
||||
const plain = sensorPickPosition(scene, click);
|
||||
assert.deepEqual([plain.x, plain.y], [300, 50]);
|
||||
});
|
||||
|
||||
test('the dispatcher is the package input export', async () => {
|
||||
const exported = await import('gods-eye-view/input');
|
||||
assert.equal(exported.inputFor, inputFor);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @module sensorPick
|
||||
* @description Where a click lands in the pick buffer while a sensor style
|
||||
* distorts the picture. Picks read the scene before post-processing, so under
|
||||
* the thermal or surveillance shader the pixel the user clicked shows a
|
||||
* different spot of the scene: map it back through the shader's barrel
|
||||
* distortion and quantization first.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
const SENSOR_STYLES = ['thermal', 'surveillance'];
|
||||
|
||||
/**
|
||||
* The pick-buffer position for a screen click.
|
||||
* @param {Cesium.Scene} scene
|
||||
* @param {{x: number, y: number}} position CSS pixels on the canvas.
|
||||
* @returns {Cesium.Cartesian2} A new position; the click's own is left alone.
|
||||
*/
|
||||
export function sensorPickPosition(scene, position) {
|
||||
const out = new Cesium.Cartesian2(position.x, position.y);
|
||||
const stages = scene.postProcessStages;
|
||||
if (typeof stages?.getStageByName !== 'function') return out;
|
||||
for (const style of SENSOR_STYLES) {
|
||||
const stage = stages.getStageByName(`godsEyeView_${style}`);
|
||||
if (!stage?.enabled) continue;
|
||||
const intensity = stage.uniforms.intensity;
|
||||
const canvas = scene.canvas,
|
||||
w = canvas.clientWidth,
|
||||
h = canvas.clientHeight;
|
||||
let u = out.x / w,
|
||||
v = 1 - out.y / h;
|
||||
if (style === 'surveillance') {
|
||||
const x = u * 2 - 1,
|
||||
y = v * 2 - 1,
|
||||
r2 = x * x + y * y;
|
||||
const d = 1 + r2 * intensity * 0.25 + r2 * r2 * intensity * 0.075;
|
||||
u = (x * d + 1) / 2;
|
||||
v = (y * d + 1) / 2;
|
||||
}
|
||||
const grid = 1 + (stage.uniforms.pixelation - 1) * intensity;
|
||||
u +=
|
||||
((Math.floor((u * canvas.width) / grid) * grid) / canvas.width - u) *
|
||||
intensity;
|
||||
v +=
|
||||
((Math.floor((v * canvas.height) / grid) * grid) / canvas.height - v) *
|
||||
intensity;
|
||||
out.x = u * w;
|
||||
out.y = (1 - v) * h;
|
||||
return out;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import { inputFor } from './dispatcher.js';
|
||||
|
||||
export const FAKE_EVENT_TYPES = Object.freeze({
|
||||
LEFT_DOWN: 'down',
|
||||
MOUSE_MOVE: 'move',
|
||||
LEFT_UP: 'up',
|
||||
LEFT_CLICK: 'click',
|
||||
LEFT_DOUBLE_CLICK: 'dblclick',
|
||||
});
|
||||
|
||||
export class FakeScreenSpaceEventHandler {
|
||||
constructor() {
|
||||
this.actions = new Map();
|
||||
this.destroyed = false;
|
||||
}
|
||||
setInputAction(fn, type) {
|
||||
this.actions.set(type, fn);
|
||||
}
|
||||
getInputAction(type) {
|
||||
return this.actions.get(type);
|
||||
}
|
||||
removeInputAction(type) {
|
||||
this.actions.delete(type);
|
||||
}
|
||||
fire(type, event) {
|
||||
this.actions.get(type)?.(event);
|
||||
}
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make `viewer`'s dispatcher on a fake handler and return ways to drive it.
|
||||
* @param {object} viewer
|
||||
* @param {{now?: () => number, eventTypes?: object}} [options] `eventTypes`
|
||||
* defaults to {@link FAKE_EVENT_TYPES}; pass Cesium's own when the code under
|
||||
* test reads the viewer's stock actions by Cesium's type values.
|
||||
*/
|
||||
export function fakeInput(viewer, { now, eventTypes = FAKE_EVENT_TYPES } = {}) {
|
||||
const handler = new FakeScreenSpaceEventHandler();
|
||||
const input = inputFor(viewer, {
|
||||
createHandler: () => handler,
|
||||
eventTypes,
|
||||
...(now ? { now } : {}),
|
||||
});
|
||||
const T = eventTypes;
|
||||
return {
|
||||
input,
|
||||
handler,
|
||||
down: (position) => handler.fire(T.LEFT_DOWN, { position }),
|
||||
move: (endPosition, startPosition = endPosition) =>
|
||||
handler.fire(T.MOUSE_MOVE, { startPosition, endPosition }),
|
||||
up: (position) => handler.fire(T.LEFT_UP, { position }),
|
||||
/** A bare LEFT_CLICK, as Cesium raises it after a tap. */
|
||||
click: (position = { x: 10, y: 10 }) =>
|
||||
handler.fire(T.LEFT_CLICK, { position }),
|
||||
/** Down, up and click at one spot. */
|
||||
tap(position = { x: 10, y: 10 }) {
|
||||
handler.fire(T.LEFT_DOWN, { position });
|
||||
handler.fire(T.LEFT_UP, { position });
|
||||
handler.fire(T.LEFT_CLICK, { position });
|
||||
},
|
||||
dblclick: (position = { x: 10, y: 10 }) =>
|
||||
handler.fire(T.LEFT_DOUBLE_CLICK, { position }),
|
||||
destroy: () => input.destroy(),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user