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
+522
-237
File diff suppressed because it is too large.
Load diff
+5
-25
@@ -81,27 +81,11 @@ import {
|
||||
LIVE_CAMERA_COLOR,
|
||||
} from '../layers/cctv/policy.js';
|
||||
import { cctvPicks } from '../layers/cctv/pickState.js';
|
||||
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const ASPECT = 16 / 9;
|
||||
const toRad = (deg) => (deg * Math.PI) / 180;
|
||||
const GESTURE_TYPES = {
|
||||
LEFT_DOWN: 'left-down',
|
||||
MOUSE_MOVE: 'mouse-move',
|
||||
LEFT_UP: 'left-up',
|
||||
LEFT_CLICK: 'left-click',
|
||||
};
|
||||
|
||||
function makeGestureHandler() {
|
||||
const actions = new Map();
|
||||
return {
|
||||
setInputAction(callback, type) {
|
||||
actions.set(type, callback);
|
||||
},
|
||||
fire(type, event) {
|
||||
actions.get(type)?.(event);
|
||||
},
|
||||
};
|
||||
}
|
||||
const GESTURE_TYPES = FAKE_EVENT_TYPES;
|
||||
// Same spherical earth radius projectPoint uses (R = 6371 km) so the
|
||||
// lat/lon→metres conversion in the assertions matches the module's math.
|
||||
const M_PER_DEG = (Math.PI / 180) * 6371000;
|
||||
@@ -987,7 +971,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
|
||||
assert.deepEqual(requests, [{ cameraId: 'atx-cam-3' }]);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/bindCctvWorldClickGesture\(_clickHandler/,
|
||||
/bindCctvWorldClickGesture\(\s*input,/,
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
@@ -1407,14 +1391,14 @@ test('active CCTV camera is absent from host by default and protected only when
|
||||
test('CCTV drag-then-release over a camera is inert, while a clean tap activates and dispatches', () => {
|
||||
let timeMs = 0;
|
||||
let activationCalls = 0;
|
||||
const handler = makeGestureHandler();
|
||||
const { input, handler } = fakeInput({ scene: {} }, { now: () => timeMs });
|
||||
const target = new EventTarget();
|
||||
const requests = [];
|
||||
target.addEventListener(CCTV_FOCUS_REQUEST_EVENT, (event) =>
|
||||
requests.push(event.detail),
|
||||
);
|
||||
bindCctvWorldClickGesture(
|
||||
handler,
|
||||
input,
|
||||
() => {
|
||||
activateCctvCameraFromWorldClick(
|
||||
'atx-cam-3',
|
||||
@@ -1425,10 +1409,6 @@ test('CCTV drag-then-release over a camera is inert, while a clean tap activates
|
||||
target,
|
||||
);
|
||||
},
|
||||
{
|
||||
now: () => timeMs,
|
||||
eventTypes: GESTURE_TYPES,
|
||||
},
|
||||
);
|
||||
|
||||
handler.fire(GESTURE_TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
|
||||
|
||||
+21
-18
@@ -8,7 +8,7 @@
|
||||
* - Pure drag math (this top section): ray↔axis closest-point, ray↔plane
|
||||
* intersection with a grazing-angle guard, ring angles. All unit-tested
|
||||
* under node:test with zero scene dependencies.
|
||||
* - createCalibrationGizmo (below): the entity + ScreenSpaceEventHandler
|
||||
* - createCalibrationGizmo (below): the entity + pointer-input
|
||||
* controller that renders grab-able handles on the ACTIVE camera and turns
|
||||
* drags into calibration patches through a narrow callback interface. It
|
||||
* never touches the layer's records/stores directly.
|
||||
@@ -24,7 +24,7 @@
|
||||
* invariant is untouched.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from './inputOwnership.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
|
||||
// Grazing guard (spec §5): reject plane intersections when the view ray is
|
||||
// nearly parallel to the constraint plane — the hit point races to infinity
|
||||
@@ -237,7 +237,8 @@ export function createCalibrationGizmo({
|
||||
const entities = new Map(); // part -> Entity
|
||||
|
||||
const scene = viewer.scene;
|
||||
const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
|
||||
const input = inputFor(viewer);
|
||||
let releaseCamera = null;
|
||||
|
||||
/** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */
|
||||
function addEntity(part, options) {
|
||||
@@ -533,9 +534,7 @@ export function createCalibrationGizmo({
|
||||
|
||||
drag = state;
|
||||
setCursor('grabbing');
|
||||
if (scene.screenSpaceCameraController) {
|
||||
scene.screenSpaceCameraController.enableInputs = false;
|
||||
}
|
||||
releaseCamera = input.suspendCamera('cctv-gizmo-drag');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -615,9 +614,8 @@ export function createCalibrationGizmo({
|
||||
if (!drag) return;
|
||||
const record = drag.record;
|
||||
drag = null;
|
||||
if (scene.screenSpaceCameraController) {
|
||||
scene.screenSpaceCameraController.enableInputs = true;
|
||||
}
|
||||
releaseCamera?.();
|
||||
releaseCamera = null;
|
||||
setCursor(hoveredId ? 'grab' : '');
|
||||
endPatch(record);
|
||||
}
|
||||
@@ -629,18 +627,21 @@ export function createCalibrationGizmo({
|
||||
}
|
||||
}
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
// A tool owns the pointer (src/data/inputOwnership.js): yield the press.
|
||||
if (!isPointerFree()) return;
|
||||
// An ambient press: the dispatcher withholds it while a tool owns the pointer
|
||||
// (src/data/inputOwnership.js).
|
||||
const offDown = input.onPointer('down', (event) => {
|
||||
if (!enabled) return;
|
||||
// A release Cesium never reported (one with a modifier key held) leaves
|
||||
// the last drag open; a new press ends it, hold and patch included.
|
||||
if (drag) endDrag();
|
||||
const part = pickGizmoPart(event.position);
|
||||
debugLog('LEFT_DOWN', event.position, 'part:', part);
|
||||
if (!part) return;
|
||||
const started = beginDrag(part, event.position);
|
||||
debugLog('beginDrag', part, '→', started);
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
|
||||
});
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
const offMove = input.onPointer('move', (event) => {
|
||||
if (!enabled) return;
|
||||
const now = Date.now();
|
||||
if (drag) {
|
||||
@@ -667,12 +668,12 @@ export function createCalibrationGizmo({
|
||||
if (now - lastHoverAt < HOVER_THROTTLE_MS) return;
|
||||
lastHoverAt = now;
|
||||
setHovered(pickGizmoPart(event.endPosition));
|
||||
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
});
|
||||
|
||||
handler.setInputAction(() => {
|
||||
const offUp = input.onPointer('up', () => {
|
||||
if (!enabled) return;
|
||||
endDrag();
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_UP);
|
||||
});
|
||||
|
||||
return {
|
||||
setEnabled(value) {
|
||||
@@ -688,7 +689,9 @@ export function createCalibrationGizmo({
|
||||
refresh,
|
||||
destroy() {
|
||||
if (drag) endDrag();
|
||||
handler.destroy();
|
||||
offDown();
|
||||
offMove();
|
||||
offUp();
|
||||
for (const entity of entities.values()) {
|
||||
viewer.entities.remove(entity);
|
||||
}
|
||||
|
||||
+140
-15
@@ -8,53 +8,87 @@
|
||||
// - rayPlaneIntersect refuses grazing rays (|dir·normal| < 0.08 — spec §5
|
||||
// precision guard) and behind-origin hits;
|
||||
// - ringAngle/signedAngleDelta give quadrant-correct, wrap-safe angles for
|
||||
// the heading/pitch ring drags.
|
||||
// the heading/pitch ring drags;
|
||||
// - the controller ends an open drag, and its camera hold, on the next press.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
GIZMO_ID_PREFIX,
|
||||
closestParamOnAxis,
|
||||
createCalibrationGizmo,
|
||||
rayPlaneIntersect,
|
||||
ringAngle,
|
||||
signedAngleDelta,
|
||||
} from './cctvGizmo.js';
|
||||
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z);
|
||||
|
||||
test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => {
|
||||
// Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5):
|
||||
// nearest axis point is x=10 → t=10.
|
||||
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(0, 0, 0), c3(1, 0, 0));
|
||||
const t = closestParamOnAxis(
|
||||
c3(10, 0, 5),
|
||||
c3(0, 0, -1),
|
||||
c3(0, 0, 0),
|
||||
c3(1, 0, 0),
|
||||
);
|
||||
assert.ok(Math.abs(t - 10) < 1e-9, `expected 10, got ${t}`);
|
||||
});
|
||||
|
||||
test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => {
|
||||
// Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the
|
||||
// axis around x=10 (it reaches y=0 at x=10).
|
||||
const dir = Cesium.Cartesian3.normalize(c3(1, -1, 0), new Cesium.Cartesian3());
|
||||
const dir = Cesium.Cartesian3.normalize(
|
||||
c3(1, -1, 0),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0));
|
||||
assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`);
|
||||
});
|
||||
|
||||
test('closestParamOnAxis: axis origin offset shifts the parameter', () => {
|
||||
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(4, 0, 0), c3(1, 0, 0));
|
||||
const t = closestParamOnAxis(
|
||||
c3(10, 0, 5),
|
||||
c3(0, 0, -1),
|
||||
c3(4, 0, 0),
|
||||
c3(1, 0, 0),
|
||||
);
|
||||
assert.ok(Math.abs(t - 6) < 1e-9, `expected 6, got ${t}`);
|
||||
});
|
||||
|
||||
test('closestParamOnAxis: near-parallel ray/axis returns null', () => {
|
||||
assert.equal(closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), null);
|
||||
const nearly = Cesium.Cartesian3.normalize(c3(1, 1e-9, 0), new Cesium.Cartesian3());
|
||||
assert.equal(closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), null);
|
||||
assert.equal(
|
||||
closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)),
|
||||
null,
|
||||
);
|
||||
const nearly = Cesium.Cartesian3.normalize(
|
||||
c3(1, 1e-9, 0),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
assert.equal(
|
||||
closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('rayPlaneIntersect: straight-on hit lands at the expected point', () => {
|
||||
const hit = rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, -1), c3(0, 0, 0), c3(0, 0, 1));
|
||||
const hit = rayPlaneIntersect(
|
||||
c3(0, 0, 10),
|
||||
c3(0, 0, -1),
|
||||
c3(0, 0, 0),
|
||||
c3(0, 0, 1),
|
||||
);
|
||||
assert.ok(hit, 'expected a hit');
|
||||
assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9);
|
||||
});
|
||||
|
||||
test('rayPlaneIntersect: oblique hit resolves correctly', () => {
|
||||
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -1), new Cesium.Cartesian3());
|
||||
const dir = Cesium.Cartesian3.normalize(
|
||||
c3(1, 0, -1),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1));
|
||||
assert.ok(hit);
|
||||
assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`);
|
||||
@@ -62,12 +96,21 @@ test('rayPlaneIntersect: oblique hit resolves correctly', () => {
|
||||
|
||||
test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => {
|
||||
// dir almost in-plane: z component 0.05 < 0.08 threshold.
|
||||
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -0.05), new Cesium.Cartesian3());
|
||||
assert.equal(rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), null);
|
||||
const dir = Cesium.Cartesian3.normalize(
|
||||
c3(1, 0, -0.05),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
assert.equal(
|
||||
rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('rayPlaneIntersect: plane behind the ray origin returns null', () => {
|
||||
assert.equal(rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)), null);
|
||||
assert.equal(
|
||||
rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
|
||||
@@ -75,9 +118,15 @@ test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
|
||||
const a = c3(1, 0, 0);
|
||||
const b = c3(0, 1, 0);
|
||||
assert.ok(Math.abs(ringAngle(c3(5, 0, 0), center, a, b) - 0) < 1e-9);
|
||||
assert.ok(Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9);
|
||||
assert.ok(Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9);
|
||||
assert.ok(Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9);
|
||||
assert.ok(
|
||||
Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9,
|
||||
);
|
||||
});
|
||||
|
||||
test('signedAngleDelta: shortest-path wrap', () => {
|
||||
@@ -86,3 +135,79 @@ test('signedAngleDelta: shortest-path wrap', () => {
|
||||
assert.ok(Math.abs(signedAngleDelta(d2r(-170), d2r(170)) - d2r(-20)) < 1e-9);
|
||||
assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9);
|
||||
});
|
||||
|
||||
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
|
||||
const viewer = {
|
||||
entities: {
|
||||
byId: new Map(),
|
||||
getById(id) {
|
||||
return this.byId.get(id);
|
||||
},
|
||||
add(options) {
|
||||
this.byId.set(options.id, options);
|
||||
return options;
|
||||
},
|
||||
remove(entity) {
|
||||
this.byId.delete(entity.id);
|
||||
},
|
||||
},
|
||||
scene: {
|
||||
canvas: { style: {} },
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
pick: () => ({ id: { id: `${GIZMO_ID_PREFIX}move-up` } }),
|
||||
drillPick: () => [],
|
||||
},
|
||||
};
|
||||
const mount = Cesium.Cartesian3.fromDegrees(0, 0, 10);
|
||||
const east = new Cesium.Cartesian3(0, 1, 0); // east at lon 0, lat 0
|
||||
viewer.camera = {
|
||||
getPickRay: () => ({
|
||||
origin: Cesium.Cartesian3.add(
|
||||
mount,
|
||||
Cesium.Cartesian3.multiplyByScalar(east, 100, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
direction: Cesium.Cartesian3.negate(east, new Cesium.Cartesian3()),
|
||||
}),
|
||||
};
|
||||
const { input, handler } = fakeInput(viewer);
|
||||
t.after(() => input.destroy());
|
||||
const record = {
|
||||
frustumPositions: {
|
||||
mount,
|
||||
capCenter: mount,
|
||||
tl: mount,
|
||||
tr: mount,
|
||||
bl: mount,
|
||||
br: mount,
|
||||
},
|
||||
frustumGeometry: { rangeM: 50 },
|
||||
camera: {
|
||||
headingDeg: 0,
|
||||
pitchDeg: 0,
|
||||
rangeM: 50,
|
||||
calibration: {},
|
||||
basePose: {},
|
||||
},
|
||||
};
|
||||
const ended = [];
|
||||
const gizmo = createCalibrationGizmo({
|
||||
viewer,
|
||||
getActiveRecord: () => record,
|
||||
applyPatch() {},
|
||||
endPatch: (r) => ended.push(r),
|
||||
});
|
||||
t.after(() => gizmo.destroy());
|
||||
gizmo.setEnabled(true);
|
||||
const controller = viewer.scene.screenSpaceCameraController;
|
||||
|
||||
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
|
||||
assert.equal(gizmo.isDragging(), true);
|
||||
assert.equal(controller.enableInputs, false);
|
||||
// The release came with a modifier key held: Cesium raised no LEFT_UP.
|
||||
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
|
||||
assert.deepEqual(ended, [record], 'the open drag was committed');
|
||||
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
|
||||
assert.equal(gizmo.isDragging(), false);
|
||||
assert.equal(controller.enableInputs, true, 'no hold was stranded');
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js';
|
||||
import { getLocale, setLocale } from '../i18n/index.js';
|
||||
import { reportMeshFloorCell, setMeshFloorPreferred } from './groundFloor.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const NOW = Date.UTC(2026, 6, 17, 4, 0);
|
||||
const H = 3600000;
|
||||
@@ -216,6 +217,7 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async ()
|
||||
primitives: { contains() { return false; } },
|
||||
},
|
||||
};
|
||||
fakeInput(viewer);
|
||||
const layer = createFirmsHeatmapLayer({
|
||||
id: 'firms',
|
||||
name: 'FIRMS',
|
||||
@@ -224,7 +226,6 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async ()
|
||||
setVisible: (...args) => calls.push(['visible', ...args]),
|
||||
clearSource: (...args) => calls.push(['clear', ...args]),
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
|
||||
});
|
||||
try {
|
||||
layer.init(viewer);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { unregisterSpriteCollection } from './spriteOrder.js';
|
||||
import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldOverlay.js';
|
||||
import { createIconSet, ICON_CULL_LIFT } from './iconSet.js';
|
||||
import { writeHoldSegment } from './iconSegment.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const AUSTIN = { lon: -97.7, lat: 30.2 };
|
||||
/** Antipode of Austin — as far behind the limb as a point on Earth can be. */
|
||||
@@ -378,6 +379,7 @@ function createHarness(rawFires) {
|
||||
mapProjection: new Cesium.GeographicProjection(),
|
||||
},
|
||||
};
|
||||
fakeInput(viewer);
|
||||
|
||||
const layer = createFirmsHeatmapLayer({
|
||||
id: 'firms',
|
||||
@@ -387,7 +389,6 @@ function createHarness(rawFires) {
|
||||
setVisible: () => {},
|
||||
clearSource: () => {},
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
|
||||
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
const LAYER_SOURCE = readLayerSource(
|
||||
path.join(path.dirname(fileURLToPath(import.meta.url)), 'firmsHeatmap.js'),
|
||||
@@ -59,7 +60,6 @@ function harness({
|
||||
};
|
||||
|
||||
const published = [];
|
||||
let handler = null;
|
||||
const layer = createFirmsHeatmapLayer({
|
||||
...(feed ? { feed } : {}),
|
||||
id: 'firms-test',
|
||||
@@ -70,10 +70,6 @@ function harness({
|
||||
clearSource() {},
|
||||
hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null),
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => {
|
||||
handler = { click: null, setInputAction(cb) { this.click = cb; }, destroy() {} };
|
||||
return handler;
|
||||
},
|
||||
});
|
||||
|
||||
const viewer = {
|
||||
@@ -85,6 +81,7 @@ function harness({
|
||||
},
|
||||
dataSources: { add() {}, remove() {} },
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
// The LOD rebuild (and with it the context-registration sweep) is inert
|
||||
// without a data source, so tests that drive a real refresh need one.
|
||||
if (withDataSource) layer.init(viewer);
|
||||
@@ -100,7 +97,7 @@ function harness({
|
||||
requests,
|
||||
published,
|
||||
fires,
|
||||
click: () => handler.click({ position: { x: 400, y: 300 } }),
|
||||
click: () => input.click({ x: 400, y: 300 }),
|
||||
cleanup() {
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection;
|
||||
if (hadWindow) globalThis.window = priorWindow;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
|
||||
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
|
||||
function services() {
|
||||
const records = new Map();
|
||||
@@ -119,7 +120,6 @@ test('two viewers use their supplied contexts and dispose independently', async
|
||||
const hosts = [services(), services()];
|
||||
const instances = hosts.map((host) => {
|
||||
const sources = new Cesium.DataSourceCollection();
|
||||
let click;
|
||||
const layer = createLocalGeoJsonLayer(
|
||||
{
|
||||
id: 'local-dams',
|
||||
@@ -127,12 +127,6 @@ test('two viewers use their supplied contexts and dispose independently', async
|
||||
osmDerived: true,
|
||||
color: '#0088ff',
|
||||
url: '/dams.geojsonl',
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction(fn) {
|
||||
click = fn;
|
||||
},
|
||||
destroy() {},
|
||||
}),
|
||||
},
|
||||
host,
|
||||
);
|
||||
@@ -147,7 +141,8 @@ test('two viewers use their supplied contexts and dispose independently', async
|
||||
},
|
||||
camera: { moveEnd: new Cesium.Event(), flyTo() {} },
|
||||
};
|
||||
return { layer, viewer, click: () => click({ position: {} }) };
|
||||
const input = fakeInput(viewer);
|
||||
return { layer, viewer, click: () => input.click({ x: 0, y: 0 }) };
|
||||
});
|
||||
t.after(() =>
|
||||
instances.forEach(({ layer, viewer }) => layer.destroy(viewer)),
|
||||
@@ -191,11 +186,16 @@ test('consumer build includes only infrastructure code and resolves assets under
|
||||
const entry = output.find((item) => item.type === 'chunk' && item.isEntry);
|
||||
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
|
||||
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
|
||||
'dispatcher.js',
|
||||
'infrastructure.js',
|
||||
'infrastructureData.js',
|
||||
'infrastructureOverlayEntry.js',
|
||||
'inputOwnership.js',
|
||||
'localGeojsonCore.js',
|
||||
'localGeojsonLod.js',
|
||||
'pickRegistry.js',
|
||||
'scenePick.js',
|
||||
'sensorPick.js',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
entry.imports,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Who owns the pointer over the globe.
|
||||
*
|
||||
* Most layers bind their own `ScreenSpaceEventHandler` to the same canvas and
|
||||
* Most layers read the same globe clicks (src/input/dispatcher.js) and
|
||||
* select whatever is under a left click. That is right when nothing else is
|
||||
* going on, and wrong the moment a tool needs the pointer for itself: a draw
|
||||
* session placing a vertex on top of an aircraft must not also track the
|
||||
@@ -15,8 +15,8 @@
|
||||
* `releasePointer(lease)` when it turns off. It does not consult anyone;
|
||||
* holding the claim is what makes it the owner.
|
||||
* - An AMBIENT SELECTION HANDLER — anything that picks an entity because the
|
||||
* user clicked — early-returns while `isPointerFree()` is false. It never
|
||||
* claims.
|
||||
* user clicked — is not called while `isPointerFree()` is false: the input
|
||||
* dispatcher skips it. It never claims.
|
||||
*
|
||||
* Claims do not stack and are never stolen: while one owner holds the pointer,
|
||||
* a second `claimPointer` returns null rather than displacing it — and so does
|
||||
|
||||
@@ -109,62 +109,49 @@ test('reset reports who was holding it, for teardown', () => {
|
||||
assert.equal(isLeaseCurrent(lease), false);
|
||||
});
|
||||
|
||||
test('every scene click handler consults ownership before it picks', () => {
|
||||
// This is the whole point of a shared contract: a new tool must not have to
|
||||
// find and edit each of these. If a layer grows a click handler it has to
|
||||
// appear here too.
|
||||
const guarded = [
|
||||
['src/data/trackingClickGesture.js', 'onClick(click, gesture);'],
|
||||
['src/data/localGeojsonCore.js', 'viewer.scene.pick(click.position)'],
|
||||
['src/data/cctvGizmo.js', 'pickGizmoPart(event.position)'],
|
||||
['src/layers/alpr/presentation.js', 'viewer.scene.pick(click.position)'],
|
||||
['src/layers/bikeshare/selection.js', 'viewer.scene.pick(click.position)'],
|
||||
['src/layers/firms/selection.js', 'scene.pick(click.position)'],
|
||||
test('pointer input, camera holds and the stock clicks go through the one dispatcher', () => {
|
||||
// The dispatcher (src/input/dispatcher.js) applies the pointer claim once
|
||||
// per event for every subscriber, so a new tool does not have to find and
|
||||
// edit each layer. A layer that binds its own handler, writes the camera
|
||||
// flag or takes the stock clicks itself steps around that contract.
|
||||
const DISPATCHER = 'src/input/dispatcher.js';
|
||||
const rules = [
|
||||
[
|
||||
'src/layers/installations/selection.js',
|
||||
'viewer.scene.pick(click.position)',
|
||||
],
|
||||
['src/layers/launches/lifecycle.js', 'drillPick(movement.position'],
|
||||
['src/layers/radio/interaction.js', 'pickedRadioStationAt(click.position)'],
|
||||
[
|
||||
'src/layers/satellites/interaction.js',
|
||||
'viewer.scene.pick(click.position)',
|
||||
/new\s+[\w.]*ScreenSpaceEventHandler\(/,
|
||||
'binds its own ScreenSpaceEventHandler',
|
||||
],
|
||||
[
|
||||
'src/layers/submarineCables/interaction.js',
|
||||
'viewer.scene.pick(click.position)',
|
||||
/\.enableInputs\s*=(?!=)/,
|
||||
'writes enableInputs instead of suspendCamera()',
|
||||
],
|
||||
[
|
||||
'src/layers/vessels/selection.js',
|
||||
'pickContact(viewer.scene, click.position)',
|
||||
/screenSpaceEventHandler\??\.removeInputAction\(/,
|
||||
'removes stock clicks instead of suppressStockClicks()',
|
||||
],
|
||||
];
|
||||
for (const [file, firstPick] of guarded) {
|
||||
const walk = (dir) =>
|
||||
fs
|
||||
.readdirSync(path.join(ROOT, dir), { withFileTypes: true })
|
||||
.flatMap((entry) => {
|
||||
const rel = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return walk(rel);
|
||||
return entry.name.endsWith('.js') ? [rel] : [];
|
||||
});
|
||||
const offenders = [];
|
||||
for (const file of walk('src')) {
|
||||
if (file === DISPATCHER) continue;
|
||||
const source = read(file);
|
||||
assert.match(
|
||||
source,
|
||||
/import \{ isPointerFree \} from '[^']*inputOwnership\.js';/,
|
||||
`${file} must consult the shared pointer claim`,
|
||||
);
|
||||
const guardAt = source.indexOf('if (!isPointerFree()) return;');
|
||||
const pickAt = source.indexOf(firstPick);
|
||||
assert.ok(guardAt >= 0, `${file} is missing the guard`);
|
||||
assert.ok(
|
||||
pickAt >= 0,
|
||||
`${file}: could not find its pick call (${firstPick})`,
|
||||
);
|
||||
assert.ok(
|
||||
guardAt < pickAt,
|
||||
`${file} must yield before it picks, not after`,
|
||||
);
|
||||
for (const [pattern, what] of rules)
|
||||
if (pattern.test(source)) offenders.push(`${file} ${what}`);
|
||||
}
|
||||
assert.deepEqual(offenders, []);
|
||||
});
|
||||
|
||||
test('ambient selection handlers never claim the pointer themselves', () => {
|
||||
// Claiming from a selection handler would deadlock every other layer the
|
||||
// moment a user clicked anything. Only tools claim.
|
||||
for (const file of [
|
||||
'src/data/trackingClickGesture.js',
|
||||
'src/input/dispatcher.js',
|
||||
'src/data/localGeojsonCore.js',
|
||||
'src/data/cctvGizmo.js',
|
||||
'src/layers/vessels/selection.js',
|
||||
|
||||
@@ -186,9 +186,9 @@ test('infra getAnalystRecords: enabled layer snapshots loaded stems; disable ret
|
||||
color: '#0088ff',
|
||||
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
|
||||
projectToWindow: () => ({ x: 400, y: 300 }),
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction() {},
|
||||
destroy() {},
|
||||
inputFor: () => ({
|
||||
onClick: () => () => {},
|
||||
suspendCamera: () => () => {},
|
||||
}),
|
||||
});
|
||||
try {
|
||||
|
||||
@@ -133,10 +133,7 @@ async function createRealLocalLayerHarness({
|
||||
color: '#0088ff',
|
||||
overlayHost,
|
||||
projectToWindow: () => ({ x: 400, y: 300 }),
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction() {},
|
||||
destroy() {},
|
||||
}),
|
||||
inputFor: () => ({ onClick: () => () => {}, suspendCamera: () => () => {} }),
|
||||
});
|
||||
try {
|
||||
await layer.enable(viewer);
|
||||
@@ -533,7 +530,7 @@ async function enableLayerWithFetch(fetchImpl, { dataSources, windowStub } = {})
|
||||
name: 'Dams',
|
||||
color: '#0088ff',
|
||||
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
|
||||
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
|
||||
inputFor: () => ({ onClick: () => () => {}, suspendCamera: () => () => {} }),
|
||||
});
|
||||
const enable = async () => {
|
||||
globalThis.fetch = fetchImpl;
|
||||
@@ -1182,7 +1179,7 @@ async function createMultiFeatureLodHarness({ featureCount = 150, cameraHeightM
|
||||
color: '#00ffff',
|
||||
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
|
||||
projectToWindow: () => ({ x: 700, y: 450 }),
|
||||
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
|
||||
inputFor: () => ({ onClick: () => () => {}, suspendCamera: () => () => {} }),
|
||||
});
|
||||
try {
|
||||
await layer.enable(viewer);
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
parseGeojsonLines,
|
||||
} from '../sources/infrastructureData.js';
|
||||
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
|
||||
import { isPointerFree } from './inputOwnership.js';
|
||||
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
|
||||
import {
|
||||
selectInfraLod,
|
||||
applyInfraEvictionGrace,
|
||||
@@ -310,8 +310,7 @@ export function createLocalGeoJsonLayer(
|
||||
labels = true,
|
||||
labelMax = DEFAULT_LABEL_MAX,
|
||||
labelGridPx = DEFAULT_LABEL_GRID_PX,
|
||||
screenSpaceEventHandlerFactory = (canvas) =>
|
||||
new Cesium.ScreenSpaceEventHandler(canvas),
|
||||
inputFor = defaultInputFor,
|
||||
projectToWindow = (scene, position) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position),
|
||||
},
|
||||
@@ -330,7 +329,7 @@ export function createLocalGeoJsonLayer(
|
||||
// The entities this layer loaded, so its click and teardown recognise them.
|
||||
const _ownEntities = new WeakSet();
|
||||
let _enabled = false;
|
||||
let _clickHandler = null;
|
||||
let _clickSubscription = null;
|
||||
let _count = 0;
|
||||
/** @type {number|null} Timestamp of the last successful dataset load. */
|
||||
let _lastUpdate = null;
|
||||
@@ -784,15 +783,11 @@ export function createLocalGeoJsonLayer(
|
||||
|
||||
if (_destroyed) return;
|
||||
// 2. Install native global click handler
|
||||
if (!_clickHandler) {
|
||||
_clickHandler = screenSpaceEventHandlerFactory(
|
||||
viewer.scene.canvas,
|
||||
);
|
||||
_clickHandler.setInputAction((click) => {
|
||||
// A tool owns the pointer (src/data/inputOwnership.js).
|
||||
if (!isPointerFree()) return;
|
||||
if (!_clickSubscription) {
|
||||
const input = inputFor(viewer);
|
||||
_clickSubscription = input.onClick((event) => {
|
||||
if (!_enabled) return;
|
||||
const picked = viewer.scene.pick(click.position);
|
||||
const picked = event.pick;
|
||||
|
||||
if (picked && _ownEntities.has(picked.id)) {
|
||||
const entity = picked.id;
|
||||
@@ -825,8 +820,12 @@ export function createLocalGeoJsonLayer(
|
||||
if (targetPos) {
|
||||
const carto = Cesium.Cartographic.fromCartesian(targetPos);
|
||||
|
||||
// Disable interactions so Cesium doesn't magically cancel the flight
|
||||
viewer.scene.screenSpaceCameraController.enableInputs = false;
|
||||
// Hold camera input so Cesium doesn't cancel the flight.
|
||||
// A hold, not a flag: the flight ending must not hand input
|
||||
// back under a drag or the cockpit.
|
||||
const releaseCamera = input.suspendCamera(
|
||||
'local-geojson-flight',
|
||||
);
|
||||
|
||||
viewer.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromRadians(
|
||||
@@ -835,16 +834,12 @@ export function createLocalGeoJsonLayer(
|
||||
5000,
|
||||
),
|
||||
duration: 1.5,
|
||||
complete: () => {
|
||||
viewer.scene.screenSpaceCameraController.enableInputs = true;
|
||||
},
|
||||
cancel: () => {
|
||||
viewer.scene.screenSpaceCameraController.enableInputs = true;
|
||||
},
|
||||
complete: releaseCamera,
|
||||
cancel: releaseCamera,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
});
|
||||
}
|
||||
})();
|
||||
try {
|
||||
@@ -1074,10 +1069,8 @@ export function createLocalGeoJsonLayer(
|
||||
// torn down even if destroy is called while the layer is enabled.
|
||||
disableLayer(viewer);
|
||||
removeEntityContextsForLayer(id);
|
||||
if (_clickHandler) {
|
||||
_clickHandler.destroy();
|
||||
_clickHandler = null;
|
||||
}
|
||||
_clickSubscription?.();
|
||||
_clickSubscription = null;
|
||||
if (_dataSource && viewer) {
|
||||
viewer.dataSources.remove(_dataSource, true);
|
||||
}
|
||||
|
||||
@@ -46,10 +46,13 @@ function harness(t) {
|
||||
const create = () => createLocalGeoJsonLayer({
|
||||
id: 'local-dams', name: 'Dams', color: '#0088ff', url: '/dams.geojsonl',
|
||||
overlayHost: { setVisible() {}, setEntries() {}, clearSource() {} },
|
||||
screenSpaceEventHandlerFactory() {
|
||||
handlers++;
|
||||
return { setInputAction() {}, destroy() { handlers--; } };
|
||||
},
|
||||
inputFor: () => ({
|
||||
onClick() {
|
||||
handlers++;
|
||||
return () => { handlers--; };
|
||||
},
|
||||
suspendCamera: () => () => {},
|
||||
}),
|
||||
});
|
||||
const layer = create();
|
||||
return { layer, create, viewer, sources, listeners, handlers: () => handlers };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Shared pick-ownership registry for layers that install their own
|
||||
* ScreenSpaceEventHandler click handlers.
|
||||
* Shared pick-ownership registry for the layers that read globe clicks
|
||||
* (src/input/dispatcher.js).
|
||||
*
|
||||
* Problem solved: each entity layer (commercial flights, military flights)
|
||||
* receives every LEFT_CLICK. When the user clicks a military aircraft while
|
||||
@@ -109,10 +109,14 @@ export function isOwnedByOtherLayer(layerId, pickedId) {
|
||||
*
|
||||
* @param {object} scene Cesium scene with pick and optional drillPick.
|
||||
* @param {{x: number, y: number}} position Screen position in CSS pixels.
|
||||
* @param {{picked?: object|null, drill?: (limit: number, width: number, height: number) => object[]}} [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.
|
||||
*/
|
||||
export function pickContact(scene, position) {
|
||||
const picked = scene.pick(position);
|
||||
export function pickContact(scene, position, options = {}) {
|
||||
const picked = 'picked' in options ? options.picked : scene.pick(position);
|
||||
if (
|
||||
!globalThis.matchMedia?.('(pointer: coarse)').matches ||
|
||||
findPickOwner(resolvePickId(picked)) ||
|
||||
@@ -122,7 +126,10 @@ export function pickContact(scene, position) {
|
||||
return picked;
|
||||
let hits;
|
||||
try {
|
||||
hits = scene.drillPick(position, 8, 14, 14) || [];
|
||||
hits =
|
||||
(options.drill
|
||||
? options.drill(8, 14, 14)
|
||||
: scene.drillPick(position, 8, 14, 14)) || [];
|
||||
} catch {
|
||||
return picked;
|
||||
}
|
||||
|
||||
@@ -849,10 +849,7 @@ function createDeferredCableLayerHarness() {
|
||||
setEntries: (...args) => hostCalls.push(['entries', ...args]),
|
||||
clearSource: (...args) => hostCalls.push(['clear', ...args]),
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction() {},
|
||||
destroy() {},
|
||||
}),
|
||||
inputFor: () => ({ onClick: () => () => {} }),
|
||||
});
|
||||
const viewer = makeStubViewer(listeners, dataSources, addCalls, addControl);
|
||||
layer.init(viewer);
|
||||
@@ -1306,10 +1303,7 @@ async function createRealCableLayerHarness({
|
||||
setEntries: (...args) => hostCalls.push(['entries', ...args]),
|
||||
clearSource: (...args) => hostCalls.push(['clear', ...args]),
|
||||
},
|
||||
screenSpaceEventHandlerFactory: () => ({
|
||||
setInputAction() {},
|
||||
destroy() {},
|
||||
}),
|
||||
inputFor: () => ({ onClick: () => () => {} }),
|
||||
...(source ? { source } : {}),
|
||||
mapStackEventTarget,
|
||||
sweepClock: () => clockMs,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from './inputOwnership.js';
|
||||
|
||||
/**
|
||||
* Click-gesture classifiers for the tracking layers. The gesture itself
|
||||
* (summed travel and press time) is measured by the input dispatcher and
|
||||
* arrives on every click as `event.gesture` (src/input/dispatcher.js).
|
||||
*/
|
||||
export const MAX_TRACKING_CLICK_TRAVEL_PX = 6;
|
||||
export const MAX_TRACKING_CLICK_DURATION_MS = 400;
|
||||
|
||||
@@ -33,79 +35,3 @@ export function isTrackingClickGesture(gesture = {}) {
|
||||
durationMs <= MAX_TRACKING_CLICK_DURATION_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind LEFT_DOWN/MOUSE_MOVE/LEFT_UP accounting ahead of a scene click.
|
||||
* Travel is accumulated segment-by-segment, so an orbit nudge that returns to
|
||||
* its starting pixel cannot masquerade as a zero-distance click. Every scene
|
||||
* click reaches `onClick` with its gesture metadata; the caller decides whether
|
||||
* selection (travel-only) or deselection (travel + duration) is allowed.
|
||||
* @param {Cesium.ScreenSpaceEventHandler|Object} handler - Input handler.
|
||||
* @param {(click: Object, gesture: {travelPx: number, durationMs: number}) => void} onClick - Scene-click callback.
|
||||
* @param {{now?: () => number, eventTypes?: Object, onMouseMove?: (event: Object) => void}} [options] - Test/interop seams.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function bindTrackingClickGesture(handler, onClick, options = {}) {
|
||||
const now = options.now || (() => performance.now());
|
||||
const eventTypes = options.eventTypes || Cesium.ScreenSpaceEventType;
|
||||
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;
|
||||
};
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
pressActive = true;
|
||||
pressStartedAt = now();
|
||||
previousPosition = null;
|
||||
travelPx = 0;
|
||||
completedGesture = null;
|
||||
appendTravel(event?.position);
|
||||
}, eventTypes.LEFT_DOWN);
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
appendTravel(event?.endPosition ?? event?.position);
|
||||
options.onMouseMove?.(event);
|
||||
}, eventTypes.MOUSE_MOVE);
|
||||
|
||||
handler.setInputAction((event) => {
|
||||
finishPress(event?.position);
|
||||
}, eventTypes.LEFT_UP);
|
||||
|
||||
handler.setInputAction((click) => {
|
||||
if (pressActive) finishPress(click?.position);
|
||||
const gesture = completedGesture || { travelPx: 0, durationMs: 0 };
|
||||
completedGesture = null;
|
||||
// A tool owns the pointer: a draw vertex placed over an aircraft is a
|
||||
// vertex, not a track request (src/data/inputOwnership.js).
|
||||
if (!isPointerFree()) return;
|
||||
onClick(click, gesture);
|
||||
}, eventTypes.LEFT_CLICK);
|
||||
}
|
||||
@@ -2,26 +2,18 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
bindTrackingClickGesture,
|
||||
isTrackingClickGesture,
|
||||
isTrackingSelectionGesture,
|
||||
} from './trackingClickGesture.js';
|
||||
import { FAKE_EVENT_TYPES as TYPES, fakeInput } from '../input/testDoubles.mjs';
|
||||
import { TRACKED_MODEL_MAX_PX as CIVIL_TRACKED_MODEL_MAX_PX } from './flights.js';
|
||||
import { TRACKED_MODEL_MAX_PX as MILITARY_TRACKED_MODEL_MAX_PX } from './militaryFlights.js';
|
||||
|
||||
const TYPES = {
|
||||
LEFT_DOWN: 'left-down',
|
||||
MOUSE_MOVE: 'mouse-move',
|
||||
LEFT_UP: 'left-up',
|
||||
LEFT_CLICK: 'left-click',
|
||||
};
|
||||
|
||||
function makeHandler() {
|
||||
const actions = new Map();
|
||||
return {
|
||||
setInputAction(callback, type) { actions.set(type, callback); },
|
||||
fire(type, event) { actions.get(type)?.(event); },
|
||||
};
|
||||
/** A dispatcher on a fake handler, with `onClick(click, gesture)` as the layers read it. */
|
||||
function gestureInput(now, onClick) {
|
||||
const { input, handler } = fakeInput({ scene: {} }, { now });
|
||||
input.onClick((event) => onClick(event.screenPosition, event.gesture));
|
||||
return { input, handler };
|
||||
}
|
||||
|
||||
test('tracking click discrimination pins the travel/duration boundary matrix', () => {
|
||||
@@ -43,12 +35,8 @@ test('tracking click discrimination pins the travel/duration boundary matrix', (
|
||||
test('synthetic drag-then-click sequence does not reach the untrack callback', () => {
|
||||
let timeMs = 0;
|
||||
let untrackCalls = 0;
|
||||
const handler = makeHandler();
|
||||
bindTrackingClickGesture(handler, (_click, gesture) => {
|
||||
const { input, handler } = gestureInput(() => timeMs, (_click, gesture) => {
|
||||
if (isTrackingClickGesture(gesture)) untrackCalls += 1;
|
||||
}, {
|
||||
now: () => timeMs,
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
|
||||
handler.fire(TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
|
||||
@@ -64,29 +52,27 @@ test('synthetic drag-then-click sequence does not reach the untrack callback', (
|
||||
|
||||
handler.fire(TYPES.LEFT_CLICK, { position: { x: 10, y: 10 } });
|
||||
assert.equal(untrackCalls, 1, 'suppression is consumed and cannot poison the next click');
|
||||
input.destroy();
|
||||
});
|
||||
|
||||
test('slow clean sprite clicks select, while long presses and orbit nudges cannot untrack', () => {
|
||||
let timeMs = 0;
|
||||
let selections = 0;
|
||||
let untracks = 0;
|
||||
const handler = makeHandler();
|
||||
bindTrackingClickGesture(handler, (click, gesture) => {
|
||||
// A click at x 0 lands on a sprite; anywhere else is empty space.
|
||||
const { input, handler } = gestureInput(() => timeMs, (click, gesture) => {
|
||||
if (!isTrackingSelectionGesture(gesture)) return;
|
||||
if (click.sprite) {
|
||||
if (click.x === 0 && click.y === 0) {
|
||||
selections += 1;
|
||||
return;
|
||||
}
|
||||
if (isTrackingClickGesture(gesture)) untracks += 1;
|
||||
}, {
|
||||
now: () => timeMs,
|
||||
eventTypes: TYPES,
|
||||
});
|
||||
|
||||
handler.fire(TYPES.LEFT_DOWN, { position: { x: 0, y: 0 } });
|
||||
timeMs = 401;
|
||||
handler.fire(TYPES.LEFT_UP, { position: { x: 0, y: 0 } });
|
||||
handler.fire(TYPES.LEFT_CLICK, { position: { x: 0, y: 0 }, sprite: true });
|
||||
handler.fire(TYPES.LEFT_CLICK, { position: { x: 0, y: 0 } });
|
||||
assert.equal(selections, 1, 'duration alone must not suppress entity selection');
|
||||
assert.equal(untracks, 0);
|
||||
|
||||
@@ -106,6 +92,7 @@ test('slow clean sprite clicks select, while long presses and orbit nudges canno
|
||||
handler.fire(TYPES.LEFT_UP, { position: { x: 3, y: 4 } });
|
||||
handler.fire(TYPES.LEFT_CLICK, { position: { x: 3, y: 4 } });
|
||||
assert.equal(untracks, 1, 'a short clean empty-space tap still untracks');
|
||||
input.destroy();
|
||||
});
|
||||
|
||||
test('civilian and military click handlers apply duration only at the deselect branch', () => {
|
||||
@@ -114,7 +101,7 @@ test('civilian and military click handlers apply duration only at the deselect b
|
||||
readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
|
||||
];
|
||||
for (const source of sources) {
|
||||
assert.match(source, /isTrackingSelectionGesture\(gesture\)[\s\S]+scene\.pick/);
|
||||
assert.match(source, /isTrackingSelectionGesture\(gesture\)[\s\S]+event\.hit/);
|
||||
assert.match(source, /isTrackingClickGesture\(gesture\)[\s\S]+(?:parts\.\w+\.)?_clearTracking\([^)]*\{ origin: 'user' \}\)/);
|
||||
}
|
||||
assert.doesNotMatch(
|
||||
|
||||
Reference in new issue
Block a user