Follow a local GeoJSON feature on double-click through the camera port

A double-click on a point or polygon of a local GeoJSON layer follows it
again, as the default renderer followed the loader's entities: looking at
the centre of what the feature draws, north up, pitched down 45 degrees,
at the range that fits it in view. A line is zoomed to at once instead.
The layer acts only while the renderer's own double-click follow is on,
stops a follow it started when disabled, and stops listening when
destroyed.
This commit is contained in:
Sameh Khamis committed 2026-11-07 23:47:04 -08:00
1 parent c5fffae09e
commit abef2800fb
5 files changed
+277 -5

No files matched your search

+1
View File
@@ -207,6 +207,7 @@ test('consumer build includes only infrastructure code and resolves assets under
'drawHit.js',
'ellipsoid.js',
'follow.js',
'frames.js',
'geojsonPins.js',
'heights.js',
'infrastructure.js',
+128 -1
View File
@@ -8,7 +8,13 @@ import {
findQuery,
} from '../render/rendererOf.js';
import { cssColor } from '../render/color.js';
import { fromDegrees, fromDegreesInto, toLonLatH } from '../geo/ellipsoid.js';
import {
WGS84,
fromDegrees,
fromDegreesInto,
toLonLatH,
} from '../geo/ellipsoid.js';
import { offsetFromHeadingPitchRange } from '../geo/frames.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { densifyRhumb } from '../geo/rhumb.js';
import { heightsOf } from '../queries/heights.js';
@@ -315,6 +321,34 @@ const STEM_WIDTH_PX = 3.5;
const PIN_SIZE_PX = 8;
const BLACK = Object.freeze([0, 0, 0, 1]);
/** The range the default renderer frames a sphere of no size from. */
const MINIMUM_FIT_RANGE_M = 100;
/**
* Where the camera frames a part it starts following, as the default
* renderer framed an entity it started following with no view of its own:
* looking at the bounds' centre, heading north, pitched down 45° (steeper
* far from the ground), at the range that fits the bounds in view, within
* the camera's zoom limits. Returned as the eye's offset from the centre,
* east-north-up there; `at` is where the part stands.
*/
function followViewFrom(sphere, at, camera) {
const pose = camera.pose?.();
const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3;
const aspect = Number.isFinite(pose?.aspectRatio) ? pose.aspectRatio : 1;
const tanPhi = Math.tan(fovy / 2);
const tanTheta = aspect * tanPhi;
let range =
sphere.radius === 0
? MINIMUM_FIT_RANGE_M
: Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi);
const { minDistance = 0, maxDistance = Infinity } = camera.controls ?? {};
range = Math.min(Math.max(range, minDistance), maxDistance);
const factor =
2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x);
return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range);
}
/** The GeoJSON loader's `marker-size` names, in pixels. */
const MARKER_SIZES = Object.freeze({ small: 24, medium: 48, large: 64 });
/**
@@ -544,6 +578,9 @@ 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;
@@ -681,6 +718,9 @@ 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);
@@ -886,6 +926,78 @@ 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
@@ -1064,6 +1176,19 @@ 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;
@@ -1305,6 +1430,8 @@ export function createLocalGeoJsonLayer(
removeEntityContextsForLayer(id);
_clickSubscription?.();
_clickSubscription = null;
_dblclickSubscription?.();
_dblclickSubscription = null;
_overlayPublisher.destroy();
_cachedFeatures = null;
pinMaker.clear();
+118 -1
View File
@@ -8,6 +8,8 @@ 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',
@@ -80,6 +82,8 @@ 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(
{
@@ -99,6 +103,14 @@ 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,
}),
},
{
@@ -117,7 +129,16 @@ async function enabledLayer(t, features) {
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
});
return { layer, viewer, fake, holds, click: (event) => click?.(event) };
return {
layer,
viewer,
fake,
holds,
stock,
click: (event) => click?.(event),
dblclick: (event) => dblclick?.(event),
subscribed: () => dblclick !== null,
};
}
test('polygons fill the ground, lines drape, points stand on pins, all shown', async (t) => {
@@ -387,3 +408,99 @@ 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);
});