Merge main into fix/earthquake-click-details

Resolves conflicts with main: a world focus target's own range past its
framed radius replaces the kind's range (#1832), so a quake asks for its
own range only past M6 and the earthquake framing stays its floor; FIRMS
keeps main's marker stand-in under the card-on-top rule; launches keep
main's label click and also read the card on top through the pick
registry.
This commit is contained in:
Sameh Khamis committed 2026-11-18 18:58:07 -08:00
commit e87aa5190d
1337 files changed
+38638 -9950

No files matched your search

+3 -7
View File
@@ -2,13 +2,9 @@ import {
formatAwarenessLabel,
AWARENESS_RADIUS_M,
} from '../../data/militaryAwarenessEngine.js';
import {
formatNumber,
onLocaleChange,
t,
translateKnown,
} from '../../i18n/index.js';
import { formatNumber, onLocaleChange, t } from '../../i18n/index.js';
import { sourceStatusLabel } from '../../ui/layerNames.js';
import { translateStatusMessage } from '../../ui/statusText.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js';
import { distanceParts } from '../../data/distanceFormat.js';
@@ -45,7 +41,7 @@ export function presentAwarenessDistance(meters) {
function presentAwarenessReason(summary = {}) {
return summary.reasonTemplate
? t(summary.reasonTemplate, summary.reasonValues)
: translateKnown(summary.reason || '');
: translateStatusMessage(summary.reason || '');
}
/**
+1 -1
View File
@@ -96,7 +96,7 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
* (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 step after the
* Cyber sonar's 80 ms cadence, so the two never beat. Fronts and band,
* 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.
+6 -6
View File
@@ -430,7 +430,7 @@ export function createRangeRing({
* 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,
* rest start in this frame; running ones keep their sonar interval,
* however many frames a drag draws.
*/
function wakePulses() {
@@ -506,7 +506,7 @@ export function createRangeRing({
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.
// 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
@@ -681,7 +681,7 @@ export function createRangeRing({
bandShown = false;
return;
}
// The soft band is painted at most once a Cyber sonar interval;
// The soft band is painted at most once a sonar interval;
// the fronts, crisp lines, move on every step.
if (
bandShown &&
@@ -726,7 +726,7 @@ export function createRangeRing({
// 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
// nothing of them, so they step a 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
@@ -746,8 +746,8 @@ export function createRangeRing({
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
// Each drawn frame, whoever asked for it, arms one step a
// sonar interval later, as the 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.
+3 -3
View File
@@ -488,7 +488,7 @@ test('pulses ask for a frame 80 ms after each drawn frame instead of holding con
const { rendering, pulseFrames } = ring;
const loop = frameLoop(t, ring);
rendering.renderVisual(flight(3));
// A Contacts view repaints at the Cyber sonar cadence, ~12.5 fps, while
// A Contacts view repaints at the sonar cadence, ~12.5 fps, while
// the pulses run, never every display frame.
assert.equal(pulseFrames(), 0);
loop.advance(1); // the frame the new ring asked for arms the first request
@@ -972,14 +972,14 @@ test('disabling the layer tears the pulses down completely', (t) => {
);
});
test('pulse requests wait 80 ms after any frame, so they cannot beat the Cyber sonar', (t) => {
test('pulse requests wait 80 ms after any frame, so they cannot beat the sonar', (t) => {
const ring = ringRendering(t);
const { rendering, pulseFrames } = ring;
const loop = frameLoop(t, ring);
rendering.renderVisual(flight(3));
loop.advance(1);
const frames = pulseFrames();
// Another owner (the Cyber sonar, a data update) draws 67 ms after ours.
// Another owner (the sonar, a data update) draws 67 ms after ours.
loop.advance(67);
loop.draw();
loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS - 1);
+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');
});
+18 -2
View File
@@ -20,6 +20,18 @@ export function createLifecycle({
}
const methods = {
/**
* 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
@@ -81,8 +93,11 @@ export function createLifecycle({
);
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._cameraChangedOff) {
@@ -124,6 +139,7 @@ export function createLifecycle({
parts.viewport.deactivateAllCities();
layerState._cityRuntime.clear();
if (layerState._stationSet) layerState._stationSet.show = false;
parts.viewport.showCoverage(false);
layerState._count = 0;
layerState._loading = false;
layerState._loadingOps = 0;
+16
View File
@@ -15,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;
+26
View File
@@ -13,7 +13,11 @@ import {
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';
@@ -24,6 +28,9 @@ import { drawOf } from '../../render/rendererOf.js';
* 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({
@@ -51,6 +58,23 @@ export function createRendering({
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`).
@@ -62,8 +86,10 @@ export function createRendering({
function detachSets() {
layerState._stationSet?.dispose();
layerState._selectedSet?.dispose();
layerState._coverageSet?.dispose();
layerState._stationSet = null;
layerState._selectedSet = null;
layerState._coverageSet = null;
}
/**
+46
View File
@@ -5,7 +5,11 @@ 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,
@@ -140,6 +144,38 @@ export function createSelection({
* @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._clickSubscription) return;
@@ -153,6 +189,15 @@ export function createSelection({
// Clicking the selected highlight itself — ignore (don't deselect).
if (hit.set === layerState._selectedSet?.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 (
hit.set === layerState._stationSet?.id &&
@@ -187,5 +232,6 @@ export function createSelection({
_selectStation,
_installClickHandler,
_onKeyDown,
coverageCityOf,
};
}
+11
View File
@@ -27,6 +27,17 @@ export function createState({ services }) {
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;
+15
View File
@@ -115,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');
@@ -212,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;
@@ -288,6 +302,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
activateCity,
runProximityCheck,
scheduleProximityCheck,
showCoverage,
onCameraChanged,
};
}
+19
View File
@@ -335,6 +335,25 @@ export function createControls({ state: layerState, services, parts, source }) {
return nextId;
},
/**
* Selects the camera nearest a WGS84 point and optionally flies to it.
* @param {number} lat Latitude in degrees.
* @param {number} lon Longitude in degrees.
* @param {Object} [options={}]
* @param {boolean} [options.focus=true] Whether to fly after selection.
* @param {number} [options.durationSec] Fly-to duration in seconds.
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
*/
focusNearestToPoint(lat, lon, options = {}) {
const nearest = parts.navigation.nearestCameraIdToPoint(lat, lon);
if (!nearest) return null;
parts.selection.setActiveCamera(nearest);
if (options.focus !== false) {
parts.navigation.focusCamera(nearest, options.durationSec || 1.8);
}
return nearest;
},
/**
* Selects and flies to the camera nearest the current viewer position.
* @param {Object} [options={}]
+24 -7
View File
@@ -9,14 +9,20 @@ export function createNavigation({
source,
}) {
/**
* Finds the camera closest to the viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
* Nearest catalog camera to a WGS84 point.
* @param {number} lat Latitude in degrees.
* @param {number} lon Longitude in degrees.
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
*/
function nearestCameraIdToViewer() {
const pose = parts.model.eyePose();
if (!pose || !layerState._records.length) return null;
const { lat, lon } = pose;
function nearestCameraIdToPoint(lat, lon) {
if (
!Number.isFinite(lat) ||
!Number.isFinite(lon) ||
Math.abs(lat) > 90 ||
Math.abs(lon) > 180 ||
!layerState._records.length
)
return null;
let best = null;
for (const record of layerState._records) {
@@ -33,6 +39,16 @@ export function createNavigation({
return best?.id || null;
}
/**
* Finds the camera closest to the viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
*/
function nearestCameraIdToViewer() {
const pose = parts.model.eyePose();
if (!pose) return null;
return nearestCameraIdToPoint(pose.lat, pose.lon);
}
/**
* The camera the layer opens on when none is selected: the one nearest the
* viewer, or the first record when the viewer has no position yet.
@@ -175,6 +191,7 @@ export function createNavigation({
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
}
return {
nearestCameraIdToPoint,
nearestCameraIdToViewer,
openingCameraId,
reopenNearestCamera,
+53
View File
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createNavigation } from './navigation.js';
function fixture() {
const records = [
{ camera: { id: 'west', lat: 40, lon: -120 } },
{ camera: { id: 'east', lat: 40, lon: -100 } },
];
const state = { _records: records };
const parts = {
model: {
eyePose: () => ({ lat: 40, lon: -101 }),
haversineKm(lat1, lon1, lat2, lon2) {
return Math.hypot(lat1 - lat2, lon1 - lon2);
},
},
};
const navigation = createNavigation({
state,
services: {},
parts,
source: {},
});
return { navigation };
}
test('nearest camera can be resolved from an explicit WGS84 target', () => {
const { navigation } = fixture();
assert.equal(navigation.nearestCameraIdToPoint(40, -119), 'west');
assert.equal(navigation.nearestCameraIdToPoint(40, -101), 'east');
});
test('viewer-nearest delegates to the same target-point owner', () => {
const { navigation } = fixture();
assert.equal(navigation.nearestCameraIdToViewer(), 'east');
});
test('invalid target coordinates fail closed', () => {
const { navigation } = fixture();
for (const [lat, lon] of [
[NaN, 0],
[null, 0],
[0, Infinity],
[90.00001, 0],
[-90.00001, 0],
[0, 180.00001],
[0, -180.00001],
]) {
assert.equal(navigation.nearestCameraIdToPoint(lat, lon), null);
}
});
+5 -3
View File
@@ -409,11 +409,13 @@ export function createEarthquakesLayer({
id: `${PICK_PREFIX}${stableId}`,
label: earthquakeMagnitudeTitle(event.mag),
position: fromDegrees(event.lon, event.lat),
// The whole disc in view: the framing's range fits an M6 disc, so a
// larger one scales it (the framing stays the floor).
// The whole disc in view: the framing's range fits an M6 disc, so only
// a larger one asks for its own range (the framing stays the floor).
radiusM: earthquakeDiscRadiusM(event.mag),
rangeM:
earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS,
event.mag > 6
? earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS
: undefined,
});
return true;
}
+3 -2
View File
@@ -449,9 +449,10 @@ test('clicking a magnitude label selects the quake and flies to it', async () =>
assert.ok(
Math.hypot(detail.position.x, detail.position.y, detail.position.z) > 6e6,
);
// The whole disc in view: radius and range scale with the magnitude.
// The whole disc in view: the radius scales with the magnitude; up to M6
// the framing's own range fits the disc.
assert.equal(detail.radiusM, 32000);
assert.equal(detail.rangeM, 32000 * 3.5);
assert.equal(detail.rangeM, undefined);
// The keyboard path does the same.
assert.equal(
+4 -1
View File
@@ -76,7 +76,10 @@ export function createCards({
const height = canvas.clientHeight;
let ambientCount = 0;
for (const candidate of layerState._labelCandidates) {
// An application drawing the detections in place of the markers draws
// them unlabelled: only the selected fire's card shows then.
const candidates = layerState._standIn ? [] : layerState._labelCandidates;
for (const candidate of candidates) {
if (ambientCount >= MAX_AMBIENT_LABELS) break;
if (candidate.fire && candidate.fire === layerState._selectedFire)
continue;
+14
View File
@@ -0,0 +1,14 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_FIRE_FILTER, filterFires } from './index.js';
test('the fire layer exports the filter its markers use', () => {
const fires = [
{ frp: 2, confidence: 0.3 },
{ frp: 40, confidence: 0.9 },
];
assert.equal(filterFires(fires, DEFAULT_FIRE_FILTER), fires);
assert.deepEqual(filterFires(fires, { minFrp: 10, confidence: 'all' }), [
fires[1],
]);
});
+3
View File
@@ -40,3 +40,6 @@ export { createFirmsSource } from './source.js';
export { createFireAnchors, FIRE_ANCHOR_LIFT_M } from './anchors.js';
export * from '../../data/firmsAdapt.js';
export * from '../../data/firmsLabels.js';
// The layer's own FRP and Confidence filter, for an application drawing the same detections
// another way: what it draws then matches the layer's markers under the same filter.
export { DEFAULT_FIRE_FILTER, filterFires } from '../../data/firmsIntensity.js';
+31 -2
View File
@@ -52,10 +52,12 @@ export function createLifecycle({
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;
if (layerState._icons) layerState._icons.show = !layerState._standIn;
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);
layerState._heatImagery?.setShow(
layerState._fires.length > 0 && !layerState._standIn,
);
// The camera can have crossed the hand-off while the layer was off.
components.rendering.applyHandoffFade(true);
components.viewport.installLodWatcher();
@@ -68,6 +70,32 @@ export function createLifecycle({
await components.ingestion.loadHeatmap();
},
/**
* Let an application draw the detections in place of the layer's
* markers. While a stand-in is set, the glows, the heatmap and the
* ambient cards are hidden and everything else works as before: a click
* on a fire the stand-in draws (`standIn.hitTest(screenPosition)`, which
* answers a detection record from the same source, or null) selects it
* and moves the camera to it as a click on its marker does, the selected
* fire's card shows, and a click on empty space clears the selection.
* Its optional `focusRangeM(record)` gives how far, in metres, the camera
* stands from a fire it draws when moving to it, for fires drawn larger
* than a marker; without one, or for null, the usual fire framing holds.
* `null` brings the markers back. The selection is kept either way.
* @param {?{hitTest: (screenPosition: {x: number, y: number}) => ?Object, focusRangeM?: (record: Object) => ?number}} standIn
*/
setMarkerStandIn(standIn) {
layerState._standIn =
typeof standIn?.hitTest === 'function' ? standIn : null;
layerState._heatImagery?.setShow(
layerState._enabled &&
layerState._fires.length > 0 &&
!layerState._standIn,
);
components.rendering.applyHandoffFade(true);
components.cards.rebuildAmbientLabels();
},
disable() {
layerState.request?.abort();
layerState.request = null;
@@ -129,6 +157,7 @@ export function createLifecycle({
layerState._currentLodIndex = -1;
layerState._lastViewRect = null;
layerState._selectedFire = null;
layerState._standIn = null;
layerState._labelCandidates = [];
layerState._labelLodDistance = 0;
layerState._pickIndexById.clear();
+6 -3
View File
@@ -122,7 +122,7 @@ export function createRendering({
glowAlpha = alpha;
const set = layerState._icons;
if (!set) return;
set.show = layerState._enabled && heat < 1;
set.show = layerState._enabled && !layerState._standIn && heat < 1;
if (!changed || !drawnGlows.size) return;
const faded = [];
for (const drawn of drawnGlows.values()) {
@@ -273,7 +273,7 @@ export function createRendering({
// The map stack may have changed since the last render.
imagery.rehome();
ensureHeatRaster(now);
imagery.setShow(layerState._enabled);
imagery.setShow(layerState._enabled && !layerState._standIn);
}
/**
@@ -469,7 +469,10 @@ export function createRendering({
// Blended as one translucent pass, as its billboards were.
blend: 'translucent',
horizonCull: true,
show: layerState._enabled && !(layerState._handoffHeat >= 1),
show:
layerState._enabled &&
!layerState._standIn &&
!(layerState._handoffHeat >= 1),
drawOrder: spriteDrawOrder?.('firms') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
+44 -5
View File
@@ -44,15 +44,23 @@ export function createSelection({
if (carded) selectAndFocusFire(carded);
return;
}
const fire = pickedFire(event.drawHit);
const pickedId = resolvePickId(event.topHit ?? null);
// A pick that belongs to a sibling layer (an aircraft, a flight trail)
// is not "empty space": leave the selection alone.
const otherLayer = Boolean(pickedId && isOwnedByOtherLayer(id, pickedId));
// The stand-in is asked where markers are picked: the click corrected
// for the sensor style (`event.position`), and only when no sibling
// layer's item is on top, as a marker under that item would not be hit.
const fire = layerState._standIn
? otherLayer
? null
: standInFire(event.position ?? event.screenPosition)
: pickedFire(event.drawHit);
if (fire) {
selectAndFocusFire(fire);
return;
}
// A pick that belongs to a sibling layer (an aircraft, a flight trail)
// is not "empty space": leave the selection alone.
const pickedId = resolvePickId(event.topHit ?? null);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
if (otherLayer) return;
clearFireSelection();
});
}
@@ -66,11 +74,15 @@ export function createSelection({
function selectAndFocusFire(fire) {
selectFire(fire);
// A stand-in that draws the fire larger than a marker says how far the
// camera stands from it (`setMarkerStandIn`).
const rangeM = layerState._standIn?.focusRangeM?.(fire);
requestWorldFocus({
kind: 'fire',
id: fireDetectionKey(fire),
label: t('FIRE'),
position: components.model.firePosition(fire),
...(Number.isFinite(rangeM) && rangeM > 0 ? { rangeM } : {}),
});
}
@@ -88,6 +100,32 @@ export function createSelection({
return layerState._pickIndexById.get(hit.id) ?? null;
}
/** The shown detections by their key, for the shown set they were made from. */
let keyed = { fires: null, byKey: null };
/**
* Resolve a click to one of this layer's fire records through the
* application's stand-in for its markers (`setMarkerStandIn`), or null:
* the record its hit test answers, matched by its detection key to a fire
* the layer shows now (so one the filter hides is not selected).
* @param {?{x: number, y: number}} screenPosition - Where the user clicked.
* @returns {?Object} Fire record.
*/
function standInFire(screenPosition) {
if (!screenPosition) return null;
const record = layerState._standIn?.hitTest(screenPosition);
if (!record) return null;
if (keyed.fires !== layerState._fires)
keyed = {
fires: layerState._fires,
byKey: new Map(
layerState._fires.map((fire) => [fireDetectionKey(fire), fire]),
),
};
return keyed.byKey.get(fireDetectionKey(record)) ?? null;
}
/**
* Select a fire: show its detail label and mark it selected in the shared
* context store so voice "what's selected" resolves to it.
@@ -224,6 +262,7 @@ export function createSelection({
removeClickHandler,
selectAndFocusFire,
pickedFire,
standInFire,
selectFire,
clearFireSelection,
refreshContextRegistrations,
+8
View File
@@ -98,6 +98,14 @@ export function createFirmsState({ services, config }) {
layerState._selectedFire = null;
/**
* What an application draws in place of the markers (`setMarkerStandIn`):
* while set, the glows, heatmap and ambient cards are hidden and clicks
* resolve through its `hitTest`.
*/
layerState._standIn = null;
/** Priority-ordered label candidates from the last rebuild (detections or cells). */
layerState._labelCandidates = [];
+55 -1
View File
@@ -27,6 +27,60 @@ export function createClockFollow({ flightState, services, parts }) {
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)
@@ -40,5 +94,5 @@ export function createClockFollow({ flightState, services, parts }) {
flightState.feed._lastUpdate = null;
}
return { resetMotion, clear };
return { resetMotion, absentAtHandover, handOverMotion, clear };
}
+5 -1
View File
@@ -156,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) {
+14 -4
View File
@@ -12,7 +12,10 @@ import { createEvidence } from './evidence.js';
import { createTesting } from './testing.js';
import { createQueries } from './queries.js';
import { createClockFollow } from './clockFollow.js';
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
import {
createSnapshotTimeline,
snapshotAnswer,
} from '../../time/snapshotTimeline.js';
import { worldClock } from '../../time/worldClock.js';
/** Compose one civil-flight layer with application-owned scene services. */
export function createCivilFlightLayer({
@@ -53,10 +56,19 @@ export function createCivilFlightLayer({
getQuery: (viewer) =>
parts.controller._flightQuery(viewer || flightState._viewer),
applySnapshot: (snapshot, viewer, options) => {
// At another time the snapshot takes the place of every contact: how
// each moved belongs to the time the clock left. Back at live too, but
// the contacts it lacks are kept as they were for it to judge.
if (options?.replace) parts.clockFollow.resetMotion();
if (options?.handover) {
parts.clockFollow.handOverMotion(
parts.clockFollow.absentAtHandover(snapshot),
);
}
return applySnapshot(snapshot, viewer, options);
},
followsClock: () => flightState.timeline.active(),
timedAnswer: snapshotAnswer,
setSourceLabel: (source) => {
layer.source = source;
},
@@ -72,9 +84,7 @@ export function createCivilFlightLayer({
load: (atMs, { signal, replace }) =>
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
clear: () => parts.clockFollow.clear(),
resumeLive: () => {
layer.update(flightState._viewer).catch(() => {});
},
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
});
Object.assign(
+26 -5
View File
@@ -12,6 +12,7 @@ export function createIngestion({
setSourceLabel,
applyPendingTrackingRestore,
followsClock = () => false,
timedAnswer = () => true,
}) {
const methods = {
async update(viewer, { signal = null } = {}) {
@@ -21,13 +22,27 @@ export function createIngestion({
await acquire(viewer, { signal });
},
/**
* Back at live from another time: poll at once, and let this live
* snapshot stand in for every contact. Those it has keep their
* icon and model and move on from where they are drawn; those it lacks
* go. Resolves true once it is applied, else false (nothing to poll yet,
* or the poll failed); rejects with an AbortError when it was dropped.
* @param {object} [viewer]
* @returns {Promise<boolean>}
*/
async resumeLive(viewer) {
return (await acquire(viewer, { handover: true })) === true;
},
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every contact when `replace`. Resolves
* whether it was applied.
* whether it was applied: `{ reachMs }`, the newest fix its records
* carry, when they carry fixes; else true, or false when it was not.
* @param {number} atMs
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
* @returns {Promise<boolean>}
* @returns {Promise<boolean|{reachMs: number}>}
*/
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
// Whatever polls or loads for another time no longer applies.
@@ -38,7 +53,10 @@ export function createIngestion({
},
};
async function acquire(viewer, { signal = null, atMs, replace = false }) {
async function acquire(
viewer,
{ signal = null, atMs, replace = false, handover = false },
) {
const nowMs = Date.now();
const timed = atMs !== undefined;
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
@@ -85,7 +103,9 @@ export function createIngestion({
setSourceLabel(feed._lastSource);
const accepted = timed
? applySnapshot(snapshot, viewer, { replace })
: applySnapshot(snapshot, viewer);
: handover
? applySnapshot(snapshot, viewer, { handover: true })
: applySnapshot(snapshot, viewer);
feed._count = accepted.count;
// Freshness belongs to the source snapshot, not the moment this browser
// received a cached 200 response.
@@ -99,7 +119,8 @@ export function createIngestion({
};
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
return true;
// At a time, what the clock's follower is told of it.
return timed ? timedAnswer(snapshot) : true;
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Flights update aborted', 'AbortError');
+266
View File
@@ -0,0 +1,266 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createFlightSnapshotRenderer } from './snapshotRenderer.js';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createFlightFeed, createIngestion } from './ingestion.js';
import { createClockFollow } from './clockFollow.js';
// Back at live from another time, the first live snapshot stands in for
// every contact: those it has keep their icon and ease on from where they
// are drawn, and only those it lacks go (src/time/snapshotTimeline.js).
/** Any property is a no-op function unless given. */
function stub(overrides = {}) {
return new Proxy(overrides, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
}
function harness() {
const iconIds = new Set();
const calls = [];
const landed = new Set();
const groundFloor = stub({
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
GROUND_FLOOR_LIFT_M: 0.5,
});
const services = stub({
geoid: { geoidHeight: () => 0 },
camera: stub(),
focus: stub(),
groundFloor,
meshFloor: stub(),
groundSnap: stub({ createGroundSnap: () => stub() }),
placement: null,
});
const flightState = createFlightState({
services,
source: { label: 'Fixture aircraft' },
});
flightState._icons = {
has: (id) => iconIds.has(id),
ids: () => [...iconIds],
get count() {
return iconIds.size;
},
};
const parts = {
rendering: stub({ _modelOwnsVisual: () => false }),
icons: stub({
_addIcon: (id) => {
calls.push(['add', id]);
iconIds.add(id);
},
_forgetContact: (id) => {
calls.push(['forget', id]);
iconIds.delete(id);
},
_planIcon: (id, options) => calls.push(['plan', id, options]),
}),
tracking: stub({
_militaryLayerSuppresses: () => false,
_appendTrailFix: () => calls.push(['trail-append']),
_startTrail: (id) => calls.push(['trail-start', id]),
_clearTrail: () => calls.push(['trail-clear']),
}),
};
parts.motion = createMotion({ flightState, services, parts, layer: {} });
const apply = createFlightSnapshotRenderer({
flightState,
records: flightState.records,
militaryRegistry: stub({ isMilitaryIcao: () => false }),
groundFloor,
rendering: parts.rendering,
tracking: parts.tracking,
motion: parts.motion,
icons: parts.icons,
enrichment: stub(),
queries: stub({ _likelyLanded: (id) => landed.has(id) }),
});
const clockFollow = createClockFollow({ flightState, services, parts });
return {
calls,
iconIds,
flightState,
clockFollow,
landed,
// `ids`: an id, or [id, fix age ms, on the ground].
snapshot: (ids, fields = {}) => ({
observedAtMs: Date.now(),
records: ids.map((entry, k) => {
const [id, ageMs = 5_000, onGround = false] = [entry].flat();
return {
id,
reference: id,
longitude: -115 + k,
latitude: 36,
callsign: 'TEST1',
baroAltitudeM: onGround ? 0 : 9_000,
onGround,
speedMps: onGround ? 5 : 220,
courseDeg: 90,
positionTimeMs: Date.now() - ageMs,
};
}),
complete: true,
...fields,
}),
apply(ids, options, fields) {
calls.length = 0;
return apply(this.snapshot(ids, fields), null, options);
},
// Back at live, as the layer applies its first live snapshot.
handOver(ids, fields) {
calls.length = 0;
const snapshot = this.snapshot(ids, fields);
clockFollow.handOverMotion(clockFollow.absentAtHandover(snapshot));
return apply(snapshot, null, { handover: true });
},
};
}
test('the first live snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
const h = harness();
h.apply(['a00001', 'a00002']);
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
const accepted = h.handOver(['a00001', 'a00003']);
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00003']);
assert.equal(accepted.count, 2);
// The contact it has keeps its icon: no remove and add, and its motion is
// planned as a handover, easing from where it is drawn.
assert.equal(
h.calls.some(
([kind, id]) => id === 'a00001' && (kind === 'add' || kind === 'forget'),
),
false,
);
assert.deepEqual(
h.calls.find(([kind, id]) => kind === 'plan' && id === 'a00001'),
['plan', 'a00001', { handover: true }],
);
assert.ok(h.calls.some(([kind, id]) => kind === 'forget' && id === 'a00002'));
assert.ok(h.calls.some(([kind, id]) => kind === 'add' && id === 'a00003'));
});
test('a plain live poll keeps a missing contact as its absence rules say', () => {
const h = harness();
h.apply(['a00001', 'a00002']);
h.apply(['a00001']);
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
assert.deepEqual(
h.calls.find(([kind]) => kind === 'plan'),
['plan', 'a00001', undefined],
);
});
test('back at live, only the first live snapshot applied takes over; a failed poll says so', async () => {
const applied = [];
let fail = false;
const feed = createFlightFeed({
async getSnapshot() {
if (fail) throw new Error('down');
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
},
});
const { methods } = createIngestion({
feed,
getQuery: () => ({}),
applySnapshot: (_snapshot, _viewer, options) => {
applied.push(options);
return { count: 0, ids: new Set() };
},
setSourceLabel: () => {},
applyPendingTrackingRestore: () => {},
});
assert.equal(await methods.resumeLive(null), true);
await methods.update(null);
assert.deepEqual(applied, [{ handover: true }, undefined]);
fail = true;
const warn = console.warn;
console.warn = () => {};
try {
assert.equal(await methods.resumeLive(null), false);
} finally {
console.warn = warn;
}
});
test('back at live, the tracked contact and those the snapshot retains stay, stale, and a partial snapshot drops none', () => {
const h = harness();
h.apply(['a00001', 'a00002', 'a00003', 'a00004']);
h.flightState._trackedIcao = 'a00001';
const history = [{ epochMs: Date.now() - 60_000 }];
h.flightState._positionHistory.set('a00001', history);
h.handOver(['a00004'], { retainIds: new Set(['a00002']) });
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002', 'a00004']);
assert.equal(
h.flightState._positionHistory.get('a00001'),
history,
'the tracked contact keeps its fixes for the next poll to judge',
);
assert.ok(h.flightState.records.data.has('a00001'));
assert.equal(
h.calls.some(([kind]) => kind === 'trail-clear' || kind === 'trail-start'),
false,
'its trail goes on',
);
const partial = harness();
partial.apply(['a00001', 'a00002']);
partial.handOver(['a00003'], { complete: false });
assert.deepEqual([...partial.iconIds].sort(), ['a00001', 'a00002', 'a00003']);
});
test('back at live, the tracked contact the snapshot has goes on adding to its trail', () => {
const h = harness();
h.apply(['a00001']);
h.flightState._trackedIcao = 'a00001';
h.handOver(['a00001']);
assert.deepEqual(
h.calls.filter(([kind]) => kind.startsWith('trail')),
[['trail-append']],
);
});
const HOURS_3 = 3 * 3_600_000;
test('back at live, a partial snapshot keeps only contacts whose newest fix is recent, by the real absence rules', () => {
const h = harness();
// Shown from a time three hours back, and one from a minute ago.
h.apply([
['a00001', HOURS_3],
['a00002', 60_000],
]);
h.handOver(['a00003'], { complete: false });
assert.deepEqual(
[...h.iconIds].sort(),
['a00002', 'a00003'],
'the three-hour-old contact is no ghost',
);
});
test('back at live, a tracked aircraft is kept only while its newest fix is recent and it has not landed', () => {
for (const [label, setUp, kept] of [
['recent', (h) => h.apply([['a00001', 60_000]]), true],
['three hours old', (h) => h.apply([['a00001', HOURS_3]]), false],
[
'landed',
(h) => {
h.apply([['a00001', 120_000]]);
h.apply([['a00001', 60_000, true]]);
h.landed.add('a00001');
},
false,
],
]) {
const h = harness();
setUp(h);
h.flightState._trackedIcao = 'a00001';
h.handOver(['a00002']);
assert.equal(h.iconIds.has('a00001'), kept, label);
}
});
+18 -10
View File
@@ -42,7 +42,6 @@ import {
limitCourseStep,
corridorPathLatLon,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from './placed.js';
import {
modelVisualAnchor,
@@ -50,7 +49,6 @@ import {
} from '../../data/modelVisualAnchor.js';
import {
FOCUS_EVIDENCE_DEV,
MODEL_MIN_PX,
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
DR_CORRECTION_MS,
COURSE_SLEW_DT_MAX_SEC,
@@ -415,19 +413,17 @@ export function createMotion({
const spec = parts.rendering._modelSpec(
flightState.records.data.get(icao24),
);
// Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX.
// Drawn as the fleet draws it: at its true size.
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
const projectedDiameterPx =
(2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM;
return Math.max(MODEL_MIN_PX, projectedDiameterPx);
return projectedDiameterPx;
}
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
const width = sprite?.width ?? 28;
const height = sprite?.height ?? 28;
const scale =
sprite?.scale ??
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
const scale = sprite?.scale ?? 1;
const scaleByDistance =
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
@@ -456,6 +452,8 @@ export function createMotion({
const sameTrack =
flightState._drReconcileValid && flightState._drReconcileIcao === icao24;
const raw = _deadReckon(icao24, flightState._scratchDrRaw);
flightState._cachedDRPlaced =
Boolean(raw) && flightState._drSpeedPlaced === true;
flightState._cachedDRCourse = flightState._drCourseDeg;
flightState._cachedDRSpeedMps = flightState._drSpeedMps;
flightState._cachedDRHold = flightState._drCourseHold;
@@ -601,6 +599,16 @@ export function createMotion({
* against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when
* there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */
/** Whether a host-supplied placement placed the tracked aircraft where
* `_trackedDisplayCached` holds it this frame, rather than this layer's
* own motion at its display delay. */
function _trackedPlaced() {
return (
_trackedDisplayCached() !== null && flightState._cachedDRPlaced === true
);
}
function _trackedDisplayCached() {
return flightState._drReconcileValid &&
flightState._drReconcileIcao === flightState._trackedIcao
@@ -645,9 +653,8 @@ export function createMotion({
/** Trail endpoint for the rendered tracked owner. Brackets/readouts stay on
* the visual centre; only the trail moves to the model's lower-centre hardpoint. */
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
* contact is drawing. Carries the scale it is drawn at, which may be
* above `scale` to satisfy its pixel floor — the trail head has to be judged
* against the size the operator SEES, not the nominal one. */
* contact is drawing, at the scale it is drawn at — the trail head has to
* be judged against the size the operator SEES. */
/** World-space origin of the tracked model, or null when no model of this
* contact is drawing. This is the centre the rendered bounding sphere is
* measured from, so the trail clip and the envelope agree on one frame. */
@@ -1222,6 +1229,7 @@ export function createMotion({
_trackedFocusSizePx,
_trackedDisplayPosition,
_trackedDisplayCached,
_trackedPlaced,
_trackedVisualCached,
_trackedModelCenterWorld,
_trackedModelEnvelopeM,
+73 -3
View File
@@ -4,6 +4,8 @@ import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { arcOffsetEnu } from '../../data/motionModel.js';
import { createMotion as createMilitaryMotion } from '../military/motion.js';
import { createQueries } from './queries.js';
import { createQueries as createMilitaryQueries } from '../military/queries.js';
import { layerPlacement } from '../../data/placementProvider.js';
import { observeLiveAircraft } from './placed.js';
@@ -248,18 +250,77 @@ const declining = (asked) =>
);
// Each kind's record carries only its own kinematics fields.
for (const [name, create, record] of [
for (const [name, create, record, queriesOf] of [
[
'civil',
createMotion,
{ velocity: 100, true_track: 90, renderAltitudeM: 1234 },
createQueries,
],
[
'military',
createMilitaryMotion,
{ speedMps: 100, track: 90, renderAltitudeM: 1234 },
createMilitaryQueries,
],
]) {
test(`${name} aircraft waiting where a placement holds them still show their reported speed`, () => {
// Drawn standing (speed 0) while its fixes catch up: the aircraft has
// not stopped, and the panels say what it reports.
const placement = layerPlacement(
{
layer: () => ({
place: () => ({
lat: 30.5,
lon: -96.5,
altitudeM: 2000,
courseDeg: 90,
speedMps: 0,
extrapolating: false,
}),
}),
},
'aircraft',
);
const { flightState, motion, start } = placedScenario(
create,
placement,
record,
);
flightState.now = () => start + 2000;
flightState.feed = {};
flightState.records.missingPolls = new Map();
const describe = (kinematics) => {
flightState.records.data.set('abc123', { ...record, ...kinematics });
return queriesOf({
flightState,
services: {
aircraftPresentation: {
tr3bTypeLabel: (_, label) => label,
tr3bAircraftClass: () => null,
},
labels: { formatFlightLevel: String },
militaryRegistry: {},
focus: {},
recession: {},
},
parts: {
motion,
icons: { _iconPosition: () => null },
tracking: { _routeIsPlausible: () => false },
testing: {},
},
})._describeFlight('abc123');
};
const waiting = describe({});
assert.equal(flightState._drSpeedMps, 0);
assert.equal(waiting.velocityMps, 100);
// Nothing reported: the speed it is drawn at.
const unreported =
name === 'civil' ? { velocity: undefined } : { speedMps: undefined };
assert.equal(describe(unreported).velocityMps, 0);
});
test(`${name} aircraft move as before without a placement or with one that places nothing`, () => {
const own = placedScenario(create, null, record).drawn;
const asked = [];
@@ -338,14 +399,20 @@ test('an aircraft fix is told to the placement live, with its drawn height', ()
'aircraft',
);
const state = { timeline: { active: () => false } };
const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false };
const meta = {
rawLat: 1,
rawLon: 2,
renderAltitudeM: 300,
groundM: 1656,
onGround: false,
};
observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270);
observeLiveAircraft(
state,
placement,
'abc123',
6000,
{ ...meta, renderAltitudeInvented: true, onGround: true },
{ ...meta, renderAltitudeInvented: true, groundM: null, onGround: true },
null,
undefined,
);
@@ -360,12 +427,15 @@ test('an aircraft fix is told to the placement live, with its drawn height', ()
lat: 1,
lon: 2,
altitudeM: 300,
groundM: 1656,
speedMps: 80,
courseDeg: 270,
headingDeg: NaN,
onGround: false,
},
]);
// Where the layer does not know the ground, it says so.
assert.ok(Number.isNaN(told[1][1].groundM));
assert.ok(Number.isNaN(told[1][1].altitudeM));
assert.ok(Number.isNaN(told[1][1].speedMps));
assert.ok(Number.isNaN(told[1][1].courseDeg));
+72
View File
@@ -654,3 +654,75 @@ test("another layer's card over an aircraft keeps the click", (t) => {
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
test("a type lookup overrides the feed's type and fills the type name", async () => {
const queries = [];
const source = {
getEnrichment(query) {
queries.push(query);
return Promise.resolve({
found: true,
typeCode: 'B738',
typeName: 'Boeing 737-800',
registration: 'N123AB',
});
},
};
const flightState = createFlightState({ source, services: services() });
const view = {
viewerLatDeg: null,
viewerLonDeg: null,
trackedId: null,
floorWarmPoints: [],
};
const { meta } = flightState.records.receive(
{
id: 'abc123',
reference: 'abc123',
longitude: -77,
latitude: 39,
callsign: 'TEST1',
baroAltitudeM: 1000,
typeCode: 'EC45',
},
view,
);
assert.equal(meta.klass, 'helicopter', 'classed by the feed type at once');
const restyled = [];
const synced = [];
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {
icons: { _applyIconPresentation: (id) => restyled.push(id) },
rendering: { _syncModelToClass: (id) => synced.push(id) },
},
});
// A present feed type does not skip the lookup.
enrichment._requestTypeEnrichment('abc123', true);
await new Promise((done) => setImmediate(done));
assert.deepEqual(queries, [{ kind: 'type', id: 'abc123' }]);
const looked = flightState.records.data.get('abc123');
assert.equal(looked.typeCode, 'B738');
assert.equal(looked.typeName, 'Boeing 737-800');
assert.equal(looked.registration, 'N123AB');
assert.equal(looked.klass, 'airliner');
assert.deepEqual(restyled, ['abc123']);
assert.deepEqual(synced, ['abc123']);
// The next poll's feed type no longer wins.
const next = flightState.records.receive(
{
id: 'abc123',
reference: 'abc123',
longitude: -77,
latitude: 39,
callsign: 'TEST1',
baroAltitudeM: 1000,
typeCode: 'EC45',
},
view,
).meta;
assert.equal(next.typeCode, 'B738');
assert.equal(next.klass, 'airliner');
flightState.lifetime.abort();
});
+7 -2
View File
@@ -61,6 +61,7 @@ export function placeLiveAircraft(
history,
out,
) {
flightState._drSpeedPlaced = false;
if (!placement || followsClock(flightState)) return false;
const placed = placeAircraftAt(
placement,
@@ -73,6 +74,7 @@ export function placeLiveAircraft(
if (!placed) return false;
flightState._drCourseDeg = placed.courseDeg;
flightState._drSpeedMps = placed.speedMps;
flightState._drSpeedPlaced = true;
flightState._drCourseHold = placed.speedMps < COURSE_HOLD_SPEED_MPS;
flightState._drExtrapolating = placed.extrapolating;
return true;
@@ -93,13 +95,15 @@ export function forgetPlacedAircraft(placement, ids) {
* Tell the host-supplied placement an aircraft's fix as the layer took it
* (nothing while the layer follows the world clock): its own time, its
* position, the height the layer draws it at (NaN when that height is
* invented), and its reported speed, course and ground state.
* invented), the ground under it in that height's reference (NaN where the
* layer does not know it), and its reported speed, course and ground state.
* @param {object} flightState
* @param {object|null|undefined} placement
* @param {string} icao24
* @param {number} fixEpochMs
* @param {{rawLat: number, rawLon: number, renderAltitudeM: number,
* renderAltitudeInvented?: boolean, onGround?: boolean}} meta
* renderAltitudeInvented?: boolean, groundM?: number|null,
* onGround?: boolean}} meta
* @param {number|null|undefined} speedMps
* @param {number|null|undefined} courseDeg
*/
@@ -119,6 +123,7 @@ export function observeLiveAircraft(
lon: meta.rawLon,
altitudeM:
meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM,
groundM: Number.isFinite(meta.groundM) ? meta.groundM : NaN,
speedMps: Number.isFinite(speedMps) ? speedMps : NaN,
courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN,
headingDeg: NaN,
+39 -38
View File
@@ -1,5 +1,6 @@
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
import { cssColor } from '../../render/color.js';
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
const rgba = (css, alpha) =>
@@ -13,6 +14,10 @@ export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true;
export const MIL_TINT = rgba('#FFB800');
/** Amber tint for airport vehicles (type ZVEH, emitter C1/C2), apart from aircraft. */
export const VEHICLE_TINT = rgba(VEHICLE_TINT_CSS);
/** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */
export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
@@ -39,18 +44,27 @@ export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
export const GROUND_SCALE = 0.8;
// --- 3D model rendering (B3) ---------------------------------------------------------
// When enabled, aircraft render as 3D glTF models once the camera is below MODEL_ALT_CEIL_M
// (zoomed in); higher up they stay flat billboards. Eligibility is FRUSTUM-based (on-screen), and
// the slots go to either the nearest planes ('proximity') or every in-view plane ('all'), each
// backed by a hard cap so a draw-call explosion can't tank the frame (no instancing yet).
// When enabled, an aircraft draws as its 3D glTF model only within MODEL_ADD_M of the camera
// (eye to aircraft); farther away it stays its icon. Models are drawn at their true size, with no
// minimum pixel size, so a model never balloons past its real extent. Eligibility is distance-based
// with on-screen priority, and the slots go to either the nearest planes ('proximity') or every
// in-range plane ('all'): the two modes share the radius and differ by their caps, each a hard
// bound on the frame cost (every model is its own draw call).
export const MODEL_ALT_CEIL_M = 800000;
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
export const MODEL_ADD_M = 3000;
// model NEW planes within 3 km of the camera
export const MODEL_MIN_PX = 24;
// floor so distant models stay visible WITHOUT ballooning into a giant
// min-pixel blob (was 54 — far planes at the All radius became white
// star-bursts); ~matches the 2D icon size so the model↔billboard read is consistent
export const MODEL_KEEP_M = 3600;
// KEEP modeled planes out to 3.6 km: the hysteresis band (KEEP > ADD) stops a plane on the edge
// from releasing and reloading its model as the camera moves (the zoom/pan flicker)
export const MODEL_HIGHEST_CONTACT_M = 30000;
// m above the ellipsoid: no aircraft the layers draw flies higher (airliners cruise near 12 km,
// the highest-flying aircraft near 21 km)
export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M;
// m: above this camera altitude no contact can be within MODEL_KEEP_M, so no model is
// considered at all (the eligibility pass is skipped)
// Per-mode caps. Each model is its own draw call (no instancing yet), so these bound the frame cost.
@@ -58,29 +72,22 @@ export const MODEL_MAX = 150;
// 'proximity' cap (the planes immediately around you)
export const MODEL_MAX_ALL = 350;
// 'all' cap (everything out to ~the horizon)
// Per-mode ADD / KEEP radii. The two modes differ by RADIUS, not just cap — otherwise they look
// IDENTICAL whenever fewer than a cap's worth of planes are in range (field bug: Proximity and All
// rendered the same). 'proximity' = a tight ring; 'all' = roughly to the horizon (state-scale). Each
// band has hysteresis (KEEP > ADD) so a plane doesn't release+reload its model when it straddles the
// add edge (the zoom/pan flicker). Beyond ADD a model would force-clamp to minimumPixelSize into a
// giant floating blob (the old 422 km airport-cluster bug), so far planes stay 2D dots; the cap +
// on-screen priority then spend the model slots on planes you can actually see.
export const MODEL_PROX_ADD_M = 150000;
// proximity: model NEW planes within 150 km
export const MODEL_PROX_KEEP_M = 185000;
// proximity: KEEP modeled planes out to 185 km
// 'all' cap (every plane in range)
export const COCKPIT_MODEL_MAX = 60;
// max concurrent GLBs in cockpit (never raises the map cap)
export const MODEL_ALL_ADD_M = 400000;
// all: model NEW planes within 400 km (~to the horizon)
// Cockpit's AIR band: contacts within it draw as aircraft silhouettes, beyond
// it as compact dots. Independent of the 3D model radius; per 3D mode, each
// with its keep hysteresis.
export const MODEL_ALL_KEEP_M = 450000;
// all: KEEP modeled planes out to 450 km
export const COCKPIT_AIR_PROX_ADD_M = 150000;
export const COCKPIT_AIR_PROX_KEEP_M = 185000;
export const COCKPIT_AIR_ALL_ADD_M = 400000;
export const COCKPIT_AIR_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite the renderer's heading 0
@@ -88,9 +95,6 @@ export const MODEL_HEADING_OFFSET_DEG = 180;
/** A model's colour where it draws its mesh's own (`aircraftModelBlend`). */
export const MODEL_WHITE = rgba('#FFFFFF');
/** The tracked contact's tint, and its billboard once a model takes over. */
export const TRACKED_CYAN = rgba('#00FFFF');
export const CYAN_TRANSPARENT = rgba('#00FFFF', 0);
/** An ordinary fleet contact's tint. */
export const FLEET_TINT = rgba('#FFFFFF');
@@ -201,18 +205,15 @@ export const FLEET_DR_INTERVAL_MS = 80;
/**
* The icon-to-model rules the aircraft layers follow, as the Vessels, Transit
* and Rail layers take them (`createFleetModelLayer`): the same altitude
* ceiling, minimum pixel size, proximity/all caps, add/keep radii and
* eligibility cadence, so every layer turns icons into models at one distance.
* ceiling, proximity/all caps, add/keep radii and eligibility cadence, so
* every layer turns icons into models at one distance, drawn at true size.
*/
export const FLEET_MODEL_POLICY = Object.freeze({
altitudeCeilingM: MODEL_ALT_CEIL_M,
minimumPixelSize: MODEL_MIN_PX,
cap: MODEL_MAX,
capAll: MODEL_MAX_ALL,
addM: MODEL_PROX_ADD_M,
addAllM: MODEL_ALL_ADD_M,
keepM: MODEL_PROX_KEEP_M,
keepAllM: MODEL_ALL_KEEP_M,
addM: MODEL_ADD_M,
keepM: MODEL_KEEP_M,
intervalMs: FLEET_DR_INTERVAL_MS,
});
+4 -3
View File
@@ -145,6 +145,7 @@ export function createQueries({
derivedSpeedMps: flightState._drSpeedMps,
derivedTrackDeg: flightState._drCourseDeg,
reportedSpeedMps: info?.velocity,
derivedFromPlacement: flightState._drSpeedPlaced === true,
reportedTrackDeg: info?.true_track,
});
const carto = toLonLatH(basePos);
@@ -345,11 +346,11 @@ export function createQueries({
/**
* Live layer params.
* `models3d` toggles 3D glTF model rendering for the FLEET (altitude-gated): when on,
* surrounding aircraft become 3D models once the camera is zoomed in past MODEL_ALT_CEIL_M.
* `models3d` toggles 3D glTF model rendering for the FLEET: when on, aircraft within
* MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true size.
* The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), so selecting
* a contact never turns its icon into a model or its model into an icon.
* `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane).
* `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius.
* @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedFlightsTrackingId?: string|null}} params
*/
setParams(params = {}, { origin = 'programmatic' } = {}) {
+98 -24
View File
@@ -92,11 +92,11 @@ export class FlightRecords {
originCountry: origin_country,
longitude: lon,
latitude: lat,
baroAltitudeM: baro_alt,
baroAltitudeM: reportedBaroAlt,
onGround: on_ground,
speedMps: velocity,
courseDeg: true_track,
ellipsoidAltitudeM: geo_alt,
ellipsoidAltitudeM: reportedGeoAlt,
category,
verticalRateMps: vertical_rate,
} = observation;
@@ -110,11 +110,12 @@ export class FlightRecords {
// The airframe's facts: this record's, or those kept across a reset.
const airframe = prevMeta ?? this.airframes.get(icao24);
this.airframes.delete(icao24);
// A ground vehicle or ground station (a feed's ZVEH or GRND: a model
// built standing, catalog category `other`) takes the feed's own type,
// which no airframe lookup knows; every other aircraft keeps waiting for
// its looked-up type. With no altitude at all it stands on the ground,
// where it is, instead of at the airborne default.
// The feed's own ICAO type classes the contact and picks its model from
// the first fix; a looked-up type outranks it once one has answered.
// A ground vehicle or ground station (a feed's ZVEH or GRND) is known
// from its feed type alone, which no airframe lookup knows. With no
// altitude at all, a contact drawn with a model built standing is on the
// ground, where it is, instead of at the airborne default.
const groundModel = (typeCode) =>
drawnAsGroundModel(
this.fleetModels(),
@@ -122,12 +123,33 @@ export class FlightRecords {
category,
stickyText(callsign, prevMeta?.callsign),
);
const feedType = observation.typeCode || null;
const typeCode =
airframe?.typeCode ??
(feedType && groundModel(feedType) ? feedType : null);
const feedType = cleanType(observation.typeCode);
// A surface category keeps only a feed's ground type: a C1 contact whose
// feed names an airliner type stays a vehicle.
// A feed's ground type holds only for a contact that behaves as one: an
// airport vehicle reported airborne, or faster than a vehicle drives (a
// test transponder, a drone), is classed as any other aircraft.
const driving =
!(Number.isFinite(velocity) && velocity > VEHICLE_MAX_SPEED_MPS) &&
(on_ground === true ||
(!Number.isFinite(reportedBaroAlt) &&
!Number.isFinite(reportedGeoAlt)));
const keepFeedType =
Boolean(feedType) &&
(feedType !== 'ZVEH' || driving) &&
(!groundCategory(category) || GROUND_FEED_TYPES.has(feedType));
// A ground station is fixed: it stands on the ground whatever height its
// reports carry, as if they carried none.
const station = keepFeedType && feedType === 'GRND';
const baro_alt = station ? null : reportedBaroAlt;
const geo_alt = station ? null : reportedGeoAlt;
const typeLookedUp = airframe?.typeLookedUp === true;
const typeCode = typeLookedUp
? airframe.typeCode
: ((keepFeedType ? feedType : null) ?? airframe?.typeCode ?? null);
const onGround =
on_ground === true ||
station ||
(!Number.isFinite(baro_alt) &&
!Number.isFinite(geo_alt) &&
groundModel(typeCode));
@@ -261,6 +283,10 @@ export class FlightRecords {
// within GROUND_FLOOR_CLAMP_RADIUS_KM of the viewer — the only ones
// whose burial is visible. Cells warm in one batch after the loop.
// Airborne only (grounded planes keep the surface-cache path above).
// The ground under the contact in its render height's reference, where
// the warm cache knows it: the surface it stands on, or the floor under a
// low contact near the view. A landing is judged above it.
let groundM = onGround ? surfaceM : null;
if (
!onGround &&
renderAltitudeM < GROUND_FLOOR_WARM_MAX_ALT_M &&
@@ -269,10 +295,8 @@ export class FlightRecords {
approxDistanceKm(viewerLatDeg, viewerLonDeg, lat, lon) <=
GROUND_FLOOR_CLAMP_RADIUS_KM))
) {
renderAltitudeM = floorAltitudeM(
renderAltitudeM,
cachedGroundFloor(lat, lon),
);
groundM = cachedGroundFloor(lat, lon);
renderAltitudeM = floorAltitudeM(renderAltitudeM, groundM);
floorWarmPoints.push({ lat, lon });
}
@@ -280,7 +304,8 @@ export class FlightRecords {
const groundFlipped =
!!prevMeta && (prevMeta.onGround === true) !== onGround;
// Store flight metadata for click-to-track labels
const cat = stickyNumber(category, prevMeta?.category, null);
// OpenSky's integer category, or a feed's ADS-B emitter category ("C1").
const cat = stickyCategory(category, prevMeta?.category);
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
// A route (and its airline) belongs to the callsign it was looked up for;
// a new callsign drops it, so an old flight's route never shows under it.
@@ -311,6 +336,10 @@ export class FlightRecords {
geoAltitudeM,
renderAltitudeM,
renderAltitudeInvented,
// The feed estimated this position: it places the aircraft, and stands
// in on the tracked trail only until the next received report.
estimated: observation.estimated === true,
groundM: Number.isFinite(groundM) ? groundM : null,
onGround,
// Round 7: sticky airborne history — the landed fast-cull only
// applies to contacts that actually flew this session.
@@ -325,11 +354,9 @@ export class FlightRecords {
),
courseAnchor: course.anchor,
category: cat,
// An adsbdb-enriched type code outranks the coarse OpenSky category.
klass: classifyAircraft({
typeCode: airframe?.typeCode ?? null,
category: cat,
}),
// A type code (the feed's, or a looked-up one) outranks the coarse
// emitter category, from the first fix.
klass: classifyAircraft({ typeCode, category: cat }),
turnRateDps: prevMeta?.turnRateDps || 0,
verticalRate: stickyNumber(vertical_rate, prevMeta?.verticalRate, null),
// Analyst seam: OpenSky origin_country (state[2]) — additive, sticky
@@ -362,8 +389,9 @@ export class FlightRecords {
null,
),
// adsbdb enrichment — written by the enrichment callbacks, carried
// across polls; a ground vehicle's or station's from the feed:
// across polls; the type is the feed's own until a lookup answers:
typeCode,
typeLookedUp,
typeName: airframe?.typeName ?? null,
registration: airframe?.registration ?? null,
airline: routeHeld ? (airframe.airline ?? null) : null,
@@ -428,6 +456,7 @@ export class FlightRecords {
for (const [id, meta] of this.data) {
this.airframes.set(id, {
typeCode: meta.typeCode,
typeLookedUp: meta.typeLookedUp,
typeName: meta.typeName,
registration: meta.registration,
airline: meta.airline,
@@ -452,13 +481,54 @@ export class FlightRecords {
}
}
/** An ADS-B emitter category as a feed gives it ("A3", "C1"). */
const EMITTER_CATEGORY = /^[A-D][0-7]$/;
/**
* A contact's category, kept across polls that omit it: OpenSky's integer
* category or an ADS-B emitter category string, else the last one, else null.
* @param {*} next
* @param {*} prev
* @returns {number|string|null}
*/
function stickyCategory(next, prev) {
if (Number.isFinite(next)) return next;
const text = typeof next === 'string' ? next.trim().toUpperCase() : '';
if (EMITTER_CATEGORY.test(text)) return text;
return prev ?? null;
}
/** A feed's ICAO type designator, upper case, or null. */
function cleanType(value) {
const text = typeof value === 'string' ? value.trim().toUpperCase() : '';
return text || null;
}
/** The types a feed gives airport vehicles (ZVEH) and ground stations (GRND). */
const GROUND_FEED_TYPES = new Set(['ZVEH', 'GRND']);
/** The fastest an airport vehicle drives, m/s (144 km/h); faster, it is no vehicle. */
const VEHICLE_MAX_SPEED_MPS = 40;
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
const groundModelCaches = new WeakMap();
/**
* Whether an emitter category is a surface one: a vehicle or an obstacle
* (ADS-B C1 to C5, OpenSky 16 to 20).
* @param {string|number|null} category
* @returns {boolean}
*/
function groundCategory(category) {
if (Number.isInteger(category)) return category >= 16 && category <= 20;
return typeof category === 'string' && /^C[1-5]$/i.test(category.trim());
}
/**
* Whether an aircraft of this type, emitter category and callsign is drawn
* with a model built standing on the ground (catalog category `other`: an
* airport vehicle, a ground station's mast). False before the set loads.
* airport vehicle, a ground station's mast). A surface emitter category
* (C1 to C5, OpenSky 16 to 20) always is. Otherwise, before the set loads,
* whether the type is one a feed gives ground vehicles and stations.
* Answered once per type, category and callsign rule matched.
* @param {object|null} set The loaded fleet model set.
* @param {string|null} typeCode
@@ -467,7 +537,11 @@ const groundModelCaches = new WeakMap();
* @returns {boolean}
*/
function drawnAsGroundModel(set, typeCode, category, callsign) {
if (!set || !typeCode) return false;
if (groundCategory(category)) return true;
if (!typeCode) return false;
// Before the set loads, the feed's own ground types: an airport vehicle
// must not be drawn as an aircraft until the set says what it is.
if (!set) return GROUND_FEED_TYPES.has(typeCode.trim().toUpperCase());
let cache = groundModelCaches.get(set);
if (!cache) groundModelCaches.set(set, (cache = new Map()));
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
+193 -8
View File
@@ -283,6 +283,7 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
observation({
id: 'v1',
typeCode: 'ZVEH',
speedMps: 8,
callsign: 'FIRE 2',
...noAltitude,
}),
@@ -298,26 +299,175 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
assert.equal(mast.onGround, true);
assert.equal(mast.typeCode, 'GRND');
// An airliner with no altitude keeps the airborne default, and its feed
// type still waits for the airframe lookup.
// type from the first fix.
const plane = store.receive(
observation({ id: 'p1', typeCode: 'A320', ...noAltitude }),
view(),
).meta;
assert.equal(plane.onGround, false);
assert.equal(plane.altitude, 10000);
assert.equal(plane.typeCode, null);
// A vehicle reporting an altitude is placed by it.
assert.equal(plane.typeCode, 'A320');
// An "airport vehicle" reported airborne is no vehicle (a drone, a test
// transponder): it is placed by its altitude and classed as an aircraft.
const reported = store.receive(
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }),
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 762 }),
view(),
).meta;
assert.equal(reported.onGround, false);
// Before the model set loads nothing is grounded by its model.
const unloaded = records().receive(
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
assert.equal(reported.typeCode, null);
assert.notEqual(reported.klass, 'vehicle');
// Nor is one on the ground faster than a vehicle drives.
const fast = store.receive(
observation({
id: 'v4',
typeCode: 'ZVEH',
onGround: true,
speedMps: 77,
...noAltitude,
}),
view(),
).meta;
assert.equal(unloaded.onGround, false);
assert.notEqual(fast.klass, 'vehicle');
// A ground station stands on the ground whatever height it reports.
const high = store.receive(
observation({ id: 'm2', typeCode: 'GRND', baroAltitudeM: 11880 }),
view(),
).meta;
assert.equal(high.onGround, true);
assert.equal(high.klass, 'station');
assert.equal(high.altitude, 0);
assert.ok(
!(high.renderAltitudeM > 1000),
`drawn at ${high.renderAltitudeM} m`,
);
// Before the model set loads, the feed's ground types already count: an
// airport vehicle is never drawn as an aircraft first.
const early = records();
const unloaded = early.receive(
observation({ id: 'v3', typeCode: 'ZVEH', speedMps: 8, ...noAltitude }),
view(),
).meta;
assert.equal(unloaded.onGround, true);
assert.equal(unloaded.typeCode, 'ZVEH');
const earlyPlane = early.receive(
observation({ id: 'p2', typeCode: 'A320', ...noAltitude }),
view(),
).meta;
assert.equal(earlyPlane.onGround, false);
assert.equal(earlyPlane.typeCode, 'A320');
});
test('airport vehicles and ground stations take their class from the first fix', () => {
// Before the model set loads, and after.
for (const store of [records(), records(() => fleetSet)]) {
const klass = (fields) =>
store.receive(observation({ callsign: '', ...fields }), view()).meta
.klass;
// An airport vehicle reports itself on the ground, at a vehicle's speed.
const driving = { onGround: true, speedMps: 8 };
assert.equal(klass({ id: 'v1', typeCode: 'ZVEH', ...driving }), 'vehicle');
assert.equal(
klass({ id: 'v2', typeCode: 'ZVEH', callsign: 'FIRE 2', ...driving }),
'vehicle',
);
assert.equal(klass({ id: 'v3', category: 'C1' }), 'vehicle');
assert.equal(klass({ id: 'v4', category: 'C2' }), 'vehicle');
assert.equal(klass({ id: 'm1', typeCode: 'GRND' }), 'station');
assert.equal(klass({ id: 'm2', category: 'C4' }), 'station');
// An aircraft's feed type outranks its emitter category.
assert.equal(
klass({ id: 'p1', typeCode: 'A320', category: 'A7' }),
'airliner',
);
}
});
test("an aircraft's feed type classes it from the first fix, until a lookup answers", () => {
for (const store of [records(), records(() => fleetSet)]) {
// A helicopter whose feed names its type, with an airliner-like category.
const first = store.receive(
observation({
id: 'h1',
callsign: 'NHC47',
typeCode: 'ec45',
category: 'A3',
}),
view(),
).meta;
assert.equal(first.typeCode, 'EC45');
assert.equal(first.klass, 'helicopter');
assert.equal(first.typeLookedUp, false);
// A later row without the type keeps it.
const quiet = store.receive(
observation({ id: 'h1', callsign: 'NHC47', category: 'A3' }),
view(),
).meta;
assert.equal(quiet.klass, 'helicopter');
assert.equal(quiet.typeCode, 'EC45');
// A looked-up type outranks the feed's on every later poll and reset.
quiet.typeCode = 'EC35';
quiet.typeLookedUp = true;
quiet.typeName = 'Airbus Helicopters H135';
const after = store.receive(
observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }),
view(),
).meta;
assert.equal(after.typeCode, 'EC35');
assert.equal(after.typeName, 'Airbus Helicopters H135');
assert.equal(after.klass, 'helicopter');
store.reset();
const again = store.receive(
observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }),
view(),
).meta;
assert.equal(again.typeCode, 'EC35');
// No type anywhere: the emitter category classes it.
const bare = store.receive(
observation({ id: 'h2', category: 'A7' }),
view(),
).meta;
assert.equal(bare.typeCode, null);
assert.equal(bare.klass, 'helicopter');
}
});
test('a surface emitter category stands on the ground, before and after the model set loads', () => {
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
for (const store of [records(), records(() => fleetSet)]) {
for (const [id, category] of [
['c1', 'C1'],
['c2', 'C2'],
['c3', 'C3'],
['c5', 'C5'],
['o16', 16],
['o20', 20],
]) {
const meta = store.receive(
observation({ id, category, callsign: '', ...noAltitude }),
view(),
).meta;
assert.equal(meta.onGround, true, `${id} stands on the ground`);
assert.equal(meta.altitude, 0, id);
}
// An aircraft category with no altitude keeps the airborne default.
const plane = store.receive(
observation({ id: 'a3', category: 'A3', ...noAltitude }),
view(),
).meta;
assert.equal(plane.onGround, false);
// A feed's aircraft type on a surface category does not make it an aircraft.
const odd = store.receive(
observation({
id: 'c9',
category: 'C1',
typeCode: 'A320',
...noAltitude,
}),
view(),
).meta;
assert.equal(odd.klass, 'vehicle');
assert.equal(odd.onGround, true);
}
});
test('a contact reported with no course faces the way its newer fixes went', () => {
@@ -365,3 +515,38 @@ test('a contact reported with no course faces the way its newer fixes went', ()
taxi(30.188, 20);
assert.equal(course(), 0);
});
test('a low contact near the view carries the ground under it; others carry none', () => {
const store = new FlightRecords({
geoidHeight: () => 40,
cachedGroundFloor: () => 1656,
floorAltitudeM: (altitude, ground) =>
Math.max(altitude, ground ?? -Infinity),
fleetModels: () => null,
});
const denver = { latitude: 39.85, longitude: -104.67 };
const near = { ...view(), viewerLatDeg: 39.8, viewerLonDeg: -104.7 };
// Landing at Denver: 1,900 m above the ellipsoid over 1,656 m ground.
const landing = store.receive(
observation({ id: 'l1', ...denver, ellipsoidAltitudeM: 1900 }),
near,
).meta;
assert.equal(landing.groundM, 1656);
// At cruise the ground is not read.
const cruise = store.receive(
observation({
id: 'c1',
...denver,
ellipsoidAltitudeM: 11000,
baroAltitudeM: 11000,
}),
near,
).meta;
assert.equal(cruise.groundM, null);
// Nor without a view to be near.
const away = store.receive(
observation({ id: 'a1', ...denver, ellipsoidAltitudeM: 1900 }),
view(),
).meta;
assert.equal(away.groundM, null);
});
+10 -13
View File
@@ -2,13 +2,12 @@ import {
aircraftLayerModelSpec,
aircraftModelSpecCacheKey,
} from './modelSpec.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { isEmergency } from '../../data/aircraftEmergency.js';
import {
MIL_TINT,
EMERGENCY_TINT,
VEHICLE_TINT,
FLEET_TINT,
TRACKED_CYAN,
GROUND_SCALE,
COCKPIT_CIVILIAN_COLOR,
} from './policy.js';
@@ -32,14 +31,16 @@ export function createRendering({
}
/** Fleet (untracked) billboard tint: red while broadcasting an emergency,
* amber for known-military, white otherwise.
* Ground traffic gets NO special tint (owner verdict 2026-07-03 field test). */
* orange amber for an airport vehicle, amber for known-military, white
* otherwise. Grounded aircraft get NO special tint (owner verdict
* 2026-07-03 field test). */
function _fleetBillboardColor(
icao24,
info = flightState.records.data.get(icao24),
) {
if (_isEmergency(icao24, info)) return EMERGENCY_TINT;
if (info?.klass === 'vehicle') return VEHICLE_TINT;
return isMilitaryIcao(icao24) ? MIL_TINT : FLEET_TINT;
}
@@ -53,13 +54,10 @@ export function createRendering({
return isMilitaryIcao(icao24) ? MIL_TINT : COCKPIT_CIVILIAN_COLOR;
}
/** Fleet billboard scale: per-class scale, ×GROUND_SCALE while grounded. */
/** Fleet billboard scale: one size for every class, ×GROUND_SCALE while grounded. */
function _fleetBillboardScale(icao24, klass) {
return (
(CLASS_SCALE_2D[klass] || 1) *
(flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1)
);
function _fleetBillboardScale(icao24) {
return flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1;
}
/** The fleet model an aircraft draws with, by its type and emitter category. */
@@ -82,11 +80,10 @@ export function createRendering({
const _iconKind = (icao24, klass) =>
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
/** Model colour: the mesh's own (white), tinted cyan while tracked and red
* while broadcasting an emergency. */
/** Model colour: the mesh's own (white), tinted red while broadcasting an
* emergency. Tracking never recolours it. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return TRACKED_CYAN;
return _isEmergency(icao24) ? EMERGENCY_TINT : policy.MODEL_WHITE;
}
+43
View File
@@ -0,0 +1,43 @@
// src/layers/flights/rendering.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRendering as createFlightsRendering } from './rendering.js';
import { createRendering as createMilitaryRendering } from '../military/rendering.js';
function rendering(create) {
const data = new Map([
['light', { klass: 'light' }],
['quadjet', { klass: 'quadjet' }],
['vehicle', { klass: 'vehicle' }],
['parked', { klass: 'quadjet', onGround: true }],
]);
return create({
flightState: { records: { data } },
services: {
militaryRegistry: { isMilitaryIcao: () => false },
aircraftPresentation: { tr3bIconKind: () => null },
focus: { focusNowMs: () => 0, getFocusTarget: () => null },
},
parts: {},
layer: {},
resolveAsset: (url) => url,
});
}
test('Flights draws every class at one size, smaller on the ground', () => {
const r = rendering(createFlightsRendering);
for (const id of ['light', 'quadjet', 'vehicle']) {
assert.equal(r._fleetBillboardScale(id), 1, id);
}
assert.equal(r._fleetBillboardScale('parked'), 0.8);
});
test('Military draws every class at its one size, smaller on the ground', () => {
const r = rendering(createMilitaryRendering);
const size = r._fleetBillboardScale('light');
for (const id of ['quadjet', 'vehicle']) {
assert.equal(r._fleetBillboardScale(id), size, id);
}
assert.ok(Math.abs(r._fleetBillboardScale('parked') - size * 0.8) < 1e-12);
});
+39 -10
View File
@@ -56,8 +56,16 @@ export function createFlightSnapshotRenderer({
/**
* `replace`: the snapshot is the world at another time (the world clock
* jumped), so it stands in for every contact: one it lacks is gone at once.
* `handover`: the first live snapshot after the clock came back to live: it
* stands in for every contact too, and those it has keep their icon and
* model and ease on from where they are drawn; of those it lacks, only
* those absence keeps (judged by their newest fix) stay.
*/
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
return function applySnapshot(
snapshot,
viewer,
{ replace = false, handover = false } = {},
) {
// Before init (or after destroy) there is no icon set to draw into.
if (!flightState._icons) return { count: 0, ids: new Set() };
const currentIcaos = new Set();
@@ -209,6 +217,7 @@ export function createFlightSnapshotRenderer({
{
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.true_track,
estimated: meta.estimated === true,
},
);
} else {
@@ -254,7 +263,7 @@ export function createFlightSnapshotRenderer({
// freshness change and the cockpit contract all land on the row's
// style; motion re-plans from the updated history.
icons._applyIconPresentation(icao24);
icons._planIcon(icao24);
icons._planIcon(icao24, handover ? { handover } : undefined);
// Poll-path type or category change: same model resync rule as the
// enrichment path — the fleet model or its scale may have changed.
if (
@@ -294,6 +303,23 @@ export function createFlightSnapshotRenderer({
// EXCEPTION: likely-landed planes (last fix low + slow) get only
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
// feed gap, and the full grace left phantom planes parked at airports.
// Back at live, a contact it lacks is from the time the clock left: it
// goes at once, unless absence keeps it as any poll would (a partial or
// retaining snapshot, the tracked aircraft), judged by its newest fix.
// No missed-poll grace, and a landed tracked aircraft is not kept.
const absenceAtHandover = (icao24) => {
const likelyLanded = queries._likelyLanded(icao24);
const judged = records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded,
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
nowMs: flightState.now?.(),
});
return judged === 'stale' && icao24 !== flightState._trackedIcao
? 'remove'
: judged;
};
const absentIds = [];
for (const icao24 of flightState._icons.ids()) {
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
@@ -301,13 +327,15 @@ export function createFlightSnapshotRenderer({
for (const icao24 of absentIds) {
const absence = replace
? 'remove'
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
: handover
? absenceAtHandover(icao24)
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
if (absence === 'retain') continue;
if (absence === 'stale') {
icons._applyIconPresentation(icao24); // the faded freshness alpha
@@ -334,7 +362,8 @@ export function createFlightSnapshotRenderer({
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
}
// The tracked contact at the new time: its trail starts there.
// The tracked contact at the new time: its trail starts there. Back at
// live its trail goes on.
if (
replace &&
flightState._trackedIcao &&
+12
View File
@@ -266,6 +266,18 @@ export function createFlightState({ source, services }) {
flightState._drSpeedMps = null;
/** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's,
* the speed it is drawn at (0 while it waits for its fixes), for motion
* only; panels show the reported ground speed (`displayedKinematics`). */
flightState._drSpeedPlaced = false;
/** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed
* it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail
* ends where it is drawn rather than at the layer's display delay. */
flightState._cachedDRPlaced = false;
flightState._drCourseHold = false;
/** Sibling scratch: whether the position `_deadReckon` just returned came from
+13 -6
View File
@@ -1,4 +1,4 @@
import { CYAN_TRANSPARENT, TRACKED_CYAN } from './policy.js';
import { trackedIconColor } from '../../data/trackedAircraftIcon.js';
import { createModelRecord } from '../../data/modelRecord.js';
import {
aircraftIconTestSeams,
@@ -217,9 +217,11 @@ export function createTesting({
/** Evaluate the production tracked-billboard handoff colour for focused tests. */
function _trackedBillboardColorForTest() {
return parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? CYAN_TRANSPARENT
: TRACKED_CYAN;
const icao24 = flightState._trackedIcao;
const color = parts.rendering._fleetBillboardColor(icao24);
return parts.rendering._modelOwnsVisual(icao24)
? trackedIconColor(color, 0)
: color;
}
/** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */
@@ -254,15 +256,20 @@ export function createTesting({
}
/** How the tracked billboard is drawn (`_trackedBillboardLook`,
* `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */
* `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet
* icon is (`_fleetLook`, `_fleetBillboardColor`). */
function _trackedIconLookForTest(icao24) {
return {
tracked: {
...parts.tracking._trackedBillboardLook(),
sprite: parts.tracking._trackedSprite(icao24),
color: parts.tracking._trackedIconColor(),
},
fleet: {
...parts.icons._fleetLook(icao24),
color: parts.rendering._fleetBillboardColor(icao24),
},
fleet: parts.icons._fleetLook(icao24),
};
}
+74 -30
View File
@@ -15,6 +15,7 @@ import {
createTrackedAircraftIcon,
isOtherTrackedIconSet,
trackedContactHolder,
trackedIconColor,
} from '../../data/trackedAircraftIcon.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { julianToEpochMs } from '../../geo/julian.js';
@@ -28,10 +29,12 @@ import {
} from '../../data/trackingClickGesture.js';
import { inputFor } from '../../input/dispatcher.js';
import {
COCKPIT_AIR_ALL_ADD_M,
COCKPIT_AIR_ALL_KEEP_M,
COCKPIT_AIR_PROX_ADD_M,
COCKPIT_AIR_PROX_KEEP_M,
TRAIL_MAX_POINTS,
TRAIL_COLOR,
CYAN_TRANSPARENT,
TRACKED_CYAN,
STALE_ALPHA,
displayDelayMs,
followsClock,
@@ -46,6 +49,7 @@ import {
trailBodySegments,
trailHeadCurvePoints,
trailHeadStartFix,
trailTimeAt,
} from '../../data/trailContinuity.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import { entityRecord } from '../../data/entityRecords.js';
@@ -61,8 +65,6 @@ function aircraftPickId(hit) {
return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id;
}
const STALE_CYAN = Object.freeze([...TRACKED_CYAN.slice(0, 3), STALE_ALPHA]);
export function createTracking({
flightState,
services,
@@ -223,11 +225,13 @@ export function createTracking({
);
distancesSquared.push([icao24, distanceSquared(eye, position)]);
}
// The AIR band follows the 3D mode, not the 3D model radius.
const all = flightState._models3dMode === 'all';
const next = nextCockpitNearContacts(
previous,
distancesSquared,
parts.rendering._modelAddDistM(),
parts.rendering._modelKeepDistM(),
all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M,
all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M,
);
flightState._cockpitNearContacts = next;
for (const icao24 of previous)
@@ -333,15 +337,17 @@ export function createTracking({
* @param {{x: number, y: number, z: number}} position - The report's ECEF position.
* @param {number} [epochMs] - The report's time; defaults to the tracked
* aircraft's newest position-history fix, which every caller has just pushed.
* @param {{nullAltitude?: boolean, track?: number}} [options] - `nullAltitude`:
* @param {{nullAltitude?: boolean, track?: number, estimated?: boolean}} [options] - `nullAltitude`:
* the report had no altitude, so its position is not kept and the line
* breaks there; `track`: its reported track, which the line leaves it along.
* breaks there; `track`: its reported track, which the line leaves it along;
* `estimated`: the feed estimated it, so it stands in only until the next
* received report.
*/
function _appendTrailFix(
position,
epochMs,
{ nullAltitude = false, track = undefined } = {},
{ nullAltitude = false, track = undefined, estimated = false } = {},
) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
@@ -352,7 +358,7 @@ export function createTracking({
position,
timeMs,
TRAIL_MAX_POINTS,
{ nullAltitude, track },
{ nullAltitude, track, estimated },
);
_refreshTrailDisplay();
}
@@ -391,12 +397,46 @@ export function createTracking({
);
}
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
/** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */
function _trailBodyCountNow() {
return trailBodyCount(
return trailBodyCount(flightState._trailFixes, _trailDisplayMs());
}
/**
* The time on its trail at which a host-supplied placement draws the
* aircraft, read off the trail where it is drawn (`trailTimeAt`): such a
* placement draws at a delay of its own, not this layer's. NaN when this
* layer's own motion draws it, or the trail has no pair to read.
* @returns {number} Epoch ms or NaN.
*/
function _placedTrailMs() {
if (!parts.motion._trackedPlaced?.()) return NaN;
return trailTimeAt(
flightState._trailFixes,
flightState.now() - displayDelayMs(flightState),
parts.motion._trackedDisplayCached(),
);
}
/**
* The time the trail runs up to: the time the aircraft is drawn at, now −
* the display delay, or where a placement draws it. Otherwise the trail
* ends short of a placed aircraft, or runs on ahead of it.
* @returns {number} Epoch ms.
*/
function _trailDisplayMs() {
const placedMs = _placedTrailMs();
return Number.isFinite(placedMs)
? placedMs
: flightState.now() - displayDelayMs(flightState);
}
/** Whether the trail holds no report behind the aircraft yet: this
* layer's own motion draws it before its oldest fix. Never for an
* aircraft a placement draws: its trail is read where it is drawn. */
function _trailWarmingUp() {
return (
!Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp()
);
}
@@ -413,7 +453,7 @@ export function createTracking({
if (
!flightState._trackedIcao ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
_trailWarmingUp()
)
return [];
const head =
@@ -436,7 +476,7 @@ export function createTracking({
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
_trailDisplayMs(),
),
head,
parts.motion._trackedModelCenterWorld(),
@@ -698,10 +738,11 @@ export function createTracking({
// Hand the contact back to its icon only now: settling floors a grounded
// contact, and while it still read as tracked its tracked model owned the
// visual, so the floor would have stepped aside.
if (flightState._icons?.has(clearedIcao)) {
flightState._icons.setShown(clearedIcao, true);
// Its fleet model, kept loaded while it was selected, takes it back in
// this frame; the icon shows only when there is no loaded one.
parts.rendering._handBackDeselected(clearedIcao);
if (flightState._icons?.has(clearedIcao))
parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg });
}
parts.icons._applyIconPresentation(clearedIcao);
clearTrackedSubjectContext('flights');
_emitAwarenessEvent('gev:awareness-subject-cleared', {
@@ -814,14 +855,18 @@ export function createTracking({
return { text: '', dimmed: false };
}
/** The tracked billboard's colour: cyan, faded while stale, clear while the 3D model is the visual. */
/** The tracked billboard's colour: the contact's own fleet colour (tracking
* never recolours it), faded while stale, clear while the 3D model is the
* visual. */
function _trackedIconColor() {
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
return CYAN_TRANSPARENT;
return _trackedStaleCue(flightState._trackedIcao).dimmed
? STALE_CYAN
: TRACKED_CYAN;
const icao24 = flightState._trackedIcao;
const color = parts.rendering._fleetBillboardColor(icao24);
if (parts.rendering._modelOwnsVisual(icao24))
return trackedIconColor(color, 0);
return _trackedStaleCue(icao24).dimmed
? trackedIconColor(color, STALE_ALPHA)
: color;
}
/**
@@ -913,10 +958,7 @@ export function createTracking({
width: look.size[0],
height: look.size[1],
get scale() {
return parts.rendering._fleetBillboardScale(
icao24,
flightState.records.data.get(icao24)?.klass,
);
return parts.rendering._fleetBillboardScale(icao24);
},
scaleByDistance: look.scaleByDistance,
};
@@ -1079,13 +1121,13 @@ export function createTracking({
imageLod: _trackedBillboardLook().imageLod,
sprite,
position: getTrackedPosition,
// Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
// street level would otherwise bury the cyan icon inside the runway
// street level would otherwise bury the icon inside the runway
// skin, so it draws over depth like the fleet icon set; its
// shared-host tracked card is top-composited separately.
rotation: () => {
@@ -1093,6 +1135,8 @@ export function createTracking({
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
// A ground station's mast stands upright.
if (tracked.klass === 'station') return 0;
const projected = courseScreenRotation(
_pose(),
pos,
+144 -2
View File
@@ -4,7 +4,12 @@ import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { TRAIL_MAX_POINTS } from './policy.js';
import { trailHeadJoins, trailPairBreaks } from '../../data/trailContinuity.js';
import {
insertTrailFix,
trailHeadJoins,
trailPairBreaks,
trailTimeAt,
} from '../../data/trailContinuity.js';
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
@@ -92,6 +97,8 @@ function trackedHarness({
nowMs,
floor,
head = null,
placed = false,
warmingUp = false,
} = {}) {
const trail = recordingTrail();
const svc = services({ trails: trail, floor });
@@ -122,7 +129,9 @@ function trackedHarness({
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_isTrackWarmingUp: () => warmingUp,
_trackedPlaced: () => placed,
_trackedDisplayCached: () => head,
_trackedTrailCached: () => head,
_trackedDisplayPosition: () => head,
_trackedModelCenterWorld: () => null,
@@ -410,3 +419,136 @@ test('every waypoint of a 24 h history survives, and the trail stays within TRAI
// The oldest go first: the newest live fix is still the last point.
assert.equal(fixes[fixes.length - 1].timeMs, liveStart);
});
/** A trail of `count` reports one minute apart flying east from (50, 1). */
function eastTrail(t0, count) {
const fixes = [];
for (let i = 0; i < count; i++)
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(1 + i * 0.12, 50, 10_000),
t0 + i * MINUTE,
TRAIL_MAX_POINTS,
);
return fixes;
}
test('the time on the trail is read where the aircraft is drawn', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const fixes = eastTrail(t0, 4);
const at = (lon) =>
trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(lon, 50, 10_000));
// Halfway between the second and third reports.
assert.ok(Math.abs(at(1.18) - (t0 + 1.5 * MINUTE)) < 2_000);
// On a report.
assert.ok(Math.abs(at(1.24) - (t0 + 2 * MINUTE)) < 2_000);
// Past the newest report the time runs on; before the oldest it runs back.
assert.ok(Math.abs(at(1.42) - (t0 + 3.5 * MINUTE)) < 2_000);
assert.ok(Math.abs(at(0.94) - (t0 - 0.5 * MINUTE)) < 2_000);
// Nothing to read without a pair of reports, or without a position.
assert.ok(Number.isNaN(trailTimeAt(fixes.slice(0, 1), fixes[0].position)));
assert.ok(Number.isNaN(trailTimeAt(fixes, null)));
});
test('the time on the trail is never read across a break', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const fixes = eastTrail(t0, 2);
// An hour later, far on: a new segment.
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(20, 50, 10_000),
t0 + HOUR,
TRAIL_MAX_POINTS,
);
insertTrailFix(
fixes,
Cesium.Cartesian3.fromDegrees(20.12, 50, 10_000),
t0 + HOUR + MINUTE,
TRAIL_MAX_POINTS,
);
assert.equal(fixes[2].breakBefore, true);
// Halfway along the gap is not on the trail: it is read on the newest pair.
const at = trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(10, 50, 10_000));
assert.ok(at <= t0 + HOUR, `read ${at - t0} ms in, across the break`);
});
test('a placed aircraft drawn ahead of the display delay keeps its trail joined to it', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2, 3].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 50,
lon: 1 + i * 0.12,
}));
// The layer's own delay puts the aircraft before its first fix (warming
// up), but the placement draws it between the third and fourth reports.
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 10_000);
const placed = trackedHarness({
liveFixes,
nowMs: t0 + 3.5 * MINUTE,
head: near,
placed: true,
warmingUp: true,
});
placed.flightState._displayDelay = { currentMs: 10 * MINUTE };
placed.tracking._startTrail('abc123');
// The body runs to the last report behind the aircraft, none ahead of it.
assert.deepEqual(
placed.trail.last().map((segment) => segment.length > 0),
[true],
);
const body = placed.trail.last()[0];
assert.ok(
Cesium.Cartesian3.distance(
body[body.length - 1],
Cesium.Cartesian3.fromDegrees(1.24, 50, 10_000),
) < 1,
);
// The head joins it to the aircraft.
const drawn = headPositions(placed);
assert.ok(drawn.length >= 2);
assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1);
assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1e-6);
// The layer's own motion, warming up, draws no head and no body.
const own = trackedHarness({
liveFixes,
nowMs: t0 + 3.5 * MINUTE,
head: near,
warmingUp: true,
});
own.flightState._displayDelay = { currentMs: 10 * MINUTE };
own.tracking._startTrail('abc123');
assert.deepEqual(own.trail.last(), []);
assert.deepEqual(headPositions(own), []);
});
test('a placed aircraft drawn behind the display delay has no trail ahead of it', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2, 3].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 50,
lon: 1 + i * 0.12,
}));
// The layer's delay would draw every report; the placement holds the
// aircraft between the first and second.
const behind = Cesium.Cartesian3.fromDegrees(1.06, 50, 10_000);
const { trail, tracking, flightState } = trackedHarness({
liveFixes,
nowMs: t0 + 4 * MINUTE,
head: behind,
placed: true,
});
flightState._displayDelay = { currentMs: 0 };
tracking._startTrail('abc123');
// One report behind it: no line yet, and nothing ahead of the aircraft.
assert.deepEqual(trail.last(), []);
const drawn = headPositions({ tracking });
assert.equal(drawn.length, 2);
assert.ok(
Cesium.Cartesian3.distance(
drawn[0],
Cesium.Cartesian3.fromDegrees(1, 50, 10_000),
) < 1,
);
assert.ok(Cesium.Cartesian3.distance(drawn[1], behind) < 1e-6);
});
+11 -2
View File
@@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
import { FLEET_TINT, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// A tracked trail is the aircraft's reports joined along the curve the icon
// is drawn along between them, so the icon always sits on its trail and a
@@ -116,7 +116,11 @@ function harness({
flightState.now = () => clock;
flightState._positionHistory.set(ICAO, fixes);
const parts = {
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
rendering: {
_modelOwnsVisual: () => false,
_modelSpec: () => ({}),
_fleetBillboardColor: () => FLEET_TINT,
},
queries: { _contactLabel: (id, info) => info?.callsign || id },
};
parts.motion = createMotion({ flightState, services: svc, parts });
@@ -797,6 +801,11 @@ test('a stalled feed dims the tracked plane as STALE', () => {
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
assert.deepEqual(
h.tracking._trackedIconColor().slice(0, 3),
FLEET_TINT.slice(0, 3),
'faded in its own colour, never recoloured',
);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
+7 -4
View File
@@ -863,9 +863,12 @@ export function createGhostMapsLayer({
title:
days === null
? t('Show markers of every age')
: t('Maximum event age: {days}d; undated markers are kept', {
days: formatNumber(days),
}),
: tn(
days,
'Maximum event age: {days}d; undated markers are kept',
'Maximum event age: {days}d; undated markers are kept',
{ days: formatNumber(days) },
),
active: days === _ageDays,
onClick: () => setAgeDays(days),
})),
@@ -900,7 +903,7 @@ export function createGhostMapsLayer({
};
}),
legend: [],
info: `${_ageDays === null ? t('All markers') : t('Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`,
info: `${_ageDays === null ? t('All markers') : tn(_ageDays, 'Event age: {days}d · undated kept', 'Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`,
infoTitle: t(
'S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.',
),
+30
View File
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
import { createGhostMapsLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
@@ -310,6 +311,35 @@ test('age controls default to seven days and widening restores filtered and expi
assert.equal(ageChip(layer, null).active, true);
});
test('the event age agrees with its number of days', async (t) => {
t.after(() => setLocale('en'));
const { layer, viewer } = fixture(t, { reports: [{ name: 'Undated' }] });
await layer.update(viewer);
const info = () =>
layer.getRowControls().info.split(' · ').slice(0, 2).join(' · ');
assert.equal(
ageChip(layer, 1).title,
'Maximum event age: 1d; undated markers are kept',
);
setLocale('de');
assert.equal(
ageChip(layer, 1).title,
'Maximales Ereignisalter: 1 Tag; undatierte Markierungen bleiben erhalten',
);
assert.equal(
ageChip(layer, 7).title,
'Maximales Ereignisalter: 7 Tage; undatierte Markierungen bleiben erhalten',
);
assert.equal(info(), 'Ereignisalter: 7 Tage · undatierte bleiben');
await ageChip(layer, 1).onClick();
assert.equal(info(), 'Ereignisalter: 1 Tag · undatierte bleiben');
setLocale('es');
assert.equal(
info(),
'Antigüedad: 1 día · se conservan los marcadores sin fecha',
);
});
test('age preferences persist independently of product choices and reject invalid storage', async (t) => {
const values = new Map([['gev.ghostmaps.products', '["cip"]']]);
const storage = {
+8 -35
View File
@@ -1,41 +1,15 @@
import { describeInstallationFeedback } from '../../data/installationFeedback.js';
import { installationFeedback } from '../../data/installationFeedback.js';
import {
LAYER_ID,
DISTANCE_PREFILTER_MARGIN_M,
ANCHOR_REFRESH_M,
} from './policy.js';
import { formatNumber, t, tn } from '../../i18n/index.js';
import { t } from '../../i18n/index.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { surfaceDistance } from '../../geo/geodesic.js';
import { toDegrees, toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
// installationFeedback.js is shared with the HUD (src/loadingFeedback.js) and
// hands back msg()-marked English plus values; getStats translates them here.
function localizeInstallationFeedback(feedback) {
if (feedback.text !== undefined) {
const values = {};
if (feedback.reason !== undefined) values.reason = t(feedback.reason);
if (feedback.seconds !== undefined) values.seconds = feedback.seconds;
return t(feedback.text, values);
}
const { count, km } = feedback;
if (km) {
const kmText = formatNumber(km);
return count === 0
? t('No mapped sites within {km} km of the contact', { km: kmText })
: tn(
count,
'{count} mapped site within {km} km of the contact',
'{count} mapped sites within {km} km of the contact',
{ km: kmText },
);
}
return count === 0
? t('No mapped sites in view')
: tn(count, '{count} mapped site in view', '{count} mapped sites in view');
}
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
id: LAYER_ID,
@@ -285,13 +259,12 @@ export function createControls({ state: layerState, services, parts, source }) {
retryAt: layerState.retryAt,
retrying: layerState.loading && Boolean(layerState.failureReason),
failureReason: layerState.failureReason,
statusMessage: localizeInstallationFeedback(
describeInstallationFeedback({
...layerState,
count: layerState.lastUpdate ? mappedCount : undefined,
retrying: layerState.loading && Boolean(layerState.failureReason),
}),
),
// English: the analyst reads it as is; displays translate it.
statusMessage: installationFeedback({
...layerState,
count: layerState.lastUpdate ? mappedCount : undefined,
retrying: layerState.loading && Boolean(layerState.failureReason),
}),
loadingLabel: layerState.loading
? t('loading mapped installation context')
: '',
@@ -1,6 +1,8 @@
// statusMessage stays English (the analyst's empty note); displays translate it.
import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale, translateKnown } from '../../i18n/index.js';
import { setLocale, t, tn } from '../../i18n/index.js';
import { translateStatusMessage } from '../../ui/statusText.js';
import { createControls } from './controls.js';
function stats(state) {
@@ -13,67 +15,113 @@ function stats(state) {
}).methods.getStats();
}
for (const locale of ['es', 'ru']) {
test(`${locale}: installation feedback is in the UI language`, () => {
setLocale(locale);
const empty = stats({ status: 'empty', lastUpdate: 1 }).statusMessage;
assert.notEqual(empty, 'No mapped sites in view');
const found = stats({
function inLocale(locale, run) {
setLocale(locale);
try {
run();
} finally {
setLocale('en');
}
}
// A retry a minute out reads "60s" (rounded up).
const cases = [
[
{ status: 'empty', lastUpdate: 1 },
'No mapped sites in view',
() => t('No mapped sites in view'),
],
[
{ status: 'ready', lastUpdate: 1, records: [{ kind: 'installation' }] },
'1 mapped site in view',
() => tn(1, '{count} mapped site in view', '{count} mapped sites in view'),
],
[
{
status: 'ready',
lastUpdate: 1,
records: [{ kind: 'installation' }, { kind: 'installation' }],
}).statusMessage;
assert.notEqual(found, '2 mapped sites in view');
const tiles = stats({
status: 'unavailable',
failureReason: 'tiles_unavailable',
}).statusMessage;
assert.notEqual(tiles, 'Map tiles temporarily unavailable');
const retry = stats({
},
'2 mapped sites in view',
() => tn(2, '{count} mapped site in view', '{count} mapped sites in view'),
],
[
{
status: 'empty',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
},
'No mapped sites within 25 km of the contact',
() => t('No mapped sites within {km} km of the contact', { km: '25' }),
],
[
{
status: 'ready',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
records: [{ kind: 'installation' }],
},
'1 mapped site within 25 km of the contact',
() =>
tn(
1,
'{count} mapped site within {km} km of the contact',
'{count} mapped sites within {km} km of the contact',
{ km: '25' },
),
],
[
{ status: 'unavailable', failureReason: 'tiles_unavailable' },
'Map tiles temporarily unavailable',
() => t('Map tiles temporarily unavailable'),
],
[
{
status: 'unavailable',
failureReason: 'names_unavailable',
retryAt: Date.now() + 5000,
}).statusMessage;
assert.doesNotMatch(retry, /^Mapped names temporarily unavailable/);
for (const text of [
'Too many mapped sites in view to list them all',
'Installation context unavailable',
]) {
assert.notEqual(translateKnown(text), text);
}
get retryAt() {
return Date.now() + 60_000;
},
},
'Mapped names temporarily unavailable — retrying in 60s',
() =>
t('{reason} — retrying in {seconds}s', {
reason: t('Mapped names temporarily unavailable'),
seconds: 60,
}),
],
[
{ status: 'zoom-in' },
'Zoom in to search mapped installations',
() => t('Zoom in to search mapped installations'),
],
];
for (const locale of ['es', 'ru']) {
test(`${locale}: installation statusMessage stays English data`, () => {
inLocale(locale, () => {
for (const [state, english] of cases)
assert.equal(stats(state).statusMessage, english);
});
});
test(`${locale}: installation statusMessage is shown in the UI language`, () => {
inLocale(locale, () => {
for (const [state, english, shown] of cases) {
const shownText = translateStatusMessage(stats(state).statusMessage);
assert.notEqual(shownText, english);
assert.equal(shownText, shown());
}
});
});
}
test('en: installation feedback keeps its English wording', () => {
setLocale('en');
assert.equal(
stats({ status: 'empty', lastUpdate: 1 }).statusMessage,
'No mapped sites in view',
);
assert.equal(
stats({
status: 'ready',
lastUpdate: 1,
records: [{ kind: 'installation' }],
}).statusMessage,
'1 mapped site in view',
);
assert.equal(
stats({
status: 'ready',
lastUpdate: 1,
wide: true,
coverage: { kind: 'subject', radiusM: 25000 },
records: [{ kind: 'installation' }, { kind: 'installation' }],
}).statusMessage,
'2 mapped sites within 25 km of the contact',
);
assert.equal(
stats({
status: 'unavailable',
failureReason: 'names_unavailable',
retryAt: Date.now() + 5000,
}).statusMessage,
'Mapped names temporarily unavailable — retrying in 5s',
);
for (const [state, english] of cases) {
assert.equal(stats(state).statusMessage, english);
assert.equal(translateStatusMessage(english), english);
}
});
+106 -1
View File
@@ -1,4 +1,35 @@
import { formatNumber, t } from '../../i18n/index.js';
export function createControls({ state: layerState, services, parts, source }) {
let unsubscribeRowControls = null;
function cycleMission(step) {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const next =
index < 0
? step > 0
? 0
: entries.length - 1
: (index + step + entries.length) % entries.length;
parts.panel.selectMissionAt(entries[next].index);
// Stepped from the Data Layers row: the panel opens, as for a globe pick.
const id = layerState._selectedLaunchId;
for (const listener of [...(layerState._globePickListeners || [])]) {
try {
listener(id);
} catch (error) {
console.warn(
'[Data:RocketLaunches] mission step listener failed',
error,
);
}
}
}
const methods = {
id: 'rocket-launches',
@@ -10,6 +41,67 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: 300000,
getRowControls() {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return null;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const disabled = entries.length === 1 && index >= 0;
return {
info:
index < 0
? t('SELECT A MISSION TO INSPECT')
: `${formatNumber(index + 1)} / ${formatNumber(entries.length)} · ${entries[index].label}`,
chips: [
{
id: 'previous-mission',
label: t('Previous mission'),
icon: 'chevron_left',
action: true,
disabled,
onClick: () => cycleMission(-1),
},
{
id: 'next-mission',
label: t('Next mission'),
icon: 'chevron_right',
action: true,
disabled,
onClick: () => cycleMission(1),
},
],
};
},
setRowControlsListener(listener) {
unsubscribeRowControls?.();
unsubscribeRowControls = null;
if (!listener) return;
let previousRoster;
let previousSelection;
unsubscribeRowControls = parts.panel.subscribePanel(({ roster }) => {
// Replay and telemetry can update without changing the roster or pick.
const selection = layerState._selectedLaunchId;
if (roster === previousRoster && selection === previousSelection)
return;
previousRoster = roster;
previousSelection = selection;
listener();
});
},
/**
* Hear each mission picked on the globe (a marker or its label), after
* it is selected. The app reveals the Space Missions panel for it.
* @param {(launchId: string) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribeGlobePick(listener) {
layerState._globePickListeners.add(listener);
return () => layerState._globePickListeners.delete(listener);
},
/** Release only Space Mission camera ownership, preserving layer and selection state. */
releaseCameraOwnership() {
// Navigation takes the camera; a failed entry must not restore the old view.
@@ -54,19 +146,32 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* Why a start failed, for the person: the mission index never loaded.
* Null when the failure is not the index's (the app then names it).
* @returns {?string}
*/
enableFailureMessage() {
return layerState._lastError && layerState._lastUpdate == null
? t(
'Space Missions unavailable: the mission index could not load. Try again later.',
)
: null;
},
getStats() {
return {
count: layerState._count,
orbitMatches: layerState._orbitMatches,
lastUpdate: layerState._lastUpdate,
error: layerState._lastError,
errorAt: layerState._lastErrorAt,
stale: layerState._stale,
};
},
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
parts.satelliteIntents.connect(dataManager);
},
};
+285 -47
View File
@@ -4,12 +4,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { DataLayerManager } from '../../data/manager.js';
import { ContextControls } from '../../ui/contextControls.js';
import { spaceMissionsIndexFailure } from '../../ui/contextActions.js';
import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createPanel } from './panel.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
@@ -98,7 +98,7 @@ function fakeCamera() {
return camera;
}
async function fixture(t) {
async function fixture(t, { beforeConnect } = {}) {
const upstream = { status: 429, results: [launchRecord] };
const source = createLaunchSource({
async fetchImpl(url) {
@@ -191,6 +191,7 @@ async function fixture(t) {
parts.panel = createPanel(context);
parts.replay = createReplay(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const missions = Object.assign(
@@ -206,6 +207,7 @@ async function fixture(t) {
manager.register(plainLayer('earthquakes', 'Earthquakes (24h)'));
manager.register(plainLayer('satellites', 'Satellites'));
manager.register(plainLayer('wind', 'Wind'));
manager.register(plainLayer('military-awareness', 'Global Context'));
manager.register(missions);
missions.attachDataManager(manager);
@@ -224,12 +226,19 @@ async function fixture(t) {
setPanelCollapsed: noop,
},
});
beforeConnect?.(manager);
controls.connect(manager);
t.after(async () => {
controls.stop();
controls.disconnect();
for (const id of ['rocket-launches', 'satellites', 'earthquakes', 'wind'])
for (const id of [
'rocket-launches',
'satellites',
'earthquakes',
'wind',
'military-awareness',
])
await manager.setEnabled(id, false);
await missions.destroy(viewer);
});
@@ -257,46 +266,37 @@ async function fixture(t) {
state,
camera,
rosters,
panel: parts.panel,
enabledIds,
view,
settle,
};
}
const entries = {
direct: (f) =>
f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
'Context-panel': async (f) =>
(
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
})
).ok,
};
test('a Space Missions start that gets HTTP 429 rolls back and leaves other layers alone', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
for (const [path, enter] of Object.entries(entries))
test(`a ${path} Space Missions entry that gets HTTP 429 rolls back instead of isolating`, async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
const entered = await enter(f);
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
const entered = await f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
});
// Holds the /api/launches reply until the returned release is called.
function holdReply(f) {
@@ -410,7 +410,12 @@ test('the roster reports a failed mission index instead of loading forever', asy
await f.settle();
assert.equal(f.rosters.slice(loadingFrom).includes(null), true);
assert.equal(f.rosters.at(-1).entries.length, 1);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.controls.getContextModeState().mode,
null,
'not a Context mode',
);
});
test('a valid empty mission index is a successful entry', async (t) => {
@@ -422,7 +427,7 @@ test('a valid empty mission index is a successful entry', async (t) => {
true,
);
await f.settle();
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.rosters.at(-1).empty,
'NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW',
@@ -430,7 +435,236 @@ test('a valid empty mission index is a successful entry', async (t) => {
assert.ok(f.camera.flights > 0, 'a successful entry frames the globe');
});
test('a refresh failure after a loaded index keeps the mode and its records', async (t) => {
for (const phase of ['while starting', 'after start']) {
test(`Space Missions runs beside Contacts and a later Satellites OFF ends it (${phase})`, async (t) => {
const gate = Promise.withResolvers();
const guardReached = Promise.withResolvers();
const f = await fixture(t, {
beforeConnect(manager) {
if (phase !== 'while starting') return;
manager.addVisibilityGuard(async ({ layerId, enabled }) => {
if (layerId !== 'rocket-launches' || !enabled) return;
guardReached.resolve();
await gate.promise;
});
},
});
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(
f.enabledIds(),
['military-awareness', 'satellites'],
'Contacts leaves Satellites alone',
);
const launch = f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
try {
if (phase === 'while starting') {
await guardReached.promise;
} else {
assert.equal(await launch, true);
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
}
assert.equal(
f.controls.getContextModeState().mode,
'flights',
'starting Space Missions leaves Contacts on',
);
assert.equal(
await f.manager.setEnabled('satellites', false, { origin: 'voice' }),
true,
);
} finally {
gate.resolve();
}
assert.equal(await launch, phase === 'after start');
await f.missions.waitForSatelliteIntents?.();
await f.settle();
assert.deepEqual(f.enabledIds(), ['military-awareness']);
assert.equal(f.controls.getContextModeState().mode, 'flights');
});
}
test('Contacts started and ended while Space Missions runs leaves it and Satellites alone', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
const missionParams = f.manager.getLayerParams('satellites');
assert.equal(missionParams.showPoints, false, 'the mission display applied');
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
assert.equal(await f.controls._selectContextMode(null), true);
await f.settle();
assert.deepEqual(f.enabledIds(), ['rocket-launches', 'satellites']);
assert.deepEqual(f.manager.getLayerParams('satellites'), missionParams);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.enabledIds(), []);
const after = f.manager.getLayerParams('satellites');
assert.notEqual(after.showPoints, false, 'Satellites shows its points again');
assert.notEqual(after.showOrbits, false, 'and its orbits');
});
test('a Satellites OFF requested before Space Missions entry does not cancel it', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
const gate = Promise.withResolvers();
const disabling = Promise.withResolvers();
satellites.disable = async () => {
disabling.resolve();
await gate.promise;
};
let entry;
try {
const off = f.manager.setEnabled('satellites', false, { origin: 'user' });
await disabling.promise;
// The entry is requested while the earlier OFF is still settling.
entry = f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
gate.resolve();
assert.equal(await off, true);
} finally {
gate.resolve();
satellites.disable = disable;
}
assert.equal(await entry, true, 'the later entry is not cancelled');
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
// Leaving keeps the earlier Satellites OFF.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
assert.equal(f.manager.isEnabled('rocket-launches'), false);
});
test('Space Missions is an ordinary layer: it neither isolates nor opens a Context session', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'earthquakes',
'rocket-launches',
'satellites',
]);
assert.equal(f.controls._contextSessionSnapshot, null);
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'other layers are not refused while Space Missions is on',
);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(
f.enabledIds(),
['earthquakes', 'wind'],
'Space Missions gives back only the Satellites it turned on',
);
});
test('a Satellites enable that never settles still lets mission disable complete', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
// A programmatic Satellites restart whose enable hangs.
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
const exit = f.manager.setEnabled('rocket-launches', false, {
origin: 'user',
});
const outcome = await Promise.race([
exit.then(() => 'settled'),
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
]);
assert.equal(
outcome,
'settled',
'the mission disable does not wait forever',
);
assert.equal(f.missions.getAnalystRecords().length, 0);
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
});
test('a failed Satellites restore still clears the selected mission panel', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), true);
let panelView;
const unsubscribe = f.panel.subscribePanel((view) => {
panelView = view;
});
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
try {
f.state._selectedLaunchId = f.state._launches[0].id;
f.panel.renderMissionPanel();
assert.ok(panelView.mission);
satellites.disable = () => {
throw new Error('injected Satellites restore failure');
};
assert.equal(
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' }),
false,
);
const { enabled, uncertain } =
f.manager.getLayerLifecycleState('rocket-launches');
assert.equal(enabled, true);
assert.equal(uncertain, true);
assert.equal(panelView.mission, null);
} finally {
satellites.disable = disable;
unsubscribe();
}
});
test('a refresh failure after a loaded index keeps the layer and its records', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
@@ -442,12 +676,11 @@ test('a refresh failure after a loaded index keeps the mode and its records', as
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.missions.getStats().count, 1);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.rosters.at(-1).entries.length, 1);
// Leaving a loaded mode does not restore the pre-entry view.
// Leaving after a loaded index does not restore the pre-entry view.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.view(), framed);
@@ -475,11 +708,9 @@ test('a failed first load tells the user the mission index is unavailable', asyn
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
});
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.equal(f.controls.getContextModeState().mode, null, 'rolled back');
assert.equal(f.manager.isEnabled('rocket-launches'), false, 'rolled back');
assert.ok(
f.toasts.some((message) => /mission index/i.test(message)),
`visible feedback names the failure, got ${JSON.stringify(f.toasts)}`,
@@ -504,10 +735,17 @@ test('navigation taking the camera keeps a mission flight it asked to preserve',
assert.equal(f.camera.flight, other);
});
test("an earlier attempt's index error is not blamed for a later failure", async (t) => {
test('a refresh error after a loaded index is not blamed on the index', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.match(spaceMissionsIndexFailure(f.manager), /mission index/);
assert.equal(spaceMissionsIndexFailure(f.manager, Date.now() + 1), null);
assert.match(f.missions.enableFailureMessage(), /mission index/);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
f.upstream.status = 429;
await f.missions.update();
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.missions.enableFailureMessage(), null);
});
+3
View File
@@ -1,5 +1,6 @@
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createOrbitRendering } from './orbitRendering.js';
import { createOverlays } from './overlays.js';
import { createSelection } from './selection.js';
@@ -24,6 +25,7 @@ export function createRocketLaunchesLayer({ services, source }) {
const context = { state, services, parts, source };
parts.policyHelpers = createPolicyHelpers(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.orbitRendering = createOrbitRendering(context);
parts.overlays = createOverlays(context);
parts.selection = createSelection(context);
@@ -45,6 +47,7 @@ export function createRocketLaunchesLayer({ services, source }) {
parts.panel.commands,
{
subscribePanel: parts.panel.subscribePanel,
waitForSatelliteIntents: parts.satelliteIntents.settled,
subscribeReplayOverlay: parts.overlays.subscribeReplayOverlay,
satelliteParamsForSpaceMissions:
parts.policyHelpers.satelliteParamsForSpaceMissions,
+55 -22
View File
@@ -1,5 +1,15 @@
import { MAX_POST_TLE_RETRIES, POST_TLE_RETRY_DELAY_MS } from './policy.js';
/**
* Let pending Satellites work finish, including requests that join it while
* waiting, so the mission dependency cannot overtake it. Bounded: a
* Satellites change that never settles cannot hold missions forever.
*/
async function waitForSatelliteVisibility(manager, { signal, timeoutMs }) {
if (typeof manager.waitForLayerIdle !== 'function') return true;
return manager.waitForLayerIdle('satellites', { signal, timeoutMs });
}
export function createIngestion({
state: layerState,
services,
@@ -97,28 +107,39 @@ export function createIngestion({
}
async function captureSatelliteDependency() {
if (!layerState._dataManager || layerState._satelliteStateBeforeMission)
const manager = layerState._dataManager;
if (!manager || layerState._satelliteStateBeforeMission) return;
const token = layerState._lifecycleToken;
// Let a pending Satellites action finish before reserving dependency ON.
// A successful explicit OFF can cancel this mission entry while we wait.
const idle = await waitForSatelliteVisibility(manager, {
signal: layerState._sourceController?.signal,
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (token !== layerState._lifecycleToken) return;
if (!idle && layerState._enabled)
throw new Error(
'Space Missions could not start: the satellites layer did not settle',
);
if (
!layerState._enabled ||
(manager.layers?.has('rocket-launches') &&
!manager.isEffectivelyEnabled('rocket-launches'))
)
return;
layerState._satelliteStateBeforeMission = {
// Effective visibility: a user enable still mid-activation is intent ON —
// capturing settled false would restore the user's enable away on exit.
enabled:
layerState._dataManager.isEffectivelyEnabled?.('satellites') ??
layerState._dataManager.isEnabled('satellites'),
enabled: manager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
layerState._dataManager.getLayerParams('satellites'),
manager.getLayerParams('satellites'),
),
};
layerState._dataManager.setLayerParams(
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsForSpaceMissions(
layerState._satelliteStateBeforeMission.params,
),
);
const token = layerState._lifecycleToken;
const activation = Promise.resolve(
layerState._dataManager.setEnabled('satellites', true),
);
const activation = Promise.resolve(manager.setEnabled('satellites', true));
layerState._satelliteActivationPromise = activation;
try {
const activated = await activation;
@@ -128,8 +149,7 @@ export function createIngestion({
if (
token === layerState._lifecycleToken &&
layerState._enabled &&
(activated === false ||
!layerState._dataManager.isEnabled('satellites'))
(activated === false || !manager.isEnabled('satellites'))
) {
throw new Error(
'Space Missions requires the satellites layer, which failed to start',
@@ -146,21 +166,35 @@ export function createIngestion({
}
async function restoreSatelliteDependency() {
const manager = layerState._dataManager;
const snapshot = layerState._satelliteStateBeforeMission;
if (!snapshot || !layerState._dataManager) return;
if (!snapshot || !manager) return;
// Keep the snapshot available until any explicit Satellites action settles.
const token = layerState._lifecycleToken;
const idle = await waitForSatelliteVisibility(manager, {
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (
token !== layerState._lifecycleToken ||
layerState._satelliteStateBeforeMission !== snapshot
)
return;
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager.setLayerParams(
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
);
const restored = await layerState._dataManager.setEnabled(
'satellites',
snapshot.enabled,
);
// An accepted Satellites action owns visibility through mission teardown.
if (snapshot.restoreVisibility === false) return;
if (!idle)
throw new Error(
'Space Missions could not restore the satellites layer: it did not settle',
);
const restored = await manager.setEnabled('satellites', snapshot.enabled);
if (
restored === false ||
layerState._dataManager.isEnabled('satellites') !== snapshot.enabled
manager.isEnabled('satellites') !== snapshot.enabled
) {
throw new Error('Space Missions could not restore the satellites layer');
}
@@ -230,7 +264,6 @@ export function createIngestion({
} catch (error) {
if (layerState._enabled && token === layerState._lifecycleToken) {
layerState._lastError = error.message;
layerState._lastErrorAt = Date.now();
console.warn('[Data:RocketLaunches] Fetch error:', error);
// No index yet: fail the enable so Context rolls back.
// After a loaded index, a failed refresh keeps its records.
+7 -1
View File
@@ -8,6 +8,7 @@ import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { layerFeedState } from '../../data/feedState.js';
@@ -147,6 +148,7 @@ async function fixture({ legacySource = false } = {}) {
const context = { state, services, parts, source };
parts.model = createModel(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const current = () => {
@@ -326,7 +328,11 @@ test('destroy followed by actual init starts a clean instance with owned handler
assert.equal(typeof f.state._inputSubscription, 'function');
await f.destroy();
assert.equal(f.state._inputSubscription, null);
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
assert.equal(
input.subscriberCount(),
before - 3,
'label click, point click and hover',
);
assert.equal(f.attachedSets(), 0);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
+221
View File
@@ -0,0 +1,221 @@
// Clicks on painted mission labels, routed through the real input dispatcher.
import test from 'node:test';
import assert from 'node:assert/strict';
import { Event } from 'cesium';
import { createLifecycle } from './lifecycle.js';
import { createState } from './state.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
import {
FAKE_EVENT_TYPES,
FakeScreenSpaceEventHandler,
fakeInput,
} from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
const noop = () => {};
/** Parts whose every method is a no-op unless given. */
function stub(methods = {}) {
return new Proxy(methods, {
get: (target, key) => (key in target ? target[key] : noop),
});
}
function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
const stock = new FakeScreenSpaceEventHandler();
stock.setInputAction(noop, FAKE_EVENT_TYPES.LEFT_CLICK);
const viewer = bindFakeCesiumCamera({
isDestroyed: () => false,
screenSpaceEventHandler: stock,
camera: {
moveStart: new Event(),
moveEnd: new Event(),
pickEllipsoid: () => null,
},
scene: {
canvas: { style: { cursor: '' } },
screenSpaceCameraController: { enableInputs: true },
pick: () => undefined,
drillPick: () => [],
},
});
const pointer = fakeInput(viewer);
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
hitTestWorldOverlay: () => overlayHit,
},
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
};
const state = createState({ services });
const focused = [];
const restoreFailure = { error: null };
const parts = {
panel: stub(),
overlays: stub(),
replay: stub(),
launchPad: stub(),
orbitRendering: stub(),
selection: stub({
setSelectedMission: (id) => focused.push(id),
}),
satelliteIntents: stub(),
ingestion: stub({
async restoreSatelliteDependency() {
if (restoreFailure.error) throw restoreFailure.error;
},
}),
rendering: stub({
missionsShown: () => true,
missionHitsAt: () => [],
launchIdFromPicks: () => geometryLaunchId,
launchMarkerAt: () => null,
}),
};
const lifecycle = createLifecycle({
state,
services,
parts,
source: {},
}).methods;
lifecycle.init(viewer);
state._enabled = true;
state._launches = [{ id: 'L1' }, { id: 'L2' }];
// Another layer's ambient click handler, as aircraft or the cockpit has.
const ambient = [];
const offAmbient = pointer.input.onClick((event) => ambient.push(event));
t.after(async () => {
restoreFailure.error = null;
offAmbient();
await lifecycle.destroy(viewer);
pointer.input.destroy();
});
return {
focused,
ambient,
state,
lifecycle,
viewer,
input: pointer.input,
restoreFailure,
setHit(hit) {
overlayHit = hit;
},
click: () => pointer.tap({ x: 40, y: 30 }),
};
}
const label = (
entryId,
sourceId = ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
) => ({
sourceId,
entryId,
});
test('a mission label click focuses its launch and stops the click there', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
r.click();
assert.deepEqual(r.focused, ['L2']);
assert.equal(r.ambient.length, 0, 'the layers beneath do not see it');
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
r.click();
assert.deepEqual(r.focused, ['L2', 'L1'], 'the selected label routes too');
});
test('a mission picked on the globe is announced, after it is selected', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const picks = [];
r.state._globePickListeners.add((id) => picks.push([id, [...r.focused]]));
r.click();
assert.deepEqual(picks, [['L2', ['L2']]], 'the label pick is announced');
r.setHit(null);
r.click();
assert.equal(picks.length, 1, 'a click on nothing announces nothing');
});
test('a throwing globe-pick listener does not stop the pick', (t) => {
const r = rig(t, { overlayHit: label('launch:L1') });
const warn = console.warn;
console.warn = noop;
t.after(() => {
console.warn = warn;
});
const heard = [];
r.state._globePickListeners.add(() => {
throw new Error('listener failure');
});
r.state._globePickListeners.add((id) => heard.push(id));
r.click();
assert.deepEqual(r.focused, ['L1']);
assert.deepEqual(heard, ['L1']);
assert.equal(r.ambient.length, 0);
});
test('a mission label for an unknown launch falls through to other layers', (t) => {
const r = rig(t, {
overlayHit: label('launch:gone'),
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'nothing is focused');
assert.equal(r.ambient.length, 1, 'other layers still get the click');
});
test("another layer's label keeps the click above mission geometry", (t) => {
// An aircraft label painted over a mission path.
const r = rig(t, {
overlayHit: { sourceId: 'aircraft-labels', entryId: 'launch:L1' },
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'the mission under the label is not picked');
assert.equal(r.ambient.length, 1, "the label's owner gets the click");
// With no label there, the same click picks the mission geometry.
r.setHit(null);
r.click();
assert.deepEqual(r.focused, ['L1']);
});
test('a mission label leaves the click to the cockpit while it is on', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: {
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
},
});
try {
r.click();
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
assert.deepEqual(r.focused, []);
assert.equal(r.ambient.length, 1, 'the cockpit click handler gets it');
});
test('destroy releases the click handlers when the Satellites restore fails', async (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const before = r.input.subscriberCount();
r.restoreFailure.error = new Error('injected Satellites restore failure');
await assert.rejects(r.lifecycle.destroy(r.viewer), /injected/);
assert.equal(r.state._inputSubscription, null);
// The rest of teardown still ran before the failure was reported.
assert.equal(r.state._viewer, null, 'the viewer is released');
assert.deepEqual(r.state._launches, [], 'the records are dropped');
assert.equal(r.state._dataManager, null, 'the manager is released');
assert.ok(r.input.subscriberCount() < before, 'the handlers unsubscribed');
r.click();
assert.deepEqual(r.focused, [], 'a later label click reaches no mission');
assert.equal(r.ambient.length, 1);
});
+83 -19
View File
@@ -2,6 +2,10 @@ import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -150,6 +154,22 @@ function restoreCameraView(viewer, view, landedView) {
/** The longest name a timeline mark carries, as in the mission index. */
const MARK_LABEL_LENGTH = 27;
/** Whether the cockpit view is on. */
function cockpitActive() {
return Boolean(
globalThis.document?.body?.classList?.contains?.('cockpit-mode'),
);
}
function markerLaunchId(hit) {
if (
hit?.sourceId !== ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID &&
hit?.sourceId !== ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID
)
return null;
return hit.entryId.startsWith('launch:') ? hit.entryId.slice(7) : null;
}
export function createLifecycle({
state: layerState,
services,
@@ -157,6 +177,25 @@ export function createLifecycle({
source,
}) {
const { holdContinuousRender, releaseContinuousRender } = services.render;
const overlayAt = (position) =>
services.overlays?.hitTestWorldOverlay?.(position?.x, position?.y);
const missionsShown = () =>
layerState._enabled && parts.rendering.missionsShown();
const focusLaunch = (id) => {
if (!id) return false;
const launch = layerState._launches.find((entry) => entry.id === id);
if (!launch) return false;
parts.selection.setSelectedMission(launch.id);
parts.selection.focusMission(launch);
for (const listener of [...layerState._globePickListeners]) {
try {
listener(launch.id);
} catch (error) {
console.warn('[Data:RocketLaunches] globe pick listener failed', error);
}
}
return true;
};
let hover = null;
// While on, the launches loaded span the time from the first to the last,
// each one a mark labelled with its mission's name (the launch's where it
@@ -204,29 +243,45 @@ export function createLifecycle({
layerState._orbitMatches = 0;
parts.overlays.clearMissionOverlaySources();
const input = inputFor(viewer);
const overlayClicks = new WeakSet();
const unsubscribeLabelClick = input.onOverlayClick((event) => {
// The cockpit reads ambient clicks; a mission label must not take them.
if (!missionsShown() || cockpitActive()) return false;
const hit = overlayAt(event.screenPosition);
if (!hit) return false;
// Capture the painted hit before other handlers can invalidate the
// overlay. An unrelated label keeps the click above mission geometry.
overlayClicks.add(event);
return focusLaunch(markerLaunchId(hit));
});
const unsubscribeClick = input.onClick((event) => {
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
// Mission overlays are not interactive, so any overlay entry hit
// here is another layer's card or label painted over the click: that
// layer's click, not a mission's.
if (services.picking?.clickCard?.(event)) return;
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
);
if (!launchId) return;
parts.selection.setSelectedMission(launchId);
parts.selection.focusMission(
layerState._launches.find((launch) => launch.id === launchId),
// Another layer's card or label on top is that layer's click, read
// once per click as every layer reads it.
if (
!missionsShown() ||
overlayClicks.has(event) ||
services.picking?.clickCard?.(event)
)
return;
focusLaunch(
parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
),
);
});
hover = createLaunchHover({
viewer,
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
launchAt: parts.rendering.launchMarkerAt,
enabled: missionsShown,
launchAt(position) {
const hit = overlayAt(position);
return hit
? Boolean(markerLaunchId(hit))
: parts.rendering.launchMarkerAt(position);
},
});
const unsubscribeHover = input.onPointer('move', hover.move);
layerState._inputSubscription = () => {
unsubscribeLabelClick();
unsubscribeClick();
unsubscribeHover();
};
@@ -325,8 +380,8 @@ export function createLifecycle({
parts.overlays.hideReplayVehicleOverlay();
layerState._selectedLaunchId = null;
parts.overlays.clearMissionOverlaySources();
await parts.ingestion.restoreSatelliteDependency();
parts.panel.renderMissionPanel();
await parts.ingestion.restoreSatelliteDependency();
layerState.coverageChanged();
},
@@ -340,14 +395,22 @@ export function createLifecycle({
layerState._enabled = false;
layerState._lifecycleToken++;
layerState._updateDirty = false;
await parts.ingestion.restoreSatelliteDependency();
// A failed Satellites restore still tears everything else down; the
// failure is reported once teardown is complete.
let restoreError = null;
try {
await parts.ingestion.restoreSatelliteDependency();
} catch (error) {
restoreError = error;
}
layerState._inputSubscription?.();
layerState._inputSubscription = null;
parts.satelliteIntents.connect(null);
parts.panel.clearMissionRosterHover();
parts.replay.stopMissionReplay();
layerState._cameraReleased = true;
parts.selection.stopMissionZoomAnchor();
parts.ingestion.clearPostTleRetry();
layerState._inputSubscription?.();
layerState._inputSubscription = null;
if (layerState._declutterHandler) layerState._declutterHandler();
layerState._declutterHandler = null;
parts.launchPad.destroyLaunchPadZonePrimitive();
@@ -374,6 +437,7 @@ export function createLifecycle({
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager = null;
if (restoreError) throw restoreError;
},
};
+179
View File
@@ -0,0 +1,179 @@
// The Data Layers row's previous/next mission controls, and the Satellites
// restore an explicit Satellites action takes over.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
const roster = (...ids) => ({
entries: ids.map((id, index) => ({ id, index, label: `Mission ${id}` })),
});
function rig({ ids = ['A', 'B', 'C'], selected = null, enabled = true } = {}) {
const panelListeners = new Set();
const state = {
_enabled: enabled,
_selectedLaunchId: selected,
_missionRosterView: ids ? roster(...ids) : null,
};
const parts = {
panel: {
selectMissionAt(index) {
state._selectedLaunchId = state._missionRosterView.entries[index].id;
},
subscribePanel(listener) {
panelListeners.add(listener);
return () => panelListeners.delete(listener);
},
},
};
const { methods } = createControls({ state, services: {}, parts });
return {
state,
methods,
chip: (id) => methods.getRowControls().chips.find((c) => c.id === id),
publish: (view) => {
for (const listener of [...panelListeners]) listener(view);
},
listenerCount: () => panelListeners.size,
};
}
test('next and previous wrap around the roster', () => {
const r = rig({ selected: 'C' });
r.chip('next-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'A',
'next after the last is the first',
);
r.chip('previous-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'C',
'previous before the first is the last',
);
r.chip('previous-mission').onClick();
assert.equal(r.state._selectedLaunchId, 'B');
assert.match(r.methods.getRowControls().info, /^2 \/ 3 · Mission B$/);
});
test('with nothing selected, next picks the first mission and previous the last', () => {
const next = rig();
next.chip('next-mission').onClick();
assert.equal(next.state._selectedLaunchId, 'A');
const previous = rig();
previous.chip('previous-mission').onClick();
assert.equal(previous.state._selectedLaunchId, 'C');
});
test('the controls disable only when the one mission is already selected', () => {
const only = rig({ ids: ['A'], selected: 'A' });
assert.equal(only.chip('next-mission').disabled, true);
assert.equal(only.chip('previous-mission').disabled, true);
// One mission, not yet picked: the controls can still select it.
const unpicked = rig({ ids: ['A'] });
assert.equal(unpicked.chip('next-mission').disabled, false);
unpicked.chip('next-mission').onClick();
assert.equal(unpicked.state._selectedLaunchId, 'A');
assert.equal(rig({ selected: 'B' }).chip('next-mission').disabled, false);
});
test('there are no controls while the layer is off or the roster is empty', () => {
assert.equal(rig({ enabled: false }).methods.getRowControls(), null);
assert.equal(rig({ ids: [] }).methods.getRowControls(), null);
assert.equal(rig({ ids: null }).methods.getRowControls(), null);
// A stale click after the layer stops selects nothing.
const r = rig({ selected: 'A' });
const next = r.chip('next-mission');
r.state._enabled = false;
next.onClick();
assert.equal(r.state._selectedLaunchId, 'A');
});
test('the row listener fires only when the roster or the selection changes', () => {
const r = rig();
let calls = 0;
r.methods.setRowControlsListener(() => calls++);
const view = r.state._missionRosterView;
r.publish({ roster: view });
assert.equal(calls, 1, 'the first view is a change');
r.publish({ roster: view });
assert.equal(calls, 1, 'a replay or telemetry update is not');
r.state._selectedLaunchId = 'B';
r.publish({ roster: view });
assert.equal(calls, 2, 'a new selection is');
r.publish({ roster: roster('A', 'B') });
assert.equal(calls, 3, 'a new roster is');
// A new listener replaces the old one; null removes it.
let replaced = 0;
r.methods.setRowControlsListener(() => replaced++);
assert.equal(r.listenerCount(), 1);
r.methods.setRowControlsListener(null);
assert.equal(r.listenerCount(), 0);
r.publish({ roster: roster('C') });
assert.equal(calls, 3);
assert.equal(replaced, 0);
});
function satelliteRig({ enabledBefore }) {
const calls = [];
let satellitesOn = true;
const manager = {
layers: new Map([['satellites', { toggleChain: null }]]),
waitForLayerIdle: async () => true,
isEnabled: () => satellitesOn,
isEffectivelyEnabled: (id) =>
id === 'satellites' ? satellitesOn : id === 'rocket-launches',
setLayerParams: (id, params) => calls.push(['params', id, params]),
async setEnabled(id, enabled) {
calls.push(['enabled', id, enabled]);
satellitesOn = enabled;
return true;
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: {
enabled: enabledBefore,
params: { mode: 'before' },
},
_satelliteActivationPromise: null,
};
const parts = {
policyHelpers: { satelliteParamsAfterSpaceMissions: (params) => params },
};
const ingestion = createIngestion({ state, services: {}, parts, source: {} });
parts.satelliteIntents = createSatelliteIntents({ state });
const { methods } = createControls({ state, services: {}, parts });
return { state, calls, ingestion, methods, intents: parts.satelliteIntents };
}
test('an accepted Satellites action keeps its visibility through mission exit', async () => {
const r = satelliteRig({ enabledBefore: false });
// The person turns Satellites on themselves while the missions are on.
r.intents.handleVisibility({
type: 'visibility',
layerId: 'satellites',
enabled: true,
origin: 'user',
});
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(
r.calls,
[['params', 'satellites', { mode: 'before' }]],
'the parameters come back, the visibility is left alone',
);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
test('without a Satellites action the exit restores the pre-mission visibility', async () => {
const r = satelliteRig({ enabledBefore: false });
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [
['params', 'satellites', { mode: 'before' }],
['enabled', 'satellites', false],
]);
});
@@ -69,3 +69,38 @@ test('the mission panel translates only the fallback status', (t) => {
assert.equal(shownStatus(UNKNOWN_LAUNCH_STATUS), 'Desconocido');
assert.equal(shownStatus('Launch Successful'), 'Launch Successful');
});
test('a confirmed landing position is worded apart from the CONFIRMED sightings chip', (t) => {
t.after(() => setLocale('en'));
const position = () =>
createPanel({
state: {
_selectedLaunchId: 'mission-1',
_launches: [
{
id: 'mission-1',
name: 'Example',
status: 'Launch Successful',
payloads: [],
recoveryStages: [
{
name: 'B1080',
endpoint: { lat: 28.41, lon: -80.6, accuracy: 'CONFIRMED' },
},
],
},
],
_replayTracks: new Map(),
},
parts: {
overlays: { shortMissionLabel: (name) => name },
policyHelpers: { missionPathPresentation: () => ({}) },
replay: { presentReplay: () => ({}) },
},
}).presentMission().stages[0].position;
assert.match(position(), / · CONFIRMED$/);
// One landing, singular: sv BEKRÄFTAD, where the sightings chip says
// BEKRÄFTADE.
setLocale('sv');
assert.match(position(), / · BEKRÄFTAD$/);
});
+1 -1
View File
@@ -135,7 +135,7 @@ export function createOverlays({ state: layerState, services, parts, source }) {
protected: selected,
paintLane: selected ? 'selected' : 'ambient-label',
collisionGroup: 'ambient-label',
interactive: false,
interactive: true,
distanceScale: {
near: 1000,
nearValue: 1.08,
+3
View File
@@ -2,6 +2,9 @@ import { TWO_PI, toRadians } from '../../geo/vector.js';
export const WINDOW_DAYS = 30;
/** Longest Space Missions waits for pending Satellites work to settle. */
export const SATELLITE_SETTLE_TIMEOUT_MS = 30000;
export const ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID = 'rocket-missions';
export const ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID =
+2
View File
@@ -336,6 +336,8 @@ export function createReplay({ state: layerState, services, parts, source }) {
// The chase camera moves on the frame loop; without one, no replay.
const frame = findFrame(layerState._viewer);
if (!layerState._viewer || !launch || !track || !frame) return false;
// Not while the layer is going off.
if (!layerState._enabled) return false;
if (layerState._replayCameraLaunchId === launchId) {
stopMissionReplay();
return false;
+126
View File
@@ -0,0 +1,126 @@
/**
* Space Missions owns its Satellites dependency. While the layer is on or
* starting, an explicit Satellites action from the person (a Data Layers
* click, a voice command) wins over the dependency:
* - the mission teardown leaves Satellites as that action set it, and
* - a Satellites OFF asked for after the newest Space Missions ON ends Space
* Missions, which cannot replay without it.
* Whether an OFF ends the missions depends on which of the two was asked for
* first, not on which settles first, so request order is recorded when each
* intent is published.
*/
const ORDERED_REQUEST_LAYER_IDS = new Set(['rocket-launches', 'satellites']);
const LAYER_ID = 'rocket-launches';
function isExplicitOrigin(origin) {
return origin === 'user' || origin === 'voice';
}
export function createSatelliteIntents({ state: layerState }) {
const requestOrder = new Map();
let sequence = 0;
let unsubscribe = null;
/** The Space Missions stop a Satellites OFF started, while it runs. */
let pendingStop = null;
/**
* Whether an accepted Satellites OFF was requested after the newest Space
* Missions ON. An OFF asked for before the entry belongs to the view the
* entry started from, so the entry it races with is kept. Without request
* records the OFF is treated as the newer action.
*/
function offFollowsMissionsEntry(change) {
const satellites = requestOrder.get('satellites');
const missions = requestOrder.get(LAYER_ID);
if (satellites?.intentEpoch !== change.intentEpoch || !missions?.enabled)
return true;
return satellites.sequence > missions.sequence;
}
function recordRequest(change) {
if (!ORDERED_REQUEST_LAYER_IDS.has(change?.layerId)) return;
requestOrder.set(change.layerId, {
enabled: change.enabled,
intentEpoch: change.intentEpoch,
sequence: ++sequence,
});
}
/**
* Hand an explicit Satellites action its visibility while Space Missions is
* on or starting.
* @returns {Promise<boolean>|boolean} Whether Space Missions was asked to stop.
*/
function handleVisibility(change) {
const manager = layerState._dataManager;
if (
!manager ||
change?.type !== 'visibility' ||
change.layerId !== 'satellites' ||
!isExplicitOrigin(change.origin)
)
return false;
const missionsRequested = manager.isEffectivelyEnabled(LAYER_ID);
if (!missionsRequested && !layerState._satelliteStateBeforeMission)
return false;
// A newer Satellites request is queued; it will report for itself.
if (manager.isEffectivelyEnabled('satellites') !== change.enabled)
return false;
// The person's choice survives the mission teardown.
const previous = layerState._satelliteStateBeforeMission;
if (previous) previous.restoreVisibility = false;
if (
change.enabled ||
!missionsRequested ||
!offFollowsMissionsEntry(change)
)
return false;
const stop = Promise.resolve(
manager.setEnabled(LAYER_ID, false, { origin: change.origin }),
)
.then(() => true)
.catch((error) => {
console.warn(
'[Data:RocketLaunches] Satellites OFF could not stop Space Missions',
error,
);
return false;
})
.finally(() => {
if (pendingStop === stop) pendingStop = null;
});
pendingStop = stop;
return stop;
}
/** Settle once a Satellites OFF has finished stopping Space Missions. */
function settled() {
return pendingStop ?? Promise.resolve(false);
}
/** Follow the manager the layer is attached to; null detaches. */
function connect(manager) {
unsubscribe?.();
unsubscribe = null;
requestOrder.clear();
if (!manager) return;
const unsubscribeRequests =
manager.subscribeVisibilityRequests?.(recordRequest) ?? null;
const unsubscribeChanges =
manager.subscribe?.((change) => {
void handleVisibility(change);
}) ?? null;
unsubscribe = () => {
unsubscribeRequests?.();
unsubscribeChanges?.();
};
}
return {
connect,
settled,
handleVisibility,
recordRequest,
offFollowsMissionsEntry,
};
}
@@ -0,0 +1,167 @@
// An explicit Satellites action while Space Missions is on or starting.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSatelliteIntents } from './satelliteIntents.js';
/** A manager whose effective and settled state can differ. */
function rig({ effective, snapshot = { enabled: false } } = {}) {
const calls = [];
const listeners = { requests: new Set(), changes: new Set() };
const manager = {
isEffectivelyEnabled: (id) => Boolean(effective[id]),
async setEnabled(id, enabled, options) {
calls.push([id, enabled, options?.origin]);
return true;
},
subscribeVisibilityRequests(listener) {
listeners.requests.add(listener);
return () => listeners.requests.delete(listener);
},
subscribe(listener) {
listeners.changes.add(listener);
return () => listeners.changes.delete(listener);
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: snapshot,
};
const intents = createSatelliteIntents({ state });
intents.connect(manager);
const request = (layerId, enabled, intentEpoch) => {
for (const listener of listeners.requests)
listener({
type: 'visibility-requested',
layerId,
enabled,
intentEpoch,
});
};
const settle = (change) => {
for (const listener of listeners.changes) listener(change);
};
return { calls, intents, listeners, manager, state, request, settle };
}
const satellitesOff = {
type: 'visibility',
layerId: 'satellites',
enabled: false,
origin: 'user',
intentEpoch: 7,
};
test('a Satellites OFF asked for after the mission start ends Space Missions', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('rocket-launches', true, 3);
r.request('satellites', false, 7);
r.settle(satellitesOff);
assert.equal(await r.intents.settled(), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
false,
'the teardown leaves Satellites as the person set it',
);
});
test('a Satellites OFF asked for before the mission start leaves the start alone', () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('satellites', false, 7);
r.request('rocket-launches', true, 3);
r.settle(satellitesOff);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('a Satellites OFF without request records is treated as the newer action', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
assert.equal(await r.intents.handleVisibility(satellitesOff), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
});
test('a superseded Satellites event is left to the newer request', () => {
// A newer Satellites ON is queued, but this OFF has already settled.
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
});
test('a Satellites ON while the missions are on is kept through their exit', () => {
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, enabled: true }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('only direct user and voice Satellites actions count', () => {
// Settled: a scene, story, preset or other programmatic Satellites OFF
// neither ends Space Missions nor survives its teardown.
for (const origin of [
'programmatic',
'context-restore',
'dependency',
'scene',
'tool',
]) {
const r = rig({
effective: { satellites: false, 'rocket-launches': true },
});
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, origin }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
}
const voice = rig({
effective: { satellites: false, 'rocket-launches': true },
});
voice.settle({ ...satellitesOff, origin: 'voice' });
assert.deepEqual(voice.calls, [['rocket-launches', false, 'voice']]);
});
test('with Space Missions off, a Satellites action is not its business', () => {
const r = rig({ effective: { satellites: false }, snapshot: null });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
});
test('reconnecting and detaching release each manager subscription', () => {
const r = rig({ effective: {} });
assert.equal(r.listeners.requests.size, 1);
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(r.manager);
assert.equal(r.listeners.requests.size, 1, 'no duplicate subscription');
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(null);
assert.equal(r.listeners.requests.size, 0);
assert.equal(r.listeners.changes.size, 0);
});
test('a failed stop is reported, not thrown', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.manager.setEnabled = async () => {
throw new Error('injected stop failure');
};
const warn = console.warn;
const warnings = [];
console.warn = (...args) => warnings.push(args);
try {
assert.equal(await r.intents.handleVisibility(satellitesOff), false);
} finally {
console.warn = warn;
}
assert.equal(warnings.length, 1);
assert.equal(await r.intents.settled(), false, 'nothing left pending');
});
+5 -2
View File
@@ -66,6 +66,9 @@ export function createSelection({
}
function setSelectedMission(launchId, isolate = true) {
// Once the layer is going off (its Satellites restore may still be
// running) a roster click selects nothing and moves no camera.
if (launchId && !layerState._enabled) return;
if (launchId) parts.panel.clearMissionRosterHover();
if (
layerState._replayCameraLaunchId &&
@@ -118,7 +121,7 @@ export function createSelection({
}
function focusMission(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
const camera = cameraOf(layerState._viewer);
@@ -163,7 +166,7 @@ export function createSelection({
}
function focusLaunchSite(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
parts.replay.stopMissionReplay();
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
+5 -2
View File
@@ -1,4 +1,5 @@
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
import { SATELLITE_SETTLE_TIMEOUT_MS } from './policy.js';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
@@ -20,8 +21,6 @@ export function createState({ services }) {
state._lastError = null;
state._lastErrorAt = null;
state._entryCameraView = null;
state._entryLandedView = null;
@@ -53,6 +52,9 @@ export function createState({ services }) {
state._lifecycleToken = 0;
/** Bound on waiting for pending Satellites work around a mission. */
state.satelliteSettleTimeoutMs = SATELLITE_SETTLE_TIMEOUT_MS;
state._enabled = false;
state._selectedLaunchId = null;
@@ -68,6 +70,7 @@ export function createState({ services }) {
state._missionPanelSignature = null;
state._missionPanelListeners = new Set();
state._globePickListeners = new Set();
state._missionRosterView = null;
+2 -1
View File
@@ -24,7 +24,8 @@ export function localAdsbClass(record, meta = null) {
const category = record?.category || null;
return {
klass: classifyAircraft({ typeCode, category }),
evidence: Boolean(typeCode) || /^(?:A[1-7]|B1)$/.test(category || ''),
evidence:
Boolean(typeCode) || /^(?:A[1-7]|B1|C[1-5])$/.test(category || ''),
};
}
+29 -10
View File
@@ -1,5 +1,7 @@
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
courseScreenRotation,
stabilizeScreenRotation,
@@ -133,6 +135,8 @@ export function createLocalAdsbLayer({
} = services.context;
const { registerPickOwner, unregisterPickOwner } = services.picking;
const color = hexColor(LOCAL_ADSB_COLOR);
// An airport vehicle's tint, as in the Flights layer.
const vehicleColor = hexColor(VEHICLE_TINT_CSS);
const uatRingColor = hexColor(LOCAL_ADSB_UAT_RING_COLOR);
let viewer = null;
@@ -265,9 +269,7 @@ export function createLocalAdsbLayer({
}
function billboardScale(marker) {
return (
(CLASS_SCALE_2D[marker.klass] || 1) * (marker.onGround ? GROUND_SCALE : 1)
);
return marker.onGround ? GROUND_SCALE : 1;
}
/** Class silhouette and per-class scale (×0.8 on the ground), magenta. */
@@ -350,18 +352,34 @@ export function createLocalAdsbLayer({
};
}
/** A marker's icon, where and how it now draws. */
function markerItem(marker, basis) {
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
return {
id: marker.id,
pos: marker.position,
image: aircraftIcon(marker.iconKind ?? 'airliner'),
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
rotationMode: 'screen',
rotation: markerRotation(marker, basis),
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -390,11 +408,12 @@ export function createLocalAdsbLayer({
function drawMarkers() {
if (!sets) return;
const basis = cameraBasis();
const at = now();
const icons = [];
const rings = [];
for (const marker of markers.values()) {
if (!marker.position) continue;
icons.push(markerItem(marker, basis));
icons.push(markerItem(marker, basis, at));
if (marker.uat) rings.push(ringItem(marker));
}
if (icons.length) sets.markers.upsert(icons);
+49 -8
View File
@@ -2,9 +2,10 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { layerFeedState } from '../../data/feedState.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import { ROTOR_STILL_FRAME, rotorFrame } from '../../data/rotorFrames.js';
import {
createLocalAdsbLayer,
HEARD_BY_RECEIVER,
@@ -200,13 +201,14 @@ function fakeFeeds(initial = {}) {
};
}
/** A viewer whose camera looks down on (0°, 0°) from 50 km. */
/** A viewer whose camera looks down on (0°, 0°) from 2 km: within the 3 km
* model radius of an aircraft there on the ground or at 10,000 ft. */
function modelViewer() {
return fakeViewer(
{ scene: {} },
{
height: 50_000,
position: { x: 6_378_137 + 50_000, y: 0, z: 0 },
height: 2_000,
position: { x: 6_378_137 + 2_000, y: 0, z: 0 },
direction: { x: -1, y: 0, z: 0 },
},
);
@@ -242,7 +244,7 @@ test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves
);
});
test('local aircraft use their class silhouette and scale in magenta', async (t) => {
test('local aircraft use their class silhouette at one size in magenta', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, draw, calls } = await enabledLayer(receiver, clock);
@@ -269,8 +271,17 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
assert.equal(typeof readEntityRecord(carrier)?.displayPosition, 'function');
const heli = () => iconOf(draw, 'local-adsb:a0b702');
assert.equal(heli().image, aircraftIcon('helicopter'));
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter);
// Airborne, its rotor turns: the frame of its own phase at the layer's time.
assert.equal(
heli().image,
aircraftIcon(
'helicopter',
undefined,
rotorFrame('local-adsb:a0b702', clock.now),
),
);
assert.equal(heli().scale, 1, 'every class draws at one size');
assert.equal(icon.scale, heli().scale);
assert.deepEqual(
heli().color,
MAGENTA,
@@ -289,18 +300,48 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
icao: 'a0b702',
category: 'A7',
onGround: true,
groundSpeedKt: 0,
lastPositionAt: 100_500,
}),
],
});
await layer.update();
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter * 0.8);
assert.equal(heli().scale, 0.8);
// Parked on the ground its rotor holds still.
assert.equal(
heli().image,
aircraftIcon('helicopter', undefined, ROTOR_STILL_FRAME),
);
const [detectable] = layer.getDetectableObjects();
assert.equal(detectable.sourceId, 'a0b702');
assert.equal(detectable.type, 'AIR');
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, draw } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
receiver.set({
aircraft: [
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c002', category: 'C2', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
for (const id of ['a0c001', 'a0c002']) {
const icon = iconOf(draw, `local-adsb:${id}`);
assert.equal(icon.image, aircraftIcon('vehicle'), id);
assert.deepEqual(icon.color, hexColor(VEHICLE_TINT_CSS), id);
}
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.deepEqual(mast.color, MAGENTA);
assert.equal(mast.rotation, 0, 'upright whatever its track');
});
test('the heading slews toward a new track instead of snapping', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+43 -11
View File
@@ -8,18 +8,21 @@ import {
sub,
} from '../../geo/vector.js';
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js';
import {
fleetModelSet,
fleetPartTable,
loadFleetModelSet,
} from '../../data/fleetModels.js';
import { aircraftLayerPartState } from '../../data/modelPartDrivers.js';
import { KNOT_MPS } from '../../data/units.js';
import {
FLEET_DR_INTERVAL_MS,
MODEL_ALL_ADD_M,
MODEL_ALL_KEEP_M,
MODEL_ADD_M,
MODEL_ALT_CEIL_M,
MODEL_HEADING_OFFSET_DEG,
MODEL_KEEP_M,
MODEL_MAX,
MODEL_MAX_ALL,
MODEL_MIN_PX,
MODEL_PROX_ADD_M,
MODEL_PROX_KEEP_M,
} from '../flights/policy.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
@@ -165,6 +168,36 @@ export function createLocalAdsbModels({
}
}
/**
* The moving parts an aircraft's model is posed with, from its record
* (`aircraftLayerPartState`). The receiver knows no ground height, so its gear
* follows the approach rule by its reported altitude, climb and speed. An
* airport vehicle is a road vehicle (`groundVehiclePartState`): its wheels
* roll with its speed.
*/
function partsOf(marker, spec) {
const table = fleetPartTable(fleetModelSet(), spec.model);
if (!table) return undefined;
const record = marker.record ?? {};
const finite = (v) => (Number.isFinite(v) ? v : null);
const speedMps =
finite(record.groundSpeedKt) === null
? null
: record.groundSpeedKt * KNOT_MPS;
return aircraftLayerPartState(table, {
klass: marker.klass,
onGround: marker.onGround === true,
heightAboveGroundM: null,
altitudeM:
finite(record.altitudeFt) === null ? null : record.altitudeFt * 0.3048,
verticalRateMps:
finite(record.verticalRateFpm) === null
? null
: (record.verticalRateFpm * 0.3048) / 60,
speedMps,
});
}
function regime(preferences, pose) {
if (!preferences?.models3d) return false;
return pose.height < MODEL_ALT_CEIL_M;
@@ -173,19 +206,17 @@ export function createLocalAdsbModels({
function refreshEligibility(markers, preferences, pose) {
const all = preferences.models3dMode === 'all';
const cap = all ? MODEL_MAX_ALL : MODEL_MAX;
const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M;
const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M;
const candidates = [];
for (const [id, marker] of markers) {
if (!marker.position) continue;
const distanceSq = distanceSquared(pose.position, marker.position);
if (distanceSq > keepM * keepM) continue;
if (distanceSq > MODEL_KEEP_M * MODEL_KEEP_M) continue;
candidates.push([id, distanceSq, inView(pose, marker.position)]);
}
candidates.sort((a, b) => a[1] - b[1]);
eligible = selectModelEligible(candidates, {
cap,
addDistSq: addM * addM,
addDistSq: MODEL_ADD_M * MODEL_ADD_M,
isModeled: (id) => models.has(id),
});
release([...models.keys()].filter((id) => !eligible.has(id)));
@@ -246,6 +277,7 @@ export function createLocalAdsbModels({
const gltf = fleetModelSet()?.bytes?.get(spec.model);
noteAsset(record, url, spec.bellyM);
const position = placement(id, marker);
const parts = partsOf(marker, spec);
const shown =
Boolean(position) && horizon.isPointVisible(marker.position);
items.push({
@@ -263,11 +295,11 @@ export function createLocalAdsbModels({
roll: 0,
},
scale: spec.scale,
minPixelSize: MODEL_MIN_PX,
// The mesh's own colours (white, multiplied).
tint: WHITE,
colorBlend: aircraftModelBlend(false),
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
...(parts ? { parts } : {}),
show: shown,
});
if (shown && record.ready) marker.modelOwnsVisual = true;
+54 -1
View File
@@ -26,6 +26,59 @@ export function createClockFollow({ flightState, services, parts }) {
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._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)
@@ -39,5 +92,5 @@ export function createClockFollow({ flightState, services, parts }) {
flightState.feed._lastUpdate = null;
}
return { resetMotion, clear };
return { resetMotion, absentAtHandover, handOverMotion, clear };
}
+14 -4
View File
@@ -10,7 +10,10 @@ import { createLifecycle } from './lifecycle.js';
import { createTesting } from './testing.js';
import { createQueries } from './queries.js';
import { createClockFollow } from './clockFollow.js';
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
import {
createSnapshotTimeline,
snapshotAnswer,
} from '../../time/snapshotTimeline.js';
import { worldClock } from '../../time/worldClock.js';
/** Compose one military-flight layer with application-owned scene services. */
export function createMilitaryFlightLayer({
@@ -46,10 +49,19 @@ export function createMilitaryFlightLayer({
parts.ingestion = createIngestion({
feed: flightState.feed,
applySnapshot: (snapshot, viewer, options) => {
// At another time the snapshot takes the place of every contact: how
// each moved belongs to the time the clock left. Back at live too, but
// the contacts it lacks are kept as they were for it to judge.
if (options?.replace) parts.clockFollow.resetMotion();
if (options?.handover) {
parts.clockFollow.handOverMotion(
parts.clockFollow.absentAtHandover(snapshot),
);
}
return applySnapshot(snapshot, viewer, options);
},
followsClock: () => flightState.timeline.active(),
timedAnswer: snapshotAnswer,
setSourceLabel: (source) => {
layer.source = source;
},
@@ -65,9 +77,7 @@ export function createMilitaryFlightLayer({
load: (atMs, { signal, replace }) =>
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
clear: () => parts.clockFollow.clear(),
resumeLive: () => {
layer.update(flightState._viewer).catch(() => {});
},
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
});
Object.assign(
+26 -5
View File
@@ -11,6 +11,7 @@ export function createIngestion({
setSourceLabel,
applyPendingTrackingRestore,
followsClock = () => false,
timedAnswer = () => true,
}) {
const methods = {
async update(viewer, { signal = null } = {}) {
@@ -20,13 +21,27 @@ export function createIngestion({
await acquire(viewer, { signal });
},
/**
* Back at live from another time: poll at once, and let this live
* snapshot stand in for every contact. Those it has keep their
* icon and model and move on from where they are drawn; those it lacks
* go. Resolves true once it is applied, else false (nothing to poll yet,
* or the poll failed); rejects with an AbortError when it was dropped.
* @param {object} [viewer]
* @returns {Promise<boolean>}
*/
async resumeLive(viewer) {
return (await acquire(viewer, { handover: true })) === true;
},
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every contact when `replace`. Resolves
* whether it was applied.
* whether it was applied: `{ reachMs }`, the newest fix its records
* carry, when they carry fixes; else true, or false when it was not.
* @param {number} atMs
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
* @returns {Promise<boolean>}
* @returns {Promise<boolean|{reachMs: number}>}
*/
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
// Whatever polls or loads for another time no longer applies.
@@ -37,7 +52,10 @@ export function createIngestion({
},
};
async function acquire(viewer, { signal = null, atMs, replace = false }) {
async function acquire(
viewer,
{ signal = null, atMs, replace = false, handover = false },
) {
const nowMs = Date.now();
const timed = atMs !== undefined;
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
@@ -77,7 +95,9 @@ export function createIngestion({
: null);
const accepted = timed
? applySnapshot(snapshot, viewer, { replace })
: applySnapshot(snapshot, viewer);
: handover
? applySnapshot(snapshot, viewer, { handover: true })
: applySnapshot(snapshot, viewer);
feed._count = accepted.count;
feed._lastUpdate = snapshot.observedAtMs;
feed._lastTrackingRefreshOutcome = {
@@ -88,7 +108,8 @@ export function createIngestion({
};
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
return true;
// At a time, what the clock's follower is told of it.
return timed ? timedAnswer(snapshot) : true;
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Military update aborted', 'AbortError');
+180
View File
@@ -0,0 +1,180 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createMilitarySnapshotRenderer } from './snapshotRenderer.js';
import { createMotion } from './motion.js';
import { createIngestion, createMilitaryFeed } from './ingestion.js';
import { MilitaryFlightRecords } from './records.js';
import { createClockFollow } from './clockFollow.js';
// Back at live from another time, the first live snapshot stands in for
// every military contact: those it has keep their icon, and only those it
// lacks go (src/time/snapshotTimeline.js).
function harness() {
const iconIds = new Set();
const calls = [];
const flightState = {
_viewer: null,
_icons: {
has: (id) => iconIds.has(id),
ids: () => [...iconIds],
get count() {
return iconIds.size;
},
},
_positionHistory: new Map(),
_groundSnap: { forget() {} },
_models: new Map(),
_trackedModel: null,
_trackedIcao: null,
records: { data: new Map() },
};
const parts = {
rendering: {
_modelOwnsVisual: () => false,
_syncModelToClass() {},
_groundSampleExclusions: () => ({ sets: [] }),
},
icons: {
_addIcon: (id) => {
calls.push(['add', id]);
iconIds.add(id);
},
_applyIconPresentation() {},
_planIcon: (id, options) => calls.push(['plan', id, options]),
_forgetContact: (id) => {
calls.push(['forget', id]);
iconIds.delete(id);
},
},
};
const services = {
camera: { trackedModelScaleForPixelCap: () => 1 },
focus: {},
groundFloor: { cachedGroundFloor: () => null, GROUND_FLOOR_LIFT_M: 0.5 },
meshFloor: { sampleMeshFloorCells() {} },
};
parts.motion = createMotion({ flightState, services, parts, layer: {} });
const records = new MilitaryFlightRecords({
geoidHeight: () => 0,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
now: () => Date.now(),
});
flightState.records = records;
flightState.now = () => Date.now();
flightState._displayCourse = new Map();
flightState._groundSnap.clear = () => {};
const apply = createMilitarySnapshotRenderer({
flightState,
records,
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
militaryRegistry: { registerMilitaryIcaos() {} },
rendering: parts.rendering,
tracking: {},
motion: parts.motion,
icons: parts.icons,
queries: { _likelyLanded: () => false },
});
const clockFollow = createClockFollow({
flightState,
services: { placement: null },
parts: { tracking: { _clearTrail() {} } },
});
// `ids`: an id, or [id, fix age ms].
const snapshot = (ids, fields) => ({
observedAtMs: Date.now(),
records: ids.map((entry, k) => {
const [id, ageMs = 5_000] = [entry].flat();
return {
id,
reference: id,
longitude: -97 + k,
latitude: 30,
baroAltitudeM: 3_000,
onGround: false,
speedMps: 200,
courseDeg: 90,
positionTimeMs: Date.now() - ageMs,
};
}),
complete: true,
...fields,
});
return {
calls,
iconIds,
apply(ids, options, fields) {
calls.length = 0;
return apply(snapshot(ids, fields), null, options);
},
// Back at live, as the layer applies its first live snapshot.
handOver(ids, fields) {
calls.length = 0;
const live = snapshot(ids, fields);
clockFollow.handOverMotion(clockFollow.absentAtHandover(live));
return apply(live, null, { handover: true });
},
};
}
test('the first live military snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
const h = harness();
h.apply(['ae0001', 'ae0002']);
h.handOver(['ae0001', 'ae0003']);
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
assert.equal(
h.calls.some(
([kind, id]) => id === 'ae0001' && (kind === 'add' || kind === 'forget'),
),
false,
);
assert.deepEqual(
h.calls.find(([kind, id]) => kind === 'plan' && id === 'ae0001'),
['plan', 'ae0001', { handover: true }],
);
// A plain poll keeps a missing contact as its absence rules say.
h.apply(['ae0001']);
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
});
test('back at live, only the first live military snapshot applied takes over; a failed poll says so', async () => {
const applied = [];
let fail = false;
const feed = createMilitaryFeed({
async getSnapshot() {
if (fail) throw new Error('down');
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
},
});
const { methods } = createIngestion({
feed,
applySnapshot: (_snapshot, _viewer, options) => {
applied.push(options);
return { count: 0, ids: new Set() };
},
setSourceLabel: () => {},
applyPendingTrackingRestore: () => {},
});
assert.equal(await methods.resumeLive(null), true);
await methods.update(null);
assert.deepEqual(applied, [{ handover: true }, undefined]);
fail = true;
const warn = console.warn;
console.warn = () => {};
try {
assert.equal(await methods.resumeLive(null), false);
} finally {
console.warn = warn;
}
});
test('back at live, a partial military snapshot keeps only contacts whose newest fix is recent', () => {
const h = harness();
h.apply([
['ae0001', 3 * 3_600_000],
['ae0002', 60_000],
]);
h.handOver(['ae0003'], { complete: false });
assert.deepEqual([...h.iconIds].sort(), ['ae0002', 'ae0003']);
});
+18 -11
View File
@@ -35,7 +35,6 @@ import {
recoveryMs,
limitCourseStep,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from '../flights/placed.js';
import {
modelVisualAnchor,
@@ -44,7 +43,6 @@ import {
import {
displayDelayMs,
followsClock,
MODEL_MIN_PX,
BILLBOARD_SCALE,
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
DR_CORRECTION_MS,
@@ -312,20 +310,17 @@ export function createMotion({
const spec = parts.rendering._modelSpec(
flightState.records.data.get(icao24),
);
// Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX.
// Drawn as the fleet draws it: at its true size.
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
const projectedDiameterPx =
(2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM;
return Math.max(MODEL_MIN_PX, projectedDiameterPx);
return projectedDiameterPx;
}
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
const width = sprite?.width ?? 28;
const height = sprite?.height ?? 28;
const scale =
sprite?.scale ??
BILLBOARD_SCALE *
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
const scale = sprite?.scale ?? BILLBOARD_SCALE;
const scaleByDistance =
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
@@ -354,6 +349,8 @@ export function createMotion({
const sameTrack =
flightState._drReconcileValid && flightState._drReconcileIcao === icao24;
const raw = _deadReckon(icao24, flightState._scratchDrRaw);
flightState._cachedDRPlaced =
Boolean(raw) && flightState._drSpeedPlaced === true;
flightState._cachedDRCourse = flightState._drCourseDeg;
flightState._cachedDRSpeedMps = flightState._drSpeedMps;
flightState._cachedDRHold = flightState._drCourseHold;
@@ -480,6 +477,16 @@ export function createMotion({
* later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the
* now-stable plane. Null when no valid fix (callers fall back to the icon position). */
/** Whether a host-supplied placement placed the tracked aircraft where
* `_trackedDisplayCached` holds it this frame, rather than this layer's
* own motion at its display delay. */
function _trackedPlaced() {
return (
_trackedDisplayCached() !== null && flightState._cachedDRPlaced === true
);
}
function _trackedDisplayCached() {
return flightState._drReconcileValid &&
flightState._drReconcileIcao === flightState._trackedIcao
@@ -515,9 +522,8 @@ export function createMotion({
}
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
* contact is drawing. Carries the scale it is drawn at, which may be
* above `scale` to satisfy its pixel floor — the trail head has to be judged
* against the size the operator SEES, not the nominal one. */
* contact is drawing, at the scale it is drawn at — the trail head has to
* be judged against the size the operator SEES. */
/** World-space origin of the tracked model, or null when no model of this
* contact is drawing. This is the centre the rendered bounding sphere is
* measured from, so the trail clip and the envelope agree on one frame. */
@@ -703,6 +709,7 @@ export function createMotion({
_trackedFocusSizePx,
_trackedDisplayPosition,
_trackedDisplayCached,
_trackedPlaced,
_trackedVisualCached,
_trackedModelCenterWorld,
_trackedModelEnvelopeM,
+27 -34
View File
@@ -31,10 +31,6 @@ export const BILLBOARD_SCALE = 0.7;
export const MIL_ICON_COLOR = rgba('#FFB800');
/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */
export const TRACKED_ICON_COLOR = rgba('#FFD166');
/** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */
export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
@@ -61,21 +57,26 @@ export const MODEL_WHITE = rgba('#FFFFFF');
export const GROUND_SCALE = 0.8;
// --- 3D model rendering (mirrors flights.js) -----------------------------------------
// When enabled, military aircraft render as 3D glTF models once the camera is below
// MODEL_ALT_CEIL_M (zoomed in); higher up they stay flat billboards. Eligibility is
// FRUSTUM-based (on-screen), and the slots go to either the nearest planes ('proximity')
// or every in-view plane ('all'), each backed by a hard cap so a draw-call explosion
// can't tank the frame (no instancing yet). Each aircraft draws the fleet model of its
// type, as the flights layer does; the amber tint sets this layer apart.
// When enabled, a military aircraft draws as its 3D glTF model only within MODEL_ADD_M of the
// camera (eye to aircraft); farther away it stays its icon. Models are drawn at their true size,
// with no minimum pixel size. Eligibility is distance-based with on-screen priority, and the slots
// go to either the nearest planes ('proximity') or every in-range plane ('all'): the two modes share
// the radius and differ by their caps. Each aircraft draws the fleet model of its type, as the
// flights layer does; the amber tint sets this layer apart.
export const MODEL_ALT_CEIL_M = 800000;
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
export const MODEL_ADD_M = 3000;
// model NEW planes within 3 km of the camera (mirror of flights.js)
export const MODEL_MIN_PX = 24;
// floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js)
export const MODEL_KEEP_M = 3600;
// KEEP modeled planes out to 3.6 km (hysteresis, mirror of flights.js)
// Per-mode caps + radii — mirror of flights.js. Modes differ by RADIUS (not just cap) so Proximity
// and All aren't identical when few planes are in range; on-screen planes win the cap (see flights.js).
export const MODEL_HIGHEST_CONTACT_M = 30000;
// m above the ellipsoid: no aircraft the layer draws flies higher (mirror of flights.js)
export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M;
// m: above this camera altitude no contact can be within MODEL_KEEP_M (mirror of flights.js)
// Per-mode caps — mirror of flights.js; on-screen planes win the cap (see flights.js).
export const MODEL_MAX = 150;
// 'proximity' cap
@@ -83,32 +84,24 @@ export const MODEL_MAX = 150;
export const MODEL_MAX_ALL = 350;
// 'all' cap
export const MODEL_PROX_ADD_M = 150000;
// proximity: model NEW planes within 150 km
export const MODEL_PROX_KEEP_M = 185000;
// proximity: KEEP modeled planes out to 185 km
// Cockpit keeps the standard Display radii but lowers the GLB budget. Contacts
// inside the selected band remain AIR silhouettes when they cannot own a model;
// contacts outside the band use compact dots.
export const COCKPIT_MODEL_MAX = 60;
// max concurrent GLBs in cockpit (never raises the map cap)
export const MODEL_ALL_ADD_M = 400000;
// all: model NEW planes within 400 km (~to the horizon)
// Cockpit's AIR band (mirror of flights.js): contacts inside it remain AIR
// silhouettes when they cannot own a model; contacts outside it use compact
// dots. Independent of the 3D model radius.
export const MODEL_ALL_KEEP_M = 450000;
// all: KEEP modeled planes out to 450 km
export const COCKPIT_AIR_PROX_ADD_M = 150000;
export const COCKPIT_AIR_PROX_KEEP_M = 185000;
export const COCKPIT_AIR_ALL_ADD_M = 400000;
export const COCKPIT_AIR_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite Cesium heading 0
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
export const AMBER_TRANSPARENT = rgba('#FFB800', 0);
export const COCKPIT_CONTACT_SIZE_PX = 6;
/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */
+5 -4
View File
@@ -109,6 +109,7 @@ export function createQueries({
derivedSpeedMps: flightState._drSpeedMps,
derivedTrackDeg: flightState._drCourseDeg,
reportedSpeedMps: info?.speedMps,
derivedFromPlacement: flightState._drSpeedPlaced === true,
reportedTrackDeg: info?.track,
});
const carto = toLonLatH(basePos);
@@ -249,11 +250,11 @@ export function createQueries({
/**
* Live layer params.
* `models3d` toggles 3D glTF jet-model rendering for the FLEET (altitude-gated): when on,
* surrounding military aircraft become 3D models once the camera is zoomed in past
* MODEL_ALT_CEIL_M. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`),
* `models3d` toggles 3D glTF jet-model rendering for the FLEET: when on, military
* aircraft within MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true
* size. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`),
* so selecting a contact never turns its icon into a model or its model into an icon.
* `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane).
* `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius.
* @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedMilitaryTrackingId?: string|null}} params
*/
setParams(params = {}, { origin = 'programmatic' } = {}) {
+4 -11
View File
@@ -1,4 +1,3 @@
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
aircraftLayerModelSpec,
aircraftModelSpecCacheKey,
@@ -9,7 +8,6 @@ import {
BILLBOARD_SCALE,
GROUND_SCALE,
MIL_ICON_COLOR,
TRACKED_ICON_COLOR,
EMERGENCY_ICON_COLOR,
MODEL_WHITE,
} from './policy.js';
@@ -41,15 +39,11 @@ export function createRendering({
return spec;
}
/** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */
/** Fleet icon scale: one size for every class, ×GROUND_SCALE while grounded. */
function _fleetBillboardScale(icao24) {
const meta = flightState.records.data.get(icao24);
return (
BILLBOARD_SCALE *
(CLASS_SCALE_2D[meta?.klass] || 1) *
(meta?.onGround ? GROUND_SCALE : 1)
);
return BILLBOARD_SCALE * (meta?.onGround ? GROUND_SCALE : 1);
}
/** Sprite kind for one contact's icon. Identity for every aircraft except
@@ -61,11 +55,10 @@ export function createRendering({
const _iconKind = (icao24, klass) =>
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
/** Model colour: the mesh's own (white), tinted amber while tracked and red
* while broadcasting an emergency. */
/** Model colour: the mesh's own (white), tinted red while broadcasting an
* emergency. Tracking never recolours it. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return TRACKED_ICON_COLOR;
const info = flightState.records.data.get(icao24);
return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MODEL_WHITE;
}
+38 -10
View File
@@ -55,8 +55,16 @@ export function createMilitarySnapshotRenderer({
/**
* `replace`: the snapshot is the world at another time (the world clock
* jumped), so it stands in for every contact: one it lacks is gone at once.
* `handover`: the first live snapshot after the clock came back to live: it
* stands in for every contact too, and those it has keep their icon and
* model and ease on from where they are drawn; of those it lacks, only
* those absence keeps (judged by their newest fix) stay.
*/
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
return function applySnapshot(
snapshot,
viewer,
{ replace = false, handover = false } = {},
) {
// Before init (or after destroy) there is no icon set to draw into.
if (!flightState._icons) return { count: 0, ids: new Set() };
const currentIcaos = new Set();
@@ -223,7 +231,7 @@ export function createMilitarySnapshotRenderer({
// freshness change and the cockpit contract all land on the row's
// style; motion re-plans from the updated history.
icons._applyIconPresentation(icao24);
icons._planIcon(icao24);
icons._planIcon(icao24, handover ? { handover } : undefined);
// Per-type fleet models: a type or category change can mean a
// different model OR scale — resync the live model, any in-flight
// load, and the tracked standalone (mirror of flights.js).
@@ -279,6 +287,23 @@ export function createMilitarySnapshotRenderer({
// EXCEPTION: likely-landed planes (last fix low + slow) get only
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
// feed gap, and the full grace left phantom planes parked at airports.
// Back at live, a contact it lacks is from the time the clock left: it
// goes at once, unless absence keeps it as any poll would (a partial or
// retaining snapshot, the tracked aircraft), judged by its newest fix.
// No missed-poll grace, and a landed tracked aircraft is not kept.
const absenceAtHandover = (icao24) => {
const likelyLanded = queries._likelyLanded(icao24);
const judged = records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded,
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
nowMs: flightState.now?.(),
});
return judged === 'stale' && icao24 !== flightState._trackedIcao
? 'remove'
: judged;
};
const absentIds = [];
for (const icao24 of flightState._icons.ids()) {
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
@@ -286,13 +311,15 @@ export function createMilitarySnapshotRenderer({
for (const icao24 of absentIds) {
const absence = replace
? 'remove'
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
: handover
? absenceAtHandover(icao24)
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
if (absence === 'retain') continue;
if (absence === 'stale') {
icons._applyIconPresentation(icao24); // the faded freshness alpha
@@ -319,7 +346,8 @@ export function createMilitarySnapshotRenderer({
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
}
// The tracked contact at the new time: its trail starts there.
// The tracked contact at the new time: its trail starts there. Back at
// live its trail goes on.
if (
replace &&
flightState._trackedIcao &&
+12
View File
@@ -230,6 +230,18 @@ export function createFlightState({ source, services }) {
flightState._drSpeedMps = null;
/** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's,
* the speed it is drawn at (0 while it waits for its fixes), for motion
* only; panels show the reported ground speed (`displayedKinematics`). */
flightState._drSpeedPlaced = false;
/** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed
* it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail
* ends where it is drawn rather than at the layer's display delay. */
flightState._cachedDRPlaced = false;
flightState._drCourseHold = false;
/** Set by `_deadReckon`: following the clock, the time drawn is well
+13 -6
View File
@@ -1,4 +1,4 @@
import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js';
import { trackedIconColor } from '../../data/trackedAircraftIcon.js';
import { createModelRecord } from '../../data/modelRecord.js';
import {
aircraftIconTestSeams,
@@ -170,9 +170,11 @@ export function createTesting({
/** Evaluate the production tracked-billboard handoff colour for focused tests. */
function _trackedBillboardColorForTest() {
return parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR;
const icao24 = flightState._trackedIcao;
const color = parts.rendering._fleetBillboardColor(icao24);
return parts.rendering._modelOwnsVisual(icao24)
? trackedIconColor(color, 0)
: color;
}
/** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */
@@ -194,15 +196,20 @@ export function createTesting({
}
/** How the tracked billboard is drawn (`_trackedBillboardLook`,
* `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */
* `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet
* icon is (`_fleetLook`, `_fleetBillboardColor`). */
function _trackedIconLookForTest(icao24) {
return {
tracked: {
...parts.tracking._trackedBillboardLook(),
sprite: parts.tracking._trackedSprite(icao24),
color: parts.tracking._trackedIconColor(),
},
fleet: {
...parts.icons._fleetLook(icao24),
color: parts.rendering._fleetBillboardColor(icao24),
},
fleet: parts.icons._fleetLook(icao24),
};
}
+69 -31
View File
@@ -15,6 +15,7 @@ import {
createTrackedAircraftIcon,
isOtherTrackedIconSet,
trackedContactHolder,
trackedIconColor,
} from '../../data/trackedAircraftIcon.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { julianToEpochMs } from '../../geo/julian.js';
@@ -27,13 +28,15 @@ import {
} from '../../data/trackingClickGesture.js';
import { inputFor } from '../../input/dispatcher.js';
import {
COCKPIT_AIR_ALL_ADD_M,
COCKPIT_AIR_ALL_KEEP_M,
COCKPIT_AIR_PROX_ADD_M,
COCKPIT_AIR_PROX_KEEP_M,
TRAIL_MAX_POINTS,
displayDelayMs,
followsClock,
STALE_ALPHA,
TRAIL_COLOR,
AMBER_TRANSPARENT,
TRACKED_ICON_COLOR,
} from './policy.js';
import {
drawTrailSegments,
@@ -45,6 +48,7 @@ import {
trailBodySegments,
trailHeadCurvePoints,
trailHeadStartFix,
trailTimeAt,
} from '../../data/trailContinuity.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import { entityRecord } from '../../data/entityRecords.js';
@@ -60,11 +64,6 @@ function aircraftPickId(hit) {
return isOtherTrackedIconSet(hit.set, 'military') ? undefined : hit.id;
}
const STALE_TRACKED_COLOR = Object.freeze([
...TRACKED_ICON_COLOR.slice(0, 3),
STALE_ALPHA,
]);
export function createTracking({
flightState,
services,
@@ -213,11 +212,13 @@ export function createTracking({
);
distancesSquared.push([icao24, distanceSquared(eye, position)]);
}
// The AIR band follows the 3D mode, not the 3D model radius.
const all = flightState._models3dMode === 'all';
const next = nextCockpitNearContacts(
previous,
distancesSquared,
parts.rendering._modelAddDistM(),
parts.rendering._modelKeepDistM(),
all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M,
all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M,
);
flightState._cockpitNearContacts = next;
for (const icao24 of previous)
@@ -307,14 +308,18 @@ export function createTracking({
return { text: '', dimmed: false };
}
/** The tracked billboard's colour: amber, faded while stale, clear while the 3D model is the visual. */
/** The tracked billboard's colour: the contact's own fleet colour (tracking
* never recolours it), faded while stale, clear while the 3D model is the
* visual. */
function _trackedIconColor() {
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
return AMBER_TRANSPARENT;
return _trackedStaleCue(flightState._trackedIcao).dimmed
? STALE_TRACKED_COLOR
: TRACKED_ICON_COLOR;
const icao24 = flightState._trackedIcao;
const color = parts.rendering._fleetBillboardColor(icao24);
if (parts.rendering._modelOwnsVisual(icao24))
return trackedIconColor(color, 0);
return _trackedStaleCue(icao24).dimmed
? trackedIconColor(color, STALE_ALPHA)
: color;
}
/**
@@ -405,10 +410,7 @@ export function createTracking({
width: look.size[0],
height: look.size[1],
get scale() {
return parts.rendering._fleetBillboardScale(
icao24,
flightState.records.data.get(icao24)?.klass,
);
return parts.rendering._fleetBillboardScale(icao24);
},
scaleByDistance: look.scaleByDistance,
};
@@ -612,12 +614,46 @@ export function createTracking({
);
}
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
/** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */
function _trailBodyCountNow() {
return trailBodyCount(
return trailBodyCount(flightState._trailFixes, _trailDisplayMs());
}
/**
* The time on its trail at which a host-supplied placement draws the
* aircraft, read off the trail where it is drawn (`trailTimeAt`): such a
* placement draws at a delay of its own, not this layer's. NaN when this
* layer's own motion draws it, or the trail has no pair to read.
* @returns {number} Epoch ms or NaN.
*/
function _placedTrailMs() {
if (!parts.motion._trackedPlaced?.()) return NaN;
return trailTimeAt(
flightState._trailFixes,
flightState.now() - displayDelayMs(flightState),
parts.motion._trackedDisplayCached(),
);
}
/**
* The time the trail runs up to: the time the aircraft is drawn at, now −
* the display delay, or where a placement draws it. Otherwise the trail
* ends short of a placed aircraft, or runs on ahead of it.
* @returns {number} Epoch ms.
*/
function _trailDisplayMs() {
const placedMs = _placedTrailMs();
return Number.isFinite(placedMs)
? placedMs
: flightState.now() - displayDelayMs(flightState);
}
/** Whether the trail holds no report behind the aircraft yet: this
* layer's own motion draws it before its oldest fix. Never for an
* aircraft a placement draws: its trail is read where it is drawn. */
function _trailWarmingUp() {
return (
!Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp()
);
}
@@ -634,7 +670,7 @@ export function createTracking({
if (
!flightState._trackedIcao ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
_trailWarmingUp()
)
return [];
const head =
@@ -662,7 +698,7 @@ export function createTracking({
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
_trailDisplayMs(),
),
end,
parts.motion._trackedModelCenterWorld(),
@@ -927,10 +963,11 @@ export function createTracking({
flightState._trackedIcao = null;
// Hand the contact back to its icon only now, once it no longer reads as
// tracked (the settle plans it as a fleet contact).
if (flightState._icons?.has(clearedIcao)) {
flightState._icons.setShown(clearedIcao, true);
// Its fleet model, kept loaded while it was selected, takes it back in
// this frame; the icon shows only when there is no loaded one.
parts.rendering._handBackDeselected(clearedIcao);
if (flightState._icons?.has(clearedIcao))
parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg });
}
parts.icons._applyIconPresentation(clearedIcao);
clearTrackedSubjectContext('military');
_emitAwarenessEvent('gev:awareness-subject-cleared', {
@@ -1045,14 +1082,13 @@ export function createTracking({
imageLod: _trackedBillboardLook().imageLod,
sprite,
position: getTrackedPosition,
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the tracked model is actually up (ready + shown).
// Amber (faded while stale), transparent once the tracked model is the visual.
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
// street level would otherwise bury the amber icon inside the runway
// street level would otherwise bury the icon inside the runway
// skin, so it draws over depth like the fleet icon set; its
// shared-host tracked card is top-composited separately.
rotation: () => {
@@ -1060,6 +1096,8 @@ export function createTracking({
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
// A ground station's mast stands upright.
if (tracked.klass === 'station') return 0;
const projected = courseScreenRotation(
_pose(),
pos,
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const source = (layer) =>
readFileSync(new URL(`../${layer}/tracking.js`, import.meta.url), 'utf8');
for (const layer of ['military', 'flights']) {
test(`${layer}: a tracked ground station's mast is never turned`, () => {
// The tracked billboard's rotation answers 0 for a station before any
// course is projected on screen.
const rotation = /rotation: \(\) => \{[\s\S]*?courseScreenRotation\(/.exec(
source(layer),
)?.[0];
assert.ok(rotation, 'the tracked billboard turns by a rotation callback');
assert.match(
rotation,
/if \(tracked\.klass === 'station'\) return 0;\s*const projected = courseScreenRotation\(/,
);
});
}
+45 -2
View File
@@ -65,7 +65,15 @@ function recordingTrail() {
};
}
function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
function trackedHarness({
liveFixes = [],
trace = null,
nowMs,
floor,
head,
placed = false,
warmingUp = false,
}) {
const trail = recordingTrail();
const svc = services({ trails: trail, floor });
const flightState = createFlightState({
@@ -104,7 +112,9 @@ function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_isTrackWarmingUp: () => warmingUp,
_trackedPlaced: () => placed,
_trackedDisplayCached: () => head ?? null,
_trackedTrailCached: () => head ?? null,
_trackedDisplayPosition: () => head ?? null,
_trackedModelCenterWorld: () => null,
@@ -256,3 +266,36 @@ test('a full 24 h military trace fits within TRAIL_MAX_POINTS without thinning',
assert.ok(TRAIL_MAX_POINTS >= day + 500);
assert.equal(flightState._trailFixes.length, day + 1);
});
test('a placed military aircraft drawn ahead of the display delay keeps its trail joined to it', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2, 3].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 50,
lon: 1 + i * 0.12,
}));
// Warming up by the layer's own delay; the placement draws it between the
// third and fourth reports.
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 9_000);
const harness = trackedHarness({
liveFixes,
nowMs: t0 + 3.5 * MINUTE,
head: near,
placed: true,
warmingUp: true,
});
harness.flightState._displayDelay = { currentMs: 10 * MINUTE };
harness.tracking._startTrail('ae0001');
const body = harness.trail.last()[0];
assert.equal(harness.trail.last().length, 1);
assert.ok(
Cesium.Cartesian3.distance(
body[body.length - 1],
Cesium.Cartesian3.fromDegrees(1.24, 50, 9_000),
) < 1,
);
const drawn = harness.headPositions();
assert.ok(drawn.length >= 2);
assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1);
assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1);
});
+11 -2
View File
@@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
import { MIL_ICON_COLOR, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// A tracked military contact's trail is its reports joined along the curve
// the icon is drawn along between them, so the icon always sits on its trail
@@ -104,7 +104,11 @@ function harness({ fixes, info, nowMs, ground = () => null }) {
flightState.now = () => clock;
flightState._positionHistory.set(ICAO, fixes);
const parts = {
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
rendering: {
_modelOwnsVisual: () => false,
_modelSpec: () => ({}),
_fleetBillboardColor: () => MIL_ICON_COLOR,
},
queries: {
_toCleanText: (value) => (typeof value === 'string' ? value.trim() : ''),
_formatAltitude: (ft) => `${ft} ft`,
@@ -649,6 +653,11 @@ test('military: a stalled feed dims the tracked plane as STALE', () => {
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
assert.deepEqual(
h.tracking._trackedIconColor().slice(0, 3),
MIL_ICON_COLOR.slice(0, 3),
'faded in its own colour, never recoloured',
);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
+10 -5
View File
@@ -173,14 +173,15 @@ export function createRailCockpitSubject({
/**
* Which way the train runs along its shape: as its binding learnt it from
* successive reports, else from its drawn course against the line's
* bearing there; 0 while neither tells.
* successive reports, else from its operator's last reported bearing
* against the line's bearing there; 0 while neither tells. Not the drawn
* course: before the binding tells, that course is GPS jitter.
*/
function directionOf(entry) {
const binding = entry.path;
if (binding.direction === 1 || binding.direction === -1)
return binding.direction;
const course = finiteOrNull(entry.courseDeg);
const course = finiteOrNull(binding.bearingDeg);
const point = pointAtS(binding.path, binding.drawS, scratch);
if (course === null || !Number.isFinite(point?.bearingDeg)) return 0;
const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180);
@@ -205,8 +206,12 @@ export function createRailCockpitSubject({
finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat;
position.longitude =
finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon;
position.railHeightM = Number.isFinite(drawn?.h) ? drawn.h - liftM : null;
position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0;
const quality = Number.isFinite(drawn?.q) ? drawn.q : 0;
// Quality 0: no floor known here, so no height; a view waits for the
// surface.
position.railHeightM =
quality > 0 && Number.isFinite(drawn.h) ? drawn.h - liftM : null;
position.heightQuality = quality;
position.atMs = finiteOrNull(drawn?.at);
let path = null;
+74 -1
View File
@@ -44,6 +44,13 @@ const PACK = Object.freeze({
routes: { R1: [0] },
});
/** A floor service that knows the ground everywhere, at 12 m. */
const WARM_GROUND = Object.freeze({
GROUND_FLOOR_LIFT_M: 1.5,
cachedGroundFloor: () => 12,
warmGroundFloor() {},
});
/** Two trains on the line, T1 running east and T2 west, a step a poll. */
async function onTheLine(t, options = {}) {
const app = harness(t, {
@@ -76,7 +83,7 @@ const T1 = railTrainKey('mbta-rail', 'T1');
const T2 = railTrainKey('mbta-rail', 'T2');
test('the selected train reads as a snapshot of its place, motion and sources', async (t) => {
const app = await onTheLine(t);
const app = await onTheLine(t, { ground: WARM_GROUND });
assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected');
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
@@ -105,6 +112,7 @@ test('the selected train reads as a snapshot of its place, motion and sources',
assert.equal(view.provenance.positionSource, 'gps');
assert.equal(view.provenance.timestampSource, 'vehicle');
const drawn = app.entry(T1).drawnHeight;
assert.ok(view.position.heightQuality > 0, 'on a known floor');
assert.equal(view.position.railHeightM, drawn.h - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
assert.ok(Array.isArray(view.stops));
@@ -129,6 +137,71 @@ const stopList = (...names) =>
state: 'upcoming',
}));
test('a train drawn on an unknown floor reports no rail height', async (t) => {
// The harness's floor service is always cold: the train is drawn on the
// ellipsoid, which is no floor for a view to stand on.
const app = await onTheLine(t);
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
assert.equal(view.position.heightQuality, 0, 'no floor is known');
assert.equal(
view.position.railHeightM,
null,
'an unknown floor is no height',
);
});
test('a train on a known floor at sea level reports a rail height of 0 m', async (t) => {
const app = await onTheLine(t, {
ground: { ...WARM_GROUND, cachedGroundFloor: () => 0 },
});
app.parts().selection.selectTrain(T1);
const { position } = app.layer.getSelectedTrain();
assert.ok(position.heightQuality > 0, 'the floor is known');
assert.equal(position.railHeightM, 0, 'a height, not none');
});
test('a train first seen standing takes no direction from its GPS jitter', async (t) => {
// Reports 13 m apart, and the course drawn between them, do not tell which
// way it runs; an operator's bearing does.
const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON });
let jitterM = 0;
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + (1000 + jitterM) / KX),
train('T2', LAT, LON0 + (3000 + jitterM) / KX, { bearing: 270 }),
]);
await app.enable();
const seen = [];
for (const next of [13, 0, 13, 0, 13, 0]) {
jitterM = next;
app.run(RAIL_POLL_MS);
await app.poll();
app.parts().selection.selectTrain(T1);
const standing = app.layer.getSelectedTrain().path.direction;
app.parts().selection.selectTrain(T2);
seen.push([standing, app.layer.getSelectedTrain().path.direction]);
}
assert.deepEqual(seen, Array(6).fill([0, -1]));
});
test('a standing train keeps its operator’s bearing through reports that leave it out', async (t) => {
const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON });
let bearing = 270;
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + 1000 / KX, { bearing }),
]);
await app.enable();
const seen = [];
for (const next of [270, 270, 270, null, null, null]) {
bearing = next;
app.run(RAIL_POLL_MS);
await app.poll();
app.parts().selection.selectTrain(T1);
seen.push(app.layer.getSelectedTrain().path.direction);
}
assert.deepEqual(seen, Array(6).fill(-1));
});
test('a snapshot read again while nothing changed is the one read before', async (t) => {
let list = stopList('Alpha', 'Bravo', 'Charlie');
const app = await onTheLine(t, {
+43 -23
View File
@@ -1,3 +1,4 @@
import { FIX_FLAGS } from '../../data/contactPlayback.js';
import { pointAtS, projectOnPath } from '../../data/railPaths.js';
/**
@@ -47,14 +48,23 @@ export function pathWindowM(dtMs) {
return window > PATH_WINDOW_MAX_M ? NaN : window;
}
/** Arc moved between two reports before it says which way a train runs (m). */
const DIRECTION_MIN_M = 1;
/**
* Arc a train must move before it tells which way it runs (m); a standing
* train's GPS jitter stays within it.
*/
export const DIRECTION_MIN_M = 15;
/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */
function directionOf(step, known) {
return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M
? Math.sign(step)
: known;
/**
* The direction after one more arc position `s`: once `s` is DIRECTION_MIN_M
* or more from `turn.s`, the sign of that move, and `turn.s` moves to `s`.
*/
function steer(direction, turn, s) {
if (!Number.isFinite(s)) return direction;
if (!Number.isFinite(turn.s)) turn.s = s;
const step = s - turn.s;
if (Math.abs(step) < DIRECTION_MIN_M) return direction;
turn.s = s;
return Math.sign(step);
}
function createBinding(shapeIndex, path, via, s, fix) {
@@ -64,14 +74,19 @@ function createBinding(shapeIndex, path, via, s, fix) {
via,
/**
* Which way the drawn train runs along the shape: +1 along it, -1
* against it, 0 until two reports or a playback segment tell. Kept until
* a rebind. Once playback has placed the train, only playback changes
* it: the newest reports run ahead of the drawn train, so a reversal
* they show turns it when playback reaches it.
* against it, 0 until it has moved DIRECTION_MIN_M (steer). Kept until
* a rebind, and while the train stands.
* Once a playback segment has told it (`directionPlayed`), only playback
* changes it: the newest reports run ahead of the drawn train, so a
* reversal they show turns it when playback reaches it.
*/
direction: 0,
/** The direction the last placed playback segment ran, 0 before one. */
drawDirection: 0,
directionPlayed: false,
/** steer() turn points: one for the reports, one for the played segments. */
reportTurn: { s },
playTurn: { s: NaN, epoch: NaN },
/** The newest operator bearing its reports gave (deg), NaN before one. */
bearingDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN,
/** Arc and time of the newest report. */
fixS: s,
fixT: fix.t,
@@ -124,7 +139,7 @@ function bestRouteShape(pack, routeId, fix, accept) {
*
* @param {object} pack From createRailPathPack.
* @param {{tripId?: string, routeId?: string}} ids
* @param {{t: number, lat: number, lon: number}} fix The newest report.
* @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix The newest report.
* @returns {object|null} A binding, or null to keep straight-line motion.
*/
export function bindTrainPath(pack, { tripId, routeId } = {}, fix) {
@@ -146,7 +161,7 @@ export function bindTrainPath(pack, { tripId, routeId } = {}, fix) {
/**
* Follow a new report on the bound shape.
* @param {object} binding
* @param {{t: number, lat: number, lon: number}} fix
* @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix
* @returns {boolean} False when the report lies off the line: the binding is wrong.
*/
export function followFix(binding, fix) {
@@ -159,8 +174,9 @@ export function followFix(binding, fix) {
pathWindowM(fix.t - binding.fixT),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
if (!binding.drawDirection)
binding.direction = directionOf(hit.s - binding.fixS, binding.direction);
if (!binding.directionPlayed)
binding.direction = steer(binding.direction, binding.reportTurn, hit.s);
if (Number.isFinite(fix.bearingDeg)) binding.bearingDeg = fix.bearingDeg;
binding.fixS = hit.s;
binding.fixT = fix.t;
binding.fixLat = fix.lat;
@@ -211,7 +227,7 @@ function projectReport(binding, fix, hintS, hintT) {
*
* @param {object} binding
* @param {{fromSeq: number, toSeq: number, fraction: number}} sample Playback sample.
* @param {{from: {seq:number, t:number, lat:number, lon:number},
* @param {{from: {seq:number, t:number, lat:number, lon:number, flags?:number},
* to: {seq:number, t:number, lat:number, lon:number}}} segment The sample's two reports.
* @param {{lat?: number, lon?: number, bearingDeg?: number}} out
* @returns {boolean} False when the train should stay on its straight-line point.
@@ -253,11 +269,15 @@ export function placeOnPath(binding, sample, segment, out) {
cache.sTo = sTo;
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok) {
binding.drawDirection = directionOf(
sTo - sFrom,
binding.drawDirection || binding.direction || 0,
);
binding.direction = binding.drawDirection;
const turn = binding.playTurn;
// A break or a new epoch is a corrected position, not a move: steer
// on from there.
if (from.flags & FIX_FLAGS.BREAK || from.epoch !== turn.epoch)
turn.s = sFrom;
turn.epoch = from.epoch;
binding.direction = steer(binding.direction, turn, sFrom);
binding.direction = steer(binding.direction, turn, sTo);
if (binding.direction) binding.directionPlayed = true;
}
}
if (!cache.ok) return false;
+193 -2
View File
@@ -1,5 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
FIX_FLAGS,
advance,
createSample,
createTrack,
insertFix,
readFix,
} from '../../data/contactPlayback.js';
import { createRailPathPack } from '../../data/railPaths.js';
import {
PATH_OFF_TRACK_M,
@@ -209,8 +217,9 @@ test('a binding learns which way its train runs, and keeps it through a stop', (
assert.equal(along.direction, 0, 'one report tells no direction');
assert.ok(followFix(along, fix(10_000, 700, 0)));
assert.equal(along.direction, 1);
// Standing still (under a metre) keeps what it learnt.
assert.ok(followFix(along, fix(20_000, 700.4, 0)));
// Standing at a stop, its reports jitter back 10 m: it keeps what it
// learnt.
assert.ok(followFix(along, fix(20_000, 690, 0)));
assert.equal(along.direction, 1);
const against = bindTrainPath(p, ids, fix(0, 1500, 0));
assert.ok(followFix(against, fix(10_000, 1200, 0)));
@@ -262,3 +271,185 @@ test('a report that runs back turns the drawn train only when playback does', ()
);
assert.equal(binding.direction, -1);
});
test('a jump to a corrected position in a new playback epoch is no reversal', () => {
const binding = bindTrainPath(
pack(),
{ tripId: 'full', routeId: 'main' },
fix(0, 1000, 0),
);
const play = (seq, from, to) => {
const { sample, segment } = playback(seq, seq + 1, from, to, 0.5);
return placeOnPath(binding, sample, segment, {});
};
assert.ok(play(0, fix(0, 1000, 0), fix(60_000, 1600, 0)));
assert.equal(binding.direction, 1);
// The source puts it back at 1400 m: a new epoch whose first report is a
// break, and no segment is played from 1600 m to there.
const epoch = { epoch: 1 };
assert.ok(
play(
5,
{ ...fix(70_000, 1400, 0), ...epoch, flags: FIX_FLAGS.BREAK },
{ ...fix(85_000, 1400, 0), ...epoch },
),
);
assert.equal(binding.direction, 1, 'standing there, it keeps its way');
// From there, a real move back still turns it.
assert.ok(
play(
6,
{ ...fix(85_000, 1400, 0), ...epoch },
{ ...fix(100_000, 1380, 0), ...epoch },
),
);
assert.equal(binding.direction, -1);
});
test('a clock correction played from past its break is no reversal', () => {
const binding = bindTrainPath(
pack(),
{ tripId: 'full', routeId: 'main' },
fix(0, 600, 0),
);
const track = createTrack();
const sample = createSample();
const segment = { from: {}, to: {} };
let now = 0;
/** One report at `t`, then 15 s of frames; the direction after each. */
const report = (t, eastM) => {
insertFix(track, fix(t, eastM, 0), { receivedAt: now, wallNowMs: now });
return [1, 2, 3].map(() => {
now += 5000;
advance(track, { wallNowMs: now, monoNowMs: now }, sample);
if (sample.fromSeq >= 0) {
readFix(track, sample.fromSeq - track.baseSeq, segment.from);
readFix(track, sample.toSeq - track.baseSeq, segment.to);
placeOnPath(binding, sample, segment, {});
}
return binding.direction;
});
};
for (const eastM of [600, 750, 900, 1050, 1200, 1200, 1200, 1200])
report(now, eastM);
assert.equal(binding.direction, 1);
assert.ok(binding.directionPlayed);
// Its source's clock falls 120 s behind and puts it at 1000 m. The third
// such report starts a new epoch, and playback starts at the newest one,
// past the break.
const seen = [0, 1, 2].flatMap(() => report(now - 120_000, 1000));
assert.equal(track.resetReason, 'out-of-order');
assert.deepEqual(seen, Array(9).fill(1));
});
/** The direction after each played segment, `[fromM, toM]` 15 s apart. */
function playDirections(binding, steps) {
return steps.map(([fromM, toM], seq) => {
const { sample, segment } = playback(
seq,
seq + 1,
fix(seq * 15_000, fromM, 0),
fix((seq + 1) * 15_000, toM, 0),
0.5,
);
assert.ok(placeOnPath(binding, sample, segment, {}));
return binding.direction;
});
}
/** The direction after each report, `eastMs` 15 s apart. */
function reportDirections(binding, eastMs) {
return eastMs.map((eastM, i) => {
assert.ok(followFix(binding, fix((i + 1) * 15_000, eastM, 0)));
return binding.direction;
});
}
test('a train that moves under 15 m a report still tells its direction', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
// It sets off slowly, runs east, then backs out 10 m a report.
const learnt = reportDirections(
bindTrainPath(p, ids, fix(0, 1000, 0)),
[1010, 1020, 1600, 1590, 1580, 1570],
);
assert.deepEqual(learnt, [0, 1, 1, 1, -1, -1], 'from the newest reports');
const played = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.deepEqual(
playDirections(played, [
[1000, 1600],
[1600, 1590],
[1590, 1580],
[1580, 1570],
]),
[1, 1, -1, -1],
'from the played-back segments',
);
});
test('a train turns 15 m back from where it ran to, not 14.9 m', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
for (const [backM, want, label] of [
[1100, -1, '15 m back'],
[1100.1, 1, '14.9 m back'],
]) {
const learnt = reportDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [
1115,
backM,
]);
assert.deepEqual(learnt, [1, want], `${label}, from the newest reports`);
assert.deepEqual(
playDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [
[1000, 1115],
[1115, backM],
]),
[1, want],
`${label}, from the played-back segments`,
);
}
});
test('GPS jitter of up to 14 m at a standing train keeps its direction', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const learnt = reportDirections(
bindTrainPath(p, ids, fix(0, 1000, 0)),
[1600, 1588, 1600, 1586, 1599, 1587],
);
assert.deepEqual(learnt, [1, 1, 1, 1, 1, 1], 'from the newest reports');
const played = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.deepEqual(
playDirections(played, [
[1000, 1600],
[1600, 1588],
[1588, 1600],
[1600, 1586],
[1586, 1599],
]),
[1, 1, 1, 1, 1],
'from the played-back segments',
);
// On both sides of where it stopped: 8 m either way, 16 m from end to end.
assert.deepEqual(
reportDirections(
bindTrainPath(p, ids, fix(0, 600, 0)),
[1000, 1008, 1000, 992, 1000, 1008],
),
[1, 1, 1, 1, 1, 1],
'both sides, from the newest reports',
);
assert.deepEqual(
playDirections(bindTrainPath(p, ids, fix(0, 600, 0)), [
[600, 1000],
[1000, 1008],
[1008, 1000],
[1000, 992],
[992, 1000],
[1000, 1008],
]),
[1, 1, 1, 1, 1, 1],
'both sides, from the played-back segments',
);
});
+2 -4
View File
@@ -16,6 +16,7 @@ import {
import { displayMotion } from '../transit/movement.js';
import { FIX_FLAGS, readFix } from '../../data/contactPlayback.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import { DIRECTION_MIN_M } from './pathBinding.js';
import {
stopClock,
stopLateMinutes,
@@ -294,9 +295,6 @@ export function playbackModeFor(railMode) {
: 'rail';
}
/** Two reports closer than this are one place: a parked train's jitter (m). */
export const FOLLOW_MIN_MOVE_M = 15;
const lastFix = {};
const priorFix = {};
@@ -333,7 +331,7 @@ export function railTrainFollowable(entry) {
sample.nextMotionT > sample.displayT
)
return true;
return lastReportsApartM(entry.track) >= FOLLOW_MIN_MOVE_M;
return lastReportsApartM(entry.track) >= DIRECTION_MIN_M;
}
/**
+21 -5
View File
@@ -48,6 +48,7 @@ import {
transitModelSpec,
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
/** How often the trains near enough for a model are gathered again (wall ms). */
const MODEL_CANDIDATES_MS = 500;
@@ -924,6 +925,25 @@ export function createRendering({ state, services, parts }) {
display: fleet.display,
policy: fleet.policy,
resolveAsset: fleet.resolveAsset,
partState: vehiclePartState,
});
}
/**
* Wheels rolling at the speed it is drawn moving at (else its reported
* one), doors open while it stands at a stop.
*/
function vehiclePartState(item, table) {
const entry = item.entry;
const drawn = entry?.sample?.segmentSpeedMps;
const reported = entry?.record?.speedMps;
return groundVehiclePartState(table, {
speedMps: Number.isFinite(drawn)
? drawn
: Number.isFinite(reported)
? reported
: null,
atStop: entry?.record?.status === 'STOPPED_AT',
});
}
@@ -978,11 +998,7 @@ export function createRendering({ state, services, parts }) {
if (now - modelCandidatesAtMs >= MODEL_CANDIDATES_MS) {
modelCandidatesAtMs = now;
const eye = cameraPose()?.position;
const policy = services.fleet.policy;
const keepM =
services.fleet.display?.()?.models3dMode === 'all'
? policy.keepAllM
: policy.keepM;
const keepM = services.fleet.policy.keepM;
const limitSq = keepM * keepM * 1.44;
if (eye)
for (const entry of state._trains.values()) {
+21 -7
View File
@@ -574,12 +574,14 @@ export function createRecentImageryLayer({
const list = stripList();
if (!list.length) return;
reconcileFocus();
thumbnails.requestOrdered(list, _box, {
focusIndex: Math.max(0, focusIndexIn(list)),
firstVisible: _visible.first,
lastVisible: _visible.last,
extra: 2,
});
const wanted = new Set(
thumbnails.requestOrdered(list, _box, {
focusIndex: Math.max(0, focusIndexIn(list)),
firstVisible: _visible.first,
lastVisible: _visible.last,
extra: 2,
}),
);
for (const key of new Set([
_assigned.a,
_assigned.b,
@@ -587,8 +589,11 @@ export function createRecentImageryLayer({
_followKey,
])) {
const candidate = candidateFor(key);
if (sourceOn(candidate)) thumbnails.request(candidate, _box, 0);
if (!sourceOn(candidate)) continue;
thumbnails.request(candidate, _box, 0);
wanted.add(candidate.key);
}
thumbnails.retain(wanted);
}
function resetCatalog() {
@@ -821,7 +826,16 @@ export function createRecentImageryLayer({
// A probe can take a pinned day off the map or let a followed focus
// preview; both change more than the cards, so a full notification
// follows the thumbnail one.
const previousFollow = _followKey;
const previousPreview = _previewKey;
const pruned = pruneEmpty();
if (
pruned &&
(_followKey !== previousFollow || _previewKey !== previousPreview)
) {
// The new automatic day's probe may have been cancelled off-screen.
requestThumbnails();
}
if (pruned) syncRender();
const followed =
Boolean(_followKey) &&
+46
View File
@@ -1105,6 +1105,10 @@ test('alpha, split and visible range notify without re-rendering the row', async
f.layer.setSplit(0.25);
f.layer.setVisibleRange(1, 3);
assert.equal(f.thumbnails.calls.at(-1)[2].firstVisible, 1);
assert.ok(
f.thumbnails.retained.at(-1).includes(f.snap().focus.key),
'the current focus remains in the retained refinement intent',
);
assert.equal(rowRenders, rows);
assert.deepEqual(f.reasons.slice(-2), ['alpha', 'split']);
f.layer.setAlpha('bad');
@@ -1193,6 +1197,48 @@ const dailyViirs = () =>
),
);
test('empty auto VIIRS re-requests a cancelled successor', async () => {
const f = fixture();
const days = dailyViirs();
const newest = days[0].key;
const next = days[1].key;
f.layer.setSources({ hls: false });
await f.ready(days);
assert.equal(f.diag().following, newest);
assert.ok(
f.thumbnails.retained.at(-1).includes(next),
'the next day was originally scheduled',
);
// Move the visible window away before either day answers: retention
// cancels the next day's probe but keeps the currently followed day.
f.layer.setVisibleRange(25, 29);
assert.equal(
f.thumbnails.retained.at(-1).includes(next),
false,
'the next day is no longer retained',
);
const before = f.thumbnails.requests.filter(([key]) => key === next).length;
f.thumbnails.probe(newest, 'empty');
assert.equal(f.diag().following, next);
assert.equal(f.snap().preview.pending, next);
assert.ok(
f.thumbnails.retained.at(-1).includes(next),
'the new follow day is retained without scrolling again',
);
assert.equal(
f.thumbnails.requests.filter(([key]) => key === next).length,
before + 1,
'the cancelled successor is requested again',
);
f.thumbnails.probe(next, 'present');
assert.equal(f.snap().preview.key, next);
assert.deepEqual(f.drapes(), { a: `${next}|none`, b: null });
});
test('restored pins outside the visible strip window are probed and swipe once present', async () => {
const f = fixture();
const days = dailyViirs();
+10 -2
View File
@@ -258,6 +258,7 @@ export function fakeThumbnails() {
const requested = [];
/** Direct `request` calls: `[key, priority]`. */
const requests = [];
const retained = [];
const ask = (key) => {
if (!requested.includes(key)) requested.push(key);
};
@@ -265,21 +266,28 @@ export function fakeThumbnails() {
calls,
requested,
requests,
retained,
requestOrdered(candidates, box, window) {
calls.push(['ordered', candidates.map((c) => c.key), window]);
const { focusIndex, firstVisible, lastVisible, extra } = window;
thumbnailOrder(
const order = thumbnailOrder(
focusIndex,
firstVisible,
lastVisible,
candidates.length,
extra,
).forEach((index) => ask(candidates[index].key));
);
const keys = order.map((index) => candidates[index].key);
keys.forEach(ask);
return keys;
},
request(candidate, box, priority) {
ask(candidate.key);
requests.push([candidate.key, priority]);
},
retain(keys) {
retained.push([...keys]);
},
/** Settle every requested key still unknown, as the loader would. */
probeRequested(status = 'present') {
for (const key of requested)
+36 -1
View File
@@ -166,6 +166,19 @@ export function createThumbnailLoader({
const existing = entries.get(key);
if (existing) {
touch(existing);
if (existing.loading && existing.controller?.signal.aborted) {
// Wanted again before the abort settles: a fresh entry, so the old
// run cannot discard it.
const renewed = {
...existing,
priority,
loading: false,
controller: null,
};
entries.set(key, renewed);
enqueue(renewed);
return;
}
if (existing.loading) return;
if (existing.status === 'unknown') {
existing.priority = priority;
@@ -210,11 +223,33 @@ export function createThumbnailLoader({
candidates.length,
extra,
);
order.forEach((index, priority) => {
return order.map((index, priority) => {
this.request(candidates[index], box, priority);
return candidates[index].key;
});
},
/**
* Cancel queued and in-flight work for every key not in `keys`. Settled
* entries stay under the LRU; a cancelled re-fetch of a present day keeps
* its status.
* @param {Iterable<string>} keys
*/
retain(keys) {
const wanted = new Set(keys);
for (let index = queue.length - 1; index >= 0; index -= 1) {
const entry = queue[index];
if (wanted.has(entry.key)) continue;
queue.splice(index, 1);
if (entry.status === 'unknown') entries.delete(entry.key);
}
for (const entry of [...entries.values()]) {
if (!entry.loading || wanted.has(entry.key)) continue;
entry.controller?.abort();
if (entry.status === 'unknown') entries.delete(entry.key);
}
},
/**
* Abort every fetch in flight and forget every unsettled request. A
* known day whose image was being fetched again keeps what it knows.
@@ -336,3 +336,93 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
loader.destroy();
assert.deepEqual(revoked, ['blob:1']);
});
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
const { loader, fetch } = fixture({ maxInFlight: 1 });
const stale = candidate('S30', '2026-09-10');
const current = candidate('S30', '2026-09-11');
loader.request(stale, BOX, 0);
loader.request(current, BOX, 1);
assert.equal(fetch.calls.length, 1);
assert.match(fetch.calls[0].url, /TIME=2026-09-10/);
loader.retain([current.key]);
assert.equal(fetch.calls[0].signal.aborted, true);
await settle();
assert.equal(
fetch.calls.length,
2,
'current intent starts after stale abort',
);
assert.match(fetch.calls[1].url, /TIME=2026-09-11/);
assert.equal(loader.get(stale.key).status, 'unknown');
});
test('a cancelled re-fetch of a known-present day keeps its status and is retryable', async () => {
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
const stale = candidate('S30', '2026-09-10');
const newer = candidate('S30', '2026-09-11');
loader.request(stale, BOX, 0);
fetch.respond(0);
await settle();
const acquisitionTime = loader.get(stale.key).acquisitionTime;
loader.request(newer, BOX, 0);
fetch.respond(1);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
assert.equal(loader.get(stale.key).objectUrl, null);
loader.request(stale, BOX, 0);
assert.equal(fetch.calls.length, 3, 'an evicted known day re-fetches');
loader.retain([]);
assert.equal(fetch.calls[2].signal.aborted, true);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
assert.equal(loader.get(stale.key).acquisitionTime, acquisitionTime);
loader.request(stale, BOX, 0);
assert.equal(fetch.calls.length, 4, 'a cancelled re-fetch is retryable');
fetch.respond(3);
await settle();
assert.equal(loader.get(stale.key).status, 'present');
});
for (const cancelRenewed of [false, true]) {
test(`a known-present day requested during abort settlement ${cancelRenewed ? 'can be cancelled again' : 'restarts without another intent change'}`, async (t) => {
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
t.after(() => loader.destroy());
const day = candidate('S30', '2026-09-10');
const other = candidate('S30', '2026-09-11');
loader.request(day, BOX);
fetch.respond(0);
await settle();
const acquisitionTime = loader.get(day.key).acquisitionTime;
loader.request(other, BOX);
fetch.respond(1);
await settle();
assert.equal(loader.get(day.key).objectUrl, null);
loader.request(day, BOX);
loader.retain([]);
assert.equal(fetch.calls[2].signal.aborted, true);
// Deliberately do not await: the old run still owns its in-flight slot.
loader.request(day, BOX);
loader.retain(cancelRenewed ? [] : [day.key]);
assert.equal(fetch.calls.length, 3, 'renewal respects the concurrency cap');
await settle();
assert.equal(loader.get(day.key).acquisitionTime, acquisitionTime);
assert.equal(fetch.calls.length, cancelRenewed ? 3 : 4);
if (!cancelRenewed) {
assert.equal(fetch.calls[3].signal.aborted, false);
fetch.respond(3);
await settle();
assert.ok(loader.get(day.key).objectUrl);
assert.equal(loader.get(day.key).loading, false);
}
});
}
+10 -1
View File
@@ -271,13 +271,22 @@ test('the rendering part draws the dots, the tracked dot and the rings through t
state._enabled = true;
state._params = { showPoints: false, showOrbits: false };
let at = { x: 10, y: 20, z: 30 };
const carrier = rendering._addTrackedEntity({ position: () => at });
const issRed = [1, 0.27, 0.27, 1];
const carrier = rendering._addTrackedEntity({
position: () => at,
color: issRed,
});
assert.deepEqual(carrier, { noradId: 25544 });
const tracked = draw.set(points.replace(':points', ':tracked'));
assert.equal(tracked.items.size, 0);
rendering._preRenderTick({ frame: 3 });
assert.deepEqual(tracked.items.get('25544').pos, at);
assert.equal(tracked.items.get('25544').pixelSize, 14);
assert.deepEqual(
tracked.items.get('25544').color,
issRed,
'the satellite keeps its own colour',
);
assert.equal(tracked.items.get('25544').disableDepthTest, Infinity);
at = { x: 11, y: 21, z: 31 };
rendering._preRenderTick({ frame: 4 });
+8 -7
View File
@@ -34,12 +34,11 @@ const POINT_SCALE_BY_DISTANCE = Object.freeze({
});
/**
* The tracked satellite's dot: 14 px yellow with a white outline, drawn
* over everything.
* The tracked satellite's dot: 14 px in the satellite's own colour with a
* white outline, drawn over everything. Tracking never recolours it.
*/
const TRACKED_DOT = Object.freeze({
pixelSize: 14,
color: Object.freeze([1, 1, 0, 1]),
outlineColor: Object.freeze([1, 1, 1, 1]),
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -386,12 +385,13 @@ export function createRendering({
/**
* Draw the tracked satellite's dot and make the carrier the follow target
* and the tracked card read (its entity record holds the card).
* @param {{position: () => object, viewFrom: {x: number, y: number,
* z: number}}} options `position` is read as the follow camera reads
* it, once each frame before the tick moves the sample on.
* @param {{position: () => object, color: number[], viewFrom: {x: number,
* y: number, z: number}}} options `position` is read as the follow
* camera reads it, once each frame before the tick moves the sample on;
* `color` is the satellite's own dot colour.
* @returns {object} The carrier.
*/
function _addTrackedEntity({ position }) {
function _addTrackedEntity({ position, color }) {
const noradId = layerState._trackedNorad;
const carrier = { noradId };
trackedDot = {
@@ -400,6 +400,7 @@ export function createRendering({
id: String(noradId),
pos: { x: 0, y: 0, z: 0 },
...TRACKED_DOT,
color,
meta: { noradId },
},
drawn: false,
+2
View File
@@ -445,6 +445,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedEntity = parts.rendering._addTrackedEntity({
position: trackedPosition,
// Its own dot's colour: tracking never recolours a satellite.
color: parts.controls._pointStyleFor(noradId, sat.group).color,
viewFrom,
});
entityRecord(layerState._trackedEntity).selectionOrigin = origin;
+27 -17
View File
@@ -83,13 +83,16 @@ export function createTransitCockpitSubject({ state, parts, services }) {
* lift: the drawn marker's height while the frame pass places it (in view,
* or held), which near the ground follows the terrain between reports;
* else its segment's two reports' floors at the playback fraction. Null
* while either floor is unknown, as on cold terrain, so a view waits for
* the surface. Not `entry.heightM`, the floor at the newest report, which
* playback has not reached yet.
* while either of those two floors is unknown, as on cold terrain, so a
* view waits for the surface. Not `entry.heightM`, the floor at the newest
* report, which playback has not reached yet.
*/
function drawnFloorOf(entry) {
const segment = entry.segment;
if (!segment || entry.heightPending) return null;
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const placed =
entry.surfaceReady === true &&
entry.hasRendered &&
@@ -99,9 +102,6 @@ export function createTransitCockpitSubject({ state, parts, services }) {
const drawn = toCartographicRadians(entry.marker.position);
if (drawn) return drawn.height - liftM;
}
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const f = Number.isFinite(segment.fraction)
? Math.max(0, Math.min(1, segment.fraction))
: 1;
@@ -173,16 +173,32 @@ export function createTransitCockpitSubject({ state, parts, services }) {
return snapshot;
}
/** Show or hide a vehicle's sprite and trail for the hold. */
/**
* Place a vehicle and show or hide its sprite and trail for the hold now:
* the icon set draws a marker as it was last pushed, not as it is.
*/
function repaint(entry) {
if (!entry?.marker) return;
if (entry.key === state._cockpitSubjectKey) entry.marker.show = false;
else parts.rendering.placeSample(entry);
parts.rendering.placeSample(entry);
parts.rendering.flushMarkers();
parts.rendering.schedulePlayback(entry);
parts.trails.update();
state._detectRevision += 1;
}
/**
* A vehicle let go of is out of play until a sweep finds it in view. It
* played on while held, so the next sweep keeps its clock if it finds it in
* view (rendering.js).
*/
function release(entry) {
if (!entry) return;
state._visible.delete(entry);
entry.releasedFromHold = true;
parts.rendering.requestVisibility();
repaint(entry);
}
const methods = {
/** The selected vehicle (see createTransitCockpitSubject), or null. */
getSelectedVehicle() {
@@ -202,13 +218,7 @@ export function createTransitCockpitSubject({ state, parts, services }) {
const previous = state._vehicles.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
// The hold kept it in play out of view: it leaves until the next
// visibility sweep finds it in view again.
if (previous) {
state._visible.delete(previous);
parts.rendering.requestVisibility();
}
repaint(previous);
release(previous);
parts.selection.refreshSelectedCard(true);
return true;
}
@@ -217,7 +227,7 @@ export function createTransitCockpitSubject({ state, parts, services }) {
if (state._selectedKey !== key) parts.selection.selectVehicle(key);
state._cockpitSubjectKey = key;
state._visible.add(entry);
if (previous && previous !== entry) repaint(previous);
if (previous !== entry) release(previous);
repaint(entry);
parts.selection.refreshSelectedCard(true);
return true;
+2
View File
@@ -165,6 +165,8 @@ export function createLifecycle({ state, services, parts }) {
state._visible.clear();
clearTimeout(state._cameraDebounceTimer);
state._cameraDebounceTimer = null;
// A hold ends with the layer (cockpitSubject.js).
state._cockpitSubjectKey = null;
parts.selection.clearSelection();
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
parts.selection.removeClickHandler();
+250 -6
View File
@@ -958,27 +958,70 @@ test('disable aborts in-flight work and a response that lands late is ignored',
assert.equal(app.vehicles().length, 1);
});
test('a held vehicle with no floor yet tells its view no height', async (t) => {
// Not the ellipsoid: a first-person view waits for the surface instead.
const app = harness(t, { floorAt: () => undefined });
/**
* Serves one bus at `place.lat` (read on every poll), enables the layer, polls
* once and settles; returns its entry.
*/
async function oneBus(app, place = { lat: 42.36 }) {
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)],
[vehicle('bus-1', place.lat, -71.06, reported())],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const entry = app.vehicles()[0];
return app.vehicles()[0];
}
test('a held vehicle with no floor yet tells its view no height', async (t) => {
// Not the ellipsoid: a first-person view waits for the surface instead.
const app = harness(t, { floorAt: () => undefined });
const entry = await oneBus(app);
assert.equal(entry.heightPending, true, 'it has nothing to stand on');
assert.ok(app.layer.setCockpitSubject(entry.key) !== false);
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('with the camera above the height gate, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => {
const app = harness(t, { altitude: 100_000, floorAt: () => undefined });
const entry = await oneBus(app);
assert.ok(app.layer.setCockpitSubject(entry.key) !== false);
app.frame();
assert.equal(entry.surfaceReady, true, 'it is drawn');
const drawnM = Cesium.Cartographic.fromCartesian(
entry.marker.position,
).height;
assert.ok(Math.abs(drawnM) < 1e-3, `on the ellipsoid, got ${drawnM} m`);
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('with the camera above the height gate, a held vehicle with one floor unknown tells its view no height', async (t) => {
// Drawn between a floor its view could stand on and none.
for (const knownLat of [42.36, 42.361]) {
await t.test(`floor known at ${knownLat}`, async (t) => {
const app = harness(t, { altitude: 100_000, floorAt: () => undefined });
app.ground._warm.set(app.ground._key(knownLat, -71.06), 12);
const start = Date.now();
const place = { lat: 42.36 };
const entry = await oneBus(app, place);
place.lat = 42.361;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
assert.equal(app.layer.setCockpitSubject(entry.key), true);
app.run(start - AGE_MS + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now());
const { from, to } = entry.segment;
assert.notEqual(Number.isFinite(from.h), Number.isFinite(to.h));
assert.equal(entry.surfaceReady, true, 'it is drawn');
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
}
});
test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => {
// The shared ground-floor system answers from the rendered mesh cell or the
// real DEM cell; until one of them is warm there is no honest height to draw
@@ -2119,13 +2162,19 @@ test('a segment climbs from the ground it left to the ground it reaches', async
`its snapshot stands where it is drawn, got ${floor().toFixed(1)} m`,
);
// Halfway along the segment it is halfway up; at the end, on the high ground.
// Halfway along the segment it still follows the low ground it crosses; at
// the end, it is on the high ground.
const firstFixAt = start - AGE_MS;
app.run(firstFixAt + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now());
assert.ok(
Math.abs(height() - 11.5) < 3,
`at the corridor floor, got ${height().toFixed(1)} m`,
);
// The two reports' floors blended at the fraction would say about 55 m.
assert.ok(
Math.abs(floor() + 1.5 - height()) < 1,
`its snapshot stands on that floor too, got ${floor().toFixed(1)} m`,
);
app.run(TRANSIT_POLL_MS);
assert.ok(
Math.abs(height() - 101.5) < 1.5,
@@ -4206,6 +4255,7 @@ test('the actual Transit lifecycle keeps exactly its own camera listener in ever
onCameraChanged: noop,
runProximityCheck: noop,
deactivateAllCities: noop,
showCoverage: noop,
},
ingestion: { abortAllInFlight: noop },
},
@@ -4905,3 +4955,197 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes',
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
/** A vehicle's icon in the set that draws it, still or moving. */
function iconOf(app, key) {
return app.markers('still').get(key) ?? app.markers('moving').get(key);
}
test('turning Transit off ends a hold; on again, the vehicle shows, a click selects it and Escape deselects it', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
assert.equal(app.layer.setCockpitSubject(key), true);
app.layer.disable(app.viewer);
assert.equal(
app.state()._cockpitSubjectKey,
null,
'the hold ended with the layer',
);
// On again, without a release: the same bus is listed again.
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held');
assert.equal(iconOf(app, key)?.show, true, 'and so is its icon in the set');
app.viewer.scene.pick = () => app.pickOf(entry);
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, key, 'a click selects it');
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null, 'Escape deselects');
});
test('a held parked vehicle draws no icon; let go, it draws its icon again', async (t) => {
// A parked bus with no course: nothing moves or turns its icon, so only the
// hold itself can take the icon out of the set that draws it.
const app = harness(t);
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, reported(), { stopId: 'place-1' })],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
for (let i = 0; i < 3; i += 1) {
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
}
const key = 'mbta:bus-1';
const [entry] = app.vehicles();
assert.equal(iconOf(app, key)?.show, true, 'drawn before the hold');
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(iconOf(app, key)?.show ?? false, false, 'hidden at once');
// The view rides it for a while: frames, a sweep, a poll.
app.run(2_000, 16);
app.settle();
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
assert.equal(entry.marker.show, false, 'its marker is hidden');
assert.equal(
iconOf(app, key)?.show ?? false,
false,
'and so is the icon the set draws',
);
assert.equal(app.layer.setCockpitSubject(null), true);
app.advance(250);
app.settle();
assert.equal(iconOf(app, key)?.show, true, 'let go: drawn again');
});
test('a hold moved to another vehicle lets the first go out of view', async (t) => {
const app = harness(t);
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[
vehicle('bus-1', 42.36, -71.06, reported()),
vehicle('bus-2', 42.37, -71.05, reported()),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const bus = (id) => app.vehicles().find((entry) => entry.key === id);
const first = bus('mbta:bus-1');
assert.equal(app.layer.setCockpitSubject(first.key), true);
// The view looks away from both, as a view from inside the first does.
app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 });
app.advance(250);
app.settle();
assert.equal(app.state()._visible.has(bus('mbta:bus-2')), false);
assert.equal(app.layer.setCockpitSubject('mbta:bus-2'), true);
assert.equal(app.state()._visible.has(first), false, 'let go, out of play');
assert.equal(first.marker.show, false, 'and not drawn out of view');
});
test('a vehicle in view let go of a hold goes on from its own clock', async (t) => {
// Held, it played on; let go, the sweep that finds it in view does not
// set its clock again, though the feed's lag has grown since.
for (const next of ['mbta:b', null]) {
await t.test(`the hold moves to ${next}`, async (t) => {
const app = harness(t, { floorAt: () => 5 });
let fixAt = Date.now() - AGE_MS;
let north = 42.36;
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[
vehicle('a', north, -71.06, fixAt / 1000),
vehicle('b', 42.37, -71.05, reported()),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const a = app.vehicles().find((e) => e.key === 'mbta:a');
app.layer.setCockpitSubject(a.key);
for (let poll = 1; poll <= 5; poll += 1) {
fixAt += TRANSIT_POLL_MS;
north += 0.001;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
// One late poll raises the feed's target lag.
app.run(TRANSIT_POLL_MS + 10_000);
fixAt += TRANSIT_POLL_MS;
north += 0.001;
await app.layer.update();
app.run(3_000);
const beforeT = a.track.displayT;
const beforeLat = lat(a);
app.layer.setCockpitSubject(next);
app.advance(250);
app.settle();
assert.equal(app.state()._visible.has(a), true, 'A is in view');
assert.ok(a.track.displayT >= beforeT, 'its clock did not go back');
assert.ok(lat(a) >= beforeLat, 'nor did it move back');
});
}
});
test('holding a vehicle out of view tells its view at once the floor it stands on', async (t) => {
// Out of view a vehicle plays on but its marker is not moved: the hold
// places it, so its view reads the floor it is on now, not the old one or
// null.
const app = harness(t, { floorAt: (lat) => (lat > 42.3625 ? 100 : 10) });
for (const [lat, floorM] of [
[42.361, 10],
[42.362, 10],
[42.363, 100],
[42.364, 100],
])
app.ground._warm.set(app.ground._key(lat, -71.06), floorM);
const place = { lat: 42.36 };
const entry = await oneBus(app, place);
const drawnM = () =>
Cesium.Cartographic.fromCartesian(entry.marker.position).height;
assert.ok(Math.abs(drawnM() - 11.5) < 1, 'drawn on the low ground');
app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 });
app.advance(250);
app.settle();
assert.equal(app.state()._visible.has(entry), false, 'out of view');
// Unseen, it drives up the hill and stands there.
for (const next of [42.361, 42.362, 42.363, 42.364, 42.364, 42.364]) {
place.lat = next;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
app.run(LAG_MS);
app.settle();
assert.ok(drawnM() < 30, 'its marker was left on the low ground');
assert.equal(app.layer.setCockpitSubject(entry.key), true);
const floorM = app.layer.getCockpitSubject().position.groundHeightM;
assert.ok(Math.abs(floorM - 100) < 1.5, `up the hill, got ${floorM} m`);
});
Loaded 100 of 1337 files, more files were not shown because too many files have changed in this diff. Show more