Merge branch 'main' into perf/imagery-stale-thumbnail-cancellation-20260929

# Conflicts:
#	docs/CURRENT-STATE.md
This commit is contained in:
German Khokhlov committed 2026-11-18 16:35:39 +04:00
commit 3348e3517e
2055 files changed
+320058 -46434

No files matched your search

@@ -7,6 +7,7 @@ import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js';
import { LayerPanel } from '../../ui/layerPanel.js';
import { translateFeedError } from '../../ui/statusText.js';
import { createAirQualityLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function inLocale(locale, run) {
setLocale(locale);
@@ -22,7 +23,8 @@ function harness(source) {
source,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const viewer = { dataSources: { add() {}, remove() {} } };
const viewer = {};
bindFakeDraw(viewer);
layer.init(viewer);
layer.enable(viewer);
return layer;
+59 -62
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { cssColor } from '../../render/color.js';
import { drawOf, findCamera } from '../../render/rendererOf.js';
import { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
@@ -22,6 +24,15 @@ const STATION_MARKER_RADIUS_M = 6_000;
/** Readings listed in the readout card. */
const READOUT_LIMIT = 5;
export const AIR_QUALITY_MARKER_SET_ID = 'air-quality';
let instances = 0;
/** A reading's colour at `alpha`; an unreadable colour falls back to white. */
function withAlpha(css, alpha) {
const [r, g, b] = cssColor(css) ?? [1, 1, 1];
return [r, g, b, alpha];
}
/** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
@@ -29,7 +40,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
let _viewer = null;
let _request = null;
let _dataSource = null;
let _markers = null;
let _readings = [];
let _count = 0;
let _lastUpdate = null;
@@ -40,17 +51,8 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
const notify = () => rowControlsListener?.();
/** The camera's lon/lat rectangle in degrees, or null when unresolvable. */
const viewRectangle = () => {
const rectangle = _viewer?.camera?.computeViewRectangle?.();
if (!rectangle) return null;
const toDeg = Cesium.Math.toDegrees;
return {
west: toDeg(rectangle.west),
south: toDeg(rectangle.south),
east: toDeg(rectangle.east),
north: toDeg(rectangle.north),
};
};
const viewRectangle = () =>
_viewer ? (findCamera(_viewer)?.viewRectangle() ?? null) : null;
const layer = {
id: 'air-quality',
@@ -61,10 +63,11 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
init(viewer) {
if (_viewer) throw new Error('Air quality layer is already initialized');
_markers = drawOf(viewer).shapes({
id: `${AIR_QUALITY_MARKER_SET_ID}:${++instances}`,
show: false,
});
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('air-quality');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_readings = [];
_count = 0;
_lastUpdate = null;
@@ -75,7 +78,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
enable() {
_enabled = true;
if (_dataSource) _dataSource.show = true;
if (_markers) _markers.show = true;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true);
notify();
},
@@ -85,14 +88,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
if (_markers) _markers.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
notify();
},
async update() {
if (!_enabled || !_dataSource) return false;
if (!_enabled || !_markers) return false;
_request?.abort();
const request = new AbortController();
_request = request;
@@ -120,47 +123,42 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
/** Rebuild entities and overlay labels from the current readings. */
/** Redraw the station markers and overlay labels from the current readings. */
_render() {
if (!_dataSource) return;
_dataSource.entities.removeAll();
if (!_markers) return;
const markers = [];
const overlayEntries = [];
for (const reading of _readings) {
const position = Cesium.Cartesian3.fromDegrees(
reading.lon,
reading.lat,
);
const color = Cesium.Color.fromCssColorString(reading.color);
_dataSource.entities.add(
new Cesium.Entity({
id: `air-quality:${reading.id}`,
position,
ellipse: {
// Static axes, as in the earthquake layer: a per-frame axis
// re-tessellates the clamped ground primitive every frame.
semiMajorAxis: STATION_MARKER_RADIUS_M,
semiMinorAxis: STATION_MARKER_RADIUS_M,
material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)),
outline: true,
outlineColor: color.withAlpha(0.9),
outlineWidth: 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
}),
);
const position = fromDegrees(reading.lon, reading.lat);
// A filled disc on the ground with static axes, as in the earthquake
// layer: a per-frame axis re-tessellates clamped ground geometry
// every frame. No outline: clamped to the ground, the default
// renderer never drew one.
markers.push({
id: `air-quality:${reading.id}`,
geometry: {
kind: 'ellipse',
center: { lon: reading.lon, lat: reading.lat },
semiMajor: STATION_MARKER_RADIUS_M,
semiMinor: STATION_MARKER_RADIUS_M,
},
fill: withAlpha(reading.color, 0.35),
height: 'clampGround',
clampTo: 'both',
meta: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
});
overlayEntries.push(
createAirQualityOverlayEntry({
id: reading.id,
@@ -171,6 +169,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}),
);
}
_markers.set(markers);
if (_enabled) {
overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID,
@@ -184,16 +183,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
destroy(viewer = _viewer) {
destroy() {
_request?.abort();
_request = null;
_enabled = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
if (_dataSource) {
viewer?.dataSources?.remove(_dataSource, true);
_dataSource = null;
}
_markers?.dispose();
_markers = null;
_viewer = null;
_readings = [];
_count = 0;
+66 -17
View File
@@ -3,20 +3,12 @@ import test from 'node:test';
import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness(source) {
const sources = [];
function harness(source, renderer = {}) {
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer, renderer);
const layer = createAirQualityLayer({
source,
overlayHost: {
@@ -29,7 +21,8 @@ function harness(source) {
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
const markers = () => draw.find('air-quality:');
return { layer, viewer, draw, markers, events };
}
const reading = (id, value, overrides = {}) => ({
@@ -61,12 +54,68 @@ test('a layer requires both a snapshot source and an overlay host', () => {
);
});
test('initialization is single-use and owns exactly one data source', () => {
const { layer, viewer, sources } = harness(staticSource([]));
assert.equal(sources.length, 1);
test('initialization is single-use and owns exactly one draw set', () => {
const { layer, viewer, draw, markers } = harness(staticSource([]));
const owned = markers();
assert.equal(owned.kind, 'shapes');
assert.equal(
[...draw.sets.values()].filter((set) => !set.disposed).length,
1,
);
assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer);
assert.equal(sources.length, 0);
assert.equal(owned.disposed, true);
});
test('stations are ground discs in their band colour, shown only while enabled', async () => {
const { layer, markers } = harness(
staticSource([reading('A', 2), reading('B', 7, { color: '#c1121f' })]),
);
assert.equal(await layer.update(), true);
const set = markers();
assert.equal(set.show, true);
assert.deepEqual(
[...set.items.keys()],
['air-quality:eccc:A', 'air-quality:eccc:B'],
);
const disc = set.items.get('air-quality:eccc:B');
assert.deepEqual(disc.geometry, {
kind: 'ellipse',
center: { lon: -79.38, lat: 43.65 },
semiMajor: 6_000,
semiMinor: 6_000,
});
assert.equal(disc.height, 'clampGround');
assert.equal(disc.clampTo, 'both');
assert.deepEqual(disc.fill, [0xc1 / 255, 0x12 / 255, 0x1f / 255, 0.35]);
assert.equal(disc.outline, undefined);
assert.equal(disc.meta.name, 'B');
assert.equal(disc.meta.value, 7);
layer.disable();
assert.equal(set.show, false);
layer.enable();
assert.equal(set.show, true);
assert.equal(await layer.update(), true);
assert.equal(set.items.size, 2, 'a refresh replaces, not appends');
});
test('the readout lists only readings inside the camera port view rectangle', async () => {
const { layer } = harness(
staticSource([
reading('Toronto', 2),
reading('Vancouver', 4, { lat: 49.28, lon: -123.12 }),
]),
{
camera: {
viewRectangle: () => ({ west: -90, south: 40, east: -70, north: 50 }),
},
},
);
await layer.update();
assert.deepEqual(
layer.getRowControls().list.items.map((item) => item.text),
['Toronto · Low health risk'],
);
});
test('a refresh renders readings and publishes an overlay cohort', async () => {
-1
View File
@@ -14,5 +14,4 @@ export * from '../../data/modelVisualAnchor.js';
export * from '../../data/motionModel.js';
export * from '../../data/renderAltitude.js';
export * from '../../data/routePlausible.js';
export * from '../../data/trackedModelRegime.js';
export * from '../../data/trackingClickGesture.js';
+34 -42
View File
@@ -1,5 +1,6 @@
import { isFollowing } from '../../data/followed.js';
import { isUnavailableCapability } from '../../sources/capability.js';
import * as Cesium from 'cesium';
import { cameraOf, drawOf, findFrame } from '../../render/rendererOf.js';
import {
LAYER_ID,
REQUEST_DEBOUNCE_MS,
@@ -11,11 +12,14 @@ import {
boxContains,
alprRetryDelayMs,
validateAlprSnapshot,
alprCreditMarkup,
alprCredit,
} from './model.js';
import { createAlprPresentation } from './presentation.js';
import { createAlprMarkerSet } from './markerState.js';
import { t, tn, msg } from '../../i18n/index.js';
let instances = 0;
/**
* Own one layer's requests, records, display and viewer subscriptions.
* A source fetches a bounded box with an AbortSignal and resolves
@@ -39,10 +43,12 @@ export function createAlprCamerasLayer({ source, services } = {}) {
const state = {
viewer: null,
dataSource: null,
/** The camera markers, drawn as one icon set. */
markers: createAlprMarkerSet(),
credit: null,
creditTimer: null,
creditPresented: false,
creditOff: null,
enabled: false,
records: [],
recordById: new Map(),
@@ -63,7 +69,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
moveEndRemove: null,
postRenderRemove: null,
lastAnchorSampleAt: 0,
clickHandler: null,
clickSubscription: null,
debounceTimer: null,
/** Snapped box of the last successful query; a view still inside it reuses its records. */
lastQueryBox: null,
@@ -182,9 +188,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
}
renderRecords();
state.retrying = false;
setAlprStatus(
state.dataSource.entities.values.length ? 'ready' : 'empty',
);
setAlprStatus(state.markers.size ? 'ready' : 'empty');
return;
}
// A move inside an in-flight query must not abort and restart that query.
@@ -252,13 +256,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
// Stale and saturated are independent facts; a cached response that also
// hit the cap must still warn about coverage, not just about freshness.
renderRecords();
setAlprStatus(
state.dataSource.entities.values.length
? stale
? 'stale'
: 'ready'
: 'empty',
);
setAlprStatus(state.markers.size ? (stale ? 'stale' : 'ready') : 'empty');
} catch (error) {
if (
error?.name === 'AbortError' ||
@@ -295,16 +293,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
init(viewer) {
if (state.viewer) throw new Error('ALPR layer is already initialized');
state.viewer = viewer;
state.dataSource = new Cesium.CustomDataSource('alpr-cameras');
const creditMarkup = alprCreditMarkup(source.attribution);
state.credit = creditMarkup
? new Cesium.Credit(creditMarkup, true)
: null;
viewer.dataSources.add(state.dataSource);
state.moveEndRemove =
viewer.camera.moveEnd.addEventListener(scheduleLoad);
state.markers.attach(
drawOf(viewer).icons({
id: `${LAYER_ID}:${++instances}:markers`,
show: state.enabled,
}),
);
state.credit = alprCredit(source.attribution);
state.moveEndRemove = cameraOf(viewer).on('moveEnd', scheduleLoad);
state.postRenderRemove =
viewer.scene.postRender?.addEventListener(updateSelectedAnchor);
findFrame(viewer)?.on('postRender', () => updateSelectedAnchor()) ??
null;
initOverlay();
installInteraction(viewer);
},
@@ -313,7 +312,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.enabled = true;
state.creditPresented = false;
registerPickOwner(LAYER_ID, (id) => state.recordById.has(id));
state.dataSource.show = true;
state.markers.icons.show = true;
// DataLayerManager calls update() right after enable(); it owns the first fetch.
},
disable() {
@@ -327,7 +326,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.pendingQueryBox = null;
state.loading = false;
state.retrying = false;
if (state.dataSource) state.dataSource.show = false;
if (state.markers.icons) state.markers.icons.show = false;
clearSelection();
clearRendered();
setAlprStatus('idle');
@@ -343,12 +342,10 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.moveEndRemove = null;
state.postRenderRemove?.();
state.postRenderRemove = null;
state.clickHandler?.destroy();
state.clickHandler = null;
state.clickSubscription?.();
state.clickSubscription = null;
clearRendered();
if (state.dataSource && viewer)
viewer.dataSources.remove(state.dataSource, true);
state.dataSource = null;
state.markers.dispose();
state.credit = null;
state.creditPresented = false;
state.records = [];
@@ -363,19 +360,18 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.viewer = null;
},
getRowControls() {
const count = state.dataSource?.entities.values.length || 0;
const count = state.markers.size;
return {
chips: [
{
id: 'find-camera',
label: t('SHOW NEAREST'),
title: state.viewer?.trackedEntity
title: isFollowing(state.viewer)
? t(
'Stop following the current object before navigating to a camera',
)
: t('Move to the nearest loaded camera and show its details'),
disabled:
!state.enabled || !count || Boolean(state.viewer?.trackedEntity),
disabled: !state.enabled || !count || isFollowing(state.viewer),
onClick: focusNearest,
},
],
@@ -424,21 +420,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
},
getStats() {
return {
count: state.dataSource?.entities.values.length || 0,
count: state.markers.size,
countLabel:
state.enabled && !state.noCoverage && state.status !== 'zoom-in'
? Number.isInteger(state.onScreen)
? tn(
state.dataSource?.entities.values.length || 0,
state.markers.size,
'{count} nearby · {onScreen} on screen',
'{count} nearby · {onScreen} on screen',
{ onScreen: state.onScreen },
)
: tn(
state.dataSource?.entities.values.length || 0,
'{count} nearby',
'{count} nearby',
)
: tn(state.markers.size, '{count} nearby', '{count} nearby')
: '',
noCoverage: Boolean(state.noCoverage),
lastUpdate: state.lastUpdate,
@@ -446,7 +438,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
saturated: state.saturated || state.renderSaturated,
renderRevision: state.renderRevision,
onScreen: state.onScreen ?? null,
shown: state.dataSource?.entities.values.length || 0,
shown: state.markers.size,
error: state.error,
status: state.status,
loading: state.loading,
+175
View File
@@ -0,0 +1,175 @@
/**
* @module alpr/markerState
* @description The ALPR layer's markers: one icon per camera in a draw set,
* and the layer's own per-marker state, held in the layer. Each marker is a
* plain carrier object (`{ id, show }`) that the layer registers as the
* camera's context entity; its state lives in `alprMarkers`:
* - `record`: the camera record the marker shows.
* - `position`, `clamped`: where the badge is drawn natively, and whether it
* follows the ground there rather than sitting at its height.
* - `selected`: drawn with the selected badge.
* - `canvasPosition`, `displayPosition`: the canvas anchor and the position the card reads.
* - `wedge`: the direction wedge's positions, plain ECEF.
* - `canvasOwned`: the overlay canvas draws the badge; the icon stays as a
* faint pick target at the canvas anchor.
* - `shown`, `surfaceCheckedFor`: whether the icon shows and the anchor last checked.
*/
import { createEntityStore } from '../../data/entityRecords.js';
import {
MARKER_ICON_SIZE,
MARKER_SCALE_BY_DISTANCE,
SELECTED_MARKER_ICON_SIZE,
} from './policy.js';
import { MARKER_IMAGE, SELECTED_IMAGE } from './visuals.js';
export const alprMarkers = createEntityStore();
const [NEAR, NEAR_SCALE, FAR, FAR_SCALE] = MARKER_SCALE_BY_DISTANCE;
/** City-wide views hold hundreds of badges; they shrink with distance. */
const SCALE_BY_DISTANCE = Object.freeze({
near: NEAR,
nearValue: NEAR_SCALE,
far: FAR,
farValue: FAR_SCALE,
});
/** Under the canvas badge: faint, but still picked. */
const PICK_TARGET_COLOR = Object.freeze([1, 1, 1, 0.01]);
/**
* Where a marker's icon is drawn: the canvas anchor while the canvas owns
* it, else its native position.
* @param {{id: string}} carrier
* @returns {import('../../render/contract/common').Ecef|null|undefined}
*/
export function alprIconPosition(carrier) {
const marker = alprMarkers.read(carrier);
if (!marker) return null;
return marker.canvasOwned && marker.canvasPosition
? marker.canvasPosition
: marker.position;
}
/**
* The icon a marker draws now.
* @param {{id: string}} carrier
* @returns {import('../../render/contract/draw').IconItem}
*/
export function alprIconItem(carrier) {
const marker = alprMarkers.read(carrier) ?? {};
const canvas = Boolean(marker.canvasOwned && marker.canvasPosition);
const size = marker.selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE;
return {
id: carrier.id,
pos: canvas ? marker.canvasPosition : marker.position,
// Ground clamping is the placeholder until a marker's floor resolves.
height: !canvas && marker.clamped ? 'clampGround' : 'absolute',
image: marker.selected ? SELECTED_IMAGE : MARKER_IMAGE,
size: [size, size],
disableDepthTest: Number.POSITIVE_INFINITY,
show: marker.shown !== false,
// The context carrier: what a pick hands to point-and-ask.
meta: carrier,
...(canvas
? { color: PICK_TARGET_COLOR }
: { scaleByDistance: SCALE_BY_DISTANCE }),
};
}
/** What tells one drawn icon from another, so unchanged ones are not sent again. */
function itemKey(item) {
const { pos } = item;
return [
pos?.x,
pos?.y,
pos?.z,
item.height,
item.image,
item.size[0],
item.show,
item.color ? 'pick' : 'badge',
].join('|');
}
/**
* The layer's markers, drawn as one icon set: carriers by camera id, and
* the writes to the set, batched until `flush`.
* @returns {object}
*/
export function createAlprMarkerSet() {
const carriers = new Map();
/** The key of each icon last sent to the set, by id. */
const sent = new Map();
const dirty = new Set();
let icons = null;
function flush() {
if (!icons || !dirty.size) return;
const items = [];
for (const carrier of dirty) {
if (carriers.get(carrier.id) !== carrier) continue;
const item = alprIconItem(carrier);
if (!item.pos) continue;
const key = itemKey(item);
if (sent.get(carrier.id) === key) continue;
sent.set(carrier.id, key);
items.push(item);
}
dirty.clear();
if (items.length) icons.upsert(items);
}
return {
/** Draw the markers into `set`, an icon set made for them. */
attach(set) {
icons = set;
},
/** The icon set, while attached. */
get icons() {
return icons;
},
get size() {
return carriers.size;
},
get(id) {
return carriers.get(id) ?? null;
},
values() {
return carriers.values();
},
/** A new marker for `id`, drawn at the next `flush`. */
add(id) {
const carrier = { id, show: true };
carriers.set(id, carrier);
dirty.add(carrier);
return carrier;
},
/** Remove the markers with these ids now. */
remove(ids) {
const gone = [];
for (const id of ids) {
if (!carriers.delete(id)) continue;
sent.delete(id);
gone.push(id);
}
if (gone.length) icons?.remove(gone);
},
/** Redraw `carrier` at the next `flush`, if how it draws changed. */
changed(carrier) {
if (carrier) dirty.add(carrier);
},
flush,
clear() {
carriers.clear();
sent.clear();
dirty.clear();
icons?.clear();
},
dispose() {
carriers.clear();
sent.clear();
dirty.clear();
icons?.dispose();
icons = null;
},
};
}
+13 -21
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { toDegrees, toRadians } from '../../geo/index.js';
import { EARTH_MEAN_RADIUS_M } from './policy.js';
export * from './records.js';
@@ -12,9 +12,9 @@ export * from './records.js';
*/
export function destinationPointDeg(latDeg, lonDeg, bearingDeg, distanceM) {
const angularDistance = distanceM / EARTH_MEAN_RADIUS_M;
const bearing = Cesium.Math.toRadians(bearingDeg);
const lat1 = Cesium.Math.toRadians(latDeg);
const lon1 = Cesium.Math.toRadians(lonDeg);
const bearing = toRadians(bearingDeg);
const lat1 = toRadians(latDeg);
const lon1 = toRadians(lonDeg);
const lat2 = Math.asin(
Math.sin(lat1) * Math.cos(angularDistance) +
Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(bearing),
@@ -26,29 +26,21 @@ export function destinationPointDeg(latDeg, lonDeg, bearingDeg, distanceM) {
Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2),
);
return {
latitude: Cesium.Math.toDegrees(lat2),
longitude: Cesium.Math.toDegrees(lon2),
latitude: toDegrees(lat2),
longitude: toDegrees(lon2),
};
}
/** Build a linked attribution from plain text and an HTTPS URL only. */
export function alprCreditMarkup(attribution) {
/**
* The on-map credit for the renderer's credits port, from plain text and an
* HTTPS URL only; the port escapes it as it shows it.
* @returns {{text: string, href: string, inline: true}|null}
*/
export function alprCredit(attribution) {
if (!attribution?.text || !attribution?.href) return null;
const href = new URL(attribution.href);
if (href.protocol !== 'https:' || href.username || href.password) {
throw new TypeError('Camera attribution requires a public HTTPS link');
}
const escape = (value) =>
String(value).replace(
/[&<>"']/g,
(char) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[char],
);
return `<span class="gev-alpr-credit">ALPR: <a href="${escape(href.href)}" target="_blank" rel="noopener">${escape(attribution.text)}</a></span>`;
return { text: `ALPR: ${attribution.text}`, href: href.href, inline: true };
}
+145 -163
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
MAX_CANVAS_FRUSTUMS,
MARKER_ICON_SIZE,
@@ -18,8 +17,19 @@ import {
paintDirectionWedge,
validAlprGroundHeight,
} from './visuals.js';
import { alprMarkers } from './markerState.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import { cameraOf, findQuery, rendererOf } from '../../render/rendererOf.js';
/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */
let lanes = 0;
/** Within `epsilon` on every axis. */
const near = (a, b, epsilon) =>
Math.abs(a.x - b.x) <= epsilon &&
Math.abs(a.y - b.y) <= epsilon &&
Math.abs(a.z - b.z) <= epsilon;
/** Per-layer presentation on a caller-owned overlay; the icon set remains the fallback. */
export function createAlprOverlay({
state,
services,
@@ -38,72 +48,55 @@ export function createAlprOverlay({
if (!destroyed && state.enabled) lane?.requestPaint();
};
function nativeVisible(entity, visible) {
if (!entity) return;
canvasOwned(entity, !visible);
setShown(entity, visible);
const markers = state.markers;
function nativeVisible(carrier, visible) {
if (!carrier) return;
canvasOwned(carrier, !visible);
setShown(carrier, visible);
}
/** Swap a marker between its native look and a faint canvas pick target. */
function canvasOwned(entity, owned) {
const visible = !owned;
const billboard = entity.billboard;
// Keep a faint native pick target under the canvas badge so sibling layer
// handlers recognize ALPR ownership instead of treating the click as empty.
if (!visible && !entity.gevAlprNativeAppearance) {
entity.gevAlprNativeAppearance = {
position: entity.position,
heightReference: billboard.heightReference,
scaleByDistance: billboard.scaleByDistance,
color: billboard.color,
};
entity.position = entity.gevAlprCanvasPosition;
entity.gevAlprPickPosition = entity.position;
billboard.heightReference = Cesium.HeightReference.NONE;
billboard.scaleByDistance = undefined;
billboard.color = Cesium.Color.WHITE.withAlpha(0.01);
} else if (visible && entity.gevAlprNativeAppearance) {
const saved = entity.gevAlprNativeAppearance;
if (entity.position === entity.gevAlprPickPosition)
entity.position = saved.position;
billboard.heightReference = saved.heightReference;
billboard.scaleByDistance = saved.scaleByDistance;
billboard.color = saved.color;
entity.gevAlprNativeAppearance = null;
entity.gevAlprPickPosition = null;
}
/**
* Swap a marker between its native look and a faint canvas pick target.
* The faint icon stays under the canvas badge, at its anchor, so sibling
* layer handlers recognize ALPR ownership instead of treating the click
* as empty.
*/
function canvasOwned(carrier, owned) {
const marker = alprMarkers.write(carrier);
if (Boolean(marker.canvasOwned) === owned) return;
marker.canvasOwned = owned;
markers.changed(carrier);
}
// Assign only on change: each Entity property write mints a new property
// and raises definitionChanged, which paint used to do for every overlay
// camera on every frame.
function setShown(entity, visible) {
if (entity.gevAlprShown === visible) return;
entity.gevAlprShown = visible;
entity.billboard.show = visible;
if (entity.polyline) entity.polyline.show = visible;
if (entity.polygon) entity.polygon.show = visible;
// Changed only on change: the icon is sent again only when it draws
// differently.
function setShown(carrier, visible) {
const marker = alprMarkers.write(carrier);
if ((marker.shown ?? true) === visible) return;
marker.shown = visible;
markers.changed(carrier);
}
function resetAnchors() {
for (const entity of state.dataSource.entities.values) {
entity.gevAlprCanvasPosition = null;
entity.gevAlprWedge = null;
entity.gevAlprDisplayPosition = null;
nativeVisible(entity, true);
for (const carrier of markers.values()) {
const marker = alprMarkers.write(carrier);
marker.canvasPosition = null;
marker.wedge = null;
marker.displayPosition = null;
nativeVisible(carrier, true);
}
markers.flush();
state.lastAnchorSampleAt = 0;
retryUntil = Date.now() + 15000;
requestPaint();
}
function anchorFor(record, entity, budget) {
if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition;
const scene = state.viewer.scene;
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
function anchorFor(record, carrier, budget) {
const cached = alprMarkers.read(carrier)?.canvasPosition;
if (cached) return cached;
const query = findQuery(state.viewer);
const point = { lon: record.longitude, lat: record.latitude };
// A floor-placed marker anchors where its native badge sits; only a
// marker still waiting for its floor samples the rendered surface, and
// each paint samples a few at most (each sample is a depth render).
@@ -113,20 +106,34 @@ export function createAlprOverlay({
record.longitude,
);
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
else if (scene.sampleHeightSupported) {
else if (query && canSampleHeight()) {
if (budget.samples <= 0) return null;
budget.samples -= 1;
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* streaming tiles */
}
// A miss is tiles still streaming.
height = query.sampleHeightNow(point, { exclude: [markers.icons?.id] });
}
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
// The globe's terrain, while the globe is drawn (hidden under photoreal
// tiles, its height is not what shows).
if (!validAlprGroundHeight(height) && globeShown())
height = query?.sampleHeightNow(point, { against: 'terrain' });
if (!validAlprGroundHeight(height)) return null;
setAnchor(record, entity, height);
return entity.gevAlprCanvasPosition;
setAnchor(record, carrier, height);
return alprMarkers.read(carrier)?.canvasPosition;
}
/**
* Whether the renderer samples the drawn surface's height (Cesium needs
* depth textures). Without, nothing is sampled or spent from the budget,
* and a marker with no floor yet anchors on the terrain.
*/
function canSampleHeight() {
const capabilities = rendererOf(state.viewer)?.capabilities;
return !capabilities || capabilities.has('sampleHeight');
}
/** Whether the globe surface is drawn; true where the renderer cannot say. */
function globeShown() {
return rendererOf(state.viewer)?.globe?.isGlobeVisible?.() !== false;
}
function floorHeightAt(latitude, longitude) {
@@ -134,27 +141,24 @@ export function createAlprOverlay({
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
}
function setAnchor(record, entity, height) {
entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees(
function setAnchor(record, carrier, height) {
const marker = alprMarkers.write(carrier);
marker.canvasPosition = fromDegrees(
record.longitude,
record.latitude,
height,
);
entity.gevAlprWedge = directionWedgePositions(
record,
height,
floorHeightAt,
);
marker.wedge = directionWedgePositions(record, height, floorHeightAt);
if (marker.canvasOwned) markers.changed(carrier);
}
/** Whether the visible photoreal tiles (or globe) have finished streaming. */
function surfaceSettled(scene) {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
const primitive = scene.primitives.get(i);
if (primitive?.show && primitive.tilesLoaded === false) return false;
}
return true;
function surfaceSettled() {
const globe = rendererOf(state.viewer)?.globe;
// The globe's terrain while it is shown, otherwise the shown 3D tiles.
// A viewer with no renderer of its own cannot say; its samples are
// still checked against the floor.
return !globe || globe.isSettled('surface');
}
/**
@@ -165,50 +169,34 @@ export function createAlprOverlay({
* samples far outside the floor prior (a roof or a streaming tile) are
* rejected. Returns whether anchors remain to check.
*/
function refineAnchors(budget) {
const camera = state.viewer.camera;
const scene = state.viewer.scene;
function refineAnchors(budget, pose) {
const still =
lastCamera &&
camera.positionWC &&
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
lastCamera.position,
0,
0.05,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastCamera.direction,
0,
1e-6,
);
if (camera.positionWC && camera.directionWC)
lastCamera = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction: Cesium.Cartesian3.clone(camera.directionWC),
};
if (!scene.sampleHeightSupported) return false;
near(pose.position, lastCamera.position, 0.05) &&
near(pose.direction, lastCamera.direction, 1e-6);
lastCamera = {
position: { ...pose.position },
direction: { ...pose.direction },
};
const query = findQuery(state.viewer);
if (!query || !canSampleHeight()) return false;
let pending = false;
for (const record of records) {
const entity = state.dataSource.entities.getById(record.id);
const anchor = entity?.gevAlprCanvasPosition;
if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue;
if (!still || !surfaceSettled(scene) || budget.samples <= 0) {
const carrier = markers.get(record.id);
const marker = alprMarkers.read(carrier);
const anchor = marker?.canvasPosition;
if (!anchor || marker.surfaceCheckedFor === anchor) continue;
if (!still || !surfaceSettled() || budget.samples <= 0) {
pending = true;
continue;
}
budget.samples -= 1;
let sample;
try {
sample = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude),
[entity],
);
} catch {
/* streaming tiles */
}
const current = Cesium.Cartographic.fromCartesian(anchor).height;
// A miss is tiles still streaming.
const sample = query.sampleHeightNow(
{ lon: record.longitude, lat: record.latitude },
{ exclude: [markers.icons?.id] },
);
const current = toLonLatH(anchor)?.height;
const floor = services.groundFloor.cachedGroundFloor(
record.latitude,
record.longitude,
@@ -219,10 +207,11 @@ export function createAlprOverlay({
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
sample <= floor + SURFACE_ABOVE_FLOOR_M));
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M);
entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition;
if (entity.id === state.selectedId)
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
setAnchor(record, carrier, sample + MARKER_FLOOR_LIFT_M);
// setAnchor rewrote the same record, so this is the new anchor.
marker.surfaceCheckedFor = marker.canvasPosition;
if (carrier.id === state.selectedId)
marker.displayPosition = marker.canvasPosition;
}
return pending;
}
@@ -233,9 +222,11 @@ export function createAlprOverlay({
let unresolved = false;
const painted = [];
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
const pose = cameraOf(state.viewer).pose();
const query = findQuery(state.viewer);
for (const record of records) {
const entity = state.dataSource.entities.getById(record.id);
if (!entity) continue;
const carrier = markers.get(record.id);
if (!carrier) continue;
const selected = record.id === state.selectedId;
const image = images[selected ? 1 : 0];
if (
@@ -243,45 +234,35 @@ export function createAlprOverlay({
!image.naturalWidth ||
(selected && !images[2]?.naturalWidth)
) {
nativeVisible(entity, true);
nativeVisible(carrier, true);
continue;
}
const anchor = anchorFor(record, entity, budget);
const anchor = anchorFor(record, carrier, budget);
if (!anchor) {
nativeVisible(entity, true);
nativeVisible(carrier, true);
unresolved = true;
continue;
}
canvasOwned(entity, true);
canvasOwned(carrier, true);
if (occluder && !occluder.isPointVisible(anchor)) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const scene = state.viewer.scene;
const origin = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
anchor,
);
const origin = query?.project(anchor);
if (!origin) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const alpha =
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
if (!(alpha > 0)) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const wedge = entity.gevAlprWedge;
const wedge = alprMarkers.read(carrier)?.wedge;
if (wedge) {
const left = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
wedge[1],
);
const right = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
wedge[2],
);
const left = query.project(wedge[1]);
const right = query.project(wedge[2]);
if (left && right) {
ctx.save();
ctx.globalAlpha *= alpha;
@@ -295,21 +276,19 @@ export function createAlprOverlay({
origin.y < -60 ||
origin.y > height + 60
) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
setShown(entity, true);
setShown(carrier, true);
painted.push({
record,
origin,
selected,
image,
alpha,
scale: markerScale(
Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor),
),
scale: markerScale(distance(pose.position, anchor)),
});
if (selected) entity.gevAlprDisplayPosition = anchor;
if (selected) alprMarkers.write(carrier).displayPosition = anchor;
}
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
for (const { record, origin, selected, image, alpha, scale } of painted) {
@@ -335,9 +314,11 @@ export function createAlprOverlay({
ctx.restore();
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
}
const refining = refineAnchors({
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
});
const refining = refineAnchors(
{ samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT) },
pose,
);
markers.flush();
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
retryTimer = setTimeout(() => {
retryTimer = null;
@@ -358,7 +339,7 @@ export function createAlprOverlay({
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
return;
lane = services.overlays.registerPaintLane('selected', paint, {
id: `alpr-${Cesium.createGuid()}`,
id: `alpr-${++lanes}`,
active: false,
});
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
@@ -371,9 +352,8 @@ export function createAlprOverlay({
},
sync(visible) {
if (!lane) return;
for (const record of records)
nativeVisible(state.dataSource.entities.getById(record.id), true);
const position = state.viewer.camera.positionWC;
const previous = records;
const position = cameraOf(state.viewer).pose().position;
records = visible
.filter(
(record) =>
@@ -383,13 +363,10 @@ export function createAlprOverlay({
.map((record) => ({
record,
distance: position
? Cesium.Cartesian3.distanceSquared(
? distance(
position,
Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
),
)
fromDegrees(record.longitude, record.latitude),
) ** 2
: 0,
}))
.sort((a, b) => a.distance - b.distance)
@@ -400,6 +377,11 @@ export function createAlprOverlay({
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
records.push(selected);
}
// Cameras that leave the cohort go native; those that stay keep the
// canvas until the next paint, so their icons are not written twice.
const kept = new Set(records.map((record) => record.id));
for (const record of previous)
if (!kept.has(record.id)) nativeVisible(markers.get(record.id), true);
hits = [];
retryUntil = Date.now() + 15000;
lane.setActive(state.enabled && records.length > 0);
@@ -421,8 +403,8 @@ export function createAlprOverlay({
clear() {
clearTimeout(retryTimer);
retryTimer = null;
for (const record of records)
nativeVisible(state.dataSource?.entities.getById(record.id), true);
for (const record of records) nativeVisible(markers.get(record.id), true);
markers.flush();
records = [];
hits = [];
lane?.setActive(false);
+134 -30
View File
@@ -8,6 +8,10 @@ import {
alprLabelDetails,
markerScale,
} from './visuals.js';
import { alprMarkers, createAlprMarkerSet } from './markerState.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { rendererOf } from '../../render/rendererOf.js';
function harness(t, count = 2, { floor = null } = {}) {
const previousImage = globalThis.Image;
@@ -23,23 +27,29 @@ function harness(t, count = 2, { floor = null } = {}) {
longitude: -97,
directionDeg: 90,
}));
const entities = new Cesium.EntityCollection();
const drawPort = fakeDrawPort();
const markers = createAlprMarkerSet();
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
const iconSet = drawPort.set('alpr-cameras:test:markers');
for (const record of records)
entities.add({
id: record.id,
billboard: { image: 'fallback', show: true },
polyline: { show: true },
polygon: { show: true },
Object.assign(alprMarkers.write(markers.add(record.id)), {
record,
position: Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
),
});
markers.flush();
const state = {
enabled: true,
selectedId: null,
dataSource: { entities },
markers,
viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500) },
scene: { globe: { show: true, getHeight: () => 150 } },
},
};
const { unbind } = bindFakeCesiumScene(state.viewer, { draw: drawPort });
let paint,
mapListener,
active,
@@ -80,6 +90,7 @@ function harness(t, count = 2, { floor = null } = {}) {
if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project;
unbind();
});
const draw = [];
const ctx = {
@@ -103,7 +114,11 @@ function harness(t, count = 2, { floor = null } = {}) {
state,
records,
overlay,
entities,
markers,
iconSet,
/** A marker's carrier, and the icon last sent for it. */
carrier: (id) => markers.get(id),
icon: (id) => iconSet.items.get(id),
draw,
paint: (occluder) => paint({ ctx, width: 800, height: 600, occluder }),
mapChanged() {
@@ -131,20 +146,25 @@ test('a selected camera without a bearing gets its badge and brackets, never a f
assert.ok(h.draw[0].endsWith('alpr-marker-selected.png'));
assert.ok(h.draw[1].endsWith('alpr-marker-selected-brackets.png'));
assert.equal(h.overlay.pick({ x: 100, y: 100 }), 'camera:0');
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.icon('camera:0').show, true);
assert.equal(h.icon('camera:0').color[3], 0.01, 'a faint pick target');
assert.equal(
h.entities.getById('camera:0').billboard.color.getValue().alpha,
0.01,
h.icon('camera:0').meta,
h.carrier('camera:0'),
'a pick hands point-and-ask the context carrier',
);
assert.equal(directionWedgePositions(h.records[0]), null);
});
test('the overlay bounds its cohort and promotes selection while leaving farther cameras native', (t) => {
const h = harness(t, 70);
// Floor anchors, so every camera anchors in one paint.
const h = harness(t, 70, { floor: 150 });
h.state.selectedId = 'camera:69';
h.overlay.sync(h.records);
h.paint();
const hidden = h.entities.values.filter((e) => e.gevAlprNativeAppearance);
const hidden = [...h.markers.values()].filter(
(carrier) => alprMarkers.read(carrier)?.canvasOwned,
);
assert.equal(hidden.length, 64);
assert.ok(hidden.some((e) => e.id === 'camera:69'));
assert.equal(
@@ -160,24 +180,25 @@ test('surface changes invalidate cached anchors, and disable/disposal release pa
const h = harness(t, 1);
h.overlay.sync(h.records);
h.paint();
const entity = h.entities.getById('camera:0');
const first = entity.gevAlprCanvasPosition;
const carrier = h.carrier('camera:0');
const first = alprMarkers.read(carrier)?.canvasPosition;
h.paint();
assert.equal(
entity.gevAlprCanvasPosition,
alprMarkers.read(carrier)?.canvasPosition,
first,
'stable anchor across frames',
);
h.state.viewer.scene.globe.show = false;
h.mapChanged();
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(alprMarkers.read(carrier)?.canvasPosition, null);
h.state.enabled = false;
h.overlay.clear();
assert.equal(h.active, false);
assert.equal(h.overlay.pick({ x: 100, y: 100 }), null);
assert.equal(entity.billboard.show.getValue(), true);
assert.equal(entity.billboard.color, undefined);
assert.equal(entity.position, undefined);
const icon = h.icon('camera:0');
assert.equal(icon.show, true);
assert.equal(icon.color, undefined, 'the native badge again');
assert.equal(icon.pos, alprMarkers.read(carrier).position);
h.overlay.destroy();
assert.equal(h.removed, 1);
});
@@ -187,7 +208,8 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
h.state.viewer.scene.globe.getHeight = () => -15000;
h.overlay.sync(h.records);
h.paint();
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.icon('camera:0').show, true);
assert.equal(h.icon('camera:0').color, undefined);
assert.equal(h.draw.length, 0);
h.state.viewer.scene.globe.getHeight = () => 150;
h.paint({ isPointVisible: () => false });
@@ -195,18 +217,37 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
assert.equal(h.draw.length, 0);
});
test('repeated paints of a still view never rewrite marker properties', (t) => {
// Each Entity write raises definitionChanged; paint used to hide then show
// every overlay camera's native marker on every frame.
test('repeated paints of a still view never rewrite markers', (t) => {
// Paint used to hide then show every overlay camera's native marker on
// every frame.
const h = harness(t, 3);
h.overlay.sync(h.records);
h.paint();
let changes = 0;
for (const entity of h.entities.values)
entity.definitionChanged.addEventListener(() => changes++);
h.paint();
const writes = h.iconSet.writes;
for (let i = 0; i < 5; i++) h.paint();
assert.equal(changes, 0);
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.iconSet.writes, writes);
assert.equal(h.icon('camera:0').show, true);
});
test('a resync hands back only the cameras that leave the overlay', (t) => {
const h = harness(t, 2, { floor: 150 });
h.overlay.sync(h.records);
h.paint();
assert.equal(h.icon('camera:0').color[3], 0.01);
assert.equal(h.icon('camera:1').color[3], 0.01);
const writes = h.iconSet.writes;
h.overlay.sync([h.records[0]]);
h.markers.flush();
assert.equal(h.icon('camera:1').color, undefined, 'native again');
assert.equal(h.icon('camera:0').color[3], 0.01, 'still under the canvas');
assert.equal(
h.iconSet.writes,
writes + 1,
'one write, for the camera that left',
);
h.paint();
assert.equal(h.iconSet.writes, writes + 1, 'the next paint writes nothing');
});
test('adapter labels never claim a custom source is public OSM data', () => {
@@ -260,7 +301,7 @@ test('a still view replaces floor anchors with the rendered surface, within the
h.paint();
const height = (id) =>
Cesium.Cartographic.fromCartesian(
h.entities.getById(id).gevAlprCanvasPosition,
alprMarkers.read(h.carrier(id))?.canvasPosition,
).height;
assert.equal(
samples,
@@ -281,3 +322,66 @@ test('a still view replaces floor anchors with the rendered surface, within the
h.paint();
assert.equal(samples, taken, 'each anchor is checked once');
});
test('a bearing wedge is plain ECEF at the apex and its two far corners', () => {
const record = { latitude: 30.26, longitude: -97.74, directionDeg: 90 };
const wedge = directionWedgePositions(record, 150, (lat) =>
lat > 30.26 ? 160 : null,
);
assert.equal(wedge.length, 3);
const apex = Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 150);
assert.deepEqual({ ...wedge[0] }, { x: apex.x, y: apex.y, z: apex.z });
const heights = wedge.map(
(p) =>
Cesium.Cartographic.fromCartesian(new Cesium.Cartesian3(p.x, p.y, p.z))
.height,
);
// The corner north of the apex takes the sampled height; the other falls back.
assert.ok(heights.some((h) => Math.abs(h - 160) < 1e-6));
assert.ok(heights.slice(1).some((h) => Math.abs(h - 150) < 1e-6));
});
test('anchors wait for the surface heights answer from: the globe’s terrain while shown, else the shown 3D tiles', (t) => {
const h = harness(t, 1, { floor: 150 });
const scene = h.state.viewer.scene;
h.state.viewer.camera.directionWC = Cesium.Cartesian3.UNIT_X;
scene.sampleHeightSupported = true;
scene.primitives = { length: 0, get: () => null };
let samples = 0;
scene.sampleHeight = () => (samples++, 172);
// The renderer's own `surface` rule; a non-base tileset still streaming
// over a hidden globe leaves it unsettled.
let surface = false;
const asked = new Set();
rendererOf(h.state.viewer).globe = {
isSettled: (kind) => (asked.add(kind), kind === 'surface' ? surface : true),
};
h.overlay.sync(h.records);
h.paint();
h.paint();
assert.equal(samples, 0, 'no samples while the surface streams');
assert.deepEqual([...asked], ['surface']);
surface = true;
h.paint();
assert.ok(samples > 0, 'sampled once it has loaded');
});
test('without height sampling no sample is spent, and the terrain anchors only while the globe is drawn', (t) => {
for (const shown of [true, false]) {
const h = harness(t, 1);
let samples = 0;
h.state.viewer.scene.sampleHeight = () => (samples++, 172);
const renderer = rendererOf(h.state.viewer);
renderer.capabilities = new Set();
renderer.globe = { isSettled: () => true, isGlobeVisible: () => shown };
h.overlay.sync(h.records);
h.paint();
h.paint();
assert.equal(samples, 0, 'nothing sampled without the capability');
assert.equal(
Boolean(alprMarkers.read(h.carrier('camera:0'))?.canvasPosition),
shown,
shown ? 'anchored on the terrain' : 'no terrain under hidden globe',
);
}
});
+201 -244
View File
@@ -1,28 +1,40 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../data/inputOwnership.js';
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
MAX_VIEWPORT_DEGREES,
MAX_RENDERED,
ALPR_COLOR,
ALPR_SELECTED_COLOR,
MARKER_ICON_SIZE,
SELECTED_MARKER_ICON_SIZE,
CREDIT_DISPLAY_MS,
MARKER_FLOOR_LIFT_M,
MARKER_SCALE_BY_DISTANCE,
} from './policy.js';
import { boxContains } from './model.js';
import { msg } from '../../i18n/index.js';
import { createAlprFloorResolver } from './floors.js';
import { createAlprOverlay } from './overlay.js';
import {
MARKER_IMAGE,
SELECTED_IMAGE,
alprDisplayId,
alprLabelDetails,
validAlprGroundHeight,
} from './visuals.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { alprIconPosition, alprMarkers } from './markerState.js';
import { horizonFrom } from '../../geo/horizon.js';
import {
cameraOf,
canvasOf,
findCredits,
findQuery,
} from '../../render/rendererOf.js';
/** A `#rrggbb` colour as `rgb(r,g,b)`, the form the readout card has always had. */
function cssRgb(hex) {
const n = Number.parseInt(hex.slice(1), 16);
return `rgb(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255})`;
}
export function createAlprPresentation({ state, services, source }) {
const { governorRequestRender } = services.render;
@@ -35,6 +47,7 @@ export function createAlprPresentation({ state, services, source }) {
} = services.context;
const { cachedGroundFloor } = services.groundFloor;
const markers = state.markers;
const overlay = createAlprOverlay({
state,
services,
@@ -42,11 +55,35 @@ export function createAlprPresentation({ state, services, source }) {
});
let visibleRecords = [];
let selectionStartedAt = 0;
/** Markers still clamped while their floor cell resolves (id -> entity). */
/** Markers still clamped while their floor cell resolves (id -> carrier). */
const clampedMarkers = new Map();
let floorResolve = null;
const floors = createAlprFloorResolver(services.groundFloor);
/** Heights under a camera now, through the renderer's query port. */
function heightNow(record, against) {
const query = findQuery(state.viewer);
if (!query) return null;
const point = { lon: record.longitude, lat: record.latitude };
// A miss is tiles still streaming. The markers are no ground: the
// height sees through them.
return against === 'terrain'
? query.sampleHeightNow(point, { against: 'terrain' })
: query.sampleHeightNow(point, { exclude: [markers.icons?.id] });
}
/**
* The ground under a camera: the rendered surface, else the terrain,
* else the cached floor; null when none is plausible.
*/
function groundHeight(record) {
let height = heightNow(record);
if (!validAlprGroundHeight(height)) height = heightNow(record, 'terrain');
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
return validAlprGroundHeight(height) ? height : null;
}
/**
* Marker placement from the cached ground floor (validated mesh or DEM, the
* ellipsoidal datum every layer shares). Ground clamping on photoreal tiles
@@ -54,14 +91,14 @@ export function createAlprPresentation({ state, services, source }) {
* whole-city view stutter while zooming, so it is only the placeholder for
* a cell that has not resolved yet.
* @param {{latitude:number, longitude:number}} record Camera.
* @returns {{position: Cesium.Cartesian3, clamped: boolean}} Placement.
* @returns {{position: {x:number, y:number, z:number}, clamped: boolean}} Placement.
*/
function markerPlacement(record) {
const floor = cachedGroundFloor(record.latitude, record.longitude);
const clamped = !validAlprGroundHeight(floor);
return {
clamped,
position: Cesium.Cartesian3.fromDegrees(
position: fromDegrees(
record.longitude,
record.latitude,
clamped ? 0 : floor + MARKER_FLOOR_LIFT_M,
@@ -130,25 +167,18 @@ export function createAlprPresentation({ state, services, source }) {
* @returns {number|null} Count, or null without a scene to project into.
*/
function countOnScreen() {
const scene = state.viewer?.scene;
const canvas = scene?.canvas;
const canvas = canvasOf(state.viewer);
const width = canvas?.clientWidth || canvas?.width;
const height = canvas?.clientHeight || canvas?.height;
const camera = state.viewer?.camera;
if (!scene || !width || !height || !camera?.positionWC) return null;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.positionWC,
);
const query = findQuery(state.viewer);
if (!query || !width || !height) return null;
let count = 0;
try {
for (const entity of state.dataSource.entities.values) {
const position = entity.position?.getValue?.(Cesium.JulianDate.now());
if (!position || !occluder.isPointVisible(position)) continue;
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
);
const horizon = horizonFrom(cameraOf(state.viewer).pose().position);
for (const carrier of markers.values()) {
const position = alprIconPosition(carrier);
if (!position || !horizon.isPointVisible(position)) continue;
const point = query.project(position);
if (
point &&
point.x >= 0 &&
@@ -165,31 +195,26 @@ export function createAlprPresentation({ state, services, source }) {
return count;
}
/** Write a marker position, respecting the overlay's pick-target swap. */
function setMarkerPosition(entity, position, clamped) {
const heightReference = clamped
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE;
const saved = entity.gevAlprNativeAppearance;
if (saved) {
saved.position = position;
saved.heightReference = heightReference;
} else {
entity.position = position;
entity.billboard.heightReference = heightReference;
}
entity.gevAlprClamped = clamped;
/** Write a marker's native placement; the canvas anchor is left alone. */
function setMarkerPosition(carrier, position, clamped) {
const marker = alprMarkers.write(carrier);
marker.position = position;
marker.clamped = clamped;
markers.changed(carrier);
}
/** Refresh all native placements, including the appearances held by the canvas. */
/** Refresh all native placements, including those under canvas badges. */
function refreshMarkerPlacements() {
if (!state.enabled || !state.dataSource) return;
if (!state.enabled || !markers.icons) return;
clampedMarkers.clear();
for (const entity of state.dataSource.entities.values) {
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
setMarkerPosition(entity, position, clamped);
if (clamped) clampedMarkers.set(entity.id, entity);
for (const carrier of markers.values()) {
const { position, clamped } = markerPlacement(
alprMarkers.read(carrier)?.record,
);
setMarkerPosition(carrier, position, clamped);
if (clamped) clampedMarkers.set(carrier.id, carrier);
}
markers.flush();
resolveClampedFloors();
governorRequestRender('alpr-surface');
}
@@ -202,74 +227,65 @@ export function createAlprPresentation({ state, services, source }) {
const batch = [...clampedMarkers.values()];
const request = Promise.resolve(
floors.resolve(
batch.map((entity) => ({
lat: entity.gevAlprRecord.latitude,
lon: entity.gevAlprRecord.longitude,
})),
batch.map((carrier) => {
const { record } = alprMarkers.read(carrier);
return { lat: record.latitude, lon: record.longitude };
}),
),
)
.catch(() => {})
.then(() => {
if (floorResolve !== request) return;
floorResolve = null;
if (!state.enabled || !state.dataSource) return;
if (!state.enabled || !markers.icons) return;
let moved = false;
for (const entity of batch) {
if (clampedMarkers.get(entity.id) !== entity) continue;
clampedMarkers.delete(entity.id);
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
for (const carrier of batch) {
if (clampedMarkers.get(carrier.id) !== carrier) continue;
clampedMarkers.delete(carrier.id);
const { position, clamped } = markerPlacement(
alprMarkers.read(carrier)?.record,
);
if (clamped) continue;
setMarkerPosition(entity, position, false);
setMarkerPosition(carrier, position, false);
moved = true;
}
markers.flush();
if (moved) governorRequestRender('alpr-floor');
// Cells that never resolved stay clamped; later renders retry them.
});
floorResolve = request;
}
function updateAppearance(entity, selected) {
const color = Cesium.Color.fromCssColorString(
selected ? ALPR_SELECTED_COLOR : ALPR_COLOR,
);
entity.billboard.image = selected ? SELECTED_IMAGE : MARKER_IMAGE;
entity.billboard.width = entity.billboard.height = selected
? SELECTED_MARKER_ICON_SIZE
: MARKER_ICON_SIZE;
if (entity.gevLabelModel) {
entity.gevLabelModel.accent = color.toCssColorString();
entity.gevLabelModel.leaderAnimationStartedAt = selected
? selectionStartedAt
: 0;
function updateAppearance(carrier, selected) {
alprMarkers.write(carrier).selected = selected;
markers.changed(carrier);
const labelModel = readEntityRecord(carrier)?.labelModel;
if (labelModel) {
labelModel.accent = cssRgb(selected ? ALPR_SELECTED_COLOR : ALPR_COLOR);
labelModel.leaderAnimationStartedAt = selected ? selectionStartedAt : 0;
}
}
function markerColor() {
return Cesium.Color.fromCssColorString(ALPR_COLOR);
}
// The horizon rectangle is unstable during low-angle orbits and can exclude
// the ground point in the center of the screen. Bound nearby coverage around
// that point instead; the camera-to-ground range keeps zoom-out queries capped.
function viewportBox(viewer) {
const camera = viewer?.camera;
const canvas = viewer?.scene.canvas;
if (typeof camera?.pickEllipsoid === 'function' && canvas) {
const query = findQuery(viewer);
const canvas = canvasOf(viewer);
if (typeof query?.pickEllipsoid === 'function' && canvas) {
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!width || !height) return null;
const focus = camera.pickEllipsoid(
new Cesium.Cartesian2(width / 2, height / 2),
viewer.scene.globe.ellipsoid,
);
const focus = query.pickEllipsoid(width / 2, height / 2);
if (!focus) return null;
const location = Cesium.Cartographic.fromCartesian(focus);
const range = Cesium.Cartesian3.distance(camera.positionWC, focus);
const location = toLonLatH(focus);
if (!location) return null;
const range = distance(cameraOf(viewer).pose().position, focus);
const radius = Math.max(1000, 2 * range);
const latitude = Cesium.Math.toDegrees(location.latitude);
const longitude = Cesium.Math.toDegrees(location.longitude);
const latitude = location.lat;
const longitude = location.lon;
const latSpan = radius / 111000;
const lonSpan = latSpan / Math.cos(location.latitude);
const lonSpan = latSpan / Math.cos((latitude * Math.PI) / 180);
if (
!Number.isFinite(latSpan + lonSpan) ||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
@@ -285,14 +301,9 @@ export function createAlprPresentation({ state, services, source }) {
};
}
// Rectangle-only viewers retain the same bounded-area contract.
const rectangle = viewer?.camera?.computeViewRectangle(
viewer.scene.globe.ellipsoid,
);
const rectangle = viewer ? cameraOf(viewer).viewRectangle() : null;
if (!rectangle) return null;
const south = Cesium.Math.toDegrees(rectangle.south);
const north = Cesium.Math.toDegrees(rectangle.north);
const west = Cesium.Math.toDegrees(rectangle.west);
const east = Cesium.Math.toDegrees(rectangle.east);
const { south, north, west, east } = rectangle;
if (
!Number.isFinite(south + north + west + east) ||
east <= west ||
@@ -310,7 +321,7 @@ export function createAlprPresentation({ state, services, source }) {
overlay.clear();
visibleRecords = [];
clampedMarkers.clear();
if (state.dataSource?.entities) state.dataSource.entities.removeAll();
markers.clear();
removeEntityContextsForLayer(LAYER_ID);
}
@@ -318,8 +329,8 @@ export function createAlprPresentation({ state, services, source }) {
services.credits?.hideOsmCredit?.(state.viewer, LAYER_ID);
clearTimeout(state.creditTimer);
state.creditTimer = null;
if (state.credit)
state.viewer?.creditDisplay?.removeStaticCredit(state.credit);
state.creditOff?.();
state.creditOff = null;
governorRequestRender('alpr-credit');
}
@@ -334,7 +345,8 @@ export function createAlprPresentation({ state, services, source }) {
}
if (!state.enabled || state.creditPresented || !state.credit) return;
state.creditPresented = true;
state.viewer.creditDisplay?.addStaticCredit(state.credit);
state.creditOff =
findCredits(state.viewer)?.addStatic(state.credit) ?? null;
state.creditTimer = setTimeout(hideOnMapCredit, CREDIT_DISPLAY_MS);
governorRequestRender('alpr-credit');
}
@@ -359,82 +371,68 @@ export function createAlprPresentation({ state, services, source }) {
governorRequestRender('alpr-render');
const visibleIds = new Set(visible.map((record) => record.id));
let changed = false;
state.dataSource.entities.suspendEvents();
for (const entity of [...state.dataSource.entities.values]) {
if (!visibleIds.has(entity.id)) {
state.dataSource.entities.remove(entity);
clampedMarkers.delete(entity.id);
changed = true;
}
const gone = [];
for (const carrier of markers.values())
if (!visibleIds.has(carrier.id)) gone.push(carrier.id);
if (gone.length) {
markers.remove(gone);
for (const id of gone) clampedMarkers.delete(id);
changed = true;
}
removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds });
for (const record of visible) {
const existing = state.dataSource.entities.getById(record.id);
if (existing?.gevAlprRecord === record) {
const existing = markers.get(record.id);
if (alprMarkers.read(existing)?.record === record) {
updateAppearance(existing, record.id === state.selectedId);
continue;
}
const color = markerColor();
const selected = record.id === state.selectedId;
const { position, clamped } = markerPlacement(record);
// Direction wedges are painted by the overlay for the nearest cameras.
// Native ground-clamped wedges (a ground polyline plus a classification
// polygon per camera) cost ~40 ms per frame for 200 downtown cameras on
// photoreal tiles, so markers stay billboards only.
const entityDef = {
id: record.id,
position,
billboard: {
image: selected ? SELECTED_IMAGE : MARKER_IMAGE,
width: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
height: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
heightReference: clamped
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
// City-wide views hold hundreds of badges; let them shrink.
scaleByDistance: new Cesium.NearFarScalar(
...MARKER_SCALE_BY_DISTANCE,
),
},
};
let entity = existing;
// Keep the Cesium entity and its ground-clamping subscription while its
// geometry is unchanged. Updating metadata must not rebuild the marker.
const previous = entity?.gevAlprRecord;
if (!entity) {
entity = state.dataSource.entities.add(entityDef);
entity.gevAlprClamped = clamped;
// photoreal tiles, so markers stay icons only.
let carrier = existing;
// Keep the marker and its icon while its geometry is unchanged.
// Updating metadata must not rebuild the marker.
const previous = alprMarkers.read(carrier)?.record;
if (!carrier) {
carrier = markers.add(record.id);
changed = true;
}
const marker = alprMarkers.write(carrier);
if (!existing) {
marker.position = position;
marker.clamped = clamped;
} else {
if (
previous.latitude !== record.latitude ||
previous.longitude !== record.longitude
) {
setMarkerPosition(entity, position, clamped);
entity.gevAlprCanvasPosition = null;
entity.gevAlprDisplayPosition = null;
setMarkerPosition(carrier, position, clamped);
marker.canvasPosition = null;
marker.displayPosition = null;
}
if (
previous.latitude !== record.latitude ||
previous.longitude !== record.longitude ||
previous.directionDeg !== record.directionDeg
) {
entity.gevAlprCanvasPosition = null;
entity.gevAlprWedge = null;
marker.canvasPosition = null;
marker.wedge = null;
}
}
entity.gevAlprRecord = record;
entity.gevTrackedId = record.id;
marker.record = record;
entityRecord(carrier).trackedId = record.id;
// The mapped camera datum has no elevation; it is not the clamped marker's
// visual anchor. Only the selected marker samples the rendered surface,
// at most once per second, through Cesium's public height APIs.
entity.gevAlprDisplayPosition ??= null;
entity.gevDisplayPosition = () => entity.gevAlprDisplayPosition;
entity.gevLabelModel = {
// at most once per second, through the renderer's height queries.
marker.displayPosition ??= null;
entityRecord(carrier).displayPosition = () => marker.displayPosition;
entityRecord(carrier).labelModel = {
title: alprDisplayId(record),
details: alprLabelDetails(record, source),
accent: color.toCssColorString(),
accent: cssRgb(ALPR_COLOR),
cardStyle: 'tactical',
selected: true,
leaderStyle: 'elbow',
@@ -444,11 +442,12 @@ export function createAlprPresentation({ state, services, source }) {
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
anchorRadiusScale: null,
};
updateAppearance(entity, selected);
registerEntityContext(entity, {
updateAppearance(carrier, selected);
registerEntityContext(carrier, {
id: record.id,
layerId: LAYER_ID,
dataSource: state.dataSource,
// Hidden with the layer: the context store reads its `show`.
dataSource: markers.icons,
layerName: 'ALPR Cameras',
source:
source.attribution?.description || source.label || 'Camera source',
@@ -468,101 +467,85 @@ export function createAlprPresentation({ state, services, source }) {
},
});
}
state.dataSource.entities.resumeEvents();
if (changed) state.renderRevision += 1;
state.onScreen = countOnScreen();
for (const entity of state.dataSource.entities.values)
if (entity.gevAlprClamped) clampedMarkers.set(entity.id, entity);
for (const carrier of markers.values())
if (alprMarkers.read(carrier)?.clamped)
clampedMarkers.set(carrier.id, carrier);
resolveClampedFloors();
const selectedEntity = state.selectedId
? state.dataSource.entities.getById(state.selectedId)
const selectedCarrier = state.selectedId
? markers.get(state.selectedId)
: null;
if (!selectedEntity) state.selectedId = null;
if (!selectedCarrier) state.selectedId = null;
updateSelectedAnchor();
overlay.sync(visible);
if (selectedEntity) services.overlays?.refreshReadout?.(selectedEntity);
markers.flush();
if (selectedCarrier) services.overlays?.refreshReadout?.(selectedCarrier);
// Keep the on-map credit tied to displayed data, not loading or zoom prompts.
if (visible.length) presentOnMapCredit();
else hideOnMapCredit();
}
function focusNearest() {
const camera = state.viewer?.camera;
if (!state.enabled || !camera?.positionWC || state.viewer.trackedEntity)
if (!state.enabled || !state.viewer || isFollowing(state.viewer))
return false;
const port = cameraOf(state.viewer);
const eye = port.pose().position;
let nearest = null,
distance = Infinity;
for (const entity of state.dataSource.entities.values) {
const position = entity.position.getValue(Cesium.JulianDate.now());
const candidate = Cesium.Cartesian3.distanceSquared(
camera.positionWC,
position,
);
if (candidate < distance) {
nearest = entity;
distance = candidate;
best = Infinity;
for (const carrier of markers.values()) {
const position = alprIconPosition(carrier);
if (!position) continue;
const candidate = distance(eye, position);
if (candidate < best) {
nearest = carrier;
best = candidate;
}
}
if (!nearest) return false;
const record = state.recordById.get(nearest.id);
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
let height;
if (state.viewer.scene.sampleHeightSupported) {
try {
height = state.viewer.scene.sampleHeight(location, [nearest]);
} catch {
/* tiles may still be streaming */
}
}
if (!validAlprGroundHeight(height) && state.viewer.scene.globe.show)
height = state.viewer.scene.globe.getHeight?.(location);
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
const center = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
validAlprGroundHeight(height) ? height : 0,
);
const height = groundHeight(record);
const center = fromDegrees(record.longitude, record.latitude, height ?? 0);
if (!selectRecord(nearest.id)) return false;
camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, 30), {
duration: 1.2,
offset: new Cesium.HeadingPitchRange(
camera.heading || 0,
-Math.PI / 4,
800,
),
});
port.flyToBounds(
{ center, radius: 30 },
{
durationS: 1.2,
offset: {
heading: port.pose().heading || 0,
pitch: -Math.PI / 4,
range: 800,
},
},
);
governorRequestRender('alpr-focus');
return true;
}
function selectRecord(id) {
const entity = state.dataSource?.entities.getById(id);
if (!entity || !state.recordById.has(id)) return false;
const carrier = markers.get(id);
if (!carrier || !state.recordById.has(id)) return false;
clearSelection();
state.selectedId = id;
selectionStartedAt = globalThis.performance?.now?.() ?? Date.now();
updateAppearance(entity, true);
updateAppearance(carrier, true);
state.lastAnchorSampleAt = 0;
selectEntityContext(entity);
selectEntityContext(carrier);
updateSelectedAnchor();
overlay.sync(visibleRecords);
markers.flush();
governorRequestRender('alpr-selection');
return true;
}
function clearSelection() {
const entity = state.selectedId
? state.dataSource?.entities.getById(state.selectedId)
: null;
const carrier = state.selectedId ? markers.get(state.selectedId) : null;
const record = state.recordById.get(state.selectedId);
if (entity && record) updateAppearance(entity, false);
if (carrier && record) updateAppearance(carrier, false);
state.selectedId = null;
selectionStartedAt = 0;
overlay.sync(visibleRecords);
markers.flush();
clearSelectedEntityContextForLayer(LAYER_ID);
governorRequestRender('alpr-selection');
}
@@ -574,60 +557,35 @@ export function createAlprPresentation({ state, services, source }) {
clearSelection();
return;
}
const entity = state.dataSource?.entities.getById(state.selectedId);
const carrier = markers.get(state.selectedId);
const record = state.recordById.get(state.selectedId);
if (entity?.gevAlprCanvasPosition) {
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
const marker = alprMarkers.read(carrier);
if (marker?.canvasPosition) {
marker.displayPosition = marker.canvasPosition;
return;
}
if (!entity || !record || Date.now() - state.lastAnchorSampleAt < 1000)
if (!carrier || !record || Date.now() - state.lastAnchorSampleAt < 1000)
return;
state.lastAnchorSampleAt = Date.now();
const scene = state.viewer.scene;
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
let height;
if (scene.sampleHeightSupported) {
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* tiles may still be streaming */
}
}
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
if (!validAlprGroundHeight(height)) return;
const next = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
height,
);
if (
!entity.gevAlprDisplayPosition ||
Cesium.Cartesian3.distance(next, entity.gevAlprDisplayPosition) > 0.1
) {
entity.gevAlprDisplayPosition = next;
const height = groundHeight(record);
if (height === null) return;
const next = fromDegrees(record.longitude, record.latitude, height);
const shown = marker?.displayPosition;
if (!shown || distance(next, shown) > 0.1) {
alprMarkers.write(carrier).displayPosition = next;
governorRequestRender('alpr-anchor');
}
}
function installInteraction(viewer) {
if (state.clickHandler) return;
state.clickHandler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas,
);
state.clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
const picked = viewer.scene.pick(click.position);
// The painted overlay answers first; the scene is picked only if not.
const hit = event.drawHit;
const id =
overlay.pick(click.position) ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
overlay.pick(event.screenPosition) ||
(hit && hit.set === markers.icons?.id ? hit.id : null);
if (
id &&
state.recordById.has(id) &&
@@ -635,12 +593,11 @@ export function createAlprPresentation({ state, services, source }) {
)
selectRecord(id);
else if (state.selectedId) clearSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
}
return {
initOverlay: () => overlay.init(),
destroyOverlay: () => overlay.destroy(),
markerColor,
viewportBox,
clearRendered,
hideOnMapCredit,
+20 -11
View File
@@ -8,7 +8,7 @@ import {
createOverpassAlprSource,
buildOverpassQuery,
} from './source.js';
import { validateAlprSnapshot, alprCreditMarkup } from './model.js';
import { validateAlprSnapshot, alprCredit } from './model.js';
const box = { south: 30, west: -98, north: 30.1, east: -97.9 };
test('the source rejects invalid and unbounded queries before fetching', async () => {
let calls = 0;
@@ -130,19 +130,28 @@ test('source snapshots reject malformed coordinates and duplicate identities', (
);
});
test('provider attribution escapes markup and rejects executable links', () => {
assert.equal(alprCreditMarkup(null), null);
test('provider attribution is plain text with a public HTTPS link only', () => {
assert.equal(alprCredit(null), null);
assert.throws(
() => alprCreditMarkup({ text: 'test', href: 'javascript:alert(1)' }),
() => alprCredit({ text: 'test', href: 'javascript:alert(1)' }),
/HTTPS/,
);
const html = alprCreditMarkup({
text: '<img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
});
assert.ok(html.includes('&lt;img onerror=alert(1)&gt;'));
assert.ok(html.includes('?a=1&amp;b=2'));
assert.ok(!html.includes('<img'));
assert.throws(
() => alprCredit({ text: 'test', href: 'https://user:[email protected]/' }),
/HTTPS/,
);
assert.deepEqual(
alprCredit({
text: '<img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
}),
{
text: 'ALPR: <img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
inline: true,
},
'left as text: the credits port escapes it',
);
});
test('wide detail view returns zoom guidance before any fetch and can retry a smaller view', async () => {
+8 -11
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/index.js';
import { destinationPointDeg } from './model.js';
import {
DIRECTION_CONE_M,
@@ -8,8 +8,8 @@ import {
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
/**
* Badge scale at a camera distance, matching Cesium's NearFarScalar for the
* native badges (linear between near and far, clamped outside).
* Badge scale at a camera distance, matching the native badges'
* scale-by-distance (linear between near and far, clamped outside).
* @param {number} distanceM Camera-to-marker distance.
* @returns {number} Scale factor.
*/
@@ -75,7 +75,8 @@ export function alprLabelDetails(record, source) {
* @param {function(number, number): (number|null)} [heightAt] Optional height
* for the two far corners (degrees lat, lon), so the wedge follows a slope
* instead of floating level from the apex; falls back to the apex height.
* @returns {Array<Cesium.Cartesian3>|null} Apex, left and right corners.
* @returns {Array<{x: number, y: number, z: number}>|null} Apex, left and
* right corners, ECEF.
*/
export function directionWedgePositions(record, heightM = 0, heightAt = null) {
if (!Number.isFinite(record.directionDeg)) return null;
@@ -96,13 +97,9 @@ export function directionWedgePositions(record, heightM = 0, heightAt = null) {
return Number.isFinite(height) ? height : heightM;
};
return [
Cesium.Cartesian3.fromDegrees(record.longitude, record.latitude, heightM),
Cesium.Cartesian3.fromDegrees(left.longitude, left.latitude, corner(left)),
Cesium.Cartesian3.fromDegrees(
right.longitude,
right.latitude,
corner(right),
),
fromDegrees(record.longitude, record.latitude, heightM),
fromDegrees(left.longitude, left.latitude, corner(left)),
fromDegrees(right.longitude, right.latitude, corner(right)),
];
}
+9 -2
View File
@@ -43,7 +43,11 @@ test('passive Contacts releases its installation anchor and subject refresh cann
const subject = createSubject({ state, services, parts });
subject.refreshSelectedSubject();
assert.equal(anchors.length, 1);
assert.ok(anchors[0] instanceof Cesium.Cartesian3);
assert.deepEqual(
{ ...anchors[0] },
{ x: position.x, y: position.y, z: position.z },
);
assert.notEqual(anchors[0], position, 'a copy, not the subject’s own');
controls.setParams({ passive: true });
assert.equal(anchors.at(-1), null);
const released = anchors.length;
@@ -57,5 +61,8 @@ test('passive Contacts releases its installation anchor and subject refresh cann
controls.setParams({ passive: false });
assert.equal(activations, 1);
subject.refreshSelectedSubject();
assert.ok(anchors.at(-1) instanceof Cesium.Cartesian3);
assert.deepEqual(
{ ...anchors.at(-1) },
{ x: position.x, y: position.y, z: position.z },
);
});
+16
View File
@@ -17,11 +17,25 @@ export function createDependencies({
parts.subject.refreshSelectedSubject(true);
return;
}
if (adoptSelectedVessel()) return;
if (layerState.autoFocusRetryPending) {
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
}
}
/**
* Take the selected AIS vessel as the subject, as its selection would have
* had Contacts been on. A followed flight is checked first by the callers.
* @returns {boolean} Whether a vessel became the subject.
*/
function adoptSelectedVessel() {
const vessel = parts.subject.currentSelectedVesselSubject?.();
if (!vessel) return false;
layerState.autoFocusRetryPending = false;
parts.subject.selectSubject(vessel);
return Boolean(layerState.subject);
}
async function enableDependencies(activationId = layerState.activationId) {
const aircraftPending = [];
for (const layerId of DEPENDENCIES) {
@@ -104,6 +118,7 @@ export function createDependencies({
const initialTrackedSubject = parts.subject.currentTrackedFlightSubject();
if (initialTrackedSubject)
parts.subject.selectSubject(initialTrackedSubject);
else adoptSelectedVessel();
return enableDependencies(activationId)
.then(() => {
if (
@@ -121,6 +136,7 @@ export function createDependencies({
parts.subject.selectSubject(layerState.subject);
return;
}
if (adoptSelectedVessel()) return;
if (layerState.autoFocusAttempted) return;
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
})
+17 -12
View File
@@ -11,22 +11,27 @@ import { useAwarenessDirectionStore } from '../../ui/stores/awarenessDirection.j
import AwarenessDirection from '../../ui/views/panels/AwarenessDirection.vue';
import { createState } from './state.js';
import { createRendering } from './rendering.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
/** The rendering part over a subject with one military contact due east. */
function overlay(screenAngle) {
const state = createState({ services: {} });
const container = document.body.appendChild(document.createElement('div'));
const subject = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
Object.assign(state, {
viewer: {
container,
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
camera: {
heading: 0,
rightWC: new Cesium.Cartesian3(0, 1, 0),
upWC: new Cesium.Cartesian3(0, 0, 1),
},
const camera = fakeCameraPort({
pose: { heading: 0, right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const viewer = {
container,
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
};
bindRenderer(viewer, { camera: camera.port });
Object.assign(state, {
viewer,
enabled: true,
subject: { position: subject, layerId: 'military' },
results: {
@@ -65,7 +70,7 @@ function overlay(screenAngle) {
},
parts: {},
});
return { state, container, rendering };
return { state, container, rendering, camera };
}
test('the overlay publishes the compass and the nearest contact bearings', () => {
@@ -108,14 +113,14 @@ test('an unstable frame keeps the last stable bearing, until the overlay is remo
{ angle: 2, opacity: 0.5, stable: false },
];
const previous = [];
const { state, rendering } = overlay((x, y, last) => {
const { state, rendering, camera } = overlay((x, y, last) => {
previous.push(last);
return answers.shift() ?? { angle: last ?? 0, opacity: 1, stable: true };
});
rendering.updateDirectionOverlay();
assert.equal(state.directionAngles[0], 1);
// The heading turns, so the next frame recomputes the contact.
state.viewer.camera.heading = 0.1;
camera.setPose({ heading: 0.1 });
rendering.updateDirectionOverlay();
assert.equal(previous[1], 1, 'the unstable frame is given the last angle');
assert.equal(state.directionAngles[0], 1, 'and does not replace it');
+14 -16
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { VESSEL_FOCUS_RADIUS_M } from './policy.js';
import { cameraOf, findCamera } from '../../render/rendererOf.js';
import { clone, distance } from '../../geo/index.js';
export function createFocus({ state: layerState, services, parts, source }) {
const flightsLayer = services.flights;
@@ -45,9 +46,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
)
return true;
announceNavigationAuthority('context-vessel-focus');
layerState.viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
{ duration: 1.4 },
cameraOf(layerState.viewer).flyToBounds(
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
{ durationS: 1.4 },
);
return true;
}
@@ -74,7 +75,7 @@ export function createFocus({ state: layerState, services, parts, source }) {
layerId,
id: String(known.id || known.mmsi),
label: known.label || known.name || known.callsign || String(id),
position: Cesium.Cartesian3.clone(known.position),
position: clone(known.position),
});
return true;
}
@@ -106,13 +107,13 @@ export function createFocus({ state: layerState, services, parts, source }) {
/**
* Pick the observed candidate closest to the current view. This is intentionally
* a navigation preference, not a risk, capability, or affiliation calculation.
* @param {Array<{position: Cesium.Cartesian3}>} candidates Observed candidates.
* @param {Array<{position: {x: number, y: number, z: number}}>} candidates Observed candidates.
* @returns {Object|null} The best currently observable candidate.
*/
function closestToCurrentView(candidates) {
if (!Array.isArray(candidates) || !candidates.length) return null;
const cameraPosition = layerState.viewer?.camera?.positionWC;
const cameraPosition = findCamera(layerState.viewer)?.pose()?.position;
if (!cameraPosition)
return candidates.find((candidate) => candidate?.position) || null;
@@ -120,13 +121,10 @@ export function createFocus({ state: layerState, services, parts, source }) {
let closestDistance = Infinity;
for (const candidate of candidates) {
if (!candidate?.position) continue;
const distance = Cesium.Cartesian3.distance(
cameraPosition,
candidate.position,
);
if (Number.isFinite(distance) && distance < closestDistance) {
const metres = distance(cameraPosition, candidate.position);
if (Number.isFinite(metres) && metres < closestDistance) {
closest = candidate;
closestDistance = distance;
closestDistance = metres;
}
}
return closest;
@@ -180,9 +178,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
announceNavigationAuthority('context-vessel-autofocus', {
cancelPendingSelection: false,
});
layerState.viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
{ duration: 1.6 },
cameraOf(layerState.viewer).flyToBounds(
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
{ durationS: 1.6 },
);
return true;
}
+1 -1
View File
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
return (
items.find(
(item) =>
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
) || subject
);
}
+8 -1
View File
@@ -13,7 +13,14 @@ import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
/** Construct one layer with its own scene state and supplied application services. */
/**
* Construct one layer with its own scene state and supplied application services.
*
* Its context rim is a renderer draw set (`drawOf(viewer)`) and its flights
* go through `cameraOf`. Given a Cesium viewer with no
* renderer bound, the caller loads the package's `./render/cesium/unbound`
* export first.
*/
export function createAwarenessLayer({ services, source }) {
const state = createState({ services });
const parts = {};
+37 -29
View File
@@ -1,4 +1,4 @@
import { cameraPoseSignature } from '../../data/iconOrientation.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { AWARENESS_RANGE_PULSE } from './policy.js';
export function createLifecycle({
@@ -11,13 +11,13 @@ export function createLifecycle({
/**
* Note the user handling the map's camera (pointer, wheel or touch on the
* Cesium canvas, where its camera controller listens), so a camera move the
* user made can wake the range pulses and one the app made (tracking,
* cockpit, orbit, a fly-to) does not. Keys are left out: Cesium's camera
* controller reads none, and typing elsewhere must not count. Nor does
* input while the camera controller's inputs are off: the cockpit (or a
* gizmo drag, or a drawing tool) owns the camera then, and the user's
* gesture moves nothing.
* renderer's canvas, where its camera controls listen), so a camera move
* the user made can wake the range pulses and one the app made (tracking,
* cockpit, orbit, a fly-to) does not. Keys are left out: the camera
* controls read none, and typing elsewhere must not count. Nor does input
* while the camera controls are suspended: the cockpit (or a gizmo drag,
* or a drawing tool) owns the camera then, and the user's gesture moves
* nothing.
*/
function noteCameraInput(event) {
if (event?.type === 'pointermove' && !event.buttons) return;
@@ -28,8 +28,9 @@ export function createLifecycle({
followGesture(true);
}
// A drag can leave the canvas, and Cesium follows it at document level
// (in Firefox, and wherever there are no pointer events). So does this,
// A drag can leave the canvas, and the camera controls follow it at
// document level (in Firefox, and wherever there are no pointer events).
// So does this,
// from a gesture's start on the canvas to its end, so a long gesture keeps
// the input window open the whole way.
const GESTURE_MOVE_EVENTS = ['pointermove', 'touchmove'];
@@ -56,7 +57,7 @@ export function createLifecycle({
}
// A gesture ends with its last contact: lifting one finger of a pinch
// leaves Cesium a one-finger drag.
// leaves the camera controls a one-finger drag.
function endGesture(event) {
noteCameraInput(event);
activePointers.delete(event?.pointerId);
@@ -77,8 +78,7 @@ export function createLifecycle({
}
function cameraInputsEnabled() {
const controller = layerState.viewer?.scene?.screenSpaceCameraController;
return controller?.enableInputs !== false;
return findCamera(layerState.viewer)?.controls?.enabled !== false;
}
const CAMERA_INPUT_EVENTS = [
@@ -90,16 +90,22 @@ export function createLifecycle({
];
/**
* Quantized camera-pose signature, or '' when the camera cannot report a full
* pose yet. An unknown pose reads as PARKED, so a camera that is still coming
* up can never be mistaken for continuous movement.
* @param {Cesium.Camera|null|undefined} camera
* Quantized camera-pose signature (position to ~10 m, angles to ~0.06
* degrees), or '' when the camera cannot report a full pose yet. An unknown
* pose reads as PARKED, so a camera that is still coming up can never be
* mistaken for continuous movement.
* @param {object|null|undefined} viewer
* @returns {string}
*/
function cameraMotionSignature(camera) {
if (!camera?.positionWC || !Number.isFinite(camera.heading)) return '';
return cameraPoseSignature(camera);
function cameraMotionSignature(viewer) {
const pose = findCamera(viewer)?.pose();
const p = pose?.position;
if (!p || !Number.isFinite(pose.heading)) return '';
return (
`${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${pose.heading.toFixed(3)}:${pose.pitch.toFixed(3)}:${pose.roll.toFixed(3)}`
);
}
/**
@@ -131,23 +137,23 @@ export function createLifecycle({
'gev:awareness-subject-cleared',
layerState.subjectClearListener,
);
const input = layerState.viewer.canvas ?? layerState.viewer.scene?.canvas;
const input = canvasOf(layerState.viewer);
for (const type of CAMERA_INPUT_EVENTS)
input?.addEventListener?.(type, noteCameraInput, { passive: true });
layerState.cameraInputTarget = input ?? null;
layerState.preRenderRemover =
layerState.viewer.scene.preRender.addEventListener(() => {
layerState.preRenderRemover = findFrame(layerState.viewer)?.on(
'preRender',
() => {
if (!layerState.enabled) return;
const now = Date.now();
// Another owner took the camera: a gesture begun before it did must
// not wake the pulses on that owner's first move.
if (!cameraInputsEnabled())
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
// "Did the camera move" uses the SAME quantized pose signature the fleet
// rotation pass gates on (iconOrientation.cameraPoseSignature) rather than
// camera.changed, whose granularity is globally degraded by other layers
// mutating camera.percentageChanged.
const poseSig = cameraMotionSignature(layerState.viewer.camera);
// "Did the camera move" uses the same quantization as the fleet
// rotation pass's cameraPoseSignature (render/cesium/iconOrientation;
// keep the two in step), read from the camera port's pose.
const poseSig = cameraMotionSignature(layerState.viewer);
if (poseSig !== layerState.lastCameraPoseSig) {
layerState.lastCameraPoseSig = poseSig;
layerState.lastCameraPoseChangeMs = now;
@@ -183,7 +189,8 @@ export function createLifecycle({
} else {
parts.rendering.scheduleDirectionOverlayUpdate();
}
});
},
);
layerState.runtimeListenersAttached = true;
}
@@ -335,6 +342,7 @@ export function createLifecycle({
detachRuntimeListeners();
parts.panel.clearPanel();
parts.rendering.removeDirectionOverlay();
parts.rendering.disposeVisual();
layerState.subjectListener = null;
layerState.contextListener = null;
layerState.clearListener = null;
+24 -6
View File
@@ -117,7 +117,7 @@ export function createPanel({ state: layerState, parts }) {
.slice(page, page + AWARENESS_PAGE_SIZE)
.map((item, index) => {
const label = formatAwarenessLabel(item);
const targetId = item.icao24 || item.mmsi || item.id;
const targetId = item.icao24 || item.id || item.mmsi;
const distance = presentAwarenessDistance(item.distanceM);
if (!targetId)
return {
@@ -182,7 +182,22 @@ export function createPanel({ state: layerState, parts }) {
: null;
}
/** The tracked airliner's photo with its credit, or null. The subject
/** The credit line: the photographer, and an open photo's licence. A
* photo whose answer names no photographer shows no photographer. */
function photoCredit(photo) {
if (photo.licence)
return photo.photographer
? t('Photo: {photographer} · {licence}', {
photographer: photo.photographer,
licence: photo.licence,
})
: t('Photo · {licence}', { licence: photo.licence });
return photo.photographer
? t('Photo © {photographer}', { photographer: photo.photographer })
: '';
}
/** The subject's photo with its credit, or null. The subject
* refresh resolves it; only the subject it was resolved for shows it. */
function presentPhoto(subject) {
const held = layerState.subjectPhoto;
@@ -198,9 +213,7 @@ export function createPanel({ state: layerState, parts }) {
width: photo.width ?? null,
height: photo.height ?? null,
link: photo.link,
credit: t('Photo © {photographer}', {
photographer: photo.photographer,
}),
credit: photoCredit(photo),
};
}
@@ -209,9 +222,14 @@ export function createPanel({ state: layerState, parts }) {
ensurePanel();
layerState.panelRenders += 1;
const { subject, cohorts } = layerState.results;
const windowLabel = t('{distance} FLIGHT / VESSEL WINDOW', {
distance: presentAwarenessDistance(AWARENESS_RADIUS_M),
});
publish({
kind: 'results',
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
subject: `${subject.label} · ${windowLabel}`,
subjectIdentity: { layerId: subject.layerId, id: subject.id },
subjectLabel: subject.label,
subjectNames: presentNames(subject.memberNames),
photo: presentPhoto(subject),
navigation: presentNavigation(),
+57 -1
View File
@@ -87,6 +87,17 @@ test('the Contacts view carries the tracked flight’s photo with its credit', (
});
});
test('the Contacts view shows an uncredited photo with no credit line', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: { ...PHOTO, photographer: '' },
});
assert.equal(view.photo.src, PHOTO.src);
assert.equal(view.photo.link, PHOTO.link);
assert.equal(view.photo.credit, '');
});
test('the Contacts view has no photo without one, or with another subject’s', () => {
assert.equal(photoView(FLIGHT, null).photo, null);
assert.equal(
@@ -102,7 +113,52 @@ test('the Contacts view has no photo without one, or with another subject’s',
);
});
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
test('the selected vessel shows its own photo, by its id', () => {
const asked = [];
const { resolveSubjectPhoto, subjectFromContext } = createSubject({
state: {},
services: {
flights: {},
military: {},
vessels: {
getVesselPhoto: (id) => {
asked.push(id);
return id === 'uuid-1' ? PHOTO : null;
},
},
installations: {},
},
parts: { navigation: { isFlightLayer: () => false } },
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-1' }),
PHOTO,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-2' }),
null,
);
assert.deepEqual(asked, ['uuid-1', 'uuid-2']);
const vessel = (label, mmsi) =>
subjectFromContext({
layerId: 'ais-live-vessels',
id: 'ais-uuid-1',
label,
latitude: 38.3,
longitude: -123.05,
properties: { vesselId: 'uuid-1', mmsi },
});
assert.equal(
vessel('USCGC SOCKEYE', '366999709').label,
'USCGC SOCKEYE · MMSI 366999709',
);
assert.equal(vessel('USCGC SOCKEYE', '366999709').id, 'uuid-1');
// A vessel named by its MMSI, or without one, is not given it twice.
assert.equal(vessel('MMSI 366999709', '366999709').label, 'MMSI 366999709');
assert.equal(vessel('USCGC SOCKEYE', null).label, 'USCGC SOCKEYE');
});
test('only the tracked flight has a flight photo: not an installation, a military aircraft or another flight', () => {
const tracked = {
layerId: 'flights',
id: 'abc123',
+20 -17
View File
@@ -49,7 +49,8 @@ export const CONTEXT_RIM_HEIGHT_M = 2500;
* the FLIR, NVG and CRT styles. A bright core inside a dark halo keeps
* luminance contrast on light and dark ground alike, and luminance is what
* the monochrome styles keep. The core is the Context panel's blue; the halo
* is the map-card ink. Widths are screen pixels; `outlineWidth` is per side.
* is the map-card ink. Widths are screen pixels; `outlineWidth` is the
* halo's width in all, half on each side.
* It is drawn as an unpickable primitive, so clicks on its edge reach the
* contacts underneath.
* While the sonar pulses run, the ring dims to `restOpacity` and flashes
@@ -74,30 +75,32 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
* over `fadeInFraction` of its travel, then fades as (1 - travel) to the
* `fadeOutPower` down to `endOpacityFraction` of `peakOpacity`, so a pulse
* is dim but still visible when it reaches the ring and the ring flashes.
* Each line is `width` CSS pixels wide, its outer `outlineWidth` a dark
* halo, in the ring's colours, as Cesium's polyline outline material draws.
* Each front is a line `width` CSS pixels wide whose outer `outlineWidth`,
* half on each side, is a dark halo, in the ring's colours.
* Behind each line a radial gradient in the same blue fades inward over
* `gradientDepthFraction` of the radius, at most
* `gradientOpacity` strong. One unpickable disc draws the lines and the
* gradient, so pulses never catch a click meant for a contact; its shader
* takes at most four pulses. The disc follows the subject by a model-matrix
* rotation, so it stays concentric with the ring, and is rebuilt only after
* the subject moves `gradientRebuildM` from where it was built; while the
* pulses rest the hidden disc is left alone and catches up when they wake. The
* disc is hidden while the camera is below its height, where it would sweep
* the sky.
* `gradientDepthFraction` of the radius, at most `gradientOpacity` strong,
* painted on a canvas that fills one flat ellipse at the rim. Lines and
* ellipse are unpickable, so pulses never catch a click meant for a
* contact. The ellipse is `gradientRebuildM` wider than the ring and moves
* only after the subject moves that far from where it was built, the
* canvas keeping the band concentric meanwhile; while the pulses rest the
* hidden band is left alone and catches up when they wake. The band is
* hidden while the camera is below its height, where it would sweep the
* sky.
* The pulses run for `activeMs` (three ring flashes) after a selection or
* a camera move, fading in and out over `settleMs`, then rest: the ring
* stays on screen, static, and nothing asks for frames, so a parked view
* goes quiet again. Only a camera move within `inputWakeMs` of the user
* handling the map (pointer, wheel or touch on the canvas, which covers a
* drag's inertia, while the camera controls take input) wakes them; a moving subject and the app's own camera moves
* (tracking, cockpit, orbit, a fly-to) do not. Below the disc's height they
* (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they
* rest too. While they run they never hold
* continuous rendering; each drawn frame arms one more request after the
* Cyber sonar's 80 ms cadence, so the two never beat. When something else
* already renders continuously they update every frame. Skipped under
* prefers-reduced-motion. */
* continuous rendering; each drawn frame arms one more step after the
* Cyber sonar's 80 ms cadence, so the two never beat. Fronts and band,
* fixed in the world, step at that cadence however many frames are
* drawn, so they look the same whether the camera moves or not; crossing
* the rim height shows or hides them at once.
* Skipped under prefers-reduced-motion. */
export const AWARENESS_RANGE_PULSE = Object.freeze({
count: 3,
periodMs: 9000,
+802
View File
@@ -0,0 +1,802 @@
/**
* @module layers/awareness/rangeRing
* @description The Global Context range ring and its sonar pulses, drawn
* through the renderer's draw port. The ring is a haloed line (a solid line
* with an outline) 2.5 km above the ellipsoid. While pulses run, each pulse
* front is a haloed line whose positions move each step, every
* `CYBER_SONAR_RENDER_INTERVAL_MS` whether the camera moves or not. The
* band behind the fronts is one flat ellipse at the same height filled
* with a canvas painted anew each step (a new key for new content). Nothing here is
* pickable, so a click or tap near the ring reaches the contact underneath.
* Under reduced motion, or where the renderer has no frame hooks, the ring
* alone is drawn and stays.
*/
import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js';
import { AWARENESS_RADIUS_M } from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_RANGE_ECHO,
AWARENESS_RANGE_PULSE,
AWARENESS_RANGE_RING_STYLE,
CONTEXT_RIM_HEIGHT_M,
} from './policy.js';
import {
awarenessEchoStrength,
clearAwarenessEchoField,
setAwarenessEchoField,
} from '../../awarenessEcho.js';
import { WGS84, fromRadians, toLonLatH } from '../../geo/ellipsoid.js';
import { distance, sub } from '../../geo/vector.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
/**
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
* raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's
* radius of curvature in that direction (Euler's formula), which keeps the
* ring within ~50 m of the true geodesic radius at 250 km.
* @param {{x: number, y: number, z: number}} groundCenter Ring centre on the ellipsoid.
* @param {number} radiusM Surface radius in metres.
* @param {number} heightM Height of the ring above the ellipsoid.
* @param {number} [segments] Chords around the ring.
* @returns {{x: number, y: number, z: number}[]} `segments + 1` positions;
* the last repeats the first.
*/
export function awarenessRangeRingPositions(
groundCenter,
radiusM,
heightM,
segments = AWARENESS_RANGE_RING_STYLE.segments,
) {
const { up, bearings } = ringFrame(groundCenter, segments);
const r2 = WGS84.radiiSquared;
const positions = new Array(bearings.length);
for (let i = 0; i < bearings.length; i++) {
const { per, along } = bearings[i];
const angular = radiusM * per;
const cosA = Math.cos(angular);
const sinA = Math.sin(angular);
// The unit vector there on the sphere, taken as the ellipsoid's
// surface normal (its latitude read as geodetic) and raised to
// `heightM` along it, as `fromRadians` places a longitude and latitude.
let nx = up[0] * cosA + along[0] * sinA;
let ny = up[1] * cosA + along[1] * sinA;
let nz = up[2] * cosA + along[2] * sinA;
const length = Math.hypot(nx, ny, nz);
nx /= length;
ny /= length;
nz /= length;
const kx = r2.x * nx;
const ky = r2.y * ny;
const kz = r2.z * nz;
const gamma = Math.sqrt(nx * kx + ny * ky + nz * kz);
positions[i] = {
x: kx / gamma + nx * heightM,
y: ky / gamma + ny * heightM,
z: kz / gamma + nz * heightM,
};
}
return positions;
}
/** The last ring frame made: fronts at one centre share it. */
let lastRingFrame = null;
/**
* What a ring about `groundCenter` needs but its radius: the centre's up
* unit vector and, per bearing, the angle a metre of surface turns
* (Euler's formula) and the unit vector along the great circle. Kept for
* the last centre asked for.
*/
function ringFrame(groundCenter, segments) {
const last = lastRingFrame;
if (
last?.segments === segments &&
last.x === groundCenter.x &&
last.y === groundCenter.y &&
last.z === groundCenter.z
)
return last;
const { lon, lat } = toLonLatH(groundCenter);
const latitude = (lat * Math.PI) / 180;
const longitude = (lon * Math.PI) / 180;
const { x: a, z: b } = WGS84.radii;
const e2 = 1 - (b * b) / (a * a);
const sinLat = Math.sin(latitude);
const cosLat = Math.cos(latitude);
const sinLon = Math.sin(longitude);
const cosLon = Math.cos(longitude);
const w = 1 - e2 * sinLat * sinLat;
const meridional = (a * (1 - e2)) / (w * Math.sqrt(w));
const primeVertical = a / Math.sqrt(w);
// Step along the great circle in 3D from the centre's up, north and east
// unit vectors. Unlike the latitude/longitude destination formula, this
// stays well conditioned at and next to the poles.
const up = [cosLat * cosLon, cosLat * sinLon, sinLat];
const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat];
const east = [-sinLon, cosLon, 0];
const bearings = [];
for (let i = 0; i <= segments; i++) {
const bearing = ((i % segments) / segments) * 2 * Math.PI;
const cosB = Math.cos(bearing);
const sinB = Math.sin(bearing);
bearings.push({
per: (cosB * cosB) / meridional + (sinB * sinB) / primeVertical,
along: north.map((n, k) => n * cosB + east[k] * sinB),
});
}
lastRingFrame = {
x: groundCenter.x,
y: groundCenter.y,
z: groundCenter.z,
segments,
up,
bearings,
};
return lastRingFrame;
}
/**
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
* constant speed from `startFraction` of the range to the full range, fade in
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
* but still visible when it reaches the range ring. The opacity already
* includes `peakOpacity`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} index Pulse number, 0 to `count - 1`.
* @param {number} [radiusM] Range the pulses grow to.
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
* @returns {{radiusM: number, alpha: number}}
*/
export function awarenessPulseState(
nowMs,
index,
radiusM = AWARENESS_RADIUS_M,
pulse = AWARENESS_RANGE_PULSE,
) {
const cycle = nowMs / pulse.periodMs + index / pulse.count;
const phase = cycle - Math.floor(cycle);
return {
radiusM:
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
alpha:
pulse.peakOpacity *
Math.min(1, phase / pulse.fadeInFraction) *
(pulse.endOpacityFraction +
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
};
}
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
/** Whether the viewer asked the system for less motion. */
function prefersReducedMotion() {
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
}
/**
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
* `wake.untilMs`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {number} 0 to 1.
*/
export function awarenessPulseLevel(
nowMs,
wake,
pulse = AWARENESS_RANGE_PULSE,
) {
const level = Math.min(
(nowMs - wake.startMs) / pulse.settleMs,
(wake.untilMs - nowMs) / pulse.settleMs,
);
return Math.max(0, Math.min(1, level));
}
/**
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
* keeps their current level, so they never jump back to full mid-fade.
* @param {{startMs: number, untilMs: number}} wake Updated in place.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {{startMs: number, untilMs: number}} `wake`.
*/
export function wakeAwarenessPulses(
wake,
nowMs,
pulse = AWARENESS_RANGE_PULSE,
) {
wake.startMs =
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
wake.untilMs = nowMs + pulse.activeMs;
return wake;
}
/**
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
* pulse front reaches it, fading over `flashMs`, so the ring appears once
* per arriving pulse instead of standing on screen.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
export function awarenessRingFlash(nowMs) {
return awarenessEchoStrength(
nowMs,
AWARENESS_RADIUS_M,
AWARENESS_RADIUS_M,
AWARENESS_RANGE_PULSE,
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
);
}
/** `rgba(r, g, b, a)` as a draw-port colour, channels 0 to 1. */
function rgba(css) {
const [r, g, b, a = 1] = css.match(/[\d.]+/g).map(Number);
return [r / 255, g / 255, b / 255, a];
}
/** A colour with its alpha scaled by `alpha`. */
const faded = ([r, g, b, a], alpha) => [r, g, b, a * alpha];
/**
* A haloed line as the draw port draws it: `widthPx` wide, an outer
* `haloPx` in all (half on each side) in the halo's colour, the rest in the
* core's.
* @returns {object} The line item.
*/
const haloedLine = (id, positions, { core, halo, widthPx, haloPx, show }) => ({
id,
positions,
widthPx,
mode: '3d',
style: {
kind: 'solid',
color: core,
outline: { color: halo, widthPx: haloPx },
},
show,
});
/** Side of the band's canvas, pixels: the band is soft, 2 km a pixel. */
export const AWARENESS_BAND_PIXELS = 256;
/**
* The band behind the pulse fronts into `image` (an `ImageData` of
* `size × size`): at each pixel, a fraction `r` of `rangeM` from the
* subject, the sum over pulses of `alpha × t²` where the pulse's front is
* within `gradientDepthFraction` of the range outside it (`t` is 1 at the
* front, 0 that far inward), times `gradientOpacity`, in `rgb`. The canvas
* spans `spanM` either side of its centre; the subject is `offset` metres
* east and north of that centre.
*
* The band depends on the distance from the subject alone: its alpha byte
* is tabulated along the radius, out to the range or the outermost front
* if that is further, finer than a pixel, and each pixel looks it up. Which
* entry each pixel reads changes only with the canvas, its span and the
* subject's offset; `memo`, kept between calls, holds it, so a step that
* only moves the fronts takes no square roots.
* @param {{data: Uint8ClampedArray, width: number}} image
* @param {{radii: number[], alphas: number[], rgb: number[], spanM: number,
* rangeM: number, offset: {east: number, north: number}, pulse?: object}} band
* @param {object} [memo] An object of the caller's, empty at first.
*/
export function paintAwarenessBand(image, band, memo = {}) {
const { radii, alphas, rgb, spanM, rangeM, offset } = band;
const pulse = band.pulse ?? AWARENESS_RANGE_PULSE;
const size = image.width;
const data = image.data;
const depth = pulse.gradientDepthFraction;
const opacity = pulse.gradientOpacity;
let outer = 0;
for (const radius of radii) outer = Math.max(outer, radius);
const reach = Math.max(1, outer);
const bins = 4 * size;
// Past `reach` a pixel reads the last entry, which stays 0.
if (memo.table?.length !== bins + 2) memo.table = new Uint8Array(bins + 2);
const table = memo.table;
for (let bin = 0; bin <= bins; bin++) {
const at = (bin / bins) * reach;
let sum = 0;
for (let i = 0; i < radii.length; i++) {
const inside = radii[i] - at;
if (inside >= 0 && inside <= depth) {
const t = 1 - inside / depth;
sum += alphas[i] * t * t;
}
}
// `Math.round` of a non-negative value.
table[bin] = (Math.min(1, sum * opacity) * 255 + 0.5) | 0;
}
table[bins + 1] = 0;
const key = `${size} ${spanM} ${rangeM} ${reach} ${offset.east} ${offset.north}`;
if (memo.key !== key) {
memo.key = key;
const bin = (memo.bin =
memo.bin?.length === size * size
? memo.bin
: new Uint16Array(size * size));
const perPixel = (2 * spanM) / size / rangeM;
const cx = size / 2 + offset.east / ((2 * spanM) / size);
// Canvas rows run north to south.
const cy = size / 2 - offset.north / ((2 * spanM) / size);
const toBin = bins / reach;
for (let y = 0; y < size; y++) {
const dy = (y + 0.5 - cy) * perPixel;
const dy2 = dy * dy;
for (let x = 0; x < size; x++) {
const dx = (x + 0.5 - cx) * perPixel;
const at = Math.sqrt(dx * dx + dy2);
bin[y * size + x] = at > reach ? bins + 1 : (at * toBin + 0.5) | 0;
}
}
}
const bin = memo.bin;
// Clamped as the image's bytes would clamp them.
const [r, g, b] = rgb.map((c) =>
Math.min(255, Math.max(0, Math.round(c * 255))),
);
// Whole pixels at a time where the bytes line up: each table entry as
// the four bytes it writes, in the platform's byte order.
if (data.byteOffset % 4 === 0 && data.length === bin.length * 4) {
if (memo.pixels?.length !== table.length)
memo.pixels = new Uint32Array(table.length);
const pixels = memo.pixels;
for (let i = 0; i < table.length; i++)
pixels[i] = LITTLE_ENDIAN
? (r | (g << 8) | (b << 16) | (table[i] << 24)) >>> 0
: ((r << 24) | (g << 16) | (b << 8) | table[i]) >>> 0;
const words = new Uint32Array(data.buffer, data.byteOffset, bin.length);
for (let p = 0; p < bin.length; p++) words[p] = pixels[bin[p]];
return;
}
for (let p = 0, k = 0; p < bin.length; p++, k += 4) {
data[k] = r;
data[k + 1] = g;
data[k + 2] = b;
data[k + 3] = table[bin[p]];
}
}
/** Whether this platform stores the low byte of a word first. */
const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
/** `p` in metres east and north of `origin`, in `origin`'s surface frame. */
function eastNorth(origin, p) {
const { lon, lat } = toLonLatH(origin);
const l = (lon * Math.PI) / 180;
const f = (lat * Math.PI) / 180;
const d = sub(p, origin);
return {
east: -Math.sin(l) * d.x + Math.cos(l) * d.y,
north:
-Math.sin(f) * Math.cos(l) * d.x -
Math.sin(f) * Math.sin(l) * d.y +
Math.cos(f) * d.z,
};
}
/** Camera height above the ellipsoid, or NaN when the renderer cannot say. */
function cameraHeightM(viewer) {
return findCamera(viewer)?.pose()?.height ?? Number.NaN;
}
/** Each instance's set ids are its own. */
let instances = 0;
/**
* The range ring and pulses of one awareness layer.
* `layerState.visual` is what is drawn now, or null.
* @param {object} options
* @param {object} options.state
* @param {(reason: string) => void} options.governorRequestRender
* @param {(subject: object) => void} options.redraw Draws the subject's
* ring again (a reduced-motion change).
*/
export function createRangeRing({
state: layerState,
governorRequestRender,
redraw,
}) {
const instance = ++instances;
/** The lines (ring and fronts) and the band's sets, on the viewer they draw on. */
let sets = null;
function setsOn(viewer) {
if (sets?.viewer === viewer) return sets;
disposeSets();
const draw = drawOf(viewer);
sets = {
viewer,
lines: draw.lines({
id: `awareness:${instance}:rim`,
pickable: false,
}),
band: draw.shapes({
id: `awareness:${instance}:band`,
pickable: false,
}),
};
return sets;
}
function disposeSets() {
sets?.lines.dispose();
sets?.band.dispose();
sets = null;
}
/**
* Run the range pulses again for `activeMs`, after a camera move. Call it
* during a frame (lifecycle's preRender): that frame's postRender arms the
* next request, so waking asks for no extra frame of its own. Pulses at
* rest start in this frame; running ones keep their Cyber sonar interval,
* however many frames a drag draws.
*/
function wakePulses() {
const visual = layerState.visual;
if (!visual?.wake) return;
const nowMs = performance.now();
wakeAwarenessPulses(visual.wake, nowMs);
if (nowMs - visual.lastStepMs < CYBER_SONAR_RENDER_INTERVAL_MS) return;
visual.lastStepMs = nowMs;
visual.step(nowMs);
}
function clearVisual() {
const visual = layerState.visual;
if (!visual) return;
visual.stopPulses?.();
visual.removeMotionListener?.();
if (sets) {
sets.lines.clear();
sets.band.clear();
}
// Idle mode renders only on request; a removed ring must not linger.
governorRequestRender('awareness-visual');
clearAwarenessEchoField();
layerState.visual = null;
}
/** Let go of the sets too, as the layer goes. */
function disposeVisual() {
clearVisual();
disposeSets();
}
function renderVisual(subject) {
const viewer = layerState.viewer;
if (!viewer || !subject?.position) return;
const location = toLonLatH(subject.position);
if (!location) return;
const groundCenter = fromRadians(
(location.lon * Math.PI) / 180,
(location.lat * Math.PI) / 180,
0,
);
const key = `${subject.layerId}:${subject.id}`;
const reducedMotion = prefersReducedMotion();
const visual = layerState.visual;
// A reduced-motion change rebuilds the visual, with or without pulses;
// so does a ring drawn on another viewer (the layer re-initialized).
if (
visual?.key === key &&
visual.viewer === viewer &&
visual.reducedMotion === reducedMotion
) {
// Move the ring only after a meaningful displacement so live tracking
// does not redraw it for sub-pixel motion every 750 ms.
if (distance(visual.center, groundCenter) >= 250) {
// The echo field reads `visual.center` in place and follows on its
// own.
Object.assign(visual.center, groundCenter);
visual.ringPositions = awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
);
visual.lastStepMs = performance.now();
visual.step(visual.lastStepMs);
// Content actually changed — buy exactly one frame instead of holding.
governorRequestRender('awareness-visual');
}
return;
}
clearVisual();
const { lines, band } = setsOn(viewer);
const frame = findFrame(viewer);
// A renderer without frame hooks gets the static ring only, as the
// Cyber sonar scene does. So does a viewer who prefers reduced motion.
const animate = Boolean(!reducedMotion && frame?.on);
// Pulses run from now until `wake.untilMs`, then rest.
const wake = animate
? wakeAwarenessPulses(
{ startMs: -Infinity, untilMs: -Infinity },
performance.now(),
)
: null;
// From a camera below the rim height the band would sweep across the
// sky, so the pulses are hidden there and rest with it: no flash, no
// echoes, no frames.
const belowRim = () => cameraHeightM(viewer) < CONTEXT_RIM_HEIGHT_M;
// One step asks for the level at one time several times over; the
// camera's pose is read once for them.
let levelMemo = { nowMs: NaN, startMs: NaN, untilMs: NaN, level: 0 };
const levelAt = (nowMs) => {
if (!wake) return 0;
const memo = levelMemo;
if (
memo.nowMs === nowMs &&
memo.startMs === wake.startMs &&
memo.untilMs === wake.untilMs
)
return memo.level;
const level = belowRim() ? 0 : awarenessPulseLevel(nowMs, wake);
levelMemo = {
nowMs,
startMs: wake.startMs,
untilMs: wake.untilMs,
level,
};
return level;
};
const ring = AWARENESS_RANGE_RING_STYLE;
const pulse = AWARENESS_RANGE_PULSE;
const core = rgba(ring.color);
const halo = rgba(ring.outlineColor);
// While pulses run, the ring flashes as each one arrives and otherwise
// dims to `restOpacity`; as they settle it returns to full and stays.
const ringAlpha = (nowMs) => {
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
return 1 - levelAt(nowMs) * (1 - pulsed);
};
const center = { ...groundCenter };
const next = {
key,
viewer,
center,
ringPositions: awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
),
reducedMotion,
wake,
stopPulses: null,
removeMotionListener: null,
step: () => {},
/** When the pulses were last drawn as they were then. */
lastStepMs: Number.NEGATIVE_INFINITY,
};
/** The ring at `alpha` of its colours. */
const ringItems = (alpha) => [
haloedLine('ring', next.ringPositions, {
core: faded(core, alpha),
halo: faded(halo, alpha),
widthPx: ring.width,
haloPx: ring.outlineWidth,
show: true,
}),
];
if (!animate) {
lines.set(ringItems(1));
next.step = () => lines.upsert(ringItems(1));
} else {
const count = pulse.count;
// The band's ellipse is built around `bandCenter` and stands until
// the subject has moved `gradientRebuildM` from it; meanwhile the
// canvas draws the band about the subject, inside a margin as wide.
const spanM = AWARENESS_RADIUS_M + pulse.gradientRebuildM;
let bandCenter = null;
let bandShown = null;
// Two canvases in turn: a new key draws new content, and a renderer
// that holds a canvas until its next frame never sees it rewritten.
const doc = globalThis.document;
const canvases = [0, 1].map(() => {
const canvas = doc?.createElement?.('canvas');
if (!canvas?.getContext) return null;
canvas.width = canvas.height = AWARENESS_BAND_PIXELS;
const context = canvas.getContext('2d');
if (!context) return null;
return {
canvas,
context,
image: context.createImageData(
AWARENESS_BAND_PIXELS,
AWARENESS_BAND_PIXELS,
),
};
});
const paints = canvases.every(Boolean);
let painted = 0;
let paintedMs = Number.NEGATIVE_INFINITY;
// What each pixel reads, kept while the subject stays put.
const bandMemo = {};
// The image last drawn: a resting band keeps it, hidden, so showing
// it again changes it in place.
let image = null;
const bandItem = (show) => {
const { lon, lat } = toLonLatH(bandCenter);
return {
id: 'band',
geometry: {
kind: 'ellipse',
center: { lon, lat, height: CONTEXT_RIM_HEIGHT_M },
semiMajor: spanM,
semiMinor: spanM,
},
height: 'absolute',
fill: { image },
show,
};
};
/**
* Draw the pulses as they are at `nowMs`, and the ring where it now
* is: the fronts, the band and the ring's flash.
*/
next.step = (nowMs) => {
const level = levelAt(nowMs);
const items = ringItems(ringAlpha(nowMs));
const radii = [];
const alphas = [];
for (let index = 0; index < count; index++) {
const state = awarenessPulseState(nowMs, index);
radii.push(state.radiusM / AWARENESS_RADIUS_M);
alphas.push(state.alpha * level);
const front =
level > 0
? awarenessRangeRingPositions(
center,
state.radiusM,
CONTEXT_RIM_HEIGHT_M,
)
: next.ringPositions;
items.push(
haloedLine(`pulse:${index}`, front, {
core: faded(core, state.alpha * level),
halo: faded(halo, state.alpha * level),
widthPx: pulse.width,
haloPx: pulse.outlineWidth,
show: level > 0,
}),
);
}
lines.upsert(items);
if (!paints) return;
const show = level > 0;
// A resting band stays where it was built, and catches up on wake.
const rebuilt =
show &&
(!bandCenter ||
distance(bandCenter, center) >= pulse.gradientRebuildM);
if (rebuilt) bandCenter = { ...center };
if (!bandCenter) return;
if (!show) {
if (bandShown) band.upsert([bandItem(false)]);
bandShown = false;
return;
}
// The soft band is painted at most once a Cyber sonar interval;
// the fronts, crisp lines, move on every step.
if (
bandShown &&
!rebuilt &&
nowMs - paintedMs < CYBER_SONAR_RENDER_INTERVAL_MS
)
return;
paintedMs = nowMs;
const target = canvases[painted % 2];
paintAwarenessBand(
target.image,
{
radii,
alphas,
rgb: core,
spanM,
rangeM: AWARENESS_RADIUS_M,
offset: eastNorth(bandCenter, center),
},
bandMemo,
);
target.context.putImageData(target.image, 0, 0);
painted += 1;
image = {
canvas: target.canvas,
key: `awareness-band:${instance}:${painted}`,
};
band.upsert([bandItem(true)]);
bandShown = true;
};
lines.set(ringItems(1));
/** Draw the pulses at `nowMs` while they run or settle. */
const stepRunning = (nowMs) => {
if (levelAt(nowMs) > 0 || bandShown || ringAlpha(nowMs) < 1) {
next.lastStepMs = nowMs;
next.step(nowMs);
}
};
next.lastStepMs = performance.now();
next.step(next.lastStepMs);
// Whether the camera was below the rim at the last step.
let wasBelow = belowRim();
// The fronts and band are fixed in the world: a camera move needs
// nothing of them, so they step a Cyber sonar interval apart however
// many frames are drawn, and look the same parked or moving. Each
// frame checks only whether the camera crossed the rim height, which
// shows or hides them at once. A step asks for the frame that draws
// it, which is no reason to step again: a parked view draws one
// frame each interval, as the timer below asks.
const offPreRender = frame.on('preRender', () => {
const nowMs = performance.now();
const below = belowRim();
if (
below !== wasBelow ||
nowMs - next.lastStepMs >= CYBER_SONAR_RENDER_INTERVAL_MS
) {
// A crossing at the instant of the last step must not reuse
// that step's level.
if (below !== wasBelow) levelMemo.nowMs = Number.NaN;
wasBelow = below;
stepRunning(nowMs);
}
});
// Each drawn frame, whoever asked for it, arms one step a Cyber
// sonar interval later, as the Cyber sonar scene does, whose changes
// ask for the frame that draws them. Requests never land within
// 80 ms of a frame, so they cannot beat the detection lane's 80 ms
// gate, and they stop once the pulses rest.
let timer = null;
const offPostRender = frame.on('postRender', () => {
globalThis.clearTimeout(timer);
timer = null;
const nowMs = performance.now();
if ((nowMs < wake.untilMs || bandShown) && !belowRim())
timer = globalThis.setTimeout(() => {
timer = null;
stepRunning(performance.now());
governorRequestRender('awareness-pulse');
}, CYBER_SONAR_RENDER_INTERVAL_MS);
});
next.stopPulses = () => {
offPreRender();
offPostRender();
globalThis.clearTimeout(timer);
timer = null;
};
// The detection overlay pulses the brackets of flights and vessels a
// front crosses; it reads the centre in place, so it follows too.
setAwarenessEchoField({
center,
radiusM: AWARENESS_RADIUS_M,
pulse,
echo: AWARENESS_RANGE_ECHO,
level: levelAt,
});
}
// Turning reduced motion on or off mid-session rebuilds the visual.
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
const onMotionChange = () => {
if (layerState.subject) redraw(layerState.subject);
};
// Safari before 14 has only the older addListener / removeListener.
if (motionQuery?.addEventListener)
motionQuery.addEventListener('change', onMotionChange);
else motionQuery?.addListener?.(onMotionChange);
next.removeMotionListener = () => {
if (motionQuery?.removeEventListener)
motionQuery.removeEventListener('change', onMotionChange);
else motionQuery?.removeListener?.(onMotionChange);
};
layerState.visual = next;
governorRequestRender('awareness-visual');
}
return { renderVisual, clearVisual, disposeVisual, wakePulses };
}
File diff suppressed because it is too large. Load diff
+54 -650
View File
@@ -1,7 +1,5 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import {
CYBER_SONAR_RENDER_INTERVAL_MS,
createCyberSonarSampler,
isCyberContactSonarActive as isCyberSonarActive,
} from '../../cyberSonar.js';
@@ -11,339 +9,30 @@ import {
AWARENESS_RADIUS_M,
} from '../../data/militaryAwarenessEngine.js';
import { bearingBetweenCoordinates } from '../../cockpitMath.js';
import {
AWARENESS_PAGE_SIZE,
AWARENESS_RANGE_ECHO,
AWARENESS_RANGE_PULSE,
AWARENESS_RANGE_RING_STYLE,
CONTEXT_RIM_HEIGHT_M,
} from './policy.js';
import { AWARENESS_PAGE_SIZE } from './policy.js';
import { createRangeRing } from './rangeRing.js';
import { formatAwarenessDirection } from './presentation.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import {
awarenessEchoStrength,
clearAwarenessEchoField,
setAwarenessEchoField,
} from '../../awarenessEcho.js';
PI_OVER_TWO,
dot,
normalize,
sub,
toDegrees,
toLonLatH,
toRadians,
} from '../../geo/index.js';
/**
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
* raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's
* radius of curvature in that direction (Euler's formula), which keeps the
* ring within ~50 m of the true geodesic radius at 250 km.
* @param {Cesium.Cartesian3} groundCenter Ring centre on the ellipsoid.
* @param {number} radiusM Surface radius in metres.
* @param {number} heightM Height of the ring above the ellipsoid.
* @param {number} [segments] Chords around the ring.
* @returns {Cesium.Cartesian3[]} `segments + 1` positions; the last repeats the first.
*/
export function awarenessRangeRingPositions(
groundCenter,
radiusM,
heightM,
segments = AWARENESS_RANGE_RING_STYLE.segments,
) {
const { latitude, longitude } =
Cesium.Cartographic.fromCartesian(groundCenter);
const { x: a, z: b } = Cesium.Ellipsoid.WGS84.radii;
const e2 = 1 - (b * b) / (a * a);
const sinLat = Math.sin(latitude);
const cosLat = Math.cos(latitude);
const sinLon = Math.sin(longitude);
const cosLon = Math.cos(longitude);
const w = 1 - e2 * sinLat * sinLat;
const meridional = (a * (1 - e2)) / (w * Math.sqrt(w));
const primeVertical = a / Math.sqrt(w);
// Step along the great circle in 3D from the centre's up, north and east
// unit vectors. Unlike the latitude/longitude destination formula, this
// stays well conditioned at and next to the poles.
const up = [cosLat * cosLon, cosLat * sinLon, sinLat];
const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat];
const east = [-sinLon, cosLon, 0];
const positions = [];
for (let i = 0; i <= segments; i++) {
const bearing = ((i % segments) / segments) * Cesium.Math.TWO_PI;
const cosB = Math.cos(bearing);
const sinB = Math.sin(bearing);
const angular =
radiusM * ((cosB * cosB) / meridional + (sinB * sinB) / primeVertical);
const cosA = Math.cos(angular);
const sinA = Math.sin(angular);
const [x, y, z] = up.map(
(u, k) => u * cosA + (north[k] * cosB + east[k] * sinB) * sinA,
);
const lat = Math.atan2(z, Math.hypot(x, y));
const lon = Math.atan2(y, x);
positions.push(Cesium.Cartesian3.fromRadians(lon, lat, heightM));
}
return positions;
}
/**
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
* constant speed from `startFraction` of the range to the full range, fade in
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
* but still visible when it reaches the range ring. The opacity already
* includes `peakOpacity`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} index Pulse number, 0 to `count - 1`.
* @param {number} [radiusM] Range the pulses grow to.
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
* @returns {{radiusM: number, alpha: number}}
*/
export function awarenessPulseState(
nowMs,
index,
radiusM = AWARENESS_RADIUS_M,
pulse = AWARENESS_RANGE_PULSE,
) {
const cycle = nowMs / pulse.periodMs + index / pulse.count;
const phase = cycle - Math.floor(cycle);
return {
radiusM:
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
alpha:
pulse.peakOpacity *
Math.min(1, phase / pulse.fadeInFraction) *
(pulse.endOpacityFraction +
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
};
}
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
/** Whether the viewer asked the system for less motion. */
function prefersReducedMotion() {
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
}
/**
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
* `wake.untilMs`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {number} 0 to 1.
*/
export function awarenessPulseLevel(
nowMs,
wake,
pulse = AWARENESS_RANGE_PULSE,
) {
const level = Math.min(
(nowMs - wake.startMs) / pulse.settleMs,
(wake.untilMs - nowMs) / pulse.settleMs,
);
return Math.max(0, Math.min(1, level));
}
/**
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
* keeps their current level, so they never jump back to full mid-fade.
* @param {{startMs: number, untilMs: number}} wake Updated in place.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {{startMs: number, untilMs: number}} `wake`.
*/
export function wakeAwarenessPulses(
wake,
nowMs,
pulse = AWARENESS_RANGE_PULSE,
) {
wake.startMs =
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
wake.untilMs = nowMs + pulse.activeMs;
return wake;
}
/**
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
* pulse front reaches it, fading over `flashMs`, so the ring appears once
* per arriving pulse instead of standing on screen.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
export function awarenessRingFlash(nowMs) {
return awarenessEchoStrength(
nowMs,
AWARENESS_RADIUS_M,
AWARENESS_RADIUS_M,
AWARENESS_RANGE_PULSE,
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
);
}
/** Most pulses the pulse shader draws; its uniforms are vec4s. */
export const AWARENESS_PULSE_GRADIENT_MAX = 4;
/** The pulse disc's Cesium material type, one cached template per page. */
const AWARENESS_PULSE_MATERIAL_TYPE = 'GevAwarenessPulseGradient';
// Ellipse texture coordinates put the centre at (0.5, 0.5) and the rim at
// distance 0.5, so `r` is the fraction of the range. Each pulse is a line
// `lineWidth` CSS pixels wide whose outer `haloWidth` is a dark halo, half
// on each side, as Cesium's polyline outline material draws it, with a band
// behind it that is strongest at the line and fades to nothing `depth`
// inward. Widths come from the screen-space gradient of `r`, as Cesium's
// contour material measures its lines; without derivatives the lines are
// left out and only the band shows.
const PULSE_GRADIENT_SOURCE = `
uniform vec4 color;
uniform vec4 lineColor;
uniform vec4 haloColor;
uniform vec4 radii;
uniform vec4 alphas;
uniform float depth;
uniform float lineWidth;
uniform float haloWidth;
vec4 over(vec4 top, vec4 under) {
float a = top.a + under.a * (1.0 - top.a);
if (a <= 0.0) return vec4(0.0);
return vec4((top.rgb * top.a + under.rgb * under.a * (1.0 - top.a)) / a, a);
}
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
float r = length(materialInput.st - vec2(0.5)) * 2.0;
float band = 0.0;
for (int i = 0; i < 4; i++) {
float inside = radii[i] - r;
if (inside >= 0.0 && inside <= depth) {
float t = 1.0 - inside / depth;
band += alphas[i] * t * t;
}
}
vec4 result = vec4(color.rgb, clamp(band * color.a, 0.0, 1.0));
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
// Change in r per CSS pixel: the gradient's length per device pixel,
// times the device pixels in one CSS pixel.
float cssPx = max(length(vec2(dFdx(r), dFdy(r))), 1e-7) * czm_pixelRatio;
float outerHalf = lineWidth * 0.5;
float coreHalf = max(lineWidth - haloWidth, 0.0) * 0.5;
for (int i = 0; i < 4; i++) {
float d = abs(radii[i] - r) / cssPx;
float cover = clamp(outerHalf + 0.5 - d, 0.0, 1.0);
if (cover <= 0.0) continue;
float core = clamp(coreHalf + 0.5 - d, 0.0, 1.0);
vec4 pulse = mix(haloColor, lineColor, core);
result = over(vec4(pulse.rgb, pulse.a * cover * alphas[i]), result);
}
#endif
material.diffuse = result.rgb;
material.alpha = result.a;
return material;
}
`;
/**
* The pulses: one flat, translucent, unpickable disc the size of the range
* ring whose shader draws each pulse line and the band behind it. Drawing
* them here rather than as entities keeps them out of picking, so clicks and
* taps near a pulse still reach the contact underneath. Moving pulses only
* change its uniforms; the disc is rebuilt only when the subject moves.
* @param {Cesium.Cartesian3} groundCenter Disc centre on the ellipsoid.
* @param {Cesium.Material} material Shared pulse-gradient material.
* @returns {Cesium.Primitive}
*/
function createPulseGradient(groundCenter, material) {
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.EllipseGeometry({
center: groundCenter,
semiMajorAxis: AWARENESS_RADIUS_M,
semiMinorAxis: AWARENESS_RADIUS_M,
height: CONTEXT_RIM_HEIGHT_M,
granularity: Cesium.Math.toRadians(
AWARENESS_RANGE_PULSE.gradientGranularityDeg,
),
vertexFormat:
Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat,
}),
}),
appearance: new Cesium.MaterialAppearance({
material,
flat: true,
translucent: true,
faceForward: true,
}),
asynchronous: false,
allowPicking: false,
});
}
/**
* The ring's polyline geometry: `AWARENESS_RANGE_RING_STYLE.width` screen
* pixels, straight chords between the given positions (they already follow
* the surface), in the material appearance's vertex format.
* @param {Cesium.Cartesian3[]} positions Ring positions.
* @returns {object} PolylineGeometry options.
*/
export function awarenessRingGeometryOptions(positions) {
return {
positions,
width: AWARENESS_RANGE_RING_STYLE.width,
arcType: Cesium.ArcType.NONE,
vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
};
}
/**
* The 250 km ring as an unpickable polyline primitive in the ring's outline
* material, so a click or tap on its edge reaches the contact underneath.
* Its positions are geometry, so a moved subject rebuilds it; the material
* is shared between builds so a flash keeps going.
* @param {Cesium.Cartesian3[]} positions Ring positions.
* @param {Cesium.Material} material Shared PolylineOutline material.
* @returns {Cesium.Primitive}
*/
function createRingPrimitive(positions, material) {
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolylineGeometry(
awarenessRingGeometryOptions(positions),
),
}),
appearance: new Cesium.PolylineMaterialAppearance({
material,
translucent: true,
}),
asynchronous: false,
allowPicking: false,
});
}
/**
* The rotation about the Earth's centre that carries `from` onto `to`, as a
* model matrix, so a disc built around `from` sits around `to`.
* @param {Cesium.Cartesian3} from Where the disc was built.
* @param {Cesium.Cartesian3} to Where it should be.
* @param {Cesium.Matrix4} [result]
* @returns {Cesium.Matrix4}
*/
export function discFollowMatrix(from, to, result = new Cesium.Matrix4()) {
const a = Cesium.Cartesian3.normalize(from, new Cesium.Cartesian3());
const b = Cesium.Cartesian3.normalize(to, new Cesium.Cartesian3());
const axis = Cesium.Cartesian3.cross(a, b, new Cesium.Cartesian3());
const sin = Cesium.Cartesian3.magnitude(axis);
if (sin < 1e-12) return Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, result);
const angle = Math.atan2(sin, Cesium.Cartesian3.dot(a, b));
const rotation = Cesium.Matrix3.fromQuaternion(
Cesium.Quaternion.fromAxisAngle(
Cesium.Cartesian3.divideByScalar(axis, sin, axis),
angle,
),
);
return Cesium.Matrix4.fromRotationTranslation(
rotation,
Cesium.Cartesian3.ZERO,
result,
);
}
/** Camera height above the ellipsoid, or NaN when the scene cannot say. */
function cameraHeightM(scene) {
return scene.camera?.positionCartographic?.height ?? Number.NaN;
}
// The ring's and the pulses' own arithmetic, for their tests.
export {
AWARENESS_BAND_PIXELS,
awarenessPulseLevel,
awarenessPulseState,
awarenessRangeRingPositions,
awarenessRingFlash,
paintAwarenessBand,
wakeAwarenessPulses,
} from './rangeRing.js';
export function createRendering({
state: layerState,
@@ -353,6 +42,12 @@ export function createRendering({
}) {
const { getKeyholeGeometry, celestialScreenAngle } = services.geometry;
const { governorRequestRender } = services.render;
/** The range ring with its pulses (`rangeRing.js`). */
const rangeRing = createRangeRing({
state: layerState,
governorRequestRender,
redraw: (subject) => renderVisual(subject),
});
const CARDINALS = [
['N', 0],
@@ -460,7 +155,7 @@ export function createRendering({
return;
}
const canvas = layerState.viewer.scene.canvas;
const canvas = canvasOf(layerState.viewer);
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
const sonar = isCyberSonarActive()
@@ -478,9 +173,9 @@ export function createRendering({
120,
Math.min(geometry.radius - 48, geometry.radius * 0.66),
);
const cameraHeading = layerState.viewer.camera.heading || 0;
const headingDeg =
(Math.round(Cesium.Math.toDegrees(cameraHeading)) + 360) % 360;
const pose = findCamera(layerState.viewer)?.pose();
const cameraHeading = pose?.heading || 0;
const headingDeg = (Math.round(toDegrees(cameraHeading)) + 360) % 360;
const ring = {
left: `${geometry.centerX - compassRadius}px`,
top: `${geometry.centerY - compassRadius}px`,
@@ -496,8 +191,8 @@ export function createRendering({
top: `${geometry.centerY - compassRadius + 39}px`,
};
const labels = root.labels.map((label) => {
const bearing = Cesium.Math.toRadians(label.bearing);
const angle = bearing - cameraHeading - Cesium.Math.PI_OVER_TWO;
const bearing = toRadians(label.bearing);
const angle = bearing - cameraHeading - PI_OVER_TWO;
const labelRadius = compassRadius - 17;
return {
...label,
@@ -525,19 +220,15 @@ export function createRendering({
marker.hidden = true;
continue;
}
const direction = Cesium.Cartesian3.subtract(
item.position,
layerState.subject.position,
layerState.DIRECTION_SCRATCH[index],
);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 1) {
const offset = sub(item.position, layerState.subject.position);
if (dot(offset, offset) < 1 || !pose) {
marker.hidden = true;
continue;
}
Cesium.Cartesian3.normalize(direction, direction);
const direction = normalize(offset);
const projection = celestialScreenAngle(
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.rightWC),
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.upWC),
dot(direction, pose.right),
dot(direction, pose.up),
layerState.directionAngles[index],
);
if (projection.stable)
@@ -565,23 +256,15 @@ export function createRendering({
transform: `translate(-50%, -50%) translate(${-Math.cos(projection.angle) * 56}px, ${-Math.sin(projection.angle) * 56}px)`,
};
const label = formatAwarenessLabel(item);
const subjectCartographic = Cesium.Cartographic.fromCartesian(
layerState.subject.position,
undefined,
layerState.SUBJECT_CARTOGRAPHIC_SCRATCH,
);
const targetCartographic = Cesium.Cartographic.fromCartesian(
item.position,
undefined,
layerState.TARGET_CARTOGRAPHIC_SCRATCH[index],
);
const subjectLocation = toLonLatH(layerState.subject.position);
const targetLocation = toLonLatH(item.position);
const bearing =
subjectCartographic && targetCartographic
subjectLocation && targetLocation
? bearingBetweenCoordinates(
Cesium.Math.toDegrees(subjectCartographic.latitude),
Cesium.Math.toDegrees(subjectCartographic.longitude),
Cesium.Math.toDegrees(targetCartographic.latitude),
Cesium.Math.toDegrees(targetCartographic.longitude),
subjectLocation.lat,
subjectLocation.lon,
targetLocation.lat,
targetLocation.lon,
)
: null;
const bearingText = Number.isFinite(bearing)
@@ -609,300 +292,20 @@ export function createRendering({
* next request, so waking asks for no extra frame of its own.
*/
function wakePulses() {
const wake = layerState.visual?.wake;
if (!wake) return;
wakeAwarenessPulses(wake, performance.now());
followPulseDisc();
}
/**
* Keep the pulse disc centred on the subject. Within `gradientRebuildM` of
* where it was built, the disc is rotated about the Earth's centre onto
* the subject by its model matrix, which keeps it concentric with the ring
* at no build cost; the ellipsoid curves a little differently from that
* sphere, a few tens of metres in height at 20 km. Further away it is
* rebuilt, which costs a few milliseconds.
*/
function followPulseDisc() {
const { gradient, gradientCenter, center } = layerState.visual;
if (!gradient) return;
if (
Cesium.Cartesian3.distance(gradientCenter, center) <
AWARENESS_RANGE_PULSE.gradientRebuildM
) {
gradient.modelMatrix = discFollowMatrix(
gradientCenter,
center,
gradient.modelMatrix,
);
return;
}
const primitives = layerState.viewer.scene.primitives;
layerState.visual.gradient = primitives.add(
createPulseGradient(center, gradient.appearance.material),
);
// Primitive.destroy leaves the material alone, so the new disc keeps
// sharing it.
primitives.remove(gradient);
Cesium.Cartesian3.clone(center, gradientCenter);
rangeRing.wakePulses();
}
function clearVisual() {
layerState.visual?.stopPulses?.();
layerState.visual?.removeMotionListener?.();
if (layerState.visual?.gradient && layerState.viewer)
layerState.viewer.scene.primitives.remove(layerState.visual.gradient);
if (layerState.visual?.ringPrimitive && layerState.viewer) {
layerState.viewer.scene.primitives.remove?.(
layerState.visual.ringPrimitive,
);
governorRequestRender('awareness-visual');
}
clearAwarenessEchoField();
if (layerState.visual?.entities && layerState.viewer) {
for (const entity of layerState.visual.entities)
layerState.viewer.entities.remove(entity);
// Idle mode renders only on request; a removed ring must not linger.
governorRequestRender('awareness-visual');
}
layerState.visual = null;
rangeRing.clearVisual();
}
/** Let the ring's draw sets go, as the layer is destroyed. */
function disposeVisual() {
rangeRing.disposeVisual();
}
function renderVisual(subject) {
if (!layerState.viewer || !subject?.position) return;
const cartographic = Cesium.Cartographic.fromCartesian(subject.position);
if (!cartographic) return;
const groundCenter = Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
0,
);
const key = `${subject.layerId}:${subject.id}`;
const reducedMotion = prefersReducedMotion();
// A reduced-motion change rebuilds the visual, with or without pulses.
if (
layerState.visual?.key === key &&
layerState.visual.reducedMotion === reducedMotion
) {
// Move the ring only after a meaningful displacement so live tracking
// does not rebuild its geometry for sub-pixel motion every 750 ms.
if (
Cesium.Cartesian3.distance(layerState.visual.center, groundCenter) >=
250
) {
const positions = awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
);
// The echo field reads `visual.center` in place and follows on its
// own. The pulse disc follows by its model matrix and is rebuilt only
// every `gradientRebuildM`: a build costs a few milliseconds.
layerState.visual.ringPositions = positions;
const { ringPrimitive } = layerState.visual;
if (ringPrimitive) {
const primitives = layerState.viewer.scene.primitives;
layerState.visual.ringPrimitive = primitives.add(
createRingPrimitive(positions, ringPrimitive.appearance.material),
);
primitives.remove(ringPrimitive);
} else layerState.visual.ring.polyline.positions.setValue(positions);
Cesium.Cartesian3.clone(groundCenter, layerState.visual.center);
// A resting disc is hidden, so it catches up when the pulses wake.
if (performance.now() < layerState.visual.wake?.untilMs)
followPulseDisc();
// Content actually changed — buy exactly one frame instead of holding.
governorRequestRender('awareness-visual');
}
return;
}
clearVisual();
const entities = [];
const scene = layerState.viewer.scene;
// A viewer without a primitive collection or a preRender hook (headless
// tools, partial stubs) gets the static ring only, as the Cyber sonar
// scene does. So does a viewer who prefers reduced motion.
const animate = Boolean(
!reducedMotion &&
scene?.primitives?.add &&
scene?.preRender?.addEventListener &&
scene?.postRender?.addEventListener,
);
// Pulses run from now until `wake.untilMs`, then rest.
const wake = animate
? wakeAwarenessPulses(
{ startMs: -Infinity, untilMs: -Infinity },
performance.now(),
)
: null;
// From a camera below the rim height the disc would sweep across the sky,
// so it is hidden there, and the pulses rest with it: no flash, no
// echoes, no frames.
const belowRim = () => cameraHeightM(scene) < CONTEXT_RIM_HEIGHT_M;
const levelAt = (nowMs) =>
wake && !belowRim() ? awarenessPulseLevel(nowMs, wake) : 0;
// A polyline, not an ellipse outline: WebGL draws ellipse outlines at
// 1 px whatever `outlineWidth` says, and the ring needs a halo.
const ring = AWARENESS_RANGE_RING_STYLE;
const core = Cesium.Color.fromCssColorString(ring.color);
const halo = Cesium.Color.fromCssColorString(ring.outlineColor);
const ringPositions = awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
);
// While pulses run, the ring flashes as each one arrives and otherwise
// dims to `restOpacity`; as they settle it returns to full and stays.
const ringAlpha = (nowMs) => {
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
return 1 - levelAt(nowMs) * (1 - pulsed);
};
let ringEntity = null;
let ringMaterial = null;
let ringPrimitive = null;
if (scene?.primitives?.add) {
ringMaterial = Cesium.Material.fromType('PolylineOutline', {
color: core.clone(),
outlineColor: halo.clone(),
outlineWidth: ring.outlineWidth,
});
ringPrimitive =
scene.primitives.add(
createRingPrimitive(ringPositions, ringMaterial),
) ?? null;
}
if (!ringPrimitive) {
// Headless tools and partial stubs have no primitive collection; they
// get the static ring as an entity.
ringEntity = layerState.viewer.entities.add({
polyline: {
positions: new Cesium.ConstantProperty(ringPositions),
width: ring.width,
arcType: Cesium.ArcType.NONE,
material: new Cesium.PolylineOutlineMaterialProperty({
color: core,
outlineColor: halo,
outlineWidth: ring.outlineWidth,
}),
},
});
entities.push(ringEntity);
}
const center = Cesium.Cartesian3.clone(groundCenter);
let gradient = null;
let stopPulses = null;
if (animate) {
const pulse = AWARENESS_RANGE_PULSE;
const count = Math.min(pulse.count, AWARENESS_PULSE_GRADIENT_MAX);
const uniforms = {
color: core.clone(),
lineColor: core.clone(),
haloColor: halo.clone(),
radii: new Cesium.Cartesian4(),
alphas: new Cesium.Cartesian4(),
depth: pulse.gradientDepthFraction,
lineWidth: pulse.width,
haloWidth: pulse.outlineWidth,
};
uniforms.color.alpha = pulse.gradientOpacity;
// A named type: Cesium caches every material type for the page's
// lifetime, so an unnamed fabric (a fresh GUID each time) would leave
// one entry per new visual. Built from the cached template, the
// uniforms come back as plain copies; restore this visual's own.
const material = new Cesium.Material({
fabric: {
type: AWARENESS_PULSE_MATERIAL_TYPE,
uniforms,
source: PULSE_GRADIENT_SOURCE,
},
translucent: true,
});
Object.assign(material.uniforms, uniforms);
gradient = scene.primitives.add(
createPulseGradient(groundCenter, material),
);
const radii = [0, 0, 0, 0];
const alphas = [0, 0, 0, 0];
const removePreRender = scene.preRender.addEventListener(() => {
const nowMs = performance.now();
const level = levelAt(nowMs);
const alpha = ringAlpha(nowMs);
ringMaterial.uniforms.color.alpha = core.alpha * alpha;
ringMaterial.uniforms.outlineColor.alpha = halo.alpha * alpha;
// The disc is looked up each frame: a subject move swaps it.
const disc = layerState.visual?.gradient;
if (disc) disc.show = level > 0;
for (let index = 0; index < count; index++) {
const state = awarenessPulseState(nowMs, index);
radii[index] = state.radiusM / AWARENESS_RADIUS_M;
alphas[index] = state.alpha * level;
}
Cesium.Cartesian4.fromArray(radii, 0, material.uniforms.radii);
Cesium.Cartesian4.fromArray(alphas, 0, material.uniforms.alphas);
});
// Each drawn frame, whoever asked for it, arms one request a Cyber
// sonar interval later, as the Cyber sonar scene does. Requests never
// land within 80 ms of a frame, so they cannot beat the detection
// lane's 80 ms gate, and they stop once the pulses rest.
let timer = null;
const removePostRender = scene.postRender.addEventListener(() => {
globalThis.clearTimeout(timer);
timer = null;
if (performance.now() < wake.untilMs && !belowRim())
timer = globalThis.setTimeout(() => {
timer = null;
governorRequestRender('awareness-pulse');
}, CYBER_SONAR_RENDER_INTERVAL_MS);
});
stopPulses = () => {
removePreRender();
removePostRender();
globalThis.clearTimeout(timer);
timer = null;
};
// The detection overlay pulses the brackets of flights and vessels a
// front crosses; it reads the centre in place, so it follows too.
setAwarenessEchoField({
center,
radiusM: AWARENESS_RADIUS_M,
pulse,
echo: AWARENESS_RANGE_ECHO,
level: levelAt,
});
}
// Turning reduced motion on or off mid-session rebuilds the visual.
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
const onMotionChange = () => {
if (layerState.subject) renderVisual(layerState.subject);
};
// Safari before 14 has only the older addListener / removeListener.
if (motionQuery?.addEventListener)
motionQuery.addEventListener('change', onMotionChange);
else motionQuery?.addListener?.(onMotionChange);
layerState.visual = {
key,
entities,
ring: ringEntity,
ringPrimitive,
ringPositions,
center,
gradient,
gradientCenter: Cesium.Cartesian3.clone(groundCenter),
reducedMotion,
wake,
stopPulses,
removeMotionListener: () => {
if (motionQuery?.removeEventListener)
motionQuery.removeEventListener('change', onMotionChange);
else motionQuery?.removeListener?.(onMotionChange);
},
};
governorRequestRender('awareness-visual');
rangeRing.renderVisual(subject);
}
return {
ensureDirectionOverlay,
@@ -913,6 +316,7 @@ export function createRendering({
cancelDirectionOverlayUpdate,
updateDirectionOverlay,
clearVisual,
disposeVisual,
renderVisual,
wakePulses,
};
@@ -0,0 +1,108 @@
// src/layers/awareness/selectedVessel.test.mjs — Contacts turned on while an
// AIS vessel is selected takes that vessel as its subject.
import test from 'node:test';
import assert from 'node:assert/strict';
import { summarizeAwarenessCohort } from '../../data/militaryAwarenessEngine.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
import { createSubject } from './subject.js';
import { createHistory } from './history.js';
import { createDependencies } from './dependencies.js';
const VESSEL_ID = '367000001';
/** Contacts parts over fake sources; focus records each nearest-flight pick. */
function contacts(selection) {
globalThis.document ??= { body: null };
const noAircraft = {
getAllPositions: () => [],
getNearby: () => [],
getTrackedSubject: () => null,
};
const services = {
flights: noAircraft,
military: noAircraft,
vessels: {
getNearby: () => [],
getAllPositions: () => [],
getSelectedInfo: () => selection.vessel,
},
installations: {
getNearby: () => [],
getStats: () => ({}),
setContextAnchor() {},
},
};
const state = createState({ services });
state.enabled = true;
state.passive = false;
state.dataManager = {
isEnabled: () => true,
isEffectivelyEnabled: () => true,
setEnabled: async () => true,
getLayerLifecycleState: () => ({
enabled: true,
lifecycleState: 'enabled',
}),
layers: new Map(),
};
const focused = [];
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {}, startAwarenessPageRotation() {} },
focus: {
focusAttentionTarget() {
focused.push('nearest');
return true;
},
},
};
const context = { state, services, parts };
parts.model = createModel(context);
parts.queries = createQueries(context);
parts.subject = createSubject(context);
parts.history = createHistory(context);
parts.dependencies = createDependencies(context);
return { state, parts, focused };
}
/** The vessel layer's answer for a selected Royal Prince. */
const ROYAL_PRINCE = Object.freeze({
id: VESSEL_ID,
mmsi: VESSEL_ID,
name: 'ROYAL PRINCE',
latitude: 37.8,
longitude: -122.4,
});
test('Contacts turned on with a vessel selected takes it as the subject', async () => {
const { state, parts, focused } = contacts({ vessel: ROYAL_PRINCE });
await parts.dependencies.activateOperationalContext();
assert.deepEqual(focused, [], 'no nearest flight is picked or followed');
assert.equal(state.subject?.layerId, 'ais-live-vessels');
assert.equal(state.subject?.id, VESSEL_ID);
assert.match(state.subject.label, /ROYAL PRINCE/);
});
test('a late source settling keeps the selected vessel, not a nearest flight', () => {
const selection = { vessel: null };
const { state, parts, focused } = contacts(selection);
state.autoFocusRetryPending = true;
selection.vessel = ROYAL_PRINCE;
parts.dependencies.refreshAfterDeferredDependency(state.activationId);
assert.deepEqual(focused, []);
assert.equal(state.subject?.id, VESSEL_ID);
});
test('with no vessel selected, Contacts still picks the nearest flight', async () => {
const { state, parts, focused } = contacts({ vessel: null });
await parts.dependencies.activateOperationalContext();
assert.deepEqual(focused, ['nearest']);
assert.equal(state.subject, null);
});
-14
View File
@@ -1,20 +1,6 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const state = {};
state.DIRECTION_SCRATCH = Array.from(
{ length: 3 },
() => new Cesium.Cartesian3(),
);
state.SUBJECT_CARTOGRAPHIC_SCRATCH = new Cesium.Cartographic();
state.TARGET_CARTOGRAPHIC_SCRATCH = Array.from(
{ length: 3 },
() => new Cesium.Cartographic(),
);
Object.assign(state, {
viewer: null,
dataManager: null,
+62 -36
View File
@@ -1,10 +1,11 @@
import { followedOf } from '../../data/followed.js';
import {
AWARENESS_RADIUS_M,
AWARENESS_RELATIONSHIP,
} from '../../data/militaryAwarenessEngine.js';
import * as Cesium from 'cesium';
import { layerFeedState } from '../../data/feedState.js';
import { t } from '../../i18n/index.js';
import { clone, distance, fromDegrees } from '../../geo/index.js';
import {
AWARENESS_QUERY_LIMIT,
SOURCE_LABEL,
@@ -25,6 +26,8 @@ function localizeCoverageLabel(label) {
return label;
}
/** @typedef {import('../../render/contract/common').Ecef} Ecef */
export function createSubject({ state: layerState, services, parts, source }) {
const aisLiveVesselsLayer = services.vessels;
const militaryInstallationsLayer = services.installations;
@@ -85,7 +88,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
.filter(
(item) =>
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
);
const coverage = installationsState.stats?.coverage;
const installationRadius =
@@ -200,17 +203,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
}
/**
* Resolve the source-owned aircraft that currently owns Cesium tracking.
* Resolve the source-owned aircraft that currently owns the follow camera.
* Both flight layers may briefly retain local state during a cross-layer
* handoff, so the viewer's normalized tracked identity is the tie-breaker.
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
* @returns {{layerId: string, id: string, label: string, position: Ecef}|null}
* Detached awareness subject, or null when no flight owns the follow camera.
*/
function currentTrackedFlightSubject() {
const trackedKey = normalizeContextId(
layerState.viewer?.trackedEntity?.gevTrackedId,
);
const trackedKey = normalizeContextId(followedOf(layerState.viewer)?.key);
if (!trackedKey) return null;
const subjects = [
flightsLayer.getTrackedSubject?.(),
@@ -250,7 +251,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
subject,
parts.history.historySourceItem(subject),
),
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
});
layerState.navigationIndex = layerState.navigationHistory.length - 1;
}
@@ -265,10 +266,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
* Resolve the currently displayed position for a selected live subject. Flight
* tracking owns the motion callback, so awareness consumes its cached display
* position instead of creating a second tracker or extrapolation path.
* @param {{layerId: string, id: string, position: Cesium.Cartesian3}} subject Current subject.
* @param {{layerId: string, id: string, position: Ecef}} subject Current subject.
* @param {object} [options] Position materialization controls.
* @param {boolean} [options.allowCollectionMaterialization=true] Whether a layer-wide fallback may run.
* @returns {Cesium.Cartesian3|null} A cloned live position when one is available.
* @returns {Ecef|null} A cloned live position when one is available.
*/
function resolveSubjectPosition(
@@ -277,16 +278,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
) {
if (!subject?.position) return null;
if (subject.layerId === 'flights' || subject.layerId === 'military') {
const trackedPosition =
layerState.viewer?.trackedEntity?.gevDisplayPosition?.();
const followed = followedOf(layerState.viewer);
const trackedPosition = followed?.displayPosition?.();
if (trackedPosition) {
return {
position: Cesium.Cartesian3.clone(trackedPosition),
position: clone(trackedPosition),
// Only the follow camera's own contact proves presence this way; a
// different tracked entity says nothing about this subject.
presence:
String(layerState.viewer?.trackedEntity?.gevTrackedId || '') ===
subjectKey(subject)
String(followed?.key || '') === subjectKey(subject)
? SUBJECT_PRESENCE.LIVE
: SUBJECT_PRESENCE.UNCHECKED,
};
@@ -296,7 +296,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// awareness position instead of allocating/scanning up to 1,000 contacts.
if (!allowCollectionMaterialization) {
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.UNCHECKED,
};
}
@@ -311,7 +311,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (subject.layerId === 'ais-live-vessels') {
if (!allowCollectionMaterialization) {
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.UNCHECKED,
};
}
@@ -324,7 +324,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// Mapped installations come from static geometry, not a live feed: there is
// nothing to be culled from.
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.LIVE,
};
}
@@ -338,10 +338,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
* ~11k contacts against a 1,000-row cap, so "not in the rows" is not "gone".
* The rows are only consulted for a fresher position — a contact past the cap
* keeps its last known position while still reading as present.
* @param {{id: string, position: Cesium.Cartesian3}} subject Current subject.
* @param {Array<{id: string, position: Cesium.Cartesian3}>} rows Live collection rows.
* @param {{id: string, position: Ecef}} subject Current subject.
* @param {Array<{id: string, position: Ecef}>} rows Live collection rows.
* @param {{hasContact?: function}} layer The owning source layer.
* @returns {{position: Cesium.Cartesian3, presence: string}} Position plus presence verdict.
* @returns {{position: Ecef, presence: string}} Position plus presence verdict.
*/
function collectionSubjectPosition(subject, rows, layer) {
@@ -359,8 +359,8 @@ export function createSubject({ state: layerState, services, parts, source }) {
: SUBJECT_PRESENCE.UNCHECKED;
return {
position: current?.position
? Cesium.Cartesian3.clone(current.position)
: Cesium.Cartesian3.clone(subject.position),
? clone(current.position)
: clone(subject.position),
presence,
};
}
@@ -406,17 +406,20 @@ export function createSubject({ state: layerState, services, parts, source }) {
}
/**
* The tracked airliner's Planespotters photo, for the Contacts panel.
* The subject's photo, for the Contacts panel: the tracked airliner's
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
*
* Only the flights layer looks photos up, and only for the plane it tracks;
* a vessel, an installation, a military aircraft or an untracked flight has
* none.
* The flights layer looks photos up only for the plane it tracks, the
* vessel layer only for the vessel selected; an installation, a military
* aircraft or an untracked flight has none.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it.
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string, licence?: string}}
*/
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
if (subject?.layerId === 'ais-live-vessels')
return aisLiveVesselsLayer.getVesselPhoto?.(subject.id) ?? null;
return subject?.layerId === 'flights' && tracked?.photo
? tracked.photo
: null;
@@ -463,7 +466,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
layerState.subject = { ...layerState.subject, position, label: nextLabel };
const movementM = layerState.lastEvaluatedPosition
? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position)
? distance(layerState.lastEvaluatedPosition, position)
: Infinity;
if (
!parts.model.awarenessRefreshRequired({
@@ -487,10 +490,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
}
layerState.results = evaluateSubject(layerState.subject, sources);
layerState.sourceRevision = nextSourceRevision;
layerState.lastEvaluatedPosition = Cesium.Cartesian3.clone(
position,
layerState.lastEvaluatedPosition,
);
layerState.lastEvaluatedPosition = clone(position);
for (const cohort of layerState.results.cohorts) {
const maxPage = Math.max(
0,
@@ -517,15 +517,40 @@ export function createSubject({ state: layerState, services, parts, source }) {
const latitude = Number(record.latitude);
const longitude = Number(record.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
// A vessel reads as its name and MMSI; a vessel named by its MMSI alone
// already carries it.
const label = String(record.label || record.id);
const mmsi = String(record.properties?.mmsi || '');
return {
layerId: record.layerId,
id: record.properties?.mmsi || record.id,
label: record.label || record.id,
id: record.properties?.vesselId || record.id,
// i18n-ignore: MMSI is a radio identity code, as on the vessel card
label: mmsi && !label.includes(mmsi) ? `${label} · MMSI ${mmsi}` : label,
memberNames: record.properties?.memberNames || [],
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
position: fromDegrees(longitude, latitude, 0),
};
}
/**
* The AIS vessel the user has selected, as a subject. Contacts turned on
* after the selection never heard its `gev:entity-selected`, so activation
* asks the vessel layer and shapes its answer as that event's record.
* @returns {object|null} Detached subject, or null when no vessel is selected.
*/
function currentSelectedVesselSubject() {
const info = aisLiveVesselsLayer.getSelectedInfo?.();
if (!info?.id) return null;
return subjectFromContext({
layerId: 'ais-live-vessels',
id: info.id,
label: info.name || info.mmsi || info.id,
latitude: info.latitude,
longitude: info.longitude,
properties: { vesselId: info.id, mmsi: info.mmsi },
});
}
/**
* Record that the current subject left its feed on its own.
*
@@ -574,6 +599,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
resolveSubjectPhoto,
refreshSelectedSubject,
subjectFromContext,
currentSelectedVesselSubject,
markSubjectEvicted,
clearAwarenessSubject,
};
+1 -1
View File
@@ -25,7 +25,7 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Return a sampled array of detectable station objects for HUD overlay rendering.
* @param {Object} [options] - Sampling options (maxCount, seed).
* @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>}
* @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>}
*/
getDetectableObjects(options = {}) {
return parts.queries.collectDetectableStations(options);
+139
View File
@@ -0,0 +1,139 @@
// Bike Share's covered cities on the globe (HAL-921): above the height
// stations draw at, every system in the registry has a marker, so the globe
// says where bike share is, and a click on one flies down into its city.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createSelection } from './selection.js';
import { createLifecycle } from './lifecycle.js';
import { COVERAGE_FLY_HEIGHT_M } from './policy.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
globalThis.document ??= {
addEventListener() {},
removeEventListener() {},
};
function makeLayer() {
const owners = new Map();
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
picking: {
registerPickOwner: (id, owns) => owners.set(id, owns),
unregisterPickOwner: (id) => owners.delete(id),
},
};
const source = { getStations: async () => ({ data: { stations: [] } }) };
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.ingestion = createIngestion(context);
parts.model = createModel(context);
parts.viewport = createViewport(context);
parts.rendering = createRendering(context);
parts.selection = createSelection(context);
parts.queries = { collectDetectableStations: () => [] };
parts.lifecycle = createLifecycle(context);
const camera = { lat: 20, lon: 0, height: 18_000_000 };
const flights = [];
const viewer = { scene: { pick: () => undefined, canvas: {} } };
const { draw } = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...camera }),
viewRectangle: () => null,
on: () => () => {},
flyTo: (destination, options) => flights.push({ destination, options }),
},
});
// The layer's click subscription, called with a hit as the dispatcher gives it.
const fake = fakeInput(viewer);
const clicks = [];
const subscribe = fake.input.onClick;
fake.input.onClick = (fn) => {
clicks.push(fn);
return subscribe.call(fake.input, () => {});
};
parts.lifecycle.methods.init(viewer);
const coverage = () =>
draw.find('bikeshare:') &&
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(':coverage'),
);
return {
state,
parts,
owners,
flights,
coverage,
click: (hit) => clicks.at(-1)({ drawHit: hit }),
async moveTo(height) {
camera.height = height;
await parts.viewport.runProximityCheck();
},
enable: () => parts.lifecycle.methods.enable(viewer),
disable: () => parts.lifecycle.methods.disable(),
};
}
test('every covered city has a marker, shown only while the layer is on and too high for stations', async () => {
const layer = makeLayer();
const set = layer.coverage();
assert.equal(set.items.size, GBFS_CITY_REGISTRY.length);
assert.equal(set.show, false, 'hidden while the layer is off');
layer.enable();
await layer.moveTo(18_000_000);
assert.equal(set.show, true, 'the globe shows where bike share is');
await layer.moveTo(20_000);
assert.equal(
set.show,
false,
'stations take over below the activation height',
);
await layer.moveTo(18_000_000);
assert.equal(set.show, true);
layer.disable();
assert.equal(set.show, false, 'gone with the layer');
});
test('a marker belongs to the layer and its click flies straight down into the city', async () => {
const layer = makeLayer();
layer.enable();
await layer.moveTo(18_000_000);
const city = GBFS_CITY_REGISTRY.find(
(each) => each.id === 'boston-bluebikes',
);
const id = `city:${city.id}`;
assert.equal(layer.owners.get('bikeshare')(id), true);
assert.equal(layer.owners.get('bikeshare')('city:nowhere'), false);
const navigated = [];
layer.parts.lifecycle.methods.attachShellServices({
runNavigation: (navigate) => {
navigated.push('explicit');
return navigate();
},
});
layer.click({ set: layer.coverage().spec.id, id });
assert.deepEqual(navigated, ['explicit'], 'an explicit camera action');
assert.equal(layer.flights.length, 1);
const { destination, options } = layer.flights[0];
assert.deepEqual(destination, {
lon: city.centerLon,
lat: city.centerLat,
height: COVERAGE_FLY_HEIGHT_M,
});
assert.equal(options.orientation.pitch, -Math.PI / 2);
assert.ok(COVERAGE_FLY_HEIGHT_M < 48_000, 'below the activation height');
});
+7 -18
View File
@@ -83,7 +83,8 @@ test('a recovered city clears its own failure', () => {
// drive the real proximity check, status poll and lifecycle against a fake
// GBFS source, so the failure state they read is the state the layer builds.
import * as Cesium from 'cesium';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { CITY_BY_ID } from './registry.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
@@ -175,7 +176,7 @@ function makeLiveLayer() {
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
sprites: {},
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
};
const state = createState({ services });
@@ -195,21 +196,9 @@ function makeLiveLayer() {
parts.lifecycle = createLifecycle(context);
const { methods: controls } = createControls(context);
const camera = { ...BETWEEN, height: LOW_M };
const viewer = {
camera: {
get positionCartographic() {
return Cesium.Cartographic.fromDegrees(
camera.lon,
camera.lat,
camera.height,
);
},
computeViewRectangle: () => undefined,
changed: { addEventListener() {}, removeEventListener() {} },
},
scene: { globe: {}, primitives: { add() {}, remove() {} } },
};
const camera = fakeCameraPort({ pose: { ...BETWEEN, height: LOW_M } });
const viewer = {};
bindFakeDraw(viewer, { camera: camera.port });
parts.lifecycle.methods.init(viewer);
return {
@@ -217,7 +206,7 @@ function makeLiveLayer() {
source,
stats: () => controls.getStats(),
moveTo(place, height = LOW_M) {
Object.assign(camera, place, { height });
camera.setPose({ ...place, height });
return parts.viewport.runProximityCheck();
},
async enable() {
+58 -65
View File
@@ -1,10 +1,9 @@
import * as Cesium from 'cesium';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
CAMERA_CHANGED_THRESHOLD,
} from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createLifecycle({
state: layerState,
@@ -12,28 +11,42 @@ export function createLifecycle({
parts,
source,
}) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { registerPickOwner, unregisterPickOwner } = services.picking;
/** Stop listening to the camera, if the layer is. */
function detachCamera() {
layerState._cameraChangedOff?.();
layerState._cameraChangedOff = null;
}
const methods = {
/**
* Initialize the bikeshare layer. Creates the point primitive collection,
* resets all internal state, and installs the click handler.
* Called once during app bootstrap.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* The shell's services: `runNavigation(navigate)` runs a covered city's
* flight as an explicit camera action, as the other camera controls are.
* @param {{ runNavigation?: Function }|null} shellServices
*/
attachShellServices(shellServices) {
layerState._runNavigation =
typeof shellServices?.runNavigation === 'function'
? shellServices.runNavigation
: null;
},
/**
* Initialize the bikeshare layer. Makes the station draw sets on the
* viewer's renderer (`drawOf`), resets all internal state, and installs
* the click handler. Called once during app bootstrap. Given a Cesium
* viewer with no renderer bound, the caller loads
* the package's `./render/cesium/unbound` export first.
* @param {object} viewer - The viewer the layer draws on.
*/
init(viewer) {
parts.rendering.attachSets(viewer);
layerState._viewer = viewer;
layerState._pointCollection = new Cesium.PointPrimitiveCollection({
blendOption: Cesium.BlendOption.TRANSLUCENT,
});
viewer.scene.primitives.add(layerState._pointCollection);
registerSpriteCollection('bikeshare', layerState._pointCollection);
layerState._pointCollection.show = false;
layerState._enabled = false;
layerState._cameraDebounceTimer = null;
layerState._cameraChangedAttached = false;
detachCamera();
layerState._altitudeGateEnabled = false;
layerState._proximityGeneration = 0;
@@ -44,9 +57,8 @@ export function createLifecycle({
layerState._inFlightInfo = new Map();
layerState._inFlightStatus = new Map();
layerState._stationRenderMap = new Map();
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._selectedKey = null;
layerState._selectedEntity = null;
layerState._count = 0;
layerState._lastUpdate = null;
layerState._loading = false;
@@ -61,8 +73,6 @@ export function createLifecycle({
parts.selection._installClickHandler(viewer);
restoreSpriteOrder(viewer);
console.log(
`[Data:Bikeshare] Initialized with ${GBFS_CITY_REGISTRY.length} cities`,
);
@@ -71,41 +81,42 @@ export function createLifecycle({
/**
* Enable the bikeshare layer. Shows points, attaches the camera listener,
* and triggers an initial proximity check.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
*/
enable(viewer) {
layerState._enabled = true;
layerState._failedCityIds.clear();
layerState._pointCollection.show = true;
layerState._stationSet.show = true;
layerState._overlayHost.setVisible(
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
true,
);
parts.selection._installClickHandler(viewer);
// Pick-ownership (H2): station point ids are string render-map keys.
registerPickOwner('bikeshare', (pickedId) =>
layerState._stationRenderMap.has(pickedId),
registerPickOwner(
'bikeshare',
(pickedId) =>
layerState._stationRenderMap.has(pickedId) ||
parts.selection.coverageCityOf(pickedId) !== null,
);
if (!layerState._cameraChangedAttached) {
viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged);
// Through the shared ledger: this is a single number every layer's
// camera.changed listener shares, and a layer leaving must not hand
// back a coarse default while this one is still driving off it.
claimCameraSensitivity(viewer.camera, 'bikeshare', 0.05);
layerState._cameraChangedAttached = true;
if (!layerState._cameraChangedOff) {
// Its own threshold: the camera measures it for this listener alone.
layerState._cameraChangedOff = cameraOf(viewer).on(
'changed',
parts.viewport.onCameraChanged,
{ threshold: CAMERA_CHANGED_THRESHOLD },
);
}
void parts.viewport.runProximityCheck();
restoreSpriteOrder(viewer);
},
/**
* Disable the bikeshare layer. Hides points, removes event listeners,
* aborts all pending fetches, and tears down all city data.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
*/
disable(viewer) {
disable() {
layerState._enabled = false;
layerState._proximityGeneration++;
layerState._altitudeGateEnabled = false;
@@ -117,58 +128,40 @@ export function createLifecycle({
false,
);
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
document.removeEventListener('keydown', parts.selection._onKeyDown);
unregisterPickOwner('bikeshare');
if (layerState._cameraChangedAttached) {
viewer.camera.changed.removeEventListener(
parts.viewport.onCameraChanged,
);
releaseCameraSensitivity(viewer.camera, 'bikeshare');
layerState._cameraChangedAttached = false;
}
detachCamera();
parts.ingestion.abortAllInFlight();
parts.viewport.deactivateAllCities();
layerState._cityRuntime.clear();
layerState._pointCollection.show = false;
if (layerState._stationSet) layerState._stationSet.show = false;
parts.viewport.showCoverage(false);
layerState._count = 0;
layerState._loading = false;
layerState._loadingOps = 0;
},
/** Permanently release primitives, handlers, and the selected host source. */
destroy(viewer) {
if (layerState._enabled) this.disable(viewer);
/** Permanently release draw sets, handlers, and the selected host source. */
destroy() {
if (layerState._enabled) this.disable();
else {
parts.selection._clearSelection();
layerState._overlayHost.setVisible(
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
false,
);
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
document.removeEventListener('keydown', parts.selection._onKeyDown);
unregisterPickOwner('bikeshare');
}
if (layerState._cameraChangedAttached) {
viewer.camera.changed.removeEventListener(
parts.viewport.onCameraChanged,
);
releaseCameraSensitivity(viewer.camera, 'bikeshare');
layerState._cameraChangedAttached = false;
}
detachCamera();
parts.ingestion.abortAllInFlight();
if (layerState._pointCollection) {
viewer.scene.primitives.remove(layerState._pointCollection);
layerState._pointCollection = null;
}
parts.rendering.detachSets();
layerState._dataManager = null;
layerState._viewer = null;
},
+77 -13
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export const BIKESHARE_SELECTED_OVERLAY_SOURCE_ID = 'bikeshare-selected';
export const BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS = Object.freeze({
@@ -17,6 +15,22 @@ const ACTIVATION_ALTITUDE_M = 50000;
export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 2000;
/**
* Where a covered city's marker flies to: straight down from this height,
* well inside the activation band, with the city's stations in view.
*/
export const COVERAGE_FLY_HEIGHT_M = 20000;
/** A covered city's marker: the stations' green, larger, ringed in white. */
export const COVERAGE_PIXEL_SIZE = 11;
export const COVERAGE_OUTLINE_WIDTH = 2;
/**
* A marker's height: above the highest covered city's ground, so terrain
* never hides it, while the globe itself hides the markers behind it.
*/
export const COVERAGE_HEIGHT_M = 5000;
/** Hysteresis exit threshold — layer deactivates when camera rises above this. */
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000;
@@ -25,6 +39,13 @@ export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000;
export const CAMERA_DEBOUNCE_MS = 340;
/**
* How far the view moves before the camera tells the layer (the camera's
* `changed` threshold): fine, so it notices entering a city's range.
*/
export const CAMERA_CHANGED_THRESHOLD = 0.05;
/** Default radius (km) for determining whether a city is in camera range. */
export const CITY_RANGE_BASE_KM = 100;
@@ -55,31 +76,74 @@ export const POINT_HEIGHT_OFFSET_M = 2.0;
export const MAX_TOTAL_POINTS = 8000;
// --- Availability color palette ---
// Renderer colours, `[r, g, b, a]` in 0..1: the CSS colours below at the
// alphas the points draw them with.
/** A CSS `#rrggbb` colour at `alpha`, as a renderer colour. */
const hex = (css, alpha) =>
Object.freeze([
parseInt(css.slice(1, 3), 16) / 255,
parseInt(css.slice(3, 5), 16) / 255,
parseInt(css.slice(5, 7), 16) / 255,
alpha,
]);
/** Station has >60% bikes available. */
export const COLOR_GREEN =
Cesium.Color.fromCssColorString('#00ff88').withAlpha(0.95);
export const COLOR_GREEN = hex('#00ff88', 0.95);
/** Station has 30-60% bikes available. */
export const COLOR_YELLOW =
Cesium.Color.fromCssColorString('#ffaa00').withAlpha(0.94);
export const COLOR_YELLOW = hex('#ffaa00', 0.94);
/** Station has <30% bikes available. */
export const COLOR_RED =
Cesium.Color.fromCssColorString('#ff4444').withAlpha(0.94);
export const COLOR_RED = hex('#ff4444', 0.94);
/** No status data available for station. */
export const COLOR_NEUTRAL =
Cesium.Color.fromCssColorString('#91a4b4').withAlpha(0.62);
export const COLOR_NEUTRAL = hex('#91a4b4', 0.62);
/** Station is offline (not installed, not renting, or not returning). */
export const COLOR_MUTED =
Cesium.Color.fromCssColorString('#687581').withAlpha(0.48);
export const COLOR_MUTED = hex('#687581', 0.48);
/** Outline color for all station points. */
export const COLOR_OUTLINE = Cesium.Color.BLACK.withAlpha(0.25);
export const COLOR_OUTLINE = Object.freeze([0, 0, 0, 0.25]);
// --- Selected-station highlight ---
/** The selected station's dot: cyan, outlined black, drawn over everything. */
export const SELECTED_POINT_STYLE = Object.freeze({
pixelSize: 14,
color: Object.freeze([0, 1, 1, 1]),
outlineColor: Object.freeze([0, 0, 0, 1]),
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
});
// --- Station dot distance falloff ---
/** Station dots grow near the eye and shrink far from it. */
export const POINT_SCALE_BY_DISTANCE = Object.freeze({
near: 200,
nearValue: 1.35,
far: 130000,
farValue: 0.4,
});
/** Station dots fade out with distance. */
export const POINT_FADE_BY_DISTANCE = Object.freeze({
near: 200,
nearValue: 1.0,
far: 180000,
farValue: 0.15,
});
/** Station dots draw over the ground within this many metres of the eye. */
export const POINT_DISABLE_DEPTH_TEST_M = 2500;
+2 -2
View File
@@ -459,7 +459,7 @@ test('a station without a published capacity re-derives it from every status pol
const state = {
_cityRuntime: new Map(),
_stationRenderMap: new Map(),
_pointCollection: { add: (options) => ({ ...options }) },
_stationSet: { upsert() {}, remove() {} },
};
const rendering = createRendering({
state,
@@ -502,7 +502,7 @@ test('a station without a published capacity re-derives it from every status pol
{ station_id: 'fixed', num_bikes_available: 2, num_docks_available: 3 },
]);
assert.equal(open.capacity, 30, 'the first poll fixed the capacity');
assert.equal(open.point.color, COLOR_YELLOW, '10 of 30 is not plenty');
assert.equal(open.color, COLOR_YELLOW, '10 of 30 is not plenty');
assert.equal(fixed.capacity, 13, 'a published capacity is kept');
poll([
+7 -8
View File
@@ -26,24 +26,23 @@ export function createQueries({ state: layerState, services, parts, source }) {
* @param {Object} [options]
* @param {number} [options.maxCount] - Maximum number of detectable objects to return.
* @param {number} [options.seed] - Seed for deterministic stride offset selection.
* @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>}
* @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>}
*/
function collectDetectableStations(options = {}) {
if (
!layerState._enabled ||
!layerState._pointCollection ||
!layerState._pointCollection.show ||
!layerState._stationSet ||
!layerState._stationSet.show ||
layerState._stationRenderMap.size === 0
)
return [];
// Gather all visible station records (include selected even though its point is hidden)
// Gather all station records (the selected one too, though its own dot
// is hidden under the highlight)
const records = [];
for (const record of layerState._stationRenderMap.values()) {
const isSelected = record.key === layerState._selectedKey;
if ((!record.point?.show && !isSelected) || !record.point?.position)
continue;
if (!record.position) continue;
records.push(record);
}
if (records.length === 0) return [];
@@ -60,7 +59,7 @@ export function createQueries({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const record = records[i];
result.push({
position: record.point.position,
position: record.position,
sourceId: record.key,
id: buildDetectionId(record),
type: 'VEH',
+126 -40
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
DEFAULT_CAPACITY,
POINT_SIZE_MIN,
@@ -11,7 +10,28 @@ import {
POINT_HEIGHT_OFFSET_M,
MAX_TOTAL_POINTS,
COLOR_OUTLINE,
POINT_SCALE_BY_DISTANCE,
POINT_FADE_BY_DISTANCE,
POINT_DISABLE_DEPTH_TEST_M,
COVERAGE_PIXEL_SIZE,
COVERAGE_OUTLINE_WIDTH,
COVERAGE_HEIGHT_M,
} from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
/**
* The draw sets the stations are drawn in start with this; each layer has
* its own (`bikeshare:1:stations`, `bikeshare:1:selected`), so several can
* share a renderer. Picks name them as `Hit.set`.
*/
export const BIKESHARE_SET_ID = 'bikeshare';
/** A covered city's marker id: its registry id under this prefix. */
export const COVERAGE_ID_PREFIX = 'city:';
let instances = 0;
export function createRendering({
state: layerState,
@@ -21,6 +41,78 @@ export function createRendering({
}) {
const { governorRequestRender } = services.render;
/**
* Make the layer's draw sets on `viewer`'s renderer (`drawOf`): the
* station dots, hidden until the layer is enabled, and the selected
* station's highlight. Sets made before are let go first.
* @param {object} viewer
*/
function attachSets(viewer) {
const draw = drawOf(viewer);
detachSets();
const prefix = `${BIKESHARE_SET_ID}:${++instances}`;
layerState._stationSet = draw.points({
id: `${prefix}:stations`,
blend: 'translucent',
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
});
layerState._selectedSet = draw.points({ id: `${prefix}:selected` });
// One marker per covered city, drawn while the camera is too high for
// stations: the globe shows where bike share is.
layerState._coverageSet = draw.points({
id: `${prefix}:coverage`,
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
});
layerState._coverageSet.set(
GBFS_CITY_REGISTRY.map((city) => ({
id: `${COVERAGE_ID_PREFIX}${city.id}`,
pos: fromDegrees(city.centerLon, city.centerLat, COVERAGE_HEIGHT_M),
pixelSize: COVERAGE_PIXEL_SIZE,
color: COLOR_GREEN,
outlineColor: [1, 1, 1, 0.9],
outlineWidth: COVERAGE_OUTLINE_WIDTH,
})),
);
// Drawn from the start, empty, so both take their place in the scene
// now, as the layer's collections did; the stations' place among the
// other sprite layers is their draw order (`spriteDrawOrder`).
layerState._stationSet.set([]);
layerState._selectedSet.set([]);
}
/** Let the layer's draw sets go. */
function detachSets() {
layerState._stationSet?.dispose();
layerState._selectedSet?.dispose();
layerState._coverageSet?.dispose();
layerState._stationSet = null;
layerState._selectedSet = null;
layerState._coverageSet = null;
}
/**
* A station's dot, from its render record; the selected station's own dot
* is hidden while its highlight replaces it.
* @param {Object} record - Render record from _stationRenderMap.
* @returns {import('../../render/contract/draw').PointItem}
*/
function stationItem(record) {
return {
id: record.key,
pos: record.position,
pixelSize: record.pixelSize,
color: record.color,
outlineColor: COLOR_OUTLINE,
outlineWidth: 1,
scaleByDistance: POINT_SCALE_BY_DISTANCE,
fadeByDistance: POINT_FADE_BY_DISTANCE,
disableDepthTest: POINT_DISABLE_DEPTH_TEST_M,
show: record.key !== layerState._selectedKey,
};
}
/**
* Resolve the effective dock capacity for a station.
* Prefers the explicit capacity from station_information; falls back to
@@ -68,7 +160,7 @@ export function createRendering({
* - <30% bikes available: red.
* @param {Object|null} status - Station status object.
* @param {number} capacity - Resolved station capacity.
* @returns {Cesium.Color} Color to apply to the station point.
* @returns {readonly number[]} Renderer colour `[r, g, b, a]` for the station point.
*/
function statusToColor(status, capacity) {
@@ -87,10 +179,10 @@ export function createRendering({
}
/**
* Create a Cartesian3 position for a station, terrain-clamped when possible.
* The ECEF position for a station, on the sampled surface when possible.
* Falls back to a fixed small height offset if terrain sampling is unsupported.
* @param {Object} station - Station info object with lat/lon.
* @returns {Cesium.Cartesian3|null} World position, or null if coordinates are invalid.
* @returns {{x: number, y: number, z: number}|null} ECEF metres, or null if coordinates are invalid.
*/
function createStationPosition(station) {
@@ -100,15 +192,13 @@ export function createRendering({
let height = POINT_HEIGHT_OFFSET_M;
// Sample terrain height so points sit on ground rather than at ellipsoid level
if (layerState._viewer?.scene?.sampleHeightSupported) {
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
const sampled = layerState._viewer.scene.sampleHeight(carto);
if (Number.isFinite(sampled)) {
height = sampled + POINT_HEIGHT_OFFSET_M;
}
const viewer = layerState._viewer;
if (viewer && heightsOf(viewer).supported().surface) {
const sampled = heightsOf(viewer).now({ lon, lat });
if (sampled !== null) height = sampled + POINT_HEIGHT_OFFSET_M;
}
return Cesium.Cartesian3.fromDegrees(lon, lat, height);
return fromDegrees(lon, lat, height);
}
/**
@@ -126,8 +216,8 @@ export function createRendering({
}
/**
* Ensure point primitives exist for all stations in a city.
* Creates new points for stations not yet rendered; skips existing ones.
* Ensure dots exist for all stations in a city.
* Creates new dots for stations not yet rendered; skips existing ones.
* Respects the MAX_TOTAL_POINTS global cap to prevent GPU overload.
* @param {string} cityId - City identifier.
* @param {Map<string, Object>} stationMap - Parsed station info map for the city.
@@ -139,6 +229,7 @@ export function createRendering({
governorRequestRender('bikeshare-points');
const runtime = ensureCityRuntime(cityId);
const added = [];
for (const station of stationMap.values()) {
const key = parts.model.stationKey(cityId, station.stationId);
if (layerState._stationRenderMap.has(key)) {
@@ -160,30 +251,14 @@ export function createRendering({
const position = createStationPosition(station);
if (!position) continue;
// Add a point primitive with distance-based scale and translucency falloff
const point = layerState._pointCollection.add({
position,
pixelSize: capacityToPixelSize(station.capacity),
color: COLOR_NEUTRAL,
outlineColor: COLOR_OUTLINE,
outlineWidth: 1,
scaleByDistance: new Cesium.NearFarScalar(200, 1.35, 130000, 0.4),
translucencyByDistance: new Cesium.NearFarScalar(
200,
1.0,
180000,
0.15,
),
disableDepthTestDistance: 2500,
id: key,
});
layerState._stationRenderMap.set(key, {
const record = {
key,
cityId,
stationId: station.stationId,
stationName: station.name,
point,
position,
pixelSize: capacityToPixelSize(station.capacity),
color: COLOR_NEUTRAL,
capacity: parts.model.toNonNegativeInteger(station.capacity),
publishedCapacity: parts.model.toNonNegativeInteger(station.capacity),
bikesAvailable: null,
@@ -191,16 +266,20 @@ export function createRendering({
isInstalled: station.isInstalled,
isRenting: station.isRenting,
isReturning: station.isReturning,
});
};
layerState._stationRenderMap.set(key, record);
// A dot with distance-based scale and translucency falloff.
added.push(stationItem(record));
runtime.stationKeys.add(key);
}
if (added.length) layerState._stationSet?.upsert(added);
layerState._count = layerState._stationRenderMap.size;
}
/**
* Remove all rendered point primitives for a city and clean up runtime state.
* Remove all rendered dots for a city and clean up runtime state.
* Also clears any active selection if it belongs to this city.
* @param {string} cityId - City identifier to remove.
*/
@@ -217,12 +296,13 @@ export function createRendering({
parts.selection._clearSelection();
}
const removed = [];
for (const key of runtime.stationKeys) {
const record = layerState._stationRenderMap.get(key);
if (!record) continue;
layerState._pointCollection.remove(record.point);
if (!layerState._stationRenderMap.has(key)) continue;
removed.push(key);
layerState._stationRenderMap.delete(key);
}
if (removed.length) layerState._stationSet?.remove(removed);
layerState._cityRuntime.delete(cityId);
layerState._count = layerState._stationRenderMap.size;
@@ -241,6 +321,7 @@ export function createRendering({
const runtime = layerState._cityRuntime.get(cityId);
if (!runtime) return;
const updated = [];
for (const key of runtime.stationKeys) {
const record = layerState._stationRenderMap.get(key);
if (!record) continue;
@@ -267,11 +348,16 @@ export function createRendering({
);
// Update visual properties based on current status
record.point.pixelSize = capacityToPixelSize(capacity);
record.point.color = statusToColor(status, capacity);
record.pixelSize = capacityToPixelSize(capacity);
record.color = statusToColor(status, capacity);
updated.push(stationItem(record));
}
if (updated.length) layerState._stationSet?.upsert(updated);
}
return {
attachSets,
detachSets,
stationItem,
resolveCapacity,
capacityToPixelSize,
statusToColor,
+7 -13
View File
@@ -6,7 +6,6 @@
// row text (LayerPanel._buildMetaText) at every refreshLayerStats() call.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { CITY_BY_ID, GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createControls } from './controls.js';
@@ -16,6 +15,7 @@ import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const BOSTON_ID = 'boston-bluebikes';
const TORONTO_ID = 'toronto-bike-share';
@@ -149,20 +149,14 @@ function makeLiveLayer() {
const { methods: controls } = createControls(context);
const camera = { ...LONDON, height: LOW_M };
const viewer = {
const viewer = {};
bindFakeDraw(viewer, {
camera: {
get positionCartographic() {
return Cesium.Cartographic.fromDegrees(
camera.lon,
camera.lat,
camera.height,
);
},
computeViewRectangle: () => undefined,
changed: { addEventListener() {}, removeEventListener() {} },
pose: () => ({ lon: camera.lon, lat: camera.lat, height: camera.height }),
viewRectangle: () => null,
on: () => () => {},
},
scene: { globe: {}, primitives: { add() {}, remove() {} } },
};
});
parts.lifecycle.methods.init(viewer);
const painted = [];
+75 -58
View File
@@ -1,10 +1,14 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
SELECTED_POINT_STYLE,
COVERAGE_FLY_HEIGHT_M,
} from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { COVERAGE_ID_PREFIX } from './rendering.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createSelection({
state: layerState,
@@ -63,7 +67,7 @@ export function createSelection({
*/
function createBikeshareSelectedOverlayEntry(key, record) {
const position = record?.point?.position;
const position = record?.position;
if (!key || !position) return null;
const [title, ...details] = buildSelectionLabel(record).split('\n');
return {
@@ -91,29 +95,22 @@ export function createSelection({
/**
* Clear the current station selection.
* Re-shows the hidden point primitive and removes the highlight entity.
* Shows the station's own dot again and removes the highlight.
*/
function _clearSelection() {
if (layerState._selectedKey) {
const record = layerState._stationRenderMap.get(layerState._selectedKey);
if (record?.point) {
record.point.show = true;
}
}
if (layerState._selectedEntity && layerState._viewer) {
layerState._viewer.entities.remove(layerState._selectedEntity);
}
const key = layerState._selectedKey;
layerState._selectedKey = null;
layerState._selectedEntity = null;
const record = key ? layerState._stationRenderMap.get(key) : null;
if (record?.position)
layerState._stationSet?.upsert([parts.rendering.stationItem(record)]);
if (layerState._selectedSet?.size()) layerState._selectedSet.clear();
layerState._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
}
/**
* Select a station by key: hides the original point primitive and adds a
* highlighted cyan entity plus a protected shared-host availability card.
* Select a station by key: hides its own dot and draws a highlighted cyan
* one in its place, plus a protected shared-host availability card.
* @param {string} key - Composite "cityId:stationId" key.
*/
@@ -121,22 +118,14 @@ export function createSelection({
_clearSelection();
const record = layerState._stationRenderMap.get(key);
if (!record || !record.point?.position || !layerState._viewer) return;
if (!record || !record.position || !layerState._stationSet) return;
layerState._selectedKey = key;
// Hide the base point so the highlight entity replaces it visually
record.point.show = false;
layerState._selectedEntity = layerState._viewer.entities.add({
position: record.point.position,
point: {
pixelSize: 14,
color: Cesium.Color.CYAN,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
// Hide the base dot so the highlight replaces it visually
layerState._stationSet.upsert([parts.rendering.stationItem(record)]);
layerState._selectedSet?.set([
{ id: 'selected', pos: record.position, ...SELECTED_POINT_STYLE },
]);
const entry = createBikeshareSelectedOverlayEntry(key, record);
if (entry) {
layerState._overlayHost.setEntries(
@@ -151,46 +140,73 @@ export function createSelection({
* Install a screen-space click handler for station selection/deselection.
* Also registers a global keydown listener for Escape-to-deselect.
* Idempotent — does nothing if a handler is already installed.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
*/
/**
* The covered city a marker id names, or null.
* @param {unknown} id
*/
function coverageCityOf(id) {
if (typeof id !== 'string' || !id.startsWith(COVERAGE_ID_PREFIX))
return null;
const cityId = id.slice(COVERAGE_ID_PREFIX.length);
return GBFS_CITY_REGISTRY.find((city) => city.id === cityId) ?? null;
}
/**
* Straight down over a covered city, low enough for its stations, as the
* shell's camera action when it gave one.
* @param {{ centerLat: number, centerLon: number }} city
*/
function flyIntoCity(city) {
const viewer = layerState._viewer;
if (!viewer) return;
const fly = () =>
cameraOf(viewer).flyTo(
{
lon: city.centerLon,
lat: city.centerLat,
height: COVERAGE_FLY_HEIGHT_M,
},
{ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 } },
);
if (layerState._runNavigation) layerState._runNavigation(fly);
else fly();
}
function _installClickHandler(viewer) {
if (layerState._clickHandler) return;
if (layerState._clickSubscription) return;
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas,
);
layerState._clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
const picked = viewer.scene.pick(click.position);
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
const hit = event.drawHit;
if (picked) {
// Clicking selected entity itself — ignore (don't deselect).
if (picked.id === layerState._selectedEntity) return;
if (hit) {
// Clicking the selected highlight itself — ignore (don't deselect).
if (hit.set === layerState._selectedSet?.id) return;
// Check if the picked primitive or entity id matches a station key
const primitive = picked.primitive;
if (
primitive &&
typeof primitive.id === 'string' &&
layerState._stationRenderMap.has(primitive.id)
) {
_selectStation(primitive.id);
return;
// A covered city's marker: fly down into it.
if (hit.set === layerState._coverageSet?.id) {
const city = coverageCityOf(hit.id);
if (city) {
flyIntoCity(city);
return;
}
}
// A station dot of this layer's own set
if (
typeof picked.id === 'string' &&
layerState._stationRenderMap.has(picked.id)
hit.set === layerState._stationSet?.id &&
layerState._stationRenderMap.has(hit.id)
) {
_selectStation(picked.id);
_selectStation(hit.id);
return;
}
}
// Clicked empty space — deselect.
// Clicked anything else — deselect.
if (layerState._selectedKey) _clearSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
document.addEventListener('keydown', _onKeyDown);
}
@@ -212,5 +228,6 @@ export function createSelection({
_selectStation,
_installClickHandler,
_onKeyDown,
coverageCityOf,
};
}
+22 -11
View File
@@ -15,7 +15,7 @@ export function createState({ services }) {
// Module-level mutable state
// ---------------------------------------------------------------------------
/** @type {Cesium.Viewer|null} Active Cesium viewer instance. */
/** @type {object|null} The viewer the layer draws on. */
layerState._viewer = null;
@@ -23,9 +23,24 @@ export function createState({ services }) {
layerState._dataManager = null;
/** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */
/** Draw set of the station dots (`drawOf(viewer).points`), or null. */
layerState._pointCollection = null;
layerState._stationSet = null;
/**
* Draw set of the covered cities' markers, shown above the activation
* height so the globe says where bike share is, or null.
*/
layerState._coverageSet = null;
/** The shell's camera action for a marker's flight (`attachShellServices`), or null. */
layerState._runNavigation = null;
/** Draw set of the selected station's highlight dot, or null. */
layerState._selectedSet = null;
/** Whether the bikeshare layer is currently enabled. */
@@ -35,9 +50,9 @@ export function createState({ services }) {
layerState._cameraDebounceTimer = null;
/** Whether the camera.changed listener is currently attached. */
/** @type {(() => void)|null} Stops the camera `changed` listener, while attached. */
layerState._cameraChangedAttached = false;
layerState._cameraChangedOff = null;
/** Hysteresis flag for altitude-based activation. */
@@ -75,18 +90,14 @@ export function createState({ services }) {
layerState._stationRenderMap = new Map();
/** @type {Cesium.ScreenSpaceEventHandler|null} Click handler for station selection. */
/** @type {(() => void)|null} Unsubscribes the station-selection click. */
layerState._clickHandler = null;
layerState._clickSubscription = null;
/** @type {string|null} Key of the currently selected station, or null. */
layerState._selectedKey = null;
/** @type {Cesium.Entity|null} Entity used to display the selected-station point highlight. */
layerState._selectedEntity = null;
/** Total number of currently rendered station points. */
layerState._count = 0;
+1 -1
View File
@@ -8,9 +8,9 @@ export function createTesting({ state: layerState, services, parts, source }) {
overlayHost,
}) {
layerState._viewer = viewer;
parts.rendering.attachSets(viewer);
layerState._stationRenderMap = new Map([[key, record]]);
layerState._selectedKey = null;
layerState._selectedEntity = null;
layerState._overlayHost = overlayHost || layerState.DEFAULT_OVERLAY_HOST;
}
+34 -20
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { negativePiToPi, toDegrees, toRadians } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import {
ACTIVATION_EXIT_ALTITUDE_M,
@@ -12,44 +13,42 @@ export function createViewport({ state: layerState, services, parts, source }) {
/**
* Get the camera's current altitude in meters above the ellipsoid.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
* @returns {number} Altitude in meters, or Infinity if unavailable.
*/
function getCameraAltitude(viewer) {
const carto = viewer?.camera?.positionCartographic;
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
const height = findCamera(viewer)?.pose().height;
return Number.isFinite(height) ? height : Infinity;
}
/**
* Determine the lat/lon the camera is currently looking at.
* Prefers the center of the computed view rectangle; falls back to the
* camera's own cartographic position when the rectangle is unavailable.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* Prefers the center of the view rectangle; falls back to the camera's
* own position when the rectangle is unavailable.
* @param {object} viewer - The viewer the layer draws on.
* @returns {{ lat: number, lon: number }|null} Center coordinates in degrees, or null.
*/
function getCameraCenterLatLon(viewer) {
const camera = findCamera(viewer);
// Try view rectangle center first (more accurate for tilted views)
const rect = viewer?.camera?.computeViewRectangle?.(
viewer.scene.globe?.ellipsoid,
);
const rect = camera?.viewRectangle();
if (rect) {
const center = Cesium.Rectangle.center(rect);
// Across the antimeridian the east edge is west of the west one.
let east = toRadians(rect.east);
const west = toRadians(rect.west);
if (east < west) east += 2 * Math.PI;
return {
lat: Cesium.Math.toDegrees(center.latitude),
lon: Cesium.Math.toDegrees(center.longitude),
lat: (rect.south + rect.north) * 0.5,
lon: toDegrees(negativePiToPi((west + east) * 0.5)),
};
}
// Fallback: use the camera's own position
const carto = viewer?.camera?.positionCartographic;
if (carto) {
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
}
const pose = camera?.pose();
if (pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon))
return { lat: pose.lat, lon: pose.lon };
return null;
}
@@ -116,6 +115,18 @@ export function createViewport({ state: layerState, services, parts, source }) {
parts.rendering.removeCityPoints(cityId);
}
/**
* Show the covered cities' markers, or hide them: shown while the layer is
* on and the camera is too high for stations.
* @param {boolean} shown
*/
function showCoverage(shown) {
const set = layerState._coverageSet;
if (!set || set.show === shown) return;
set.show = shown;
governorRequestRender('bikeshare-coverage');
}
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
function refreshRow() {
layerState._dataManager?.refreshLayerStats?.('bikeshare');
@@ -213,11 +224,13 @@ export function createViewport({ state: layerState, services, parts, source }) {
const wasGateEnabled = layerState._altitudeGateEnabled;
// Altitude gate: disable all cities when camera is too high
if (!shouldActivateAtAltitude(altitude)) {
showCoverage(true);
deactivateAllCities();
if (wasGateEnabled) refreshRow();
return;
}
showCoverage(false);
const center = getCameraCenterLatLon(layerState._viewer);
if (!center) return;
@@ -289,6 +302,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
activateCity,
runProximityCheck,
scheduleProximityCheck,
showCoverage,
onCameraChanged,
};
}
+2
View File
@@ -261,6 +261,8 @@ export function createCalibration({
// §9.1: touching range takes manual control — clear the activation clamp.
if ('rangeScale' in patch) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
}
const anchorMoved = calibrationPatchMovesAnchor(patch);
if (options.transient === true && anchorMoved) {
+24 -28
View File
@@ -1,3 +1,4 @@
import { findFrame } from '../../render/rendererOf.js';
import {
createFrameSlot,
CCTV_OVERLAY_SOURCE_ID,
@@ -8,8 +9,6 @@ import {
CCTV_FRAME_CANVAS_H,
applyFrameResult,
} from '../../data/cctvCards.js';
import * as Cesium from 'cesium';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { selectCctvLod, applyEvictionGrace } from '../../data/cctvLod.js';
import {
CCTV_OVERLAY_SOURCE_OPTIONS,
@@ -35,7 +34,7 @@ export function createCards({ state: layerState, services, parts, source }) {
} = {}) {
layerState._activeCameraCardEnabled = activeCameraCardEnabled === true;
if (layerState._enabled) pushAmbientCardEntries();
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-cards');
return { activeCameraCardEnabled: layerState._activeCameraCardEnabled };
}
@@ -83,17 +82,16 @@ export function createCards({ state: layerState, services, parts, source }) {
);
return;
}
const scene = layerState._viewer.scene;
const carto = layerState._viewer.camera.positionCartographic;
const viewerLat = carto ? Cesium.Math.toDegrees(carto.latitude) : 0;
const viewerLon = carto ? Cesium.Math.toDegrees(carto.longitude) : 0;
// An eye with no geographic position (the earth's centre) measures from 0, 0.
const pose = parts.model.eyePose();
const viewerLat = pose ? pose.lat : 0;
const viewerLon = pose ? pose.lon : 0;
// The active camera is excluded from ambient selection ALWAYS (not just
// after its async activation settles). It is published separately in the
// protected lane below, and grace never applies to it.
const activeId = layerState._activeCameraId;
const occluder = horizonOccluder(layerState._viewer.camera);
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
const view = parts.rendering.cardView();
const { width, height } = view;
const marginX = width * CARD_VIEW_MARGIN;
const marginY = height * CARD_VIEW_MARGIN;
@@ -106,22 +104,20 @@ export function createCards({ state: layerState, services, parts, source }) {
let inView = false;
let sx = NaN;
let sy = NaN;
if (occluder.isPointVisible(record.position)) {
const screen = scene.cartesianToCanvasCoordinates(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
const screen = view.screenOf(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
candidates.push({
id,
@@ -148,7 +144,7 @@ export function createCards({ state: layerState, services, parts, source }) {
// the budget fill through the screen-distribution grid, so periphery
// cells hold cards instead of everything clustering at screen center.
const { cardIds, budgets } = selectCctvLod(candidates, {
cameraHeightM: carto?.height,
cameraHeightM: pose?.height,
incumbentIds: layerState._cardIds,
viewW: width,
viewH: height,
@@ -335,7 +331,7 @@ export function createCards({ state: layerState, services, parts, source }) {
slot,
applyFrameResult(slot, { ok: !!frame, frame }, Date.now()),
);
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-card-frame');
};
image.onload = () => settle(true);
image.onerror = () => settle(false);
+1 -1
View File
@@ -202,7 +202,7 @@ export function createControls({ state: layerState, services, parts, source }) {
* @param {Object} [options={}]
* @param {number} [options.maxCount] - Maximum number of objects to return.
* @param {number} [options.seed] - Offset seed for deterministic stride sampling.
* @returns {{ position: Cesium.Cartesian3, id: string, type: string }[]}
* @returns {{ position: {x: number, y: number, z: number}, id: string, type: string }[]}
*/
getDetectableObjects(options = {}) {
// The cameras the view pass shows, not icons it has hidden.
+195
View File
@@ -0,0 +1,195 @@
/**
* @module layers/cctv/drawSets
* @description The CCTV layer's draw sets: the frustum wireframes
* (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the
* active camera's monitor plane (`plane`, a quad), made through the draw
* port of the viewer the layer is on. They are made when first drawn into
* and made again on another viewer. Item ids keep the layer's
* `cctv-<cameraId>-<role>` scheme the shared pick registry reads, and each
* line's and plane's `meta.cameraId` names its camera (volumes are never
* picked and carry none).
*
* Coverage lines and the plane are written from handles the layer keeps
* (a record's `coverageEntities`, a projection runtime's `plane`): plain
* objects the layer changes and then writes, only what changed reaching
* the set.
*
* Meshes and quads are capabilities: on a renderer without them there are
* no viewshed volumes or monitor plane, and the lines still draw.
*/
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
let instances = 0;
/** A line handle's item, or null for a handle that names no line yet. */
function lineItemOf(handle) {
if (!handle?.id || !Array.isArray(handle.positions)) return null;
const color = handle.color;
return {
id: handle.id,
positions: handle.positions,
widthPx: handle.widthPx,
// As a polyline entity runs: along the ellipsoid between its positions.
mode: 'geodesic',
style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color },
depthFail: handle.depthFailColor
? { kind: 'solid', color: handle.depthFailColor }
: null,
meta: { cameraId: handle.cameraId },
show: handle.show !== false,
};
}
/** What a line item draws, as a key: an unchanged key is not written. */
const lineKey = (item) =>
[
item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'),
item.widthPx,
item.style.kind,
item.style.color.join(','),
item.depthFail ? item.depthFail.color.join(',') : '',
item.show,
].join('|');
/** The plane handle's quad item. */
function quadItemOf(plane) {
return {
id: plane.id,
center: plane.center,
orientation: plane.orientation,
size: plane.size,
source: plane.source,
alpha: plane.alpha,
outline: plane.outline,
meta: { cameraId: plane.cameraId },
show: plane.show === true,
};
}
export function createDrawSets({ state: layerState }) {
/** The live sets and the viewer they draw on, or null. */
let current = null;
/** Viewshed volumes written, ever (the QA harness checks for churn). */
let volumeWrites = 0;
/** The layer's sets on its viewer now, made if need be; null with none. */
function sets() {
const viewer = layerState._viewer;
if (!viewer) return null;
if (current?.viewer === viewer) return current;
dispose();
const draw = drawOf(viewer);
const n = ++instances;
current = {
viewer,
coverage: draw.lines({ id: `cctv:${n}:coverage` }),
viewshed:
draw.meshes?.({ id: `cctv:${n}:viewshed`, pickable: false }) ?? null,
plane: draw.quads?.({ id: `cctv:${n}:plane` }) ?? null,
// What each line item was last written as, by id.
lineKeys: new Map(),
};
return current;
}
/** The live sets, without making them. */
const live = () =>
current && current.viewer === layerState._viewer ? current : null;
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set?.dispose();
} catch {
// Its viewer went first.
}
current = null;
}
/** The ids of the sets that draw the layer's lines and plane. */
function pickableSetIds() {
const s = live();
if (!s) return [];
return s.plane ? [s.coverage.id, s.plane.id] : [s.coverage.id];
}
/** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */
function roleOfSet(setId) {
const s = live();
if (!s) return null;
if (setId === s.coverage.id) return 'coverage';
if (setId === s.plane?.id) return 'plane';
return null;
}
/** Write line handles that changed since they were last written. */
function writeLines(handles) {
if (!handles?.length) return;
const s = handles.some((h) => h?.id) ? sets() : null;
if (!s) return;
const changed = [];
for (const handle of handles) {
const item = lineItemOf(handle);
if (!item) continue;
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
}
/** Take every line out. */
function clearLines() {
const s = live();
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
sets()?.plane?.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
if (plane?.id) live()?.plane?.remove([plane.id]);
}
/** Write a viewshed volume. */
function writeVolume(item) {
const s = sets();
if (!s?.viewshed) return;
s.viewshed.upsert([item]);
volumeWrites += 1;
}
/** Take a viewshed volume out. */
function removeVolume(id) {
if (id) live()?.viewshed?.remove([id]);
}
/** How many viewshed volumes were written, for the QA harness. */
const volumeWritesForTest = () => volumeWrites;
return {
sets,
dispose,
pickableSetIds,
roleOfSet,
writeLines,
clearLines,
writePlane,
removePlane,
writeVolume,
removeVolume,
volumeWritesForTest,
};
}
+135
View File
@@ -0,0 +1,135 @@
// The CCTV layer's draw sets: lines written only as they change, dashed for
// an estimated bearing, the depth-fail colour passed as it is; the sets made
// again on another viewer and let go on dispose.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDrawSets } from './drawSets.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const line = (id, fields = {}) => ({
id,
cameraId: 'cam',
role: 'edge',
positions: [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
],
widthPx: 1.2,
color: [0.1, 0.2, 0.3, 0.4],
dashed: false,
depthFailColor: null,
show: true,
...fields,
});
test('lines are written as they change, and drawn as their handles say', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
const a = line('cctv-cam-ray-tl');
const b = line('cctv-cam-cap', { role: 'cap' });
drawSets.writeLines([a, b]);
const coverage = draw.find('cctv:');
assert.equal(coverage.kind, 'lines');
assert.equal(coverage.writes, 1);
assert.deepEqual(coverage.items.get(a.id), {
id: a.id,
positions: a.positions,
widthPx: 1.2,
mode: 'geodesic',
style: { kind: 'solid', color: a.color },
depthFail: null,
meta: { cameraId: 'cam' },
show: true,
});
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 1, 'unchanged handles write nothing');
b.dashed = true;
b.depthFailColor = [1, 1, 1, 0.2];
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 2);
const cap = coverage.items.get(b.id);
assert.deepEqual(cap.style, {
kind: 'dash',
color: b.color,
length: 16,
pattern16: 255,
});
assert.deepEqual(cap.depthFail, { kind: 'solid', color: [1, 1, 1, 0.2] });
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null);
drawSets.clearLines();
assert.equal(coverage.items.size, 0);
drawSets.writeLines([a]);
assert.ok(coverage.items.has(a.id), 'a cleared line is written again');
} finally {
unbind();
}
});
test('another viewer gets sets of its own; dispose lets them go', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
const old = one.draw.find('cctv:');
assert.equal(drawSets.volumeWritesForTest(), 1);
state._viewer = second;
assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet');
drawSets.writeLines([a]);
assert.ok(old.disposed, 'the old viewer’s sets are let go');
const now = two.draw.find('cctv:');
assert.ok(now.items.has(a.id), 'the line is written anew');
const [coverage, plane] = drawSets.pickableSetIds();
assert.equal(two.draw.set(coverage).kind, 'lines');
assert.equal(two.draw.set(plane).kind, 'quads');
assert.equal(drawSets.roleOfSet(plane), 'plane');
drawSets.dispose();
assert.ok(
[...two.draw.sets.values()].every((set) => set.disposed),
'every set is let go',
);
assert.equal(drawSets.roleOfSet(coverage), null);
} finally {
one.unbind();
two.unbind();
}
});
test('a renderer without meshes or quads still draws the lines', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
delete draw.meshes;
delete draw.quads;
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
drawSets.writeLines([line('cctv-cam-ray-tl')]);
const coverage = draw.find('cctv:');
assert.equal(coverage.items.size, 1);
// No viewshed volumes and no monitor plane: their writes do nothing.
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
drawSets.removeVolume('cctv-cam-viewshed');
const plane = { id: 'cctv-cam-plane', cameraId: 'cam', show: true };
drawSets.writePlane(plane);
drawSets.removePlane(plane);
assert.equal(drawSets.volumeWritesForTest(), 0);
assert.deepEqual(drawSets.pickableSetIds(), [coverage.spec.id]);
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
drawSets.dispose();
} finally {
unbind();
}
});
+8 -8
View File
@@ -106,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Blits the latest projection canvas into the next of two alternating
* offscreen buffer canvases and returns it (H5).
*
* Two buffers are required because Cesium's Material image path re-uploads a
* canvas texture only when the uniform receives a NEW object reference —
* redrawing the same canvas in place is invisible to the GPU. Alternating
* Two buffers are required because the plane re-uploads a canvas texture
* only when it is given a NEW canvas — redrawing the same canvas in place
* is invisible to the GPU. Alternating
* references forces a texture recreate, which at <=1Hz and 1080p is cheap.
*
* @param {Object} runtime - Projection runtime with `.canvas`.
@@ -139,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Pushes fresh pixels into the monitor plane material. Called every
* projection tick.
*
* Video feeds are skipped entirely — their HTMLVideoElement uniform is
* updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap
* Video feeds are skipped entirely — the renderer reads their
* HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap
* the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS.
*
* @param {Object} record - Camera record with an initialized projection runtime.
@@ -156,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
)
return;
const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial);
const planeShowing = !!runtime.plane?.show;
if (!planeShowing) return;
// Only swap when the canvas content actually changed since the last swap.
@@ -170,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
if (!buffer) return;
runtime.lastTextureSwapAt = now;
runtime.lastSwappedCanvasStamp = runtime.canvasStamp;
runtime.planeMaterial.image = buffer;
parts.projection.setPlaneSource(runtime, { canvas: buffer });
}
/**
@@ -355,7 +355,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
// camera republished once in 5 minutes, an Austin one not at all.
// Redrawing regardless bumped canvasStamp, which forced a buffer swap
// and a fresh 1920x1080 texture upload; the plane renders its white
// base color (planeMaterial color = WHITE, alpha .95) for the frame or
// base color (white, alpha .95) for the frame or
// two Cesium needs to rebind, which IS the periodic white flash from the
// owner field tests (2026-07-04 and 2026-07-30).
const fit = fitToProjection(
+114 -221
View File
@@ -1,12 +1,12 @@
import * as Cesium from 'cesium';
import { createFrustumVolumePrimitive } from '../../data/cctvViewshed.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp, frameVector } from '../../geo/frames.js';
import { distance, vec } from '../../geo/vector.js';
import {
FRUSTUM_GROUND_CLEARANCE_M,
PROBE_MIN_RANGE_M,
PROBE_CLEARANCE_M,
COVERAGE_NEIGHBOR_RADIUS_KM,
COVERAGE_NEIGHBOR_LIMIT,
IDLE_COVERAGE_COLOR,
PLANE_FOOTPRINT_LIFT_CAP_M,
} from './policy.js';
@@ -261,30 +261,18 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
/**
* Converts a computeFrustumGeometry result into the Cartesian3 positions the
* entities consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and entities must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: Cesium.Cartesian3, capCenter: Cesium.Cartesian3,
* tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, br: Cesium.Cartesian3,
* bl: Cesium.Cartesian3, label: Cesium.Cartesian3 }}
* Distance along a pitched-down view axis to flat ground at the mount's own
* ground height, or null for an axis at or above the horizon.
* @param {number} mountHeightM Mount height above its ground.
* @param {number} pitchDeg Axis pitch (negative looks down).
* @returns {number|null}
*/
function frustumCartesians(geometry) {
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
tl: at(geometry.corners.tl),
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: Cesium.Cartesian3.fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
),
};
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
const height = Number(mountHeightM);
const pitch = Number(pitchDeg);
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
return height / Math.sin((Math.min(89, -pitch) * Math.PI) / 180);
}
/**
@@ -292,40 +280,35 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* Used by the plane orientation and the activation obstruction probe — both
* need the UNCLAMPED axis, so it comes from the pose, not from clamped points.
* @param {Object} camera - Camera pose (headingDeg, pitchDeg).
* @param {Cesium.Cartesian3} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: Cesium.Cartesian3, up: Cesium.Cartesian3 }} View axis + the
* @param {{x: number, y: number, z: number}} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: {x: number, y: number, z: number}, up: {x: number, y: number, z: number} }} View axis + the
* frame's in-plane "up" (both unit, mutually perpendicular).
*/
function frustumFrameEcef(camera, atPos) {
const h = parts.model.toRad(camera.headingDeg);
const p = parts.model.toRad(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const enu = eastNorthUp(atPos);
// ENU components: view axis + the perpendicular "up" of the pitched cap.
const dirEnu = new Cesium.Cartesian3(
const dirEnu = vec(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
const upEnu = vec(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
return {
dir: Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
),
up: Cesium.Matrix3.multiplyByVector(rot, upEnu, new Cesium.Cartesian3()),
dir: frameVector(enu, dirEnu),
up: frameVector(enu, upEnu),
};
}
/**
* Recomputes the pure frustum geometry from the camera pose + the given ground
* altitude and writes it into the scene: billboard position, the 5 wireframe
* altitude and writes it into the scene: icon position, the 5 wireframe
* polylines (4 corner rays + closed far-plane rectangle), and the monitor
* plane placement. This is the ONLY place v2 geometry is written — called on
* slider input / save / activation / the one-shot ground snap, never per frame.
@@ -340,38 +323,16 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
footprintGroundFor(record),
);
const positions = frustumCartesians(geometry);
const positions = parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
record.camera.absoluteHeightM = geometry.mount.alt;
if (record.billboard) {
record.billboard.position = positions.mount;
}
parts.rendering.moveCameraIcon(record);
record.groundAltM = groundAltM;
if (record.coverageEntities?.length >= 5) {
record.coverageEntities[0].polyline.positions = [
positions.mount,
positions.tl,
];
record.coverageEntities[1].polyline.positions = [
positions.mount,
positions.tr,
];
record.coverageEntities[2].polyline.positions = [
positions.mount,
positions.br,
];
record.coverageEntities[3].polyline.positions = [
positions.mount,
positions.bl,
];
record.coverageEntities[4].polyline.positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
parts.rendering.placeCoverageLines(record.coverageEntities, positions);
parts.drawSets.writeLines(record.coverageEntities);
}
// A live viewshed volume tracks its wireframe: rebuild from the SAME fresh
// positions (weld invariant). Only records currently showing a volume pay
@@ -379,8 +340,8 @@ export function createGeometry({ state: layerState, services, parts, source }) {
// Tint derives from the live active id, not the cached viewshedActiveTint —
// during an activation switch this runs BEFORE refreshCoverageStyles, and
// the cache is stale for exactly that window.
if (record.viewshedPrimitive) {
rebuildViewshedVolume(
if (record.viewshedVolume) {
parts.rendering.rebuildViewshedVolume(
record,
record.camera.id === layerState._activeCameraId,
);
@@ -453,19 +414,12 @@ export function createGeometry({ state: layerState, services, parts, source }) {
if (sampleGround && parts.model.projectionTilesReady()) {
record.groundMeshSampleRequestCount =
(record.groundMeshSampleRequestCount || 0) + 1;
const viewerCarto = layerState._viewer?.camera?.positionCartographic;
const excludeObjects = [...(record.coverageEntities || [])];
if (record.billboard) excludeObjects.push(record.billboard);
if (record.projection?.planeEntity)
excludeObjects.push(record.projection.planeEntity);
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
excludeObjects: excludeObjects.filter(Boolean),
viewerLat: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.latitude)
: undefined,
viewerLon: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.longitude)
: undefined,
const eye = parts.model.eyePose();
// The layer's own lines and plane are not ground; named all the same.
sampleMeshFloorCells(layerState._viewer, [point], {
sets: parts.drawSets.pickableSetIds(),
viewerLat: eye ? eye.lat : undefined,
viewerLon: eye ? eye.lon : undefined,
});
}
@@ -525,52 +479,6 @@ export function createGeometry({ state: layerState, services, parts, source }) {
return new Set(chosen);
}
/**
* Removes (and destroys) a record's viewshed volume primitive, if any.
* @param {Object} record - Camera record.
*/
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedPrimitive && layerState._viewer) {
layerState._viewer.scene.primitives.remove(record.viewshedPrimitive);
}
record.viewshedPrimitive = null;
}
/**
* (Re)builds a record's translucent viewshed volume from its CURRENT
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
* is welded to the cone by construction. Called only where the wireframe
* already rewrites (style refresh on mode/visible-set/active changes,
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
* queries (viewshed design §3b).
* @param {Object} record - Camera record.
* @param {boolean} isActive - Active camera gets the brighter fill.
*/
function rebuildViewshedVolume(record, isActive) {
destroyViewshedVolume(record);
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
)
return;
const color = isActive
? record.viewshedColors.fillActive
: record.viewshedColors.fill;
const primitive = createFrustumVolumePrimitive(
record.frustumPositions,
color,
);
// QA tag: the harness counts viewshed volumes by this marker.
primitive._gevViewshed = record.camera.id;
record.viewshedPrimitive =
layerState._viewer.scene.primitives.add(primitive);
record.viewshedActiveTint = !!isActive;
}
/**
* Counts how many other cameras have overlapping coverage with the target.
* Overlap is approximated by comparing inter-camera distance against the
@@ -611,47 +519,94 @@ export function createGeometry({ state: layerState, services, parts, source }) {
/**
* §9.1 activation obstruction probe (LOCKED owner decision): on camera
* ACTIVATION only, fire ONE scene.pickFromRay along the frustum axis
* ACTIVATION only, cast ONE ray against the scene along the frustum axis
* (mount → cap-center direction). If it hits the tiles closer than the pose
* range, clamp the plane's effective range just short of the first hit so the
* "big and dramatic" true end cap never clips into downtown buildings.
*
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
* never per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range.
* On a globe map it also casts along the same axis against the globe's
* terrain (flat ground at the mount's ground when terrain is missed or met
* beyond the range) and clamps at the nearer end. These are the ONLY
* raycasts in the whole CCTV subsystem — once per activation, never
* per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips
* the probe entirely. A miss on the photoreal stack or a probe failure
* keeps the unclamped range.
*
* The casts are made now, against the scene as it is, and answer a
* microtask later: the clamp then lands by rewriting the geometry from the
* ground it was last written at, before the next frame draws. A newer
* activation, or the camera's deactivation, drops an answer still to come.
* @param {Object} record - Camera record being activated.
* @returns {Promise<void>} Settled once the clamp (if any) has landed.
*/
function runActivationObstructionProbe(record) {
record.probeClampRangeM = null;
const scene = layerState._viewer?.scene;
if (!scene || typeof scene.pickFromRay !== 'function') return;
const token = (record.probeToken = (record.probeToken || 0) + 1);
const viewer = layerState._viewer;
if (!parts.rendering.canPickFromRay()) return Promise.resolve();
const camera = record.camera;
const rangeScale = parts.calibration.normalizeCalibration(
camera.calibration,
).rangeScale;
if (Math.abs(rangeScale - 1) > 0.0001) return; // slider overrides the clamp
// The slider overrides the clamp.
if (Math.abs(rangeScale - 1) > 0.0001) return Promise.resolve();
try {
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
const mountPos = Cesium.Cartesian3.fromDegrees(
camera.lon,
camera.lat,
mountAlt,
);
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
const { dir } = frustumFrameEcef(camera, mountPos);
// Exclude everything the layer itself draws so the probe can only hit the
// world (3D tiles), not our own billboards/polylines/planes.
const exclude = [layerState._billboards, ...layerState._coverageEntities];
for (const runtime of layerState._projectionEntities) {
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
}
const hit = scene.pickFromRay(new Cesium.Ray(mountPos, dir), exclude);
if (!hit?.position) return;
const dist = Cesium.Cartesian3.distance(mountPos, hit.position);
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
// The casts see through everything the layer draws. The surface cast
// meets what is drawn on the globe (the photoreal tiles); on a globe
// map the axis also ends on the globe's terrain, the nearer of that and
// any surface hit. A hit at or beyond the range counts as none. Terrain
// still loading at a coarse level can be missed or met beyond the
// range; then flat ground at the mount's own ground stands in for it.
const inRange = (d) => Number.isFinite(d) && d > 0 && d < camera.rangeM;
return Promise.all([
parts.rendering.obstructionHit(mountPos, dir),
parts.rendering.terrainHit?.(mountPos, dir) ?? null,
])
.then(([hit, terrain]) => {
if (record.probeToken !== token) return;
if (record.camera.id !== layerState._activeCameraId) return;
// A layer torn down or re-initialised since (another viewer, or
// a new record for the same camera) is not the one it asked for.
if (layerState._viewer !== viewer) return;
if (layerState._recordById?.get(record.camera.id) !== record) return;
const hitDist = hit ? distance(mountPos, hit) : NaN;
const distances = inRange(hitDist) ? [hitDist] : [];
if (terrain) {
const terrainDist = terrain.hit
? distance(mountPos, terrain.hit)
: NaN;
const ground = inRange(terrainDist)
? terrainDist
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
}
if (!distances.length) return;
const clamp = activationProbeClampRange(
camera.rangeM,
Math.min(...distances),
);
if (!Number.isFinite(clamp)) return;
record.probeClampRangeM = clamp;
if (Number.isFinite(record.groundAltM))
applyFrustumGeometry(record, record.groundAltM);
// The activation asked for the ground under the unclamped plane's
// footprint; the clamped plane's is asked for now, and the layer
// restyles and tells its listeners, as that answer will.
void parts.ground.resolveFootprintGround(record);
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
})
.catch(() => {
// probe failure → keep the unclamped range
});
} catch {
// probe failure → keep the unclamped range
return Promise.resolve();
}
}
@@ -664,77 +619,17 @@ export function createGeometry({ state: layerState, services, parts, source }) {
*/
function clearProbeClampOnDeactivation(record, rewriteGeometry) {
if (record) record.probeToken = (record.probeToken || 0) + 1;
if (!record || !Number.isFinite(record.probeClampRangeM)) return false;
record.probeClampRangeM = null;
rewriteGeometry?.(record);
return true;
}
/**
* Creates the five Cesium polyline entities that visualize a camera's pitched
* frustum: 4 corner rays (mount → far-plane corner) + the closed far-plane
* rectangle. Entity ids stay in the `cctv-<id>-<role>` scheme (pick-owner
* regex depends on it): roles ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Cesium.Entity[]} Array of five coverage entities.
*/
function buildCoverageEntities(record) {
const { camera } = record;
// Prefer the record's already-refined geometry. Lazy creation commonly
// happens after the staggered ground pass; recomputing from the catalog
// prior here would regress the camera to its pre-sampled datum.
let geometry = record.frustumGeometry;
let positions = record.frustumPositions;
if (!geometry || !positions) {
geometry = computeFrustumGeometry(
camera,
parts.ground.groundPriorAltFor(record),
record.probeClampRangeM,
);
positions = frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
}
const addPolyline = (role, linePositions) =>
layerState._viewer.entities.add({
id: `cctv-${camera.id}-${role}`,
properties: { cctvCameraId: camera.id },
polyline: {
positions: linePositions,
width: 1.2,
material: IDLE_COVERAGE_COLOR,
},
});
const entities = [
addPolyline('ray-tl', [positions.mount, positions.tl]),
addPolyline('ray-tr', [positions.mount, positions.tr]),
addPolyline('ray-br', [positions.mount, positions.br]),
addPolyline('ray-bl', [positions.mount, positions.bl]),
addPolyline('cap', [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
]),
];
entities[0]._coverageRole = 'edge';
entities[1]._coverageRole = 'edge';
entities[2]._coverageRole = 'edge';
entities[3]._coverageRole = 'edge';
entities[4]._coverageRole = 'cap';
return entities;
}
/**
* Materializes coverage entities for eligible records exactly once.
* The helper is dependency-injected so unit tests can prove the enable policy
* without constructing Cesium entities.
* without constructing entities.
*
* @param {Object[]} records CCTV runtime records.
* @param {(record: Object) => boolean} [isEligible] Eligibility predicate.
@@ -792,7 +687,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function ensureActiveCoverageEntities(record) {
return registerCoverageEntities(
materializeCctvActiveCoverageEntities(record, buildCoverageEntities),
materializeCctvActiveCoverageEntities(
record,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -801,7 +699,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
materializeCctvVisibleCoverageEntities(
records,
visibleIds,
buildCoverageEntities,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -812,13 +710,11 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function destroyCoverageEntities() {
if (!layerState._viewer) return;
for (const entity of layerState._coverageEntities) {
layerState._viewer.entities.remove(entity);
}
parts.rendering.removeCoverageEntities();
layerState._coverageEntities = [];
for (const record of layerState._records) {
destroyViewshedVolume(record);
parts.rendering.destroyViewshedVolume(record);
}
for (const runtime of layerState._projectionEntities) {
@@ -831,17 +727,14 @@ export function createGeometry({ state: layerState, services, parts, source }) {
hasShippedFootprint,
footprintPose,
activationProbeClampRange,
frustumCartesians,
flatGroundAxisDistance,
frustumFrameEcef,
applyFrustumGeometry,
updateRecordGeometry,
buildCoverageVisibleSet,
destroyViewshedVolume,
rebuildViewshedVolume,
coverageNeighborCount,
runActivationObstructionProbe,
clearProbeClampOnDeactivation,
buildCoverageEntities,
materializeCctvCoverageEntities,
materializeCctvActiveCoverageEntities,
materializeCctvVisibleCoverageEntities,
+182
View File
@@ -0,0 +1,182 @@
// src/layers/cctv/geometry.test.mjs
// The frustum's view axis and the monitor plane's orientation are computed
// with the shared geo helpers; they must give what the renderer's own transforms
// gave, bit for bit, so frustums, probes and planes land where they did.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createGeometry } from './geometry.js';
import { createModel } from './model.js';
function parts() {
const p = {};
const context = {
state: {},
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
p.model = createModel(context);
p.geometry = createGeometry(context);
return p;
}
/** The renderer's own frame, as the layer computed it before. */
function cesiumFrame(camera, atPos) {
const h = Cesium.Math.toRadians(camera.headingDeg);
const p = Cesium.Math.toRadians(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const dirEnu = new Cesium.Cartesian3(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
const dir = Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
);
const up = Cesium.Matrix3.multiplyByVector(
rot,
upEnu,
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.cross(dir, up, new Cesium.Cartesian3());
const normal = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
const orientation = Cesium.Quaternion.fromRotationMatrix(
new Cesium.Matrix3(
right.x,
up.x,
normal.x,
right.y,
up.y,
normal.y,
right.z,
up.z,
normal.z,
),
);
return { dir, up, orientation };
}
const xyz = (v) => [v.x, v.y, v.z];
test('the frustum axis and plane orientation match the renderer transforms exactly', () => {
const { geometry, model } = parts();
let seed = 7;
const random = () => {
seed = (seed * 16807) % 2147483647;
return seed / 2147483647;
};
for (let i = 0; i < 500; i++) {
const camera = {
headingDeg: random() * 360,
pitchDeg: -89 + random() * 120,
};
const atPos = Cesium.Cartesian3.fromDegrees(
-180 + random() * 360,
-89 + random() * 178,
random() * 3000,
);
const expected = cesiumFrame(camera, atPos);
const frame = geometry.frustumFrameEcef(camera, atPos);
assert.deepEqual(xyz(frame.dir), xyz(expected.dir));
assert.deepEqual(xyz(frame.up), xyz(expected.up));
const q = model.planeOrientationFor(camera, atPos);
const e = expected.orientation;
assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]);
}
});
test('the activation probe clamps the range once its ray answers, unless the camera moved on', async () => {
const { createRendering } = await import('./rendering.js');
const p = {};
const state = { _activeCameraId: 'cam', _viewer: {} };
const context = {
state,
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
const written = [];
const footprints = [];
let restyles = 0;
let notices = 0;
let hitAtM = 80;
p.model = createModel(context);
p.geometry = createGeometry(context);
p.rendering = {
...createRendering(context),
canPickFromRay: () => true,
refreshCoverageStyles: () => (restyles += 1),
// The first surface `hitAtM` metres along the axis.
obstructionHit: async (origin, direction) => ({
x: origin.x + direction.x * hitAtM,
y: origin.y + direction.y * hitAtM,
z: origin.z + direction.z * hitAtM,
}),
};
p.calibration = { normalizeCalibration: () => ({ rangeScale: 1 }) };
p.ground = {
groundAltFor: () => 100,
resolveFootprintGround: async (r) =>
footprints.push(p.geometry.footprintPose(r)),
};
p.presentation = { notifyListeners: () => (notices += 1) };
p.drawSets = { writeLines: (lines) => written.push(lines) };
p.projection = { updatePlanePlacement() {} };
const record = {
camera: {
id: 'cam',
lon: -97.74,
lat: 30.27,
headingDeg: 90,
pitchDeg: -10,
fovDeg: 60,
rangeM: 200,
mountHeightM: 8,
},
coverageEntities: [],
};
state._recordById = new Map([['cam', record]]);
p.geometry.applyFrustumGeometry(record, 100);
assert.equal(record.frustumGeometry.rangeM, 200, 'unclamped at first');
const landed = p.geometry.runActivationObstructionProbe(record);
assert.equal(record.probeClampRangeM, null, 'the answer is still to come');
await landed;
const clamp = p.geometry.activationProbeClampRange(200, 80);
assert.ok(Math.abs(record.probeClampRangeM - clamp) < 1e-6);
assert.ok(
Math.abs(record.frustumGeometry.rangeM - clamp) < 1e-6,
'the geometry is rewritten at the clamp, from the ground it had',
);
assert.equal(record.frustumGeometry.mount.alt, 108);
assert.deepEqual(
footprints,
[p.geometry.footprintPose(record)],
"the clamped plane's footprint ground is asked for",
);
assert.ok(
Math.abs(footprints[0].rangeM - clamp) < 1e-6,
'at the clamped pose',
);
assert.deepEqual([restyles, notices], [1, 1]);
// A probe whose camera is deactivated before it answers lands nothing.
hitAtM = 50;
const stale = p.geometry.runActivationObstructionProbe(record);
p.geometry.clearProbeClampOnDeactivation(record, () => {});
await stale;
assert.equal(record.probeClampRangeM, null);
// Nor does one whose record a re-init replaced for the same camera.
const replaced = p.geometry.runActivationObstructionProbe(record);
state._recordById = new Map([['cam', { ...record }]]);
await replaced;
assert.equal(record.probeClampRangeM, null);
});
+8 -12
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { followedOf } from '../../data/followed.js';
import {
GEO_PROGRESS_NOTIFY_INTERVAL_MS,
GEO_PROGRESS_NOTIFY_BATCH_LIMIT,
@@ -125,16 +125,16 @@ export function createGeometryQueue({
* throughput without restarting the queue.
*
* @param {Object} [ownership={}] Current camera-ownership state.
* @param {*} [ownership.trackedEntity] Cesium tracked entity, if any.
* @param {*} [ownership.followed] What the camera follows, if anything.
* @param {boolean} [ownership.cockpitActive] Whether cockpit owns the camera.
* @returns {{ batchSize: number, delayMs: number }} Drain pacing.
*/
function cctvGeometryDrainPacing({
trackedEntity = null,
followed = null,
cockpitActive = false,
} = {}) {
if (trackedEntity || cockpitActive) {
if (followed || cockpitActive) {
return {
batchSize: GEO_TRACKING_BATCH_SIZE,
delayMs: GEO_TRACKING_BATCH_DELAY_MS,
@@ -213,7 +213,7 @@ export function createGeometryQueue({
const batchResult = processCctvGeometryDrainBatch({
queue: layerState._geoQueue,
readOwnership: () => ({
trackedEntity: layerState._viewer.trackedEntity,
followed: followedOf(layerState._viewer),
cockpitActive:
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode'),
@@ -303,13 +303,9 @@ export function createGeometryQueue({
layerState._tilesReadyReenqueued = false;
if (!layerState._records.length) return;
const active = parts.selection.getActiveRecord();
const carto = layerState._viewer?.camera?.positionCartographic;
const refLat = carto
? Cesium.Math.toDegrees(carto.latitude)
: (active?.camera.lat ?? 0);
const refLon = carto
? Cesium.Math.toDegrees(carto.longitude)
: (active?.camera.lon ?? 0);
const pose = parts.model.eyePose();
const refLat = pose ? pose.lat : (active?.camera.lat ?? 0);
const refLon = pose ? pose.lon : (active?.camera.lon ?? 0);
const pending = geometryWorkingSet()
.filter((record) => record !== active)
.map((record) => ({
+14 -10
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
planeSupportPoints,
@@ -13,7 +14,7 @@ export function createGround({ state: layerState, services, parts, source }) {
const { resolveEllipsoidalGround } = services.terrain;
/**
* Task 5 (height-datum fix): maps the scene's `globe.show` flag to the surface
* Task 5 (height-datum fix): maps whether the renderer shows the globe to the surface
* regime key the per-camera ground cache is keyed by (spec §2 "cache by
* surface regime", collapsed to two keys — ion World Terrain and Re:Earth
* globe terrain get the same handling):
@@ -26,7 +27,8 @@ export function createGround({ state: layerState, services, parts, source }) {
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - `viewer.scene.globe.show`.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
*/
@@ -36,15 +38,15 @@ export function createGround({ state: layerState, services, parts, source }) {
/**
* Task 5: the surface regime the scene is CURRENTLY rendering, derived live
* from `globe.show` (mapStackController's `_activatePhotoreal` /
* `_activateGlobeStack` flip exactly this flag). Reading scene state directly
* from whether the renderer shows the globe (mapStackController's
* `_activatePhotoreal` / `_activateGlobeStack` flip exactly this). Reading it live
* — rather than caching the map-stack id — means the regime is correct even
* for stack changes this module never got an event for.
* @returns {'google-3d'|'terrain-globe'}
*/
function currentSurfaceRegime() {
return surfaceRegimeKey(layerState._viewer?.scene?.globe?.show);
return surfaceRegimeKey(findGlobe(layerState._viewer)?.isGlobeVisible?.());
}
/**
@@ -231,14 +233,16 @@ export function createGround({ state: layerState, services, parts, source }) {
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
Cesium.Cartesian3.fromDegrees(
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
undefined,
record.position,
);
if (record.billboard) record.billboard.position = record.position;
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
+2 -8
View File
@@ -10,7 +10,7 @@ export function createHover({ state: layerState, services, parts, source }) {
* Throttled MOUSE_MOVE hover pass (owner round 2, item B): pointing at a
* camera icon that has no card summons its card immediately. This is
* EVENT-DRIVEN picking on a user gesture, not steady-state work — the
* ≥120 ms throttle caps it at ~8 scene.pick calls/s while the pointer is
* ≥120 ms throttle caps it at ~8 scene picks/s while the pointer is
* actually moving (a still pointer costs nothing), so it can never approach
* per-frame cost. Skipped while the camera is in motion, while ADJUST mode
* owns the pointer (gizmo drags), and while the layer is disabled.
@@ -29,13 +29,7 @@ export function createHover({ state: layerState, services, parts, source }) {
const now = Date.now();
if (now - layerState._hoverLastPickAt < HOVER_PICK_THROTTLE_MS) return;
layerState._hoverLastPickAt = now;
let picked = null;
try {
picked = layerState._viewer.scene.pick(position);
} catch {
picked = null;
}
const cameraId = parts.selection.extractPickedCameraId(picked);
const cameraId = parts.rendering.pickCameraIdAt(position);
if (cameraId && cameraId === layerState._hoverCardId) {
// Still on the hovered camera — keep the card alive.
cancelHoverRelease();
+5
View File
@@ -18,6 +18,7 @@ import { createHealth } from './health.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
import { createDrawSets } from './drawSets.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createCctvLayer({ services, source }) {
@@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) {
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.drawSets = createDrawSets(context);
parts.calibration = createCalibration(context);
parts.testing = createTesting(context);
parts.projection = createProjection(context);
@@ -73,6 +75,7 @@ export function createCctvLayer({ services, source }) {
deriveCalBadge: parts.calibration.deriveCalBadge,
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
activationProbeClampRange: parts.geometry.activationProbeClampRange,
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
_createCctvProjectionPlaneForTest:
parts.testing._createCctvProjectionPlaneForTest,
@@ -110,6 +113,8 @@ export function createCctvLayer({ services, source }) {
_extractPickedCameraIdForTest:
parts.testing._extractPickedCameraIdForTest,
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
_cctvIconsForTest: parts.testing._cctvIconsForTest,
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
focusCctvRecord: parts.navigation.focusCctvRecord,
maybeAutoHop: parts.navigation.maybeAutoHop,
openingCameraId: parts.navigation.openingCameraId,
+2 -2
View File
@@ -29,8 +29,8 @@ export function createIngestion({
layerState._tilesReadyReenqueued = true;
// Per-regime resolution (Task 5): only records unresolved for the
// CURRENT surface regime need the completion pass. On globe stacks
// projectionTilesReady() is false while a (hidden) Google tileset
// exists, so this latch effectively fires for the google-3d regime —
// projectionTilesReady() is false (only drawn photoreal tiles can be
// ready), so this latch fires for the google-3d regime alone —
// terrain-globe records resolve from the prior in their drain pass.
const unresolved = parts.geometryQueue
.geometryWorkingSet()
+113 -153
View File
@@ -1,11 +1,12 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
import { inputFor } from '../../input/dispatcher.js';
import {
GROUND_PRIOR_INIT_WAIT_MS,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
CALIBRATION_RANGE_FLOOR_M,
VIEW_MOTION_REFRESH_MS,
VIEW_MOTION_MIN_MOVE_FRACTION,
@@ -21,7 +22,6 @@ export function createLifecycle({
parts,
source,
}) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
services.picking;
@@ -46,12 +46,11 @@ export function createLifecycle({
/** Records the camera pose the last view pass ran at. */
function noteViewPose() {
const camera = layerState._viewer?.camera;
if (!camera?.positionWC) return;
const pose = findCamera(layerState._viewer)?.pose();
if (!pose) return;
layerState._viewPose = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction:
camera.directionWC && Cesium.Cartesian3.clone(camera.directionWC),
position: pose.position,
direction: pose.direction,
};
}
@@ -61,16 +60,14 @@ export function createLifecycle({
* would otherwise rerun the full pass on every tick.
*/
function viewPoseChanged() {
const camera = layerState._viewer?.camera;
const now = findCamera(layerState._viewer)?.pose();
const pose = layerState._viewPose;
if (!pose || !camera?.positionWC) return true;
const height = Math.max(1, camera.positionCartographic?.height ?? 0);
const moved = Cesium.Cartesian3.distance(camera.positionWC, pose.position);
if (!pose || !now) return true;
// An eye with no geographic position (the earth's centre) has no height.
const height = Math.max(1, Number.isFinite(now.height) ? now.height : 0);
const moved = distance(now.position, pose.position);
if (moved > height * VIEW_MOTION_MIN_MOVE_FRACTION) return true;
if (!pose.direction || !camera.directionWC) return false;
return (
Cesium.Cartesian3.dot(camera.directionWC, pose.direction) < MIN_TURN_COS
);
return dot(now.direction, pose.direction) < MIN_TURN_COS;
}
function viewMotionTick() {
@@ -99,6 +96,59 @@ export function createLifecycle({
layerState._viewMotionTimer = 0;
}
/**
* Listen for the camera's moves on the viewer's camera port: hover picking
* pauses while it moves, and the view pass reruns on an interval until the
* move ends, then once more. A re-init against a new viewer moves the
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
layerState._viewListenerCamera !== viewCamera
) {
layerState._horizonCullListener?.();
layerState._moveStartListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener = null;
layerState._cameraMoving = false;
}
layerState._viewListenerCamera = viewCamera;
if (!layerState._horizonCullListener && viewCamera) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = viewCamera.on('moveEnd', () => {
layerState._cameraMoving = false;
stopViewMotionTimer();
parts.navigation.reopenNearestCamera();
settleView();
});
}
if (!layerState._moveStartListener && viewCamera) {
// Item B: hover picking pauses while the camera is in motion. A long
// move (cockpit flight, a drag) never settles, so the view pass also
// reruns on an interval until it does.
layerState._moveStartListener = viewCamera.on('moveStart', () => {
layerState._cameraMoving = true;
// enable() starts it for a move already under way.
if (layerState._enabled) startViewMotionTimer();
});
}
}
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
layerState._moveStartListener = null;
layerState._cameraMoving = false;
layerState._viewListenerCamera = null;
stopViewMotionTimer();
}
/** Resets all module-scoped runtime state to initial values. */
function clearRuntimeState() {
@@ -107,6 +157,9 @@ export function createLifecycle({
// Idempotent — also covers a re-init without a prior destroy().
parts.cards.teardownAmbientCards();
parts.projection.clearProjectionOverlay();
// An activation probe still to answer lands on none of these records.
for (const record of layerState._records || [])
if (record) record.probeToken = (record.probeToken || 0) + 1;
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
@@ -123,9 +176,6 @@ export function createLifecycle({
layerState._lastError = null;
layerState._lastFocusStyleAt = 0;
layerState._activeFocusStyleCount = 0;
// FIX ①/③: the discovered tileset handle is scene-scoped — drop it so a fresh
// init re-discovers against the current scene primitives.
layerState._activeTileset = null;
// Task 5: the applied-regime tracker is record-set-scoped — a fresh init
// recomputes it against the then-current scene.
layerState._lastAppliedRegime = null;
@@ -133,9 +183,9 @@ export function createLifecycle({
const methods = {
/**
* Initializes the CCTV layer: loads camera sources, builds the catalog,
* restores calibration from localStorage, creates billboards, sets up click
* restores calibration from localStorage, creates camera icons, sets up click
* handling, and performs initial health sync. Coverage entities stay lazy.
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
* @param {object} viewer - The viewer.
*/
async init(viewer) {
layerState._sourceAbort?.abort();
@@ -156,16 +206,7 @@ export function createLifecycle({
layerState._lastViewContext = '';
layerState._calibrationById = parts.calibration.loadCalibrationStore();
layerState._billboards = new Cesium.BillboardCollection();
// Cesium switches a property's buffer-usage hint whenever it starts or
// stops changing from one frame to the next, and every switch rewrites
// the vertex data of every billboard. The view pass toggles `show` on a
// few icons of a large catalog at a time, so on a 33K catalog each pass
// cost two full rewrites. With the hint fixed, Cesium uploads only the
// icons that changed.
layerState._billboards.computeNewBuffersUsage = () => false;
layerState._viewer.scene.primitives.add(layerState._billboards);
registerSpriteCollection('cctv', layerState._billboards);
parts.rendering.createCameraIcons(layerState._viewer);
const sources = await parts.catalog.loadCameraSources();
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
@@ -233,32 +274,14 @@ export function createLifecycle({
? groundPrior.ellipsoid
: Number(camera.groundElevationM) || 0;
camera.absoluteHeightM = priorGround + camera.mountHeightM;
const position = Cesium.Cartesian3.fromDegrees(
const position = fromDegrees(
camera.lon,
camera.lat,
camera.absoluteHeightM,
);
const billboard = layerState._billboards.add({
id: camera.id,
image: CAMERA_ICON,
position,
color: IDLE_CAMERA_COLOR,
width: 24,
height: 24,
// Field-test fix (2026-07-06): always-on-top. The old finite value
// (1800 m) re-engaged the depth test at far zoom, where the COARSE
// far-LOD Google-3D mesh sits above the true ground and swallowed
// ground-anchored icons ("submerged" pills over SF). Far-side-of-globe
// icons are handled by refreshHorizonCulling() (the flights-layer
// EllipsoidalOccluder pattern), not by the depth test.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(350, 1.25, 4_000_000, 0.42),
});
const record = {
camera,
position,
billboard,
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
@@ -292,11 +315,12 @@ export function createLifecycle({
viewshedColors: viewshedColors(
cameraHue(hueIndexById.get(camera.id) ?? 0),
),
viewshedPrimitive: null,
viewshedVolume: null,
viewshedActiveTint: false,
};
layerState._records.push(record);
layerState._recordById.set(camera.id, record);
parts.rendering.addCameraIcon(record);
}
layerState._count = layerState._records.length;
@@ -331,57 +355,12 @@ export function createLifecycle({
}
// Field-test fix (2026-07-06): horizon-cull on camera settle (pairs with
// the billboards' always-on-top depth setting) + one initial pass so the
// the icons' always-on-top drawing) + one initial pass so the
// first paint is already culled.
// A re-init against a new viewer moves the move listeners to its camera.
if (
layerState._viewListenerCamera &&
layerState._viewListenerCamera !== layerState._viewer.camera
) {
const previous = layerState._viewListenerCamera;
if (layerState._horizonCullListener)
previous.moveEnd?.removeEventListener(
layerState._horizonCullListener,
);
if (layerState._moveStartListener)
previous.moveStart?.removeEventListener(
layerState._moveStartListener,
);
layerState._horizonCullListener = null;
layerState._moveStartListener = null;
layerState._cameraMoving = false;
}
layerState._viewListenerCamera = layerState._viewer.camera;
if (!layerState._horizonCullListener) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = () => {
layerState._cameraMoving = false;
stopViewMotionTimer();
parts.navigation.reopenNearestCamera();
settleView();
};
layerState._viewer.camera.moveEnd.addEventListener(
layerState._horizonCullListener,
);
}
if (!layerState._moveStartListener) {
// Item B: hover picking pauses while the camera is in motion. A long
// move (cockpit flight, a drag) never settles, so the view pass also
// reruns on an interval until it does.
layerState._moveStartListener = () => {
layerState._cameraMoving = true;
// enable() starts it for a move already under way.
if (layerState._enabled) startViewMotionTimer();
};
layerState._viewer.camera.moveStart.addEventListener(
layerState._moveStartListener,
);
}
attachViewListeners();
// A resize or rotation changes what is on screen without moving the
// camera.
const canvas = layerState._viewer.scene?.canvas;
const canvas = canvasOf(layerState._viewer);
if (layerState._viewResizeCanvas !== canvas) {
// A re-init against a new viewer observes its canvas instead.
layerState._viewResizeObserver?.disconnect();
@@ -406,15 +385,15 @@ export function createLifecycle({
}
parts.rendering.refreshHorizonCulling();
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
layerState._viewer.scene.canvas,
);
parts.selection.bindCctvWorldClickGesture(
layerState._clickHandler,
(click) => {
const input = inputFor(layerState._viewer);
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
if (!layerState._enabled) return;
const picked = layerState._viewer.scene.pick(click.position);
const cameraId = parts.selection.extractPickedCameraId(picked);
const picked = event.topHit;
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
if (cameraId) {
activateCctvCameraFromWorldClick(
cameraId,
@@ -431,11 +410,11 @@ export function createLifecycle({
// Item A (owner round 2): the scene pick found no camera — try the
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Cesium click positions
// its camera exactly like a click on the icon. Click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
click.position.x,
click.position.y,
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
@@ -454,14 +433,15 @@ export function createLifecycle({
parts.selection.deactivateActiveCamera();
}
},
{
// Item B: hover summons a card on a cardless camera icon. The gesture
// classifier owns MOUSE_MOVE too, so chain hover work through its seam
// instead of replacing the travel accumulator's handler.
onMouseMove: (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
},
);
// Item B: hover summons a card on a cardless camera icon.
const unsubscribeHover = input.onPointer('move', (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
);
layerState._clickSubscription = () => {
unsubscribeClick();
unsubscribeHover();
};
await parts.health.syncHealthState(true);
// Health ranks crowded cells: thin again now that it has arrived (a
@@ -472,7 +452,6 @@ export function createLifecycle({
}
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
console.log('[Data:CCTV] Initialized with', layerState._count, 'cameras');
},
@@ -491,7 +470,7 @@ export function createLifecycle({
)
services.credits?.showOsmCredit?.(layerState._viewer, 'cctv');
layerState._lastUpdate = Date.now();
// Pick-ownership (H2): camera billboards use the camera id directly;
// Pick-ownership (H2): camera icons use the camera id directly;
// coverage polyline entities use `cctv-<cameraId>-<role>` entity ids.
registerPickOwner('cctv', (pickedId) => {
if (layerState._recordById.has(pickedId)) return true;
@@ -535,7 +514,6 @@ export function createLifecycle({
parts.cards.startCardFrameLoop();
parts.cards.refreshAmbientCards();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
},
/** Disables the layer: hides entities, stops the projection loop and load queue. */
@@ -564,10 +542,10 @@ export function createLifecycle({
/**
* Tears down the layer: destroys click handler, projection loop, coverage
* entities, billboards, and clears all runtime state and subscribers.
* @param {Cesium.Viewer} [viewer] - Viewer instance (falls back to stored ref).
* entities, icons, and clears all runtime state and subscribers. It
* releases what init attached, whichever viewer it is handed.
*/
destroy(viewer) {
destroy() {
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._sourceAbort?.abort();
if (typeof document !== 'undefined')
@@ -583,23 +561,7 @@ export function createLifecycle({
);
layerState._mapStackListener = null;
}
const teardownViewer = viewer || layerState._viewer;
if (layerState._horizonCullListener && teardownViewer?.camera?.moveEnd) {
teardownViewer.camera.moveEnd.removeEventListener(
layerState._horizonCullListener,
);
layerState._horizonCullListener = null;
}
if (layerState._moveStartListener && teardownViewer?.camera?.moveStart) {
teardownViewer.camera.moveStart.removeEventListener(
layerState._moveStartListener,
);
layerState._moveStartListener = null;
}
// The move listeners are gone; nothing will report the end of a move.
layerState._cameraMoving = false;
layerState._viewListenerCamera = null;
stopViewMotionTimer();
detachViewListeners();
layerState._viewResizeObserver?.disconnect();
layerState._viewResizeObserver = null;
layerState._viewResizeCanvas = null;
@@ -609,21 +571,14 @@ export function createLifecycle({
}
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
if (teardownViewer?.scene?.screenSpaceCameraController) {
teardownViewer.scene.screenSpaceCameraController.enableInputs = true;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
parts.projection.stopProjectionLoop();
parts.geometryQueue.stopGeometryLoadQueue();
parts.cards.teardownAmbientCards();
parts.geometry.destroyCoverageEntities();
if (layerState._billboards && teardownViewer) {
teardownViewer.scene.primitives.remove(layerState._billboards);
layerState._billboards = null;
}
parts.rendering.destroyCameraIcons();
parts.drawSets.dispose();
clearRuntimeState();
layerState._viewer = null;
layerState._enabled = false;
@@ -636,5 +591,10 @@ export function createLifecycle({
},
};
return { clearRuntimeState, methods };
return {
clearRuntimeState,
attachViewListeners,
detachViewListeners,
methods,
};
}
+74
View File
@@ -0,0 +1,74 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
function viewerWithCamera() {
const camera = fakeCameraPort();
const viewer = {};
bindRenderer(viewer, { camera: camera.port });
return { viewer, camera };
}
function lifecycleFor(state) {
const passes = [];
const lifecycle = createLifecycle({
state,
services: {
sprites: {},
activation: {},
picking: {},
focus: {},
render: {},
},
parts: {
rendering: {
refreshHorizonCulling: () => {
passes.push('view');
return false;
},
},
geometryQueue: { enqueueViewGeometry() {} },
cards: { refreshAmbientCards() {} },
presentation: { notifyListeners() {} },
navigation: { reopenNearestCamera() {} },
},
});
return { lifecycle, passes };
}
test('the view listeners follow the camera port and let go on teardown', () => {
const first = viewerWithCamera();
const state = { _viewer: first.viewer, _enabled: false };
const { lifecycle, passes } = lifecycleFor(state);
const counts = (camera) => [
camera.listenerCount('moveStart'),
camera.listenerCount('moveEnd'),
];
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
first.camera.emit('moveStart');
assert.equal(state._cameraMoving, true, 'hover pauses while moving');
first.camera.emit('moveEnd');
assert.equal(state._cameraMoving, false);
assert.deepEqual(passes, ['view'], 'a settled move reruns the view pass');
// A re-init on the same viewer keeps its listeners.
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
// One on a new viewer moves them to its camera.
const second = viewerWithCamera();
state._viewer = second.viewer;
first.camera.emit('moveStart');
lifecycle.attachViewListeners();
assert.equal(state._cameraMoving, false, 'the old move is forgotten');
assert.deepEqual(counts(first.camera), [0, 0]);
assert.deepEqual(counts(second.camera), [1, 1]);
lifecycle.detachViewListeners();
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
+33 -63
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { cross, negate, toDegrees, toRadians } from '../../geo/vector.js';
import { fromAxes } from '../../geo/quaternion.js';
import { findCamera } from '../../render/rendererOf.js';
import { greatCircleKm } from '../../geoDistance.js';
import { staticFrameRefreshMs } from '../../data/cctvLod.js';
import { frameFetchDue, cardFetchPolicy } from '../../data/cctvCards.js';
@@ -14,7 +16,7 @@ export function createModel({ state: layerState, services, parts, source }) {
*/
function toRad(deg) {
return Cesium.Math.toRadians(deg);
return toRadians(deg);
}
/**
@@ -308,8 +310,8 @@ export function createModel({ state: layerState, services, parts, source }) {
const lon2 = lon1 + Math.atan2(y, x);
return {
lat: Cesium.Math.toDegrees(lat2),
lon: Cesium.Math.toDegrees(lon2),
lat: toDegrees(lat2),
lon: toDegrees(lon2),
};
}
@@ -345,12 +347,22 @@ export function createModel({ state: layerState, services, parts, source }) {
* @returns {string} Grid key in the form "zoomBucket:latGrid:lonGrid".
*/
/**
* The eye's pose from the camera port, or null when there is no camera or
* the eye has no geographic position (the earth's centre).
* @returns {object|null}
*/
function eyePose() {
const pose = findCamera(layerState._viewer)?.pose();
return Number.isFinite(pose?.lat) ? pose : null;
}
function currentViewContext() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto) return 'none';
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const alt = carto.height || 0;
const pose = eyePose();
if (!pose) return 'none';
const { lat, lon } = pose;
const alt = pose.height || 0;
const zoomBucket =
alt < 1500
? 'street'
@@ -371,43 +383,13 @@ export function createModel({ state: layerState, services, parts, source }) {
}
/**
* Reports whether the active Google Photorealistic 3D Tileset (if any) has
* finished loading the tiles in view. Shared mesh-floor sampling is gated on
* this so a one-shot cell never bakes in a miss from still-streaming tiles.
* Discovers + caches the tileset lazily from scene
* primitives (the CCTV module holds only a `_viewer` reference). When no
* tileset is present (OSM fallback) this returns true so ground sampling is
* not permanently blocked.
*
* Task 5 (review correction, spec §2): a HIDDEN tileset (`show === false`,
* i.e. a globe stack is active) must NOT report ready — Cesium 1.138's
* the shared sampler can only inspect *visible* 3D tilesets, so a sample taken
* against the hidden Google tileset would silently miss.
*
* @returns {boolean} True when tiles are loaded AND visible (or no tileset
* exists to wait on).
* Whether the photoreal tiles in view have finished loading; the rendering
* part, which reads the scene, answers.
* @returns {boolean}
*/
function projectionTilesReady() {
if (
!layerState._activeTileset ||
layerState._activeTileset.isDestroyed?.()
) {
layerState._activeTileset = null;
const primitives = layerState._viewer?.scene?.primitives;
if (primitives && typeof primitives.get === 'function') {
for (let i = 0; i < primitives.length; i++) {
const p = primitives.get(i);
if (p instanceof Cesium.Cesium3DTileset && !p.isDestroyed?.()) {
layerState._activeTileset = p;
break;
}
}
}
}
if (!layerState._activeTileset) return true;
if (layerState._activeTileset.show === false) return false;
return layerState._activeTileset.tilesLoaded === true;
return parts.rendering.projectionTilesReady();
}
/**
@@ -418,30 +400,17 @@ export function createModel({ state: layerState, services, parts, source }) {
* frame-up, so the 16:9 texture maps upright and unmirrored. Static geometry —
* computed only on slider/save/activation, never per frame (§2b).
* @param {Object} camera - Camera pose.
* @param {Cesium.Cartesian3} capCenterPos - Plane center in ECEF.
* @returns {Cesium.Quaternion}
* @param {{x: number, y: number, z: number}} capCenterPos - Plane center in ECEF.
* @returns {{x: number, y: number, z: number, w: number}} The quaternion.
*/
function planeOrientationFor(camera, capCenterPos) {
const frame = parts.geometry.frustumFrameEcef(camera, capCenterPos);
const right = Cesium.Cartesian3.cross(
frame.dir,
frame.up,
new Cesium.Cartesian3(),
);
const normal = Cesium.Cartesian3.negate(frame.dir, new Cesium.Cartesian3());
const m = new Cesium.Matrix3(
right.x,
frame.up.x,
normal.x,
right.y,
frame.up.y,
normal.y,
right.z,
frame.up.z,
normal.z,
);
return Cesium.Quaternion.fromRotationMatrix(m);
return fromAxes({
x: cross(frame.dir, frame.up),
y: frame.up,
z: negate(frame.dir),
});
}
/**
@@ -564,6 +533,7 @@ export function createModel({ state: layerState, services, parts, source }) {
return cameraId !== activeCameraId || record?.activationDone !== true;
}
return {
eyePose,
toRad,
normalizeHeading,
clamp,
+17 -20
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -8,15 +9,14 @@ export function createNavigation({
source,
}) {
/**
* Finds the camera closest to the Cesium viewer's current position.
* Finds the camera closest to the viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
*/
function nearestCameraIdToViewer() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto || !layerState._records.length) return null;
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const pose = parts.model.eyePose();
if (!pose || !layerState._records.length) return null;
const { lat, lon } = pose;
let best = null;
for (const record of layerState._records) {
@@ -64,9 +64,9 @@ export function createNavigation({
}
/**
* Flies the Cesium viewer camera to frame the specified CCTV camera,
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
* @param {Cesium.Viewer|null} viewer Cesium viewer that owns the camera.
* @param {object|null} viewer The viewer that owns the camera.
* @param {Object|null} record CCTV camera runtime record.
* @param {number} [duration=2.2] - Flight duration in seconds.
* @returns {'focused'|'no-active-camera'|'tracking-holds-view'|'cockpit-active'} Focus result.
@@ -81,7 +81,7 @@ export function createNavigation({
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (viewer.trackedEntity) {
if (isFollowing(viewer)) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -89,19 +89,16 @@ export function createNavigation({
}
const { camera } = record;
const range = Math.max(280, camera.rangeM * 1.18);
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
record.position,
Math.max(40, camera.rangeM * 0.36),
),
cameraOf(viewer).flyToBounds(
{ center: record.position, radius: Math.max(40, camera.rangeM * 0.36) },
{
offset: new Cesium.HeadingPitchRange(
parts.model.toRad(camera.headingDeg),
parts.model.toRad(-22),
offset: {
heading: parts.model.toRad(camera.headingDeg),
pitch: parts.model.toRad(-22),
range,
),
duration: Math.max(0.2, duration || 0),
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
},
durationS: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
);
return CCTV_FOCUS_RESULT.FOCUSED;
+19 -26
View File
@@ -1,7 +1,7 @@
export { ACTIVE_FRAME_REFRESH_MS } from './sourcePolicy.js';
import * as Cesium from 'cesium';
import { CCTV_CARD_FETCH_BURST_SPACING_MS } from '../../data/cctvCards.js';
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { hexColor } from '../../render/color.js';
// ---------------------------------------------------------------------------
// API endpoints
@@ -179,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
heightM: 0,
});
/** Base64-encoded SVG camera icon for billboard rendering. */
/**
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
* 2× display draws it at 60 device px, and it stays sharp there.
*/
export const CAMERA_ICON = (() => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/>
@@ -434,44 +438,33 @@ export const CAMERA_SEEDS = [
];
// ---------------------------------------------------------------------------
// Visual style constants
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.88);
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
export const ACTIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#ffd97a').withAlpha(0.95);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
export const LIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#b48cff').withAlpha(0.88);
export const LIVE_CAMERA_COLOR = hexColor('#b48cff', 0.88);
export const IDLE_COVERAGE_COLOR =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.24);
export const IDLE_COVERAGE_COLOR = hexColor('#2fe0ff', 0.24);
export const IDLE_COVERAGE_CENTER_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.2);
export const IDLE_COVERAGE_CENTER_MUTED = hexColor('#2fe0ff', 0.2);
export const IDLE_COVERAGE_EDGE_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.18);
export const IDLE_COVERAGE_EDGE_MUTED = hexColor('#2fe0ff', 0.18);
export const ACTIVE_COVERAGE_EDGE =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.58);
export const ACTIVE_COVERAGE_EDGE = hexColor('#8dff87', 0.58);
export const ACTIVE_COVERAGE_CENTER =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.82);
export const ACTIVE_COVERAGE_CENTER = hexColor('#d7ff8d', 0.82);
// H6: dimmer depth-fail materials let the active frustum wireframe read
// through buildings while in monitor fallback mode.
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.18);
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = hexColor('#8dff87', 0.18);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.26);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = hexColor('#d7ff8d', 0.26);
export const PLANE_OUTLINE_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.55);
export const PLANE_OUTLINE_COLOR = hexColor('#6be8ff', 0.55);
/**
* Card budget while the staggered geometry drain is running — the raised
+90 -63
View File
@@ -1,5 +1,4 @@
import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
@@ -8,6 +7,25 @@ import {
PROJECTION_CANVAS_HEIGHT,
} from './policy.js';
/** The monitor plane's alpha over its frame, as its image material had it. */
const PLANE_ALPHA = 0.95;
/** A plain white image, for a plane with no media (tests). */
const WHITE_IMAGE =
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">' +
'<rect width="1" height="1" fill="#fff"/></svg>',
);
/** Copy a position's coordinates into `out`. */
function copyPosition(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
export function createProjection({
state: layerState,
services,
@@ -18,7 +36,7 @@ export function createProjection({
/**
* Build the protected label associated with one active monitor plane.
* @param {{cameraId: string, name: string, position: Cesium.Cartesian3|Function}} input
* @param {{cameraId: string, name: string, position: object|Function}} input
* @returns {Object} Shared-host presentation entry.
*/
@@ -46,7 +64,7 @@ export function createProjection({
}
/**
* Re-derives the monitor plane entity's placement (position, orientation,
* Re-derives the monitor plane's placement (position, orientation,
* dimensions) + label from the record's current frustum geometry, so the plane
* always caps the wireframe exactly (corner rays terminate on its corners).
* No-op when the record has no plane runtime (idle neighbors have no plane).
@@ -55,7 +73,8 @@ export function createProjection({
function updatePlanePlacement(record) {
const runtime = record?.projection;
if (!runtime?.planeEntity) return;
const plane = runtime?.plane;
if (!plane) return;
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -64,21 +83,33 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeEntity.position = positions.capCenter;
runtime.planeEntity.orientation = parts.model.planeOrientationFor(
record.camera,
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
placePlane(plane, record.camera, geometry, positions);
if (runtime.labelPosition)
copyPosition(positions.label, runtime.labelPosition);
parts.drawSets.writePlane(plane);
}
/** Pose a plane handle on the frustum's far cap. */
function placePlane(plane, camera, geometry, positions) {
plane.center = positions.capCenter;
plane.orientation = parts.model.planeOrientationFor(
camera,
positions.capCenter,
);
if (runtime.planeEntity.plane) {
runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
);
}
if (runtime.labelPosition) {
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
}
plane.size = [geometry.halfW * 2, geometry.halfH * 2];
}
/**
* Give the monitor plane another image: a canvas, or the video element.
* @param {Object} runtime - Projection runtime.
* @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source
*/
function setPlaneSource(runtime, source) {
runtime.planeSource = source;
if (!runtime.plane) return;
runtime.plane.source = source;
parts.drawSets.writePlane(runtime.plane);
}
/**
@@ -102,7 +133,10 @@ export function createProjection({
function setPlaneVisible(runtime, visible) {
if (!runtime) return;
if (runtime.planeEntity) runtime.planeEntity.show = !!visible;
if (runtime.plane && runtime.plane.show !== !!visible) {
runtime.plane.show = !!visible;
parts.drawSets.writePlane(runtime.plane);
}
if (visible && runtime.overlayEntry && runtime.cameraId) {
if (layerState._projectionOverlayOwnerId !== runtime.cameraId) {
layerState._cctvOverlayHost.setEntries(
@@ -121,38 +155,34 @@ export function createProjection({
}
}
/** Create the native monitor plane plus its cached host-label presentation. */
/** A plain white plane image, for a plane with no media (tests). */
function plainPlaneSource() {
return { image: WHITE_IMAGE };
}
/** Create the monitor plane plus its cached host-label presentation. */
function createProjectionPlane(record, runtime, geometry, positions) {
runtime.labelPosition ||= new Cesium.Cartesian3();
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
runtime.labelPosition ||= { x: 0, y: 0, z: 0 };
copyPosition(positions.label, runtime.labelPosition);
runtime.cameraId = String(record.camera.id);
runtime.overlayEntry = createCctvProjectionOverlayEntry({
cameraId: runtime.cameraId,
name: record.camera.name,
position: () => runtime.labelPosition,
});
runtime.planeEntity = layerState._viewer.entities.add({
const plane = {
id: `cctv-${record.camera.id}-plane`,
properties: { cctvCameraId: record.camera.id },
cameraId: record.camera.id,
source: runtime.planeSource || plainPlaneSource(),
alpha: PLANE_ALPHA,
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
show: false,
position: positions.capCenter,
orientation: parts.model.planeOrientationFor(
record.camera,
positions.capCenter,
),
plane: {
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
dimensions: new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
),
material: runtime.planeMaterial,
outline: true,
outlineColor: PLANE_OUTLINE_COLOR,
},
});
return runtime.planeEntity;
};
placePlane(plane, record.camera, geometry, positions);
runtime.plane = plane;
parts.drawSets.writePlane(plane);
return plane;
}
/**
@@ -187,11 +217,11 @@ export function createProjection({
ctx,
image: null,
video: null,
planeEntity: null,
plane: null,
cameraId: String(record.camera.id),
labelPosition: new Cesium.Cartesian3(),
labelPosition: { x: 0, y: 0, z: 0 },
overlayEntry: null,
planeMaterial: null,
planeSource: { canvas },
buffers: null,
bufferIndex: 0,
lastTextureSwapAt: 0,
@@ -222,16 +252,17 @@ export function createProjection({
video.playsInline = true;
video.crossOrigin = 'anonymous';
video.preload = 'auto';
// Cesium sizes the video texture from the element's width/height
// attributes at first upload. Set them from the real stream dimensions
// and rebind on any resolution change (camera switch, adaptive source).
// The plane shows the video once it knows its size (the element's
// width/height follow the real stream dimensions); the renderer reads
// it at a new size on any later resolution change (camera switch,
// adaptive source).
const bindVideoTexture = () => {
if (runtime.video !== video || !runtime.planeMaterial) return;
if (runtime.video !== video || runtime.disposed) return;
if (!(video.videoWidth > 0 && video.videoHeight > 0)) return;
video.width = video.videoWidth;
video.height = video.videoHeight;
runtime.planeMaterial.image = runtime.canvas;
runtime.planeMaterial.image = video;
if (runtime.planeSource?.video !== video)
setPlaneSource(runtime, { video });
};
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
@@ -256,7 +287,7 @@ export function createProjection({
runtime.imageLoading = false;
runtime.imageReady = false;
};
runtime.planeMaterial.image = runtime.canvas;
setPlaneSource(runtime, { canvas: runtime.canvas });
parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners();
},
@@ -279,9 +310,8 @@ export function createProjection({
}
// Monitor plane = the frustum's far cap: video feeds bind the video element
// directly (Cesium updates video-backed entity materials per frame); image
// feeds start on the placeholder canvas and switch to double-buffer swaps
// at <=1Hz.
// directly (the renderer reads it every frame); image feeds start on the
// placeholder canvas and switch to double-buffer swaps at <=1Hz.
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -290,12 +320,7 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
image: canvas,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
createProjectionPlane(record, runtime, geometry, positions);
return runtime;
@@ -340,15 +365,15 @@ export function createProjection({
runtime.video.removeAttribute('src');
runtime.video.load();
}
if (runtime.planeEntity && layerState._viewer) {
layerState._viewer.entities.remove(runtime.planeEntity);
runtime.planeEntity = null;
if (runtime.plane) {
parts.drawSets.removePlane(runtime.plane);
runtime.plane = null;
}
if (layerState._projectionOverlayOwnerId === runtime.cameraId)
clearProjectionOverlay();
runtime.overlayEntry = null;
runtime.labelPosition = null;
runtime.planeMaterial = null;
runtime.planeSource = null;
}
function startProjectionLoop() {
@@ -430,6 +455,8 @@ export function createProjection({
updatePlanePlacement,
clearProjectionOverlay,
setPlaneVisible,
setPlaneSource,
plainPlaneSource,
createProjectionPlane,
createProjectionRuntime,
ensureProjectionRuntime,
+592 -139
View File
@@ -1,7 +1,7 @@
import * as Cesium from 'cesium';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
ACTIVE_COVERAGE_CENTER,
@@ -10,10 +10,88 @@ import {
ACTIVE_COVERAGE_EDGE,
IDLE_COVERAGE_EDGE_MUTED,
ACTIVE_COVERAGE_EDGE_DEPTHFAIL,
IDLE_COVERAGE_COLOR,
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
import {
canvasOf,
drawOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js';
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** Icon sets made so far, by every layer: set ids unique to each. */
let iconSets = 0;
/** A point's coordinates, as an item keeps them. */
const copyPoint = (p) => ({ x: p.x, y: p.y, z: p.z });
/** Whether two points are the same, coordinate for coordinate. */
const samePoint = (a, b) =>
!!a && !!b && a.x === b.x && a.y === b.y && a.z === b.z;
/** Degrees to radians. */
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25×
* near scale on a 2× display draws it at 60 device px, so it is rasterised
* past the drawn size to stay sharp there.
*/
const CAMERA_ICON_PX = 24;
const CAMERA_SCALE_BY_DISTANCE = Object.freeze({
near: 350,
nearValue: 1.25,
far: 4_000_000,
farValue: 0.42,
});
/**
* The translucent frustum volume of one camera, as a mesh item: the same 5
* points the wireframe draws (frustumVolumeGeometryData), in the
* east-north-up frame at the mount. Unlit flat colour, both faces visible
* (the viewer is routinely inside or behind a cone); its set is never
* pickable (clicks fall through to the icon/wireframe/plane, whose pick
* semantics are established).
* @param {string} id - Item id.
* @param {Object} positions - frustumCartesians shape.
* @param {number[]} color - Per-camera fill colour (already alpha'd).
*/
function frustumVolumeItem(id, positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const origin = positions.mount;
const frame = eastNorthUp(origin);
const local = new Float32Array(flat.length);
for (let i = 0; i < flat.length; i += 3) {
const dx = flat[i] - origin.x;
const dy = flat[i + 1] - origin.y;
const dz = flat[i + 2] - origin.z;
local[i] = dx * frame.x.x + dy * frame.x.y + dz * frame.x.z;
local[i + 1] = dx * frame.y.x + dy * frame.y.y + dz * frame.y.z;
local[i + 2] = dx * frame.z.x + dy * frame.z.y + dz * frame.z.z;
}
return {
id,
origin: { x: origin.x, y: origin.y, z: origin.z },
positions: local,
indices,
color,
flat: true,
};
}
/** FNV-1a over a camera id: a stable, well-spread order for crowded cells. */
function idHash(id) {
@@ -31,6 +109,102 @@ export function createRendering({
parts,
source,
}) {
/**
* The catalog's camera icons: an icon draw set, and the book the layer
* reads them back from (`render/motion/iconBook.js`), each item a camera
* by its id. Cameras hold still, so each item's motion is a hold at its
* mount. Items draw depth-test-free (field-test fix 2026-07-06: the old
* finite depth-test distance re-engaged at far zoom, where the COARSE
* far-LOD Google-3D mesh sits above the true ground and swallowed
* ground-anchored icons); the set culls the far side of the globe and
* refreshHorizonCulling thins the rest.
* The set stacks under the other sprite layers (`spriteDrawOrder`).
* @param {object} viewer The layer's viewer.
* @returns {string} The icon set's id.
*/
function createCameraIcons(viewer) {
// A re-init against a new viewer replaces the icons; the old ones go.
destroyCameraIcons();
const set = drawOf(viewer).icons({
id: `cctv:${++iconSets}:icons`,
horizonCull: true,
// Hidden until enable() has thinned and culled them
// (refreshHorizonCulling, then refreshCoverageStyles shows the set):
// shown from the start, every camera in the catalogue drew while the
// layer waited on its health check.
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
return set.id;
}
/** Let the icon draw set go, whichever viewer the caller tears down. */
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
function cameraIconItem(record) {
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
motion: { kind: 'hold' },
meta: { layer: 'cctv', id },
show: true,
};
}
/**
* A camera's icon item with `fields` changed, to write with the pass's
* others in one go (`writeCameraIcons`); null when none of them changes
* or it has no icon, so a large catalog writes only what changed.
*/
function patchedCameraIcon(id, fields) {
const item = layerState._icons?.item(id);
if (!item) return null;
for (const key in fields)
if (item[key] !== fields[key]) return { ...item, ...fields };
return null;
}
/** Write a pass's changed icons, in one write to the set. */
function writeCameraIcons(items) {
if (items.length) layerState._icons?.putMany(items);
}
/** Add a camera record's icon, idle and shown, once it has a position. */
function addCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
icons.put(cameraIconItem(record));
}
/** Hold a camera's icon at its record's current position. */
function moveCameraIcon(record) {
const icons = layerState._icons;
if (!icons || !record.position) return;
const item = icons.item(record.camera.id);
// A camera whose icon waited for a position is drawn now.
if (!item) {
icons.put(cameraIconItem(record));
return;
}
if (samePoint(item.pos, record.position)) return;
icons.put({ ...item, pos: copyPoint(record.position) });
}
/** Icon color: active wins, then live-capable video feeds, then idle stills. */
function cameraColorFor(record) {
if (record.camera.id === layerState._activeCameraId)
@@ -64,40 +238,36 @@ export function createRendering({
return;
if (nowMs - layerState._lastFocusStyleAt < 80) return;
layerState._lastFocusStyleAt = nowMs;
const scene = layerState._viewer.scene;
const camera = layerState._viewer.camera;
const query = findQuery(layerState._viewer);
const eye = findCamera(layerState._viewer)?.pose()?.position;
if (!query || !eye) return;
const result = applyCctvFocusDeemphasis({
records: layerState._records,
target,
previousActiveCount: layerState._activeFocusStyleCount,
nowMs,
screenPositionFor: (position) =>
Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
layerState._scratchFocusScreen,
),
cameraDistanceFor: (position) =>
Cesium.Cartesian3.distance(camera.positionWC, position),
baseColorFor: cameraColorFor,
screenPositionFor: (position) => query.project(position),
cameraDistanceFor: (position) => distance(eye, position),
});
layerState._activeFocusStyleCount = result.activeCount;
}
/**
* Apply the gated CCTV focus pass through the production color path.
* Apply the gated CCTV focus pass through the set's focus column (the shader
* multiplies it into the base color's alpha).
* @param {object} input
* @param {object} [input.icons] The icon book (defaults to the layer's).
* @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}}
*/
function applyCctvFocusDeemphasis({
records,
icons = layerState._icons,
target,
previousActiveCount = 0,
nowMs,
screenPositionFor,
cameraDistanceFor,
baseColorFor,
params,
}) {
if (!focusPassIsNeeded(target, previousActiveCount)) {
@@ -107,30 +277,30 @@ export function createRendering({
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const bb = record.billboard;
if (!bb) continue;
const position = bb.position;
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(bb, {
const focus = advanceSpriteFocus(item.meta, {
// Keep hidden icons in the state/release pass so the active count cannot
// drop while a stale dim alpha remains waiting to reappear.
screenPosition:
bb.show === false || !position ? null : screenPositionFor(position),
item.show === false || !position ? null : screenPositionFor(position),
cameraDistance: position ? cameraDistanceFor(position) : Number.NaN,
nowMs,
target,
params,
spriteHalfWidthPx: (bb.width || 24) * (bb.scale || 1) * 0.5,
spriteHalfHeightPx: (bb.height || 24) * (bb.scale || 1) * 0.5,
spriteHalfWidthPx: item.size[0] * scale * 0.5,
spriteHalfHeightPx: item.size[1] * scale * 0.5,
});
transitioning ||= focus.transitioning;
if (focus.active) activeCount += 1;
const base = baseColorFor(record);
const alpha = base.alpha * focus.factor;
if (focusAlphaNeedsWrite(bb.color?.alpha, alpha, params)) {
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
bb.color = base.withAlpha(alpha);
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
writes += 1;
}
}
@@ -138,18 +308,17 @@ export function createRendering({
}
/**
* Updates visual styles (colors, widths, visibility) for all camera billboards,
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera billboards, mirroring the
* flights layer's EllipsoidalOccluder pass. With the Cesium globe hidden
* (Google-3D regime) nothing writes far-side depth, and the billboards are now
* always-on-top (`disableDepthTestDistance: INFINITY` — the far-zoom submerge
* fix), so without this pass London's cluster would shine through the planet
* from a US viewpoint.
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
@@ -168,38 +337,37 @@ export function createRendering({
if (
!layerState._enabled ||
!layerState._viewer ||
layerState._viewer.isDestroyed() ||
!layerState._records.length
)
return false;
const { camera, scene } = layerState._viewer;
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
const pose = findCamera(layerState._viewer)?.pose();
if (!pose?.position) return false;
const canvas = canvasOf(layerState._viewer);
const width = canvas?.clientWidth || canvas?.width || 0;
const height = canvas?.clientHeight || canvas?.height || 0;
const minX = -width * VIEW_ICON_MARGIN;
const maxX = width * (1 + VIEW_ICON_MARGIN);
const minY = -height * VIEW_ICON_MARGIN;
const maxY = height * (1 + VIEW_ICON_MARGIN);
// Ground metres one pixel covers per metre of distance from the viewer.
const fovy = Number.isFinite(camera.frustum?.fovy)
? camera.frustum.fovy
: Math.PI / 3;
const fovy = Number.isFinite(pose.fovy) ? pose.fovy : Math.PI / 3;
const metresPerPixelPerMetre =
(2 * Math.tan(fovy / 2)) / Math.max(1, height);
const viewer = camera.positionWC;
// The horizon test of Cesium's EllipsoidalOccluder, inlined: this loop
const viewer = pose.position;
// The renderer's horizon test (geo/horizon.js), inlined: this loop
// visits every camera in the catalog.
const inverseRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
const inverseRadii = WGS84.oneOverRadii;
const cx = viewer.x * inverseRadii.x;
const cy = viewer.y * inverseRadii.y;
const cz = viewer.z * inverseRadii.z;
const limbSquared = cx * cx + cy * cy + cz * cz - 1;
const activeId = layerState._activeCameraId;
const project = screenProjector(scene, camera, width, height);
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const cells = new Map();
for (const record of layerState._records) {
const position = record.billboard?.position;
const position = record.position;
if (!position) continue;
const vx = position.x * inverseRadii.x - cx;
const vy = position.y * inverseRadii.y - cy;
@@ -240,12 +408,14 @@ export function createRendering({
record.viewPass = pass;
shown.push(record);
}
const writes = [];
for (const record of layerState._records) {
const bb = record.billboard;
if (!bb) continue;
const visible = record.viewPass === pass;
if (bb.show !== visible) bb.show = visible;
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
if (item) writes.push(item);
}
writeCameraIcons(writes);
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
@@ -255,37 +425,21 @@ export function createRendering({
}
/**
* Canvas coordinates for world positions. In 3D the pass multiplies by one
* view-projection matrix per call instead of Cesium's per-point
* cartesianToCanvasCoordinates, which dominated the pass on a large
* catalog; other scene modes keep Cesium's projection.
* @returns {(position: Cesium.Cartesian3) => ({x: number, y: number}|null)}
* Canvas coordinates for world positions, from the eye's pose by the
* renderer's perspective projection (geo/frustum.js): one pose read per
* pass rather than a renderer projection per point, which dominated the
* pass on a large catalog. Null behind the eye or before its near plane.
* A pose with no perspective field of view is projected by the renderer,
* point by point.
* @returns {(position: {x: number, y: number, z: number}) =>
* ({x: number, y: number}|null)}
*/
function screenProjector(scene, camera, width, height) {
const out = layerState._scratchViewScreen;
const projection = camera.frustum?.projectionMatrix;
if (
scene.mode !== Cesium.SceneMode.SCENE3D ||
!projection ||
!camera.viewMatrix
)
return (position) => scene.cartesianToCanvasCoordinates(position, out);
const m = Cesium.Matrix4.multiply(
projection,
camera.viewMatrix,
layerState._scratchViewProjection,
);
return (p) => {
const w = m[3] * p.x + m[7] * p.y + m[11] * p.z + m[15];
const z = m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14];
// Behind the eye or before the near plane: Cesium does not draw it.
if (!(w > 0) || z < 0) return null;
out.x =
((m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12]) / w + 1) * 0.5 * width;
out.y =
(1 - (m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13]) / w) * 0.5 * height;
return out;
};
function screenProjector(pose, width, height) {
if (Number.isFinite(pose.fovy) && Number.isFinite(pose.aspectRatio)) {
return poseProjector(pose, width, height, layerState._scratchViewScreen);
}
const query = findQuery(layerState._viewer);
return (position) => query?.project(position) ?? null;
}
/**
@@ -307,7 +461,7 @@ export function createRendering({
return record.viewCellKey;
const latStep = 2 ** level / 111_320;
const row = Math.floor(lat / latStep);
const rowLat = Cesium.Math.toRadians((row + 0.5) * latStep);
const rowLat = toRadians((row + 0.5) * latStep);
const lonStep = latStep / Math.max(0.05, Math.cos(rowLat));
record.viewCellLevel = level;
record.viewCellLat = lat;
@@ -349,23 +503,29 @@ export function createRendering({
for (const record of Array.isArray(records) ? records : []) {
if (record) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
if (record.camera?.id === activeCameraId) record.activationDone = false;
}
for (const entity of record?.coverageEntities || []) entity.show = false;
if (record?.viewshedPrimitive) destroyVolume?.(record);
if (record?.projection?.planeEntity)
record.projection.planeEntity.show = false;
parts.drawSets.writeLines(record?.coverageEntities);
if (record?.viewshedVolume) destroyVolume?.(record);
const plane = record?.projection?.plane;
if (plane?.show) {
plane.show = false;
parts.drawSets.writePlane(plane);
}
}
}
function hideCctvVisuals() {
hideCctvRecordVisuals(
layerState._records,
parts.geometry.destroyViewshedVolume,
destroyViewshedVolume,
layerState._activeCameraId,
);
parts.projection.clearProjectionOverlay();
if (layerState._billboards) layerState._billboards.show = false;
if (layerState._icons) layerState._icons.show = false;
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -387,19 +547,16 @@ export function createRendering({
coverageVisible,
);
}
// Only changed icons are written, in one go after the pass, so across a
// large catalog only the changed rows upload.
const restyled = [];
for (const record of layerState._records) {
const isActive = record.camera.id === activeId;
if (record.billboard) {
// Unchanged writes still dirty the collection, which then rewrites
// every icon's vertices: across a large catalog, write only changes.
const color = cameraColorFor(record);
if (!Cesium.Color.equals(record.billboard.color, color))
record.billboard.color = color;
const scale = isActive ? 1.25 : 1.0;
if (record.billboard.scale !== scale) record.billboard.scale = scale;
// disableDepthTestDistance stays POSITIVE_INFINITY for every billboard
// (set at creation) — see the field-test far-zoom submerge fix there.
}
const icon = patchedCameraIcon(record.camera.id, {
color: cameraColorFor(record),
scale: isActive ? 1.25 : 1.0,
});
if (icon) restyled.push(icon);
if (
layerState._enabled &&
@@ -426,10 +583,6 @@ export function createRendering({
// rather than rendering identically to a surveyed one (#639). Colors,
// widths, and the active/idle emphasis are unchanged.
const bearingEstimated = isHeadingEstimated(record.camera);
const lineMaterial = (color) =>
bearingEstimated
? new Cesium.PolylineDashMaterialProperty({ color })
: color;
for (const entity of record.coverageEntities || []) {
// The frustum wireframe is part of the projection representation —
// force it on for the active camera and let it read through geometry
@@ -438,45 +591,43 @@ export function createRendering({
layerState._enabled &&
((coverageOn && inVisibleSet) || planeShowing)
);
if (!entity.polyline) continue;
if (!entity.role) continue;
// Viewshed mode swaps the cyan/green scheme for the camera's own hue so
// adjacent cones read as distinct coverage claims (design §3b); the
// active camera keeps its width/alpha emphasis in both schemes.
const hue = viewshedOn ? record.viewshedColors : null;
if (entity._coverageRole === 'cap') {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED,
);
entity.polyline.width = isActive ? 2.2 : 1.0;
entity.polyline.depthFailMaterial = planeShowing
const hue = viewshedOn ? record.viewshedColors || null : null;
entity.dashed = bearingEstimated;
if (entity.role === 'cap') {
entity.color = hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED;
entity.widthPx = isActive ? 2.2 : 1.0;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.26)
? withAlpha(hue.line, 0.26)
: ACTIVE_COVERAGE_CENTER_DEPTHFAIL
: undefined;
: null;
} else {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line.withAlpha(0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED,
);
entity.polyline.width = isActive ? 1.8 : 0.9;
entity.polyline.depthFailMaterial = planeShowing
entity.color = hue
? isActive
? hue.lineActive
: withAlpha(hue.line, 0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED;
entity.widthPx = isActive ? 1.8 : 0.9;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.18)
? withAlpha(hue.line, 0.18)
: ACTIVE_COVERAGE_EDGE_DEPTHFAIL
: undefined;
: null;
}
}
parts.drawSets.writeLines(record.coverageEntities);
// Viewshed volume lifecycle: exists iff enabled + viewshed mode + in the
// visible set. Rebuild on active-tint flips (rare); otherwise leave the
@@ -488,14 +639,11 @@ export function createRendering({
record.frustumPositions
);
if (wantVolume) {
if (
!record.viewshedPrimitive ||
record.viewshedActiveTint !== isActive
) {
parts.geometry.rebuildViewshedVolume(record, isActive);
if (!record.viewshedVolume || record.viewshedActiveTint !== isActive) {
rebuildViewshedVolume(record, isActive);
}
} else if (record.viewshedPrimitive) {
parts.geometry.destroyViewshedVolume(record);
} else if (record.viewshedVolume) {
destroyViewshedVolume(record);
}
if (record.projection) {
@@ -503,11 +651,316 @@ export function createRendering({
}
}
if (layerState._billboards)
layerState._billboards.show = !!layerState._enabled;
writeCameraIcons(restyled);
if (layerState._icons) layerState._icons.show = !!layerState._enabled;
parts.projection.pauseInactiveProjectionFeeds(activeId);
}
/**
* Reports whether the photorealistic tiles the scene draws have finished
* loading the tiles in view. Shared mesh-floor sampling is gated on this so
* a one-shot cell never bakes in a miss from still-streaming tiles.
*
* Only the photoreal regime (the globe hidden under the tiles) can be
* ready: on a globe stack the tiles are hidden, and the shared sampler can
* only inspect tiles that are drawn, so a sample taken against them would
* silently miss (Task 5, spec §2). The tiles' readiness is the globe
* port's (`isSettled('tiles')`), true as well when no tiles are drawn.
*
* @returns {boolean} True when the regime is photoreal and its tiles in
* view have loaded.
*/
function projectionTilesReady() {
const globe = layerState._viewer ? findGlobe(layerState._viewer) : null;
if (!globe || globe.isGlobeVisible?.() !== false) return false;
return globe.isSettled('tiles') === true;
}
/**
* Converts a computeFrustumGeometry result into the ECEF positions the
* drawn items consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and items must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: object, capCenter: object, tl: object, tr: object,
* br: object, bl: object, label: object }} ECEF points with x, y and z.
*/
function frustumCartesians(geometry) {
const at = (p) => fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
tl: at(geometry.corners.tl),
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
),
};
}
/**
* Creates the five lines that visualize a camera's pitched frustum: 4
* corner rays (mount → far-plane corner) + the closed far-plane rectangle,
* as line handles the layer restyles and then writes to its coverage set.
* Item ids stay in the `cctv-<id>-<role>` scheme (pick-owner regex depends
* on it): ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Object[]} Array of five coverage line handles.
*/
function buildCoverageEntities(record) {
const { camera } = record;
// Prefer the record's already-refined geometry. Lazy creation commonly
// happens after the staggered ground pass; recomputing from the catalog
// prior here would regress the camera to its pre-sampled datum.
let geometry = record.frustumGeometry;
let positions = record.frustumPositions;
if (!geometry || !positions) {
geometry = parts.geometry.computeFrustumGeometry(
camera,
parts.ground.groundPriorAltFor(record),
record.probeClampRangeM,
);
positions = frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
moveCameraIcon(record);
}
const line = (name, role) => ({
id: `cctv-${camera.id}-${name}`,
cameraId: camera.id,
role,
positions: null,
widthPx: 1.2,
color: IDLE_COVERAGE_COLOR,
dashed: false,
depthFailColor: null,
show: true,
});
const entities = [
line('ray-tl', 'edge'),
line('ray-tr', 'edge'),
line('ray-br', 'edge'),
line('ray-bl', 'edge'),
line('cap', 'cap'),
];
placeCoverageLines(entities, positions);
parts.drawSets.writeLines(entities);
return entities;
}
/**
* Put a camera's five coverage line handles on its frustum positions (not
* written: the caller writes them).
* @param {Object[]} entities - The record's coverage handles.
* @param {Object} positions - frustumCartesians shape.
*/
function placeCoverageLines(entities, positions) {
if (!(entities?.length >= 5)) return;
entities[0].positions = [positions.mount, positions.tl];
entities[1].positions = [positions.mount, positions.tr];
entities[2].positions = [positions.mount, positions.br];
entities[3].positions = [positions.mount, positions.bl];
entities[4].positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
}
/**
* The activation obstruction probe's one ray cast against the scene: the
* first surface along the ray from `origin`. The layer's own lines, plane
* and volumes are not ground, so the cast sees through them.
* @param {{x: number, y: number, z: number}} origin - ECEF ray origin.
* @param {{x: number, y: number, z: number}} direction - Unit ECEF direction.
* @returns {Promise<{x: number, y: number, z: number}|null>} Null as well
* when the scene cannot cast rays.
*/
async function obstructionHit(origin, direction) {
const query = findQuery(layerState._viewer);
if (!query) return null;
return query.rayCast({ origin, direction }, { against: 'surface' });
}
/**
* On a globe map, where the activation probe's axis meets the globe's
* terrain: `{hit}`, `hit` null on a miss. Null when the globe is not shown
* (the photoreal stack), where only the surface cast counts.
* @returns {Promise<{hit: object|null}|null>}
*/
async function terrainHit(origin, direction) {
const viewer = layerState._viewer;
if (findGlobe(viewer)?.isGlobeVisible?.() !== true) return null;
const query = findQuery(viewer);
if (!query) return null;
return {
hit: await query.rayCast({ origin, direction }, { against: 'terrain' }),
};
}
/** Whether there is a query port to cast the activation probe through. */
function canPickFromRay() {
return typeof findQuery(layerState._viewer)?.rayCast === 'function';
}
/** Removes the layer's coverage lines from the scene. */
function removeCoverageEntities() {
parts.drawSets.clearLines();
}
/**
* The camera a pick (a draw-port `Hit`: `event.drawHit`, `query.pick`)
* names: an item of the layer's own sets that its record still draws.
* @param {{set: string, id: string, meta?: object}|null} hit
* @returns {string|null} Camera ID, or null if the pick is not a CCTV item.
*/
function extractPickedCameraId(hit) {
if (!hit || typeof hit.set !== 'string' || typeof hit.id !== 'string')
return null;
// A camera icon: its item id is the upstream camera id, so a sibling
// may legitimately use the same string. A bare id match is not
// ownership proof: the layer's own icon set must have drawn the pick.
const icons = layerState._icons;
if (icons && hit.set === icons.setId)
return icons.has(hit.id) && layerState._recordById.has(hit.id)
? hit.id
: null;
// A coverage line or monitor plane: an item of the layer's own sets
// that its record still draws.
const role = parts.drawSets.roleOfSet(hit.set);
if (!role) return null;
const value = hit.meta?.cameraId;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
if (!record) return null;
const owns =
role === 'coverage'
? Boolean(record.coverageEntities?.some((h) => h?.id === hit.id))
: record.projection?.plane?.id === hit.id ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.plane?.id === hit.id,
);
return owns ? value : null;
}
/**
* The camera whose icon or coverage is under a screen position (CSS px),
* from one pick; null when none is, or the pick throws.
* @param {{x: number, y: number}} position
* @returns {string|null}
*/
function pickCameraIdAt(position) {
let hit = null;
try {
hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null;
} catch {
hit = null;
}
return extractPickedCameraId(hit);
}
/**
* Where the ambient cards can go this pass: the canvas size, and the
* canvas position of a world point on the near side of the horizon (null
* behind it or off the projection).
* @returns {{width: number, height: number,
* screenOf: (position: object) => ({x: number, y: number}|null)}}
*/
function cardView() {
const viewer = layerState._viewer;
const canvas = canvasOf(viewer);
const query = findQuery(viewer);
const eye = findCamera(viewer)?.pose()?.position;
const horizon = eye ? horizonFrom(eye) : null;
return {
width: canvas?.clientWidth || canvas?.width || 0,
height: canvas?.clientHeight || canvas?.height || 0,
screenOf: (position) =>
query && horizon?.isPointVisible(position)
? query.project(position)
: null,
};
}
/**
* Removes (and destroys) a record's viewshed volume primitive, if any.
* @param {Object} record - Camera record.
*/
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedVolume)
parts.drawSets.removeVolume(record.viewshedVolume);
record.viewshedVolume = null;
}
/**
* (Re)builds a record's translucent viewshed volume from its CURRENT
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
* is welded to the cone by construction. Called only where the wireframe
* already rewrites (style refresh on mode/visible-set/active changes,
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
* queries (viewshed design §3b).
* @param {Object} record - Camera record.
* @param {boolean} isActive - Active camera gets the brighter fill.
*/
function rebuildViewshedVolume(record, isActive) {
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
) {
destroyViewshedVolume(record);
return;
}
const colors = record.viewshedColors;
const id = `cctv-${record.camera.id}-viewshed`;
// Replaced where it is: the volume draws in the frame its old one did.
parts.drawSets.writeVolume(
frustumVolumeItem(
id,
record.frustumPositions,
isActive ? colors.fillActive : colors.fill,
),
);
record.viewshedVolume = id;
record.viewshedActiveTint = !!isActive;
}
return {
projectionTilesReady,
frustumCartesians,
buildCoverageEntities,
placeCoverageLines,
obstructionHit,
terrainHit,
canPickFromRay,
removeCoverageEntities,
extractPickedCameraId,
pickCameraIdAt,
cardView,
destroyViewshedVolume,
rebuildViewshedVolume,
createCameraIcons,
destroyCameraIcons,
addCameraIcon,
moveCameraIcon,
refreshCctvFocusStyles,
applyCctvFocusDeemphasis,
refreshHorizonCulling,
+333 -33
View File
@@ -2,6 +2,7 @@
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
// from the same base color the coverage refresh assigns, so a video-feed camera
// stays violet while it dims instead of falling back to the idle cyan.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRendering } from './rendering.js';
@@ -11,68 +12,367 @@ import {
LIVE_CAMERA_COLOR,
} from './policy.js';
import { isVideoFeedType } from '../../sources/cctvTypes.js';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
const FOCUS_FACTOR = 0.5;
function assertFadedFrom(actual, base, label) {
assert.ok(actual, `${label}: color written`);
assert.deepEqual(
[actual.red, actual.green, actual.blue],
[base.red, base.green, base.blue],
`${label}: hue`,
);
assert.equal(actual.alpha, base.alpha * FOCUS_FACTOR, `${label}: alpha`);
function assertKeepsColor(icons, id, base, label) {
assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`);
assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`);
}
test('focus de-emphasis fades each icon from its own color', () => {
const record = (id, feedType) => ({
camera: { id, feedType },
// No position, so the pass skips screen projection; the focus stub below
// decides the factor on its own.
billboard: { show: true },
position: { x: 6378137, y: 0, z: 0 },
});
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
});
const projected = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
query: {
project: (position) => {
projected.push(position);
return { x: 10, y: 20 };
},
},
});
const state = {
_enabled: true,
_viewer: { scene: {}, camera: {} },
_viewer: viewer,
_records: [idleVideo, idleStill, activeVideo],
_activeCameraId: activeVideo.camera.id,
_activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity,
};
const distances = [];
const focus = {
focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => ({}),
focusPassIsNeeded: () => true,
advanceSpriteFocus: () => ({
factor: FOCUS_FACTOR,
active: true,
transitioning: false,
}),
advanceSpriteFocus: (meta, input) => {
distances.push(input.cameraDistance);
return { factor: FOCUS_FACTOR, active: true, transitioning: false };
},
focusAlphaNeedsWrite: () => true,
};
const { refreshCctvFocusStyles } = createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedCamera: (camera) =>
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedType,
isVideoFeedCamera: (camera) =>
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
},
},
source: {},
});
try {
const setId = createCameraIcons(viewer);
for (const r of state._records) addCameraIcon(r);
refreshCctvFocusStyles(1000);
const icons = state._icons;
assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video');
assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still');
assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video');
assert.equal(state._activeFocusStyleCount, 3);
assert.equal(projected.length, 3, 'each shown icon is projected');
assert.deepEqual(distances, [1000, 1000, 1000], 'from the eye');
// What the set draws: depth-test-free, held at the mount, shrinking
// with distance as before.
const drawn = draw.set(setId).items.get('idle-hls');
assert.equal(drawn.disableDepthTest, Infinity);
assert.deepEqual(drawn.motion, { kind: 'hold' });
assert.deepEqual(drawn.pos, idleVideo.position);
assert.deepEqual(drawn.size, [24, 24]);
assert.deepEqual(drawn.scaleByDistance, {
near: 350,
nearValue: 1.25,
far: 4_000_000,
farValue: 0.42,
});
assert.equal(drawn.focus, FOCUS_FACTOR);
assert.equal(draw.set(setId).spec.horizonCull, true);
// Hidden until enable() has culled and thinned the cameras: the layer
// waits on its health check between drawing them and that pass.
assert.equal(draw.set(setId).show, false);
} finally {
unbind();
}
});
test('the icons go with the viewer that drew them, whichever tears down', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus: {} },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
state._viewer = second;
const current = createCameraIcons(second);
assert.notEqual(old, current);
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
assert.equal(two.draw.sets.get(current).disposed, false);
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
} finally {
one.unbind();
two.unbind();
}
});
test('the obstruction probe casts one ray through the query port', async () => {
const calls = [];
const viewer = {};
const unbind = bindRenderer(viewer, {
query: {
rayCast: async (ray, options) => {
calls.push({ ray, options });
return { x: 1, y: 2, z: 3 };
},
},
});
const state = { _viewer: viewer };
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
try {
assert.equal(rendering.canPickFromRay(), true);
const origin = { x: 0, y: 0, z: 0 };
const direction = { x: 1, y: 0, z: 0 };
assert.deepEqual(await rendering.obstructionHit(origin, direction), {
x: 1,
y: 2,
z: 3,
});
// The layer's own sets are not ground: the cast sees through them
// without naming them.
assert.deepEqual(calls, [
{ ray: { origin, direction }, options: { against: 'surface' } },
]);
} finally {
unbind();
}
state._viewer = {};
assert.equal(rendering.canPickFromRay(), false);
assert.equal(
await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
null,
);
});
test('cards go only where the horizon lets the camera see', () => {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000);
const front = Cesium.Cartesian3.fromDegrees(0, 0);
const back = Cesium.Cartesian3.fromDegrees(180, 0);
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: eye.x, y: eye.y, z: eye.z } },
});
const unbind = bindRenderer(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 0, height: 600 },
query: { project: () => ({ x: 10, y: 20 }) },
});
try {
const view = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
}).cardView();
assert.equal(view.width, 800);
assert.equal(view.height, 600);
assert.deepEqual(view.screenOf(front), { x: 10, y: 20 });
assert.equal(view.screenOf(back), null);
} finally {
unbind();
}
});
test('the projection tiles are ready only when drawn and settled', () => {
const viewer = {};
let globeVisible = true;
let settled = true;
const unbind = bindRenderer(viewer, {
globe: {
isGlobeVisible: () => globeVisible,
isSettled: (kind) => kind === 'tiles' && settled,
},
});
try {
const { projectionTilesReady } = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
});
assert.equal(projectionTilesReady(), false, 'a globe stack hides them');
globeVisible = false;
assert.equal(projectionTilesReady(), true);
settled = false;
assert.equal(projectionTilesReady(), false, 'still streaming');
} finally {
unbind();
}
const bare = createRendering({
state: { _viewer: {} },
services: { focus: {} },
parts: {},
});
assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles');
});
test('a view pass writes only the icons it changes, in one write', () => {
const viewer = {};
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 2000);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const camera = fakeCameraPort({
pose: {
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: { x: 0, y: 0, z: 1 },
fovy: Math.PI / 3,
aspectRatio: 4 / 3,
near: 0.1,
far: 5e8,
},
});
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
});
const record = (id, lon) => {
const p = Cesium.Cartesian3.fromDegrees(lon, 0, 10);
return {
camera: { id, lat: 0, lon },
position: { x: p.x, y: p.y, z: p.z },
};
};
// One in view, one far off it.
const near = record('near', 0);
const far = record('far', 1);
const state = {
_enabled: true,
_viewer: viewer,
_records: [near, far],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
drawSets: { roleOfSet: () => null },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
const set = draw.set(setId);
const writes = set.writes;
refreshCctvFocusStyles(1000);
assert.equal(rendering.refreshHorizonCulling(), true);
assert.equal(set.writes, writes + 1, 'one write for the pass');
assert.equal(set.items.get('near').show, true);
assert.equal(set.items.get('far').show, false);
assertFadedFrom(idleVideo.billboard.color, LIVE_CAMERA_COLOR, 'idle video');
assertFadedFrom(idleStill.billboard.color, IDLE_CAMERA_COLOR, 'idle still');
assertFadedFrom(
activeVideo.billboard.color,
ACTIVE_CAMERA_COLOR,
'active video',
);
assert.equal(state._activeFocusStyleCount, 3);
assert.equal(rendering.refreshHorizonCulling(), false);
assert.equal(set.writes, writes + 1, 'an unchanged view writes nothing');
// Another layer on the same viewer draws its icons in a set of its own.
const other = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
source: {},
});
const otherId = other.createCameraIcons(viewer);
assert.notEqual(otherId, setId);
assert.equal(
rendering.extractPickedCameraId({ set: otherId, id: 'near' }),
null,
"the other layer's icon is not this layer's camera",
);
} finally {
unbind();
}
});
test('a pose with no perspective field of view is projected by the renderer', () => {
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 7e6, y: 0, z: 0 }, fovy: undefined },
});
const asked = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
query: {
project: (position) => {
asked.push(position.y);
return position.y === 0 ? { x: 400, y: 300 } : null;
},
},
});
// On the ground under the eye, in cells of their own.
const record = (id, y) => ({
camera: { id, lat: 0, lon: y / 1000 },
position: { x: 6378137, y, z: 0 },
});
const state = {
_enabled: true,
_viewer: viewer,
_records: [record('on', 0), record('off', 1000)],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
rendering.refreshHorizonCulling();
const set = draw.set(setId);
assert.deepEqual(asked.sort(), [0, 1000]);
assert.equal(set.items.get('on').show, true);
assert.equal(set.items.get('off').show, false);
} finally {
unbind();
}
});
+23 -74
View File
@@ -1,8 +1,4 @@
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../data/trackingClickGesture.js';
import * as Cesium from 'cesium';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
state: layerState,
@@ -34,24 +30,19 @@ export function createSelection({
}
/**
* Bind CCTV activation to clean taps while preserving the layer's hover-move
* callback on the shared Cesium handler. Drag-like and long-press gestures do
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
* @param {Cesium.ScreenSpaceEventHandler|Object} handler - Input handler.
* @param {(click: Object) => void} onClick - Accepted CCTV click callback.
* @param {Object} [options] - Gesture test seams and optional onMouseMove hook.
* @returns {void}
* @param {import('../../input/dispatcher.js').InputDispatcher} input
* @param {(event: import('../../input/dispatcher.js').ClickEvent) => void} onClick
* Accepted CCTV click callback.
* @returns {() => void} Unsubscribe.
*/
function bindCctvWorldClickGesture(handler, onClick, options = {}) {
bindTrackingClickGesture(
handler,
(click, gesture) => {
if (!isTrackingClickGesture(gesture)) return;
onClick(click);
},
options,
);
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
onClick(event);
});
}
/**
@@ -119,12 +110,13 @@ export function createSelection({
layerState._geoQueue.splice(queueIdx, 1);
layerState._geoQueue.unshift(record);
}
// §9.1: one obstruction probe per activation, BEFORE the geometry pass so
// the range clamp lands in the same rewrite. A FIRST-EVER activation (no
// real ground sample yet) probes from the catalog-prior altitude — if that
// prior is off, the clamp is measured from a shifted origin, but a
// re-activation after the one-shot snap lands re-probes from real ground,
// so it self-corrects.
// §9.1: one obstruction probe per activation, cast before the geometry
// pass; its range clamp lands a microtask later, before the next frame,
// rewriting the geometry and asking again for the footprint ground. A
// FIRST-EVER activation (no real ground sample yet) probes from the
// catalog-prior altitude — if that prior is off, the clamp is measured
// from a shifted origin, but a re-activation after the one-shot snap
// lands re-probes from real ground, so it self-corrects.
parts.geometry.runActivationObstructionProbe(record);
// Coverage is activation-lazy even while the mode is OFF: the active
// camera's projection representation must be ready without materializing
@@ -214,57 +206,14 @@ export function createSelection({
}
/**
* Extracts a camera ID from a Cesium pick result by checking billboard IDs,
* primitive IDs, and entity cctvCameraId properties.
* @param {Object|null} picked - Result from scene.pick().
* @returns {string|null} Camera ID, or null if the pick is not a CCTV entity.
* The camera a scene pick result is, or null: read by the rendering part,
* which owns the scene objects the pick names.
* @param {Object|null} picked - Result from a scene pick.
* @returns {string|null}
*/
function extractPickedCameraId(picked) {
if (!picked) return null;
const entity = picked.id?.properties
? picked.id
: picked.primitive?.id?.properties
? picked.primitive.id
: null;
const maybeProp = entity?.properties?.cctvCameraId;
if (maybeProp) {
const value =
typeof maybeProp.getValue === 'function'
? maybeProp.getValue(Cesium.JulianDate.now())
: maybeProp;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
const ownsCoverageEntity = Boolean(
record?.coverageEntities?.includes(entity),
);
const ownsProjectionEntity =
record?.projection?.planeEntity === entity ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.planeEntity === entity,
);
if (record && (ownsCoverageEntity || ownsProjectionEntity)) return value;
}
// Camera billboard IDs are intentionally the upstream camera ID, so a
// sibling may legitimately use the same string. A bare ID match is not
// ownership proof: require this layer's billboard collection or the exact
// billboard stored on the record.
const directId =
typeof picked.id === 'string'
? picked.id
: typeof picked.primitive?.id === 'string'
? picked.primitive.id
: null;
const record =
directId === null ? null : layerState._recordById.get(directId);
if (!record) return null;
return picked.primitive === layerState._billboards ||
picked.primitive === record.billboard
? directId
: null;
return parts.rendering.extractPickedCameraId(picked);
}
return {
getActiveRecord,
+5 -4
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCctvSource, createCctvLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const camera = {
id: 'pack/camera ?x',
@@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
},
sprites: { registerSpriteCollection: noop },
sprites: {},
activation: {},
locations: {},
picking: { unregisterPickOwner: noop },
@@ -134,9 +135,9 @@ test('camera construction is inert and destruction cancels a pending catalog and
const a = createCctvLayer({ services, source });
const b = createCctvLayer({ services, source });
assert.equal(listeners.size, 0);
const viewer = {
scene: { primitives: { add: (value) => value, remove: () => true } },
};
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
t.after(unbind);
const initializing = a.init(viewer);
assert.equal(listeners.size, 1);
assert.equal(signal.aborted, false);
+10 -20
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const {
clearOverlaySource,
@@ -15,7 +13,8 @@ export function createState({ services }) {
layerState._viewer = null;
layerState._billboards = null;
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._records = [];
@@ -58,7 +57,7 @@ export function createState({ services }) {
layerState._lastViewContext = '';
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._count = 0;
@@ -84,11 +83,8 @@ export function createState({ services }) {
layerState._activeFocusStyleCount = 0;
layerState._scratchFocusScreen = new Cesium.Cartesian2();
layerState._scratchViewScreen = new Cesium.Cartesian2();
layerState._scratchViewProjection = new Cesium.Matrix4();
// The view pass's screen-point scratch: its projection writes only x and y.
layerState._scratchViewScreen = { x: 0, y: 0 };
// Counts view passes; a record shown by the latest pass carries its number.
@@ -114,7 +110,7 @@ export function createState({ services }) {
layerState._viewResizeCanvas = null;
// The camera the moveStart/moveEnd listeners are attached to.
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = null;
@@ -174,16 +170,9 @@ export function createState({ services }) {
layerState._lastTransientNotifyAt = 0;
// Cached handle on the active Google Photorealistic 3D Tileset, discovered
// lazily from scene.primitives. Shared mesh-floor sampling is gated on its
// tilesLoaded flag so a coarse-LOD miss is never baked in. Cleared when the
// tileset is destroyed / the layer tears down.
layerState._activeTileset = null;
// Task 5: last surface regime the record geometry was recomputed for. The
// map-stack change listener compares the CURRENT regime (derived live from
// scene.globe.show) against this so bing→osm switches (same 'terrain-globe'
// whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe'
// regime) don't trigger a pointless full-catalog rewrite.
layerState._lastAppliedRegime = null;
@@ -193,8 +182,8 @@ export function createState({ services }) {
layerState._mapStackListener = null;
// Field-test fix (2026-07-06): camera.moveEnd handle for the horizon-culling
// pass (removed in destroy). Event-driven only — never a per-frame loop, so
// Field-test fix (2026-07-06): the Off of the camera's moveEnd listener for
// the horizon-culling pass (called in destroy). Event-driven only — never a per-frame loop, so
// the zero-steady-state-work invariant holds.
layerState._horizonCullListener = null;
@@ -269,6 +258,7 @@ export function createState({ services }) {
layerState._cameraMoving = false;
// The Off of the camera's moveStart listener.
layerState._moveStartListener = null;
layerState._sourceAbort = null;
return layerState;
+54 -7
View File
@@ -1,4 +1,13 @@
import * as Cesium from 'cesium';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
const testIconSet = () => ({
id: 'cctv:test:icons',
show: true,
upsert() {},
remove() {},
dispose() {},
});
export function createTesting({ state: layerState, services, parts, source }) {
/** Test seam: republishes host entries through the real push path, so tests
@@ -19,7 +28,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
/**
* Create the production monitor-plane/host-label pair without media setup.
* @param {Object} viewer Cesium viewer seam.
* @param {Object} viewer Viewer whose renderer draws the plane.
* @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime.
*/
@@ -34,15 +43,16 @@ export function createTesting({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
const runtime = {
cameraId: String(record.camera.id),
planeEntity: null,
labelPosition: new Cesium.Cartesian3(),
plane: null,
// createProjectionPlane gives it its label position.
labelPosition: null,
overlayEntry: null,
planeMaterial: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
planeSource: parts.projection.plainPlaneSource(),
};
parts.projection.createProjectionPlane(
record,
@@ -102,7 +112,6 @@ export function createTesting({ state: layerState, services, parts, source }) {
);
layerState._coverageEntities = [];
layerState._projectionEntities = [];
layerState._billboards = null;
layerState._activeCameraId = activeCameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = !!openingCameraProvisional;
@@ -117,6 +126,42 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
/**
* What the layer draws now, for the QA harness: the gizmo's parts, the
* coverage lines and monitor planes by item id, the viewshed volumes'
* ids, and how many volumes were ever written.
*/
function _cctvDrawnForTest() {
const coverage = {};
for (const record of layerState._records)
for (const line of record.coverageEntities || [])
if (line?.id) coverage[line.id] = line;
const planes = {};
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
viewsheds: layerState._records
.map((record) => record.viewshedVolume)
.filter(Boolean),
viewshedWrites: parts.drawSets.volumeWritesForTest(),
};
}
/** The layer's icon book, for tests that read what the icons draw. */
function _cctvIconsForTest() {
return layerState._icons;
}
return {
_pushAmbientCardEntriesForTest,
@@ -125,5 +170,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
_updateCctvProjectionPlaneForTest,
_extractPickedCameraIdForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_cctvDrawnForTest,
};
}
+55 -59
View File
@@ -1,7 +1,6 @@
import * as Cesium from 'cesium';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import {
registerPickOwner,
unregisterPickOwner,
@@ -23,6 +22,7 @@ import {
translateKnown,
} from '../../i18n/index.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
// "10-12 15:00 UTC" never breaks across lines: no-break spaces, and a word
// joiner after the hyphen (JetBrains Mono has no U+2011 non-breaking hyphen).
@@ -59,8 +59,22 @@ const classificationName = (code) =>
Object.hasOwn(CLASSIFICATION_NAMES, code)
? t(CLASSIFICATION_NAMES[code])
: code;
const number = (value, unit) =>
value === null ? t('Unavailable') : formatQuantity(value, unit);
// A value the advisory leaves out (null) is left out of the line too.
const intensityText = (storm) => {
const has = (value) => value !== null && value !== undefined;
const wind = has(storm.windKt) ? formatQuantity(storm.windKt, 'kt') : null;
const pressure = has(storm.pressureHpa)
? formatQuantity(storm.pressureHpa, 'hPa')
: null;
if (wind && pressure)
return t('Maximum sustained wind: {wind} · Pressure: {pressure}', {
wind,
pressure,
});
if (wind) return t('Maximum sustained wind: {wind}', { wind });
if (pressure) return t('Pressure: {pressure}', { pressure });
return '';
};
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
@@ -68,7 +82,6 @@ export function createCyclonesLayer({
hitTestOverlay = hitTestWorldOverlay,
overlayHost,
context = null,
cesium = Cesium,
createRendering = createCycloneRendering,
matchMedia = globalThis.matchMedia?.bind(globalThis),
openLink = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
@@ -83,8 +96,8 @@ export function createCyclonesLayer({
selectedId = null,
selectionIntent = 'auto',
navigationGeneration = 0,
selectionOwner = null,
selectedContextStormId = null,
clickHandler = null,
removeClickCapture = null;
let enabled = false,
loading = false,
@@ -155,26 +168,13 @@ export function createCyclonesLayer({
selectedId = id;
rendering?.setSelection(id);
}
// Photorealistic 3D Tiles pick as tileset content without an entity id;
// that is empty map, the same as no pick at all on the globe.
const isSurfacePick = (picked) =>
!picked ||
(picked.id === undefined &&
(picked.content !== undefined ||
(typeof cesium.Cesium3DTileset === 'function' &&
picked.primitive instanceof cesium.Cesium3DTileset)));
function installSelection() {
if (
clickHandler ||
!viewer?.scene?.canvas ||
typeof cesium.ScreenSpaceEventHandler !== 'function'
)
return;
const owner = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
clickHandler = owner;
const canvas = canvasOf(viewer);
if (selectionOwner || !canvas) return;
const owner = {};
selectionOwner = owner;
// Snapshot before sibling bubble listeners can rebuild the overlay hit
// rectangles. A vessel selection does that synchronously in the same click.
const canvas = viewer.scene.canvas;
let capturedHit = null;
const overlayHit = (x, y) => {
const hit = hitTestOverlay(x, y);
@@ -212,28 +212,24 @@ export function createCyclonesLayer({
canvas.removeEventListener?.(type, resetCapture, { capture: true });
capturedHit = null;
};
owner.setInputAction((click) => {
const unsubscribe = inputFor(viewer).onClick((event) => {
const nativeHit = capturedHit;
capturedHit = null;
// Ambient selection yields to draw tools and Director; it never claims
// the pointer, camera, or tracking state.
if (
!enabled ||
destroyed ||
clickHandler !== owner ||
!isPointerFree() ||
!click?.position
)
// Ambient selection yields to draw tools and Director (the dispatcher
// skips a held pointer); it never claims the pointer, camera, or
// tracking state.
const position = event.screenPosition;
if (!enabled || destroyed || selectionOwner !== owner || !position)
return;
// AIS cards paint above the globe on a pointer-events:none canvas. The
// vessel handler resolves this same topmost hit before cyclone geometry.
const captureMatches =
nativeHit &&
Math.abs(nativeHit.x - click.position.x) < 1 &&
Math.abs(nativeHit.y - click.position.y) < 1;
Math.abs(nativeHit.x - position.x) < 1 &&
Math.abs(nativeHit.y - position.y) < 1;
const hit = captureMatches
? nativeHit
: overlayHit(click.position.x, click.position.y);
: overlayHit(position.x, position.y);
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
// Storm cards and lead-hour labels paint on the same canvas; a click on
// one selects its storm. An id from a superseded advisory changes nothing.
@@ -242,18 +238,20 @@ export function createCyclonesLayer({
if (id) layer.setParams({ stormId: id });
return;
}
const picked = viewer.scene.pick(click.position);
const id = rendering?.pickStorm(picked);
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
// clears the selection.
const id = rendering?.pickStorm(event.drawHit);
if (id) layer.setParams({ stormId: id });
else if (isSurfacePick(picked)) layer.setParams({ clear: true });
}, cesium.ScreenSpaceEventType.LEFT_CLICK);
else if (!event.topHit) layer.setParams({ clear: true });
});
owner.unsubscribe = unsubscribe;
}
function removeSelection() {
const owner = clickHandler;
clickHandler = null;
const owner = selectionOwner;
selectionOwner = null;
removeClickCapture?.();
removeClickCapture = null;
if (owner && !owner.isDestroyed?.()) owner.destroy();
owner?.unsubscribe?.();
}
const layer = {
id: 'weather-cyclones',
@@ -263,7 +261,7 @@ export function createCyclonesLayer({
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
rendering = createRendering({ viewer, cesium, overlayHost });
rendering = createRendering({ viewer, overlayHost });
},
attachShellServices(services) {
runNavigation =
@@ -394,12 +392,15 @@ export function createCyclonesLayer({
selectedId !== storm.id
)
return;
return viewer.camera.flyToBoundingSphere(sphere, {
duration: matchMedia?.('(prefers-reduced-motion: reduce)')
?.matches
? 0
: 1.4,
});
cameraOf(viewer).flyToBounds(
{ center: sphere.center, radius: sphere.radius },
{
durationS: matchMedia?.('(prefers-reduced-motion: reduce)')
?.matches
? 0
: 1.4,
},
);
});
}
}
@@ -437,12 +438,7 @@ export function createCyclonesLayer({
const position = storm
? t('Position as of {time}', { time: utc(storm.positionAt) })
: '';
const intensity = storm
? t('Maximum sustained wind: {wind} · Pressure: {pressure}', {
wind: number(storm.windKt, 'kt'),
pressure: number(storm.pressureHpa, 'hPa'),
})
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
@@ -492,7 +488,7 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
]
].filter((line) => line.text)
: [],
detail,
status,
@@ -524,7 +520,7 @@ export function createCyclonesLayer({
]
: [],
info: storm
? `${detail}\n${position}\n${intensity}\n${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
infoTitle: t(
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
@@ -587,7 +583,7 @@ export function createCyclonesLayer({
enabled,
loading,
requestPending: !!request,
selectionActive: clickHandler !== null,
selectionActive: selectionOwner !== null,
selectedId,
selectionIntent,
timerActive: false,
+137 -52
View File
@@ -7,9 +7,39 @@ import {
isPointerFree,
} from '../../data/inputOwnership.js';
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
/** Record each click subscription the layer makes, as the old handler fakes did. */
function recordHandlers(viewer, handlers) {
const fake = fakeInput(viewer);
const subscribe = fake.input.onClick;
fake.input.onClick = (fn) => {
const handler = {
destroyed: false,
// A live subscription hears clicks through the dispatcher; a removed
// one is called directly, as a queued callback would be.
click: (click) =>
handler.destroyed
? fn({
screenPosition: click.position,
get pick() {
return viewer.scene.pick(click.position);
},
})
: fake.click(click.position),
};
handlers.push(handler);
const off = subscribe(fn);
return () => {
handler.destroyed = true;
off();
};
};
}
import * as contextStore from '../../data/contextStore.js';
import { createGevActionRunner } from '../../voice/gevActions.js';
import * as Cesium from 'cesium';
import { fromRadians } from '../../geo/ellipsoid.js';
const time = '2026-09-16T03:00:00.000Z';
const storm = (id = 'ep152026') => ({
@@ -49,8 +79,16 @@ const deferred = () => {
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
const handlers = [],
pickedEntity = {},
foreignEntity = {};
// A pick of an item in one of the layer's draw sets, and one of another
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
pickedEntity = {
set: 'weather-cyclones:1:points',
id: 'cyclone:ep162026:center',
},
foreignEntity = {
set: 'other-layer:points',
id: 'cyclone:ep162026:center',
};
let picked = { id: pickedEntity },
overlayHit = null,
overlayTests = 0,
@@ -61,33 +99,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
setSelection() {},
clear() {},
destroy() {},
pickStorm: (value) => (value?.id === pickedEntity ? 'ep162026' : null),
pickStorm: (hit) =>
hit?.set === pickedEntity.set && hit.id === pickedEntity.id
? 'ep162026'
: null,
ownsPickId: (id) => id === 'cyclone:ep162026:center',
getDiagnostics: () => ({}),
};
const cesium = {
ScreenSpaceEventType: { LEFT_CLICK: 'left' },
ScreenSpaceEventHandler: class {
constructor(canvas) {
assert.ok(canvas);
handlers.push(this);
this.destroyed = false;
}
setInputAction(callback, type) {
assert.equal(type, 'left');
this.click = callback;
}
destroy() {
this.destroyed = true;
}
isDestroyed() {
return this.destroyed;
}
},
};
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
cesium,
createRendering: () => rendering,
hitTestOverlay: () => {
overlayTests++;
@@ -97,6 +117,9 @@ test('map selection yields to pointer owners and owns only its enabled handler',
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: {
canvas,
pick() {
@@ -111,6 +134,8 @@ test('map selection yields to pointer owners and owns only its enabled handler',
},
},
};
bindFakeCesiumCamera(viewer);
recordHandlers(viewer, handlers);
layer.init(viewer);
layer.setRowControlsListener(() => notices++);
assert.equal(handlers.length, 0, 'disabled module installs no handler');
@@ -271,18 +296,6 @@ test('a click on a storm card or lead-hour label selects that storm without pick
hostArgument;
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
cesium: {
ScreenSpaceEventType: { LEFT_CLICK: 'left' },
ScreenSpaceEventHandler: class {
constructor() {
handlers.push(this);
}
setInputAction(callback) {
this.click = callback;
}
destroy() {}
},
},
overlayHost: 'host',
createRendering: ({ overlayHost }) => {
hostArgument = overlayHost;
@@ -300,7 +313,10 @@ test('a click on a storm card or lead-hour label selects that storm without pick
});
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
layer.init({
const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: {
canvas,
pick() {
@@ -308,7 +324,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
return { content: {} };
},
},
});
};
recordHandlers(viewer, handlers);
layer.init(viewer);
assert.equal(hostArgument, 'host', 'the overlay host reaches the renderer');
layer.enable();
await layer.update();
@@ -357,7 +375,10 @@ function harness(
setSelection(id) {
selection = id;
},
getFocusSphere: () => ({ radius: 500000 }),
getFocusSphere: () => ({
center: { x: 6378137, y: 0, z: 0 },
radius: 500000,
}),
clear() {
cleared++;
},
@@ -382,6 +403,7 @@ function harness(
navigation.push({ sphere, options }),
},
};
bindFakeCesiumCamera(viewer);
layer.init(viewer);
layer.attachShellServices({
runNavigation: (fn) => {
@@ -432,19 +454,29 @@ async function withSharedContext(t, body) {
);
// The voice runner bounds its basemap wait with the window timers.
Object.assign(host, { setTimeout, clearTimeout });
const position = Cesium.Cartesian3.fromDegrees(-125.8, 15.5, 5_000_000);
const runner = createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
positionWC: position,
positionCartographic: Cesium.Cartographic.fromCartesian(position),
heading: 0,
pitch: 0,
},
const cartographic = {
longitude: (-125.8 * Math.PI) / 180,
latitude: (15.5 * Math.PI) / 180,
height: 5_000_000,
};
const position = fromRadians(
cartographic.longitude,
cartographic.latitude,
cartographic.height,
);
const viewer = bindFakeCesiumCamera({
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
positionWC: position,
positionCartographic: cartographic,
heading: 0,
pitch: 0,
},
});
const runner = createGevActionRunner({
viewer,
styleManager: {},
dataManager: {
layers: new Map(),
@@ -792,6 +824,59 @@ test('classification display expands known codes without altering the source or
}
}
});
// Quantities join number and unit with a no-break space.
const plain = (text) => text?.replace(/\u00a0/g, ' ') ?? null;
test('an advisory without pressure, movement or link leaves those values out', async () => {
const record = {
...storm(),
windKt: 85,
pressureHpa: null,
movement: { directionDegrees: null, speedKt: null },
advisoryUrl: null,
};
const h = harness({ getSnapshot: async () => snapshot([record]) });
try {
h.layer.enable();
await h.layer.update();
const { summary, info } = h.layer.getRowControls();
const intensity = summary.lines.find((line) => line.id === 'intensity');
assert.equal(plain(intensity.text), 'Maximum sustained wind: 85 kt');
assert.deepEqual(
summary.lines.map((line) => line.id),
['position', 'intensity', 'geometry'],
);
assert.deepEqual(summary.actions, [], 'no advisory link to open');
assert.ok(plain(info).includes('Maximum sustained wind: 85 kt\n'));
for (const text of [info, ...summary.lines.map((line) => line.text)])
assert.doesNotMatch(text, /Unavailable|Pressure/);
} finally {
h.layer.destroy();
}
});
test('an advisory with only one of wind and pressure shows that one alone', async () => {
for (const [values, expected] of [
[{ windKt: null, pressureHpa: 990 }, 'Pressure: 990 hPa'],
[
{ windKt: 60, pressureHpa: 990 },
'Maximum sustained wind: 60 kt · Pressure: 990 hPa',
],
[{ windKt: null, pressureHpa: null }, null],
]) {
const h = harness({
getSnapshot: async () => snapshot([{ ...storm(), ...values }]),
});
try {
h.layer.enable();
await h.layer.update();
const { summary, info } = h.layer.getRowControls();
const intensity = summary.lines.find((line) => line.id === 'intensity');
assert.equal(plain(intensity?.text), expected);
assert.doesNotMatch(info, /Unavailable|\n\n/);
} finally {
h.layer.destroy();
}
}
});
test('advisory selection uses accessible row descriptors and shared camera handoff', async () => {
const h = harness(
{ getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
+207 -245
View File
@@ -1,3 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { drawOf } from '../../render/rendererOf.js';
import {
CYCLONE_ACCENT,
CYCLONE_MARKER_PX,
@@ -5,6 +8,14 @@ import {
createCycloneLabels,
} from './labels.js';
/**
* The draw sets the advisories are drawn in start with this; each rendering
* has its own (`weather-cyclones:1:points`, …), so several can share a
* renderer. Picks name them as `Hit.set`.
*/
export const CYCLONE_SET_PREFIX = 'weather-cyclones';
let renderings = 0;
/** Only geometry from the displayed status advisory is eligible for rendering. */
export function coherentCycloneGeometry(storm) {
return (
@@ -13,299 +24,250 @@ export function coherentCycloneGeometry(storm) {
);
}
/** A `#rrggbb` colour at `alpha`, as CSS. */
function withAlpha(hex, alpha) {
const n = Number.parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;
}
const BLACK = [0, 0, 0, 1];
const WHITE = [1, 1, 1, 1];
/**
* Static Cesium entities with owned horizon culling; no timers or clock.
* Storm names and lead hours are published to the shared overlay host at the
* same anchors the points use.
* Static renderer draw sets with the renderer's horizon cull; no timers or
* clock. Points are clamped and drawn over depth, so the points set culls
* them past the horizon; tracks, cones and their outlines drape on the
* ground, where the globe hides the far side. Storm names and lead hours
* are published to the shared overlay host at the same anchors the points
* use.
*/
export function createCycloneRendering({ viewer, cesium: C, overlayHost }) {
export function createCycloneRendering({ viewer, overlayHost }) {
const labels = createCycloneLabels({ host: overlayHost });
let source = null,
generation = 0,
const draw = drawOf(viewer);
const prefix = `${CYCLONE_SET_PREFIX}:${++renderings}`;
const setIds = new Set(
['points', 'lines', 'cones'].map((kind) => `${prefix}:${kind}`),
);
const points = draw.points({
id: `${prefix}:points`,
horizonCull: true,
clampTo: 'both',
});
const lines = draw.lines({ id: `${prefix}:lines`, clampTo: 'both' });
const cones = draw.shapes({ id: `${prefix}:cones`, clampTo: 'both' });
let committed = false,
selected = null,
destroyed = false;
// Per storm: its center point (redrawn on selection), forecast points and
// focus sphere; per drawn item, the storm it belongs to.
let centers = new Map(),
spheres = new Map();
let entityStorms = new WeakMap();
let entityIds = new Set();
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let horizonStorms = [],
removePreRender = null,
pointOccluder = null,
sphereOccluder = null;
const blue = C.Color.fromCssColorString(CYCLONE_ACCENT);
const gold = C.Color.fromCssColorString(CYCLONE_SELECTED_ACCENT);
const white = C.Color.WHITE;
const render = () => {
if (!viewer.isDestroyed?.()) viewer.scene.requestRender();
};
function cullHorizon() {
pointOccluder.cameraPosition = viewer.camera.positionWC;
sphereOccluder.cameraPosition = viewer.camera.positionWC;
let changed = false;
for (let i = 0; i < horizonStorms.length; i++) {
const storm = horizonStorms[i];
for (let j = 0; j < storm.points.length; j++) {
const { entity, position } = storm.points[j];
const show = pointOccluder.isPointVisible(position);
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
if (!storm.shapes.length) continue;
const show = sphereOccluder.isBoundingSphereVisible(storm.sphere);
for (let j = 0; j < storm.shapes.length; j++) {
const entity = storm.shapes[j];
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
}
if (changed) render();
let itemCount = 0;
function centerItem(storm) {
const chosen = storm.id === selected;
return {
id: `cyclone:${storm.id}:center`,
pos: storm.at,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: chosen ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm,
color: chosen ? CYCLONE_SELECTED_ACCENT : CYCLONE_ACCENT,
outlineColor: BLACK,
outlineWidth: 2,
};
}
function syncHorizonListener() {
if (!horizonStorms.length) {
removePreRender?.();
removePreRender = null;
return;
}
if (removePreRender) return;
pointOccluder ||= new C.EllipsoidalOccluder(
C.Ellipsoid.WGS84,
viewer.camera.positionWC,
);
// EllipsoidalOccluder only tests points. An inscribed WGS84 sphere
// conservatively culls extents, retaining partially visible tracks/cones.
sphereOccluder ||= new C.Occluder(
new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius),
viewer.camera.positionWC,
);
removePreRender = viewer.scene.preRender.addEventListener(cullHorizon);
}
function remove(value) {
if (!value) return;
if (!viewer.dataSources.isDestroyed?.())
viewer.dataSources.remove(value, true);
value.entities.removeAll();
function drawPoints() {
points.set([...[...centers.values()].map(centerItem), ...forecasts]);
}
// Only the centers show the selection: a change redraws the points set.
function select(id) {
if (destroyed || id === selected) return;
selected = id;
for (const [stormId, entity] of centers) {
entity.point.color = stormId === id ? gold : blue;
entity.point.pixelSize =
stormId === id ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm;
}
drawPoints();
labels.setSelection(id);
render();
}
return {
async setSnapshot(snapshot, { signal } = {}) {
signal?.throwIfAborted();
if (destroyed) return false;
const owner = ++generation;
const next = new C.CustomDataSource('weather-cyclones');
const nextCenters = new Map(),
nextSpheres = new Map();
const nextEntityStorms = new WeakMap();
const nextEntityIds = new Set();
nextSpheres = new Map(),
nextItemStorms = new Map();
const nextForecasts = [],
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const nextHorizonStorms = [];
const nextLabels = [];
const position = ({ longitude, latitude }) =>
C.Cartesian3.fromDegrees(longitude, latitude, 0);
const coordinate = (pair) =>
position({ longitude: pair[0], latitude: pair[1] });
try {
for (const storm of snapshot.storms) {
const horizon = { points: [], shapes: [], sphere: null };
const addEntity = (options) => {
const entity = next.entities.add(options);
if (options.position)
horizon.points.push({ entity, position: options.position });
else horizon.shapes.push(entity);
nextEntityStorms.set(entity, storm.id);
nextEntityIds.add(entity.id);
return entity;
};
const center = position(storm.position),
extent = [center];
const entity = addEntity({
id: `cyclone:${storm.id}:center`,
name: storm.name,
position: center,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.storm,
color: blue,
outlineColor: C.Color.BLACK,
outlineWidth: 2,
},
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
height: 0,
});
const pair = (coordinate) => ({
lon: coordinate[0],
lat: coordinate[1],
height: 0,
});
const ecef = (p) => fromDegrees(p.lon, p.lat, 0);
for (const storm of snapshot.storms) {
const own = (id) => (nextItemStorms.set(id, storm.id), id);
const at = lonLat(storm.position);
const center = ecef(at);
const extent = [center];
own(`cyclone:${storm.id}:center`);
nextCenters.set(storm.id, { id: storm.id, at });
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const tracks =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
tracks.forEach((line, index) => {
// Lines take ECEF (draw.d.ts `LineItem`).
const positions = line.map((c) => ecef(pair(c)));
extent.push(...positions);
nextLines.push({
id: own(`cyclone:${storm.id}:track:${index}`),
positions,
widthPx: 2.5,
mode: 'draped',
style: { kind: 'solid', color: CYCLONE_ACCENT },
});
nextCounts.tracks++;
});
nextCenters.set(storm.id, entity);
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const lines =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
lines.forEach((line, index) => {
const positions = line.map(coordinate);
extent.push(...positions);
addEntity({
id: `cyclone:${storm.id}:track:${index}`,
polyline: {
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
positions,
width: 2.5,
material: blue,
arcType: C.ArcType.GEODESIC,
},
});
nextCounts.tracks++;
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(CYCLONE_ACCENT, 0.16),
height: 'clampGround',
});
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const exterior = rings[0].map(coordinate);
extent.push(...exterior);
const holes = rings
.slice(1)
.map((ring) => new C.PolygonHierarchy(ring.map(coordinate)));
addEntity({
id: `cyclone:${storm.id}:cone:${index}`,
polygon: {
hierarchy: new C.PolygonHierarchy(exterior, holes),
classificationType: C.ClassificationType.BOTH,
material: blue.withAlpha(0.16),
arcType: C.ArcType.GEODESIC,
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: 1,
mode: 'draped',
style: {
kind: 'solid',
color: withAlpha(CYCLONE_ACCENT, 0.55),
},
});
[exterior, ...holes.map((hole) => hole.positions)].forEach(
(positions, ringIndex) => {
addEntity({
id: `cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
polyline: {
positions,
width: 1,
material: blue.withAlpha(0.55),
arcType: C.ArcType.GEODESIC,
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
},
});
},
);
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const p = position(point.position);
extent.push(p);
addEntity({
id: `cyclone:${storm.id}:forecast:${index}`,
position: p,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: white,
outlineColor: C.Color.BLACK,
outlineWidth: 1,
},
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
const p = ecef(pos);
extent.push(p);
nextForecasts.push({
id: own(`cyclone:${storm.id}:forecast:${index}`),
pos,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: WHITE,
outlineColor: BLACK,
outlineWidth: 1,
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
const sphere = C.BoundingSphere.fromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
horizon.sphere = sphere;
nextHorizonStorms.push(horizon);
}
await viewer.dataSources.add(next);
if (destroyed || generation !== owner || signal?.aborted) {
remove(next);
return false;
}
remove(source);
source = next;
centers = nextCenters;
spheres = nextSpheres;
entityStorms = nextEntityStorms;
entityIds = nextEntityIds;
counts = nextCounts;
horizonStorms = nextHorizonStorms;
syncHorizonListener();
labels.setSnapshot(nextLabels, selected);
select(selected);
return true;
} catch (error) {
remove(next);
if (signal?.aborted || generation !== owner || destroyed) return false;
throw error;
const sphere = sphereFromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
}
if (destroyed || signal?.aborted) return false;
centers = nextCenters;
forecasts = nextForecasts;
spheres = nextSpheres;
itemStorms = nextItemStorms;
counts = nextCounts;
itemCount = nextItemStorms.size;
committed = true;
lines.set(nextLines);
cones.set(nextCones);
// Every commit redraws the points, an empty advisory included.
drawPoints();
labels.setSnapshot(nextLabels, selected);
return true;
},
setSelection: select,
ownsPickId(id) {
return source !== null && typeof id === 'string' && entityIds.has(id);
return committed && typeof id === 'string' && itemStorms.has(id);
},
pickStorm(picked) {
// Cesium Entity picks carry the exact entity in `id`. IDs/prefixes alone
// cannot establish ownership, especially after an advisory replacement.
const entity = picked?.id;
return source && entity && typeof entity === 'object'
? entityStorms.get(entity) || null
: null;
/**
* The storm a click's draw hit (`Hit`, query.d.ts) belongs to: an item
* of these sets in the advisory drawn now, never an id from another.
*/
pickStorm(hit) {
if (!committed || !hit || hit.surface) return null;
if (!setIds.has(hit.set)) return null;
return itemStorms.get(hit.id) ?? null;
},
getFocusSphere(id) {
return spheres.get(id) || null;
},
clear() {
++generation;
horizonStorms = [];
syncHorizonListener();
pointOccluder = null;
sphereOccluder = null;
remove(source);
source = null;
committed = false;
if (!destroyed) {
points.clear();
lines.clear();
cones.clear();
}
labels.clear();
centers.clear();
spheres.clear();
entityStorms = new WeakMap();
entityIds.clear();
centers = new Map();
forecasts = [];
spheres = new Map();
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
render();
},
destroy() {
if (destroyed) return;
this.clear();
destroyed = true;
points.dispose();
lines.dispose();
cones.dispose();
},
getDiagnostics() {
return {
...counts,
dataSources: Number(!!source),
entities: source?.entities.values.length || 0,
// One display: the committed advisory's sets, and the items in them.
dataSources: Number(committed),
entities: itemCount,
selectedId: selected,
timerActive: false,
};
+286 -502
View File
@@ -1,8 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createCycloneRendering } from './rendering.js';
import { CYCLONE_OVERLAY_SOURCE_ID } from './labels.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { CYCLONE_SET_PREFIX, createCycloneRendering } from './rendering.js';
import {
CYCLONE_ACCENT,
CYCLONE_MARKER_PX,
CYCLONE_OVERLAY_SOURCE_ID,
CYCLONE_SELECTED_ACCENT,
} from './labels.js';
/** Records what the renderer publishes to the shared overlay host. */
function overlayRecorder() {
@@ -28,161 +35,40 @@ function overlayRecorder() {
};
}
function harness({ deferred = false } = {}) {
const sources = [],
completions = [],
pointOccluders = [],
sphereOccluders = [];
const listeners = new Set();
const visibility = {
points: new Map(),
spheres: new Map(),
pointCalls: [],
sphereCalls: [],
writes: 0,
};
const color = (value) => ({
value,
withAlpha: (alpha) => ({ value, alpha }),
});
const cesium = {
Color: {
fromCssColorString: color,
WHITE: color('white'),
BLACK: color('black'),
},
Cartesian2: class {
constructor(x, y) {
this.x = x;
this.y = y;
}
},
Cartesian3: {
ZERO: { x: 0, y: 0, z: 0 },
fromDegrees: (lon, lat, height) => ({ lon, lat, height }),
},
Ellipsoid: { WGS84: { minimumRadius: 6356752 } },
EllipsoidalOccluder: class {
constructor(ellipsoid, cameraPosition) {
this.ellipsoid = ellipsoid;
this.cameraPosition = cameraPosition;
pointOccluders.push(this);
}
isPointVisible(position) {
visibility.pointCalls.push(position);
return visibility.points.get(position) ?? true;
}
},
Occluder: class {
constructor(sphere, cameraPosition) {
this.sphere = sphere;
this.cameraPosition = cameraPosition;
sphereOccluders.push(this);
}
isBoundingSphereVisible(sphere) {
visibility.sphereCalls.push(sphere);
return visibility.spheres.get(sphere) ?? true;
}
},
PolygonHierarchy: class {
constructor(positions, holes = []) {
this.positions = positions;
this.holes = holes;
}
},
BoundingSphere: class {
constructor(center, radius) {
this.center = center;
this.radius = radius;
}
static fromPoints(points) {
return { points, radius: 10 };
}
},
LabelStyle: { FILL_AND_OUTLINE: 1 },
HorizontalOrigin: { LEFT: 1 },
ArcType: { GEODESIC: 1 },
HeightReference: Cesium.HeightReference,
ClassificationType: Cesium.ClassificationType,
DistanceDisplayCondition: Cesium.DistanceDisplayCondition,
CustomDataSource: class {
constructor() {
const values = [];
this.entities = {
values,
add: (value) => {
let show = true;
Object.defineProperty(value, 'show', {
get: () => show,
set: (next) => {
show = next;
visibility.writes++;
},
});
values.push(value);
return value;
},
removeAll: () => {
values.length = 0;
},
};
}
},
};
let renders = 0;
/** A rendering on a viewer bound to a fake draw port. */
function harness() {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const overlay = overlayRecorder();
const viewer = {
camera: { positionWC: { x: 6378487, y: 0, z: 0 } },
scene: {
requestRender: () => renders++,
preRender: {
addEventListener(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
},
},
dataSources: {
add(value) {
if (deferred)
return new Promise((resolve) =>
completions.push(() => {
sources.push(value);
resolve(value);
}),
);
sources.push(value);
return Promise.resolve(value);
},
remove(value) {
const i = sources.indexOf(value);
if (i >= 0) sources.splice(i, 1);
},
},
};
return {
rendering: createCycloneRendering({
viewer,
cesium,
overlayHost: overlay.host,
}),
overlay,
sources,
completions,
const rendering = createCycloneRendering({
viewer,
cesium,
visibility,
pointOccluders,
sphereOccluders,
listeners,
frame() {
for (const listener of listeners) listener();
overlayHost: overlay.host,
});
const sets = {};
for (const kind of ['points', 'lines', 'cones'])
sets[kind] = [...draw.sets.values()].find((record) =>
record.spec.id.endsWith(`:${kind}`),
);
return {
viewer,
draw,
unbind,
overlay,
rendering,
sets,
/** Every item drawn now, across the rendering's sets. */
items() {
return Object.values(sets).flatMap((record) => [
...record.items.values(),
]);
},
get renders() {
return renders;
/** A click's draw hit on the item `id`, in the set of `kind`. */
hit(kind, id) {
return { set: sets[kind].spec.id, id, surface: false };
},
};
}
const storm = () => ({
id: 'ep152026',
name: 'Fifteen-E',
@@ -191,6 +77,7 @@ const storm = () => ({
geometryStatus: 'current',
position: { longitude: 179, latitude: 15 },
forecastPoints: [
{ position: { longitude: 179, latitude: 15 }, tauHours: 0 },
{ position: { longitude: -179, latitude: 16 }, tauHours: 12 },
],
track: {
@@ -231,301 +118,94 @@ const storm = () => ({
},
});
test('horizon culling updates only changed entities and keeps selection independent', async () => {
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near' }],
test('each rendering draws into its own point, line and cone sets', () => {
const a = harness();
const { sets } = a;
assert.match(sets.points.spec.id, new RegExp(`^${CYCLONE_SET_PREFIX}:\\d+:`));
assert.equal(sets.points.kind, 'points');
assert.equal(sets.points.spec.horizonCull, true);
assert.equal(sets.points.spec.clampTo, 'both');
assert.equal(sets.lines.kind, 'lines');
assert.equal(sets.lines.spec.clampTo, 'both');
assert.equal(sets.cones.kind, 'shapes');
assert.equal(sets.cones.spec.clampTo, 'both');
// A second rendering on the same renderer is a separate display.
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const first = createCycloneRendering({
viewer,
overlayHost: overlayRecorder().host,
});
const entities = h.sources[0].entities.values;
const far = entities.filter((e) => e.id.startsWith('cyclone:ep152026:'));
const near = entities.filter((e) => e.id.startsWith('cyclone:near:'));
const forecast = far.find((e) => e.id.endsWith('forecast:0'));
const sphere = h.rendering.getFocusSphere('ep152026');
for (const entity of far)
if (entity.position) h.visibility.points.set(entity.position, false);
h.visibility.spheres.set(sphere, false);
h.rendering.setSelection('ep152026');
const publishes = h.overlay.publishes;
const before = h.renders;
h.frame();
assert.ok(far.every((e) => e.show === false));
assert.ok(near.every((e) => e.show === true));
assert.equal(
h.overlay.entry('lead:ep152026:12').position,
forecast.position,
'the host culls labels at the same anchors the points use',
);
assert.equal(h.overlay.publishes, publishes, 'culling never republishes');
assert.equal(h.renders, before + 1);
assert.equal(h.visibility.writes, far.length);
assert.equal(h.visibility.pointCalls.length, 4);
assert.deepEqual(h.visibility.sphereCalls, [
sphere,
h.rendering.getFocusSphere('near'),
]);
h.frame();
assert.equal(h.renders, before + 1);
assert.equal(h.visibility.writes, far.length);
// A visible portion of the extent keeps all tracks/cones shown even when
// the centre and an individual forecast point remain beyond the horizon.
h.visibility.spheres.set(sphere, true);
h.viewer.camera.positionWC = { x: 0, y: 6378487, z: 0 };
h.frame();
assert.ok(far.filter((e) => !e.position).every((e) => e.show));
assert.ok(far.filter((e) => e.position).every((e) => !e.show));
assert.equal(h.renders, before + 2);
assert.equal(h.pointOccluders.length, 1);
assert.equal(h.sphereOccluders.length, 1);
assert.equal(h.pointOccluders[0].ellipsoid, h.cesium.Ellipsoid.WGS84);
assert.equal(h.pointOccluders[0].cameraPosition, h.viewer.camera.positionWC);
assert.equal(h.sphereOccluders[0].cameraPosition, h.viewer.camera.positionWC);
h.rendering.setSelection('near');
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
assert.equal(
h.overlay.entry('lead:near:12').position,
near.find((e) => e.id.endsWith('forecast:0')).position,
);
h.visibility.points.set(forecast.position, true);
const beforeReveal = h.renders;
const revealPublishes = h.overlay.publishes;
h.frame();
assert.equal(forecast.show, true);
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
assert.equal(h.overlay.publishes, revealPublishes);
assert.equal(far[0].show, false);
assert.equal(h.renders, beforeReveal + 1);
h.rendering.destroy();
});
test('horizon listener follows committed nonempty snapshots and clear/destroy', async () => {
const h = harness();
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [] });
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
const old = [...h.sources[0].entities.values];
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
h.frame();
assert.ok(
h.visibility.pointCalls.every((p) => !old.some((e) => e.position === p)),
);
await h.rendering.setSnapshot({ storms: [] });
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
assert.equal(h.listeners.size, 0);
const before = h.renders;
h.frame();
assert.equal(h.renders, before);
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
h.rendering.destroy();
h.rendering.destroy();
assert.equal(h.listeners.size, 0);
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false);
assert.equal(h.listeners.size, 0);
});
test('late asynchronous additions never restore a cleared or destroyed horizon listener', async () => {
for (const method of ['clear', 'destroy']) {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 0);
h.rendering[method]();
h.completions.shift()();
assert.equal(await pending, false);
assert.equal(h.listeners.size, 0);
}
});
test('real Cesium culls far storms and retains partially visible extents with either globe visibility', async () => {
for (const globeShow of [true, false]) {
const sources = [];
const viewer = {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 350) },
scene: {
globe: { show: globeShow },
preRender: new Cesium.Event(),
requestRender() {},
},
dataSources: {
async add(source) {
sources.push(source);
},
remove() {},
},
};
const overlay = overlayRecorder();
const rendering = createCycloneRendering({
viewer,
cesium: Cesium,
overlayHost: overlay.host,
});
const at = (id, longitude) => ({
...storm(),
id,
position: { longitude, latitude: 0 },
forecastPoints: [{ position: { longitude, latitude: 0 }, tauHours: 24 }],
track: {
type: 'LineString',
coordinates: [
[longitude, 0],
[longitude, 1],
],
},
cone: {
type: 'Polygon',
coordinates: [
[
[longitude, 0],
[longitude + 1, 0],
[longitude, 1],
[longitude, 0],
],
],
},
});
await rendering.setSnapshot({
storms: [at('near', 0), at('far', 180), at('limb', 5)],
});
rendering.setSelection('near');
viewer.scene.preRender.raiseEvent();
const entities = sources[0].entities.values;
for (const entity of entities.filter((e) => e.position)) {
assert.equal(
entity.point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
assert.equal(entity.point.disableDepthTestDistance.getValue(), Infinity);
assert.equal(entity.label, undefined, 'no Cesium label graphics');
const published = overlay.entry(
entity.id.includes(':forecast:')
? `lead:${entity.id.split(':')[1]}:24`
: `storm:${entity.id.split(':')[1]}`,
);
if (entity.id.startsWith('cyclone:near:')) {
assert.ok(
Cesium.Cartesian3.equals(
published.position,
entity.position.getValue(),
),
);
assert.equal(published.horizonCull, true);
}
if (entity.id === 'cyclone:near:forecast:0')
assert.equal(published.maxDistance, 4_000_000);
}
assert.ok(
entities
.filter((e) => e.id.startsWith('cyclone:near:'))
.every((e) => e.show),
);
assert.ok(
entities
.filter((e) => e.id.startsWith('cyclone:far:'))
.every((e) => !e.show),
);
const limb = entities.filter((e) => e.id.startsWith('cyclone:limb:'));
assert.ok(limb.filter((e) => e.position).every((e) => !e.show));
assert.ok(limb.filter((e) => !e.position).every((e) => e.show));
rendering.destroy();
assert.equal(viewer.scene.preRender.numberOfListeners, 0);
}
});
test('picking accepts exact current owned entities, never prefixes or superseded identities', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const oldEntities = [...h.sources[0].entities.values];
assert.equal(oldEntities.length, 8);
for (const entity of oldEntities) {
assert.equal(h.rendering.pickStorm({ id: entity }), 'ep152026', entity.id);
assert.equal(h.rendering.ownsPickId(entity.id), true);
assert.equal(
h.rendering.pickStorm({ id: { ...entity } }),
null,
'copied ID is not ownership',
);
assert.equal(
h.rendering.pickStorm({ id: entity.id }),
null,
'string prefix is not ownership',
);
}
assert.equal(h.rendering.pickStorm(undefined), null);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false);
await h.rendering.setSnapshot({ storms: [storm()] });
for (const entity of oldEntities)
assert.equal(h.rendering.pickStorm({ id: entity }), null);
const current = h.sources[0].entities.values[0];
assert.equal(h.rendering.pickStorm({ id: current }), 'ep152026');
h.rendering.clear();
assert.equal(h.rendering.pickStorm({ id: current }), null);
assert.equal(h.rendering.ownsPickId(current.id), false);
h.rendering.destroy();
});
test('registry IDs switch only when the next coherent data source commits', async () => {
const h = harness({ deferred: true });
const first = h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
h.completions.shift()();
await first;
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true);
const next = h.rendering.setSnapshot({
storms: [{ ...storm(), id: 'ep162026' }],
const second = createCycloneRendering({
viewer,
overlayHost: overlayRecorder().host,
});
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
h.completions.shift()();
await next;
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), true);
h.rendering.destroy();
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
assert.equal(draw.sets.size, 6);
second.destroy();
assert.equal(
[...draw.sets.values()].filter((record) => !record.disposed).length,
3,
);
first.destroy();
a.rendering.destroy();
});
test('static entities preserve polygon parts, holes and geographic seam coordinates', async () => {
test('advisory geometry keeps polygon parts, holes and geographic seam coordinates', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const entities = h.sources[0].entities.values;
const cones = entities.filter((e) => e.polygon);
assert.equal(cones.length, 2);
assert.equal(cones[0].polygon.hierarchy.holes.length, 1);
assert.equal(cones[0].polygon.hierarchy.positions[1].lon, -178);
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), true);
const cones = [...h.sets.cones.items.values()];
assert.deepEqual(
cones.map((cone) => cone.id),
['cyclone:ep152026:cone:0', 'cyclone:ep152026:cone:1'],
);
assert.equal(cones[0].geometry.kind, 'polygon');
assert.equal(cones[0].geometry.rings.length, 2, 'the hole stays');
assert.equal(cones[0].geometry.rings[0][1].lon, -178);
for (const cone of cones) {
assert.equal(
cone.polygon.classificationType,
h.cesium.ClassificationType.BOTH,
);
assert.equal(cone.polygon.height, undefined);
assert.equal(cone.polygon.extrudedHeight, undefined);
assert.equal(cone.polygon.outline, undefined);
assert.equal(cone.height, 'clampGround');
assert.equal(cone.fill, 'rgba(127,230,237,0.16)');
assert.equal(cone.outline, undefined, 'outlines are lines of their own');
assert.equal(cone.extrudedHeight, undefined);
}
const outlines = entities.filter((e) => e.id.includes(':outline:'));
const lines = [...h.sets.lines.items.values()];
const outlines = lines.filter((line) => line.id.includes(':outline:'));
assert.equal(outlines.length, 3);
assert.deepEqual(
outlines.map((e) => e.polyline.positions.map((p) => [p.lon, p.lat])),
storm().cone.coordinates.flat(),
outlines.map((line) => line.positions),
storm()
.cone.coordinates.flat()
.map((ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0))),
'lines take ECEF',
);
for (const outline of outlines) {
assert.deepEqual(outline.polyline.material, {
value: '#7fe6ed',
alpha: 0.55,
assert.equal(outline.widthPx, 1);
assert.deepEqual(outline.style, {
kind: 'solid',
color: 'rgba(127,230,237,0.55)',
});
}
for (const { polyline } of entities.filter((e) => e.polyline)) {
assert.equal(polyline.clampToGround, true);
assert.equal(polyline.classificationType, h.cesium.ClassificationType.BOTH);
assert.ok(polyline.positions.every((p) => p.height === 0));
}
assert.equal(
entities.find((e) => e.polyline).polyline.positions[1].lon,
-179,
const track = lines.find((line) => line.id === 'cyclone:ep152026:track:0');
assert.equal(track.widthPx, 2.5);
assert.deepEqual(track.style, { kind: 'solid', color: CYCLONE_ACCENT });
assert.deepEqual(track.positions[1], fromDegrees(-179, 16, 0));
for (const line of lines) assert.equal(line.mode, 'draped');
const points = [...h.sets.points.items.values()];
assert.deepEqual(
points.map((point) => point.id),
['cyclone:ep152026:center', 'cyclone:ep152026:forecast:1'],
'the zero-hour forecast is the center',
);
for (const point of points) {
assert.equal(point.height, 'clampGround');
assert.equal(point.disableDepthTest, Number.POSITIVE_INFINITY);
assert.deepEqual(point.outlineColor, [0, 0, 0, 1]);
}
assert.deepEqual(points[1].color, [1, 1, 1, 1]);
assert.equal(points[1].pixelSize, CYCLONE_MARKER_PX.forecast);
assert.equal(points[0].pixelSize, CYCLONE_MARKER_PX.storm);
assert.equal(points[1].outlineWidth, 1);
assert.equal(points[0].outlineWidth, 2);
assert.deepEqual(h.rendering.getDiagnostics(), {
storms: 1,
tracks: 1,
@@ -536,17 +216,111 @@ test('static entities preserve polygon parts, holes and geographic seam coordina
selectedId: null,
timerActive: false,
});
h.rendering.setSelection('ep152026');
assert.equal(
h.overlay.entry('lead:ep152026:12').position,
entities.find((e) => e.id.endsWith('forecast:0')).position,
);
assert.ok(entities.every((e) => e.label === undefined));
assert.ok(h.rendering.getFocusSphere('ep152026').radius >= 500000);
h.rendering.destroy();
assert.equal(h.sources.length, 0);
assert.ok(Object.values(h.sets).every((record) => record.disposed));
assert.equal(h.rendering.getDiagnostics().entities, 0);
});
test('selection redraws the centers and labels; an unchanged one is quiet', async () => {
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near', name: 'Near' }],
});
const center = (id) => h.sets.points.items.get(`cyclone:${id}:center`);
assert.equal(center('near').pixelSize, 9);
h.rendering.setSelection('near');
assert.equal(center('near').pixelSize, 12);
assert.equal(center('near').color, CYCLONE_SELECTED_ACCENT);
assert.equal(center('ep152026').pixelSize, 9);
assert.equal(center('ep152026').color, CYCLONE_ACCENT);
assert.ok(h.sets.points.items.has('cyclone:near:forecast:1'));
const pointWrites = h.sets.points.writes;
const lineWrites = h.sets.lines.writes;
const publishes = h.overlay.publishes;
h.rendering.setSelection('near');
assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet');
assert.equal(h.sets.points.writes, pointWrites, 'points are not redrawn');
assert.equal(h.sets.lines.writes, lineWrites, 'tracks are not redrawn');
h.rendering.destroy();
});
test('a click names a storm only through a current item of its own sets', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const items = h.items();
assert.equal(items.length, 8);
for (const kind of ['points', 'lines', 'cones'])
for (const id of h.sets[kind].items.keys()) {
assert.equal(h.rendering.pickStorm(h.hit(kind, id)), 'ep152026', id);
assert.equal(h.rendering.ownsPickId(id), true);
assert.equal(
h.rendering.pickStorm({ set: 'other:points', id, surface: false }),
null,
"another layer's set is not ownership",
);
}
assert.equal(
h.rendering.pickStorm({
...h.hit('points', 'cyclone:ep152026:center'),
surface: true,
}),
null,
);
assert.equal(h.rendering.pickStorm(undefined), null);
assert.equal(h.rendering.pickStorm(null), null);
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026')),
null,
'a prefix is not an item',
);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false);
// A newer advisory without the storm drops its ids at once.
await h.rendering.setSnapshot({ storms: [{ ...storm(), id: 'ep162026' }] });
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026:center')),
null,
);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')),
'ep162026',
);
h.rendering.clear();
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')),
null,
);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
h.rendering.destroy();
});
test('focus spheres bound the advisory and never shrink below a region', async () => {
const h = harness();
const statusOnly = {
...storm(),
id: 'status',
geometryStatus: 'pending',
};
await h.rendering.setSnapshot({ storms: [storm(), statusOnly] });
const at = ([lon, lat]) => fromDegrees(lon, lat, 0);
const expected = sphereFromPoints([
at([179, 15]),
...storm().track.coordinates[0].map(at),
...storm().cone.coordinates[0][0].map(at),
...storm().cone.coordinates[1][0].map(at),
at([-179, 16]),
]);
const sphere = h.rendering.getFocusSphere('ep152026');
assert.deepEqual(sphere.center, expected.center);
assert.equal(sphere.radius, Math.max(expected.radius, 500_000));
assert.equal(h.rendering.getFocusSphere('status').radius, 500_000);
assert.equal(h.rendering.getFocusSphere('missing'), null);
h.rendering.clear();
assert.equal(h.rendering.getFocusSphere('ep152026'), null);
h.rendering.destroy();
});
test('pending or mismatched advisory geometry never renders even when supplied', async () => {
for (const changed of [
{ geometryStatus: 'pending' },
@@ -554,60 +328,76 @@ test('pending or mismatched advisory geometry never renders even when supplied',
]) {
const h = harness();
await h.rendering.setSnapshot({ storms: [{ ...storm(), ...changed }] });
assert.equal(h.sources[0].entities.values.length, 1);
assert.deepEqual(
h.items().map((item) => item.id),
['cyclone:ep152026:center'],
);
assert.equal(h.rendering.getDiagnostics().tracks, 0);
h.rendering.destroy();
}
});
test('a data-source add settling after disable is removed, without a new owner', async () => {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
h.completions.shift()();
assert.equal(await pending, false);
assert.equal(h.sources.length, 0);
assert.equal(h.rendering.getDiagnostics().dataSources, 0);
});
test('superseded asynchronous additions cannot replace newer geometry', async () => {
const h = harness({ deferred: true });
const old = h.rendering.setSnapshot({ storms: [storm()] });
const latest = h.rendering.setSnapshot({ storms: [] });
h.completions[1]();
assert.equal(await latest, true);
h.completions[0]();
assert.equal(await old, false);
assert.equal(h.sources.length, 1);
assert.equal(h.rendering.getDiagnostics().storms, 0);
h.rendering.destroy();
});
test('aborting a pending add retains the prior complete source', async () => {
const h = harness({ deferred: true });
const initial = h.rendering.setSnapshot({ storms: [storm()] });
h.completions.shift()();
await initial;
test('an aborted or destroyed update keeps what is drawn', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const controller = new AbortController();
const update = h.rendering.setSnapshot(
{ storms: [] },
{ signal: controller.signal },
);
controller.abort();
h.completions.shift()();
assert.equal(await update, false);
assert.equal(h.sources.length, 1);
await assert.rejects(
h.rendering.setSnapshot({ storms: [] }, { signal: controller.signal }),
);
assert.equal(h.items().length, 8);
assert.equal(h.rendering.getDiagnostics().storms, 1);
h.rendering.destroy();
h.rendering.destroy();
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false);
assert.ok(Object.values(h.sets).every((record) => record.disposed));
});
test('an empty advisory after a full one leaves nothing drawn', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.setSelection('ep152026');
assert.equal(await h.rendering.setSnapshot({ storms: [] }), true);
assert.deepEqual(h.items(), []);
assert.equal(h.rendering.getDiagnostics().entities, 0);
h.rendering.destroy();
h.rendering.setSelection('ep152026');
});
test('clear empties the sets and a later advisory draws again', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.setSelection('ep152026');
h.rendering.clear();
assert.equal(h.items().length, 0);
assert.ok(Object.values(h.sets).every((record) => !record.disposed));
assert.deepEqual(h.rendering.getDiagnostics(), {
storms: 0,
tracks: 0,
cones: 0,
forecastPoints: 0,
dataSources: 0,
entities: 0,
selectedId: null,
timerActive: false,
});
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.items().length, 8);
assert.equal(
h.sets.points.items.get('cyclone:ep152026:center').pixelSize,
9,
'clear drops the selection',
);
h.rendering.destroy();
});
test('labels publish committed anchors to the shared overlay and follow selection and clear', async () => {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near', name: 'Near' }],
});
assert.equal(h.overlay.calls.length, 0, 'nothing publishes before commit');
h.completions.shift()();
assert.equal(await pending, true);
const entities = h.sources[0].entities.values;
const center = (id) => entities.find((e) => e.id === `cyclone:${id}:center`);
const anchor = (item) => fromDegrees(item.pos.lon, item.pos.lat, 0);
const point = (id) => h.sets.points.items.get(id);
assert.deepEqual(
h.overlay.calls
.slice(0, 2)
@@ -623,24 +413,27 @@ test('labels publish committed anchors to the shared overlay and follow selectio
'no selection, no lead-hour labels',
);
assert.equal(h.overlay.entry('storm:near').title, 'Near');
assert.equal(h.overlay.entry('storm:near').position, center('near').position);
assert.deepEqual(
h.overlay.entry('storm:near').position,
anchor(point('cyclone:near:center')),
'labels sit at the anchors the points use',
);
assert.equal(h.overlay.entry('storm:near').horizonCull, true);
h.rendering.setSelection('near');
assert.equal(center('near').point.pixelSize, 12);
assert.equal(center('ep152026').point.pixelSize, 9);
assert.equal(h.overlay.entry('storm:near').variant, 'selected');
assert.equal(h.overlay.entry('storm:ep152026').variant, 'card');
assert.ok(h.overlay.entry('lead:near:12'));
const publishes = h.overlay.publishes;
h.rendering.setSelection('near');
assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet');
assert.deepEqual(
h.overlay.entry('lead:near:12').position,
anchor(point('cyclone:near:forecast:1')),
);
assert.equal(h.overlay.entry('lead:near:12').maxDistance, 4_000_000);
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
// A refresh republishes the new anchors with the retained selection.
const refresh = h.rendering.setSnapshot({
await h.rendering.setSnapshot({
storms: [{ ...storm(), id: 'near', name: 'Near' }],
});
h.completions.shift()();
await refresh;
assert.deepEqual(
h.overlay.published().map((entry) => [entry.id, entry.variant]),
[
@@ -648,22 +441,13 @@ test('labels publish committed anchors to the shared overlay and follow selectio
['lead:near:12', 'card'],
],
);
assert.equal(
h.overlay.entry('storm:near').position,
h.sources[0].entities.values[0].position,
);
// A superseded addition never publishes, and clear hides the source.
const stale = h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
const afterClear = h.overlay.calls.slice(-2);
assert.deepEqual(afterClear, [
{ kind: 'clear', source: CYCLONE_OVERLAY_SOURCE_ID },
{ kind: 'visible', source: CYCLONE_OVERLAY_SOURCE_ID, visible: false },
]);
h.completions.shift()();
assert.equal(await stale, false);
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
h.rendering.destroy();
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
});
+338 -283
View File
@@ -16,16 +16,12 @@
* route.
*/
import * as Cesium from 'cesium';
import { roadLabel } from '../../data/routeSteps.js';
import {
t,
msg,
formatNumber,
getLocale,
translateKnown,
} from '../../i18n/index.js';
import { pointerOwnerName } from '../../data/pointerOwnerNames.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf } from '../../render/rendererOf.js';
import { t, msg, formatNumber, getLocale } from '../../i18n/index.js';
import { inputFor } from '../../input/dispatcher.js';
import {
formatQuantity,
quantitySeparator,
@@ -39,6 +35,13 @@ export const DIRECTIONS_STEP_OVERLAY_SOURCE_OPTIONS = Object.freeze({
collisionCapacity: 0,
moving: false,
});
/** The A and B letters above the endpoint markers. */
export const DIRECTIONS_MARKER_OVERLAY_SOURCE_ID = 'directions-markers';
export const DIRECTIONS_MARKER_OVERLAY_SOURCE_OPTIONS = Object.freeze({
cohortLimit: 2,
collisionCapacity: 0,
moving: false,
});
/** Travel modes, keyed by the `/api/route` profile name. */
export const DIRECTIONS_MODES = Object.freeze({
@@ -68,10 +71,26 @@ export function presentRoutingFailure(error) {
/** Route colour — the annotation palette's cyan, so voice routes and Directions match. */
export const DIRECTIONS_ROUTE_COLOR = '#39d0ff';
const MARKER_A_COLOR = Cesium.Color.fromCssColorString('#5dff9f');
const MARKER_B_COLOR = Cesium.Color.fromCssColorString('#ff6b6b');
const STEP_COLOR = Cesium.Color.WHITE.withAlpha(0.95);
const STEP_OUTLINE = Cesium.Color.fromCssColorString(DIRECTIONS_ROUTE_COLOR);
const MARKER_A_CSS = '#5dff9f';
const MARKER_B_CSS = '#ff6b6b';
const MARKER_A_COLOR = hexColor(MARKER_A_CSS);
const MARKER_B_COLOR = hexColor(MARKER_B_CSS);
const MARKER_OUTLINE = [0, 0, 0, 1];
const STEP_COLOR = [1, 1, 1, 0.95];
const STEP_OUTLINE = hexColor(DIRECTIONS_ROUTE_COLOR);
/**
* The route's flowing dashes, as the voice route annotation draws them:
* 64 cells along the whole route, each lit for its first 46%, running
* toward B at 0.55 cells a second.
*/
const ROUTE_STYLE = Object.freeze({
kind: 'flow',
color: hexColor(DIRECTIONS_ROUTE_COLOR, 0.95),
repeat: 64,
duty: 0.46,
speed: 0.55,
});
const ROUTE_WIDTH_PX = 9;
const STEP_PIXEL_SIZE = 8;
const STEP_SELECTED_PIXEL_SIZE = 13;
/** Route request timeout (ms) — the proxy itself gives OSRM 12 s. */
@@ -493,46 +512,6 @@ export function directionsRowControls(state) {
};
}
/**
* Plain names for the tools that can be holding the pointer, and how to leave
* each one. A tool missing from here still gets a usable sentence from its id.
*/
export const POINTER_TOOL_EXITS = Object.freeze({
draw: Object.freeze({
name: msg('Draw'),
leave: msg('press Escape twice to leave Draw'),
}),
});
/**
* What to say when a globe click cannot be armed because something else owns
* the pointer.
*
* The claim failing used to be silent: the chip simply did not light and the
* operator was left to guess which of the open tools was eating the click
* (owner field test — he thought Directions was broken). So the message names
* the tool and says how to put it down. Pure.
* @param {string|null} owner Current pointer-owner id.
* @param {'a'|'b'} which Endpoint that was being armed.
* @returns {string|null} Toast text, or null when nothing holds the pointer.
*/
export function pointerBlockedMessage(owner, which) {
const id = typeof owner === 'string' ? owner.trim() : '';
if (!id || id === DIRECTIONS_POINTER_OWNER) return null;
const endpoint = which === 'b' ? 'B' : 'A';
const known = POINTER_TOOL_EXITS[id];
if (!known)
return t('{name} is active — turn {name} off, then set {endpoint}', {
name: translateKnown(pointerOwnerName(id)),
endpoint,
});
return t('{name} is active — {leave}, then set {endpoint}', {
name: t(known.name),
leave: t(known.leave),
endpoint,
});
}
/**
* Which maneuvers get a dot on the globe: every one except departure and
* arrival, which the A and B markers already stand for.
@@ -649,29 +628,8 @@ export function stepIndexAtDistance(steps, traveledM) {
* @returns {object}
*/
export function directionsStats(state) {
const {
mode,
a,
b,
status,
error,
route,
lastUpdate,
armed,
pointerBlocked,
} = state;
const { mode, a, b, status, error, route, lastUpdate, armed } = state;
const source = 'OSM routing'; // English in layer state; the layer row translates it
if (pointerBlocked) {
return {
count: route?.steps.length || 0,
lastUpdate,
error: msg(
'Another map tool is using clicks — close it, then SET A again',
),
status: 'empty',
source,
};
}
if (status === 'routing') {
return {
count: 0,
@@ -766,7 +724,7 @@ export function directionsStepCopy(steps, index) {
/**
* Shared-host card for the selected maneuver.
* @param {number} index
* @param {Cesium.Cartesian3} position
* @param {{x: number, y: number, z: number}} position
* @param {{title:string, details:string[]}} copy
* @returns {object|null}
*/
@@ -795,6 +753,32 @@ export function createDirectionsStepOverlayEntry(index, position, copy) {
};
}
/**
* The letter above one endpoint marker, as a world-overlay label. It is
* protected, like the step card, so it never yields to ambient labels.
* @param {'A'|'B'} letter
* @param {{x: number, y: number, z: number}|(() => {x: number, y: number, z: number}|null)} position
* @param {string} accent CSS colour of the marker.
*/
export function createDirectionsMarkerOverlayEntry(letter, position, accent) {
return {
id: `directions-marker-${letter.toLowerCase()}`,
position,
variant: 'label',
title: letter,
accent,
protected: true,
priority: Number.MAX_SAFE_INTEGER - 1,
interactive: false,
gapPx: 13,
verticalOnly: true,
placement: 'above',
edgeFade: 'keyhole',
horizonCull: true,
terrainOcclusion: false,
};
}
/**
* Build the `/api/route` URL for two endpoints.
* @param {string} mode car | foot | bike
@@ -849,13 +833,16 @@ export function normalizeRoutePayload(payload, mode) {
};
}
/** Directions layers made, so each one's draw sets have ids of their own. */
let _instances = 0;
/**
* Construct one Directions layer over the application scene owners.
*
* Each catalog builds its own, so two applications on a page never share the
* route, the markers, the pointer claim or the flight this layer owns. The
* shared services are injected, which is what keeps this module's own imports
* down to Cesium and the pure step formatter.
* down to the renderer's draw port, geodesy and the pure step formatter.
* @param {{services: object, source: {getRoute: Function}}} options
* @returns {object} The layer module the data manager registers.
*/
@@ -880,6 +867,10 @@ export function createDirectionsLayer({ services, source }) {
let _mode = DEFAULT_DIRECTIONS_MODE;
/** @type {null|'a'|'b'} which endpoint the next globe click places */
let _armed = null;
/** Surface heights of clicked endpoints, by point. */
const _surfaceHeights = new WeakMap();
/** Endpoints whose floor cell resolve has settled, height or not. */
const _floorSettled = new WeakSet();
/** @type {{lat:number, lon:number}|null} */
let _a = null;
/** @type {{lat:number, lon:number}|null} */
@@ -892,17 +883,25 @@ export function createDirectionsLayer({ services, source }) {
let _routeSeq = 0;
let _routeAbort = null;
let _lastUpdate = null;
let _markerA = null;
let _markerB = null;
let _routeEntity = null;
let _stepPoints = null;
/**
* The layer's draw sets on its viewer's renderer (`drawOf`), made at
* `init`: the A and B markers, the maneuver dots and the route.
* @type {{markers: object, steps: object, route: object}|null}
*/
let _sets = null;
/** Whether a route is drawn. */
let _routeDrawn = false;
/**
* Each maneuver dot drawn, by step index: where it stands (once its ground
* cell has answered) and whether it shows.
* @type {Map<number, {pos: {x: number, y: number, z: number}, show: boolean}>}
*/
const _stepDots = new Map();
let _selectedStep = null;
let _clickHandler = null;
let _clickSubscription = null;
let _renderHeld = false;
let _rowControlsListener = null;
let _dataManager = null;
/** Set when arming failed because another tool holds the pointer. */
let _pointerBlocked = false;
/**
* What `claimPointer` handed back for the claim this layer currently holds, or
* null. Held rather than re-derived so the release names THIS claim: a claim
@@ -929,6 +928,15 @@ export function createDirectionsLayer({ services, source }) {
// Internals
// ---------------------------------------------------------------------------
/** Let the layer's draw sets go. */
function detachSets() {
if (!_sets) return;
for (const set of Object.values(_sets)) set.dispose();
_sets = null;
_routeDrawn = false;
_stepDots.clear();
}
function state() {
return {
enabled: _enabled,
@@ -942,7 +950,6 @@ export function createDirectionsLayer({ services, source }) {
lastUpdate: _lastUpdate,
selectedStep: _selectedStep,
flightStep: _flightStep,
pointerBlocked: _pointerBlocked,
};
}
@@ -956,7 +963,7 @@ export function createDirectionsLayer({ services, source }) {
}
function syncRenderHold() {
const shouldHold = _enabled && Boolean(_routeEntity);
const shouldHold = _enabled && _routeDrawn;
if (shouldHold && !_renderHeld) {
services.render.holdContinuousRender('directions');
_renderHeld = true;
@@ -966,69 +973,111 @@ export function createDirectionsLayer({ services, source }) {
}
}
function pickGround(screenPosition) {
const cartesian = services.scenePick.pickGroundPosition(
_viewer,
screenPosition,
);
if (!cartesian) return null;
const carto = Cesium.Cartographic.fromCartesian(cartesian);
/**
* Where a click lands on the ground, from the click's own ground pick (the
* rendered surface, else the ellipsoid; null over the sky).
* @param {{ground: () => ({x: number, y: number, z: number}|null)}} event
*/
function pickGround(event) {
const ecef = event.ground?.();
if (!ecef) return null;
const carto = toLonLatH(ecef);
if (!carto) return null;
const point = { lat: carto.lat, lon: carto.lon };
// A pick at the ellipsoid itself is the fallback when the drawn surface
// gave no position; the floor path places that letter instead.
if (Math.abs(carto.height) > 0.01) _surfaceHeights.set(point, carto.height);
return point;
}
/** An endpoint marker: a dot on the ground, drawn over everything. */
function markerItem(letter, point, color) {
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
id: `directions:marker:${letter}`,
pos: { lon: point.lon, lat: point.lat, height: 0 },
height: 'clampGround',
pixelSize: 14,
color,
outlineColor: MARKER_OUTLINE,
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
};
}
function markerEntity(letter, point, color) {
return _viewer.entities.add({
id: `directions:marker:${letter}`,
position: Cesium.Cartesian3.fromDegrees(point.lon, point.lat, 0),
point: {
pixelSize: 14,
color,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: letter,
font: 'bold 13px "JetBrains Mono", "SF Mono", monospace',
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 3,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
pixelOffset: new Cesium.Cartesian2(0, -20),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
/**
* Where a marker's letter hangs: over the surface the user clicked, or for an
* endpoint placed without a click, over the shared ground floor once its cell
* is known. Until then the letter stays hidden, as the step dots do, rather
* than hanging at the ellipsoid far below its point; only a cell that settled
* with no height falls back to the ellipsoid. Resolved once.
*/
function markerLabelPosition(point) {
let position = null;
return () => {
if (position) return position;
const height =
_surfaceHeights.get(point) ??
services.ground.cachedGroundFloor(point.lat, point.lon);
if (!Number.isFinite(height) && !_floorSettled.has(point)) return null;
position = fromDegrees(
point.lon,
point.lat,
Number.isFinite(height) ? height : 0,
);
return position;
};
}
function removeEntity(entity) {
if (entity && _viewer && !_viewer.isDestroyed?.())
_viewer.entities.remove(entity);
/** Publish the letters for whichever endpoints are placed. */
function publishMarkerLabels() {
const entries = [];
for (const [letter, point, accent] of [
['A', _a, MARKER_A_CSS],
['B', _b, MARKER_B_CSS],
])
if (point)
entries.push(
createDirectionsMarkerOverlayEntry(
letter,
markerLabelPosition(point),
accent,
),
);
_overlayHost.setEntries(
DIRECTIONS_MARKER_OVERLAY_SOURCE_ID,
entries,
DIRECTIONS_MARKER_OVERLAY_SOURCE_OPTIONS,
);
}
function placeMarker(letter, point) {
if (!_viewer) return;
if (letter === 'a') {
removeEntity(_markerA);
_markerA = markerEntity('A', point, MARKER_A_COLOR);
} else {
removeEntity(_markerB);
_markerB = markerEntity('B', point, MARKER_B_COLOR);
}
if (!_viewer || !_sets) return;
_sets.markers.upsert([
letter === 'a'
? markerItem('A', point, MARKER_A_COLOR)
: markerItem('B', point, MARKER_B_COLOR),
]);
publishMarkerLabels();
if (_surfaceHeights.has(point)) return;
// The letter appears when its floor cell lands, even under a still camera.
services.ground
.resolveGroundFloorCells([{ lat: point.lat, lon: point.lon }])
.catch(() => {})
.then(() => {
_floorSettled.add(point);
if (_viewer && (point === _a || point === _b))
services.render.governorRequestRender('directions-place');
});
}
function clearRouteGraphics() {
services.credits?.hideOsmCredit?.(_viewer, 'directions');
_clearStepSelection();
stopStepAnchoring();
removeEntity(_routeEntity);
_routeEntity = null;
_stepPoints?.removeAll();
_sets?.route.clear();
_routeDrawn = false;
_stepDots.clear();
_sets?.steps.clear();
syncRenderHold();
}
@@ -1047,31 +1096,28 @@ export function createDirectionsLayer({ services, source }) {
*/
function anchorStepPoints() {
_anchorTimer = null;
if (!_stepPoints || !_route || !_enabled) return;
if (!_sets || !_route || !_enabled) return;
const steps = _route.steps;
const pending = [];
let unresolved = 0;
for (const index of stepMarkerIndices(steps)) {
const step = steps[index];
const point = findStepPoint(index);
if (!point) continue;
const dot = _stepDots.get(index);
if (!dot) continue;
const height = stepMarkerHeightM(
services.ground.cachedGroundFloor(step.lat, step.lon),
services.ground.GROUND_FLOOR_LIFT_M,
);
if (height === null) {
unresolved += 1;
point.show = false;
dot.show = false;
pending.push({ lat: step.lat, lon: step.lon });
continue;
}
point.position = Cesium.Cartesian3.fromDegrees(
step.lon,
step.lat,
height,
);
point.show = true;
dot.pos = fromDegrees(step.lon, step.lat, height);
dot.show = true;
}
drawStepDots();
// A card already open on a step that has just been anchored moves with it.
if (_selectedStep !== null) refreshStepCard(_selectedStep);
services.render.governorRequestRender('directions-anchor');
@@ -1090,52 +1136,69 @@ export function createDirectionsLayer({ services, source }) {
_anchorTimer = setTimeout(anchorStepPoints, delay);
}
/** One maneuver dot as the steps set draws it. */
function stepDotItem(index, dot) {
return {
id: `directions:step:${index}`,
pos: dot.pos,
color: STEP_COLOR,
pixelSize:
index === _selectedStep ? STEP_SELECTED_PIXEL_SIZE : STEP_PIXEL_SIZE,
outlineColor: STEP_OUTLINE,
outlineWidth: 2,
show: dot.show,
// The shared ground floor is a coarse cell, and on the photoreal stack
// the rendered mesh can stand above it. Keeping the dot always visible
// is the same choice every other anchored sprite in the app makes.
disableDepthTest: Number.POSITIVE_INFINITY,
};
}
/** Draw the maneuver dots as they now are (moved and restyled in place). */
function drawStepDots(indices = _stepDots.keys()) {
if (!_sets) return;
const items = [];
for (const index of indices) {
const dot = _stepDots.get(index);
if (dot) items.push(stepDotItem(index, dot));
}
if (items.length) _sets.steps.upsert(items);
}
function drawRoute(route) {
clearRouteGraphics();
if (!_viewer) return;
services.annotations.ensureFlowFabricRegistered();
const positions = Cesium.Cartesian3.fromDegreesArray(route.geometry.flat());
_routeEntity = _viewer.entities.add({
id: 'directions:route',
polyline: {
positions,
width: 9,
material: new services.annotations.FlowMaterialProperty(
DIRECTIONS_ROUTE_COLOR,
),
clampToGround: true,
// BOTH: drape on 3D tiles when they are up and on terrain when they are
if (!_viewer || !_sets) return;
_sets.route.set([
{
id: 'directions:route',
positions: route.geometry.map(([lon, lat]) => fromDegrees(lon, lat, 0)),
widthPx: ROUTE_WIDTH_PX,
mode: 'draped',
// Draped on 3D tiles when they are up and on terrain when they are
// not, so the keyless globe shows the route too.
classificationType: Cesium.ClassificationType.BOTH,
clampTo: 'both',
style: ROUTE_STYLE,
},
});
]);
_routeDrawn = true;
// One dot per decision; A and B already mark departure and arrival. The dots
// start hidden and appear as anchorStepPoints resolves each ground cell.
const cells = [];
const dots = [];
for (const index of stepMarkerIndices(route.steps)) {
const step = route.steps[index];
cells.push({ lat: step.lat, lon: step.lon });
_stepPoints.add({
id: `directions:step:${index}`,
position: Cesium.Cartesian3.fromDegrees(step.lon, step.lat, 0),
color: STEP_COLOR,
pixelSize: STEP_PIXEL_SIZE,
outlineColor: STEP_OUTLINE,
outlineWidth: 2,
show: false,
// The shared ground floor is a coarse cell, and on the photoreal stack
// the rendered mesh can stand above it. Keeping the dot always visible
// is the same choice every other anchored sprite in the app makes.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
});
const dot = { pos: fromDegrees(step.lon, step.lat, 0), show: false };
_stepDots.set(index, dot);
dots.push(stepDotItem(index, dot));
}
_sets.steps.set(dots);
services.credits?.showOsmCredit?.(_viewer, 'directions');
services.ground.warmGroundFloor(cells);
_anchorAttempts = 0;
_anchorStartedAt = Date.now();
anchorStepPoints();
syncRenderHold();
services.sprites.restoreSpriteOrder(_viewer);
services.render.governorRequestRender('directions-route');
}
@@ -1212,12 +1275,15 @@ export function createDirectionsLayer({ services, source }) {
* Give the pointer back, but only once the click that consumed it has finished
* being dispatched.
*
* Every layer binds its own handler to the same canvas, and they all run
* inside ONE browser event. Releasing the claim the instant this layer places
* an endpoint hands the rest of that same click to every ambient handler
* registered after this one — placing A on top of a bikeshare station also
* deselected the station. A timer, not a microtask: a microtask checkpoint
* runs between two DOM listeners, which is exactly the gap this closes.
* The input dispatcher decides who hears a click before any subscriber
* runs, so its own click subscribers cannot hear this click once it is let
* go. DOM `click` listeners on the canvas (the evidence cards) are another
* matter: the renderer's click comes from the pointer's `up`, and the
* browser's `click` follows inside the SAME input event, where they ask
* `isPointerFree()`. Releasing the claim the instant this layer places an
* endpoint would hand that same click to them. A timer, not a microtask: a
* microtask checkpoint runs between two DOM listeners, which is exactly the
* gap this closes.
*/
function releaseClaimAfterDispatch() {
if (_pointerClaim === null || _releaseTimer) return;
@@ -1234,7 +1300,6 @@ export function createDirectionsLayer({ services, source }) {
*/
function disarm({ afterDispatch = false } = {}) {
_armed = null;
_pointerBlocked = false;
if (afterDispatch) releaseClaimAfterDispatch();
else releaseClaim();
}
@@ -1243,8 +1308,8 @@ export function createDirectionsLayer({ services, source }) {
* Place one endpoint at a picked ground point and reroute when both are set.
*
* The globe click handler is the only caller in the running app; it is
* exported because a ScreenSpaceEventHandler needs a real canvas, and the
* ownership timing this function decides is exactly what has to be tested.
* exported so the ownership timing this function decides can be tested on
* its own.
* @param {'a'|'b'} which Which endpoint to place.
* @param {{lat: number, lon: number}} point Ground point in degrees.
* @returns {boolean} Whether the endpoint was placed.
@@ -1269,8 +1334,9 @@ export function createDirectionsLayer({ services, source }) {
* Arm (or cancel) a globe click for one endpoint.
*
* Placement is a TOOL: it takes the pointer so no ambient layer also selects
* whatever happened to be under the click. If another tool already holds it,
* this refuses — nothing is armed and the row says why.
* whatever happened to be under the click. The newest claim takes over: the
* tool holding it is told and turns itself off, and a newer tool taking it
* disarms this layer.
* @param {null|'a'|'b'} which
* @returns {boolean} Whether the layer is armed after this call.
*/
@@ -1279,23 +1345,19 @@ export function createDirectionsLayer({ services, source }) {
disarm();
return false;
}
// A claim does not stack, not even under the same name — two live instances
// of one tool are two owners. So re-arming for the other endpoint reuses the
// lease already held instead of asking for a second one.
// Two live instances of one tool are two owners, so a second claim under
// the same name would end this layer's own. Re-arming for the other
// endpoint reuses the lease already held instead.
if (!services.input.isLeaseCurrent(_pointerClaim)) {
const lease = services.input.claimPointer(DIRECTIONS_POINTER_OWNER);
if (!lease) {
_armed = null;
_pointerBlocked = true;
// The row already says it, but the row is not where the operator is
// looking after pressing a chip — say it where the app says everything.
const message = pointerBlockedMessage(
services.input.pointerOwner(),
which,
);
if (message) _shellSeams?.showToast?.(message);
return false;
}
// The newest claim takes over: a tool holding the pointer is told and
// turns itself off, and a newer one disarms this layer as Escape would.
const lease = services.input.claimPointer(DIRECTIONS_POINTER_OWNER, {
onLost: () => {
if (_pointerClaim !== lease) return;
disarm();
notifyRow();
},
});
_pointerClaim = lease;
}
// A pending release from the previous placement would otherwise hand the
@@ -1304,7 +1366,6 @@ export function createDirectionsLayer({ services, source }) {
clearTimeout(_releaseTimer);
_releaseTimer = null;
}
_pointerBlocked = false;
_armed = which;
_clearStepSelection();
return true;
@@ -1321,10 +1382,8 @@ export function createDirectionsLayer({ services, source }) {
_route = null;
_status = 'idle';
_error = null;
removeEntity(_markerA);
removeEntity(_markerB);
_markerA = null;
_markerB = null;
_sets?.markers.clear();
_overlayHost.clearSource(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID);
clearRouteGraphics();
services.render.governorRequestRender('directions-clear');
}
@@ -1415,24 +1474,12 @@ export function createDirectionsLayer({ services, source }) {
// --- Step selection ---
function _clearStepSelection() {
if (_selectedStep !== null && _stepPoints) {
const point = findStepPoint(_selectedStep);
if (point) point.pixelSize = STEP_PIXEL_SIZE;
}
const was = _selectedStep;
_selectedStep = null;
if (was !== null) drawStepDots([was]);
_overlayHost.clearSource(DIRECTIONS_STEP_OVERLAY_SOURCE_ID);
}
function findStepPoint(index) {
if (!_stepPoints) return null;
const id = `directions:step:${index}`;
for (let i = 0; i < _stepPoints.length; i += 1) {
const point = _stepPoints.get(i);
if (point.id === id) return point;
}
return null;
}
/**
* Where a step's card should hang, or null while that is not yet known.
*
@@ -1442,13 +1489,13 @@ export function createDirectionsLayer({ services, source }) {
* the same shared floor, and a step whose cell is still cold has no anchor at
* all rather than one at sea level.
* @param {number} index Step index.
* @returns {Cesium.Cartesian3|null}
* @returns {{x: number, y: number, z: number}|null}
*/
function stepAnchorPosition(index) {
const step = _route?.steps?.[index];
if (!step) return null;
const point = findStepPoint(index);
if (point?.show) return Cesium.Cartesian3.clone(point.position);
const dot = _stepDots.get(index);
if (dot?.show) return { ...dot.pos };
const height = stepMarkerHeightM(
services.ground.cachedGroundFloor(step.lat, step.lon),
services.ground.GROUND_FLOOR_LIFT_M,
@@ -1457,7 +1504,7 @@ export function createDirectionsLayer({ services, source }) {
services.ground.warmGroundFloor([{ lat: step.lat, lon: step.lon }]);
return null;
}
return Cesium.Cartesian3.fromDegrees(step.lon, step.lat, height);
return fromDegrees(step.lon, step.lat, height);
}
function refreshStepCard(index) {
@@ -1494,20 +1541,17 @@ export function createDirectionsLayer({ services, source }) {
return false;
}
_selectedStep = index;
const point = findStepPoint(index);
if (point) point.pixelSize = STEP_SELECTED_PIXEL_SIZE;
drawStepDots([index]);
services.render.governorRequestRender('directions-select');
return true;
}
function stepIndexFromPick(picked) {
const candidates = [picked?.primitive?.id, picked?.id];
for (const candidate of candidates) {
if (typeof candidate !== 'string') continue;
const match = /^directions:step:(\d+)$/.exec(candidate);
if (match) return Number(match[1]);
}
return null;
/** The step of a maneuver dot this layer draws under a click, or null. */
function stepIndexFromHit(hit) {
if (!hit || !_sets || hit.set !== _sets.steps.id) return null;
const match = /^directions:step:(\d+)$/.exec(hit.id);
const index = match ? Number(match[1]) : null;
return index !== null && _stepDots.has(index) ? index : null;
}
function _onKeyDown(event) {
@@ -1521,44 +1565,49 @@ export function createDirectionsLayer({ services, source }) {
}
function _installClickHandler(viewer) {
if (_clickHandler) return;
_clickHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
_clickHandler.setInputAction((click) => {
if (!_enabled) return;
// Placement acts only while this layer actually HOLDS the pointer, and the
// maneuver-dot selection below is an ambient handler like any other: it
// yields the moment a tool (this one included) owns the click.
// The lease, not the owner name: a superseded instance of this layer must
// not act on a click its replacement owns.
if (_armed && services.input.isLeaseCurrent(_pointerClaim)) {
const point = pickGround(click.position);
if (_clickSubscription) return;
const input = inputFor(viewer);
// Placement acts only while this layer actually HOLDS the pointer. The
// lease, not the owner name: a superseded instance of this layer must not
// act on a click its replacement owns.
const offPlace = input.onPointer(
'click',
(event) => {
if (!_enabled || !_armed) return;
const point = pickGround(event);
if (!point) return;
placeDirectionsEndpoint(_armed, point);
return;
}
if (!services.input.isPointerFree()) return;
let picked = null;
},
{ lease: () => _pointerClaim },
);
// The maneuver-dot selection is an ambient handler like any other: it
// yields the moment a tool (this one included) owns the click.
const offSelect = input.onClick((event) => {
if (!_enabled) return;
let hit = null;
try {
picked = viewer.scene.pick(click.position);
hit = event.drawHit;
} catch {
picked = null;
hit = null;
}
const index = stepIndexFromPick(picked);
const index = stepIndexFromHit(hit);
if (index !== null) {
_selectStep(index);
return;
}
if (_selectedStep !== null) _clearStepSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
_clickSubscription = () => {
offPlace();
offSelect();
};
if (typeof document !== 'undefined')
document.addEventListener('keydown', _onKeyDown);
}
function _removeClickHandler() {
if (_clickHandler) {
_clickHandler.destroy();
_clickHandler = null;
}
_clickSubscription?.();
_clickSubscription = null;
// Teardown can outlive the document (page unload, and every headless test).
if (typeof document !== 'undefined')
document.removeEventListener('keydown', _onKeyDown);
@@ -1576,17 +1625,29 @@ export function createDirectionsLayer({ services, source }) {
updateInterval: 0,
/**
* Create the maneuver-dot collection. Called once at bootstrap.
* @param {Cesium.Viewer} viewer
* Make the layer's draw sets on the viewer's renderer. Called once at
* bootstrap.
* @param {object} viewer
*/
init(viewer) {
_viewer = viewer;
_stepPoints = new Cesium.PointPrimitiveCollection({
blendOption: Cesium.BlendOption.TRANSLUCENT,
});
viewer.scene.primitives.add(_stepPoints);
services.sprites.registerSpriteCollection('directions', _stepPoints);
_stepPoints.show = false;
detachSets();
const draw = drawOf(viewer);
const prefix = `directions:${++_instances}`;
_sets = {
markers: draw.points({ id: `${prefix}:markers` }),
steps: draw.points({
id: `${prefix}:steps`,
blend: 'translucent',
show: false,
drawOrder: services.sprites.spriteDrawOrder?.('directions') ?? 0,
}),
route: draw.lines({ id: `${prefix}:route` }),
};
// Drawn from the start, empty, so the dots take their place in the
// scene now, as their collection did; their place among the other
// sprite layers is their draw order.
_sets.steps.set([]);
_enabled = false;
_mode = DEFAULT_DIRECTIONS_MODE;
disarm();
@@ -1597,19 +1658,19 @@ export function createDirectionsLayer({ services, source }) {
_error = null;
_flightStep = null;
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, false);
services.sprites.restoreSpriteOrder(viewer);
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, false);
console.log('[Data:Directions] Initialized');
},
/**
* Show the row chips and listen for placement clicks.
* @param {Cesium.Viewer} viewer
* @param {object} viewer
*/
enable(viewer) {
_enabled = true;
_pointerBlocked = false;
_stepPoints.show = true;
if (_sets) _sets.steps.show = true;
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, true);
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, true);
_installClickHandler(viewer);
services.picking.registerPickOwner(
'directions',
@@ -1617,20 +1678,20 @@ export function createDirectionsLayer({ services, source }) {
typeof pickedId === 'string' && pickedId.startsWith('directions:'),
);
syncRenderHold();
services.sprites.restoreSpriteOrder(viewer);
},
/**
* Remove the route, markers and listeners.
* @param {Cesium.Viewer} viewer
* @param {object} viewer
*/
disable(viewer) {
_enabled = false;
clearAll();
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, false);
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, false);
_removeClickHandler();
services.picking.unregisterPickOwner('directions');
if (_stepPoints) _stepPoints.show = false;
if (_sets) _sets.steps.show = false;
syncRenderHold();
void viewer;
},
@@ -1704,10 +1765,7 @@ export function createDirectionsLayer({ services, source }) {
* the same immediate-navigation facade voice destinations use — so the route
* dolly is one more caller of the single camera owner rather than a second
* one. `floorFn`/`warmFn` are the shared ground floor the dolly flies over.
* `showToast` is the app's own toast, so a refusal is said where the rest of
* the UI says things.
* @param {{runNavigation?: Function, floorFn?: Function, warmFn?: Function,
* showToast?: Function}|null} services
* @param {{runNavigation?: Function, floorFn?: Function, warmFn?: Function}|null} services
*/
attachShellServices(services) {
_shellSeams = services || null;
@@ -1715,7 +1773,7 @@ export function createDirectionsLayer({ services, source }) {
/**
* Tear down entirely.
* @param {Cesium.Viewer} viewer
* @param {object} viewer
*/
destroy(viewer) {
if (_enabled) this.disable(viewer);
@@ -1728,20 +1786,17 @@ export function createDirectionsLayer({ services, source }) {
_shellSeams = null;
_dataManager = null;
_rowControlsListener = null;
if (_stepPoints) {
services.sprites.unregisterSpriteCollection('directions', _stepPoints);
viewer.scene.primitives.remove(_stepPoints);
_stepPoints = null;
}
detachSets();
void viewer;
_overlayHost.clearSource(DIRECTIONS_STEP_OVERLAY_SOURCE_ID);
_overlayHost.clearSource(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID);
_viewer = null;
},
/**
* Place one endpoint at a picked ground point. The globe click handler is
* the only caller in the running app; it is on the instance because a
* ScreenSpaceEventHandler needs a real canvas, and the ownership timing
* this decides is exactly what has to be tested.
* the only caller in the running app; it is on the instance so the
* ownership timing this decides can be tested on its own.
*/
placeEndpoint: placeDirectionsEndpoint,
+9 -2
View File
@@ -21,7 +21,13 @@ export function createDirectionsSource({
signal,
headers: { Accept: 'application/json' },
});
const payload = await response.json();
// Proxy error pages may not be JSON.
let payload = null;
try {
payload = await response.json();
} catch (error) {
if (response.ok) throw error;
}
signal?.throwIfAborted();
// Failures keep their English message and carry the HTTP status and the
// server's refusal text, so the layer can show them in the language.
@@ -39,7 +45,8 @@ export function createDirectionsSource({
{ status: 429, refusal },
);
}
if (!response.ok && !payload?.error)
// A 5xx body may mislabel an outage as a route refusal.
if (response.status >= 500 || (!response.ok && !payload?.error))
throw Object.assign(
new Error(`Routing unavailable (HTTP ${response.status})`),
{ status: response.status },
+12
View File
@@ -41,3 +41,15 @@ test('route failures are surfaced without fallback requests', async () => {
assert.equal(calls, 1);
}
});
test('a routing outage stays an outage when its body carries an error', async () => {
const source = createDirectionsSource({ fetchImpl: async () =>
Response.json({ ok: false, error: 'routing service unavailable' }, { status: 502 }) });
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
});
test('a routing outage page that is not JSON still reads as an outage', async () => {
const source = createDirectionsSource({ fetchImpl: async () =>
new Response('<html>Bad Gateway</html>', { status: 502, headers: { 'content-type': 'text/html' } }) });
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
});
@@ -20,10 +20,6 @@ const idle = {
};
const cases = [
[
{ ...idle, pointerBlocked: true },
'Another map tool is using clicks — close it, then SET A again',
],
[{ ...idle, status: 'error' }, 'No route found'],
[
{ ...idle, status: 'error', error: 'Routing timed out' },
+92 -74
View File
@@ -1,4 +1,7 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { cssColor } from '../../render/color.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import { msg, t } from '../../i18n/index.js';
import {
DRONE_AIRSPACE_OVERLAY_SOURCE_ID,
@@ -10,13 +13,21 @@ export { normalizeDroneAirspaceSnapshot } from './records.js';
export { createDroneAirspaceSource } from './source.js';
export * from './cards.js';
/** Fill/line color for a zone by TYPE_CODE. */
/** Fill/line colour for a zone by TYPE_CODE, as a renderer colour `[r, g, b, a]`. */
export function droneAirspaceColor(typeCode) {
return Cesium.Color.fromCssColorString(droneAirspaceAccent(typeCode));
return cssColor(droneAirspaceAccent(typeCode));
}
const ringPositions = (ring) =>
ring.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat));
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
/**
* The draw sets the zones are drawn in start with this; each layer has its
* own (`drone-airspace:1:fills`, …), so several can share a renderer. Picks
* name them as `Hit.set`.
*/
export const DRONE_AIRSPACE_SET_PREFIX = 'drone-airspace';
let instances = 0;
/**
* FNV-1a over a zone's rings: a short, deterministic fingerprint so a
@@ -39,33 +50,40 @@ const CARD_HOST_OPTIONS = Object.freeze({
moving: false,
});
/** Own one drone-restriction display, its refresh lifecycle, and click selection. */
/**
* Own one drone-restriction display, its refresh lifecycle, and click selection.
*
* Each zone polygon is a ground-clamped fill in one renderer draw set and
* its boundary a draped line in another (`drawOf(viewer)`), made at `init`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*/
export function createDroneAirspaceLayer({
source,
overlayHost = null,
screenSpaceEventHandlerFactory = null,
inputFor = defaultInputFor,
picking = null,
pointer = null,
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Drone airspace requires a snapshot source');
let _viewer = null;
let _request = null;
let _snapshotSignature = null;
let _dataSource = null;
let _fills = null;
let _lines = null;
let _setIds = new Set();
let _count = 0;
let _lastUpdate = null;
let _lastError = null;
let _stale = false;
let _enabled = false;
let _clickHandler = null;
let _clickSubscription = null;
let _selectedId = null;
let _selectedCardId = null;
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
const _rowById = new Map();
const canSelect = () =>
overlayHost && screenSpaceEventHandlerFactory && picking;
const canSelect = () => overlayHost && inputFor && picking;
function publishSelectedCard() {
if (!canSelect()) return;
@@ -82,7 +100,7 @@ export function createDroneAirspaceLayer({
}
const card = {
...buildDroneAirspaceCard(row),
position: Cesium.Cartesian3.fromDegrees(row.anchor.lon, row.anchor.lat),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
_selectedCardId = card.id;
overlayHost.setEntries(
@@ -92,33 +110,34 @@ export function createDroneAirspaceLayer({
);
}
/** Resolve a scene pick to one of this layer's zone ids, or null. */
function pickedZoneId(picked) {
const pickId = picking.resolvePickId(picked);
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
/**
* The zone a click's draw hit (`Hit`, query.d.ts) belongs to: an item of
* this layer's own sets, for a zone drawn now; else null.
*/
function pickedZoneId(hit) {
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
return null;
const zoneId = pickId.slice(PICK_PREFIX.length).split(':')[0];
const zoneId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
return _rowById.has(zoneId) ? zoneId : null;
}
function installClickHandler() {
if (!canSelect() || _clickHandler || !_viewer) return;
if (!canSelect() || _clickSubscription || !_viewer) return;
// Deliberately NOT registered in the pick-ownership registry: sibling
// layers yield to owned picks before their own overlay-card hit-tests,
// so claiming these large ground polygons would make FIRMS/vessel/CCTV
// cards inert anywhere over a zone. Unowned, our picks read as
// "empty space" to siblings — the same contract as fire perimeters.
_clickHandler = screenSpaceEventHandlerFactory(_viewer);
_clickHandler.setInputAction((click) => {
if (pointer && !pointer.isPointerFree()) return;
_clickSubscription = inputFor(_viewer).onClick((event) => {
const cardHit = overlayHost.hitTest?.(
click.position?.x,
click.position?.y,
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) return;
const picked = _viewer.scene.pick(click.position);
const zoneId = picked ? pickedZoneId(picked) : null;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
if (zoneId) {
_selectedId = zoneId;
publishSelectedCard();
@@ -132,14 +151,12 @@ export function createDroneAirspaceLayer({
_selectedId = null;
publishSelectedCard();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
}
function removeClickHandler() {
if (_clickHandler) {
_clickHandler.destroy();
_clickHandler = null;
}
_clickSubscription?.();
_clickSubscription = null;
}
function clearSelection() {
@@ -161,10 +178,20 @@ export function createDroneAirspaceLayer({
init(viewer) {
if (_viewer)
throw new Error('Drone airspace layer is already initialized');
const draw = drawOf(viewer);
const prefix = `${DRONE_AIRSPACE_SET_PREFIX}:${++instances}`;
_fills = draw.shapes({
id: `${prefix}:fills`,
clampTo: 'both',
show: false,
});
_lines = draw.lines({
id: `${prefix}:lines`,
clampTo: 'both',
show: false,
});
_setIds = new Set([_fills.id, _lines.id]);
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('drone-airspace');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -175,7 +202,7 @@ export function createDroneAirspaceLayer({
enable() {
_enabled = true;
if (_dataSource) _dataSource.show = true;
if (_fills) _fills.show = _lines.show = true;
overlayHost?.setVisible?.(DRONE_AIRSPACE_OVERLAY_SOURCE_ID, true);
installClickHandler();
},
@@ -184,13 +211,13 @@ export function createDroneAirspaceLayer({
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
if (_fills) _fills.show = _lines.show = false;
removeClickHandler();
clearSelection();
},
async update() {
if (!_enabled || !_dataSource) return false;
if (!_enabled || !_fills) return false;
_request?.abort();
const request = new AbortController();
_request = request;
@@ -227,38 +254,29 @@ export function createDroneAirspaceLayer({
_lastError = null;
return true;
}
const nextEntities = [];
const nextFills = [];
const nextLines = [];
_rowById.clear();
for (const row of rows) {
const color = droneAirspaceColor(row.typeCode);
for (const [index, rings] of row.polygons.entries()) {
const [outer, ...holes] = rings;
const outerPositions = ringPositions(outer);
nextEntities.push(
new Cesium.Entity({
id: `drone-airspace:${row.stableId}:${index}`,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(
outerPositions,
holes.map(
(hole) =>
new Cesium.PolygonHierarchy(ringPositions(hole)),
),
),
material: new Cesium.ColorMaterialProperty(
color.withAlpha(0.25),
),
},
polyline: {
positions: outerPositions,
clampToGround: true,
width: 2,
material: new Cesium.ColorMaterialProperty(
color.withAlpha(0.9),
),
},
}),
);
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
// Each exterior keeps its own holes.
nextFills.push({
id,
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(color, 0.25),
height: 'clampGround',
});
// The boundary: the exterior ring draped on the ground (lines
// take ECEF, draw.d.ts `LineItem`).
nextLines.push({
id,
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
style: { kind: 'solid', color: withAlpha(color, 0.9) },
});
}
const { polygons, ...facts } = row;
_rowById.set(row.stableId, {
@@ -267,15 +285,15 @@ export function createDroneAirspaceLayer({
});
}
_dataSource.entities.removeAll();
for (const entity of nextEntities) _dataSource.entities.add(entity);
_fills.set(nextFills);
_lines.set(nextLines);
_snapshotSignature = signature;
if (_selectedId) publishSelectedCard();
_count = rows.length;
_lastUpdate = updatedAt;
_lastError = null;
console.log(
`[Data:DroneAirspace] Updated: ${_count} zones, ${nextEntities.length} polygons`,
`[Data:DroneAirspace] Updated: ${_count} zones, ${nextFills.length} polygons`,
);
return true;
} catch (e) {
@@ -292,7 +310,7 @@ export function createDroneAirspaceLayer({
}
},
destroy(viewer = _viewer) {
destroy() {
_request?.abort();
_request = null;
removeClickHandler();
@@ -301,10 +319,10 @@ export function createDroneAirspaceLayer({
_snapshotSignature = null;
_viewer = null;
_enabled = false;
if (_dataSource) {
viewer.dataSources.remove(_dataSource, true);
_dataSource = null;
}
_fills?.dispose();
_lines?.dispose();
_fills = _lines = null;
_setIds = new Set();
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -312,7 +330,7 @@ export function createDroneAirspaceLayer({
},
getAnalystRecords(maxCount = 2000) {
if (!_dataSource || !_dataSource.show) return [];
if (!_fills || !_fills.show) return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 2000;
+55 -38
View File
@@ -2,21 +2,28 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createDroneAirspaceLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: zone picks name it.
let fillsSetId = null;
/** A Cesium pick of a zone's fill, as the draw port makes it. */
const zonePick = (id) => ({ id: { set: fillsSetId, id } });
const liveSet = (draw, suffix) =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(suffix),
);
function harness(source, { pick = () => null, cardHit = () => null } = {}) {
const sources = [];
const overlay = { entries: new Map(), visible: null };
const clicks = { handler: null, destroyed: 0 };
const owners = new Map();
const viewer = {
scene: { pick },
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
const input = fakeInput(viewer);
const clicks = {
handler: (click) => input.click(click.position),
get destroyed() {
return input.input.subscriberCount() === 0 ? 1 : 0;
},
};
const layer = createDroneAirspaceLayer({
@@ -33,27 +40,28 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
},
hitTest: (x, y, options) => cardHit(x, y, options),
},
screenSpaceEventHandlerFactory: () => ({
setInputAction(callback) {
clicks.handler = callback;
},
destroy() {
clicks.destroyed += 1;
clicks.handler = null;
},
}),
inputFor: () => input.input,
picking: {
resolvePickId: (picked) => picked?.id ?? null,
resolvePickId: (picked) => picked?.id?.id ?? picked?.id ?? null,
isOwnedByOtherLayer: (layerId, pickedId) =>
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
},
pointer: { isPointerFree: () => true },
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, overlay, clicks, owners };
fillsSetId = liveSet(draw, ':fills').spec.id;
return {
layer,
viewer,
draw,
fills: () => liveSet(draw, ':fills'),
lines: () => liveSet(draw, ':lines'),
overlay,
clicks,
owners,
};
}
const ring = [
@@ -76,7 +84,7 @@ const row = {
polygons: [[ring]],
};
test('each zone polygon renders as one filled entity with its outline', async () => {
test('each zone polygon draws as one clamped fill with its draped boundary', async () => {
const h = harness({
getSnapshot: async () => [
row,
@@ -84,11 +92,23 @@ test('each zone polygon renders as one filled entity with its outline', async ()
],
});
assert.equal(await h.layer.update(h.viewer), true);
const entities = h.sources[0].entities.values;
assert.equal(entities.length, 3);
assert.equal(entities[0].id, 'drone-airspace:310:0');
assert.ok(entities[0].polygon, 'zone fill missing');
assert.ok(entities[0].polyline, 'zone outline missing');
const ids = [
'drone-airspace:310:0',
'drone-airspace:400:0',
'drone-airspace:400:1',
];
assert.deepEqual([...h.fills().items.keys()], ids, 'zone fill missing');
assert.deepEqual([...h.lines().items.keys()], ids, 'zone outline missing');
assert.equal(h.fills().show, true);
const fill = h.fills().items.get(ids[0]);
assert.equal(fill.height, 'clampGround');
assert.equal(fill.geometry.kind, 'polygon');
assert.equal(fill.fill[3], 0.25);
const line = h.lines().items.get(ids[0]);
assert.equal(line.mode, 'draped');
assert.equal(line.widthPx, 2);
assert.equal(line.style.color[3], 0.9);
assert.equal(line.positions.length, ring.length, 'the exterior ring only');
assert.equal(h.layer.getStats().count, 2);
});
@@ -99,10 +119,10 @@ test('clicking a zone publishes its card; empty space clears it', async () => {
{ pick: () => pickResult },
);
await h.layer.update(h.viewer);
assert.equal(typeof h.clicks.handler, 'function', 'click handler missing');
assert.equal(h.clicks.destroyed, 0, 'click handler missing');
assert.equal(h.owners.size, 0);
pickResult = { id: 'drone-airspace:310:0' };
pickResult = zonePick('drone-airspace:310:0');
h.clicks.handler({ position: { x: 10, y: 10 } });
const entries = h.overlay.entries.get('drone-airspace');
assert.equal(entries.length, 1);
@@ -202,17 +222,14 @@ test('a boundary change alone redraws the zone; identical geometry does not', as
let rows = [row];
const h = harness({ getSnapshot: async () => rows });
await h.layer.update(h.viewer);
const [first] = h.sources[0].entities.values;
const [first] = h.lines().items.values();
rows = [{ ...row, polygons: [[ring.map((point) => [...point])]] }];
await h.layer.update(h.viewer);
assert.equal(h.sources[0].entities.values[0], first, 'same geometry kept');
assert.equal([...h.lines().items.values()][0], first, 'same geometry kept');
rows = [{ ...row, polygons: [[moved]] }];
await h.layer.update(h.viewer);
const [redrawn] = h.sources[0].entities.values;
const [redrawn] = h.lines().items.values();
assert.notEqual(redrawn, first, 'moved boundary must redraw');
assert.notDeepEqual(
redrawn.polyline.positions.getValue(),
first.polyline.positions.getValue(),
);
assert.notDeepEqual(redrawn.positions, first.positions);
assert.ok(h.layer.getAnalystRecords()[0].lon > -76.6);
});
+94 -76
View File
@@ -1,12 +1,16 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
EARTHQUAKE_OVERLAY_COLLISION_CAPACITY,
depthColor,
depthAccent,
createEarthquakeOverlayEntry,
selectEarthquakeOverlayCohort,
mapAnalystRecord,
earthquakeCoverage,
} from './model.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
@@ -15,18 +19,47 @@ export { createUsgsEarthquakeSource } from './source.js';
// panel shows it translated.
const msg = (text) => text;
/** Own one earthquake display and its refresh lifecycle. */
/**
* The draw sets the discs are drawn in start with this; each layer has its
* own (`earthquakes:1`, …), so several can share a renderer. Picks name it
* as `Hit.set`.
*/
export const EARTHQUAKE_DISC_SET_ID = 'earthquakes';
let instances = 0;
/**
* Own one earthquake display and its refresh lifecycle.
*
* The discs are one renderer draw set (`drawOf(viewer)`), made at `init`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*/
export function createEarthquakesLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Earthquakes require a snapshot source');
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
let _viewer = null;
let _request = null;
let _dataSource = null;
let _discs = null;
let _count = 0;
let _lastUpdate = null;
let _lastError = null;
let _enabled = false;
// What the discs were drawn from, so analyst reads come from the layer, not the
// drawing, and the timeline reads its marks ({ mag, time, place, usgsId }).
let _events = [];
let _uncover = null;
// The marks last told to the clock, so a refresh with the same strong
// quakes does not tell it again.
let _marksKey = null;
const coverage = () => (_enabled ? earthquakeCoverage(_events) : null);
const coverageChanged = () => {
const covered = coverage();
const key = covered ? JSON.stringify(covered.marks) : null;
if (key === _marksKey) return;
_marksKey = key;
worldClock.coverageChanged();
};
const layer = {
id: 'earthquakes',
@@ -37,10 +70,15 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
init(viewer) {
if (_viewer) throw new Error('Earthquake layer is already initialized');
_discs = drawOf(viewer).shapes({
id: `${EARTHQUAKE_DISC_SET_ID}:${++instances}`,
show: false,
});
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('earthquakes');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
// While on, the strong quakes are marks on the world clock's timeline.
// Registered once; off, the layer has no time to show.
_marksKey = null;
_uncover = worldClock.register({ id: 'earthquakes', coverage });
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -53,21 +91,23 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_enabled = true;
// No continuous-render hold: the discs are static geometry now, so the
// layer has no per-frame animator to keep the render loop alive for.
if (_dataSource) _dataSource.show = true;
if (_discs) _discs.show = true;
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
coverageChanged();
},
disable(viewer) {
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
if (_discs) _discs.show = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
coverageChanged();
},
async update(viewer) {
if (!_enabled || !_dataSource) return false;
if (!_enabled || !_discs) return false;
_request?.abort();
const request = new AbortController();
_request = request;
@@ -76,7 +116,8 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
if (request.signal.aborted || _request !== request || !_enabled)
return false;
const nextEntities = [];
const nextDiscs = [];
const nextEvents = [];
let count = 0;
const overlayEntries = [];
@@ -93,50 +134,40 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
count++;
const baseRadius = Math.pow(2, mag) * 1000;
const color = depthColor(depthKm || 0);
const [r, g, b] = color;
const isSignificant = mag >= 5.0;
const fillAlpha = isSignificant ? 0.4 : 0.3;
const outlineAlpha = isSignificant ? 1.0 : 0.8;
const position = Cesium.Cartesian3.fromDegrees(lon, lat);
nextEntities.push(
new Cesium.Entity({
id: `earthquake:${stableId}`,
position,
ellipse: {
// Static axes — see the module header. A CallbackProperty here
// re-tessellates the clamped ground geometry every frame.
semiMajorAxis: baseRadius,
semiMinorAxis: baseRadius,
material: new Cesium.ColorMaterialProperty(
color.withAlpha(fillAlpha),
),
outline: true,
outlineColor: color.withAlpha(outlineAlpha),
outlineWidth: isSignificant ? 3 : 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: {
// Analyst seam (additive): the USGS event id (e.g. "us7000abcd").
usgsId,
mag,
place,
time,
depth: depthKm,
},
}),
);
const position = fromDegrees(lon, lat);
nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat });
// A filled disc on the ground, with static axes: re-tessellating
// clamped ground geometry every frame is what once cost 30 fps.
// No outline: clamped to the ground, Cesium never drew one.
nextDiscs.push({
id: `earthquake:${stableId}`,
geometry: {
kind: 'ellipse',
center: { lon, lat },
semiMajor: baseRadius,
semiMinor: baseRadius,
},
fill: [r, g, b, fillAlpha],
height: 'clampGround',
clampTo: 'both',
});
overlayEntries.push(
createEarthquakeOverlayEntry({
id: String(stableId),
position,
magnitude: mag,
accent: color.toCssColorString(),
accent: depthAccent(depthKm || 0),
}),
);
}
_dataSource.entities.removeAll();
for (const entity of nextEntities) _dataSource.entities.add(entity);
_discs.set(nextDiscs);
_events = nextEvents;
coverageChanged();
if (_enabled) {
overlayHost.setEntries(
EARTHQUAKE_OVERLAY_SOURCE_ID,
@@ -172,10 +203,12 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_enabled = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
if (_dataSource) {
viewer.dataSources.remove(_dataSource, true);
_dataSource = null;
}
_discs?.dispose();
_discs = null;
_events = [];
_uncover?.();
_uncover = null;
_marksKey = null;
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -190,39 +223,24 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
* @returns {Array<Object>} See mapAnalystRecord for the record shape.
*/
getAnalystRecords(maxCount = 2000) {
if (!_dataSource || !_dataSource.show) return [];
const entities = _dataSource.entities.values;
if (!entities.length) return [];
if (!_discs || !_enabled || !_events.length) return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 2000;
const now = Cesium.JulianDate.now();
const result = [];
for (const entity of entities) {
if (result.length >= limit) break;
const cartesian = entity.position
? entity.position.getValue(now)
: null;
const carto = cartesian
? Cesium.Cartographic.fromCartesian(cartesian)
: null;
const p = entity.properties;
result.push(
mapAnalystRecord(
{
id: p?.usgsId?.getValue(now) ?? null,
mag: p?.mag?.getValue(now),
place: p?.place?.getValue(now),
time: p?.time?.getValue(now),
depth: p?.depth?.getValue(now),
lat: carto ? Cesium.Math.toDegrees(carto.latitude) : null,
lon: carto ? Cesium.Math.toDegrees(carto.longitude) : null,
},
result.length,
),
);
}
return result;
return _events.slice(0, limit).map((event, index) =>
mapAnalystRecord(
{
id: event.usgsId ?? null,
mag: event.mag,
place: event.place,
time: event.time,
depth: event.depthKm,
lat: event.lat,
lon: event.lon,
},
index,
),
);
},
getStats() {
+78 -7
View File
@@ -1,27 +1,98 @@
import * as Cesium from 'cesium';
export const EARTHQUAKE_OVERLAY_SOURCE_ID = 'earthquakes';
export const EARTHQUAKE_OVERLAY_COHORT_LIMIT = 96;
export const EARTHQUAKE_OVERLAY_COLLISION_CAPACITY = 48;
// The depth bands' colours: CSS red, orange and yellow, as the renderer's
// colour tuples (`[r, g, b, a]`, 0..1) and as CSS for the labels' accent.
const SHALLOW = Object.freeze({ rgba: [1, 0, 0, 1], css: 'rgb(255,0,0)' });
const INTERMEDIATE = Object.freeze({
rgba: [1, 165 / 255, 0, 1],
css: 'rgb(255,165,0)',
});
const DEEP = Object.freeze({ rgba: [1, 1, 0, 1], css: 'rgb(255,255,0)' });
const depthBand = (depthKm) =>
depthKm < 70 ? SHALLOW : depthKm < 300 ? INTERMEDIATE : DEEP;
/**
* Color by depth:
* The smallest magnitude the timeline marks. Most quakes are small shakes;
* M6 and up come about once every two days worldwide, so each is an event
* worth stepping to. The map still draws every quake.
*/
export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
`M${Number(magnitude).toFixed(1)}`;
/**
* A strong quake's timeline label: its magnitude and, where the feed names
* one, its place, cut short (`M6.4 · 113 km SSE of Lata, Solomon Islands`).
* @param {{mag: number, place?: string | null}} event
* @returns {string}
*/
export function earthquakeMarkLabel({ mag, place }) {
const title = earthquakeMagnitudeTitle(mag);
const where =
typeof place === 'string' ? place.replace(/\s+/g, ' ').trim() : '';
if (!where) return title;
const short =
where.length > MARK_PLACE_LENGTH
? `${where.slice(0, MARK_PLACE_LENGTH - 1).trimEnd()}…`
: where;
return `${title} · ${short}`;
}
/**
* The time a world clock's timeline can show for `events` (`{mag, time,
* place?, usgsId?}`, time in ms): the span of the quakes of
* EARTHQUAKE_MARK_MAGNITUDE and up, each one a mark labelled with its
* magnitude and place, or null with none, so the layer never stretches the
* timeline past what its feed covers.
* @returns {{start: number, end: number, marks: Array<{time: number, label: string, id?: string, kind: string}>} | null}
*/
export function earthquakeCoverage(events) {
const marks = events
.filter(
({ mag, time }) =>
mag >= EARTHQUAKE_MARK_MAGNITUDE && Number.isFinite(time),
)
.map((event) => ({
time: event.time,
label: earthquakeMarkLabel(event),
...(event.usgsId ? { id: String(event.usgsId) } : {}),
kind: 'earthquake',
}))
.sort((a, b) => a.time - b.time);
return marks.length
? { start: marks[0].time, end: marks.at(-1).time, marks }
: null;
}
/**
* Color by depth, as a renderer colour `[r, g, b, a]` (0..1):
* - Shallow (<70km): Red
* - Intermediate (70-300km): Orange
* - Deep (>300km): Yellow
*/
export function depthColor(depthKm) {
if (depthKm < 70) return Cesium.Color.RED;
if (depthKm < 300) return Cesium.Color.ORANGE;
return Cesium.Color.YELLOW;
return [...depthBand(depthKm).rgba];
}
/** The depth band's colour as CSS, for the magnitude label's accent. */
export const depthAccent = (depthKm) => depthBand(depthKm).css;
/**
* Build the source-owned presentation for one ambient magnitude label.
* Magnitude formatting deliberately remains here instead of moving into the
* shared renderer.
* @param {object} input
* @param {string} input.id Stable USGS or deterministic fallback id.
* @param {Cesium.Cartesian3} input.position Ground anchor shared with the pulse.
* @param {{x: number, y: number, z: number}} input.position ECEF ground
* anchor, shared with the disc.
* @param {number} input.magnitude USGS magnitude.
* @param {string} input.accent Source-owned depth-band color.
* @returns {object}
@@ -37,7 +108,7 @@ export function createEarthquakeOverlayEntry({
id: String(id),
position,
variant: 'label',
title: `M${mag.toFixed(1)}`,
title: earthquakeMagnitudeTitle(mag),
accent,
priority: Math.round(mag * 1000),
collisionGroup: 'ambient-label',
+166 -15
View File
@@ -2,19 +2,13 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createEarthquakesLayer } from './index.js';
import { createUsgsEarthquakeSource } from './source.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { EARTHQUAKE_MARK_MAGNITUDE, earthquakeMarkLabel } from './model.js';
import { worldClock } from '../../time/worldClock.js';
function harness(source) {
const sources = [];
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const layer = createEarthquakesLayer({
source,
overlayHost: {
@@ -27,7 +21,7 @@ function harness(source) {
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
return { layer, viewer, draw, events };
}
const row = {
stableId: 'event-a',
@@ -61,17 +55,19 @@ test('late refresh cannot publish after disable, re-enable, or destroy', async (
h.layer.destroy(h.viewer);
}
});
test('two displays own separate data sources and destruction', async () => {
test('two displays own separate draw sets and destruction', async () => {
const a = harness({ getSnapshot: async () => [row] });
const b = harness({ getSnapshot: async () => [] });
await a.layer.update(a.viewer);
await b.layer.update(b.viewer);
assert.equal(a.layer.getStats().count, 1);
assert.equal(b.layer.getStats().count, 0);
assert.equal(a.draw.find('earthquakes:').items.size, 1);
a.layer.destroy();
assert.equal(a.sources.length, 0);
assert.equal(b.sources.length, 1);
assert.equal(a.draw.find('earthquakes:'), undefined, 'disposed');
assert.equal(b.draw.find('earthquakes:').items.size, 0);
b.layer.destroy();
assert.equal(b.draw.find('earthquakes:'), undefined);
});
test('USGS body completion honors cancellation even with an uncooperative transport', async () => {
const abort = new AbortController();
@@ -88,3 +84,158 @@ test('USGS body completion honors cancellation even with an uncooperative transp
name: 'AbortError',
});
});
test('analyst records come from the events the layer drew, and only while it is on', async () => {
const h = harness({
getSnapshot: async () => [
row,
{ ...row, stableId: 'event-b', usgsId: 'event-b', mag: 5.5 },
],
});
await h.layer.update(h.viewer);
assert.deepEqual(h.layer.getAnalystRecords(), [
{
id: 'event-a',
magnitude: 4,
depthKm: 3,
lat: 20,
lon: 30,
timeMs: 1000,
place: 'Fixture',
},
{
id: 'event-b',
magnitude: 5.5,
depthKm: 3,
lat: 20,
lon: 30,
timeMs: 1000,
place: 'Fixture',
},
]);
assert.equal(h.layer.getAnalystRecords(1).length, 1);
const [disc] = h.draw.find('earthquakes:').items.values();
assert.equal(disc.meta, undefined, 'the disc carries drawing only');
h.layer.disable(h.viewer);
assert.deepEqual(h.layer.getAnalystRecords(), []);
h.layer.destroy(h.viewer);
});
test('two layers share one renderer, each with its own disc set', async () => {
const events = [];
const overlayHost = {
setEntries: (...args) => events.push(args),
setVisible() {},
clearSource() {},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const a = createEarthquakesLayer({
source: { getSnapshot: async () => [row] },
overlayHost,
});
const b = createEarthquakesLayer({
source: { getSnapshot: async () => [] },
overlayHost,
});
a.init(viewer);
b.init(viewer);
a.enable(viewer);
b.enable(viewer);
await a.update(viewer);
await b.update(viewer);
const live = [...draw.sets.values()].filter((set) => !set.disposed);
assert.equal(live.length, 2);
assert.deepEqual(
live.map((set) => set.items.size),
[1, 0],
);
a.destroy();
a.init(viewer);
assert.equal(
[...draw.sets.values()].filter((set) => !set.disposed).length,
2,
'destroyed, then started again',
);
a.destroy();
b.destroy();
});
test('a viewer with nothing to draw with is refused at init, and init can be retried', () => {
const layer = createEarthquakesLayer({
source: { getSnapshot: async () => [] },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const viewer = {};
assert.throws(() => layer.init(viewer), /no renderer to draw with/);
const { unbind } = bindFakeDraw(viewer);
layer.init(viewer);
layer.destroy();
unbind();
});
test('the timeline marks only strong quakes, while the layer is on', async () => {
assert.equal(EARTHQUAKE_MARK_MAGNITUDE, 6);
const rows = [
{ ...row, stableId: 'small', mag: 4.5, time: 1_000 },
{ ...row, stableId: 'strong', usgsId: 'us-strong', mag: 6, time: 5_000 },
{
...row,
stableId: 'great',
usgsId: 'us-great',
mag: 7.2,
place: ' 113 km SSE of Lata, Solomon Islands region of the Pacific ',
time: 3_000,
},
{ ...row, stableId: 'untimed', mag: 6.5, time: null },
];
let snapshot = rows;
const h = harness({ getSnapshot: async () => snapshot });
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
let changes = 0;
const unsubscribe = worldClock.subscribe(() => changes++);
await h.layer.update(h.viewer);
// Every quake is drawn; only M6 and up are marks, spanning their own time.
assert.equal(h.draw.find('earthquakes:').items.size, 4);
// Each labelled with its magnitude and, cut short, its place.
assert.deepEqual(worldClock.coverage(), {
start: 3_000,
end: 5_000,
marks: [3_000, 5_000],
markDetails: [
{
time: 3_000,
label: 'M7.2 · 113 km SSE of Lata, Solomon Islands reg…',
id: 'us-great',
kind: 'earthquake',
},
{
time: 5_000,
label: 'M6.0 · Fixture',
id: 'us-strong',
kind: 'earthquake',
},
],
});
const told = changes;
await h.layer.update(h.viewer);
assert.equal(changes, told, 'the same strong quakes are not told again');
snapshot = rows.slice(0, 1);
await h.layer.update(h.viewer);
assert.equal(worldClock.coverage(), null, 'small shakes alone cover no time');
snapshot = rows;
await h.layer.update(h.viewer);
h.layer.disable(h.viewer);
assert.equal(worldClock.coverage(), null, 'off, no time to show');
h.layer.enable(h.viewer);
assert.deepEqual(worldClock.coverage().marks, [3_000, 5_000]);
h.layer.destroy();
assert.equal(worldClock.coverage(), null);
unsubscribe();
});
test('a strong quake with no place is labelled with its magnitude alone', () => {
assert.equal(earthquakeMarkLabel({ mag: 6.44, place: null }), 'M6.4');
assert.equal(earthquakeMarkLabel({ mag: 6, place: ' ' }), 'M6.0');
assert.equal(
earthquakeMarkLabel({ mag: 8.1, place: 'Off the coast' }),
'M8.1 · Off the coast',
);
});
+20 -23
View File
@@ -1,10 +1,10 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import {
FIRMS_OVERLAY_SOURCE_ID,
FIRMS_AMBIENT_COHORT_LIMIT,
} from '../../data/firmsLabels.js';
import { MAX_AMBIENT_LABELS, LABEL_VIEW_MARGIN_PX } from './policy.js';
import { canvasOf } from '../../render/rendererOf.js';
export function createCards({
layerState,
@@ -19,8 +19,8 @@ export function createCards({
* Rebuild the card entries for the shared world-overlay host: the
* selected-fire detail card (if any) plus at most MAX_AMBIENT_LABELS
* ambient cards picked by a greedy screen-space declutter — walk the
* priority-ranked candidates, project each with
* SceneTransforms.worldToWindowCoordinates, and accept only candidates
* priority-ranked candidates, project each with the renderer's
* `query.project`, and accept only candidates
* ≥ LABEL_MIN_SEP_PX from every already-accepted card. Candidates whose
* projection fails are dropped silently. SELECTION runs here, on LOD/
* viewport rebuilds and camera moveEnd — never per frame; RENDERING is
@@ -30,20 +30,22 @@ export function createCards({
function rebuildAmbientLabels() {
if (!layerState._viewer) return;
const scene = layerState._viewer.scene;
const now = Date.now();
const { query } = components.rendering.scenePorts();
const project = (position) => query?.project(position) ?? null;
// Ages count back from the time shown: the window's end, or now when live.
const now = components.model.ageReferenceMs();
const entries = [];
/** @type {Array<{x: number, y: number}>} Screen positions of accepted labels. */
const accepted = [];
// worldToWindowCoordinates happily projects points on the FAR side of the
// planet, so without this the ≤18 ambient slots get spent on fires the
// overlay host will then horizon-cull at paint time (`horizonCull: true`
// in applyFirmsOverlayPolicy) — near-side fires silently lose their cards.
// Shared with the sprite pass (fireHorizonOccluder) so cards and sprites
// never disagree about which hemisphere a detection is on.
const occluder = components.rendering.fireHorizonOccluder();
// Projection happily answers for points on the FAR side of the planet,
// so without this the ≤18 ambient slots get spent on fires the overlay
// host will then horizon-cull at paint time (`horizonCull: true` in
// applyFirmsOverlayPolicy) — near-side fires silently lose their cards.
// The renderer's ellipsoid horizon from the eye, the test the sprites'
// GPU cull makes, so cards and sprites never disagree about which
// hemisphere a detection is on.
const beyondHorizon = (position) =>
occluder ? occluder.isPointVisible(position) !== true : false;
query ? query.isOccluded(position) : false;
layerState._fireByCardId.clear();
if (layerState._selectedFire) {
@@ -53,10 +55,8 @@ export function createCards({
);
layerState._fireByCardId.set(selectedCard.id, layerState._selectedFire);
entries.push(selectedCard);
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
const screen = project(
components.model.firePosition(layerState._selectedFire),
layerState.scratchWindowCoord,
);
// Seed the accepted list so ambient cards keep clear of the detail card.
// A selected fire behind the limb is not painted, so it must not reserve
@@ -71,8 +71,9 @@ export function createCards({
}
}
const width = scene.canvas.clientWidth;
const height = scene.canvas.clientHeight;
const canvas = canvasOf(layerState._viewer);
const width = canvas.clientWidth;
const height = canvas.clientHeight;
let ambientCount = 0;
for (const candidate of layerState._labelCandidates) {
@@ -83,11 +84,7 @@ export function createCards({
// LOD, far-side cells can still project on-canvas; accepting those first
// starves front-side cards before the host applies its authoritative cull.
if (beyondHorizon(candidate.cullPosition || candidate.position)) continue;
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
candidate.position,
layerState.scratchWindowCoord,
);
const screen = project(candidate.position);
if (!screen) continue; // projection failed (e.g. behind camera) — drop silently
if (
screen.x < -LABEL_VIEW_MARGIN_PX ||
+221
View File
@@ -0,0 +1,221 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer } from '../../data/firmsHeatmap.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
// Ports built over a viewer of the test's own, with no renderer bound: the
// adapter's factories load as `./render/cesium/unbound` loads them.
import '../../render/cesium/unbound.js';
const raw = (lat, lon, frp) => ({
lat,
lon,
frp,
confidence: 'h',
brightness: 340,
daynight: 'D',
acqDate: '2026-08-03',
acqTime: '0412',
instrument: 'VIIRS',
satellite: 'N20',
});
/** Enough canvas for the glow sprites and the heat raster. */
const canvasStub = () => ({
width: 0,
height: 0,
getContext: () => ({
createRadialGradient: () => ({ addColorStop() {} }),
fillRect() {},
createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }),
putImageData() {},
}),
toDataURL: () => 'data:image/png;base64,iVBORw0KGgo=',
});
function harness(fires, heightM, { sceneFromViewer = false } = {}) {
const saved = {
window: globalThis.window,
document: globalThis.document,
project: Cesium.SceneTransforms.worldToWindowCoordinates,
};
globalThis.window = new EventTarget();
globalThis.document = { createElement: canvasStub };
// Headless: every position projects to the canvas middle.
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 400, y: 300 });
const primitives = [];
const viewer = {
camera: {
moveEnd: new Cesium.Event(),
positionWC: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, heightM),
directionWC: new Cesium.Cartesian3(0, 0, -1),
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
heightM,
),
},
get canvas() {
return this.scene?.canvas;
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
preRender: new Cesium.Event(),
primitives: {
add: (value) => (primitives.push(value), value),
remove: (value) => {
const at = primitives.indexOf(value);
if (at >= 0) primitives.splice(at, 1);
value.destroy?.();
return at >= 0;
},
contains: () => false,
},
},
};
let ports = bindFakeCesiumScene(viewer);
const { draw } = ports;
// The heatmap drapes through the globe port.
const globe = fakeGlobePort();
{
const { unbind, ...bound } = ports;
unbind();
ports = { ...bound, unbind: bindRenderer(viewer, { ...bound, globe }) };
}
// A renderer with no query or frame: the Cesium adapter builds them over
// the viewer's scene, as it does for a viewer with no renderer.
if (sceneFromViewer) {
ports.unbind();
bindRenderer(viewer, { draw, camera: ports.camera, globe });
Object.assign(viewer.scene, {
preUpdate: new Cesium.Event(),
postRender: new Cesium.Event(),
requestRender() {},
forceRender() {},
pick: () => undefined,
drillPick: () => [],
camera: viewer.camera,
});
viewer.camera.pickEllipsoid = () => undefined;
viewer.clock = { currentTime: Cesium.JulianDate.now() };
}
const input = fakeInput(viewer);
const layer = createFirmsHeatmapLayer({
id: 'firms',
name: 'FIRMS',
feed: { getSnapshot: async () => ({ fires, fetchedAt: Date.now() }) },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const cells = () =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(':cells'),
);
const icons = () =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(':icons'),
);
return {
layer,
viewer,
cells,
icons,
globe,
cleanup() {
layer.destroy(viewer);
input.destroy();
Cesium.SceneTransforms.worldToWindowCoordinates = saved.project;
for (const key of ['window', 'document'])
if (saved[key] === undefined) delete globalThis[key];
else globalThis[key] = saved[key];
},
};
}
/** Put the camera at `heightM` and run a frame past the LOD check's throttle. */
function moveTo(h, heightM) {
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
heightM,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
heightM,
);
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
try {
h.viewer.scene.preRender.raiseEvent();
} finally {
performance.now = now;
}
}
test('far out, one heatmap is draped through the globe port and the markers under it are hidden', async () => {
const h = harness(
[raw(30.5, -98.2, 1500), raw(30.6, -98.3, 20), raw(-12.1, 131.4, 5)],
12_000_000,
);
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
assert.equal(h.cells().items.size, 0, 'no heat rectangles any more');
const [heat] = h.globe.imagery.list();
assert.equal(h.globe.imagery.list().length, 1);
assert.equal(heat.spec.kind, 'single-image');
assert.deepEqual(heat.spec.rectangle, {
west: -180,
south: -90,
east: 180,
north: 90,
});
assert.equal(heat.show, true);
assert.equal(heat.alpha, 1, 'past the hand-off: all heat');
// The nearest band's markers stay built for the hand-off, hidden.
assert.equal(h.icons().items.size, 3);
assert.equal(h.icons().show, false);
h.layer.disable();
assert.equal(heat.show, false, 'hidden with the layer');
h.layer.destroy(h.viewer);
assert.equal(h.globe.imagery.list().length, 0, 'destroy takes it down');
assert.equal(h.icons(), undefined);
} finally {
h.cleanup();
}
});
for (const sceneFromViewer of [false, true]) {
const title = sceneFromViewer
? "with no query or frame port, the layer still follows the camera through ports built over the viewer's scene"
: 'zooming in cross-fades the heatmap out and the markers in';
test(title, async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000, {
sceneFromViewer,
});
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
const [heat] = h.globe.imagery.list();
assert.equal(heat.alpha, 1);
assert.equal(h.icons().show, false);
// Half way through the hand-off (3,600 to 5,400 km): both show.
moveTo(h, 4_500_000);
assert.equal(heat.alpha, 0.5);
assert.equal(h.icons().show, true);
assert.equal([...h.icons().items.values()][0].alpha, 0.5);
// Close in: markers alone; the heatmap stays mapped at alpha 0.
moveTo(h, 500_000);
assert.equal(heat.alpha, 0);
assert.equal(heat.show, true);
assert.equal(h.icons().show, true);
assert.equal([...h.icons().items.values()][0].alpha, 1);
} finally {
h.cleanup();
}
});
}
+48 -24
View File
@@ -1,16 +1,26 @@
/**
* Drapes the Active Fires heat raster over the globe as one full-extent
* imagery tile on the active imagery host (globe or 3D-tiles), like the wind
* layer's scalar field. Owns the canvas and the imagery layer; nothing else
* in the fires layer touches imagery.
* image on the renderer's imagery (`globe.imagery`, the globe port), like
* the wind layer's scalar field. It drapes on whatever the map stack draws
* (the globe's surface, or the 3D tiles). Owns the canvas and the imagery
* layer; nothing else in the fires layer touches imagery.
*
* `show` is only for the layer being on or off. The zoom hand-off fades
* `alpha` instead: Cesium unmaps a hidden imagery layer from the globe
* tiles and re-maps it when shown, so a show toggle at the band edge left
* `alpha` instead: a renderer may unmap a hidden imagery layer from the
* surface and re-map it when shown, so a show toggle at the band edge left
* a beat with neither markers nor heat. At alpha 0 the layer stays mapped
* and costs no draw.
*/
const WORLD = Object.freeze({ west: -180, south: -90, east: 180, north: 90 });
/**
* Drawn over the port's other imagery (zOrder 0) and under the weather
* layers (`WEATHER_IMAGERY_Z` starts at 1), so weather turned on after the
* heat stacks above it, as each weather frame went on top of the stack.
*/
export const HEAT_IMAGERY_Z = 0.5;
const defaultCanvas = (width, height) => {
const canvas = document.createElement('canvas');
canvas.width = width;
@@ -18,44 +28,57 @@ const defaultCanvas = (width, height) => {
return canvas;
};
export function createHeatImagery({
cesium,
getHost,
createCanvas = defaultCanvas,
}) {
/**
* @param {object} options
* @param {() => {globe: object|null, kind: string}|null} options.getHost
* Where draped imagery goes now: the renderer's globe port, and the kind
* of surface the active map stack drapes on (`'none'`: nothing to drape
* on, so nothing is draped).
* @param {(width: number, height: number) => object} [options.createCanvas]
*/
export function createHeatImagery({ getHost, createCanvas = defaultCanvas }) {
let raster = null;
let layer = null;
let collection = null;
/** The host the layer is draped on: its globe port and kind. */
let globe = null;
let kind = 'none';
let show = true;
let opacity = 1;
const hostNow = () => {
const host = getHost?.();
return host?.globe && host.kind !== 'none'
? host
: { globe: null, kind: 'none' };
};
function detach() {
if (layer && collection) collection.remove(layer, true);
layer?.remove();
layer = null;
collection = null;
globe = null;
kind = 'none';
}
function attach() {
detach();
if (!raster) return;
const host = getHost?.() ?? { collection: null, kind: 'none' };
if (!host.collection) return;
const host = hostNow();
if (!host.globe) return;
const canvas = createCanvas(raster.width, raster.height);
const ctx = canvas.getContext('2d');
const image = ctx.createImageData(raster.width, raster.height);
image.data.set(raster.rgba);
ctx.putImageData(image, 0, 0);
const provider = new cesium.SingleTileImageryProvider({
layer = host.globe.imagery.add({
kind: 'single-image',
url: canvas.toDataURL('image/png'),
tileWidth: raster.width,
tileHeight: raster.height,
rectangle: cesium.Rectangle.MAX_VALUE,
rectangle: WORLD,
zOrder: HEAT_IMAGERY_Z,
});
collection = host.collection;
layer = collection.addImageryProvider(provider);
globe = host.globe;
kind = host.kind;
layer.show = show;
layer.alpha = opacity;
collection.raiseToTop?.(layer);
}
return {
@@ -76,9 +99,10 @@ export function createHeatImagery({
opacity = Math.min(1, Math.max(0, Number(value) || 0));
if (layer) layer.alpha = opacity;
},
/** Drape again when the map stack's surface has changed. */
rehome() {
const host = getHost?.();
if ((host?.collection ?? null) !== collection) attach();
const host = hostNow();
if (host.globe !== globe || host.kind !== kind) attach();
},
destroy() {
detach();
+46 -26
View File
@@ -7,27 +7,25 @@ import { HEAT_RASTER } from './policy.js';
function harness() {
const layers = [];
const removed = [];
const collection = {
addImageryProvider(provider) {
const layer = { provider, show: true, alpha: 1 };
layers.push(layer);
return layer;
},
remove(layer, destroy) {
layers.splice(layers.indexOf(layer), 1);
removed.push({ layer, destroy });
},
raiseToTop() {},
};
let host = { collection, kind: 'globe' };
const cesium = {
Rectangle: { MAX_VALUE: { max: true } },
SingleTileImageryProvider: class {
constructor(options) {
this.options = options;
}
// The renderer's globe port, reduced to its imagery.
const globe = {
imagery: {
add(spec) {
const layer = {
spec,
show: true,
alpha: 1,
remove() {
layers.splice(layers.indexOf(layer), 1);
removed.push(layer);
},
};
layers.push(layer);
return layer;
},
},
};
let host = { globe, kind: 'globe' };
const createCanvas = (w, h) => ({
width: w,
height: h,
@@ -40,11 +38,16 @@ function harness() {
toDataURL: () => 'data:image/png;base64,AAAA',
});
const imagery = createHeatImagery({
cesium,
getHost: () => host,
createCanvas,
});
return { imagery, layers, removed, collection, setHost: (h) => (host = h) };
return {
imagery,
layers,
removed,
globe,
setHost: (h) => (host = h),
};
}
const raster = { width: 4, height: 2, rgba: new Uint8ClampedArray(32) };
@@ -53,11 +56,19 @@ test('setRaster drapes one full-globe tile and replaces it on the next build', (
const h = harness();
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 1);
assert.deepEqual(h.layers[0].provider.options.rectangle, { max: true });
assert.equal(h.layers[0].provider.options.tileWidth, 4);
assert.equal(h.layers[0].spec.kind, 'single-image');
assert.deepEqual(h.layers[0].spec.rectangle, {
west: -180,
south: -90,
east: 180,
north: 90,
});
assert.equal(h.layers[0].spec.url, 'data:image/png;base64,AAAA');
assert.equal(h.layers[0].spec.zOrder, 0.5, 'over the other imagery');
const first = h.layers[0];
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 1, 'never two heat layers');
assert.equal(h.removed[0].destroy, true);
assert.deepEqual(h.removed, [first]);
});
test('setShow toggles without rebuilding', () => {
@@ -89,12 +100,21 @@ test('setOpacity fades the same layer and survives a rebuild', () => {
test('no imagery host keeps nothing draped; rehome brings it back', () => {
const h = harness();
h.setHost({ collection: null, kind: 'none' });
h.setHost({ globe: h.globe, kind: 'none' });
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 0);
h.setHost({ collection: h.collection, kind: 'globe' });
h.setHost({ globe: h.globe, kind: 'globe' });
h.imagery.rehome();
assert.equal(h.layers.length, 1);
// The same surface: nothing is draped again.
const kept = h.layers[0];
h.imagery.rehome();
assert.equal(h.layers[0], kept);
// The map stack moves to 3D tiles: draped again, once.
h.setHost({ globe: h.globe, kind: 'tileset' });
h.imagery.rehome();
assert.equal(h.layers.length, 1);
assert.notEqual(h.layers[0], kept);
});
test('destroy removes the layer', () => {
+1 -1
View File
@@ -8,7 +8,7 @@ test('reenabling an empty filtered layer never reveals the retained pre-filter h
const layerState = {
_enabled: false,
_viewer: {},
_dataSource: {},
_cells: {},
_fires: [],
_loading: true,
_pickIndexById: new Map(),
+9 -1
View File
@@ -3,6 +3,10 @@ import { fireDetectionKey } from '../../data/firmsLabels.js';
import { filterFires } from '../../data/firmsIntensity.js';
import { msg } from '../../i18n/index.js';
/** A time a Date can print: epoch ms within JavaScript's date range. */
const isSnapshotEnd = (value) =>
Number.isFinite(value) && Math.abs(value) <= 8_640_000_000_000_000;
export function createIngestion({
layerState,
services,
@@ -16,7 +20,7 @@ export function createIngestion({
/** Replace a validated snapshot while preserving source freshness and selection identity. */
async function loadHeatmap() {
if (!layerState._dataSource || !layerState._enabled) return;
if (!layerState._cells || !layerState._enabled) return;
layerState.request?.abort();
const request = new AbortController();
layerState.request = request;
@@ -32,6 +36,7 @@ export function createIngestion({
return;
if (payload.keyRequired) {
layerState._keyRequired = true;
layerState._at = null;
layerState._error = null;
layerState._stale = false;
return;
@@ -39,6 +44,9 @@ export function createIngestion({
layerState._keyRequired = false;
layerState._error = null;
layerState._stale = Boolean(payload?.stale);
// A snapshot of the 24 hours to a set time names it; one of the
// trailing 24 hours to now does not.
layerState._at = isSnapshotEnd(payload?.at) ? payload.at : null;
const previousSelection = layerState._selectedFire;
layerState._selectedFire = null;
layerState._allFires = adaptFirmsRecords(payload?.fires);
+23 -31
View File
@@ -1,6 +1,13 @@
import * as Cesium from 'cesium';
import { drawOf } from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
/**
* The layer's shape sets start with this; each layer has its own
* (`firms:1:cells`, …), so several can share a renderer.
*/
export const FIRMS_CELL_SET_PREFIX = 'firms';
let instances = 0;
export function createLifecycle({
layerState,
services,
@@ -9,7 +16,6 @@ export function createLifecycle({
feed,
}) {
const { registerPickOwner, unregisterPickOwner } = services.picking;
const { restoreSpriteOrderOnEnable } = services.sprites;
const { clearSelectedEntityContextForLayer } = services.context;
const { id, overlayHost } = config;
@@ -31,28 +37,22 @@ export function createLifecycle({
init(viewer) {
if (layerState._destroyed) return;
layerState._viewer = viewer;
layerState._dataSource = new Cesium.CustomDataSource(id);
layerState._dataSource.show = false;
viewer.dataSources.add(layerState._dataSource);
layerState._cells = drawOf(viewer).shapes({
id: `${FIRMS_CELL_SET_PREFIX}:${++instances}:cells`,
clampTo: 'both',
show: false,
});
},
async enable(viewer) {
if (layerState._destroyed) return;
layerState._enabled = true;
layerState._viewer = viewer;
if (!layerState._dataSource) this.init(viewer);
if (layerState._dataSource) layerState._dataSource.show = true;
if (layerState._billboards) {
// The camera can have moved anywhere while the layer was off: moveEnd
// was not being listened to, and the preRender watcher is inert while
// disabled AND while the (untimed) refetch below is in flight. So the
// retained per-sprite show flags describe the OLD viewpoint. Re-cull
// BEFORE the collection becomes visible — otherwise re-enabling at a
// new location flashes far-side fires through the planet (and keeps
// near-side ones hidden) until the fetch resolves.
components.rendering.refreshHorizonCulling();
layerState._billboards.show = true;
}
if (!layerState._cells) this.init(viewer);
if (layerState._cells) layerState._cells.show = true;
// The GPU culls the far side each frame, so retained rows are right
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, true);
// A filter can leave an old raster cached while the current set is empty.
layerState._heatImagery?.setShow(layerState._fires.length > 0);
@@ -66,12 +66,6 @@ export function createLifecycle({
);
if (!layerState._fires.length && !layerState._loading)
await components.ingestion.loadHeatmap();
if (
layerState._enabled &&
!layerState._destroyed &&
layerState._viewer === viewer
)
restoreSpriteOrderOnEnable('firms', viewer);
},
disable() {
@@ -80,8 +74,8 @@ export function createLifecycle({
layerState._loading = false;
layerState._enabled = false;
components.selection.clearFireSelection();
if (layerState._dataSource) layerState._dataSource.show = false;
if (layerState._billboards) layerState._billboards.show = false;
if (layerState._cells) layerState._cells.show = false;
if (layerState._icons) layerState._icons.show = false;
layerState._heatImagery?.setShow(false);
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
@@ -103,10 +97,8 @@ export function createLifecycle({
components.viewport.removeMoveEndWatcher();
components.selection.removeClickHandler();
unregisterPickOwner(id);
if (layerState._dataSource && viewer) {
viewer.dataSources.remove(layerState._dataSource, true);
}
layerState._dataSource = null;
layerState._cells?.dispose();
layerState._cells = null;
components.rendering.removeDetectionCollections(viewer);
components.selection.clearContextRegistrations();
clearSelectedEntityContextForLayer(id);
@@ -127,6 +119,7 @@ export function createLifecycle({
layerState._rowControlsListener = null;
layerState._cellCount = 0;
layerState._lastUpdate = null;
layerState._at = null;
layerState._keyRequired = false;
layerState._stale = false;
layerState._error = null;
@@ -140,7 +133,6 @@ export function createLifecycle({
layerState._labelLodDistance = 0;
layerState._pickIndexById.clear();
layerState._fireByCardId.clear();
layerState._cullPositions.length = 0;
layerState._camSnapValid = false;
},
};
+97 -104
View File
@@ -1,4 +1,11 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { rectangleHeight, rectangleWidth } from '../../geo/rectangle.js';
import {
PI_OVER_TWO,
TWO_PI,
negativePiToPi,
toDegrees,
} from '../../geo/vector.js';
import { formatNumber, getLocale, isolate, t, tn } from '../../i18n/index.js';
import {
satelliteShortName,
@@ -10,10 +17,10 @@ import { FRP_RAMP, frpRampStop } from '../../data/firmsIntensity.js';
import {
VIEW_PADDING,
DETECTION_COLOR_STOPS,
CULL_LIFT_THRESHOLD_M,
CULL_LIFT_M,
GLOW_SPRITE_PX,
LABEL_MIN_SEP_PX,
} from './policy.js';
import { ICON_CULL_HEIGHT_M } from '../../data/iconSet.js';
export function createModel({
layerState,
@@ -59,35 +66,36 @@ export function createModel({
* Expand a view rectangle by VIEW_PADDING per side and convert to degree
* bounds with an explicit anti-meridian wrap flag. Returns null for
* near-global views where clipping would be pointless.
* @param {Cesium.Rectangle} rect - Camera view rectangle (radians).
* @param {{west: number, south: number, east: number, north: number}} rect
* Camera view rectangle, radians.
* @returns {?{west: number, south: number, east: number, north: number, wraps: boolean}}
*/
function paddedDegreeBounds(rect) {
const width = Cesium.Rectangle.computeWidth(rect);
const height = Cesium.Rectangle.computeHeight(rect);
const width = rectangleWidth(rect);
const height = rectangleHeight(rect);
if (width >= Math.PI * 1.85) return null;
const padLon = width * VIEW_PADDING;
const padLat = height * VIEW_PADDING;
const south = Math.max(-Cesium.Math.PI_OVER_TWO, rect.south - padLat);
const north = Math.min(Cesium.Math.PI_OVER_TWO, rect.north + padLat);
const south = Math.max(-PI_OVER_TWO, rect.south - padLat);
const north = Math.min(PI_OVER_TWO, rect.north + padLat);
let west = rect.west - padLon;
let east = rect.east + padLon;
let wraps;
if (width + padLon * 2 >= Cesium.Math.TWO_PI) {
if (width + padLon * 2 >= TWO_PI) {
west = -Math.PI;
east = Math.PI;
wraps = false;
} else {
west = Cesium.Math.negativePiToPi(west);
east = Cesium.Math.negativePiToPi(east);
west = negativePiToPi(west);
east = negativePiToPi(east);
wraps = west > east;
}
return {
west: Cesium.Math.toDegrees(west),
south: Cesium.Math.toDegrees(south),
east: Cesium.Math.toDegrees(east),
north: Cesium.Math.toDegrees(north),
west: toDegrees(west),
south: toDegrees(south),
east: toDegrees(east),
north: toDegrees(north),
wraps,
};
}
@@ -125,7 +133,7 @@ export function createModel({
* Intensity alone drives the color: confidence feeds the card text and the
* switch, brightness is unreliable (saturates at 367 K) — see HAL-675.
* @param {number} frp - Megawatts.
* @returns {{name: string, minFrp: number, color: Cesium.Color}}
* @returns {{name: string, minFrp: number, color: number[]}}
*/
function frpColorStop(frp) {
@@ -139,7 +147,7 @@ export function createModel({
/**
* Pick a sprite color stop for one detection from its FRP on the shared ramp.
* @param {Object} fire - Detection record.
* @returns {{name: string, color: Cesium.Color}}
* @returns {{name: string, color: number[]}}
*/
function detectionColorStop(fire) {
@@ -164,18 +172,17 @@ export function createModel({
/**
* Build (and cache) a radial-glow sprite: hot near-white center fading
* through the stop color to a transparent edge. The glow lives in the
* sprite itself because global bloom defaults OFF.
* @param {{name: string, color: Cesium.Color}} stop - Color stop.
* @param {number} corePx - Bucketed core size in pixels.
* sprite itself because global bloom defaults OFF. One raster per color
* (GLOW_SPRITE_PX); each fire draws it at its own size.
* @param {{name: string, color: number[]}} stop - Color stop.
* @returns {string} PNG data URL.
*/
function glowSprite(stop, corePx) {
const key = `${stop.name}:${corePx}`;
const cached = layerState.glowSpriteCache.get(key);
function glowSprite(stop) {
const cached = layerState.glowSpriteCache.get(stop.name);
if (cached) return cached;
const dimension = corePx * 2;
const dimension = GLOW_SPRITE_PX;
const canvas = document.createElement('canvas');
canvas.width = dimension;
canvas.height = dimension;
@@ -183,9 +190,9 @@ export function createModel({
if (!context) return '';
const radius = dimension / 2;
const rgb = [
Math.round(stop.color.red * 255),
Math.round(stop.color.green * 255),
Math.round(stop.color.blue * 255),
Math.round(stop.color[0] * 255),
Math.round(stop.color[1] * 255),
Math.round(stop.color[2] * 255),
].join(',');
const gradient = context.createRadialGradient(
radius,
@@ -203,12 +210,12 @@ export function createModel({
context.fillRect(0, 0, dimension, dimension);
const dataUrl = canvas.toDataURL('image/png');
layerState.glowSpriteCache.set(key, dataUrl);
layerState.glowSpriteCache.set(stop.name, dataUrl);
return dataUrl;
}
/**
* Lazily-cached Cartesian3 anchor at the shared ground floor (DEM/mesh cell
* Lazily-cached ECEF anchor at the shared ground floor (DEM/mesh cell
* + lift) when the floor is warm, else ellipsoid height 0 (owner field
* finding 2026-07-21: height-0 anchors read as buried under high terrain at
* close/oblique zoom). Warm-cache read only — floors are warmed in batch by
@@ -219,13 +226,13 @@ export function createModel({
* free either way (contacts are ALWAYS visible — never below the surface,
* slightly above is fine).
* @param {Object} fire - Detection record.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function firePosition(fire) {
const height = fireAnchorHeight(fire.lat, fire.lon);
if (!fire.position || fire.positionHeight !== height) {
fire.position = Cesium.Cartesian3.fromDegrees(fire.lon, fire.lat, height);
fire.position = fromDegrees(fire.lon, fire.lat, height);
fire.positionHeight = height;
}
return fire.position;
@@ -237,7 +244,7 @@ export function createModel({
* difference is invisible, so tens of thousands of markers skip a cache
* read each per rebuild. Builds one through {@link firePosition} once.
* @param {Object} fire - Detection record.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function fireBuiltPosition(fire) {
@@ -247,22 +254,22 @@ export function createModel({
/**
* Occlusion-test anchor for one detection. Returns the render position
* outright for anchors comfortably above the ellipsoid (the common case) and
* a lazily-cached lifted point otherwise — see CULL_LIFT_THRESHOLD_M. This
* NEVER feeds rendering: the datum-correct anchor from {@link firePosition}
* is what the sprite and the card are drawn at.
* a lazily-cached lifted point otherwise, the point the icon set's GPU
* horizon test judges a fire row at (ICON_CULL_LIFT), so a card shows exactly
* when its sprite does. In negative-geoid coastal regions the floored anchor
* lands tens of metres BELOW the WGS84 ellipsoid, which the occluder judges
* beyond the horizon while true-surface neighbours stay visible. This NEVER
* feeds rendering: the datum-correct anchor from {@link firePosition} is what
* the sprite and the card are drawn at.
* @param {Object} fire - Detection record.
* @param {Cesium.Cartesian3} [position] Its render anchor, if at hand.
* @returns {Cesium.Cartesian3}
* @param {{x: number, y: number, z: number}} [position] Its render anchor, if at hand.
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function fireCullPosition(fire, position = firePosition(fire)) {
if (fire.positionHeight >= CULL_LIFT_THRESHOLD_M) return position;
if (fire.positionHeight >= ICON_CULL_HEIGHT_M) return position;
if (!fire.cullPosition) {
fire.cullPosition = Cesium.Cartesian3.fromDegrees(
fire.lon,
fire.lat,
CULL_LIFT_M,
);
fire.cullPosition = fromDegrees(fire.lon, fire.lat, ICON_CULL_HEIGHT_M);
}
return fire.cullPosition;
}
@@ -273,58 +280,18 @@ export function createModel({
* boundary case, so they get the same lift as sub-ellipsoid fire anchors.
* @param {number} lon - Cell center longitude in degrees.
* @param {number} lat - Cell center latitude in degrees.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function cellCullPosition(lon, lat) {
return Cesium.Cartesian3.fromDegrees(lon, lat, CULL_LIFT_M);
}
/**
* Horizon-cull a billboard collection against an ellipsoid occluder.
*
* The Cesium globe is hidden in this app (Google 3D Tiles render the planet),
* so nothing writes far-side depth — and these sprites are additionally
* always-on-top (`disableDepthTestDistance: INFINITY`, so a detection is never
* swallowed by terrain it sits on). Without an explicit occluder pass, fires on
* the opposite side of the Earth shine through the planet at tilted mid-altitude
* views. Same pattern as the flights/CCTV layers' `EllipsoidalOccluder` passes.
*
* Pure and allocation-free: reads `billboard.position`, writes `billboard.show`
* only when it actually flips (assigning `show` dirties the collection's vertex
* buffer). Accepts any `{length, get(i)}` shape so it is unit-testable without
* a WebGL scene.
*
* @param {?{length: number, get: function(number): (Object|undefined)}} billboards
* Billboard collection (or collection-shaped stub).
* @param {?{isPointVisible: function(Object): boolean}} occluder Horizon occluder.
* @param {?Array<Cesium.Cartesian3>} [cullPositions=null] Index-aligned lifted
* occlusion-test anchors (see {@link fireCullPosition}); falls back to the
* billboard's own render position wherever an entry is absent.
* @returns {number} Count of billboards left visible (0 when nothing to test).
*/
function applyHorizonCull(billboards, occluder, cullPositions = null) {
if (!billboards || typeof billboards.get !== 'function') return 0;
if (typeof occluder?.isPointVisible !== 'function') return 0;
const total = Number(billboards.length) || 0;
let visibleCount = 0;
for (let i = 0; i < total; i += 1) {
const billboard = billboards.get(i);
if (!billboard) continue;
const point = (cullPositions && cullPositions[i]) || billboard.position;
const visible = occluder.isPointVisible(point) === true;
if (billboard.show !== visible) billboard.show = visible;
if (visible) visibleCount += 1;
}
return visibleCount;
return fromDegrees(lon, lat, ICON_CULL_HEIGHT_M);
}
/**
* True when `screen` is at least LABEL_MIN_SEP_PX away from every accepted
* screen position (greedy declutter accept test).
* @param {Array<{x: number, y: number}>} accepted - Accepted label positions.
* @param {Cesium.Cartesian2} screen - Candidate window coordinates.
* @param {{x: number, y: number}} screen - Candidate window coordinates.
* @returns {boolean}
*/
@@ -343,7 +310,7 @@ export function createModel({
* (on top) and never distance-faded by the overlay.
* Exported for unit tests.
* @param {Object} fire - Detection record.
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -384,9 +351,10 @@ export function createModel({
* Card model for an ambient fire detection, e.g. title "▲ 47 MW", detail
* "high · 14h · N20". Ages are computed against each detection's acquisition
* time — with the live feed everything reads under 24 h (and a stale cache
* reads truthfully old). Exported for unit tests.
* @param {{fire: Object, position: Cesium.Cartesian3}} candidate - Label candidate.
* @param {number} nowMs - Current epoch milliseconds.
* reads truthfully old); `nowMs` is the time ages count back from, the end
* of the window shown (see {@link ageReferenceMs}). Exported for unit tests.
* @param {{fire: Object, position: {x: number, y: number, z: number}}} candidate - Label candidate.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -417,8 +385,8 @@ export function createModel({
* Card model for an aggregated heat cell, e.g. title "14 FIRES", detail
* "max 210 MW · new 3h". Accent comes from the candidate (renderHeat sets
* it with {@link cellCardAccent}). Exported for unit tests.
* @param {{cell: Object, position: Cesium.Cartesian3, accent: string}} candidate
* @param {number} nowMs - Current epoch milliseconds.
* @param {{cell: Object, position: {x: number, y: number, z: number}, accent: string}} candidate
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -535,14 +503,39 @@ export function createModel({
return `${isolate(latPart)} ${isolate(lonPart)}`;
}
/**
* Millisecond delta → `{ unit: '<1h' | 'h' | 'd', count }`, or null for
* invalid input. Both age formatters read it, so they pick the same unit.
*/
function ageParts(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return null;
const hours = deltaMs / 3600000;
if (hours < 1) return { unit: '<1h', count: 0 };
const wholeHours = Math.round(hours);
if (wholeHours < 48) return { unit: 'h', count: wholeHours };
return { unit: 'd', count: Math.round(hours / 24) };
}
/**
* The time a card's ages count back from: the end of the 24 hours shown
* when the snapshot ends at a set time, now while it runs to now. A window
* that ended months ago then reads its fires as hours old, as they were.
* @param {number} [nowMs] - Current epoch milliseconds.
* @returns {number}
*/
function ageReferenceMs(nowMs = Date.now()) {
const at = layerState?._at;
return Number.isFinite(at) ? at : nowMs;
}
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
function formatAge(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return '<1h';
if (hours < 48) return `${Math.round(hours)}h`;
return `${Math.round(hours / 24)}d`;
const age = ageParts(deltaMs);
if (!age) return '';
return age.unit === '<1h' ? '<1h' : `${age.count}${age.unit}`;
}
/** Millisecond delta → "<1m ago" / "Xm ago" / "Xh ago" (fresh-feed readout). */
@@ -573,12 +566,12 @@ export function createModel({
/** formatAge for a card: "<1h", "24h", "3d" in the UI language ("24 ч"). */
function formatAgeLabel(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return t('<1h', { context: 'age' });
if (hours < 48)
return t('{count}h', { context: 'age', count: Math.round(hours) });
return t('{count}d', { context: 'age', count: Math.round(hours / 24) });
const age = ageParts(deltaMs);
if (!age) return '';
if (age.unit === '<1h') return t('<1h', { context: 'age' });
return age.unit === 'h'
? t('{count}h', { context: 'age', count: age.count })
: t('{count}d', { context: 'age', count: age.count });
}
/** Normalized 0..1 confidence → low/nominal/high display bucket. */
@@ -603,7 +596,6 @@ export function createModel({
fireBuiltPosition,
fireCullPosition,
cellCullPosition,
applyHorizonCull,
screenSeparated,
buildSelectedFireCard,
buildFireCard,
@@ -612,6 +604,7 @@ export function createModel({
cellCardAccent,
formatLatLon,
formatFrp,
ageReferenceMs,
formatAge,
formatAgeLabel,
formatAgoMinutes,
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
const HOUR_MS = 3600000;
test('a fire age that rounds to 48 hours reads in days, as 48 hours does', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
assert.equal(formatAge(47.4 * HOUR_MS), '47h');
assert.equal(formatAge(47.5 * HOUR_MS), '2d');
assert.equal(formatAge(47.6 * HOUR_MS), '2d');
assert.equal(formatAge(48 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.4 * HOUR_MS), '47h');
assert.equal(formatAgeLabel(47.5 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.6 * HOUR_MS), formatAgeLabel(48 * HOUR_MS));
assert.equal(formatAgeLabel(48 * HOUR_MS), '2d');
} finally {
setLocale(previousLocale);
}
});
test('both fire age formatters agree on invalid, sub-hour and multi-day ages', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
for (const format of [formatAge, formatAgeLabel]) {
assert.equal(format(-1), '');
assert.equal(format(Number.NaN), '');
assert.equal(format(0.5 * HOUR_MS), '<1h');
assert.equal(format(1 * HOUR_MS), '1h');
assert.equal(format(72 * HOUR_MS), '3d');
}
} finally {
setLocale(previousLocale);
}
});
+10 -17
View File
@@ -1,6 +1,6 @@
import { FIRMS_AMBIENT_COHORT_LIMIT } from '../../data/firmsLabels.js';
import { FRP_RAMP } from '../../data/firmsIntensity.js';
import * as Cesium from 'cesium';
import { cssColor } from '../../render/color.js';
/** Client poll interval; the proxy's 30 min TTL is what guards upstream quota. */
@@ -10,7 +10,7 @@ export const REFRESH_INTERVAL_MS = 600_000;
* LOD bands keyed by camera height. `heat` bands (above ~4,500 km) drape a
* Snap Map–style heatmap over the globe (firmsHeatRaster.js); their
* `gridDegrees` aggregation only feeds the "N FIRES" cards. `detections`
* bands render individual fire detections as glow-sprite billboards.
* bands render individual fire detections as glow-sprite icons.
* Labels in every band go through the shared screen-space greedy declutter
* (hard cap MAX_AMBIENT_LABELS) — there are no per-band label knobs.
*/
@@ -111,31 +111,24 @@ export const LABEL_MIN_SEP_PX = 150;
export const LABEL_VIEW_MARGIN_PX = 16;
/**
* Anchors below this height get a separate LIFTED point for occlusion tests
* (never for rendering). Mirrors the flights layer's `cullPosition` idiom
* (`renderAltitudeM < 10` → test at 12 m): `fireAnchorHeight` is ground floor
* + lift, and in negative-geoid coastal regions that lands a few tens of
* metres BELOW the WGS84 ellipsoid — EllipsoidalOccluder then judges such a
* point "beyond the horizon" while its true-surface neighbours stay visible,
* so near-limb fires would blink out for a datum reason.
* Glow sprites are rasterised once per colour at the largest core size
* (frpPixelSize tops out at 28 px, a 56 px sprite) and drawn smaller per fire:
* the gradient stops are relative, so the glow keeps its shape at any size.
*/
export const CULL_LIFT_THRESHOLD_M = 10;
/** Height of the lifted occlusion-test point (flights uses the same 12 m). */
export const CULL_LIFT_M = 12;
export const GLOW_SPRITE_PX = 56;
/**
* Color stops for detection glow sprites and card accents: the
* six-stop ember → white-hot FRP ramp (firmsIntensity.js), weakest first, as Cesium
* colors. Stop names key the glow-sprite cache and the card accents.
* six-stop ember → white-hot FRP ramp (firmsIntensity.js), weakest first, as
* renderer colours `[r, g, b, a]`. Stop names key the glow-sprite cache and
* the card accents.
*/
export const DETECTION_COLOR_STOPS = FRP_RAMP.map((stop) =>
Object.freeze({
name: stop.name,
minFrp: stop.minFrp,
color: Cesium.Color.fromCssColorString(stop.hex),
color: Object.freeze(cssColor(stop.hex)),
}),
);
+19 -7
View File
@@ -8,7 +8,7 @@ import {
rampTrackGradient,
sliderPositionForFrp,
} from '../../data/firmsIntensity.js';
import { formatNumber, t } from '../../i18n/index.js';
import { formatNumber, formatUtcDayMonth, t } from '../../i18n/index.js';
import { LOD_LEVELS, REFRESH_INTERVAL_MS } from './policy.js';
/** Slider resolution: whole-percent positions along the log axis. */
@@ -190,8 +190,9 @@ export function createQueries({
* Layer stats for the data panel. Degraded feed states surface through
* `error` (established qa-failstate pattern: a dead feed must never look
* like a healthy empty layer) with a matching human `loadingLabel`:
* 'LIVE · updated Xm ago' fresh, 'STALE · cached Xh' when the proxy
* served past-TTL cache, 'KEY REQUIRED' keyless.
* 'LIVE · updated Xm ago' fresh, '24 h to MM-DD HH:MM UTC' for a
* snapshot that ends at a set time (`at`), 'STALE · cached Xh' when the
* proxy served past-TTL cache, 'KEY REQUIRED' keyless.
*/
getStats() {
const now = Date.now();
@@ -213,6 +214,11 @@ export function createQueries({
loadingLabel = staleText;
} else if (layerState._error) {
loadingLabel = layerState._error;
} else if (Number.isFinite(layerState._at)) {
loadingLabel = t('24 h to {day} {time} UTC', {
day: formatUtcDayMonth(layerState._at),
time: new Date(layerState._at).toISOString().slice(11, 16),
});
} else if (layerState._lastUpdate) {
loadingLabel = t('LIVE · updated {age}', {
age: components.model.formatAgoMinutes(now - layerState._lastUpdate),
@@ -226,6 +232,11 @@ export function createQueries({
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
stale: layerState._stale,
// The end of the 24 hours shown when the snapshot ends at a set time;
// null for the trailing 24 hours to now. Such a snapshot is not live,
// so the row names the provider without the catalog's "LIVE".
at: Number.isFinite(layerState._at) ? layerState._at : null,
...(Number.isFinite(layerState._at) ? { source: 'NASA FIRMS' } : {}),
// The machine-readable half of the keyless state, ahead of the human
// strings below: without it "no key configured" is indistinguishable
// from a broken feed, and the row reads as a fault instead of a step
@@ -267,7 +278,8 @@ export function createQueries({
* layer's greedy declutter as the SELECTOR and the shared overlay remains
* the renderer. Walks the FRP-sorted index so the strongest fires come first.
* @param {{maxCount?: number}} [options]
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string}>}
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string}>}
* Positions are ECEF.
*/
getDetectableObjects(options = {}) {
if (!layerState._enabled || !layerState._firesByFrp.length) return [];
@@ -322,9 +334,9 @@ export function createQueries({
components.rendering.applyHandoffFade();
},
/** Test seam: entities drawn by the layer's data source. */
/** Test seam: shapes drawn in the layer's own set (none: the heat is imagery). */
_entityCountForTest() {
return layerState._dataSource?.entities?.values?.length ?? 0;
return layerState._cells?.size() ?? 0;
},
/** Test seam that binds the production click path and indexes. */
@@ -339,13 +351,13 @@ export function createQueries({
layerState._totalCount = fires.length;
layerState._pickIndexById.clear();
layerState._labelLodDistance = 1e7;
components.rendering.ensureDetectionCollections();
layerState._labelCandidates = fires.map((fire) => {
layerState._pickIndexById.set(`firms-${fire.index}`, fire);
return { fire, position: components.model.firePosition(fire) };
});
components.cards.rebuildAmbientLabels();
components.selection.installClickHandler();
return layerState._clickHandler;
},
};
+159 -105
View File
@@ -1,20 +1,29 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import {
drawOf,
findFrame,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { buildHeatRaster } from '../../data/firmsHeatRaster.js';
import {
LOD_LEVELS,
CONTEXT_TOP_N,
GLOW_SPRITE_PX,
HANDOFF_FADE,
HEAT_RASTER,
HEAT_REBUILD_MS,
} from './policy.js';
import { createHeatImagery } from './heatImagery.js';
/** Icon sets made so far, by every fire layer: set ids unique to each. */
let iconSets = 0;
/** The markers drawn under the far bands' heatmap for the hand-off fade. */
const HANDOFF_MARKER_LOD = LOD_LEVELS.find((lod) => lod.mode === 'detections');
/** Fade steps: a moving camera rewrites marker colors at most this often. */
/** Fade steps: a moving camera rewrites marker opacity at most this often. */
const FADE_STEPS = 32;
export function createRendering({
@@ -25,7 +34,7 @@ export function createRendering({
feed,
}) {
const { warmFireAnchorFloors } = services.anchors;
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { spriteDrawOrder } = services.sprites;
const { overlayHost } = config;
/**
@@ -33,19 +42,18 @@ export function createRendering({
* when neither the (hysteresis-damped) LOD band nor the padded view
* rectangle changed meaningfully.
* @param {boolean} force - Rebuild even if LOD/view appear unchanged.
* @returns {boolean} True when a rebuild actually ran. Callers use this to
* avoid a second horizon walk in the same tick: a rebuild already culls
* its freshly-added sprites, an early-out does not.
* @returns {boolean} True when a rebuild actually ran.
*/
function renderCurrentLod(force = false) {
if (
!layerState._dataSource ||
!layerState._fires.length ||
!layerState._viewer
) {
if (!layerState._cells || !layerState._viewer) return false;
if (!layerState._fires.length) {
// A filter that leaves nothing shown must not leave the old heat behind.
if (!layerState._fires.length) layerState._heatImagery?.setShow(false);
layerState._heatImagery?.setShow(false);
// A refresh that came back empty takes down what the last one drew, so
// no sprite or card is left on screen (and clickable) for a fire that is
// gone.
if (force) clearRendered();
return false;
}
const lodIndex = components.viewport.selectLodIndex(
@@ -61,9 +69,7 @@ export function createRendering({
return false;
layerState._currentLodIndex = lodIndex;
layerState._currentLodId = lod.id;
layerState._lastViewRect = viewRect
? Cesium.Rectangle.clone(viewRect)
: null;
layerState._lastViewRect = viewRect ? { ...viewRect } : null;
const bounds = viewRect
? components.model.paddedDegreeBounds(viewRect)
: null;
@@ -86,7 +92,8 @@ export function createRendering({
applyHandoffFade(true);
}
const fadeColor = new Cesium.Color();
/** The opacity the drawn glows were last written with. */
let glowAlpha = 1;
/**
* Cross-fade between markers and heatmap by camera height (HANDOFF_FADE),
@@ -108,12 +115,44 @@ export function createRendering({
if (!force && heat === layerState._handoffHeat) return;
layerState._handoffHeat = heat;
layerState._heatImagery?.setOpacity(heat);
const billboards = layerState._billboards;
if (!billboards) return;
billboards.show = layerState._enabled && heat < 1;
const color = Cesium.Color.WHITE.withAlpha(1 - heat, fadeColor);
for (let i = 0; i < billboards.length; i += 1)
billboards.get(i).color = color;
// Glows written from here on carry the fade (fireGlow); those already
// drawn are rewritten only when it changed.
const alpha = 1 - heat;
const changed = alpha !== glowAlpha;
glowAlpha = alpha;
const set = layerState._icons;
if (!set) return;
set.show = layerState._enabled && heat < 1;
if (!changed || !drawnGlows.size) return;
const faded = [];
for (const drawn of drawnGlows.values()) {
drawn.glow = { ...drawn.glow, alpha };
faded.push(drawn.glow);
}
set.upsert(faded);
}
/**
* Each drawn glow's detection, anchor and item, by its item id: what it
* was last written with, so a rebuild writes only the glows that changed.
* @type {Map<string, {fire: object, position: object, glow: object}>}
*/
const drawnGlows = new Map();
/** Take every glow down (no write when there are none). */
function clearIcons() {
if (!drawnGlows.size) return;
drawnGlows.clear();
layerState._icons?.clear();
}
function clearRendered() {
clearIcons();
layerState._pickIndexById.clear();
layerState._cellCount = 0;
layerState._labelCandidates = [];
components.cards.rebuildAmbientLabels();
components.selection.refreshContextRegistrations([]);
}
/**
@@ -180,12 +219,13 @@ export function createRendering({
function heatImagery() {
if (!layerState._heatImagery) {
layerState._heatImagery = createHeatImagery({
cesium: Cesium,
getHost: () =>
layerState._imageryHost?.() ?? {
collection: layerState._viewer?.imageryLayers ?? null,
kind: 'globe',
},
// Draped through the renderer's globe port, on the surface the
// active map stack draws (the shell's imagery host names it; without
// a shell, the globe).
getHost: () => ({
globe: findGlobe(layerState._viewer),
kind: layerState._imageryHost?.()?.kind ?? 'globe',
}),
});
}
return layerState._heatImagery;
@@ -260,7 +300,7 @@ export function createRendering({
const centerLon = cell.lonCell + lod.gridDegrees / 2;
const centerLat = cell.latCell + lod.gridDegrees / 2;
layerState._labelCandidates.push({
position: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 0),
position: fromDegrees(centerLon, centerLat, 0),
cullPosition: components.model.cellCullPosition(centerLon, centerLat),
fire: null,
cell,
@@ -276,7 +316,7 @@ export function createRendering({
/**
* Render individual detections (local/close bands) as pre-baked
* radial-glow sprite billboards sized by FRP, capped per viewport by
* radial-glow sprite icons sized by FRP, capped per viewport by
* highest FRP, depth test disabled. The 3D Tiles mesh is never sampled
* per point; instead, the CLOSE band (where terrain parallax is actually
* visible) batch-warms the shared cached DEM floor for its rendered
@@ -321,20 +361,19 @@ export function createRendering({
/**
* The glow-sprite markers for a detections band: the strongest fires in
* view, capped at the band's maxDetections, horizon-culled.
* view, capped at the band's maxDetections. The set culls the far side of
* the globe itself (`horizonCull`).
* @param {Object} lod - Detections band descriptor.
* @param {?Object} bounds - Padded view bounds in degrees, or null.
* @returns {?Array<Object>} Label candidates for the fires drawn,
* strongest first; null before the sprite collection exists.
* strongest first; null before the icon set exists.
*/
function paintMarkers(lod, bounds) {
ensureDetectionCollections();
layerState._dataSource.entities.removeAll();
if (!layerState._billboards) return null;
layerState._billboards.removeAll();
const set = layerState._icons;
if (!set) return null;
layerState._pickIndexById.clear();
layerState._cullPositions.length = 0;
let candidates;
if (bounds) {
@@ -359,96 +398,113 @@ export function createRendering({
lod.id === 'close'
? components.model.firePosition
: components.model.fireBuiltPosition;
// Fires keep their glows across rebuilds: a pan that keeps a fire in
// view rewrites nothing for it, and only glows that left the view go.
const keep = new Set();
const writes = [];
for (const fire of candidates) {
const coreSize = components.model.frpPixelSize(fire.frp);
const position = anchor(fire);
const cullPosition = components.model.fireCullPosition(fire, position);
const pickId = `firms-${fire.index}`;
layerState._pickIndexById.set(pickId, fire);
layerState._cullPositions.push(cullPosition);
keep.add(pickId);
const glow = fireGlow(pickId, fire, position);
if (glow) writes.push({ glow, fire, position });
markers.push({ position, cullPosition, fire, cell: null });
layerState._billboards.add({
id: pickId,
position,
image: components.model.glowSprite(
components.model.detectionColorStop(fire),
components.model.sizeBucket(coreSize),
),
verticalOrigin: Cesium.VerticalOrigin.CENTER,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
});
}
// Freshly-added sprites default to show=true; cull the far side now so a
// rebuild never flashes through-the-planet detections while the camera
// sits still (the moveEnd/preRender hooks only fire on camera motion).
refreshHorizonCulling();
const gone = [];
for (const pickId of drawnGlows.keys())
if (!keep.has(pickId)) gone.push(pickId);
for (const pickId of gone) drawnGlows.delete(pickId);
if (gone.length) set.remove(gone);
if (writes.length) {
set.upsert(writes.map((write) => write.glow));
for (const { glow, fire, position } of writes)
drawnGlows.set(glow.id, { fire, position, glow });
}
return markers;
}
/**
* A fire's glow icon, when it is new or changed since it was last drawn
* (else null): drawn depth-test-free at its anchor (a detection is never
* swallowed by terrain it sits on), with the far side of the globe culled
* by the set's horizon cull each frame. The Cesium globe is hidden here
* (Google 3D Tiles render the planet), so nothing writes far-side depth,
* and the cull is what keeps fires from shining through the planet. The
* anchor moves once, when its floor warms. A refresh reuses indices, so a
* kept id can hold a different detection, restyled then. It is written at
* the hand-off fade's current opacity (applyHandoffFade).
*
* The glow is rasterised once per colour at GLOW_SPRITE_PX and drawn at
* the fire's own size by its scale. Its hold motion draws it on the
* renderer's moving-icon path, which culls the horizon on the GPU.
*/
function fireGlow(pickId, fire, position) {
const drawn = drawnGlows.get(pickId);
if (drawn && drawn.fire === fire && drawn.position === position)
return null;
const corePx = components.model.sizeBucket(
components.model.frpPixelSize(fire.frp),
);
return {
id: pickId,
pos: { x: position.x, y: position.y, z: position.z },
image: components.model.glowSprite(
components.model.detectionColorStop(fire),
),
size: [GLOW_SPRITE_PX, GLOW_SPRITE_PX],
scale: (corePx * 2) / GLOW_SPRITE_PX,
alpha: glowAlpha,
disableDepthTest: Infinity,
motion: { kind: 'hold' },
meta: { layer: 'firms', id: pickId },
};
}
function ensureDetectionCollections() {
if (!layerState._viewer || layerState._billboards) return;
layerState._billboards = new Cesium.BillboardCollection({
scene: layerState._viewer.scene,
blendOption: Cesium.BlendOption.TRANSLUCENT,
if (!layerState._viewer || layerState._icons) return;
const set = drawOf(layerState._viewer).icons({
id: `firms:${++iconSets}:icons`,
// Blended as one translucent pass, as its billboards were.
blend: 'translucent',
horizonCull: true,
show: layerState._enabled && !(layerState._handoffHeat >= 1),
drawOrder: spriteDrawOrder?.('firms') ?? 0,
});
layerState._billboards.show = layerState._enabled;
layerState._viewer.scene.primitives.add(layerState._billboards);
registerSpriteCollection('firms', layerState._billboards);
restoreSpriteOrder(layerState._viewer);
// Columns of no rows put the set's host in the scene now, rather than
// with its first fire.
set.setColumns?.({ ids: [] });
layerState._icons = set;
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, layerState._enabled);
}
function removeDetectionCollections(viewer) {
const scene = viewer?.scene || layerState._viewer?.scene;
if (scene && !scene.isDestroyed?.()) {
try {
if (layerState._billboards)
scene.primitives.remove(layerState._billboards);
} catch {
/* already torn down */
}
}
layerState._billboards = null;
/**
* Let the glow set go, whichever viewer the caller tears down: its
* renderer takes it out of the scene it draws in.
*/
function removeDetectionCollections() {
layerState._icons?.dispose();
layerState._icons = null;
drawnGlows.clear();
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
}
/**
* Shared horizon occluder positioned at the current camera, or null when
* there is no usable camera yet (init order / headless stubs).
* `viewer.camera` and `viewer.scene.camera` are the SAME object in Cesium;
* both are probed so a partial stub (either shape) still gets a real
* occluder rather than silently degrading to "nothing is ever occluded".
* @returns {?Cesium.EllipsoidalOccluder}
* The renderer's query and frame ports the cards and the LOD watcher use:
* the bound renderer's, or for a viewer with no
* renderer bound, those the Cesium adapter builds over it once the
* caller has loaded `./render/cesium/unbound` (`findQuery`, `findFrame`).
* @returns {{query: object|null, frame: object|null}}
*/
function fireHorizonOccluder() {
const camera = layerState._viewer?.camera?.positionWC
? layerState._viewer.camera
: layerState._viewer?.scene?.camera;
if (!camera?.positionWC) return null;
return horizonOccluder(camera);
function scenePorts() {
const viewer = layerState._viewer;
return { query: findQuery(viewer), frame: findFrame(viewer) };
}
/**
* Hide detection sprites that sit beyond the ellipsoid horizon (see
* {@link applyHorizonCull}). Runs on the cadences that already exist in this
* layer — the throttled LOD preRender watcher (camera-moved only), camera
* moveEnd, and each detection rebuild — never as a new per-frame pass.
* No-ops in the `cells` bands, where the collection is empty.
*/
function refreshHorizonCulling() {
if (!layerState._billboards || !layerState._billboards.length) return;
components.model.applyHorizonCull(
layerState._billboards,
fireHorizonOccluder(),
layerState._cullPositions,
);
}
return {
scenePorts,
renderCurrentLod,
renderBand,
aggregateFires,
@@ -457,7 +513,5 @@ export function createRendering({
applyHandoffFade,
ensureDetectionCollections,
removeDetectionCollections,
fireHorizonOccluder,
refreshHorizonCulling,
};
}
+26 -43
View File
@@ -2,8 +2,7 @@ import {
FIRMS_OVERLAY_SOURCE_ID,
fireDetectionKey,
} from '../../data/firmsLabels.js';
import * as Cesium from 'cesium';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { CONTEXT_TOP_N } from './policy.js';
import { t } from '../../i18n/index.js';
@@ -22,7 +21,7 @@ export function createSelection({
getContextStore,
registerEntityContext,
} = services.context;
const { id, name, overlayHost, screenSpaceEventHandlerFactory } = config;
const { id, name, overlayHost } = config;
/**
* Install the LEFT_CLICK handler for fire selection (enable-time only,
@@ -32,15 +31,11 @@ export function createSelection({
*/
function installClickHandler() {
if (layerState._clickHandler || !layerState._viewer) return;
layerState._clickHandler = screenSpaceEventHandlerFactory(
layerState._viewer,
);
layerState._clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
const picked = layerState._viewer.scene.pick(click.position);
const fire = pickedFire(picked);
if (layerState._clickSubscription || !layerState._viewer) return;
const input = inputFor(layerState._viewer);
layerState._clickSubscription = input.onClick((event) => {
const picked = event.topHit;
const fire = pickedFire(event.drawHit);
if (fire) {
selectAndFocusFire(fire);
return;
@@ -52,8 +47,8 @@ export function createSelection({
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
}
const cardHit = overlayHost.hitTest?.(
click.position?.x,
click.position?.y,
event.screenPosition?.x,
event.screenPosition?.y,
{
sourceId: FIRMS_OVERLAY_SOURCE_ID,
},
@@ -64,14 +59,12 @@ export function createSelection({
return;
}
clearFireSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
}
function removeClickHandler() {
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
}
/** Select one stable detection and request one UI-owned camera transfer. */
@@ -87,29 +80,17 @@ export function createSelection({
}
/**
* Resolve a scene pick to one of this layer's fire records, or null.
* BillboardCollection picks surface our id either on picked.primitive.id
* or directly on picked.id depending on the CesiumJS pick path.
* @param {*} picked - Result of scene.pick().
* Resolve a pick to one of this layer's fire records, or null: a hit (a
* draw-port `Hit`, `event.drawHit`) on a glow of the layer's own icon set
* whose id is a fire it draws now.
* @param {?{set: string, id: string}} hit - The renderer's hit.
* @returns {?Object} Fire record.
*/
function pickedFire(picked) {
if (!picked) return null;
const primitiveId = picked.primitive?.id;
if (
typeof primitiveId === 'string' &&
layerState._pickIndexById.has(primitiveId)
) {
return layerState._pickIndexById.get(primitiveId);
}
if (
typeof picked.id === 'string' &&
layerState._pickIndexById.has(picked.id)
) {
return layerState._pickIndexById.get(picked.id);
}
return null;
function pickedFire(hit) {
if (!hit || !layerState._icons || hit.set !== layerState._icons.id)
return null;
return layerState._pickIndexById.get(hit.id) ?? null;
}
/**
@@ -185,14 +166,14 @@ export function createSelection({
// Refreshed every registration: the anchor re-grounds onto the DEM when
// its floor cell warms, and voice targeting must project the same point
// the sprite renders at.
fire.contextEntity.__localBaseCartesian =
components.model.firePosition(fire);
registerEntityContext(fire.contextEntity, {
targetPosition: components.model.firePosition(fire),
id: recordId,
layerId: id,
layerName: name,
source: 'NASA FIRMS',
dataSource: layerState._dataSource,
// Hidden with the layer: the context store reads its `show`.
dataSource: layerState._cells,
// i18n-ignore: English entity label; the voice card translates it (shownEntityLabel)
label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`,
latitude: fire.lat,
@@ -202,7 +183,9 @@ export function createSelection({
confidence: components.model.confidenceBucket(fire.confidence),
age:
fire.acqMs > 0
? components.model.formatAge(Date.now() - fire.acqMs)
? components.model.formatAge(
components.model.ageReferenceMs() - fire.acqMs,
)
: 'unknown',
sensor: fire.sensor || 'unknown',
},
+17 -26
View File
@@ -1,26 +1,25 @@
import * as Cesium from 'cesium';
import { DEFAULT_FIRE_FILTER } from '../../data/firmsIntensity.js';
export function createFirmsState({ services, config }) {
const layerState = {};
/** Pre-baked radial-glow sprites keyed by `<colorStop>:<sizeBucket>`. */
/** Pre-baked radial-glow sprites keyed by color stop name. */
layerState.glowSpriteCache = new Map();
layerState.scratchViewRect = new Cesium.Rectangle();
layerState.scratchCenterA = new Cesium.Cartographic();
layerState.scratchCenterB = new Cesium.Cartographic();
layerState.scratchWindowCoord = new Cesium.Cartesian2();
layerState._viewer = null;
layerState._dataSource = null;
/**
* The layer's own shape set (made at `init`): empty since the heat became
* draped imagery, it marks the layer initialized and carries the `show`
* the context store reads.
*/
layerState._billboards = null;
layerState._cells = null;
/** The detection glows' icon draw set (made with the first render). */
layerState._icons = null;
layerState._enabled = false;
@@ -77,6 +76,8 @@ export function createFirmsState({ services, config }) {
layerState._lastUpdate = null;
layerState._at = null;
layerState._currentLodId = null;
layerState._currentLodIndex = -1;
@@ -91,7 +92,7 @@ export function createFirmsState({ services, config }) {
layerState._contextIds = new Set();
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._moveEndRemover = null;
@@ -111,16 +112,6 @@ export function createFirmsState({ services, config }) {
layerState._fireByCardId = new Map();
/**
* Occlusion-test anchors index-aligned with the billboard collection (the
* collection is cleared and refilled in one ordered pass per rebuild, and
* nothing else adds to it). Lifted where the render anchor sits at/below
* the ellipsoid — see {@link fireCullPosition}.
* @type {Array<Cesium.Cartesian3>}
*/
layerState._cullPositions = [];
/**
* gridDegrees -> heat-sorted full cell list. The full-grid aggregation is
* viewport-independent but walks every detection (~200k live), so it is
@@ -150,7 +141,7 @@ export function createFirmsState({ services, config }) {
layerState._heatImagery = null;
/** Shell-provided imagery host resolver; falls back to viewer.imageryLayers. */
/** Shell-provided imagery host resolver; without one, the globe. */
layerState._imageryHost = null;
@@ -158,9 +149,9 @@ export function createFirmsState({ services, config }) {
layerState._camSnapValid = false;
layerState._camPos = new Cesium.Cartesian3();
layerState._camPos = { x: 0, y: 0, z: 0 };
layerState._camDir = new Cesium.Cartesian3();
layerState._camDir = { x: 0, y: 0, z: 0 };
layerState.request = null;
return layerState;
}
+75 -84
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium';
import {
rectangleCenter,
rectangleHeight,
rectangleWidth,
} from '../../geo/rectangle.js';
import { TWO_PI, toRadians } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
import {
LOD_LEVELS,
LOD_HYSTERESIS,
@@ -6,6 +12,12 @@ import {
LOD_CHECK_MS,
} from './policy.js';
/** Each component of `a` within `epsilon` of `b`'s. */
const near = (a, b, epsilon) =>
Math.abs(a.x - b.x) <= epsilon &&
Math.abs(a.y - b.y) <= epsilon &&
Math.abs(a.z - b.z) <= epsilon;
export function createViewport({
layerState,
services,
@@ -14,6 +26,7 @@ export function createViewport({
feed,
}) {
const { governorRequestRender } = services.render;
const camera = () => findCamera(layerState._viewer);
/**
* Ambient labels are placed via screen-space projection, so they need a
@@ -23,16 +36,10 @@ export function createViewport({
function installMoveEndWatcher() {
if (layerState._moveEndRemover || !layerState._viewer) return;
layerState._moveEndRemover =
layerState._viewer.camera.moveEnd.addEventListener(() => {
if (!layerState._enabled) return;
// Settled-camera exactness for the horizon pass (the throttled preRender
// watcher can last have run up to LOD_CHECK_MS before the camera
// stopped). Runs ahead of the `_loading` gate on purpose: the sprites on
// screen during a refresh are the ones that need culling.
components.rendering.refreshHorizonCulling();
if (layerState._loading) return;
camera()?.on('moveEnd', () => {
if (!layerState._enabled || layerState._loading) return;
components.cards.rebuildAmbientLabels();
});
}) ?? null;
}
function removeMoveEndWatcher() {
@@ -43,10 +50,8 @@ export function createViewport({
}
function cameraHeight() {
return (
layerState._viewer?.camera?.positionCartographic?.height ??
Number.POSITIVE_INFINITY
);
const height = camera()?.pose().height;
return Number.isFinite(height) ? height : Number.POSITIVE_INFINITY;
}
/** Raw LOD index for a camera height (0 = global ... 3 = close). */
@@ -84,15 +89,21 @@ export function createViewport({
return index;
}
/** Current camera view rectangle, or null when looking at sky/horizon. */
/**
* Current camera view rectangle, radians, or null when looking at
* sky/horizon.
*/
function computeViewRect() {
try {
const rect = layerState._viewer?.camera?.computeViewRectangle(
layerState._viewer?.scene?.globe?.ellipsoid,
layerState.scratchViewRect,
);
return rect || null;
const rect = camera()?.viewRectangle();
if (!rect) return null;
return {
west: toRadians(rect.west),
south: toRadians(rect.south),
east: toRadians(rect.east),
north: toRadians(rect.north),
};
} catch {
return null;
}
@@ -102,27 +113,25 @@ export function createViewport({
* True when the camera view rectangle drifted far enough from the last
* rendered one that the padding is at risk of being consumed (pan) or
* the footprint changed notably (zoom within a band).
* @param {?Cesium.Rectangle} viewRect - Current view rectangle.
* @param {?{west: number, south: number, east: number, north: number}} viewRect
* Current view rectangle, radians.
* @returns {boolean}
*/
function viewChangedEnough(viewRect) {
if (!viewRect) return false; // sky/horizon — keep the current render
if (!layerState._lastViewRect) return true; // previous render was global fallback
const lastWidth = Cesium.Rectangle.computeWidth(layerState._lastViewRect);
const lastHeight = Cesium.Rectangle.computeHeight(layerState._lastViewRect);
const width = Cesium.Rectangle.computeWidth(viewRect);
const height = Cesium.Rectangle.computeHeight(viewRect);
const lastWidth = rectangleWidth(layerState._lastViewRect);
const lastHeight = rectangleHeight(layerState._lastViewRect);
const width = rectangleWidth(viewRect);
const height = rectangleHeight(viewRect);
if (width > lastWidth * 1.3 || width < lastWidth * 0.75) return true;
if (height > lastHeight * 1.3 || height < lastHeight * 0.75) return true;
const lastCenter = Cesium.Rectangle.center(
layerState._lastViewRect,
layerState.scratchCenterA,
);
const center = Cesium.Rectangle.center(viewRect, layerState.scratchCenterB);
const latShift = Math.abs(center.latitude - lastCenter.latitude);
let lonShift = Math.abs(center.longitude - lastCenter.longitude);
if (lonShift > Math.PI) lonShift = Cesium.Math.TWO_PI - lonShift;
const lastCenter = rectangleCenter(layerState._lastViewRect);
const center = rectangleCenter(viewRect);
const latShift = Math.abs(center.lat - lastCenter.lat);
let lonShift = Math.abs(center.lon - lastCenter.lon);
if (lonShift > Math.PI) lonShift = TWO_PI - lonShift;
return (
latShift > lastHeight * VIEW_PADDING * 0.6 ||
lonShift > lastWidth * VIEW_PADDING * 0.6
@@ -136,63 +145,45 @@ export function createViewport({
// for a frame that idle mode never produces — schedule one. (perf wave 2)
if (!layerState._moveEndSettleRemover) {
layerState._moveEndSettleRemover =
layerState._viewer.camera.moveEnd.addEventListener(() => {
camera()?.on('moveEnd', () => {
if (!layerState._enabled) return;
setTimeout(
() => governorRequestRender('firms-lod-settle'),
LOD_CHECK_MS + 40,
);
});
}) ?? null;
}
layerState._preRenderRemover =
layerState._viewer.scene.preRender.addEventListener(() => {
// NOTE: `_loading`/empty-data are deliberately NOT part of this guard.
// A refresh has no timeout, and sprites from the previous payload stay
// on screen throughout it — so the horizon pass below must keep running
// while a fetch is in flight. Only the rebuild is gated on fresh data.
if (!layerState._enabled) return;
// Every frame, ahead of the throttle: a fast zoom crosses the whole
// hand-off between two band checks.
components.rendering.applyHandoffFade();
const now = performance.now();
if (now - layerState._lastLodCheck < LOD_CHECK_MS) return;
layerState._lastLodCheck = now;
// Idle camera: two scratch compares and out — no view-rect math, no
// aggregation, no allocation while the user is parked.
const camera = layerState._viewer.camera;
if (
layerState._camSnapValid &&
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
layerState._camPos,
0,
0.5,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
layerState._camDir,
0,
1e-7,
)
) {
return;
}
Cesium.Cartesian3.clone(camera.positionWC, layerState._camPos);
Cesium.Cartesian3.clone(camera.directionWC, layerState._camDir);
layerState._camSnapValid = true;
// The camera moved, so the horizon moved. A rebuild culls its own fresh
// sprites (renderDetections); an early-out — same LOD band and view
// rect, or a refresh in flight — does not, so cull here instead.
// Exactly ONE occlusion walk per tick either way, bounded by the
// idle-gate + LOD_CHECK_MS throttle above: a parked camera costs
// nothing, a moving one pays one ≤maxDetections show-flip walk at
// ~1.5 Hz.
const rebuilt =
layerState._fires.length && !layerState._loading
? components.rendering.renderCurrentLod(false)
: false;
if (!rebuilt) components.rendering.refreshHorizonCulling();
});
const { frame } = components.rendering.scenePorts();
if (!frame) return;
layerState._preRenderRemover = frame.on('preRender', () => {
// NOTE: `_loading`/empty-data are deliberately NOT part of this guard.
// A refresh has no timeout, and sprites from the previous payload stay
// on screen throughout it — so the hand-off fade below must keep running
// while a fetch is in flight. Only the rebuild is gated on fresh data.
if (!layerState._enabled) return;
// Every frame, ahead of the throttle: a fast zoom crosses the whole
// hand-off between two band checks.
components.rendering.applyHandoffFade();
const now = performance.now();
if (now - layerState._lastLodCheck < LOD_CHECK_MS) return;
layerState._lastLodCheck = now;
// Idle camera: two compares and out — no view-rect math and no
// aggregation while the user is parked.
const pose = camera()?.pose();
if (!pose) return;
if (
layerState._camSnapValid &&
near(pose.position, layerState._camPos, 0.5) &&
near(pose.direction, layerState._camDir, 1e-7)
) {
return;
}
layerState._camPos = pose.position;
layerState._camDir = pose.direction;
layerState._camSnapValid = true;
if (layerState._fires.length && !layerState._loading)
components.rendering.renderCurrentLod(false);
});
}
function removeLodWatcher() {
+102
View File
@@ -0,0 +1,102 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
import { createCards } from './cards.js';
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
const now = 1800000000000;
context.mock.method(Date, 'now', () => now);
const previousLocale = getLocale();
const at = Date.UTC(2026, 9, 21, 15);
const layerState = {
_loading: false,
_stale: false,
_keyRequired: false,
_error: null,
_lastUpdate: now - 120000,
_at: at,
_count: 1,
_cellCount: 0,
_fires: [],
};
const model = createModel({ services: { anchors: {} } });
const { methods } = createQueries({
layerState,
components: { model },
config: {},
});
try {
setLocale('en');
assert.equal(methods.getStats().loadingLabel, '24 h to 10-21 15:00 UTC');
assert.equal(methods.getStats().at, at);
assert.equal(methods.getStats().source, 'NASA FIRMS', 'the row drops LIVE');
setLocale('de');
assert.equal(methods.getStats().loadingLabel, '24 h bis 21.10. 15:00 UTC');
layerState._at = null;
setLocale('en');
assert.equal(methods.getStats().loadingLabel, 'LIVE · updated 2m ago');
assert.equal(methods.getStats().at, null);
assert.equal(methods.getStats().source, undefined);
} finally {
setLocale(previousLocale);
}
});
test('fire cards count ages from the end of the window shown, and from now when live', (context) => {
const now = Date.UTC(2026, 10, 14, 12);
context.mock.method(Date, 'now', () => now);
// A window that ended months before now: its newest fire three hours earlier.
const at = Date.UTC(2026, 7, 1, 12);
const layerState = { _at: at };
const model = createModel({ layerState, services: { anchors: {} } });
const cell = {
count: 4,
maxFrp: 210,
newestAcqMs: at - 3 * 3_600_000,
latCell: 1,
lonCell: 2,
};
const previousLocale = getLocale();
try {
setLocale('en');
assert.equal(model.ageReferenceMs(), at);
const card = model.buildCellCard({ cell, position: {} }, model.ageReferenceMs());
assert.equal(card.details[0], 'max 210 MW · new 3h', 'not months old');
// The cards the scene shows use the same time.
const entries = [];
layerState._viewer = { canvas: { clientWidth: 800, clientHeight: 600 } };
layerState._fireByCardId = new Map();
layerState._selectedFire = null;
layerState._labelCandidates = [{ cell, position: {} }];
layerState._labelLodDistance = 0;
const { rebuildAmbientLabels } = createCards({
layerState,
services: {},
components: {
model,
rendering: {
scenePorts: () => ({
query: { project: () => ({ x: 400, y: 300 }), isOccluded: () => false },
}),
},
},
config: { overlayHost: { setEntries: (source, shown) => entries.push(...shown) } },
});
rebuildAmbientLabels();
assert.equal(entries.length, 1);
assert.equal(entries[0].details[0], 'max 210 MW · new 3h');
// Live, they count from now.
layerState._at = null;
cell.newestAcqMs = now - 5 * 3_600_000;
assert.equal(model.ageReferenceMs(), now);
entries.length = 0;
rebuildAmbientLabels();
assert.equal(entries[0].details[0], 'max 210 MW · new 5h');
} finally {
setLocale(previousLocale);
}
});
+98
View File
@@ -0,0 +1,98 @@
import { forgetPlacedAircraft } from './placed.js';
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
export function createClockFollow({ flightState, services, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses, floors and the tracked
* trail belong to the time the clock left.
*/
function resetMotion() {
forgetPlacedAircraft(
services?.placement,
flightState._positionHistory.keys(),
);
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState._displayFloorState.clear();
flightState._drReconcileValid = false;
flightState._cachedDRFrame = -1;
flightState._cachedDRPosition = null;
parts.tracking._clearTrail();
flightState._lastCamPoseSig = '';
}
/**
* The contacts drawn now that the first live snapshot after the clock came
* back to live lacks (the tracked one too): the snapshot judges them as a
* poll judges any absence (see the snapshot renderer).
* @param {{records: Array<{id: string}>}} snapshot
* @returns {Set<string>}
*/
function absentAtHandover(snapshot) {
const present = new Set(snapshot.records.map((record) => record.id));
const drawn = [...(flightState._icons?.ids() ?? [])];
if (flightState._trackedIcao) drawn.push(flightState._trackedIcao);
return new Set(drawn.filter((id) => !present.has(id)));
}
/**
* Back at live: forget how every contact moved, as at a jump, but keep the
* tracked trail, and keep the contacts `kept` (absentAtHandover) as they
* were: their record, fixes and course. Each was last seen at its newest
* fix, not when it was loaded, so absence judges how old it really is.
* @param {Set<string>} kept
*/
function handOverMotion(kept) {
const held = [];
for (const id of kept)
held.push([
id,
flightState.records.data.get(id),
flightState._positionHistory.get(id),
flightState._displayCourse.get(id),
]);
forgetPlacedAircraft(
services?.placement,
[...flightState._positionHistory.keys()].filter((id) => !kept.has(id)),
);
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState._displayFloorState.clear();
flightState._drReconcileValid = false;
flightState._cachedDRFrame = -1;
flightState._cachedDRPosition = null;
flightState._lastCamPoseSig = '';
for (const [id, meta, history, course] of held) {
if (meta)
flightState.records.data.set(id, {
...meta,
observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs,
});
if (history) flightState._positionHistory.set(id, history);
if (course !== undefined) flightState._displayCourse.set(id, course);
}
}
/** Drop every contact: the time has none to show, or the clock went live. */
function clear() {
if (flightState._trackedIcao)
parts.tracking._clearTracking(false, { evicted: true });
resetMotion();
// Each contact's icon row and 3D model go with it.
for (const icao24 of [...(flightState._icons?.ids() ?? [])])
parts.icons._forgetContact(icao24);
flightState._detectionObjects.clear();
flightState.feed._count = 0;
flightState.feed._lastUpdate = null;
}
return { resetMotion, absentAtHandover, handOverMotion, clear };
}
+255
View File
@@ -0,0 +1,255 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FlightRecords } from './records.js';
import { createIngestion } from './ingestion.js';
import { createClockFollow } from './clockFollow.js';
import { displayDelayMs, followsClock, RENDER_DELAY_SEC } from './policy.js';
// Flights follow the world clock only while their source declares a timeline
// (src/time/snapshotTimeline.js); these cover the layer's side of it.
const T = 1_800_000_000_000;
const following = { timeline: { active: () => true } };
const live = { timeline: { active: () => false } };
function records(now = () => T) {
return new FlightRecords({
geoidHeight: () => 0,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
now,
});
}
const view = () => ({
viewerLatDeg: null,
viewerLonDeg: null,
trackedId: null,
floorWarmPoints: [],
});
const observation = (fields = {}) => ({
id: 'abc123',
reference: 'abc123',
longitude: -77,
latitude: 39,
callsign: 'TEST1',
baroAltitudeM: 1000,
onGround: false,
speedMps: 120,
courseDeg: 90,
positionTimeMs: T - 5_000,
...fields,
});
test('contacts are drawn behind the live edge, and at the time following the clock', () => {
assert.equal(displayDelayMs({ timeline: null }), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs({}), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs(live), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs(following), 0);
assert.equal(followsClock({}), false);
assert.equal(followsClock(following), true);
});
test('civil records judge absence and receipt at the layer clock', () => {
let now = T;
const store = records(() => now);
const { meta } = store.receive(observation({ positionTimeMs: null }), view());
assert.equal(meta.observedReceiptMs, T);
assert.equal(meta.newestFixMs, T, 'an undated fix is the clock time');
assert.equal(
store.absence('abc123', { complete: true, tracked: true }),
'stale',
);
assert.equal(
store.absence('abc123', {
complete: true,
tracked: true,
nowMs: T + 11 * 60_000,
}),
'remove',
'a given time judges retention',
);
store.receive(observation(), view());
now = T + 11 * 60_000;
assert.equal(
store.absence('abc123', { complete: true, tracked: true }),
'remove',
'the clock judges retention when no time is given',
);
});
test('a records reset forgets where airframes were and keeps what they are', () => {
const store = records();
const first = store.receive(observation(), view());
first.meta.typeCode = 'B738';
first.meta.registration = 'N123';
first.meta.photo = { src: 'photo.jpg' };
store.absence('abc123', { complete: true });
store.beginSnapshot(T);
store.reset();
assert.equal(store.data.size, 0);
assert.equal(store.missingPolls.size, 0);
assert.equal(store.lastSnapshotMs, null);
const again = store.receive(
observation({ positionTimeMs: T - 600_000, callsign: 'OTHER' }),
view(),
);
assert.equal(again.prevMeta, undefined, 'no motion carries across');
assert.equal(again.groundFlipped, false);
assert.equal(again.meta.typeCode, 'B738');
assert.equal(again.meta.registration, 'N123');
assert.equal(again.meta.photo.src, 'photo.jpg');
assert.equal(again.meta.newestFixMs, T - 600_000, 'an earlier fix applies');
store.forget('abc123');
assert.equal(store.airframes.size, 0);
});
function ingestion(source, { follows = false } = {}) {
const feed = {
_source: source,
_activeUpdateControllers: new Set(),
_trackingRefreshEpoch: 0,
_lastSource: 'Fixture',
_retryAt: 0,
};
const applied = [];
const state = { follows };
const { methods } = createIngestion({
feed,
getQuery: () => ({ latitude: 39 }),
applySnapshot: (snapshot, _viewer, options) => {
applied.push({ snapshot, options });
return { count: 1, ids: new Set() };
},
setSourceLabel: () => {},
applyPendingTrackingRestore: () => {},
followsClock: () => state.follows,
});
return { feed, applied, state, methods };
}
test('civil polls carry no time; a snapshot at a time carries it and replaces', async () => {
const queries = [];
const probe = ingestion({
async getSnapshot(query) {
queries.push(query);
return { records: [], observedAtMs: T - 60_000, freshness: 'current' };
},
});
await probe.methods.update(null);
assert.deepEqual(queries[0], { latitude: 39 });
assert.equal(probe.applied[0].options, undefined);
assert.equal(await probe.methods.loadAt(T - 60_000, { replace: true }), true);
assert.deepEqual(queries[1], { latitude: 39, atMs: T - 60_000 });
assert.deepEqual(probe.applied[1].options, { replace: true });
assert.equal(probe.feed._lastUpdate, T - 60_000);
});
test('following the clock, civil polls stop and a poll already out is dropped', async () => {
let release;
const probe = ingestion({
getSnapshot: () =>
new Promise((resolve) => {
release = resolve;
}),
});
const out = probe.methods.update(null);
probe.state.follows = true;
release({ records: [], observedAtMs: T, freshness: 'current' });
await out;
assert.equal(probe.applied.length, 0);
await probe.methods.update(null);
assert.equal(probe.applied.length, 0, 'no poll while following');
});
test('a failed snapshot at a time reports it without holding the live backoff', async () => {
const probe = ingestion({
async getSnapshot() {
throw Object.assign(new Error('nope'), { retryAfterMs: 60_000 });
},
});
assert.equal(await probe.methods.loadAt(T), false);
assert.equal(probe.feed._retryAt, 0);
assert.equal(probe.feed._lastError, 'Live data unavailable');
});
test('a jump forgets how contacts moved; clearing drops every contact', () => {
const calls = [];
// The contacts' icon rows.
const icons = new Set(['abc123']);
const flightState = {
records: records(),
_positionHistory: new Map([['abc123', []]]),
_displayCourse: new Map([['abc123', 90]]),
_groundSnap: { clear: () => calls.push('ground') },
_displayFloorState: new Map([['abc123', {}]]),
_drReconcileValid: true,
_cachedDRFrame: 7,
_icons: { ids: () => [...icons] },
_detectionObjects: new Map([['abc123', {}]]),
_trackedIcao: 'abc123',
feed: { _count: 1, _lastUpdate: T },
};
const parts = {
tracking: {
_clearTrail: () => calls.push('trail'),
_clearTracking: (_skip, { evicted }) => {
calls.push(`untrack:${evicted}`);
flightState._trackedIcao = null;
},
},
icons: {
// A contact's row goes, and its 3D model with it.
_forgetContact: (id) => {
icons.delete(id);
calls.push(`model:${id}`);
},
},
};
const follow = createClockFollow({ flightState, parts });
flightState.records.receive(observation(), view());
follow.resetMotion();
assert.equal(flightState.records.data.size, 0);
assert.equal(flightState._positionHistory.size, 0);
assert.equal(flightState._displayCourse.size, 0);
assert.equal(flightState._displayFloorState.size, 0);
assert.equal(flightState._drReconcileValid, false);
assert.equal(icons.size, 1, 'contacts stay until replaced');
follow.clear();
assert.equal(icons.size, 0);
assert.equal(flightState._detectionObjects.size, 0);
assert.equal(flightState.feed._count, 0);
assert.equal(flightState.feed._lastUpdate, null);
assert.ok(calls.includes('untrack:true'));
assert.ok(calls.includes('model:abc123'));
});
test('leaving the live edge forgets every contact a host placement was told of', () => {
const forgotten = [];
const flightState = {
records: records(),
_positionHistory: new Map([
['abc123', []],
['def456', []],
]),
_displayCourse: new Map(),
_groundSnap: { clear() {} },
_displayFloorState: new Map(),
};
const parts = { tracking: { _clearTrail() {} } };
const services = { placement: { forget: (id) => forgotten.push(id) } };
createClockFollow({ flightState, services, parts }).resetMotion();
assert.deepEqual(forgotten, ['abc123', 'def456']);
assert.equal(flightState._positionHistory.size, 0);
});
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
const probe = ingestion({
async getSnapshot() {
throw new DOMException('Superseded', 'AbortError');
},
});
await assert.rejects(probe.methods.loadAt(T), { name: 'AbortError' });
assert.equal(probe.feed._lastError, undefined);
assert.equal(probe.feed._backoff, undefined);
assert.equal(probe.feed._retryAt, 0);
});
+6 -7
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { findCamera } from '../../render/rendererOf.js';
export function createController({
flightState,
@@ -13,13 +13,12 @@ export function createController({
flightState.feed._activeUpdateControllers.clear();
}
/** The feed query around the camera's ground point, or {} with none. */
function _flightQuery(viewer) {
const cartographic = viewer?.camera?.positionCartographic;
return cartographic
? {
latitude: Cesium.Math.toDegrees(cartographic.latitude),
longitude: Cesium.Math.toDegrees(cartographic.longitude),
}
const pose = viewer ? findCamera(viewer)?.pose() : null;
// An eye at the earth's centre has no ground point: the pose gives NaN.
return pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon)
? { latitude: pose.lat, longitude: pose.lon }
: {};
}
return { _abortActiveUpdates, _flightQuery };
+38
View File
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindRenderer } from '../../render/rendererOf.js';
import { createController } from './controller.js';
const controller = () =>
createController({ flightState: { feed: {} }, parts: {}, layer: {} });
test('the feed is asked for the flights around the camera port’s ground point', () => {
let pose = { lon: -97.04, lat: 32.9, height: 9000 };
const viewer = {};
const unbind = bindRenderer(viewer, { camera: { pose: () => pose } });
try {
const { _flightQuery } = controller();
assert.deepEqual(_flightQuery(viewer), {
latitude: 32.9,
longitude: -97.04,
});
pose = { lon: NaN, lat: NaN, height: NaN };
assert.deepEqual(_flightQuery(viewer), {}, 'no ground point: no area');
pose = { lon: -97.04, lat: NaN, height: 9000 };
assert.deepEqual(_flightQuery(viewer), {}, 'half a ground point: none');
} finally {
unbind();
}
});
test('with no viewer or camera the query names no area', () => {
const { _flightQuery } = controller();
assert.deepEqual(_flightQuery(null), {});
assert.deepEqual(_flightQuery(undefined), {});
assert.deepEqual(_flightQuery({}), {}, 'a viewer with no camera');
assert.deepEqual(
_flightQuery({ isDestroyed: () => true, camera: {} }),
{},
'a destroyed viewer',
);
});
+32 -34
View File
@@ -1,7 +1,9 @@
import { classifyAircraft } from '../../data/aircraftClass.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { findCamera } from '../../render/rendererOf.js';
import { frustumPlanes, sphereOutside } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distanceSquared, vec } from '../../geo/vector.js';
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
import * as Cesium from 'cesium';
import {
ENRICH_MAX_INFLIGHT,
ENRICH_DISPATCH_GAP_MS,
@@ -12,6 +14,9 @@ import {
ENRICH_RETRY_COOLDOWN_MS,
} from './policy.js';
/** A contact counts as on screen while a sphere this big around it is (m). */
const AMBIENT_CULL_RADIUS_M = 1;
export function createEnrichment({
flightState,
services,
@@ -151,7 +156,11 @@ export function createEnrichment({
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return; // evicted while the lookup was in flight
meta.typeCode = data.typeCode || meta.typeCode;
// A looked-up type outranks the feed's own from now on.
if (data.typeCode) {
meta.typeCode = data.typeCode;
meta.typeLookedUp = true;
}
meta.typeName = data.typeName || meta.typeName;
meta.registration = data.registration || meta.registration;
if (meta.typeCode) {
@@ -161,13 +170,11 @@ export function createEnrichment({
});
if (klass !== meta.klass) {
meta.klass = klass;
const bb = flightState._billboards.get(icao24);
if (bb)
parts.rendering._applyFleetBillboardPresentation(icao24, bb);
// Hangar fleet: the class's GLB/scale may have changed — resync the
// live model, any in-flight load, and the tracked standalone model.
parts.rendering._syncModelToClass(icao24);
parts.icons._applyIconPresentation(icao24);
}
// The type picks the fleet model and its length — resync the live
// model, any in-flight load, and the tracked standalone model.
parts.rendering._syncModelToClass(icao24);
}
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
parts.tracking._updateTrackedLabelModel(icao24);
@@ -282,40 +289,31 @@ export function createEnrichment({
if (
flightState._enrichAmbientBudget <= 0 ||
!flightState._viewer ||
!flightState._billboardCollection ||
!flightState._billboardCollection.show
!flightState._icons?.show
)
return;
try {
const camera = flightState._viewer.camera;
const camPos = camera.positionWC;
const occluder = horizonOccluder(camera);
const cull = camera.frustum.computeCullingVolume(
camPos,
camera.directionWC,
camera.upWC,
);
// What is on screen, from the camera's pose: past the limb or outside
// the view frustum is not looked at.
const pose = findCamera(flightState._viewer)?.pose();
if (!pose) return;
const camPos = pose.position;
const occluder = horizonFrom(camPos);
const planes = frustumPlanes(pose);
const position = vec();
const cand = [];
for (const [icao24, bb] of flightState._billboards) {
const icons = flightState._icons;
const t = parts.icons._displayMs();
for (const icao24 of icons.ids()) {
// Answered, queued, negative this session, or cooling down after a
// failure: never spend a token on it.
if (_enrichHeld(`t:${icao24}`)) continue;
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
if (!bb.position || !occluder.isPointVisible(bb.position)) continue; // beyond the limb
Cesium.Cartesian3.clone(
bb.position,
flightState._scratchModelBS.center,
);
if (
cull.computeVisibility(flightState._scratchModelBS) ===
Cesium.Intersect.OUTSIDE
)
continue; // off-screen
cand.push([
icao24,
Cesium.Cartesian3.distanceSquared(camPos, bb.position),
]);
if (!icons.position(icao24, t, position)) continue;
if (!occluder.isPointVisible(position)) continue; // beyond the limb
if (sphereOutside(planes, position, AMBIENT_CULL_RADIUS_M)) continue; // off-screen
cand.push([icao24, distanceSquared(camPos, position)]);
}
cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first
const n = Math.min(
Loaded 100 of 2055 files, more files were not shown because too many files have changed in this diff. Show more