fix(input): no double-click follow or zoom on the map

The globe viewer's own double-click tracked a picked entity with a
position or zoomed to one without. Layers moving onto the draw port had it
re-created one by one (data/stockFollow.js); following is a click in GEV,
so the viewer's handler is removed where the viewer is made and every
re-creation goes: earthquakes, cyclones, air quality, news, perimeters,
drone airspace, ghost maps, places, radio, cables, CCTV, ALPR, launches,
bikeshare, Local ADS-B, installations, directions, trails, data packs,
annotations, the library's view and local GeoJSON. The Cockpit's own
double-click and the draw tool's finishing double-click stay.
This commit is contained in:
Sameh Khamis committed 2026-11-14 09:10:14 -08:00
1 parent bb2d22dbce
commit b86014244d
69 files changed
+94 -2797

No files matched your search

+1 -39
View File
@@ -315,7 +315,7 @@ function cameraHarness(layer = alprCamerasLayer) {
},
});
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let click, dblclick, picked;
let click, picked;
const credits = new Set();
const viewer = {
creditDisplay: {
@@ -344,15 +344,6 @@ function cameraHarness(layer = alprCamerasLayer) {
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
// The viewer's stock double-click (its follow), which the input port
// takes and runs before layers' own.
screenSpaceEventHandler: {
getInputAction: (type) =>
type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
? () => {}
: undefined,
removeInputAction() {},
},
};
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, ports);
@@ -370,11 +361,6 @@ function cameraHarness(layer = alprCamerasLayer) {
modifier === undefined
)
click = fn;
if (
type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK &&
modifier === undefined
)
dblclick = fn;
return setInput.call(this, fn, type, modifier);
};
try {
@@ -423,11 +409,6 @@ function cameraHarness(layer = alprCamerasLayer) {
picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
click({ position: new Cesium.Cartesian2() });
},
dblclick(id) {
const item = typeof id === 'string' ? icons()?.items.get(id) : null;
picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
dblclick({ position: new Cesium.Cartesian2() });
},
restore() {
layer.destroy(viewer);
Date.now = originals.now;
@@ -1566,22 +1547,3 @@ test('ALPR display tags collapse controls and cap final text without erasing Uni
assert.equal(record.cameraType, null);
assert.equal(record.zone, 'traffic zone');
});
test('a double-click follows a camera with its card until it is no longer shown, as its entity was', async () => {
const { followedOf } = await import('./followed.js');
const h = cameraHarness();
try {
await alprCamerasLayer.update();
h.dblclick('alpr:42');
const followed = followedOf(h.viewer);
assert.ok(followed, 'the camera is followed');
assert.equal(followed.key, 'alpr:42');
assert.ok(followed.entity, 'through its entity record, for its card');
h.setFetch(async () => cameraResponse([cameraNode(43)]));
h.expire();
await alprCamerasLayer.update();
assert.equal(followedOf(h.viewer), null, 'gone: no longer followed');
} finally {
h.restore();
}
});
-68
View File
@@ -2,8 +2,6 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { createStubRenderer } from '../render/stub/index.js';
import {
DEFAULT_DIRECTIONS_MODE,
DIRECTIONS_MODES,
@@ -1027,69 +1025,3 @@ test('a placed endpoint draws its letter through the overlay, not as entity text
directionsLayer.destroy(viewer);
assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID));
});
test('a double-click follows an A or B marker and zooms to the route, as their entities did', async (t) => {
directionsLayer = createApplicationDirectionsLayer({
source: {
getRoute: async () => ({
ok: true,
distanceM: route.distanceM,
durationS: route.durationS,
geometry: route.geometry,
steps: route.steps,
}),
},
});
directionsLayer._setOverlayHostForTest({
setEntries() {},
setVisible() {},
clearSource() {},
});
resetPointerOwnership();
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
t.after(() => {
directionsLayer.destroy(viewer);
directionsLayer._setOverlayHostForTest(null);
unbind();
renderer.destroy();
resetPointerOwnership();
});
directionsLayer.init(viewer);
directionsLayer.enable(viewer);
directionsLayer.placeEndpoint('a', A);
directionsLayer.placeEndpoint('b', B);
const started = Date.now();
while (
directionsLayer.getStats().status !== 'ready' &&
Date.now() - started < 5000
)
await new Promise((resolve) => setTimeout(resolve, 5));
const setOf = (suffix) =>
renderer.testing.sets().find((id) => id.endsWith(suffix));
let hit = null;
renderer.testing.scriptPicks(() => (hit ? [hit] : []));
const markersId = setOf(':markers');
const routeId = setOf(':route');
assert.ok(markersId && routeId, 'the sets are drawn');
hit = { set: markersId, id: 'directions:marker:B', surface: false };
renderer.testing.pointer('dblclick', 10, 10);
const followed = renderer.camera.followed;
assert.ok(followed, 'B is followed');
assert.equal(followed.key, 'directions:marker:B');
const p = followed.position(0);
const at = Cesium.Cartographic.fromCartesian(
new Cesium.Cartesian3(p.x, p.y, p.z),
);
assert.ok(Math.abs(Cesium.Math.toDegrees(at.latitude) - B.lat) < 1e-9);
hit = { set: routeId, id: 'directions:route', surface: false };
renderer.testing.pointer('dblclick', 10, 10);
assert.equal(renderer.camera.followed, null, 'the route is zoomed to');
renderer.testing.tick();
const pose = renderer.camera.pose();
assert.ok(Math.abs(pose.lat - (A.lat + B.lat) / 2) < 0.2, String(pose.lat));
assert.ok(Math.abs(pose.lon - (A.lon + B.lon) / 2) < 0.2, String(pose.lon));
});
+3 -50
View File
@@ -1,20 +1,17 @@
/**
* The drawn part of the file import: what `geoImportFeatures.js` read from
* a file, drawn through the draw port in three sets (its pins, its lines,
* its shapes), its ground pins placed on the ground in batches, followed on
* a double-click like every drawn item, and its footprint read back.
* its shapes), its ground pins placed on the ground in batches, and its
* footprint read back.
*/
import {
GeoImportError,
MAX_IMPORT_ENTITIES,
boundedImport,
} from './geoImportShared.js';
import { followOnDoubleClick } from './stockFollow.js';
import { msg } from '../i18n/marker.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { heightsOf } from '../queries/heights.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import {
drawOf,
findCamera,
@@ -73,13 +70,8 @@ function turnedCorners({ west, south, east: eastEdge, north }, rotation = 0) {
* `mount()`; `refreshGround()` places the ground pins first.
* @param {object} viewer
* @param {object[]} features From `readKmlFeatures` or `readGeoJsonFeatures`.
* @param {{inputFor?: Function}} [options]
*/
export function createImportedDrawing(
viewer,
features,
{ inputFor = defaultInputFor } = {},
) {
export function createImportedDrawing(viewer, features) {
const prefix = `geo-import:${++drawings}`;
const ids = {
icons: `${prefix}:pins`,
@@ -98,11 +90,9 @@ export function createImportedDrawing(
offset: pin.mode === 'relative' ? pin.height : 0,
groundHeight: undefined,
}));
const byId = new Map();
let sets = null;
/** The items last handed to each set, for inspection. */
let drawn = { icons: [], lines: [], shapes: [] };
let follow = null;
let show = true;
let destroyed = false;
/** The surface last asked whether it is the bare ellipsoid, and its answer. */
@@ -241,11 +231,6 @@ export function createImportedDrawing(
}
}
/** The points a feature is framed by, ECEF. */
function framePoints(feature) {
return footprintOf(feature).map(ecef);
}
/** A feature's footprint, `[lon, lat, height]`. */
function footprintOf(feature) {
switch (feature.kind) {
@@ -283,17 +268,14 @@ export function createImportedDrawing(
// A pin with no icon draws nothing, but frames its file.
if (!feature.image) return;
const item = pinItem(feature, index);
byId.set(`${ids.icons}\u0000${item.id}`, feature);
icons.push(item);
} else if (feature.kind === 'line') {
const item = lineItem(feature, `l${index}`);
if (!item) return;
byId.set(`${ids.lines}\u0000${item.id}`, feature);
lines.push(item);
} else {
const item = shapeItem(feature, `s${index}`);
if (!item) return;
byId.set(`${ids.shapes}\u0000${item.id}`, feature);
shapes.push(item);
}
});
@@ -323,19 +305,6 @@ export function createImportedDrawing(
sets = null;
}
/** What a double-click on one of these items follows or zooms to. */
function targetFor(hit) {
const feature = byId.get(`${hit.set}\u0000${hit.id}`);
if (!feature) return null;
if (feature.kind === 'pin')
return {
key: `${hit.set}:${hit.id}`,
position: () => fromDegrees(feature.lon, feature.lat, feature.height),
};
const points = framePoints(feature);
return points.length ? { zoomTo: sphereFromPoints(points) } : null;
}
/** Move the drawn pins to where they now stand. */
function redrawPins() {
if (!sets?.icons) return;
@@ -470,18 +439,6 @@ export function createImportedDrawing(
mount() {
if (destroyed || sets) return;
draw();
try {
follow = followOnDoubleClick({
viewer,
inputFor,
name: 'geo-import',
enabled: () => show && !destroyed,
targetFor,
});
} catch {
// A renderer that takes no input has no double-click to follow on.
follow = null;
}
},
/** Place the ground pins again, and move the drawn ones. */
async refreshGround(signal) {
@@ -507,12 +464,8 @@ export function createImportedDrawing(
destroy() {
if (destroyed) return;
destroyed = true;
// A pin it follows is no longer there to follow.
follow?.destroy();
follow = null;
disposeSets();
drawn = { icons: [], lines: [], shapes: [] };
byId.clear();
},
};
}
+8 -36
View File
@@ -65,30 +65,16 @@ const FEATURES = [
},
];
/** A drawing of `features` on a renderer double, with double-clicks it is handed. */
/** A drawing of `features` on a renderer double. */
function drawn(features = FEATURES) {
const viewer = {};
const ground = bindFakeGroundRenderer(viewer);
const clicks = [];
const input = {
onPointer(type, fn) {
if (type === 'dblclick') clicks.push(fn);
return () => clicks.splice(clicks.indexOf(fn), 1);
},
stockEnabled: () => true,
};
const drawing = createImportedDrawing(viewer, features, {
inputFor: () => input,
});
const drawing = createImportedDrawing(viewer, features);
drawing.mount();
const items = (kind) => [
...ground.draw.set(drawing.ids[kind]).items.values(),
];
const doubleClick = (hit) => {
ground.setPick(() => hit);
for (const fn of clicks) fn({ position: { x: 1, y: 1 } });
};
return { ground, drawing, items, doubleClick, clicks };
return { ground, drawing, items };
}
test('pins draw as icons with the look their file gave them', (t) => {
@@ -141,36 +127,22 @@ test('paths, polygons, walls and overlays draw as lines and shapes', (t) => {
assert.equal(overlay.height, 'clampGround');
});
test('a double-click follows a pin and zooms to a path, until the file goes', (t) => {
const { ground, drawing, doubleClick, clicks } = drawn();
test('destroying a file takes its sets with it', (t) => {
const { ground, drawing } = drawn();
t.after(ground.unbind);
doubleClick({ set: drawing.ids.icons, id: 'p0' });
const followed = ground.follows.at(-1);
assert.equal(followed.key, `${drawing.ids.icons}:p0`);
const at = toLonLatH(followed.position());
assert.ok(Math.abs(at.lon - 1) < 1e-9 && Math.abs(at.lat - 2) < 1e-9);
doubleClick({ set: drawing.ids.lines, id: 'l2' });
assert.ok(ground.flights.at(-1).sphere.radius > 0, 'zoomed to the path');
assert.equal(ground.follows.at(-1), null, 'which ends the follow');
doubleClick({ set: 'someone-else', id: 'p0' });
assert.equal(ground.flights.length, 1, 'other sets are not followed');
doubleClick({ set: drawing.ids.icons, id: 'p0' });
drawing.destroy();
assert.equal(ground.follows.at(-1), null, 'a removed pin is not followed');
assert.equal(clicks.length, 0);
assert.equal(ground.liveSets().length, 0);
assert.deepEqual(drawing.items(), { icons: [], lines: [], shapes: [] });
});
test('hiding a file hides its sets and takes no double-clicks', (t) => {
const { ground, drawing, doubleClick } = drawn();
test('hiding a file hides its sets', (t) => {
const { ground, drawing } = drawn();
t.after(ground.unbind);
drawing.show = false;
for (const id of Object.values(drawing.ids))
assert.equal(ground.draw.set(id).show, false);
doubleClick({ set: drawing.ids.icons, id: 'p0' });
assert.equal(ground.follows.length, 0);
drawing.show = true;
assert.equal(ground.draw.set(drawing.ids.icons).show, true);
});
-2
View File
@@ -200,7 +200,6 @@ test('consumer build includes only infrastructure code and resolves assets under
'color.js',
'dispatcher.js',
'ellipsoid.js',
'frames.js',
'frustum.js',
'geojsonPins.js',
'heights.js',
@@ -217,7 +216,6 @@ test('consumer build includes only infrastructure code and resolves assets under
'scenePick.js',
'sensorPick.js',
'sphere.js',
'stockFollow.js',
'styleStages.js',
'vector.js',
]);
+3 -2
View File
@@ -132,8 +132,9 @@ test('pointer input, camera holds and the stock clicks go through the one dispat
[
/(?:screenSpaceEventHandler|stockHandler)\??\.removeInputAction\(/,
'removes stock clicks instead of suppressStockClicks()',
// It runs the stock clicks itself.
['src/render/cesium/input.js'],
// It runs the stock clicks itself; the viewer's factory drops the
// stock double-click before any input port exists.
['src/render/cesium/input.js', 'src/render/cesium/applicationViewer.js'],
],
];
const walk = (dir) =>
-96
View File
@@ -21,7 +21,6 @@ import {
} from '../sources/infrastructureData.js';
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
import { createGeojsonPins } from './geojsonPins.js';
import { followViewFrom } from './stockFollow.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import {
selectInfraLod,
@@ -567,9 +566,6 @@ export function createLocalGeoJsonLayer(
let _drawn = null;
let _enabled = false;
let _clickSubscription = null;
let _dblclickSubscription = null;
/** The follow a double-click started, while the camera keeps it. */
let _follow = null;
let _count = 0;
/** @type {number|null} Timestamp of the last successful dataset load. */
let _lastUpdate = null;
@@ -713,9 +709,6 @@ export function createLocalGeoJsonLayer(
_lastLodBudgetLimit = 0;
_lodComputed = false;
_lastLodProbeMs = Number.NEGATIVE_INFINITY;
// Its parts go, and the follow of one with them, as a removed entity
// stopped being followed.
stopFollow(viewer);
releaseDrawn();
_overlayPublisher.hide();
clearSelectedEntityContextForLayer(id);
@@ -936,78 +929,6 @@ export function createLocalGeoJsonLayer(
if (pins.length) drawn.sets.pins.upsert(pins);
}
/**
* Follow the part under `position`: a part with a stem by the centre of
* all it draws, stem and all, as the default renderer followed the
* loader's entity by its bounds, framed as that renderer framed an entity
* it started following; a line, which had no position to
* follow, is flown into view instead.
*/
function followAt(viewer, position) {
const hit = findQuery(viewer)?.pick(position.x, position.y);
if (!hit || !hit.set?.startsWith(`${setPrefix}:`)) return;
const part = _drawn?.parts.get(hit.id);
if (!part) return;
const camera = findCamera(viewer);
if (!camera) return;
const points = framedPoints(part);
if (!points.length) return;
const record = part.carrier.record;
try {
if (!record) {
// As the default renderer zoomed to an entity with no position: at
// once, north up, pitched down 45°, at the range that fits it in
// view (the camera port's defaults).
const sphere = sphereFromPoints(points);
// Following nothing then, as that zoom stopped any follow first.
if (camera.followed) camera.follow(null);
camera.flyToBounds(sphere, { durationS: 0 });
return;
}
// The camera looks at the bounds' centre, kept where the stem now
// stands, as the default renderer kept its entity's bounds.
const outline = framedPoints(part, false);
const centre = () =>
sphereFromPoints([...outline, record.base, record.tip]).center;
const target = {
key: `${id}:${record.id}`,
position: centre,
frame: 'enu',
viewFrom: followViewFrom(sphereFromPoints(points), record.tip, camera),
};
camera.follow(target);
_follow = target;
} catch (error) {
// A camera that cannot follow (a viewer without entity tracking)
// leaves the view where it is, as that viewer's double-click did.
console.warn(`${id}: cannot follow`, error);
}
}
/**
* What the default renderer framed for a part: all it drew of it (but
* for its stem, without `withStem`).
*/
function framedPoints(part, withStem = true) {
const record = part.carrier.record;
const points = [];
if (part.kind === 'polygon')
for (const { lon, lat, height } of part.rings[0])
points.push(fromDegrees(lon, lat, height ?? 0));
else if (part.kind === 'line')
for (const [lon, lat] of part.coordinates)
points.push(fromDegrees(lon, lat, 0));
if (record && withStem) points.push(copy(record.base), copy(record.tip));
return points;
}
/** Stop a follow this layer started, if the camera still keeps it. */
function stopFollow(viewer) {
const camera = findCamera(viewer);
if (_follow && camera?.followed === _follow) camera.follow(null);
_follow = null;
}
/** Fly to where a clicked part stands, holding camera input meanwhile. */
function flyToPart(viewer, input, part) {
const target = part.carrier.record
@@ -1202,19 +1123,6 @@ export function createLocalGeoJsonLayer(
flyToPart(viewer, input, part);
});
}
// 3. Follow a part on a double-click, as the default renderer's
// own double-click followed the loader's entities.
if (!_dblclickSubscription) {
const input = inputFor(viewer);
_dblclickSubscription =
input.onPointer?.('dblclick', (event) => {
if (!_enabled || !_drawn) return;
// The renderer's own double-click follow, off while a
// tool holds it or on a renderer without one.
if (input.stockEnabled?.('dblclickFollow') !== true) return;
followAt(viewer, event.position);
}) ?? null;
}
})();
try {
await _loadPromise;
@@ -1536,8 +1444,6 @@ export function createLocalGeoJsonLayer(
record.context.label === selectedHere.label,
))
: null;
// A follow of an old part ends with it, as a removed entity's did.
stopFollow(viewer);
_drawn = built;
_stemRecords = built.records;
_count = built.count;
@@ -1576,8 +1482,6 @@ export function createLocalGeoJsonLayer(
removeEntityContextsForLayer(id);
_clickSubscription?.();
_clickSubscription = null;
_dblclickSubscription?.();
_dblclickSubscription = null;
_overlayPublisher.destroy();
_cachedFeatures = null;
pinMaker.clear();
-112
View File
@@ -8,9 +8,6 @@ import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { getContextStore } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { distance, normalize, sub } from '../geo/vector.js';
import { eastNorthUp, framePoint, inverseFrameVector } from '../geo/frames.js';
const feature = (id, geometry, properties = { name: `Feature ${id}` }) => ({
type: 'Feature',
id,
@@ -82,8 +79,6 @@ async function enabledLayer(t, features) {
eye: { lon: 0.005, lat: 0.005, height: 50_000 },
});
let click = null;
let dblclick = null;
const stock = { dblclickFollow: true };
const holds = [];
const layer = createLocalGeoJsonLayer(
{
@@ -103,14 +98,6 @@ async function enabledLayer(t, features) {
holds.push(reason);
return () => holds.push(`release:${reason}`);
},
onPointer: (type, handler) => {
assert.equal(type, 'dblclick');
dblclick = handler;
return () => {
dblclick = null;
};
},
stockEnabled: (name) => stock[name] === true,
}),
},
{
@@ -134,10 +121,7 @@ async function enabledLayer(t, features) {
viewer,
fake,
holds,
stock,
click: (event) => click?.(event),
dblclick: (event) => dblclick?.(event),
subscribed: () => dblclick !== null,
};
}
@@ -410,99 +394,3 @@ test('a marker-symbol is stamped on its pin: a character as text, a longer one a
assert.match(pins.get('missing').image.svg, /fill="rgba\(255,0,0,1\)"/);
assert.deepEqual(pins.get('missing').image, pins.get('plain').image);
});
test('a double-click follows a part as the default renderer followed its entity, and zooms to a line', async (t) => {
const env = await enabledLayer(t, [
feature('pt', { type: 'Point', coordinates: [0.002, 0.003] }),
feature('l', {
type: 'LineString',
coordinates: [
[0, 0],
[0.01, 0],
],
}),
]);
const { fake } = env;
const setOf = (role) => fake.set(role).spec.id;
const stem = fake.set('stems').items.get('pt');
const [base, tip] = stem.positions;
let picked = null;
fake.setPick((x, y) => (x === 7 && y === 9 ? picked : null));
// Nothing of this layer's under it: nothing happens.
env.dblclick({ position: { x: 7, y: 9 } });
picked = { set: 'someone-else', id: 'pt' };
env.dblclick({ position: { x: 7, y: 9 } });
assert.equal(fake.follows.length, 0);
// Its pin, its stem or its dot: the camera follows the stem's centre,
// where the default renderer kept the entity's bounds. A tall view, so
// its width is what fits the stem in.
fake.view.aspectRatio = 0.5;
picked = { set: setOf('pins'), id: 'pt' };
env.dblclick({ position: { x: 7, y: 9 } });
const target = fake.follows.at(-1);
assert.equal(target.key, 'local-dams:pt');
assert.equal(target.frame, 'enu');
const center = {
x: (base.x + tip.x) / 2,
y: (base.y + tip.y) / 2,
z: (base.z + tip.z) / 2,
};
assert.ok(distance(target.position(0), center) < 1e-6);
// Looking at it north up, pitched down 45 degrees (a little more for a
// tip above the ellipsoid), at the range that fits the stem in view.
const eye = framePoint(eastNorthUp(center), target.viewFrom);
const radius = distance(base, tip) / 2;
const fit = radius / (0.5 * Math.tan(Math.PI / 6));
assert.ok(Math.abs(distance(eye, center) - fit) < 1e-6);
const look = inverseFrameVector(
eastNorthUp(center),
normalize(sub(center, eye)),
);
const factor = 2 - 1 / Math.max(1, Math.hypot(tip.x, tip.y, tip.z) / 6378137);
assert.ok(factor > 1 + 1e-5, 'the tip stands above the ellipsoid');
assert.ok(Math.abs(look.x) < 1e-9, 'heading north');
assert.ok(look.y > 0);
assert.ok(
Math.abs(Math.asin(-look.z) - (Math.PI / 4) * factor) < 1e-9,
'pitched down 45 degrees, steeper above the ground',
);
fake.view.aspectRatio = 1;
// Off while the renderer's own double-click follow is held off.
env.stock.dblclickFollow = false;
picked = { set: setOf('stems'), id: 'pt' };
env.dblclick({ position: { x: 7, y: 9 } });
assert.equal(fake.follows.length, 1);
env.stock.dblclickFollow = true;
// A line had no position to follow: it is zoomed to instead, at once,
// with the camera's default framing (north, 45 degrees down, fitted).
picked = { set: setOf('lines'), id: 'l' };
env.dblclick({ position: { x: 7, y: 9 } });
const zoom = fake.flights.at(-1);
assert.ok(zoom.sphere.radius > 500);
assert.deepEqual(zoom.options, { durationS: 0 });
// Stopping the follow first, as that zoom did.
assert.equal(fake.follows.length, 2);
assert.equal(fake.follows.at(-1), null);
// Disabled, the layer leaves a follow another started in place of its
// own, and stops its own.
picked = { set: setOf('dots'), id: 'pt' };
env.dblclick({ position: { x: 7, y: 9 } });
assert.equal(fake.follows.at(-1).key, 'local-dams:pt');
const theirs = { key: 'theirs' };
fake.follows.push(theirs);
env.layer.disable(env.viewer);
assert.equal(fake.follows.at(-1), theirs);
await env.layer.enable(env.viewer);
env.dblclick({ position: { x: 7, y: 9 } });
assert.equal(fake.follows.at(-1).key, 'local-dams:pt');
env.layer.disable(env.viewer);
assert.equal(fake.follows.at(-1), null);
// Destroyed, it stops listening.
env.layer.destroy(env.viewer);
assert.equal(env.subscribed(), false);
});
-184
View File
@@ -1,184 +0,0 @@
/**
* @module data/stockFollow
* @description A double-click on a layer's drawn item follows it, as the
* default renderer's own double-click followed the entities layers drew
* before they drew through the draw port: an item with a position is
* followed, framed as that renderer framed an entity it started following;
* one without (a line) is zoomed to at once instead. It runs only while the
* renderer's own double-click follow is on (a tool can hold it off).
*/
import { followOffsetFitting } from '../geo/frames.js';
import { findCamera, findQuery } from '../render/rendererOf.js';
import { entityFollowTarget } from './followed.js';
import { positionToEcef } from '../geo/ellipsoid.js';
import { sphereFromPoints } from '../geo/sphere.js';
/** A line's or shape's positions as ECEF points. */
function pointsOf(positions) {
if (!positions) return [];
if (ArrayBuffer.isView(positions)) {
const out = [];
for (let i = 0; i + 2 < positions.length; i += 3)
out.push({ x: positions[i], y: positions[i + 1], z: positions[i + 2] });
return out;
}
return Array.from(positions, positionToEcef);
}
/**
* What a double-click on a drawn item does, as the default renderer did
* for the entity a layer drew it as before: a point, an icon or a disc
* (an entity with a position) is followed, framed to fit the disc; a line
* or another shape (an entity without one) is zoomed to. For a layer's
* `targetFor`, given the hit's set id and the item drawn there.
* @param {string} set The hit's set id.
* @param {object|null|undefined} item The draw item (draw.d.ts) the hit names.
*/
export function drawnItemTarget(set, item) {
if (!item) return null;
const key = `${set}:${item.id}`;
if (item.pos) {
const at = positionToEcef(item.pos);
return { key, position: () => ({ ...at }) };
}
const geometry = item.geometry;
if (geometry?.kind === 'ellipse') {
const at = positionToEcef(geometry.center);
const radius = Math.max(geometry.semiMajor, geometry.semiMinor);
return {
key,
position: () => ({ ...at }),
sphere: { center: at, radius: Number.isFinite(radius) ? radius : 0 },
};
}
let points = pointsOf(item.positions);
if (geometry?.kind === 'polygon') points = pointsOf(geometry.rings?.[0]);
else if (geometry?.kind === 'wall') points = pointsOf(geometry.positions);
else if (geometry?.kind === 'rectangle') {
const { west, south, east, north } = geometry.rect;
points = pointsOf([
{ lon: west, lat: south },
{ lon: east, lat: south },
{ lon: east, lat: north },
{ lon: west, lat: north },
]);
}
return points.length ? { zoomTo: sphereFromPoints(points) } : null;
}
/**
* Where the camera frames a part it starts following: `followOffsetFitting`
* with the camera port's field of view and zoom limits.
* @param {{center: {x: number, y: number, z: number}, radius: number}} sphere
* @param {{x: number, y: number, z: number}} at
* @param {object} camera The camera port.
*/
export function followViewFrom(sphere, at, camera) {
const pose = camera.pose?.();
const { minDistance, maxDistance } = camera.controls ?? {};
return followOffsetFitting(sphere, at, {
fovy: pose?.fovy,
aspectRatio: pose?.aspectRatio,
minDistance,
maxDistance,
});
}
/**
* Follow (or zoom to) a layer's item on a double-click.
* @param {object} options
* @param {object} options.viewer
* @param {(viewer: object) => object} options.inputFor The click dispatcher.
* @param {string} options.name The layer, for warnings.
* @param {() => boolean} options.enabled Whether the layer takes clicks now.
* @param {(hit: import('../render/contract/query').Hit) =>
* ({key: string, position: () => ({x: number, y: number, z: number}|null),
* sphere?: {center: object, radius: number}, entity?: object}
* | {zoomTo: {center: object, radius: number}}
* | null)} options.targetFor What a hit on one of the layer's items is
* followed by (`key`, its live `position`, the bounds it is framed by,
* radius 0 by default, and the holder whose entity record shows it, as
* `entityFollowTarget` reads one), or zoomed to (`zoomTo`); null for
* anything else.
* @returns {{readonly following: object|null, retain(drawn: (key: string) => boolean): void,
* stop(): void, destroy(): void}}
*/
export function followOnDoubleClick({
viewer,
inputFor,
name,
enabled,
targetFor,
}) {
const input = inputFor(viewer);
/** The follow a double-click started, while the camera keeps it. */
let follow = null;
const off =
input.onPointer?.('dblclick', (event) => {
if (!enabled()) return;
// The renderer's own double-click follow, off while a tool holds it
// or on a renderer without one.
if (input.stockEnabled?.('dblclickFollow') !== true) return;
const hit = findQuery(viewer)?.pick(event.position.x, event.position.y);
const found = hit && !hit.surface ? targetFor(hit) : null;
if (!found) return;
const camera = findCamera(viewer);
if (!camera) return;
try {
if (found.zoomTo) {
// As the default renderer zoomed to an entity with no position:
// at once, north up, pitched down 45°, at the range that fits it
// in view. Following nothing then, as that zoom stopped any
// follow first.
if (camera.followed) camera.follow(null);
camera.flyToBounds(found.zoomTo, { durationS: 0 });
return;
}
const at = found.position();
if (!at) return;
const fields = {
key: found.key,
position: found.position,
frame: 'enu',
viewFrom: followViewFrom(
found.sphere ?? { center: at, radius: 0 },
at,
camera,
),
};
const target = found.entity
? entityFollowTarget(found.entity, fields)
: fields;
camera.follow(target);
follow = target;
} catch (error) {
// A camera that cannot follow leaves the view where it is, as a
// viewer without entity tracking did.
console.warn(`${name}: cannot follow`, error);
}
}) ?? null;
return {
get following() {
return follow && findCamera(viewer)?.followed === follow ? follow : null;
},
/**
* Stop a follow this started of something no longer drawn, as removing
* an entity ended the default renderer's follow of it.
* @param {(key: string) => boolean} drawn Whether the item keyed so is.
*/
retain(drawn) {
const key = this.following?.key;
if (key && !drawn(key)) this.stop();
},
/** Stop a follow this started, if the camera still keeps it. */
stop() {
const camera = findCamera(viewer);
if (follow && camera?.followed === follow) camera.follow(null);
follow = null;
},
destroy() {
this.stop();
off?.();
},
};
}
-168
View File
@@ -1,168 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { followOnDoubleClick, followViewFrom } from './stockFollow.js';
import { bindRenderer } from '../render/rendererOf.js';
import { WGS84 } from '../geo/ellipsoid.js';
/** A viewer whose renderer answers picks with `hit` and records the camera. */
function scene({ hit, stock = true, enabled = true }) {
const viewer = {};
const handlers = new Map();
const calls = [];
const camera = {
followed: null,
controls: { minDistance: 0, maxDistance: Infinity },
pose: () => ({ fovy: Math.PI / 3, aspectRatio: 2 }),
follow(target) {
calls.push(['follow', target]);
camera.followed = target;
},
flyToBounds(sphere, options) {
calls.push(['flyToBounds', sphere, options]);
},
};
const unbind = bindRenderer(viewer, {
camera,
query: { pick: () => hit },
});
const input = {
onPointer(type, handler) {
handlers.set(type, handler);
return () => handlers.delete(type);
},
stockEnabled: (name) => name === 'dblclickFollow' && stock,
};
const at = { x: WGS84.radii.x, y: 0, z: 0 };
const follow = followOnDoubleClick({
viewer,
inputFor: () => input,
name: 'test-layer',
enabled: () => enabled,
targetFor: (picked) =>
picked.id === 'point'
? { key: 'layer:point', position: () => at }
: picked.id === 'line'
? { zoomTo: { center: at, radius: 50 } }
: null,
});
const dblclick = () =>
handlers.get('dblclick')?.({ position: { x: 1, y: 2 } });
return { follow, camera, calls, dblclick, handlers, unbind };
}
test('a double-click follows a point, framed as the default renderer framed an entity', () => {
const s = scene({ hit: { set: 'layer', id: 'point', surface: false } });
s.dblclick();
const [[kind, target]] = s.calls;
assert.equal(kind, 'follow');
assert.equal(target.key, 'layer:point');
assert.equal(target.frame, 'enu');
// No size: the minimum fit range, 45 degrees down on the ground.
const range = Math.hypot(
target.viewFrom.x,
target.viewFrom.y,
target.viewFrom.z,
);
assert.ok(Math.abs(range - 100) < 1e-6);
assert.ok(Math.abs(target.viewFrom.z + target.viewFrom.y) < 1e-6);
assert.equal(s.follow.following, target);
// Stopping ends only the follow it started.
s.follow.stop();
assert.equal(s.camera.followed, null);
s.follow.destroy();
assert.equal(s.handlers.size, 0);
s.unbind();
});
test('a double-click on a line zooms to it at once, following nothing', () => {
const s = scene({ hit: { set: 'layer', id: 'line', surface: false } });
s.camera.followed = { key: 'other' };
s.dblclick();
assert.deepEqual(
s.calls.map(([kind]) => kind),
['follow', 'flyToBounds'],
);
assert.equal(s.calls[0][1], null);
assert.deepEqual(s.calls[1][2], { durationS: 0 });
s.follow.destroy();
s.unbind();
});
test('no follow while the stock double-click is held off, the layer is off, or the pick is not its own', () => {
for (const options of [
{ hit: { id: 'point', surface: false }, stock: false },
{ hit: { id: 'point', surface: false }, enabled: false },
{ hit: { id: 'other', surface: false } },
{ hit: { surface: true } },
{ hit: null },
]) {
const s = scene(options);
s.dblclick();
assert.deepEqual(s.calls, []);
s.follow.destroy();
s.unbind();
}
});
test('the frame view fits a sphere and steepens far from the ground', () => {
const camera = { pose: () => ({ fovy: Math.PI / 2, aspectRatio: 1 }) };
const ground = { x: WGS84.radii.x, y: 0, z: 0 };
const near = followViewFrom({ center: ground, radius: 1000 }, ground, camera);
assert.ok(Math.abs(Math.hypot(near.x, near.y, near.z) - 1000) < 1e-6);
const high = { x: WGS84.radii.x * 2, y: 0, z: 0 };
const far = followViewFrom({ center: high, radius: 0 }, high, camera);
// Looking down 45 degrees times 1.5 at twice the radius: the eye that
// far above, south of the point.
const elevation = Math.atan2(far.z, Math.hypot(far.x, far.y));
assert.ok(Math.abs(elevation - (Math.PI / 4) * 1.5) < 1e-9);
assert.ok(far.y < 0);
});
test('a drawn item is followed as an entity with a position was, or zoomed to as one without', async () => {
const { drawnItemTarget } = await import('./stockFollow.js');
const near = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z) < 1e-6;
const { fromDegrees } = await import('../geo/ellipsoid.js');
const point = drawnItemTarget('s', { id: 'p', pos: { lon: 10, lat: 20 } });
assert.equal(point.key, 's:p');
assert.ok(near(point.position(), fromDegrees(10, 20, 0)));
const disc = drawnItemTarget('s', {
id: 'd',
geometry: {
kind: 'ellipse',
center: { lon: 10, lat: 20 },
semiMajor: 4000,
semiMinor: 3000,
},
});
assert.equal(disc.sphere.radius, 4000);
assert.ok(near(disc.position(), fromDegrees(10, 20, 0)));
const flat = new Float64Array([
...Object.values(fromDegrees(0, 0, 0)),
...Object.values(fromDegrees(2, 0, 0)),
]);
const line = drawnItemTarget('s', { id: 'l', positions: flat });
assert.ok(line.zoomTo.radius > 100_000 && !line.position);
const polygon = drawnItemTarget('s', {
id: 'g',
geometry: {
kind: 'polygon',
rings: [
[
{ lon: 0, lat: 0 },
{ lon: 1, lat: 0 },
{ lon: 1, lat: 1 },
],
],
},
});
assert.ok(polygon.zoomTo.radius > 50_000);
const rect = drawnItemTarget('s', {
id: 'r',
geometry: {
kind: 'rectangle',
rect: { west: 0, south: 0, east: 1, north: 1 },
},
});
assert.ok(rect.zoomTo.radius > 50_000);
assert.equal(drawnItemTarget('s', null), null);
});
@@ -564,8 +564,6 @@ function createCableHarness({
// event-dirty behavior with no wall-clock coupling.
let clockMs = 0;
let clickHandler = null;
let doubleHandler = null;
let picked = null;
const layer = createTeleGeographySubmarineCableLayer({
overlayHost: {
setVisible: (...args) => hostCalls.push(['visible', ...args]),
@@ -579,14 +577,6 @@ function createCableHarness({
if (clickHandler === fn) clickHandler = null;
};
},
onPointer: (type, fn) => {
if (type !== 'dblclick') return () => {};
doubleHandler = fn;
return () => {
if (doubleHandler === fn) doubleHandler = null;
};
},
stockEnabled: (name) => name === 'dblclickFollow',
}),
source,
mapStackEventTarget,
@@ -617,13 +607,8 @@ function createCableHarness({
camera.port.cancelFlight = () => flights.push('cancel');
camera.port.flyTo = (destination, options) =>
flights.push({ destination, options });
camera.port.followed = null;
camera.port.follow = (target) => (camera.port.followed = target ?? null);
const zooms = [];
camera.port.flyToBounds = (sphere) => zooms.push(sphere);
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { pick: () => picked },
frame: fakeSceneFrame(viewer),
});
layer.init(viewer);
@@ -652,13 +637,6 @@ function createCableHarness({
click(drawHit) {
clickHandler?.({ drawHit, pick: null });
},
/** A double-click over a drawn item; what the camera then does. */
dblclick(hit) {
picked = hit;
doubleHandler?.({ position: { x: 1, y: 1 } });
},
followed: () => camera.port.followed,
zooms,
async load() {
layer.enable(viewer);
source.releaseAll?.();
@@ -1362,26 +1340,3 @@ test('every bundled cable segment is drawn with its source feature', async () =>
assert.equal(env.set('references').items.size, features.length);
env.layer.destroy();
});
test('a double-click follows a landing point or reference and zooms to a cable, as their entities did', async () => {
const env = await loadedHarness();
const [lineId] = env.set('lines').items.keys();
const [pinId] = env.set('pins').items.keys();
const [cableRef] = env.set('references').items.keys();
const surface = { surface: false };
env.dblclick({ set: env.set('pins').spec.id, id: pinId, ...surface });
assert.ok(env.followed(), 'a landing point is followed');
env.dblclick({ set: env.set('stems').spec.id, id: cableRef, ...surface });
assert.equal(
env.followed().key,
`${env.set('references').spec.id}:${cableRef}`,
'a stem follows its reference, one entity before',
);
env.dblclick({ set: env.set('lines').spec.id, id: lineId, ...surface });
assert.equal(env.followed(), null, 'a cable is zoomed to');
assert.ok(env.zooms.at(-1)?.radius > 0);
env.dblclick({ set: env.set('pins').spec.id, id: pinId, ...surface });
env.layer.disable();
assert.equal(env.followed(), null, 'hidden, its entities went: no follow');
env.layer.destroy();
});
+10 -71
View File
@@ -27,9 +27,8 @@
* changing settle into static geometry.
*/
import { cssColor } from '../render/color.js';
import { findDraw, findInput } from '../render/rendererOf.js';
import { findDraw } from '../render/rendererOf.js';
import { registerPickOwner } from './pickRegistry.js';
import { drawnItemTarget, followOnDoubleClick } from './stockFollow.js';
// Trail lines are pickable (a click on one must not fall through to the
// ground under it). A trail hugs its aircraft, so an unclaimed pick would
@@ -44,54 +43,6 @@ registerPickOwner('trails', (pickedId) =>
/** @type {number} Uniquifier for trail set and line ids. */
let _trailSeq = 0;
/**
* Per viewer, its trails' drawn lines by set id and the one double-click
* handler they share: a double-click on a trail line zooms to it, as the
* default renderer zoomed to the polyline entity a trail was drawn as.
* @type {WeakMap<object, {lines: Map<string, (id: string) => object|null>,
* follow: object|null}>}
*/
const doubleClicks = new WeakMap();
/**
* Take part in `viewer`'s trail double-click with the set `setId`, whose
* line by id `lineFor` gives. Returns how to leave it.
*/
function joinDoubleClick(viewer, setId, lineFor) {
let shared = doubleClicks.get(viewer);
if (!shared) {
const lines = new Map();
// A scene that takes no input (or a headless one, with no page to take
// it from) has no double-click.
let input = null;
try {
input = findInput(viewer);
} catch {
input = null;
}
shared = {
lines,
follow: input
? followOnDoubleClick({
viewer,
inputFor: () => input,
name: 'trails',
enabled: () => true,
targetFor: (hit) =>
drawnItemTarget(hit.set, lines.get(hit.set)?.(hit.id)),
})
: null,
};
doubleClicks.set(viewer, shared);
}
shared.lines.set(setId, lineFor);
return () => {
if (!shared.lines.delete(setId) || shared.lines.size) return;
shared.follow?.destroy();
if (doubleClicks.get(viewer) === shared) doubleClicks.delete(viewer);
};
}
/** @constant {number} Alpha where the trail passes the depth test. */
const TRAIL_ALPHA = 0.85;
/** @constant {number} Alpha where the trail is behind/below scene geometry —
@@ -182,21 +133,11 @@ export function createTrail(viewer, { color, width = 2.5 }) {
* the position objects it was drawn from, which never change. */
let chunks = [];
let chunkSeq = 0;
/** Leaves the viewer's trail double-click, once the set is drawn. */
let leaveDoubleClick = null;
/** The line drawn under `id`, for a double-click to zoom to. */
function lineFor(id) {
const shown = drawn.get(id)?.item;
if (shown) return shown.show === false ? null : shown;
return chunks.find((chunk) => chunk.id === id)?.item ?? null;
}
function ensureSet() {
if (set || destroyed || !viewer || viewer.isDestroyed?.()) return set;
set =
findDraw(viewer)?.lines({ id: `trail:${seq}`, show: visible }) ?? null;
if (set) leaveDoubleClick = joinDoubleClick(viewer, set.id, lineFor);
return set;
}
@@ -282,16 +223,16 @@ export function createTrail(viewer, { color, width = 2.5 }) {
}
}
const positions = seg.slice(i, end + 1);
const id = `${bodyId}:${++chunkSeq}`;
const item = lineItem(
id,
positions.map(plain),
TRAIL_ALPHA,
TRAIL_OCCLUDED_ALPHA,
);
const chunk = { id, positions, item };
const chunk = { id: `${bodyId}:${++chunkSeq}`, positions };
next.push(chunk);
added.push(item);
added.push(
lineItem(
chunk.id,
positions.map(plain),
TRAIL_ALPHA,
TRAIL_OCCLUDED_ALPHA,
),
);
i = end;
}
});
@@ -377,8 +318,6 @@ export function createTrail(viewer, { color, width = 2.5 }) {
/** Remove the trail permanently (layer disable/teardown). */
destroy() {
destroyed = true;
leaveDoubleClick?.();
leaveDoubleClick = null;
try {
set?.dispose();
} catch {
-55
View File
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { CHUNK_POINTS, createTrail } from './trailRenderer.js';
import { findPickOwner } from './pickRegistry.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { fromDegrees } from '../geo/ellipsoid.js';
function viewerWithDraw(t) {
const viewer = { isDestroyed: () => false };
@@ -231,56 +229,3 @@ test('clearing a segmented trail lets every line go', (t) => {
trail.setSegments([points(4)]);
assert.equal(historyLines(set).length, 1, 'drawn again after a clear');
});
test('a double-click on a trail line zooms to that line, as to the polyline entity it was', (t) => {
const viewer = { isDestroyed: () => false };
const fake = bindFakeGroundRenderer(viewer);
t.after(fake.unbind);
let dblclick = null;
const stock = { dblclickFollow: true };
fake.renderer.input = {
onPointer(type, handler) {
assert.equal(type, 'dblclick');
dblclick = handler;
return () => {
dblclick = null;
};
},
stockEnabled: (name) => stock[name] === true,
};
const trail = createTrail(viewer, { color: '#00d4ff' });
const a = fromDegrees(0, 0, 1000);
const b = fromDegrees(0.1, 0, 1000);
trail.setPositions([a, b]);
const set = fake.liveSets().find((s) => s.spec.id.startsWith('trail:'));
const [line] = set.items.values();
fake.setPick(() => ({ set: set.spec.id, id: line.id }));
const at = { position: { x: 1, y: 2 } };
dblclick(at);
assert.equal(fake.flights.length, 1, 'zoomed at once');
const { sphere, options } = fake.flights[0];
assert.equal(options.durationS, 0);
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, z: (a.z + b.z) / 2 };
assert.ok(
Math.hypot(
sphere.center.x - mid.x,
sphere.center.y - mid.y,
sphere.center.z - mid.z,
) < 1,
);
assert.equal(fake.follows.length, 0, 'nothing followed');
// Held off (a tool holds the stock follow), a hidden trail line, or
// another layer's hit: nothing.
stock.dblclickFollow = false;
dblclick(at);
stock.dblclickFollow = true;
fake.setPick(() => ({ set: 'other', id: line.id }));
dblclick(at);
assert.equal(fake.flights.length, 1);
// The last trail gone, the viewer's double-click is let go.
trail.destroy();
assert.equal(dblclick, null);
});