Draw the installations layer through the renderer ports

The site dots, outlines and selected footprint fill are now draw-port sets
(points, draped lines, clamped shapes) instead of Cesium entities. The
selected site's dot is drawn by a set of its own, so selecting a site
redraws no other dot. Selection is registered through plain carrier
objects in the context store, as the local GeoJSON layer does, and the
tracked card reads the site's label and position from the carrier's entity
record.

A double-click on a site dot now follows it through camera.follow (gated on
the stock double-click follow), centred on the surface under the dot when
its height is loaded; one on an outline or fill zooms to it. Hiding the
layer stops a follow it started. The layer no longer lowers the shared
camera change sensitivity: its own camera-port listener carries its
threshold.

The follow offset fitting moves to src/geo/frames.js and is shared with
the local GeoJSON layer. rendering.js leaves the Cesium allow-list
(33 -> 32); the layer's entry joins DRAW_FROM_CALLER.
This commit is contained in:
Sameh Khamis committed 2026-11-08 12:13:29 -08:00
1 parent a59f9b10b2
commit 1bff078097
21 files changed
+864 -337

No files matched your search

+2 -6
View File
@@ -20,8 +20,6 @@ export function createLifecycle({
const camera = cameraOf(viewer);
layerState.moveEndRemove = camera.on('moveEnd', cameraChanged);
// Measured for this listener alone; off, a load is never scheduled.
// The sensitivity claim in enable() is for raw camera listeners
// elsewhere, which this layer has always made finer while on.
layerState.changedRemove = camera.on('changed', cameraChanged, {
threshold: CAMERA_CHANGED_THRESHOLD,
});
@@ -48,9 +46,8 @@ export function createLifecycle({
});
parts.namedMarkers?.enable();
parts.namedMarkers?.sync(layerState.records || []);
parts.rendering.claimCameraChanges?.();
registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id));
layerState.dataSource.show = true;
parts.rendering.setShown(true);
// DataLayerManager invokes update() immediately after enable(), which owns
// the first fetch. Avoid racing it with a second aborting request here.
},
@@ -59,7 +56,6 @@ export function createLifecycle({
layerState.enabled = false;
services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
parts.namedMarkers?.hide();
parts.rendering.releaseCameraChanges?.();
layerState.contextAnchor = null;
layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' };
@@ -71,7 +67,7 @@ export function createLifecycle({
layerState.abort?.abort();
layerState.abort = null;
layerState.loading = false;
if (layerState.dataSource) layerState.dataSource.show = false;
parts.rendering.setShown(false);
clearSelectedEntityContextForLayer(LAYER_ID);
layerState.selectedId = null;
parts.rendering.clearSelectionFill?.();
+10 -4
View File
@@ -25,9 +25,9 @@ for (const source of [
viewer,
records: source ? [{ id: 'base', sources: [source] }] : [],
recordById: new Map(),
dataSource: { show: false },
};
let markersVisible = false;
let drawnShown = false;
const parts = {
namedMarkers: {
enable: () => {
@@ -38,7 +38,13 @@ for (const source of [
markersVisible = false;
},
},
rendering: { attach: noop, detach: noop },
rendering: {
attach: noop,
detach: noop,
setShown: (shown) => {
drawnShown = shown;
},
},
viewport: { clearUnavailableRetry: noop },
ingestion: { setInstallationStatus: noop },
};
@@ -61,12 +67,12 @@ for (const source of [
try {
for (let cycle = 0; cycle < 2; cycle++) {
lifecycle.enable();
assert.equal(state.dataSource.show, true);
assert.equal(drawnShown, true);
assert.equal(markersVisible, true);
// No renderRecords or successful fetch occurs between toggles.
assert.equal(visibleCredits.size, expected);
lifecycle.disable();
assert.equal(state.dataSource.show, false);
assert.equal(drawnShown, false);
assert.equal(markersVisible, false);
assert.equal(visibleCredits.size, 0);
}
-9
View File
@@ -1,9 +0,0 @@
import { createEntityStore } from '../../data/entityRecords.js';
/**
* What the installations layer last drew for a retained marker entity, so an
* unchanged record leaves it alone: `heightM` (surface height) and `selected`.
* Selection fills and outlines record the installation they belong to as
* `recordId`, which a pick on them resolves through.
*/
export const installationMarkers = createEntityStore();
@@ -26,7 +26,7 @@ function setup(t) {
bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(state.viewer) });
const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } };
let loads = 0;
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() { state.dataSource = { show: false }; }, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } };
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() {}, setShown() {}, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } };
const ctx = { state, services, parts, source: {}, overlayHost };
parts.namedMarkers = createNamedMarkers(ctx);
const lifecycle = createLifecycle(ctx).methods;
+2 -3
View File
@@ -25,9 +25,8 @@ test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and
const parts = {
selection: { installInteraction() {} },
rendering: {
attach() {
state.dataSource = { show: false };
},
attach() {},
setShown() {},
detach() {},
clearRendered() {},
},
+339 -169
View File
@@ -1,22 +1,38 @@
import { installationClassLabel, installationTitle } from './classLabel.js';
import * as Cesium from 'cesium';
// Still Cesium for its entities, so this layer loads the unbound camera
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { entityFollowTarget } from '../../data/followed.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { followOffsetFitting } from '../../geo/frames.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { heightsOf } from '../../queries/heights.js';
import {
CAMERA_CHANGED_THRESHOLD,
LAYER_ID,
MAX_RENDERED,
COLOR_BY_CLASS,
} from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { entityRecord } from '../../data/entityRecords.js';
import { installationMarkers } from './markerState.js';
drawOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
let instances = 0;
const DOT_OUTLINE = Object.freeze([0, 0, 0, 0.8]);
const SELECTED_DOT = Object.freeze([1, 1, 1, 1]);
/** A record's footprint polygons, each its rings of `[lon, lat]`. */
const footprintsOf = (record) =>
record.footprints || (record.footprint ? [[record.footprint]] : []);
/** A record's outline polylines of `[lon, lat]`. */
const outlinesOf = (record) =>
record.outlineLines || (record.footprint ? [record.footprint] : []);
/**
* The installations layer's drawing: a draw-port point set of site dots, a
* point set of the selected site's dot (so selecting one restyles no other
* dot), a line set of their ground outlines and a shape set of the selected
* site's footprint fill, on the viewer's renderer (`drawOf`).
*/
export function createRendering({
state: layerState,
services,
@@ -33,27 +49,48 @@ export function createRendering({
const { governorRequestRender } = services.render;
const { warmFireAnchorFloors } = services.anchors;
/** A record's class colour, for the entities. */
function colorFor(record) {
/** A record's class colour with alpha `alpha`, as the draw port takes it. */
function colorFor(record, alpha = null) {
const [r, g, b, a] = parts.model.colorFor(record);
return new Cesium.Color(r, g, b, a);
return [r, g, b, alpha ?? a];
}
/**
* The layer's entities. They stay entities: the camera can follow a site
* (double-click), and the tracked card reads what it shows from them.
* Make the layer's draw sets, hidden until the layer is enabled, and
* follow a site on a double-click.
*/
function attach(viewer) {
layerState.dataSource = new Cesium.CustomDataSource(
'military-installations',
);
viewer.dataSources.add(layerState.dataSource);
const draw = drawOf(viewer);
selectedDotKey = null;
const prefix = `${LAYER_ID}:${++instances}`;
layerState.sets = {
dots: draw.points({ id: `${prefix}:dots`, show: false }),
selected: draw.points({ id: `${prefix}:selected`, show: false }),
outlines: draw.lines({ id: `${prefix}:outlines`, show: false }),
fills: draw.shapes({ id: `${prefix}:fills`, show: false }),
};
}
function detach(viewer) {
if (layerState.dataSource && viewer)
viewer.dataSources.remove(layerState.dataSource, true);
layerState.dataSource = null;
function detach() {
stopFollow();
if (layerState.sets)
for (const set of Object.values(layerState.sets)) set.dispose();
layerState.sets = null;
}
/** Show or hide everything the layer draws. */
function setShown(shown) {
if (!layerState.sets) return;
for (const set of Object.values(layerState.sets)) set.show = shown;
if (!shown) stopFollow();
}
/** Whether `setId` is one of this layer's sets. */
function ownsSet(setId) {
return Boolean(
layerState.sets &&
Object.values(layerState.sets).some((set) => set.id === setId),
);
}
/**
@@ -75,8 +112,7 @@ export function createRendering({
const selectedFillIds = [];
function clearSelectionFill() {
for (const id of selectedFillIds)
layerState.dataSource?.entities.removeById(id);
if (selectedFillIds.length) layerState.sets?.fills.remove(selectedFillIds);
selectedFillIds.length = 0;
selectedFillKey = null;
}
@@ -84,68 +120,63 @@ export function createRendering({
/** Ground geometry classifies the active surface; no height/extrusion plane. */
function syncSelectionFill() {
const record =
layerState.enabled && layerState.recordById.get(layerState.selectedId);
layerState.enabled &&
layerState.sets &&
layerState.recordById.get(layerState.selectedId);
if (!record) {
clearSelectionFill();
return;
}
const classificationType =
layerState.viewer.scene.globe?.show === false
? Cesium.ClassificationType.CESIUM_3D_TILE
: Cesium.ClassificationType.BOTH;
const key = `${record.id}|${renderKey(record)}|${classificationType}`;
// Tiles alone while the globe surface is hidden, as under photoreal.
const clampTo =
findGlobe(layerState.viewer)?.isGlobeVisible?.() === false
? 'tiles'
: 'both';
const key = `${record.id}|${renderKey(record)}|${clampTo}`;
if (key === selectedFillKey) return;
clearSelectionFill();
selectedFillKey = key;
const footprints =
record.footprints || (record.footprint ? [[record.footprint]] : []);
const material = new Cesium.ColorMaterialProperty(
colorFor(record).withAlpha(0.22),
);
for (let i = 0; i < footprints.length; i++) {
const rings = footprints[i];
const positions = (ring) =>
ring.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat));
const fill = layerState.dataSource.entities.add({
id: `${record.id}:selected-fill:${i}`,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(
positions(rings[0]),
rings
.slice(1)
.map((ring) => new Cesium.PolygonHierarchy(positions(ring))),
),
material,
classificationType,
},
});
installationMarkers.write(fill).recordId = record.id;
selectedFillIds.push(fill.id);
}
const fill = colorFor(record, 0.22);
const meta = { installationId: record.id };
const items = footprintsOf(record).map((rings, i) => ({
id: `${record.id}:selected-fill:${i}`,
geometry: {
kind: 'polygon',
rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))),
},
fill,
height: 'clampGround',
clampTo,
meta,
}));
if (items.length) layerState.sets.fills.upsert(items);
for (const item of items) selectedFillIds.push(item.id);
governorRequestRender('installation-selection-fill');
}
function clearRendered() {
clearSelectionFill();
if (layerState.dataSource?.entities)
layerState.dataSource.entities.removeAll();
stopFollow();
if (layerState.sets) {
layerState.sets.dots.clear();
layerState.sets.selected.clear();
layerState.sets.outlines.clear();
}
selectedDotKey = null;
layerState.renderedKeys.clear();
removeEntityContextsForLayer(LAYER_ID);
}
/**
* Geometry identity of one rendered record. Records whose key is unchanged
* keep their Cesium entities across refreshes: ground-clamped outlines and
* classification fills rebuild asynchronously, so recreating them on every
* reload made unchanged sites blink.
* keep their drawn items across refreshes, only restyled or moved in
* place, so an unchanged site never blinks.
* @param {object} record Installation record.
* @returns {string} Stable key for the record's drawn geometry.
*/
function renderKey(record) {
const footprints =
record.footprints || (record.footprint ? [[record.footprint]] : []);
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
const footprints = footprintsOf(record);
const outlines = outlinesOf(record);
let points = 0;
for (const rings of footprints)
for (const ring of rings) points += ring.length;
@@ -162,22 +193,84 @@ export function createRendering({
].join('|');
}
function removeRecordEntities(id) {
const entities = layerState.dataSource.entities;
for (const entityId of layerState.renderedKeys.get(id)?.entityIds || [])
entities.removeById(entityId);
/**
* A site's dot. The selected site's is hidden here and drawn larger, in
* white, by the selected set (`selectedDotItem`): a clamped dot is
* restyled only by drawing it again, so its own set never changes look.
*/
function dotItem(record, rendered) {
return {
id: record.id,
pos: {
lon: record.longitude,
lat: record.latitude,
height: rendered.heightM,
},
height: 'clampGround',
show: !record.namedArea && !rendered.selected,
pixelSize: 9,
color: colorFor(record),
outlineColor: DOT_OUTLINE,
outlineWidth: 1,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: rendered.carrier,
};
}
/** The selected site's dot, as its own set draws it. */
function selectedDotItem(record, rendered) {
return {
...dotItem(record, rendered),
show: true,
pixelSize: 13,
color: SELECTED_DOT,
};
}
/** What the selected set draws now (site, place, height), or null. */
let selectedDotKey = null;
/** Draw the selected site's dot, when it has one shown. */
function syncSelectedDot() {
const sets = layerState.sets;
if (!sets) return;
const rendered = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null;
const record = rendered
? layerState.recordById.get(layerState.selectedId)
: null;
const key =
record && rendered.selected && !record.namedArea
? [record.id, record.longitude, record.latitude, rendered.heightM].join(
'|',
)
: null;
if (key === selectedDotKey) return;
selectedDotKey = key;
if (key) sets.selected.set([selectedDotItem(record, rendered)]);
else sets.selected.clear();
}
/** Stop drawing a record's dot and outlines, and following it. */
function removeRecordItems(id, dotIds, outlineIds) {
const rendered = layerState.renderedKeys.get(id);
if (!rendered) return;
dotIds.push(id);
outlineIds.push(...rendered.outlineIds);
if (follow?.recordId === id) stopFollow();
layerState.renderedKeys.delete(id);
}
/**
* The records that get entities this paint: the nearest `MAX_RENDERED`, plus
* The records that get drawn this paint: the nearest `MAX_RENDERED`, plus
* the selected one when it falls outside that window.
*
* Context navigation walks the FULL nearby cohort, which is not bounded by the
* render cap, so selecting item 701+ used to produce no entity at all — the
* camera flew, `getById` returned null, and the selection was silently dropped
* render cap, so selecting item 701+ used to produce no marker at all — the
* camera flew, the lookup returned null, and the selection was silently dropped
* on the floor, leaving the Context subject stale so NEXT offered the same
* installation forever. One extra entity keeps every cohort item selectable
* installation forever. One extra marker keeps every cohort item selectable
* and the cohort count honest.
* @returns {Array<object>} Records to render this paint.
*/
@@ -218,7 +311,7 @@ export function createRendering({
}
}
// Post-moveEnd debounced fetches commit after the camera settles; the
// rebuilt entities need one frame in idle mode. (perf wave 2 fix)
// rebuilt markers need one frame in idle mode. (perf wave 2 fix)
governorRequestRender('installations-render');
if (
layerState.records.some((r) =>
@@ -237,81 +330,74 @@ export function createRendering({
const keys = new Map(
records.map((record) => [record.id, renderKey(record)]),
);
const entities = layerState.dataSource.entities;
entities.suspendEvents();
const removedDots = [];
const removedOutlines = [];
for (const [id, rendered] of [...layerState.renderedKeys])
if (keys.get(id) !== rendered.key) removeRecordEntities(id);
if (keys.get(id) !== rendered.key)
removeRecordItems(id, removedDots, removedOutlines);
const dots = [];
const outlines = [];
for (const record of records) {
const color = colorFor(record);
const surfaceHeightM = installationSurfaceHeightM(record);
const displayPosition = Cesium.Cartesian3.fromDegrees(
const selectedRecord = record.id === layerState.selectedId;
const retained = layerState.renderedKeys.get(record.id);
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
let changed = false;
if (retained.heightM !== surfaceHeightM) {
retained.heightM = surfaceHeightM;
const displayPosition = fromDegrees(
record.longitude,
record.latitude,
surfaceHeightM,
);
entityRecord(retained.carrier).displayPosition = () =>
displayPosition;
changed = true;
}
if (retained.selected !== selectedRecord) {
retained.selected = selectedRecord;
changed = true;
}
if (changed) dots.push(dotItem(record, retained));
continue;
}
const displayPosition = fromDegrees(
record.longitude,
record.latitude,
surfaceHeightM,
);
const selectedRecord = record.id === layerState.selectedId;
const retained = layerState.renderedKeys.has(record.id)
? entities.getById(record.id)
: null;
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
const marker = installationMarkers.write(retained);
if (marker.heightM !== surfaceHeightM) {
marker.heightM = surfaceHeightM;
retained.position = displayPosition;
entityRecord(retained).displayPosition = () => displayPosition;
}
if (marker.selected !== selectedRecord) {
marker.selected = selectedRecord;
retained.point.pixelSize = selectedRecord ? 13 : 9;
retained.point.color = selectedRecord ? Cesium.Color.WHITE : color;
}
continue;
}
const entityIds = [record.id];
layerState.renderedKeys.set(record.id, {
// What the dot's pick carries and the shared selection, the tracked
// card and a follow read this site through.
const carrier = { id: record.id, installationId: record.id };
const rendered = {
key: keys.get(record.id),
entityIds,
});
const entity = layerState.dataSource.entities.add({
id: record.id,
position: displayPosition,
point: {
show: !record.namedArea,
pixelSize: record.id === layerState.selectedId ? 13 : 9,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
color:
record.id === layerState.selectedId ? Cesium.Color.WHITE : color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.8),
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
for (let i = 0; i < outlines.length; i++) {
const outline = layerState.dataSource.entities.add({
id: `${record.id}:outline:${i}`,
polyline: {
positions: outlines[i].map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
),
width: 2,
material: color.withAlpha(0.85),
clampToGround: true,
classificationType: Cesium.ClassificationType.BOTH,
},
});
installationMarkers.write(outline).recordId = record.id;
entityIds.push(outline.id);
}
Object.assign(installationMarkers.write(entity), {
outlineIds: [],
carrier,
heightM: surfaceHeightM,
selected: selectedRecord,
});
entityRecord(entity).trackedId = `installations:${record.id}`;
entityRecord(entity).displayPosition = () => displayPosition;
entityRecord(entity).labelModel = {
};
layerState.renderedKeys.set(record.id, rendered);
dots.push(dotItem(record, rendered));
const outlineColor = colorFor(record, 0.85);
const outlineMeta = { installationId: record.id };
const lines = outlinesOf(record);
for (let i = 0; i < lines.length; i++) {
const id = `${record.id}:outline:${i}`;
outlines.push({
id,
positions: lines[i].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color: outlineColor },
meta: outlineMeta,
});
rendered.outlineIds.push(id);
}
entityRecord(carrier).trackedId = `installations:${record.id}`;
entityRecord(carrier).displayPosition = () => displayPosition;
entityRecord(carrier).labelModel = {
title: installationTitle(record.name) || t('MAPPED INSTALLATION'),
details: [
installationClassLabel(record.class),
@@ -319,7 +405,7 @@ export function createRendering({
],
accent: COLOR_BY_CLASS[record.class] || '#9ca6b0',
};
registerEntityContext(entity, {
registerEntityContext(carrier, {
id: record.id,
layerId: LAYER_ID,
layerName:
@@ -340,19 +426,116 @@ export function createRendering({
},
});
}
entities.resumeEvents();
const selectedEntity = layerState.selectedId
? layerState.dataSource.entities.getById(layerState.selectedId)
const sets = layerState.sets;
if (removedDots.length) sets.dots.remove(removedDots);
if (removedOutlines.length) sets.outlines.remove(removedOutlines);
if (dots.length) sets.dots.upsert(dots);
if (outlines.length) sets.outlines.upsert(outlines);
syncSelectedDot();
const selected = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null;
if (selectedEntity && (claimSelection || migratedSelection))
selectEntityContext(selectedEntity);
else if (!selectedEntity) layerState.selectedId = null;
if (selected && (claimSelection || migratedSelection))
selectEntityContext(selected.carrier);
else if (!selected) layerState.selectedId = null;
// Re-register rebuilt geometry and migrate aliases before pruning old context.
removeEntityContextsForLayer(LAYER_ID, { retainIds: new Set(keys.keys()) });
parts.namedMarkers?.sync(layerState.records);
syncSelectionFill();
}
/** The follow a double-click started, while the camera keeps it. */
let follow = null;
/**
* Follow the site whose dot is under `position`, as the default renderer
* followed the site's entity on a double-click: by the site's display
* position, framed as that renderer framed an entity it started
* following. A double-click on an outline or the selected fill, which had
* no position to follow, zooms to it at once instead.
* @param {{x: number, y: number}} position Canvas pixels.
*/
function followAt(position) {
const viewer = layerState.viewer;
if (!layerState.enabled || !layerState.sets) return;
const query = findQuery(viewer);
const hit = query?.pick(position.x, position.y);
if (!hit || !ownsSet(hit.set)) return;
const camera = findCamera(viewer);
if (!camera) return;
const recordId = hit.meta?.installationId;
const record = layerState.recordById.get(recordId);
if (!record) return;
try {
if (
hit.set !== layerState.sets.dots.id &&
hit.set !== layerState.sets.selected.id
) {
const points = partPoints(record, hit.id);
if (!points.length) return;
// Following nothing then, as that zoom stopped any follow first.
if (camera.followed) camera.follow(null);
camera.flyToBounds(sphereFromPoints(points), { durationS: 0 });
return;
}
const rendered = layerState.renderedKeys.get(recordId);
if (!rendered) return;
const { carrier } = rendered;
const shown = readEntityRecord(carrier)?.displayPosition?.();
if (!shown) return;
// Centred where the dot is drawn, on the surface under it when its
// height is loaded (the cached floor may not be yet), and held there
// as the stock follow held the dot's bounding sphere.
const surface = heightsOf(viewer).now({
lon: record.longitude,
lat: record.latitude,
});
const at = Number.isFinite(surface)
? fromDegrees(record.longitude, record.latitude, surface)
: shown;
const pose = camera.pose?.();
const target = entityFollowTarget(carrier, {
key: `installations:${record.id}`,
position: () => at,
frame: 'enu',
viewFrom: followOffsetFitting({ center: at, radius: 0 }, at, {
fovy: pose?.fovy,
aspectRatio: pose?.aspectRatio,
minDistance: camera.controls?.minDistance,
maxDistance: camera.controls?.maxDistance,
}),
});
camera.follow(target);
follow = { target, recordId };
} catch (error) {
// A camera that cannot follow leaves the view where it is, as a
// viewer without entity tracking did on a double-click.
console.warn(`${LAYER_ID}: cannot follow`, error);
}
}
/** The ground points of a record's outline or fill item `itemId`. */
function partPoints(record, itemId) {
const outline = /:outline:(\d+)$/.exec(itemId);
if (outline) {
const line = outlinesOf(record)[Number(outline[1])] || [];
return line.map(([lon, lat]) => fromDegrees(lon, lat));
}
const fill = /:selected-fill:(\d+)$/.exec(itemId);
if (fill) {
const rings = footprintsOf(record)[Number(fill[1])] || [];
return rings.flat().map(([lon, lat]) => fromDegrees(lon, lat));
}
return [];
}
/** Stop a follow this layer started, if the camera still keeps it. */
function stopFollow() {
const camera = follow && findCamera(layerState.viewer);
if (follow && camera?.followed === follow.target) camera.follow(null);
follow = null;
}
/**
* Second paint for floors that missed the bounded pre-render deadline.
*
@@ -383,7 +566,7 @@ export function createRendering({
.map((record) => ({ lat: record.latitude, lon: record.longitude }));
if (!cold.length) return;
warmFireAnchorFloors(cold).then(() => {
if (!layerState.enabled || !layerState.dataSource) return;
if (!layerState.enabled || !layerState.sets) return;
if (
!cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null)
)
@@ -391,26 +574,13 @@ export function createRendering({
renderRecords();
});
}
/**
* While the layer is on, the Cesium camera reports changes at the layer's
* threshold to its own `changed` listeners too (the camera port measures
* each listener's threshold itself).
*/
function claimCameraChanges() {
claimCameraSensitivity(
layerState.viewer.camera,
LAYER_ID,
CAMERA_CHANGED_THRESHOLD,
);
}
function releaseCameraChanges() {
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
}
return {
attach,
detach,
claimCameraChanges,
releaseCameraChanges,
setShown,
ownsSet,
followAt,
stopFollow,
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
+21 -10
View File
@@ -1,6 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
import { LAYER_ID } from './policy.js';
import { installationMarkers } from './markerState.js';
export function createSelection({
state: layerState,
@@ -11,6 +10,7 @@ export function createSelection({
const { clearSelectedEntityContextForLayer } = services.context;
let removeContextListeners = null;
let removeDoubleClick = null;
function syncContextSelection(event) {
if (!layerState.enabled) return;
@@ -30,10 +30,10 @@ export function createSelection({
function selectRecord(id) {
const record = layerState.recordById.get(id);
if (!record || !layerState.dataSource) return false;
if (!record || !layerState.sets) return false;
layerState.selectedId = id;
parts.rendering.renderRecords({ claimSelection: true });
// renderRecords drops selectedId when the record produced no entity.
// renderRecords drops selectedId when the record produced no marker.
return layerState.selectedId === id;
}
@@ -50,17 +50,17 @@ export function createSelection({
for (const event of events)
globalThis.window?.removeEventListener?.(event, syncContextSelection);
};
layerState.clickSubscription = inputFor(viewer).onClick((event) => {
const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
// A named marker is a draw item; site markers are still entities.
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit;
const target = event.pick?.id;
const id =
(hit?.set === parts.namedMarkers?.setId
hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId
: null) ||
installationMarkers.read(target)?.recordId ||
(typeof target?.id === 'string' ? target.id : null);
: null;
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id);
} else if (layerState.selectedId) {
@@ -72,6 +72,15 @@ export function createSelection({
parts.rendering.renderRecords();
}
});
// Follow a site on a double-click, as the renderer's own double-click
// followed the site's entity.
removeDoubleClick =
input.onPointer?.('dblclick', (event) => {
// 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;
parts.rendering.followAt(event.position);
}) ?? null;
}
return {
selectRecord,
@@ -79,6 +88,8 @@ export function createSelection({
destroy() {
removeContextListeners?.();
removeContextListeners = null;
removeDoubleClick?.();
removeDoubleClick = null;
},
};
}
+157 -6
View File
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { inputFor } from '../../input/dispatcher.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -37,9 +38,18 @@ function harness(t) {
records: [record],
recordById: new Map([[record.id, record]]),
renderedKeys: new Map(),
dataSource: new Cesium.CustomDataSource(),
viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) },
// The viewer's stock double-click follow, which the site follow
// stands in for.
screenSpaceEventHandler: {
getInputAction: (type) =>
type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
? () => {}
: undefined,
setInputAction() {},
removeInputAction() {},
},
scene: {
globe: { show: false },
canvas: Object.assign(new EventTarget(), {
@@ -52,7 +62,7 @@ function harness(t) {
},
};
let picked;
const { draw } = bindFakeCesiumScene(state.viewer);
const { draw, camera, query } = bindFakeCesiumScene(state.viewer);
const input = fakeInput(state.viewer);
t.mock.method(
Cesium.SceneTransforms,
@@ -85,6 +95,7 @@ function harness(t) {
},
};
parts.rendering = createRendering(ctx);
parts.rendering.attach(state.viewer);
parts.namedMarkers = createNamedMarkers(ctx);
const selection = createSelection(ctx);
selection.installInteraction(state.viewer);
@@ -93,6 +104,7 @@ function harness(t) {
state.clickSubscription();
parts.namedMarkers.destroy();
parts.rendering.clearRendered();
parts.rendering.detach();
input.destroy();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
@@ -103,10 +115,7 @@ function harness(t) {
assert.equal(state.selectedId, selected ? record.id : null);
assert.equal(labels[0].selected, selected);
assert.equal(labels[0].variant, selected ? 'selected' : 'card');
assert.equal(
state.dataSource.entities.values.filter((e) => e.polygon).length,
selected ? 1 : 0,
);
assert.equal(state.sets.fills.size(), selected ? 1 : 0);
};
assert.equal(selection.selectRecord(record.id), true);
assertSelected(true);
@@ -115,6 +124,9 @@ function harness(t) {
selection,
assertSelected,
draw,
camera,
query,
input,
parts,
/** Click on what `pick` names, as the scene would pick it. */
click(value) {
@@ -186,3 +198,142 @@ test('a click on a named marker point selects its site; again releases it', (t)
h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } });
h.assertSelected(false);
});
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords();
const selectedNow = () => h.state.selectedId === 'base';
assert.equal(selectedNow(), false);
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
assert.equal(dot.show, true);
assert.equal(dot.height, 'clampGround');
assert.equal(dot.pixelSize, 9);
assert.equal(dot.disableDepthTest, Infinity);
// The dot carries the site's shared context record, for point-and-ask.
assert.equal(context.getContextStore().entities.get('base').entity, dot.meta);
h.click({ id: { set: dots.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), true);
assert.equal(context.getSelectedEntityContext().id, 'base');
// Drawn larger and white by the selected set, hidden in its own.
assert.equal(h.draw.set(dots.id).items.get('base').show, false);
assert.equal(h.draw.set(dots.id).items.get('base').pixelSize, 9);
const selectedSet = h.draw.set(h.state.sets.selected.id);
const selected = selectedSet.items.get('base');
assert.equal(selected.pixelSize, 13);
assert.deepEqual(selected.color, [1, 1, 1, 1]);
assert.equal(selected.meta, dot.meta);
// A click on the selected dot clears it.
h.click({ id: { set: selectedSet.spec.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), false);
assert.equal(selectedSet.items.size, 0);
assert.equal(h.draw.set(dots.id).items.get('base').show, true);
const outlines = h.state.sets.outlines;
const outline = h.draw.set(outlines.id).items.get('base:outline:0');
assert.equal(outline.mode, 'draped');
assert.equal(outline.clampTo, 'both');
h.click({ id: { set: outlines.id, id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), true);
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
test('a double-click follows a site dot where it is drawn and zooms to its outline', (t) => {
const h = harness(t);
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords({ claimSelection: true });
h.state.enabled = true;
const follows = [];
const flights = [];
let followed = null;
Object.assign(h.camera, {
follow(target) {
follows.push(target);
followed = target;
},
flyToBounds(sphere, options) {
flights.push({ sphere, options });
},
controls: { minDistance: 1, maxDistance: 1e9 },
});
Object.defineProperty(h.camera, 'followed', { get: () => followed });
let hit = null;
h.query.pick = () => hit;
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, 0, 'nothing of the layer under it');
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
const target = follows.at(-1);
assert.equal(target.key, 'installations:base');
assert.equal(target.frame, 'enu');
// The tracked card reads the site through the target's entity.
assert.equal(target.entity, dot.meta);
assert.equal(target.labelModel.title, 'Base');
const at = target.position(0);
assert.ok(Math.abs(at.x - 6378137) < 1e-6 && Math.abs(at.y) < 1e-6);
// 100 m from it, north up, pitched down 45 degrees.
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.x) < 1e-9);
assert.ok(Math.abs(target.viewFrom.y + target.viewFrom.z) < 1e-6);
// On the surface under the dot once its height is loaded, before the
// cached floor has it, and held there.
h.query.sampleHeightNow = () => 2400;
h.input.dblclick({ x: 640, y: 400 });
const raised = follows.at(-1).position(0);
assert.ok(Math.abs(raised.x - 6380537) < 1e-6);
h.query.sampleHeightNow = () => null;
h.input.dblclick({ x: 640, y: 400 });
assert.ok(Math.abs(follows.at(-1).position(0).x - 6378137) < 1e-6);
const outlines = h.state.sets.outlines;
hit = {
set: outlines.id,
id: 'base:outline:0',
meta: { installationId: 'base' },
surface: false,
};
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed, null, 'a zoom stops the follow');
assert.equal(flights.length, 1);
assert.equal(flights[0].options.durationS, 0);
// The follow stops when the layer hides.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed?.key, 'installations:base');
h.parts.rendering.setShown(false);
assert.equal(followed, null);
// Another layer's item under the cursor neither follows nor zooms.
h.parts.rendering.setShown(true);
const before = follows.length;
hit = { set: 'another:1', id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
assert.equal(flights.length, 1);
// With the stock double-click follow turned off, nothing follows.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
const release = inputFor(h.state.viewer).suppressStockClicks();
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
release();
});
+28 -22
View File
@@ -1,54 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { installationMarkers } from './markerState.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness() {
const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]];
const record = { id: 'base', latitude: 30, longitude: -97, name: 'Base', class: 'base', footprints: [[ring, ring.map(([x,y]) => [x+0.001,y+0.001])], [ring]] };
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), dataSource: new C.CustomDataSource(), viewer: { scene: { globe: { show: false } }, camera: {} } };
let globeVisible = false;
const viewer = { scene: {}, camera: {} };
const { draw } = bindFakeDraw(viewer, { globe: { isGlobeVisible: () => globeVisible } });
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), viewer };
let listener, removed = 0;
const noop = () => {};
const services = { ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {}, render: { governorRequestRender: noop }, context: { removeEntityContextsForLayer: noop, clearSelectedEntityContextForLayer: noop }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, maps: { subscribeMapStack(cb) { listener = cb; return () => { listener = null; removed++; }; } } };
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1], installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } };
parts.rendering = createRendering({ state, services, parts });
parts.rendering.attach(viewer);
const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods;
return { state, record, parts, lifecycle, changeSurface: () => listener(), removed: () => removed };
const fills = () => [...draw.set(state.sets.fills.id).items.values()];
return { state, record, parts, lifecycle, draw, fills, showGlobe: (shown) => { globeVisible = shown; }, changeSurface: () => listener(), removed: () => removed };
}
test('selected multipart footprints classify Google tiles with one constant translucent material and holes', () => {
test('selected multipart footprints drape on Google tiles with one constant translucent colour and holes', () => {
const h = harness(), render = h.parts.rendering;
render.syncSelectionFill();
const fills = h.state.dataSource.entities.values.slice();
const fills = h.fills();
assert.equal(fills.length, 2);
for (const fill of fills) {
assert.equal(installationMarkers.read(fill)?.recordId, 'base');
assert.equal(fill.polygon.classificationType.getValue(), C.ClassificationType.CESIUM_3D_TILE);
assert.equal(fill.polygon.height, undefined);
assert.equal(fill.polygon.extrudedHeight, undefined);
assert.equal(fill.polygon.material.isConstant, true);
assert.equal(fill.polygon.material.color.getValue().alpha, 0.22);
assert.equal(fill.meta.installationId, 'base');
assert.equal(fill.clampTo, 'tiles');
assert.equal(fill.height, 'clampGround');
assert.equal(fill.extrudeHeight, undefined);
assert.deepEqual(fill.fill, [1, 165 / 255, 0, 0.22]);
}
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1);
assert.equal(fills[0].polygon.material, fills[1].polygon.material);
assert.equal(fills[0].geometry.rings.length, 2, 'the hole is a second ring');
assert.equal(fills[0].fill, fills[1].fill);
const writes = h.draw.set(h.state.sets.fills.id).writes;
for (let i = 0; i < 100; i++) render.syncSelectionFill();
assert.deepEqual(h.state.dataSource.entities.values, fills, 'repaints retain ground geometry');
assert.equal(h.draw.set(h.state.sets.fills.id).writes, writes, 'repaints retain ground geometry');
assert.deepEqual(h.fills(), fills);
h.state.selectedId = null; render.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0);
assert.equal(h.fills().length, 0);
});
test('surface changes reclassify selected geometry and disable tears down fills and subscription', () => {
const h = harness();
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
h.state.viewer.scene.globe.show = true; h.changeSurface();
assert.ok(h.state.dataSource.entities.values.every(e => e.polygon.classificationType.getValue() === C.ClassificationType.BOTH));
h.showGlobe(true); h.changeSurface();
assert.ok(h.fills().every((fill) => fill.clampTo === 'both'));
h.lifecycle.disable();
assert.equal(h.state.dataSource.entities.values.length, 0);
assert.equal(h.fills().length, 0);
assert.equal(h.removed(), 1);
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0, 'reenabling cannot revive a stale selection');
assert.equal(h.fills().length, 0, 'reenabling cannot revive a stale selection');
h.lifecycle.disable();
});
@@ -61,15 +66,16 @@ test('geometry rebuild and canonical alias migration preserve shared selection b
const h = harness();
const services = { context, render: { governorRequestRender() {} }, ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {} };
const rendering = createRendering({ state: h.state, services, parts: h.parts });
rendering.attach(h.state.viewer);
const cleared = [];
window.addEventListener('gev:entity-selection-cleared', e => { cleared.push(e.detail); h.state.selectedId = null; });
rendering.renderRecords({ claimSelection: true });
const oldEntity = context.getSelectedEntityContext().entity;
const oldCarrier = context.getSelectedEntityContext().entity;
h.record.latitude += 0.001;
rendering.renderRecords();
assert.equal(h.state.selectedId, 'base');
assert.equal(context.getSelectedEntityContext().id, 'base');
assert.notEqual(context.getSelectedEntityContext().entity, oldEntity);
assert.notEqual(context.getSelectedEntityContext().entity, oldCarrier);
const replacement = { ...h.record, id: 'canonical', aliasIds: ['base'] };
h.state.records = [replacement]; h.state.recordById = new Map([['canonical', replacement]]);
rendering.renderRecords();
+6 -2
View File
@@ -3,7 +3,8 @@ export function createState({ services }) {
Object.assign(state, {
viewer: null,
dataSource: null,
/** The layer's draw sets (`dots`, `outlines`, `fills`) while attached. */
sets: null,
enabled: false,
records: [],
recordById: new Map(),
@@ -32,7 +33,10 @@ export function createState({ services }) {
contextPosition: null,
/** Coverage of the last successful load: viewport, or radius around a subject. */
coverage: { kind: 'viewport' },
/** Per-record geometry keys of the rendered entities, for in-place updates. */
/**
* What each drawn record last drew: its geometry key, outline item ids,
* context carrier, height and selection, for in-place updates.
*/
renderedKeys: new Map(),
});
return state;