mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 09:12:18 +00:00
Sprites for helicopters, ground vehicles, stations and vessel types; history to live without an empty map; model parts in Cesium
Aircraft icons are one size; helicopters turn a three-frame rotor while airborne or moving; ADS-B ground vehicles share one amber sprite and stations/obstacles one mast; vessels get hull sprites by type and one buoy. Going live keeps contacts until the first live answer and replaces them by id; fast playback holds before the loaded positions end and prefetches ahead. Cesium models move their parts from the optional model part state.
This commit is contained in:
1 parent
624c229bc2
commit
7186f720df
97 files changed
+6586
-343
No files matched your search
@@ -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 };
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
@@ -425,9 +424,7 @@ export function createMotion({
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -123,9 +123,14 @@ export class FlightRecords {
|
||||
stickyText(callsign, prevMeta?.callsign),
|
||||
);
|
||||
const feedType = observation.typeCode || null;
|
||||
const typeCode =
|
||||
airframe?.typeCode ??
|
||||
(feedType && groundModel(feedType) ? feedType : null);
|
||||
// The feed's type is kept for what it names itself, not for a surface
|
||||
// category: a C1 contact whose feed names an airliner type stays a vehicle.
|
||||
const keepFeedType =
|
||||
Boolean(feedType) &&
|
||||
(groundCategory(category)
|
||||
? GROUND_FEED_TYPES.has(feedType.trim().toUpperCase())
|
||||
: groundModel(feedType));
|
||||
const typeCode = airframe?.typeCode ?? (keepFeedType ? feedType : null);
|
||||
const onGround =
|
||||
on_ground === true ||
|
||||
(!Number.isFinite(baro_alt) &&
|
||||
@@ -280,7 +285,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.
|
||||
@@ -325,11 +331,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,
|
||||
}),
|
||||
// An adsbdb-enriched type code outranks the coarse OpenSky category;
|
||||
// a feed's own ground type (ZVEH, GRND) classes it 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
|
||||
@@ -452,13 +456,46 @@ 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;
|
||||
}
|
||||
|
||||
/** The types a feed gives airport vehicles (ZVEH) and ground stations (GRND). */
|
||||
const GROUND_FEED_TYPES = new Set(['ZVEH', 'GRND']);
|
||||
|
||||
/** 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 +504,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);
|
||||
|
||||
@@ -312,12 +312,83 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(reported.onGround, false);
|
||||
// Before the model set loads nothing is grounded by its model.
|
||||
const unloaded = records().receive(
|
||||
// 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', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(unloaded.onGround, false);
|
||||
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, null);
|
||||
});
|
||||
|
||||
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;
|
||||
assert.equal(klass({ id: 'v1', typeCode: 'ZVEH' }), 'vehicle');
|
||||
assert.equal(
|
||||
klass({ id: 'v2', typeCode: 'ZVEH', callsign: 'FIRE 2' }),
|
||||
'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 still waits for the airframe lookup.
|
||||
assert.equal(
|
||||
klass({ id: 'p1', typeCode: 'A320', category: 'A7' }),
|
||||
'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', () => {
|
||||
|
||||
@@ -2,11 +2,11 @@ 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,
|
||||
@@ -32,14 +32,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 +55,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. */
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
@@ -254,7 +262,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 +302,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 +326,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 +361,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 &&
|
||||
|
||||
@@ -912,10 +912,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,
|
||||
};
|
||||
@@ -1092,6 +1089,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,
|
||||
|
||||
@@ -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 || ''),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
@@ -238,7 +239,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);
|
||||
@@ -265,8 +266,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,
|
||||
@@ -285,18 +295,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 };
|
||||
|
||||
@@ -8,7 +8,13 @@ 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,
|
||||
@@ -165,6 +171,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;
|
||||
@@ -246,6 +282,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({
|
||||
@@ -268,6 +305,7 @@ export function createLocalAdsbModels({
|
||||
tint: WHITE,
|
||||
colorBlend: aircraftModelBlend(false),
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(parts ? { parts } : {}),
|
||||
show: shown,
|
||||
});
|
||||
if (shown && record.ready) marker.modelOwnsVisual = true;
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -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,
|
||||
@@ -322,10 +321,7 @@ export function createMotion({
|
||||
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);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
@@ -41,15 +40,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
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -404,10 +404,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,
|
||||
};
|
||||
@@ -1059,6 +1056,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,
|
||||
|
||||
@@ -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\(/,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
|
||||
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
@@ -944,6 +945,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',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -216,3 +216,87 @@ test('back at live, the live poll goes out at once even while a snapshot at a ti
|
||||
assert.equal(Object.hasOwn(queries[1], 'atMs'), false);
|
||||
assert.equal(probe.applied.at(-1).rows.length, 1);
|
||||
});
|
||||
|
||||
test('back at live, only the first live vessel rows applied take over; a poll that fails or brings none says so', async () => {
|
||||
let answer = 'rows';
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
if (answer === 'fail') throw new Error('down');
|
||||
return {
|
||||
records:
|
||||
answer === 'rows'
|
||||
? [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }]
|
||||
: [],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal(await probe.resumeLive({}), true);
|
||||
await probe.methods.update();
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }, { complete: true }],
|
||||
);
|
||||
answer = 'none';
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
answer = 'fail';
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live while a live poll is already out, that poll takes over and its answer is awaited', async () => {
|
||||
let answer;
|
||||
const probe = ingestion({
|
||||
getSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
answer = () =>
|
||||
resolve({
|
||||
records: [
|
||||
{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 },
|
||||
],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
});
|
||||
}),
|
||||
});
|
||||
const poll = probe.methods.update();
|
||||
const resumed = probe.resumeLive({});
|
||||
answer();
|
||||
assert.equal(await resumed, true);
|
||||
await poll;
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }],
|
||||
);
|
||||
});
|
||||
|
||||
test('without AbortSignal.any a vessel request still gives up after its timeout', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const any = AbortSignal.any;
|
||||
AbortSignal.any = undefined;
|
||||
try {
|
||||
const probe = ingestion({
|
||||
getSnapshot: (_query, { signal }) =>
|
||||
new Promise((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason)),
|
||||
),
|
||||
});
|
||||
const resumed = probe.resumeLive({});
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(await resumed, false);
|
||||
assert.equal(probe.feed.loading, false);
|
||||
} finally {
|
||||
AbortSignal.any = any;
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,10 @@ import { createTesting } from './testing.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one vessel layer with application-owned scene services. */
|
||||
export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
@@ -58,6 +61,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
layer.source = source;
|
||||
},
|
||||
followsClock: () => followsClock(vesselState),
|
||||
timedAnswer: snapshotAnswer,
|
||||
reloadAtClock: () => vesselState.timeline.reload(),
|
||||
});
|
||||
// Vessels follow the world clock while the source declares a timeline.
|
||||
@@ -77,9 +81,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
state.feed.count = state.records.all.length;
|
||||
state.feed.lastUpdate = null;
|
||||
},
|
||||
resumeLive: () => {
|
||||
void parts.ingestion.loadLivePositions(vesselState.state.viewer);
|
||||
},
|
||||
resumeLive: () => parts.ingestion.resumeLive(vesselState.state.viewer),
|
||||
});
|
||||
Object.assign(
|
||||
layer,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { AIS_FIRST_CONNECT_LABEL } from './recordPolicy.js';
|
||||
import { viewAreaMovedEnough } from './viewArea.js';
|
||||
|
||||
/** Longest a vessel request may take before it is given up. */
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
// A portable export (package.json): no i18n here. The text stays English data
|
||||
// and the layer panel shows it translated.
|
||||
const msg = (text) => text;
|
||||
@@ -23,14 +26,47 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
followsClock = () => false,
|
||||
reloadAtClock = () => {},
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
async function loadLivePositions(viewer) {
|
||||
// The live load in flight: its result, and its request, whose `handover`
|
||||
// may still be set while it loads (see resumeLive).
|
||||
let liveLoad = null;
|
||||
|
||||
async function loadLivePositions(viewer, { handover = false } = {}) {
|
||||
// Following the world clock, the layer shows the snapshots loadAt applies.
|
||||
if (followsClock()) return;
|
||||
if (followsClock()) return false;
|
||||
// Back at live, a snapshot at a time still loading no longer applies:
|
||||
// it would hold the live poll back until the next refresh.
|
||||
if (feed.loading && feed.loadingAtTime) dropLoad();
|
||||
await loadPositions(viewer);
|
||||
// A live load already out answers this one too.
|
||||
if (feed.loading && liveLoad) {
|
||||
if (handover) liveLoad.request.handover = true;
|
||||
return liveLoad.promise;
|
||||
}
|
||||
const request = { handover };
|
||||
const promise = loadPositions(viewer, { request });
|
||||
const load = { request, promise };
|
||||
liveLoad = load;
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
if (liveLoad === load) liveLoad = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once (or take the live poll
|
||||
* already out), and let its snapshot stand in for every vessel. Those it has keep their
|
||||
* icon and model and move on from where they are; those it lacks go.
|
||||
* Resolves true once it is applied, else false (it could not be had).
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function resumeLive(viewer) {
|
||||
const applied = await loadLivePositions(viewer || readViewer(), {
|
||||
handover: true,
|
||||
});
|
||||
return applied === true;
|
||||
}
|
||||
|
||||
/** Let go of the load in flight, so another can start now. */
|
||||
@@ -44,10 +80,11 @@ export function createIngestion({
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every vessel 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}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async function loadAt(atMs, { signal = null, replace = false } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies: the
|
||||
@@ -56,7 +93,10 @@ export function createIngestion({
|
||||
return loadPositions(readViewer(), { atMs, replace, signal });
|
||||
}
|
||||
|
||||
async function loadPositions(viewer, { atMs, replace = false, signal } = {}) {
|
||||
async function loadPositions(
|
||||
viewer,
|
||||
{ atMs, replace = false, signal, request = null } = {},
|
||||
) {
|
||||
const timed = atMs !== undefined;
|
||||
if (!viewer || feed.loading) return false;
|
||||
feed.loading = true;
|
||||
@@ -65,18 +105,35 @@ export function createIngestion({
|
||||
const requestController = new AbortController();
|
||||
const requestSessionId = feed.sessionId;
|
||||
feed.abort = requestController;
|
||||
let timeout = null;
|
||||
|
||||
try {
|
||||
// Combine the layer's teardown-abort with a hard timeout so a hung upstream
|
||||
// can't wedge the poll indefinitely (parity with the track fetch + flights).
|
||||
const requestSignal =
|
||||
typeof AbortSignal.any === 'function'
|
||||
? AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(10000),
|
||||
...(signal ? [signal] : []),
|
||||
])
|
||||
: requestController.signal;
|
||||
let requestSignal;
|
||||
if (typeof AbortSignal.any === 'function')
|
||||
requestSignal = AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
...(signal ? [signal] : []),
|
||||
]);
|
||||
else {
|
||||
// Without it, the request's own controller takes the timeout and
|
||||
// the caller's abort.
|
||||
timeout = setTimeout(
|
||||
() =>
|
||||
requestController.abort(
|
||||
new DOMException('Vessel request timed out', 'TimeoutError'),
|
||||
),
|
||||
REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
signal?.addEventListener(
|
||||
'abort',
|
||||
() => requestController.abort(signal.reason),
|
||||
{ once: true },
|
||||
);
|
||||
requestSignal = requestController.signal;
|
||||
}
|
||||
// Ask for the vessels in view; a wide view asks for every vessel.
|
||||
const area = readArea(viewer);
|
||||
feed.lastArea = area;
|
||||
@@ -92,9 +149,10 @@ export function createIngestion({
|
||||
if (signal?.aborted) return false;
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return false;
|
||||
const takesOver = !timed && request?.handover === true;
|
||||
setSourceLabel(snapshot.source);
|
||||
// Map observations into the existing display store; source fields stop here.
|
||||
applyAisFeedSnapshot(viewer, {
|
||||
const applied = applyAisFeedSnapshot(viewer, {
|
||||
rows: snapshot.records.map(vesselDisplayRow),
|
||||
observedAtMs: snapshot.observedAtMs,
|
||||
freshness: snapshot.freshness,
|
||||
@@ -112,8 +170,12 @@ export function createIngestion({
|
||||
silentForMs: snapshot.silentForMs,
|
||||
reconnectAttempt: snapshot.reconnectAttempt,
|
||||
...(replace && { replace }),
|
||||
...(takesOver && { handover: true }),
|
||||
});
|
||||
return true;
|
||||
// Back at live, a snapshot that placed no vessel could not take over.
|
||||
if (takesOver) return applied.reconciled;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (error) {
|
||||
// A snapshot at a time the source dropped for a newer one is no failure.
|
||||
if (timed && error?.name === 'AbortError') throw error;
|
||||
@@ -130,6 +192,7 @@ export function createIngestion({
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
if (
|
||||
feed.abort === requestController &&
|
||||
feed.sessionId === requestSessionId
|
||||
@@ -197,6 +260,7 @@ export function createIngestion({
|
||||
applyRows(viewer, snapshot.acceptedRows, {
|
||||
complete: payload?.complete !== false,
|
||||
...(payload?.replace && { replace: true }),
|
||||
...(payload?.handover && { handover: true }),
|
||||
});
|
||||
feed.count = readCount();
|
||||
feed.stale =
|
||||
@@ -266,6 +330,7 @@ export function createIngestion({
|
||||
|
||||
return {
|
||||
loadLivePositions,
|
||||
resumeLive,
|
||||
loadAt,
|
||||
refreshIfMoved,
|
||||
ownsAisRequest,
|
||||
|
||||
@@ -7,6 +7,10 @@ import { createVesselIconBook } from './iconBook.js';
|
||||
import { liftedForHorizon } from '../../geo/horizon.js';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { VESSEL_KIND_STYLES } from '../../data/vesselTypes.js';
|
||||
import { AID_TO_NAVIGATION_STYLE } from '../../data/vesselLabels.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
|
||||
/** A query port with nothing on screen: the viewer doubles have no scene. */
|
||||
const offscreen = {
|
||||
@@ -90,7 +94,7 @@ const snapshot = (records, extra = {}) => ({
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('vessel construction is inert and each instance owns its records, icon cache and clock', () => {
|
||||
test('vessel construction is inert and each instance owns its records and clock', () => {
|
||||
let requested = 0;
|
||||
const source = {
|
||||
getSnapshot() {
|
||||
@@ -99,8 +103,7 @@ test('vessel construction is inert and each instance owns its records, icon cach
|
||||
};
|
||||
const one = createVesselState({ source, services: services() });
|
||||
const two = createVesselState({ source, services: services() });
|
||||
for (const key of ['state', 'shipIconCache'])
|
||||
assert.notEqual(one[key], two[key]);
|
||||
assert.notEqual(one.state, two.state);
|
||||
assert.notEqual(one.state.records.byId, two.state.records.byId);
|
||||
assert.notEqual(one.state.feed, two.state.feed);
|
||||
assert.notEqual(one.state.records.all, two.state.records.all);
|
||||
@@ -557,7 +560,7 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
|
||||
test('an aid to navigation is drawn as the upright buoy, a vessel as its kind’s hull turned with course', async () => {
|
||||
const aid = {
|
||||
...observation('993672001'),
|
||||
mmsi: '993672001',
|
||||
@@ -565,26 +568,39 @@ test('an aid to navigation is drawn as a disc, a vessel as its chevron', async (
|
||||
speedMps: 0,
|
||||
};
|
||||
const ship = { ...observation('366999002'), type: 'Cargo' };
|
||||
const sailing = { ...observation('366999003'), type: '36' };
|
||||
const { layer, icons } = setup({
|
||||
async getSnapshot() {
|
||||
return snapshot([aid, ship]);
|
||||
return snapshot([aid, ship, sailing]);
|
||||
},
|
||||
});
|
||||
await layer.update();
|
||||
const svgOf = (id) => {
|
||||
const itemOf = (id) => {
|
||||
assert.ok(icons.has(id), id);
|
||||
return atob(icons.item(id).image.split(',')[1]);
|
||||
return icons.item(id);
|
||||
};
|
||||
assert.match(svgOf('993672001'), /<circle/);
|
||||
const buoy = itemOf('993672001');
|
||||
assert.equal(buoy.image, aidSprite());
|
||||
assert.equal(buoy.rotationMode, 'screen', 'upright');
|
||||
assert.equal(buoy.rotation, 0, 'never turned');
|
||||
assert.deepEqual(buoy.color, cssColor(AID_TO_NAVIGATION_STYLE.css));
|
||||
// The source's virtual flag reaches the layer's record.
|
||||
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
|
||||
assert.equal(recordOf('993672001').virtual, false);
|
||||
assert.equal(recordOf('366999002').virtual, false);
|
||||
assert.doesNotMatch(svgOf('993672001'), /<path/);
|
||||
assert.match(svgOf('366999002'), /<path/);
|
||||
const cargo = itemOf('366999002');
|
||||
assert.equal(cargo.image, vesselSprite('cargo'));
|
||||
assert.equal(cargo.rotationMode, 'course');
|
||||
assert.deepEqual(cargo.color, cssColor(VESSEL_KIND_STYLES.cargo.css));
|
||||
const sail = itemOf('366999003');
|
||||
assert.equal(sail.image, vesselSprite('sailing'));
|
||||
assert.deepEqual(sail.color, cssColor(VESSEL_KIND_STYLES.sailing.css));
|
||||
// Every vessel and aid draws the same size before its speed scale.
|
||||
assert.deepEqual(cargo.size, buoy.size);
|
||||
assert.deepEqual(sail.size, buoy.size);
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation keeps its disc and its virtual flag', async () => {
|
||||
test('a virtual aid to navigation keeps its buoy and its virtual flag', async () => {
|
||||
const aid = {
|
||||
...observation('993672009'),
|
||||
mmsi: '993672009',
|
||||
@@ -599,7 +615,7 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async ()
|
||||
await layer.update();
|
||||
assert.ok(icons.has('993672009'));
|
||||
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
|
||||
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
|
||||
assert.equal(icons.item('993672009').image, aidSprite());
|
||||
});
|
||||
|
||||
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ function harness({ placement = null, following = false } = {}) {
|
||||
const visuals = [];
|
||||
const state = { selectedRecord: null, trailId: null };
|
||||
const records = new VesselRecords({ now: () => 5_000_000 });
|
||||
const primitives = [];
|
||||
const rendering = {
|
||||
ensureCollections() {},
|
||||
makeOccluder: () => null,
|
||||
@@ -28,8 +29,12 @@ function harness({ placement = null, following = false } = {}) {
|
||||
visuals.push(record.id);
|
||||
return { billboard: null };
|
||||
},
|
||||
addRecordPrimitives() {},
|
||||
removeRecordPrimitives() {},
|
||||
addRecordPrimitives(record) {
|
||||
primitives.push(['add', record.id]);
|
||||
},
|
||||
removeRecordPrimitives(record) {
|
||||
primitives.push(['remove', record.id]);
|
||||
},
|
||||
shipIcon: () => 'icon',
|
||||
shipScale: () => 1,
|
||||
syncRecordIcon() {},
|
||||
@@ -41,12 +46,15 @@ function harness({ placement = null, following = false } = {}) {
|
||||
records,
|
||||
rendering,
|
||||
tracking: {},
|
||||
selection: {},
|
||||
cards: {},
|
||||
selection: { clearVesselInspection() {} },
|
||||
cards: { updateSelectedVesselHud() {} },
|
||||
followsClock: () => following,
|
||||
});
|
||||
return {
|
||||
visuals,
|
||||
primitives,
|
||||
state,
|
||||
records,
|
||||
reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
|
||||
};
|
||||
}
|
||||
@@ -105,3 +113,61 @@ test('following the world clock, or rows at another time, tell the placement not
|
||||
harness({ placement }).reconcile([row('a')], { replace: true });
|
||||
assert.deepEqual(told, []);
|
||||
});
|
||||
|
||||
test('back at live, the first live vessel rows keep the vessels they have, drop the rest, and are told to the placement', () => {
|
||||
const { told, forgotten, placement } = recording();
|
||||
const probe = harness({ placement });
|
||||
probe.reconcile([row('a'), row('b')]);
|
||||
probe.primitives.length = 0;
|
||||
told.length = 0;
|
||||
probe.reconcile(
|
||||
[row('a', { lat: 52, last_position_epoch: 1_060 }), row('c')],
|
||||
{ handover: true },
|
||||
);
|
||||
// The vessel it has keeps its icon; the one it lacks goes; a new one is
|
||||
// added.
|
||||
assert.deepEqual(probe.primitives, [
|
||||
['add', 'c'],
|
||||
['remove', 'b'],
|
||||
]);
|
||||
assert.deepEqual(forgotten, ['b']);
|
||||
assert.deepEqual(
|
||||
told.map(([id]) => id),
|
||||
['a', 'c'],
|
||||
'live fixes, told to the placement',
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, partial vessel rows keep the vessels they lack whose newest fix is recent; complete rows pin the selected one', () => {
|
||||
const probe = harness();
|
||||
// The records' clock reads 5 000 s: 'recent' was fixed 100 s before it,
|
||||
// 'old' and 'picked' over an hour before.
|
||||
probe.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('old'),
|
||||
row('picked'),
|
||||
]);
|
||||
probe.state.selectedRecord = probe.records.byId.get('picked');
|
||||
probe.primitives.length = 0;
|
||||
probe.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
complete: false,
|
||||
handover: true,
|
||||
});
|
||||
// Partial rows prove no absence for a recent fix; an old one is gone.
|
||||
assert.ok(probe.records.byId.has('recent'));
|
||||
assert.equal(probe.records.byId.get('recent').motion, null);
|
||||
assert.equal(probe.records.byId.has('old'), false);
|
||||
|
||||
const complete = harness();
|
||||
complete.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('picked'),
|
||||
]);
|
||||
complete.state.selectedRecord = complete.records.byId.get('picked');
|
||||
complete.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
handover: true,
|
||||
});
|
||||
// Complete rows judge as a refresh does: the selected vessel is pinned for
|
||||
// a few refreshes, the rest go.
|
||||
assert.deepEqual([...complete.records.byId.keys()].sort(), ['c', 'picked']);
|
||||
});
|
||||
@@ -103,7 +103,12 @@ export class VesselRecords {
|
||||
* between the two (see motion.js). `replace`: the rows are the world at
|
||||
* another time (the clock jumped), so they stand in for every vessel: one
|
||||
* they lack is gone at once, selected or not, and none moves from where it
|
||||
* was at the time the clock left.
|
||||
* was at the time the clock left. `handover`: the first live rows after the
|
||||
* clock came back to live: a vessel they have moves to its live fix, not
|
||||
* from where it was at the time the clock left; one they lack is judged
|
||||
* as any live refresh judges it (a partial refresh, the selected vessel),
|
||||
* by how old its newest fix is rather than when it was loaded, and holds
|
||||
* at its last position meanwhile.
|
||||
*/
|
||||
reconcile(
|
||||
rows,
|
||||
@@ -112,6 +117,7 @@ export class VesselRecords {
|
||||
selectedRecord = null,
|
||||
cap = Infinity,
|
||||
replace = false,
|
||||
handover = false,
|
||||
follow = false,
|
||||
},
|
||||
effects,
|
||||
@@ -152,7 +158,7 @@ export class VesselRecords {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
if (replace) {
|
||||
if (replace || handover) {
|
||||
record.motion = null;
|
||||
record.fixes = next.fixes;
|
||||
} else if (follow) {
|
||||
@@ -195,6 +201,13 @@ export class VesselRecords {
|
||||
}
|
||||
for (const [id, record] of this.byId) {
|
||||
if (seen.has(id)) continue;
|
||||
if (handover) {
|
||||
record.motion = null;
|
||||
record.fixes = null;
|
||||
// Loaded for another time: last seen at its newest fix.
|
||||
const fixMs = finiteNumber(record.lastPositionEpoch);
|
||||
if (fixMs !== null) record.receivedAtMs = fixMs * 1000;
|
||||
}
|
||||
if (replace) {
|
||||
effects.remove(record, record === selectedRecord);
|
||||
this.byId.delete(id);
|
||||
|
||||
@@ -43,7 +43,11 @@ import {
|
||||
vesselModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { isAidToNavigation } from '../../data/vesselTypes.js';
|
||||
import { vesselPartState } from '../../data/modelPartDrivers.js';
|
||||
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
/** A moving vessel's next frame is asked for once it would move this far on
|
||||
* screen (pixels), so it glides when it moves visibly and the scene idles
|
||||
@@ -55,11 +59,16 @@ const PLACEMENT_FRAME_MS = 1000;
|
||||
* ms), so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
|
||||
/** The ship artwork's own raster size (px). */
|
||||
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
|
||||
const SHIP_ICON_PX = 32;
|
||||
/** A selected vessel's or aid's tint. */
|
||||
const SELECTED_TINT = Object.freeze([1, 1, 1, 1]);
|
||||
|
||||
let instances = 0;
|
||||
|
||||
/** Tint by CSS colour: a handful of type colours. */
|
||||
const tints = new Map();
|
||||
|
||||
/** How often the vessels near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
|
||||
@@ -405,6 +414,7 @@ export function createRendering({
|
||||
/** The icon item a record draws, as it now is. */
|
||||
function iconItem(record, visual) {
|
||||
const selected = record === state.selectedRecord;
|
||||
const aid = isAidToNavigation(record);
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
// Following the clock, not there yet at the time drawn.
|
||||
visual.seen = seenYet(record);
|
||||
@@ -418,11 +428,14 @@ export function createRendering({
|
||||
// is not there yet.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
|
||||
pos: plan?.pos ?? visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
image: shipIcon(record),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
// Selection changes the colour only, never the size.
|
||||
// Tinted by type; selection changes the colour only, never the size.
|
||||
color: selected ? SELECTED_TINT : shipTint(record),
|
||||
scale: shipScale(record),
|
||||
rotationMode: 'course',
|
||||
// An aid's buoy stands upright on screen; a vessel turns with course.
|
||||
rotationMode: aid ? 'screen' : 'course',
|
||||
rotation: 0,
|
||||
// Held on course, or along its track on the renderer's clock;
|
||||
// `course` for renderers without motion segments.
|
||||
course: courseDeg,
|
||||
@@ -519,40 +532,33 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
|
||||
* The shape points north (up) so the row's course maps directly to heading.
|
||||
* An aid to navigation, which has no heading, is a ringed disc instead.
|
||||
* One icon is generated per color+variant and shares one atlas slot.
|
||||
* @param {Object} record - Vessel record (drives per-type tint).
|
||||
* @param {boolean} selected - True for the white/brighter selected variant.
|
||||
* The sprite a vessel is drawn as: the white hull of its kind
|
||||
* (`vesselKind`), bow up so the row's course turns it to its heading, or
|
||||
* for an aid to navigation the buoy. The layer tints it
|
||||
* (`shipTint`), so each shape takes one icon-atlas slot.
|
||||
* @param {Object} record - Vessel record.
|
||||
* @returns {string} SVG data URL.
|
||||
*/
|
||||
|
||||
function shipIcon(record, selected) {
|
||||
const aid = isAidToNavigation(record);
|
||||
const cssColor = selected
|
||||
? '#ffffff'
|
||||
: aid
|
||||
? AID_TO_NAVIGATION_STYLE.css
|
||||
: vesselTypeCss(record.type);
|
||||
const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`;
|
||||
if (vesselState.shipIconCache.has(key))
|
||||
return vesselState.shipIconCache.get(key);
|
||||
function shipIcon(record) {
|
||||
return isAidToNavigation(record)
|
||||
? aidSprite()
|
||||
: vesselSprite(vesselKind(record.type));
|
||||
}
|
||||
|
||||
const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)';
|
||||
const strokeWidth = selected ? 1.1 : 0.7;
|
||||
const shape = aid
|
||||
? `<circle r="8" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth * 2}"/>
|
||||
<circle r="3" fill="${stroke}"/>`
|
||||
: `<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>`;
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
|
||||
<g transform="translate(16,16)">
|
||||
${shape}
|
||||
</g>
|
||||
</svg>`;
|
||||
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
|
||||
vesselState.shipIconCache.set(key, icon);
|
||||
return icon;
|
||||
/**
|
||||
* A vessel's tint, `[r, g, b, a]`: its type's colour (vesselLabels.js,
|
||||
* shared with its card), an aid's bone white.
|
||||
* @param {Object} record - Vessel record.
|
||||
*/
|
||||
|
||||
function shipTint(record) {
|
||||
const css = isAidToNavigation(record)
|
||||
? AID_TO_NAVIGATION_STYLE.css
|
||||
: vesselTypeCss(record.type);
|
||||
let tint = tints.get(css);
|
||||
if (!tint) tints.set(css, (tint = Object.freeze(cssColor(css))));
|
||||
return tint;
|
||||
}
|
||||
|
||||
// Under the DISPLAY rail's 3D toggle, vessels near the camera are drawn as
|
||||
@@ -578,6 +584,13 @@ export function createRendering({
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
// A hull below the waterline would show through a plain globe.
|
||||
waterline: true,
|
||||
// Its radar sweeps while it is under way (speed in knots).
|
||||
partState: (item, table) =>
|
||||
vesselPartState(table, {
|
||||
speedMps: Number.isFinite(item.record?.speed)
|
||||
? item.record.speed * KNOT_MPS
|
||||
: null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const KNOT_MPS = 1852 / 3600;
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
const finiteOrNaN = (value) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : NaN;
|
||||
|
||||
@@ -34,11 +35,15 @@ export function createVesselSnapshotRenderer({
|
||||
cards,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
/** `replace`: the rows are the world at another time (see VesselRecords). */
|
||||
/**
|
||||
* `replace`: the rows are the world at another time (see VesselRecords).
|
||||
* `handover`: the first live rows after the clock came back to live (see
|
||||
* VesselRecords); they are live fixes.
|
||||
*/
|
||||
function reconcileVessels(
|
||||
viewer,
|
||||
rows,
|
||||
{ complete = true, replace = false } = {},
|
||||
{ complete = true, replace = false, handover = false } = {},
|
||||
) {
|
||||
rendering.ensureCollections(viewer);
|
||||
const occluder = rendering.makeOccluder();
|
||||
@@ -57,6 +62,7 @@ export function createVesselSnapshotRenderer({
|
||||
selectedRecord: state.selectedRecord,
|
||||
cap: rendering.renderRowLimit(),
|
||||
...(replace && { replace }),
|
||||
...(handover && { handover }),
|
||||
...(follow && { follow }),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -53,10 +53,6 @@ export function createVesselState({ source, services }) {
|
||||
|
||||
vesselState._geoidReady = false;
|
||||
|
||||
/** @type {Map<string, string>} `${cssColor}:${variant}` -> chevron SVG data URL */
|
||||
|
||||
vesselState.shipIconCache = new Map();
|
||||
|
||||
/** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */
|
||||
|
||||
vesselState._unkeyedIconSequence = 0;
|
||||
|
||||
Reference in new issue
Block a user