Hand features the engine instead of guessing it from a viewer

No code outside src/globe calls isGlobeEngine or engineFromViewer any
more (14 calls left before this). The features that still sniffed take
the engine from their caller:

- Projection and surface helpers (focus de-emphasis, icon orientation,
  ground snap, the mesh floor sampler, ground picks) take the engine; the
  engine view's scene carries its projector instead of registering itself
  as a viewer.
- Credits go only through engine.credits, so annotations and layers
  share one OSM credit state on Cesium too (it could show twice).
- The annotation board and the resolver work on the engine: camera
  assists, visibility and picks go through engine.camera,
  engine.projector and src/geo, without Cesium.
- The Recent Imagery box tool has one implementation for both engines,
  on capture-phase canvas pointer events with the layer's engine.ground
  preview; the Navara copy goes. On Cesium the preview outline is solid
  now, as on Navara.
- Scene interactions take the engine, and the render governor has an
  engine variant beside the Cesium one.

Remaining engine-specific features stay behind explicit seams until the
contract covers them: the draw tool's Cesium surface (stock click actions
cannot be suspended), the annotation drapes (animated materials), share
follow, Cesium post effects and cyber sonar, and data packs (meshes).

Coupling: Cesium-importing files fall from 31 to 27, `viewer` lines
from 1367 to 1234, engine sniffing calls from 14 to 0.
This commit is contained in:
German Khokhlov committed 2026-11-07 08:46:30 +04:00
1 parent 406dd9122e
commit f1ec9d4a22
61 files changed
+823 -1230

No files matched your search

+5 -4
View File
@@ -6,9 +6,10 @@ import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { createAnnotationEngine } from './annotationEngine.js';
import { _resetRenderGovernorForTest } from '../renderGovernor.js';
import { cameraOnlyEngine } from '../testSupport/viewerEngine.mjs';
function viewerAt(lat, lon, height = 20_000) {
return {
return cameraOnlyEngine({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -16,7 +17,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
@@ -45,7 +46,7 @@ function harness(place = null) {
const resolve = (target, viewer, extra = {}) =>
resolveAnnotationTarget({
placeSearch,
viewer,
engine: viewer,
target,
footprint: true,
deferFootprint: true,
@@ -287,7 +288,7 @@ test('the engine keeps every part on the mark, drawn at once or upgraded', async
destroy() {},
};
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async ({ target }) =>
target === 'now'
+27 -70
View File
@@ -1,8 +1,6 @@
import { isUnavailableCapability } from '../sources/capability.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import * as geo from '../geo/index.js';
import { isGlobeEngine } from '../globe/contract.js';
import { greatCircleMeters } from '../geoDistance.js';
import {
holdContinuousRender,
@@ -22,16 +20,6 @@ import {
} from '../sources/phaseTiming.js';
import { formatDistanceText } from '../data/distanceFormat.js';
// Dev convenience: expose the app's Cesium instance for console/preview probing
// (single shared module instance — avoids dual-Cesium state bugs when testing).
// A getter, because the production build's Cesium global loads only with the
// first Cesium globe.
if (typeof window !== 'undefined' && !('__CESIUM__' in window))
Object.defineProperty(window, '__CESIUM__', {
configurable: true,
get: () => Cesium,
});
/**
* Annotation engine — the voice agent's "whiteboard" over the 3D world.
*
@@ -148,7 +136,7 @@ const DETACHED_RENDERER = Object.freeze({
export function createAnnotationEngine({
placeSearch = defaultGeospatial,
viewer = null,
globe = null,
renderer = DETACHED_RENDERER,
outlineRetryDelaysMs = OUTLINE_RETRY_DELAYS_MS,
resolveTarget = resolveAnnotationTarget,
@@ -428,7 +416,7 @@ export function createAnnotationEngine({
* @returns {Promise<{ok, drawn, failed, ids, results}>}
*/
async function annotate(requests, opts = {}) {
if (destroyed || !viewer)
if (destroyed || !globe)
return {
ok: false,
drawn: 0,
@@ -437,7 +425,7 @@ export function createAnnotationEngine({
results: [],
error: destroyed
? 'destroyed'
: 'Annotations are drawn on the Cesium globe only.',
: 'Annotations are drawn on a globe only.',
};
const list = (Array.isArray(requests) ? requests : [requests]).map(
promoteStreetHighlight,
@@ -914,7 +902,7 @@ export function createAnnotationEngine({
const type = normalizeType(spec?.type);
// MANUAL geometry (drawTool.js): the person clicked the vertices, so there is
// nothing to resolve. Same record shapes as a resolved spec, source 'manual'.
if (isManualSpec(spec, type)) return resolveManualSpec(spec, type, viewer);
if (isManualSpec(spec, type)) return resolveManualSpec(spec, type, globe);
if (type === 'route') {
const points = Array.isArray(spec.points) ? spec.points : [];
if (points.length < 2)
@@ -925,7 +913,7 @@ export function createAnnotationEngine({
const name = pt.target ?? pt.name ?? null;
const r = await resolveTarget({
placeSearch,
viewer,
engine: globe,
target: name,
latitude: pt.latitude,
longitude: pt.longitude,
@@ -983,7 +971,7 @@ export function createAnnotationEngine({
if (type === 'arrow') {
const from = await resolveTarget({
placeSearch,
viewer,
engine: globe,
target: spec.target,
latitude: spec.latitude,
longitude: spec.longitude,
@@ -995,7 +983,7 @@ export function createAnnotationEngine({
});
const to = await resolveTarget({
placeSearch,
viewer,
engine: globe,
target: spec.toTarget,
latitude: spec.toLatitude,
longitude: spec.toLongitude,
@@ -1028,7 +1016,7 @@ export function createAnnotationEngine({
type === 'area' ? spec.footprint !== false : Boolean(spec.footprint);
return resolveTarget({
placeSearch,
viewer,
engine: globe,
target: spec.target,
latitude: spec.latitude,
longitude: spec.longitude,
@@ -1669,7 +1657,7 @@ export function createAnnotationEngine({
/** Fly the camera to one mark; a line is framed whole, not by its start. */
function frame(id) {
const anno = annotations.get(id);
if (!anno || !viewer) return false;
if (!anno || !globe) return false;
if (anno.type === 'route' && anno.path?.length) {
const ring = anno.path.map((p) => [p.lon, p.lat]);
// Unwrap around the first vertex, as ringRange does, so a line across
@@ -1739,7 +1727,7 @@ export function createAnnotationEngine({
const cart = points.map((p) =>
geo.cartesian3.fromDegrees(p.lon, p.lat, p.height || 0),
);
const sphere = Cesium.BoundingSphere.fromPoints(cart);
const sphere = geo.boundingSphere.fromPoints(cart);
flyToSphere(sphere.center, sphere.radius, {
pitch: geo.math.toRadians(-35),
range: Math.max(900, sphere.radius * 2.6),
@@ -1755,23 +1743,7 @@ export function createAnnotationEngine({
function isPointOnScreen(p) {
try {
const pos = geo.cartesian3.fromDegrees(p.lon, p.lat, p.height || 0);
if (isGlobeEngine(viewer)) return engineSeesPoint(viewer, pos);
const camera = viewer.camera;
const cv = camera.frustum.computeCullingVolume(
camera.position,
camera.direction,
camera.up,
);
if (
cv.computeVisibility(new Cesium.BoundingSphere(pos, 1)) ===
Cesium.Intersect.OUTSIDE
)
return false;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.position,
);
return occluder.isPointVisible(pos);
return engineSeesPoint(globe, pos);
} catch {
return true;
}
@@ -1810,28 +1782,13 @@ export function createAnnotationEngine({
}
/**
* Fly to a sphere keeping the camera's heading: Cesium's
* flyToBoundingSphere on a viewer, the contract's flyToSphere on a globe
* engine (the same offset semantics).
* Fly to a sphere keeping the camera's heading (the contract's
* flyToSphere: Cesium's flyToBoundingSphere offset).
*/
function flyToSphere(center, radius, { pitch, range, duration }) {
if (isGlobeEngine(viewer)) {
viewer.camera.flyToSphere(
{ center, radius },
{ heading: viewer.camera.pose().heading, pitch, range, duration },
);
return;
}
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(center, radius),
{
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading,
pitch,
range,
),
duration,
},
globe.camera.flyToSphere(
{ center, radius },
{ heading: globe.camera.pose().heading, pitch, range, duration },
);
}
@@ -1861,7 +1818,7 @@ export function createAnnotationEngine({
generation++;
const previous = renderer;
renderer = DETACHED_RENDERER;
viewer = null;
globe = null;
for (const anno of annotations.values()) {
anno.pendingOutline = false;
try {
@@ -1877,13 +1834,13 @@ export function createAnnotationEngine({
}
},
/**
* Draw the board on a globe: `viewer` and the `renderer` built for it.
* Marks kept while no globe drew them appear again as they were.
* Draw the board on a globe: its `engine` and the `renderer` built for
* it. Marks kept while no globe drew them appear again as they were.
*/
attachRenderer({ viewer: nextViewer, renderer: nextRenderer }) {
attachRenderer({ engine: nextGlobe = null, renderer: nextRenderer }) {
if (destroyed) return;
engine.detachRenderer();
viewer = nextViewer;
globe = nextGlobe;
renderer = nextRenderer ?? DETACHED_RENDERER;
for (const anno of annotations.values()) {
try {
@@ -2093,7 +2050,7 @@ export function createAnnotationEngine({
}) {
if (destroyed) return;
try {
viewer?.camera.flyTo({
globe?.camera.flyTo({
destination: geo.cartesian3.fromDegrees(lon, lat, height),
orientation: {
heading: geo.math.toRadians(heading),
@@ -2371,7 +2328,7 @@ function manualPairs(list) {
* (not synthesized) outline so it drapes solid; a line is a `route` with mode
* 'manual', its length as distance and no travel time; a pin is a point.
*/
function resolveManualSpec(spec, type, viewer) {
function resolveManualSpec(spec, type, globe) {
if (type === 'route') {
// height 0 is a placeholder, not a placement: the world renderer draws a
// route with clampToGround + CESIUM_3D_TILE classification, so the line is
@@ -2412,7 +2369,7 @@ function resolveManualSpec(spec, type, viewer) {
return {
lon,
lat,
height: sampleGroundHeight(viewer, lon, lat),
height: sampleGroundHeight(globe, lon, lat),
ring,
...(polygons ? { polygons } : {}),
footprintKind: 'area',
@@ -2427,7 +2384,7 @@ function resolveManualSpec(spec, type, viewer) {
return {
lon,
lat,
height: sampleGroundHeight(viewer, lon, lat),
height: sampleGroundHeight(globe, lon, lat),
ring: null,
source: 'manual',
};
@@ -2490,8 +2447,8 @@ function appendDistance(baseLabel, distM) {
/**
* Whether a globe engine shows a world point: in front of the camera, inside
* the canvas and on the near side of the globe (what the Cesium path's
* culling volume and ellipsoid occluder answer).
* the canvas and on the near side of the globe (what Cesium's culling
* volume and ellipsoid occluder answer).
*/
function engineSeesPoint(engine, position) {
if (!engine.projector.horizonVisible(position)) return false;
+42 -41
View File
@@ -241,7 +241,7 @@ test('outline queue: an 8-spec batch keeps at most two FIFO upgrades in flight',
};
};
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget,
});
@@ -313,7 +313,7 @@ test('outline queue: clear drops queued-but-unstarted upgrades without a later f
}),
});
engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget,
});
@@ -379,7 +379,7 @@ test('retry: HTTP 429 Retry-After 5s gets one ladder-spaced retry; a second 429
});
const resolved = await resolveAnnotationTarget({
viewer: {},
globe: {},
target: 'PT2 rate-limit fixture',
latitude: 12.345,
longitude: 67.89,
@@ -453,7 +453,7 @@ test('retry: a plain HTTP 500 still exhausts the existing 8s/25s transient ladde
});
const resolved = await resolveAnnotationTarget({
viewer: {},
globe: {},
target: 'PT2 transient fixture',
latitude: -12.345,
longitude: -67.89,
@@ -603,8 +603,8 @@ test('outline upgrade updates the rendered element in place without remove/add',
remove() { calls.remove += 1; },
sync() {},
};
const viewer = {};
const engine = createAnnotationEngine({ viewer, renderer, placeSearch: createStandalonePlaceSearch({ resolveApiKey: () => 'unit-test-key' }) });
const globe = {};
const engine = createAnnotationEngine({ globe, renderer, placeSearch: createStandalonePlaceSearch({ resolveApiKey: () => 'unit-test-key' }) });
const upgraded = new Promise((resolve) => engine.onOutlineEvent(resolve));
const result = await engine.annotate([{
@@ -715,7 +715,7 @@ test('fresh async building batch reserves slots together and releases failed/cle
t.after(() => _resetRenderGovernorForTest());
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async ({ target }) => ({
...BUILDING_FP,
@@ -762,7 +762,7 @@ test('outline workers retain completion ownership and clear cancels resolved-but
const h = controlledBuildingRenderer();
const started = [];
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async ({ target }) => ({
...FIXED_POINT,
@@ -805,7 +805,7 @@ test('building recaption timeout retains old route and a newer replacement owns
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async () => ({ ...BUILDING_FP }),
});
@@ -860,7 +860,7 @@ test('replacement cleanup failure still removes the old route and retains failed
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
globe: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
});
const initial = engine.annotate([{ type: 'area', target: 'Capitol', label: 'Old' }]);
await flushMicrotasks();
@@ -905,7 +905,7 @@ test('identical refresh revokes an older building replacement even if cancellati
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
globe: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
});
const initial = engine.annotate([{ type: 'area', target: 'Capitol', label: 'Old' }]);
await flushMicrotasks(); h.pending[0].finish(); await initial;
@@ -936,7 +936,7 @@ test('successful replacement survives failed old-route retirement and keeps clea
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
globe: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
});
const initial = engine.annotate([{ type: 'area', target: 'Capitol', label: 'Old' }]);
await flushMicrotasks(); h.pending[0].finish(); await initial;
@@ -975,7 +975,7 @@ test('pending fresh predecessor failure cannot erase a newer building intent', a
globalThis.requestAnimationFrame = (callback) => { frames.push(callback); return frames.length; };
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
globe: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
});
const first = engine.annotate([{ type: 'area', target: 'Capitol', label: 'First' }]);
await flushMicrotasks();
@@ -1004,7 +1004,7 @@ test('duplicate pending building results reflect final failure rather than a dea
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
globe: {}, renderer: h.renderer, resolveTarget: async () => ({ ...BUILDING_FP }),
});
const spec = { type: 'area', target: 'Capitol', label: 'Same' };
const batch = engine.annotate([spec, spec]);
@@ -1023,7 +1023,7 @@ test('separate duplicate callers observe the original building install outcome',
for (const outcome of ['installed', 'failed', 'timeout', 'clear']) {
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async () => ({ ...BUILDING_FP }),
});
@@ -1077,7 +1077,7 @@ test('a duplicate joins the physical deferred install but not another outline lo
const h = controlledBuildingRenderer();
let lookups = 0;
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async () => ({
...FIXED_POINT,
@@ -1119,7 +1119,7 @@ test('duplicate-replacement: a renderer throw leaves no phantom mark and no leak
const { renderer, failAddOnce } = throwingRendererHarness();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
@@ -1173,7 +1173,7 @@ test('fresh path: a renderer throw is rolled back the same way', async (t) => {
const { renderer, failAddOnce } = throwingRendererHarness();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
@@ -1237,7 +1237,7 @@ test('fresh path: a throw AFTER partial renderer state leaves nothing on the boa
const { renderer, failAddOnce, live } = partialStateRendererHarness();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
@@ -1278,7 +1278,7 @@ test('duplicate-replacement: a throw AFTER partial renderer state leaves nothing
const { renderer, failAddOnce, live } = partialStateRendererHarness();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
@@ -1335,7 +1335,7 @@ test('destroy releases the renderer and prevents subsequent annotation work', as
renderer.destroy = () => {
destroyed++;
};
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
const drawn = await engine.annotate([
{ type: 'pin', longitude: -97.74, latitude: 30.27 },
]);
@@ -1360,7 +1360,7 @@ test('a late annotation resolver cannot redraw after destruction', async (t) =>
let release;
let signal;
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: (options) => {
signal = options.signal;
@@ -1385,9 +1385,10 @@ test('caller cancellation prevents a late annotation and camera mutation', async
let resolverSignal;
let flights = 0;
const engine = createAnnotationEngine({
viewer: {
globe: {
camera: {
flyToBoundingSphere() {
pose: () => ({ heading: 0 }),
flyToSphere() {
flights += 1;
},
},
@@ -1424,7 +1425,7 @@ test('only an explicit navigation request permits resolving distant annotation t
renderer.destroy = () => {};
const received = [];
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async (options) => {
received.push(options);
@@ -1448,7 +1449,7 @@ test('recaption inherits outline credit from borrowed geometry rather than its n
const { renderer } = fakeRenderer();
let first = true;
const ring = [[-99,31],[-98.99,31],[-98.99,31.01],[-99,31]];
const engine = createAnnotationEngine({ viewer: {}, renderer,
const engine = createAnnotationEngine({ globe: {}, renderer,
resolveTarget: async () => {
if (first) { first = false; return { ...FIXED_POINT, ring, footprintKind: 'area', outlineCredit: 'tiles' }; }
return { ...FIXED_POINT, source: 'osm-local', resolveOutline: async () => null };
@@ -1471,7 +1472,7 @@ test('hand-drawn marks: one mark can be hidden, renamed, recoloured, framed and
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: { camera: { heading: 0, flyToBoundingSphere: (sphere) => flights.push(sphere) } },
globe: { camera: { pose: () => ({ heading: 0 }), flyToSphere: (sphere) => flights.push(sphere) } },
renderer,
});
let changes = 0;
@@ -1540,10 +1541,10 @@ test('hand-drawn marks: remove, hide, clear, expiry and framing have their effec
const { renderer, calls } = fakeRenderer();
const flights = [];
const engine = createAnnotationEngine({
viewer: {
globe: {
camera: {
heading: 0,
flyToBoundingSphere: (sphere) => flights.push(sphere),
pose: () => ({ heading: 0 }),
flyToSphere: (sphere) => flights.push(sphere),
},
},
renderer,
@@ -1638,7 +1639,7 @@ test('hand-drawn marks: a voice mark or a hidden mark is not taken as their dupl
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
await engine.annotate(
[
{
@@ -1691,7 +1692,7 @@ test('hand-drawn marks: only a manual mark can be restyled', async (t) => {
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget: async () => ({ ...FIXED_POINT }),
});
@@ -1706,7 +1707,7 @@ test('a drawn line that rounds up to the next unit is labelled in it, not as 100
installAnimationFrameStubs(t);
const labels = [];
const renderer = { add(anno) { labels.push(anno.label); }, update() {}, remove() {}, sync() {}, destroy() {} };
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
const metresPerDegree = (6371.0088 * 1000 * Math.PI) / 180;
for (const metres of [994, 996, 9940, 9960]) {
await engine.annotate([
@@ -1722,7 +1723,7 @@ test('hand-drawn marks: two unnamed pins close together are two pins, whatever t
_resetRenderGovernorForTest();
t.after(() => _resetRenderGovernorForTest());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
const pin = (lon, color) => ({ type: 'pin', manual: true, latitude: 30.27, longitude: lon, label: '', color });
await engine.annotate([pin(-97.74, 'primary')], { persist: true });
await engine.annotate([pin(-97.7402, 'primary')], { persist: true });
@@ -1740,7 +1741,7 @@ test('hand-drawn marks: hiding a mark before its first frame takes it off at onc
t.after(() => _resetRenderGovernorForTest());
let syncs = 0;
const renderer = { add() {}, update() {}, remove() {}, sync() { syncs += 1; }, destroy() {} };
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
const before = syncs;
@@ -1759,7 +1760,7 @@ test('hand-drawn marks: with every mark hidden the scene idles, and showing one
let renders = 0;
installRenderGovernor({ scene: { requestRenderMode: true, requestRender: () => (renders += 1) } });
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
await engine.annotate([
{ type: 'pin', manual: true, latitude: 1, longitude: 1 },
{ type: 'pin', manual: true, latitude: 2, longitude: 2 },
@@ -1784,7 +1785,7 @@ test('hand-drawn marks: a restyle the renderer cannot draw takes the mark off an
const { renderer, failAddOnce } = throwingRendererHarness();
let syncs = 0;
renderer.sync = () => (syncs += 1);
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
let changes = 0;
@@ -1811,7 +1812,7 @@ test('hand-drawn marks: a mark shown again right after it was drawn appears at o
});
const tick = () => queued.splice(0).forEach((callback) => callback());
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({ viewer: {}, renderer });
const engine = createAnnotationEngine({ globe: {}, renderer });
await engine.annotate([{ type: 'pin', manual: true, latitude: 1, longitude: 1 }], { persist: true });
const [mark] = engine.list();
engine.setHidden(mark.id, true);
@@ -1832,7 +1833,7 @@ test('removing one mark whose cleanup fails keeps it addressable for a retry', a
calls.remove += 1;
if (failRemove) throw new Error('renderer remove failed');
};
const engine = createAnnotationEngine({ viewer: { camera: { heading: 0 } }, renderer });
const engine = createAnnotationEngine({ globe: { camera: { pose: () => ({ heading: 0 }) } }, renderer });
await engine.annotate([
{ type: 'pin', manual: true, latitude: 30.27, longitude: -97.74, label: 'Camp' },
], { persist: true });
@@ -1850,7 +1851,7 @@ test('a building install in the batch does not re-judge marks that never install
installAnimationFrameStubs(t);
const h = controlledBuildingRenderer();
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: h.renderer,
resolveTarget: async ({ target }) =>
target === 'Tower' ? { ...BUILDING_FP, lon: -97.7 } : { ...FIXED_POINT },
@@ -1873,7 +1874,7 @@ test('plain recaption keeps the old mark addressable when its removal throws', a
installAnimationFrameStubs(t);
const { renderer } = fakeRenderer();
const engine = createAnnotationEngine({
viewer: {}, renderer, resolveTarget: async () => ({ ...FIXED_POINT }),
globe: {}, renderer, resolveTarget: async () => ({ ...FIXED_POINT }),
});
await engine.annotate([{ type: 'point', target: 'Capitol', label: 'Capitol' }]);
const old = engine.list()[0];
+18 -17
View File
@@ -19,6 +19,7 @@ import {
refineScope,
isGroundsLikeAsk,
} from './annotationResolver.js';
import { cameraOnlyEngine } from '../testSupport/viewerEngine.mjs';
// Build a square way of ~`areaM2` centred `dLatM`/`dLonM` metres from an anchor,
// in Overpass `out geom` element shape ({ tags, geometry: [{lat,lon}...] }).
@@ -157,7 +158,7 @@ test('refineScope: entityKind refines only an unresolved (auto) scope', () => {
});
function closeViewportViewer() {
return {
return cameraOnlyEngine({
camera: {
positionCartographic: {
latitude: 30.2672 * Math.PI / 180,
@@ -165,7 +166,7 @@ function closeViewportViewer() {
height: 1000,
},
},
};
});
}
function geocodePayload({ lat, lon, types, label }) {
@@ -221,7 +222,7 @@ test('ask-side admin bypass: "the Texas Capitol" recovers near-view despite a fa
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: 'the Texas Capitol',
});
@@ -245,7 +246,7 @@ test('ask-side admin bypass: explicit "state of Texas" skips recovery and proxim
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: 'state of Texas',
});
@@ -286,7 +287,7 @@ for (const fixture of [
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: fixture.target,
});
@@ -312,7 +313,7 @@ test('ask-side admin bypass: bare "Texas" remains on the guarded recovery path',
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: 'Texas',
});
@@ -351,7 +352,7 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township
for (const target of fixtures.keys()) {
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target,
});
assert.ok(resolved);
@@ -369,11 +370,11 @@ test('ask-side admin bypass: admin level 2/3 result types never grant a township
// Synthetic footprints reproduce the real Capitol/YOTEL selection without live APIs.
const CAPITOL_ANCHOR = { lat: 38.8899389, lon: -77.0090505 };
function capitolViewer() {
return { camera: { positionCartographic: {
return cameraOnlyEngine({ camera: { positionCartographic: {
latitude: CAPITOL_ANCHOR.lat * Math.PI / 180,
longitude: CAPITOL_ANCHOR.lon * Math.PI / 180,
height: 1000,
} } };
} } });
}
function installCapitolMocks(t, elements, components = [
{ long_name: 'Washington', types: ['locality', 'political'] },
@@ -401,7 +402,7 @@ for (const [target, deferFootprint] of [
const capitol = squareWay(CAPITOL_ANCHOR, 0, 0, 20000, { building: 'yes', name: 'United States Capitol' });
const hotel = squareWay(CAPITOL_ANCHOR, 620, -140, 3000, { building: 'yes', tourism: 'hotel', name: 'YOTEL Washington DC' });
installCapitolMocks(t, [hotel, capitol]);
const result = await resolveAnnotationTarget({ viewer: capitolViewer(), target, entityKind: 'building', footprint: true, deferFootprint });
const result = await resolveAnnotationTarget({ engine: capitolViewer(), target, entityKind: 'building', footprint: true, deferFootprint });
assert.ok(result);
const outline = deferFootprint ? await result.resolveOutline() : result;
assert.deepEqual(outline.ring, capitol.geometry.map(p => [p.lon, p.lat]));
@@ -412,7 +413,7 @@ for (const [target, deferFootprint] of [
test('address-only landmark without a matching outline keeps its geocoded point', async t => {
const hotel = squareWay(CAPITOL_ANCHOR, 620, -140, 3000, { building: 'yes', tourism: 'hotel', name: 'YOTEL Washington DC' });
installCapitolMocks(t, [hotel]);
const result = await resolveAnnotationTarget({ viewer: capitolViewer(), target: 'US Capitol building, Washington', entityKind: 'building', footprint: true, deferFootprint: true });
const result = await resolveAnnotationTarget({ engine: capitolViewer(), target: 'US Capitol building, Washington', entityKind: 'building', footprint: true, deferFootprint: true });
assert.ok(result);
assert.deepEqual([result.lat, result.lon], [CAPITOL_ANCHOR.lat, CAPITOL_ANCHOR.lon]);
assert.equal(await result.resolveOutline(), null);
@@ -422,7 +423,7 @@ test('missing address components do not turn a formatted city address into the l
const capitol = squareWay(CAPITOL_ANCHOR, 0, 0, 20000, { building: 'yes', name: 'United States Capitol' });
const hotel = squareWay(CAPITOL_ANCHOR, 620, -140, 3000, { building: 'yes', name: 'YOTEL Washington DC' });
installCapitolMocks(t, [hotel, capitol], []);
const result = await resolveAnnotationTarget({ viewer: capitolViewer(), target: 'United States Capitol building', footprint: true });
const result = await resolveAnnotationTarget({ engine: capitolViewer(), target: 'United States Capitol building', footprint: true });
assert.deepEqual(result.ring, capitol.geometry.map(p => [p.lon, p.lat]));
});
@@ -430,7 +431,7 @@ test('a genuine geocoded feature name still canonicalizes an alternate user name
const capitol = squareWay(CAPITOL_ANCHOR, 0, 0, 20000, { building: 'yes', name: 'United States Capitol' });
const decoy = squareWay(CAPITOL_ANCHOR, 620, -140, 3000, { building: 'yes', name: 'Congress meeting building' });
installCapitolMocks(t, [decoy, capitol], [{ long_name: 'United States Capitol', types: ['landmark'] }]);
const result = await resolveAnnotationTarget({ viewer: capitolViewer(), target: 'Congress meeting building', footprint: true });
const result = await resolveAnnotationTarget({ engine: capitolViewer(), target: 'Congress meeting building', footprint: true });
assert.deepEqual(result.ring, capitol.geometry.map(p => [p.lon, p.lat]));
});
@@ -479,7 +480,7 @@ test('keyless: a key that geocodes to nothing still anchors the annotation', asy
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: 'Lady Bird Lake',
});
@@ -534,7 +535,7 @@ test('keyless: OSM matching uses the feature\'s canonical name, not the user\'s
});
const resolved = await resolveAnnotationTarget({
viewer: closeViewportViewer(),
engine: closeViewportViewer(),
target: 'the monument near the Texas Capitol, Austin',
footprint: true,
});
@@ -581,11 +582,11 @@ test('keyless: a Photon outage is not remembered as "no such place"', async (t)
});
const target = 'Waller Creek';
assert.equal(await resolveAnnotationTarget({ viewer: closeViewportViewer(), target }), null);
assert.equal(await resolveAnnotationTarget({ engine: closeViewportViewer(), target }), null);
const duringOutage = requests.length;
photonReachable = true;
const retried = await resolveAnnotationTarget({ viewer: closeViewportViewer(), target });
const retried = await resolveAnnotationTarget({ engine: closeViewportViewer(), target });
assert.ok(retried, 'the same target must resolve once the network is back');
assert.deepEqual([retried.lat, retried.lon], [30.2665, -97.7385]);
+5 -5
View File
@@ -47,7 +47,7 @@ test('the marks survive a globe leaving and are drawn again on the next one', as
withAnimationFrames(t);
const log = [];
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: recordingRenderer(log, 'cesium'),
resolveTarget: async () => ({ ...BUILDING }),
});
@@ -69,7 +69,7 @@ test('the marks survive a globe leaving and are drawn again on the next one', as
log.length = 0;
engine.attachRenderer({
viewer: {},
engine: {},
renderer: recordingRenderer(log, 'next'),
});
assert.deepEqual(log, ['next add Capitol']);
@@ -83,13 +83,13 @@ test('detaching twice and attaching over an attached globe release each drawing
withAnimationFrames(t);
const log = [];
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: recordingRenderer(log, 'a'),
});
engine.detachRenderer();
engine.detachRenderer();
engine.attachRenderer({ viewer: {}, renderer: recordingRenderer(log, 'b') });
engine.attachRenderer({ viewer: {}, renderer: recordingRenderer(log, 'c') });
engine.attachRenderer({ engine: {}, renderer: recordingRenderer(log, 'b') });
engine.attachRenderer({ engine: {}, renderer: recordingRenderer(log, 'c') });
assert.deepEqual(log, ['a destroy', 'b destroy']);
engine.destroy();
});
+21 -14
View File
@@ -67,15 +67,17 @@ const PREVIEW = DRAW_COLOR_CSS;
* through the actions it gives `connect`, which returns their disconnect.
* A row's fly-to is an immediate navigation through `navigation`, like
* Import's, so Cockpit can refuse it and a running orbit or follow lets go.
* The globe it draws on is a Cesium `viewer` or a draw `surface` factory
* (`surface({ session, cursor })`: the input and preview of a globe without
* a viewer, src/annotations/drawInputNavara.js), which gets the open shape
* and the rubber band's end as live getters.
* @param {{viewer?: Cesium.Viewer, surface?: Function, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* The globe it draws on is a Cesium `viewer` (with its `engine`, which
* answers the picks) or a draw `surface` factory (`surface({ session,
* cursor })`: the input and preview of a globe without a viewer,
* src/annotations/drawInputNavara.js), which gets the open shape and the
* rubber band's end as live getters.
* @param {{viewer?: Cesium.Viewer, engine?: object, surface?: Function, annotations: {annotate: Function, clear: Function}, navigation?: object, publish?: Function, connect?: Function}} deps
* @returns {{destroy: Function}|null}
*/
export function initDrawTool({
viewer = null,
engine = null,
surface: makeSurface = null,
annotations,
navigation = null,
@@ -119,7 +121,7 @@ export function initDrawTool({
const live = { session: () => session, cursor: () => cursor };
const surface = makeSurface
? makeSurface(live)
: cesiumDrawSurface(viewer, live);
: cesiumDrawSurface(viewer, engine, live);
const present = () =>
publish({
@@ -485,7 +487,7 @@ export function initDrawTool({
* click actions on its own handler (select, track); they are borrowed while a
* sketch is open and given back on the way out.
*/
function cesiumDrawSurface(viewer, live) {
function cesiumDrawSurface(viewer, engine, live) {
const previewEntities = [];
const dataSource = new Cesium.CustomDataSource(PREVIEW_DATA_SOURCE_NAME);
// `add()` resolves on the NEXT tick, so an init-then-immediate-destroy would
@@ -526,12 +528,15 @@ function cesiumDrawSurface(viewer, live) {
});
return {
canvas: viewer.scene.canvas,
/** The world point under a canvas position, or null. */
/** The world point under a canvas position (the engine's picks), or null. */
pick(position) {
const canvas = viewer.scene.canvas;
const w = canvas.clientWidth || canvas.width || 1;
const h = canvas.clientHeight || canvas.height || 1;
return pickWorldFromScreen(viewer, position.x / w, position.y / h);
if (!engine) return null;
const { width, height } = engine.host.size();
return pickWorldFromScreen(
engine,
position.x / (width || 1),
position.y / (height || 1),
);
},
/** Show the open shape (null: none) in `color`. */
sync(session, color) {
@@ -657,8 +662,8 @@ function cesiumDrawSurface(viewer, live) {
* The Draw control for the page session. The marks live on the annotation
* board and the chosen shape and colour here; the drawing tool itself (its
* preview, click handler and Escape/Enter keys) belongs to the attached
* globe. `attachScene({ viewer, navigation })` starts the tool on a Cesium
* viewer, `attachScene({ surface, navigation })` on a globe without one
* globe. `attachScene({ viewer, engine, navigation })` starts the tool on
* a Cesium viewer, `attachScene({ surface, navigation })` on a globe without one
* (Navara: src/annotations/drawInputNavara.js), with the shape and colour
* last chosen; `detachScene()` ends it, an open shape included. Without a
* globe the controls answer nothing. Same handle as initDrawTool's
@@ -731,6 +736,7 @@ export function createSessionDrawTool({
whenSettled: () => inner?.whenSettled() ?? settled,
attachScene({
viewer = null,
engine = null,
surface = null,
navigation: next = navigation,
} = {}) {
@@ -740,6 +746,7 @@ export function createSessionDrawTool({
if (!viewer && !surface) return;
inner = initDrawTool({
viewer,
engine,
surface,
annotations,
navigation,
+1 -1
View File
@@ -53,7 +53,7 @@ test('the engine resolves manual geometry before any name resolution', () => {
'async function resolveSpec(spec, signal) {',
);
const manualAt = engine.indexOf(
'if (isManualSpec(spec, type)) return resolveManualSpec(spec, type, viewer);',
'if (isManualSpec(spec, type)) return resolveManualSpec(spec, type, globe);',
resolveAt,
);
const routeAt = engine.indexOf("if (type === 'route') {", resolveAt);
+3 -2
View File
@@ -24,9 +24,10 @@ import { createScreenAnnotationRenderer } from './screenAnnotationRenderer.js';
*/
export function createHybridAnnotationRenderer(
viewer,
{ screen: screenOptions, world: worldRenderer, screenScene } = {},
{ screen: screenOptions, world: worldRenderer, screenScene, engine } = {},
) {
const world = worldRenderer ?? createWorldAnnotationRenderer(viewer);
const world =
worldRenderer ?? createWorldAnnotationRenderer(viewer, { engine });
const screen = createScreenAnnotationRenderer(
screenScene ?? viewer,
screenOptions,
@@ -5,11 +5,18 @@ import { createPinia } from 'pinia';
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
import { createCesiumCredits } from '../globe/cesium/credits.js';
/** The engine fakeViewer built for each viewer double (its credits). */
const enginesOf = new WeakMap();
/** A hybrid renderer whose screen board is presented to its own store. */
function hybridWithBoard(viewer) {
const store = useScreenAnnotationsStore(createPinia());
const renderer = createHybridAnnotationRenderer(viewer, { screen: { store } });
const renderer = createHybridAnnotationRenderer(viewer, {
screen: { store },
engine: enginesOf.get(viewer),
});
return { store, renderer };
}
@@ -107,10 +114,7 @@ function fakeViewer(lon, lat) {
scene.renderRequests += 1;
},
};
return {
dataSources,
frames,
viewer: {
const viewer = {
credits,
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
@@ -130,8 +134,14 @@ function fakeViewer(lon, lat) {
return index >= 0;
},
},
},
};
// The Cesium engine's credits over the viewer's credit display.
const engine = {
credits: createCesiumCredits(viewer).credits,
render: { request: () => scene.requestRender() },
};
enginesOf.set(viewer, engine);
return { dataSources, frames, viewer, engine };
}
function controlledFrames() {
@@ -475,14 +485,14 @@ function workTrace() {
test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => {
installBrowserGlobals(t);
const { viewer, dataSources, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer);
const { viewer, engine, dataSources, frames } = fakeViewer(-99, 31);
const renderer = createHybridAnnotationRenderer(viewer, { engine });
t.after(() => renderer.destroy());
const first = buildingAnnotation('sampled-building');
const second = buildingAnnotation('fallback-building', 0.01);
second.outlineCredit = 'osm';
const otherOwner = {};
showOsmCredit(viewer, otherOwner);
showOsmCredit(engine, otherOwner);
const probes = [];
const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90];
viewer.scene.clampToHeight = (position) => {
@@ -583,7 +593,7 @@ test('buildings share one probe per frame and preserve probe geometry, filtering
'removing the last tile proxy retains the OSM building and other owner');
renderer.remove(second);
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1);
hideOsmCredit(viewer, otherOwner);
hideOsmCredit(engine, otherOwner);
assert.equal(viewer.credits.size, 0);
});
+12 -10
View File
@@ -12,22 +12,25 @@ import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
*/
export function initAnnotations({
viewer,
engine: globe = null,
tileset = null,
placeSearch,
resolver,
}) {
const engine = createSessionAnnotations({ placeSearch, resolver });
engine.attachScene({ viewer, tileset });
engine.attachScene({ viewer, engine: globe, tileset });
return engine;
}
/**
* The page's annotation board, kept across globe engine switches: the marks
* belong to the page session, their drawing to the attached globe.
* `attachScene({ viewer, tileset })` draws the board on a Cesium viewer;
* `attachScene({ engine, renderer })` on a globe engine without a viewer
* (Navara: src/annotations/navaraAnnotationRenderer.js, built by the caller
* so this module never loads it); with neither the marks stay undrawn.
* belong to the page session, their drawing to the attached globe. The board
* works on the globe `engine` (camera, picks, surface); its drawing is the
* `renderer` built for that engine (Navara:
* src/annotations/navaraAnnotationRenderer.js, built by the caller so this
* module never loads it), or on a Cesium `viewer` the hybrid renderer built
* here. `attachScene({ engine, viewer, tileset })` or
* `attachScene({ engine, renderer })`; with neither the marks stay undrawn.
* `detachScene()` releases the drawing and keeps the marks.
*/
export function createSessionAnnotations({ placeSearch, resolver }) {
@@ -41,8 +44,7 @@ export function createSessionAnnotations({ placeSearch, resolver }) {
engine: globe = null,
renderer = null,
} = {}) => {
if (!viewer && globe && renderer)
return engine.attachRenderer({ viewer: globe, renderer });
if (renderer) return engine.attachRenderer({ engine: globe, renderer });
if (!viewer) return engine.detachRenderer();
// World-space footprint draping; clamped marks can use the photoreal tiles.
if (tileset) {
@@ -53,8 +55,8 @@ export function createSessionAnnotations({ placeSearch, resolver }) {
}
}
engine.attachRenderer({
viewer,
renderer: createHybridAnnotationRenderer(viewer),
engine: globe,
renderer: createHybridAnnotationRenderer(viewer, { engine: globe }),
});
};
engine.detachScene = () => engine.detachRenderer();
+3 -3
View File
@@ -52,7 +52,7 @@ test('outlines sharing an outer ring but not their holes stay two marks', async
footprintKind: 'area',
});
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget,
});
@@ -108,7 +108,7 @@ test('the engine resolves a bare street highlight with its footprint', async (t)
};
};
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer,
resolveTarget,
});
@@ -138,7 +138,7 @@ test('a duplicate that fails to clean up never costs the new outline', async (t)
const stuck = new Set();
const outcomes = [];
const engine = createAnnotationEngine({
viewer: {},
globe: {},
renderer: {
...renderer,
add(anno) {
+13 -11
View File
@@ -28,6 +28,7 @@ import {
createNominatimGate,
} from '../../server/providers/regional/nominatimGate.js';
import { createVoiceAreas } from '../voice/areaActions.js';
import { cameraOnlyEngine } from '../testSupport/viewerEngine.mjs';
const TILES = [6745, 6746].map((y) =>
decodeOpenFreeMapOutlineTile(
@@ -924,15 +925,16 @@ const PLACES = {
},
};
const viewerAt = (lat, lon, height = 4000) => ({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
const viewerAt = (lat, lon, height = 4000) =>
cameraOnlyEngine({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
longitude: (lon * Math.PI) / 180,
height,
},
},
},
});
});
test('default settings: outline, street and building asks send nothing to Overpass', async (t) => {
const prior = process.env.OVERPASS_UPSTREAMS;
@@ -979,9 +981,9 @@ test('default settings: outline, street and building asks send nothing to Overpa
const placeSearch = {
geocode: async (q) => ({ place: PLACES[q] || null, answered: true }),
};
const resolve = async (viewer, args) => {
const resolve = async (engine, args) => {
const result = await resolver.resolveAnnotationTarget({
viewer,
engine,
placeSearch,
footprint: true,
deferFootprint: true,
@@ -1000,7 +1002,7 @@ test('default settings: outline, street and building asks send nothing to Overpa
});
const areas = createVoiceAreas({
viewer: viewerAt(27.7, 85.3, 40_000),
engine: viewerAt(27.7, 85.3, 40_000),
annotationResolver: resolver,
placeSearch,
});
+5 -4
View File
@@ -7,9 +7,10 @@ import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from './resolver.js';
import { polygonsContain } from '../data/adminBoundaries.js';
import { streetFootprint } from './outlineRungs.js';
import { cameraOnlyEngine } from '../testSupport/viewerEngine.mjs';
function viewerAt(lat, lon, height = 20_000) {
return {
return cameraOnlyEngine({
camera: {
positionCartographic: {
latitude: (lat * Math.PI) / 180,
@@ -17,7 +18,7 @@ function viewerAt(lat, lon, height = 20_000) {
height,
},
},
};
});
}
/** A resolver whose boundary lookups and geocoder record every call. */
@@ -47,7 +48,7 @@ function harness(place = null, { outlineRungs } = {}) {
const resolve = (target, viewer, extra = {}) =>
resolveAnnotationTarget({
placeSearch,
viewer,
engine: viewer,
target,
footprint: true,
deferFootprint: true,
@@ -710,7 +711,7 @@ test('configured OSM geometry retains its origin through inline, deferred and ca
});
for (const deferFootprint of [false, true]) {
const result = await resolver.resolveAnnotationTarget({
viewer: viewerAt(31, -99, 3000),
engine: viewerAt(31, -99, 3000),
latitude: 31,
longitude: -99,
target: 'Library',
+66 -147
View File
@@ -14,7 +14,6 @@ import {
nearestPointOnLines,
} from '../sources/featureGeometry.js';
import { defaultGeospatial } from '../search/defaults.js';
import * as Cesium from 'cesium';
import * as geo from '../geo/index.js';
import { lookupNeighborhoodRing } from '../data/neighborhoodPolygons.js';
import {
@@ -46,7 +45,6 @@ import {
import { createOutlineRungs } from './outlineRungs.js';
import { unavailablePlaceSearch } from '../search/placeSearch.js';
import { isPickedWorldPosition } from '../data/scenePick.js';
import { isGlobeEngine } from '../globe/contract.js';
/** Prepare only local dateline outlines for planar admission and centering. */
function localOutlineFrame(fp) {
@@ -180,7 +178,8 @@ export function createAnnotationResolver({
* Resolve a single annotation target to a normalized world anchor.
*
* @param {object} opts
* @param {Cesium.Viewer} opts.viewer
* @param {object} [opts.engine] The globe engine (view bias, screen picks,
* ground heights, credits).
* @param {string} [opts.target] Place name to geocode.
* @param {number} [opts.latitude] Explicit latitude (wins over target).
* @param {number} [opts.longitude] Explicit longitude.
@@ -202,7 +201,7 @@ export function createAnnotationResolver({
*/
async function resolveAnnotationTarget({
placeSearch = unavailablePlaceSearch,
viewer,
engine,
target,
latitude,
longitude,
@@ -273,7 +272,7 @@ export function createAnnotationResolver({
!NON_ADMIN_ENTITY_KINDS.has(entityKind)
) {
const center =
pickWorldFromScreen(viewer, 0.5, 0.5) || viewportProximity(viewer);
pickWorldFromScreen(engine, 0.5, 0.5) || viewportProximity(engine);
bundledCenter = center;
const admin = await findAdminArea(trace.query, { near: center }).catch(
() => null,
@@ -282,7 +281,7 @@ export function createAnnotationResolver({
if (admin && !askNamesAdmin && isCoarseCityShape(admin))
coarseCityShape = admin;
else if (admin)
return bundledAdminTarget(viewer, admin, trace.query, signal);
return bundledAdminTarget(engine, admin, trace.query, signal);
// Bundled US places and neighborhoods named at or near the view. A
// campus, grounds or monument ask ("Stanford" as a compound, "the
// Capitol grounds") wants that feature, not a district of its name,
@@ -290,10 +289,10 @@ export function createAnnotationResolver({
if (intent !== 'around_the_thing' && !isMonumentLikeQuery(trace.query)) {
const area = await bundledAreaNear(trace.query, center, {
entityKind,
viewRadiusKm: viewportProximity(viewer)?.radiusKm ?? null,
viewRadiusKm: viewportProximity(engine)?.radiusKm ?? null,
});
signal?.throwIfAborted();
if (area) return bundledAdminTarget(viewer, area, trace.query, signal);
if (area) return bundledAdminTarget(engine, area, trace.query, signal);
}
}
@@ -301,7 +300,7 @@ export function createAnnotationResolver({
const query = String(target || '').trim();
if (query) {
const center =
pickWorldFromScreen(viewer, 0.5, 0.5) || viewportProximity(viewer);
pickWorldFromScreen(engine, 0.5, 0.5) || viewportProximity(engine);
// Monument / grounds names scatter under Geocoding — try a view-biased Places Text Search FIRST.
// A hit near the view centre is trusted (skips the proximity gate, like the osm-local snap); on a
// miss we fall through to geocode + fetchLocalMonument below. The model's entityKind counts too:
@@ -338,7 +337,7 @@ export function createAnnotationResolver({
if (source !== 'places') {
const geocoded = await geocodePlace(
query,
viewportBias(viewer),
viewportBias(engine),
signal,
placeSearch,
);
@@ -411,7 +410,7 @@ export function createAnnotationResolver({
Number.isFinite(Number(screenY))
) {
const picked = pickWorldFromScreen(
viewer,
engine,
Number(screenX),
Number(screenY),
);
@@ -424,7 +423,7 @@ export function createAnnotationResolver({
if (!Number.isFinite(lat) || !Number.isFinite(lon))
return coarseCityHolds(bundledCenter)
? bundledAdminTarget(viewer, coarseCityShape, trace.query, signal)
? bundledAdminTarget(engine, coarseCityShape, trace.query, signal)
: null;
// Monument/memorial/statue names geocode unreliably — Google scatters them across the city (e.g.
@@ -437,7 +436,7 @@ export function createAnnotationResolver({
(isMonumentLikeQuery(target) || entityKind === 'point_feature')
) {
const center =
pickWorldFromScreen(viewer, 0.5, 0.5) || viewportProximity(viewer);
pickWorldFromScreen(engine, 0.5, 0.5) || viewportProximity(engine);
if (center) {
const mon = await fetchLocalMonument(
center.lat,
@@ -470,7 +469,7 @@ export function createAnnotationResolver({
// footprint resolution below re-checks its own recentered centroid against the same bound — a
// polygon that would drag a good anchor out of plausibility is dropped (the mark stays an
// honest point) rather than rejecting the whole annotation.
const vpGate = viewportProximity(viewer);
const vpGate = viewportProximity(engine);
const gateDrift = (gLat, gLon) => {
if (!vpGate) return null; // no camera info → pass
const driftKm =
@@ -491,7 +490,7 @@ export function createAnnotationResolver({
);
}
return coarseCityHolds(bundledCenter)
? bundledAdminTarget(viewer, coarseCityShape, trace.query, signal)
? bundledAdminTarget(engine, coarseCityShape, trace.query, signal)
: null;
}
}
@@ -581,7 +580,7 @@ export function createAnnotationResolver({
);
signal?.throwIfAborted();
if (ne) {
registerDynamicCredit(viewer, NATURAL_EARTH_CREDIT);
registerDynamicCredit(engine, NATURAL_EARTH_CREDIT);
traceBundledOutline(ne.name, 'natural-earth');
const neCentroid = ringCentroid(ne.ring);
return {
@@ -594,7 +593,7 @@ export function createAnnotationResolver({
lat: neCentroid?.lat ?? lat,
lon: neCentroid?.lon ?? lon,
height: sampleGroundHeight(
viewer,
engine,
neCentroid?.lon ?? lon,
neCentroid?.lat ?? lat,
),
@@ -642,7 +641,7 @@ export function createAnnotationResolver({
signal?.throwIfAborted();
if (admin && !askNamesAdmin && isCoarseCityShape(admin))
coarseCityShape ||= admin;
else if (admin) return bundledAdminOutline(viewer, admin, signal);
else if (admin) return bundledAdminOutline(engine, admin, signal);
}
// A geocoded US city, town or CDP: the Census place that holds it.
if (scope === 'city') {
@@ -652,7 +651,7 @@ export function createAnnotationResolver({
lon,
).catch(() => null);
signal?.throwIfAborted();
if (place) return bundledAdminOutline(viewer, place, signal);
if (place) return bundledAdminOutline(engine, place, signal);
}
// Pure admin: only an admin boundary is correct — never fall back to a
// building/landuse (a city is never a single building).
@@ -676,7 +675,7 @@ export function createAnnotationResolver({
lon,
).catch(() => null);
signal?.throwIfAborted();
if (wof) return bundledAdminOutline(viewer, wof, signal);
if (wof) return bundledAdminOutline(engine, wof, signal);
}
// Else fall through to the OSM admin/place → named-landuse → synthesis ladder. Each
// returns a footprint, null (definitively no polygon), or undefined (transient
@@ -875,7 +874,7 @@ export function createAnnotationResolver({
...(fp.adminLevel ? { adminLevel: fp.adminLevel } : {}),
lat: centroid.lat,
lon: centroid.lon,
height: sampleGroundHeight(viewer, centroid.lon, centroid.lat),
height: sampleGroundHeight(engine, centroid.lon, centroid.lat),
};
};
@@ -891,11 +890,11 @@ export function createAnnotationResolver({
pointLike,
groundsLike,
around: intent === 'around_the_thing',
view: viewportProximity(viewer),
view: viewportProximity(engine),
signal,
credit: (kind) =>
registerDynamicCredit(
viewer,
engine,
kind === 'tiles' ? OPENMAPTILES_CREDIT : OSM_CREDIT,
),
};
@@ -911,7 +910,7 @@ export function createAnnotationResolver({
coarseCityHolds({ lat, lon }) &&
!(result?.ring && !result.synthesized)
)
return bundledAdminOutline(viewer, coarseCityShape, signal);
return bundledAdminOutline(engine, coarseCityShape, signal);
return result;
};
@@ -939,7 +938,7 @@ export function createAnnotationResolver({
}
}
const height = sampleGroundHeight(viewer, lon, lat);
const height = sampleGroundHeight(engine, lon, lat);
// One concise line per target so the resolution path is visible in the browser console.
if (trace.query) {
console.log(
@@ -1004,13 +1003,13 @@ export function createAnnotationResolver({
const COARSE_CITY_MAX_VERTICES = 32;
/** Credit the pack a bundled boundary came from. */
function creditAdminSource(viewer, admin) {
function creditAdminSource(engine, admin) {
const credit = {
'natural-earth': NATURAL_EARTH_CREDIT,
'us-census': US_CENSUS_CREDIT,
wof: WOF_CREDIT,
}[admin.source];
if (credit) registerDynamicCredit(viewer, credit);
if (credit) registerDynamicCredit(engine, credit);
}
/**
@@ -1113,9 +1112,9 @@ export function createAnnotationResolver({
* draw them. Like the Natural Earth rung, it bypasses the scope caps and the
* centroid drift bound: the unit IS the asked scope.
*/
function bundledAdminOutline(viewer, admin, signal) {
function bundledAdminOutline(engine, admin, signal) {
signal?.throwIfAborted();
creditAdminSource(viewer, admin);
creditAdminSource(engine, admin);
traceBundledOutline(admin.name, admin.source, admin.polygons?.length);
const { lat, lon } = admin.label;
return {
@@ -1128,7 +1127,7 @@ export function createAnnotationResolver({
outlineSource: admin.source,
lat,
lon,
height: sampleGroundHeight(viewer, lon, lat),
height: sampleGroundHeight(engine, lon, lat),
};
}
@@ -1158,8 +1157,8 @@ export function createAnnotationResolver({
}
/** A complete resolved target for a bundled administrative unit (no outline pending). */
function bundledAdminTarget(viewer, admin, query, signal) {
const outline = bundledAdminOutline(viewer, admin, signal);
function bundledAdminTarget(engine, admin, query, signal) {
const outline = bundledAdminOutline(engine, admin, signal);
const [west, south, east, north] = admin.bbox;
console.log(
`[Resolver] "${query}": bundled ${admin.kind} "${admin.name}"` +
@@ -2200,7 +2199,7 @@ export function createAnnotationResolver({
return matches;
}
// --- viewer helpers ---------------------------------------------------------
// --- engine helpers ---------------------------------------------------------
/**
* Current view rectangle as a Google `bounds` string `swLat,swLng|neLat,neLng`,
@@ -2216,12 +2215,9 @@ export function createAnnotationResolver({
* Radius is scaled from camera height (a generous proxy for how much ground is on screen), with a
* floor so a super-zoomed-in view doesn't over-reject genuinely nearby places.
*/
function viewportProximity(viewer) {
function viewportProximity(engine) {
try {
// A globe engine (search) or a Cesium viewer (annotations until 1c).
const carto = isGlobeEngine(viewer)
? viewer.camera.pose().cartographic
: viewer?.camera?.positionCartographic;
const carto = engine?.camera.pose().cartographic;
if (!carto) return null;
const lat = geo.math.toDegrees(carto.latitude);
const lon = geo.math.toDegrees(carto.longitude);
@@ -2234,11 +2230,9 @@ export function createAnnotationResolver({
}
/** Exported for searchAndFlyTo (src/locations.js), which shares this bias. */
function viewportBias(viewer) {
function viewportBias(engine) {
try {
const rect = isGlobeEngine(viewer)
? viewer.camera.viewRectangle()
: viewer?.camera?.computeViewRectangle?.();
const rect = engine?.camera.viewRectangle();
if (!rect) return null;
const swLat = geo.math.toDegrees(rect.south).toFixed(4);
const swLng = geo.math.toDegrees(rect.west).toFixed(4);
@@ -2262,14 +2256,14 @@ export function createAnnotationResolver({
* ({ lat, lon, label, types, viewport, distanceM, … }) or null.
*/
async function placesNearViewRecovery(
viewer,
engine,
query,
geocoded = null,
signal = undefined,
placeSearch = defaultGeospatial,
) {
const center =
pickWorldFromScreen(viewer, 0.5, 0.5) || viewportProximity(viewer);
pickWorldFromScreen(engine, 0.5, 0.5) || viewportProximity(engine);
if (!center) return null;
const geocodeFar =
!geocoded ||
@@ -2313,9 +2307,28 @@ export function createAnnotationResolver({
return geo.cartesian3.distance(hit, camera) < Math.max(2, 0.01 * reference);
}
/** pickWorldFromScreen through a globe engine: the same cascade. */
function enginePickWorldFromScreen(engine, nx, ny) {
const { width: w, height: h } = engine.host.size();
/**
* Convert a NORMALIZED screen point (x,y in [0,1] of the current viewport) into
* a world lon/lat using the depth-aware pick cascade — the inverse of the
* project-to-screen used by the renderers. This is the "point at the pixel"
* fallback: the agent indicates a spot in the viewport screenshot when it can't
* name the place, and we anchor the mark to the actual world point under it.
*
* Each stage is validated before it is accepted: a depth pick over empty sky
* can return a NaN or centre-of-the-earth Cartesian. A degenerate pick IS a
* missed pick, so it falls through to the next stage and ultimately to the
* caller's null. The answer carries the height the pick landed on (a roof, a
* hillside, or 0 on the ellipsoid): the draw tool's live preview needs it,
* or the rubber band sinks to sea level while the pointer is on a hill.
*/
function pickWorldFromScreen(engine, nx, ny) {
let size;
try {
size = engine?.host.size();
} catch {
return null;
}
const { width: w, height: h } = size ?? {};
if (!w || !h) return null;
const screen = {
x: Math.max(0, Math.min(1, nx)) * w,
@@ -2343,107 +2356,13 @@ export function createAnnotationResolver({
}
/**
* Convert a NORMALIZED screen point (x,y in [0,1] of the current viewport) into
* a world lon/lat using the depth-aware pick cascade — the inverse of the
* project-to-screen used by the renderers. This is the "point at the pixel"
* fallback: the agent indicates a spot in the viewport screenshot when it can't
* name the place, and we anchor the mark to the actual world point under it.
* Best-effort ground height at a coordinate. The globe is hidden behind
* the Google 3D tiles, so we try to clamp onto the rendered surface; if the
* tiles for that spot aren't loaded we fall back to the terrain, else the
* ellipsoid (0).
*/
function pickWorldFromScreen(viewer, nx, ny) {
if (isGlobeEngine(viewer)) return enginePickWorldFromScreen(viewer, nx, ny);
const scene = viewer?.scene;
if (!scene) return null;
const canvas = scene.canvas;
const w = canvas.clientWidth || canvas.width || 0;
const h = canvas.clientHeight || canvas.height || 0;
if (!w || !h) return null;
const px = Math.max(0, Math.min(1, nx)) * w;
const py = Math.max(0, Math.min(1, ny)) * h;
const pos = new Cesium.Cartesian2(px, py);
// Each stage is validated before it is accepted: a depth pick over empty sky
// can return a NaN or centre-of-the-earth Cartesian, and converting one of
// those throws inside Cesium. A degenerate pick IS a missed pick, so it falls
// through to the next stage and ultimately to the caller's null.
let cart = null;
if (
scene.pickPositionSupported &&
typeof scene.pickPosition === 'function'
) {
try {
cart = scene.pickPosition(pos);
} catch {
cart = null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.pickEllipsoid === 'function'
) {
try {
cart = viewer.camera.pickEllipsoid(pos, Cesium.Ellipsoid.WGS84);
} catch {
cart = null;
}
}
if (
!isPickedWorldPosition(cart) &&
typeof viewer.camera.getPickRay === 'function'
) {
try {
const ray = viewer.camera.getPickRay(pos);
cart = ray ? scene.globe?.pick(ray, scene) || null : null;
} catch {
cart = null;
}
}
if (!isPickedWorldPosition(cart)) return null;
const carto = geo.cartographic.fromCartesian(cart);
if (!carto) return null;
return {
lat: geo.math.toDegrees(carto.latitude),
lon: geo.math.toDegrees(carto.longitude),
// The height the pick actually landed on — a roof, a hillside, or 0 on
// the ellipsoid. Callers that only want a coordinate ignore it; the draw
// tool's live preview needs it, or the rubber band sinks to sea level
// while the pointer is on a hill.
height: Number.isFinite(carto.height) ? carto.height : 0,
};
}
/**
* Best-effort ground height at a coordinate. The Cesium globe is hidden behind
* the Google 3D tiles, so we try to clamp onto the photoreal tile surface; if
* the tiles for that spot aren't loaded we fall back to the ellipsoid (0).
*/
function sampleGroundHeight(viewer, lon, lat) {
if (isGlobeEngine(viewer)) return engineGroundHeight(viewer, lon, lat);
const scene = viewer?.scene;
if (!scene) return 0;
try {
if (
scene.clampToHeightSupported &&
typeof scene.clampToHeight === 'function'
) {
const carto = geo.cartographic.fromDegrees(lon, lat);
const surface = geo.cartographic.toCartesian(carto);
const clamped = scene.clampToHeight(surface);
if (clamped) {
const h = geo.cartographic.fromCartesian(clamped).height;
if (Number.isFinite(h)) return h;
}
}
} catch {
/* tiles not ready — fall through */
}
const globeHeight = scene.globe?.getHeight?.(
geo.cartographic.fromDegrees(lon, lat),
);
return Number.isFinite(globeHeight) && globeHeight > 0 ? globeHeight : 0;
}
/** sampleGroundHeight on a globe engine: the rendered surface, else terrain. */
function engineGroundHeight(engine, lon, lat) {
function sampleGroundHeight(engine, lon, lat) {
if (!engine) return 0;
try {
if (engine.surface.clampToHeightSupported) {
const clamped = engine.surface.clampToHeight(
+2 -3
View File
@@ -1,6 +1,5 @@
// The view-centred search helpers read the camera through a globe engine as
// well as through a viewer (src/locations.js searchAndFlyTo hands them the
// engine).
// The view-centred search helpers read the camera through the globe engine
// (src/locations.js searchAndFlyTo and the annotation board hand it to them).
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../geo/index.js';
+10 -5
View File
@@ -47,7 +47,12 @@ const PALETTE = {
* BOTH paints onto terrain AND onto 3D tiles, so one value covers both worlds.
*/
export function createWorldAnnotationRenderer(viewer) {
/**
* @param {Cesium.Viewer} viewer
* @param {{ engine?: object }} [options] `engine`: the globe engine whose
* credits show the OpenStreetMap attribution of the marks drawn from it.
*/
export function createWorldAnnotationRenderer(viewer, { engine = null } = {}) {
const CLASSIFY = Cesium.ClassificationType.BOTH;
const CLAMP = Cesium.HeightReference.CLAMP_TO_GROUND;
const dataSource = new Cesium.CustomDataSource('gev-annotations');
@@ -522,7 +527,7 @@ export function createWorldAnnotationRenderer(viewer) {
}),
);
osmAnnotations.add(anno);
showOsmCredit(viewer, anno);
showOsmCredit(engine, anno);
} else if (anno.type === 'arrow' && anno.to) {
// Connector draped across the ground from origin to destination.
const positions = [
@@ -577,7 +582,7 @@ export function createWorldAnnotationRenderer(viewer) {
) {
// The actual world proxy owns both geometry and credit, including rollback.
osmAnnotations.add(anno);
showOsmCredit(viewer, anno, {
showOsmCredit(engine, anno, {
openMapTiles: anno.outlineCredit === 'tiles',
});
}
@@ -600,7 +605,7 @@ export function createWorldAnnotationRenderer(viewer) {
function remove(anno) {
pendingGround.get(anno)?.finish('cancelled');
hideOsmCredit(viewer, anno);
hideOsmCredit(engine, anno);
osmAnnotations.delete(anno);
drawn.delete(anno);
if (!anno?._entities) return;
@@ -630,7 +635,7 @@ export function createWorldAnnotationRenderer(viewer) {
function destroy() {
destroyed = true;
for (const task of [...pendingGround.values()]) task.finish('cancelled');
for (const anno of osmAnnotations) hideOsmCredit(viewer, anno);
for (const anno of osmAnnotations) hideOsmCredit(engine, anno);
osmAnnotations.clear();
drawn.clear();
try {