Merge main (663b56f62, #1755) into the renderer branch

This commit is contained in:
Sameh Khamis committed 2026-11-15 16:34:05 -08:00
commit a0d299523d
91 files changed
+1793 -396

No files matched your search

+15 -1
View File
@@ -1,4 +1,5 @@
import { stickyNumber, stickyText } from '../../data/aircraftMeta.js';
import { courseFromFixes } from '../../data/courseFromFixes.js';
import {
geoidSurfaceLastResortM,
pickRenderAltitudeM,
@@ -291,6 +292,12 @@ export class FlightRecords {
observation.positionTimeMs > 0
? observation.positionTimeMs
: this.now();
const course = courseFromFixes(prevMeta?.courseAnchor, {
lat,
lon,
ms: fixEpochMs,
speedMps: velocity,
});
const meta = {
sourceReference: observation.reference,
observedReceiptMs: this.now(),
@@ -309,7 +316,14 @@ export class FlightRecords {
// applies to contacts that actually flew this session.
wasAirborne: prevMeta?.wasAirborne === true || !onGround,
velocity: stickyNumber(velocity, prevMeta?.velocity, 0),
true_track: stickyNumber(true_track, prevMeta?.true_track, 0),
// With no reported track or true heading, a moving contact faces the
// way its fixes went (src/data/courseFromFixes.js); else the last one.
true_track: stickyNumber(
true_track,
course.courseDeg ?? prevMeta?.true_track,
0,
),
courseAnchor: course.anchor,
category: cat,
// An adsbdb-enriched type code outranks the coarse OpenSky category.
klass: classifyAircraft({
+46
View File
@@ -319,3 +319,49 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
).meta;
assert.equal(unloaded.onGround, false);
});
test('a contact reported with no course faces the way its newer fixes went', () => {
const store = records();
const T = 1700000000000;
const taxi = (latitude, seconds, fields = {}) =>
store.receive(
observation({
latitude,
longitude: -97.6588,
courseDeg: null,
onGround: true,
speedMps: 8,
positionTimeMs: T + seconds * 1000,
...fields,
}),
view(),
);
const course = () => store.data.get('abc123').true_track;
taxi(30.1908, 0);
assert.equal(course(), 0, 'nothing known yet');
// Fixes a second apart, 8 m each: they add up until 30 m are covered.
taxi(30.19073, 1);
taxi(30.19066, 2);
assert.equal(course(), 0, 'under 30 m: still nothing');
taxi(30.19059, 3);
taxi(30.19052, 4);
assert.ok(Math.abs(course() - 180) < 0.1, 'southbound');
// An older fix from another feed, behind it: never turns it around.
taxi(30.1912, 2);
assert.ok(Math.abs(course() - 180) < 0.1, 'an older fix gives no course');
taxi(30.1901, 8);
assert.ok(Math.abs(course() - 180) < 0.1);
// Standing (reported under 2 m/s) with 40 m of position noise: kept.
taxi(30.18974, 12, { speedMps: 0.5, longitude: -97.6584 });
assert.ok(
Math.abs(course() - 180) < 0.1,
'a standing contact keeps its course',
);
// A reported course always wins.
taxi(30.189, 16, { courseDeg: 175 });
assert.equal(course(), 175);
// A reset forgets where it was: it starts again from north.
store.reset();
taxi(30.188, 20);
assert.equal(course(), 0);
});
+17 -22
View File
@@ -7,10 +7,10 @@ import { formatNumber, msg, t } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
GNSS_LEVEL_COLORS,
GNSS_MIN_AIRCRAFT,
GNSS_WINDOW_MS,
accumulateGnssObservations,
binGnssCells,
gnssCellRing,
gnssProvenance,
pruneGnssObservations,
} from './records.js';
@@ -74,7 +74,7 @@ export function defaultGnssViewAnchor(viewer) {
/**
* Own one GNSS navigation-integrity display: rolling integrity observations
* around the views the user visits, binned into cells coloured by the
* around the views the user visits, binned into H3 hexagons coloured by the
* gpsjam low-accuracy score. Share links retain token 3.
*/
export function createGnssIntegrityLayer({
@@ -190,20 +190,19 @@ export function createGnssIntegrityLayer({
if (signature === _signature) return;
_signature = signature;
_fills.set(
_cells.map((cell) => ({
id: `${layer.id}:${cell.id}`,
geometry: {
kind: 'rectangle',
rect: {
west: cell.west,
south: cell.south,
east: cell.east,
north: cell.north,
},
},
fill: hexColor(GNSS_LEVEL_COLORS[cell.level], FILL_ALPHA[cell.level]),
height: 'clampGround',
})),
_cells.map((cell) => {
const ring = gnssCellRing(cell);
const positions = [];
for (let i = 0; i < ring.length; i += 2)
positions.push({ lon: ring[i], lat: ring[i + 1] });
return {
id: `${layer.id}:${cell.id}`,
// H3 edges are great-circle arcs, as a polygon's edges are drawn.
geometry: { kind: 'polygon', rings: [positions] },
fill: hexColor(GNSS_LEVEL_COLORS[cell.level], FILL_ALPHA[cell.level]),
height: 'clampGround',
};
}),
);
}
@@ -386,7 +385,7 @@ export function createGnssIntegrityLayer({
}`
: ''),
infoTitle: t(
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.',
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank areas had no aircraft reporting navigation accuracy in the window.',
),
legend: ['high', 'medium', 'low'].map((level, index) => ({
label: t(LEVEL_LABELS[level]),
@@ -395,11 +394,7 @@ export function createGnssIntegrityLayer({
...(index === 0
? {
blurb: t(
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
{
aircraft: formatNumber(GNSS_MIN_AIRCRAFT),
minutes: formatNumber(provenance.window.minutes),
},
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
),
}
: {}),
+25 -17
View File
@@ -69,8 +69,8 @@ function harness(
const MIN = 60_000;
const threeHealthy = () => [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
];
const flush = () => new Promise((resolve) => setImmediate(resolve));
@@ -246,25 +246,29 @@ test('an enabled refresh bins the snapshot into coloured ground cells', async ()
assert.equal(fills().show, true);
assert.equal(await layer.update(), true);
const cells = [...fills().items.values()];
assert.equal(cells.length, 1, 'the one-aircraft cell is withheld');
assert.equal(cells[0].id, 'gnss-integrity:280:420');
assert.deepEqual(cells[0].geometry, {
kind: 'rectangle',
rect: { west: 30, south: 50, east: 30.5, north: 50.5 },
});
assert.equal(cells[0].height, 'clampGround');
assert.equal(cells.length, 2, 'a one-aircraft cell is shown too');
assert.deepEqual(
cells.map(({ id }) => id),
['gnss-integrity:841e631ffffffff', 'gnss-integrity:841f6b3ffffffff'],
);
for (const cell of cells) {
assert.equal(cell.geometry.kind, 'polygon');
assert.equal(cell.geometry.rings.length, 1);
assert.equal(cell.geometry.rings[0].length, 6, 'a hexagon');
assert.equal(cell.height, 'clampGround');
}
assert.equal(fills().spec.pickable, false, 'cells never take part in picks');
const stats = layer.getStats();
assert.equal(stats.count, 1);
assert.equal(stats.count, 2);
assert.equal(stats.error, null);
assert.equal(stats.fallback, false);
const { legend } = layer.getRowControls();
assert.deepEqual(
legend.map(({ count }) => count),
[1, 0, 0],
[1, 0, 1],
);
assert.match(legend[0].blurb, /not a detection/);
assert.match(legend[0].blurb, /need 3 aircraft/);
assert.doesNotMatch(legend[0].blurb, /need \d+ aircraft/);
});
test('the visible layer leads with low navigation accuracy and exposes its provenance', async () => {
@@ -296,10 +300,10 @@ test('the visible layer leads with low navigation accuracy and exposes its prove
assert.deepEqual(layer.provenance.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(layer.provenance.aggregation.grid, 'h3');
assert.equal(layer.provenance.aggregation.h3Resolution, 4);
assert.equal(layer.provenance.interpretation.validated, false);
assert.equal(layer.getStats().provenance, layer.provenance);
});
@@ -311,8 +315,8 @@ test('a failed refresh keeps the last cells and reports the error', async () =>
return {
rows: [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
stale: true,
};
@@ -339,7 +343,11 @@ test('observations expire with the window, and disable aborts the request in fli
layer.enable();
let result = layer.update();
pending.resolve({
rows: [row('a1', 1.1, false), row('a2', 1.2, false), row('a3', 1.3, false)],
rows: [
row('a1', 1.1, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
});
assert.equal(await result, true);
assert.equal(layer.getStats().count, 1);
+48 -34
View File
@@ -1,5 +1,5 @@
/**
* Low navigation accuracy reported by ADS-B aircraft, binned into cells.
* Low navigation accuracy reported by ADS-B aircraft, binned into H3 cells.
*
* Aircraft broadcasting DO-260 version 1/2 ADS-B report how much they trust
* their own position: NIC (integrity containment radius) and NACp (position
@@ -16,9 +16,12 @@
* from the US 14 CFR 91.227(c) ADS-B Out performance minima, which are not
* a published interference classifier) or the readsb/tar1090 `gpsOkBefore`
* flag. gpsjam.org does not publish its per-aircraft threshold.
* - Cell aggregation: gpsjam.org's published formula and 2% / 10% bands.
* - Cell aggregation: gpsjam.org's published formula, 2% / 10% bands and
* hex grid (H3 resolution 4). Every cell with an aircraft is shown, as on
* gpsjam.org; the one-aircraft discount is the only small-sample guard.
* - Window: a GEV-defined rolling 30 minutes over the views the user visits.
*/
import { cellToBoundary, cellToLatLng, latLngToCell } from 'h3-js';
/** Position source can switch to MLAT after GPS loss; quality must remain aircraft-reported. */
const QUALIFYING_TYPES = new Set(['adsb_icao', 'mlat']);
@@ -30,10 +33,8 @@ export const GNSS_NIC_THRESHOLD = 7;
export const GNSS_NACP_THRESHOLD = 8;
/** Positions older than this are not current evidence of the local sky. */
const MAX_POSITION_AGE_S = 60;
/** Cell edge in degrees: roughly 55 km north-south, similar in area to an H3 res-4 cell. */
export const GNSS_CELL_DEG = 0.5;
/** Hide sparse one- and two-aircraft cells; the aggregation separately discounts one bad report. */
export const GNSS_MIN_AIRCRAFT = 3;
/** H3 resolution of the cells, gpsjam.org's grid: hexagons of about 1,770 km² (22.6 km edge). */
export const GNSS_H3_RESOLUTION = 4;
/** Rolling window over which aircraft seen in a cell are counted. */
export const GNSS_WINDOW_MS = 30 * 60_000;
/** gpsjam.org band edges, in percent of aircraft (after discounting one). */
@@ -68,14 +69,14 @@ export function gnssProvenance({ windowMs = GNSS_WINDOW_MS } = {}) {
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: Object.freeze([GNSS_MEDIUM_PERCENT, GNSS_HIGH_PERCENT]),
grid: 'h3',
h3Resolution: GNSS_H3_RESOLUTION,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
}),
window: Object.freeze({
minutes: windowMs / 60_000,
scope: 'visited-view',
cellDeg: GNSS_CELL_DEG,
minAircraft: GNSS_MIN_AIRCRAFT,
definedBy: 'GEV',
}),
state: Object.freeze({
@@ -161,11 +162,30 @@ export function normalizeGnssAircraft(payload) {
return rows;
}
/** Stable key of the cell containing a position. */
export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
const row = Math.floor((Math.min(lat, 89.999999) + 90) / cellDeg);
const col = Math.floor((Math.min(lon, 179.999999) + 180) / cellDeg);
return `${row}:${col}`;
/** Stable key of the cell containing a position: its H3 index. */
export function gnssCellKey(lat, lon, resolution = GNSS_H3_RESOLUTION) {
return latLngToCell(lat, lon, resolution);
}
/**
* The ring to draw for a cell, as flat `[lon, lat, lon, lat, ...]` degrees.
* Longitudes are unwrapped to within 180° of the cell centre, so a cell
* across the antimeridian stays one narrow polygon (some longitudes then lie
* just outside ±180°) instead of spanning the globe. A cell around a pole
* keeps its full turn of longitudes; drawn on the globe it is still small.
*
* @param {{lat: number, lon: number, boundary: {lat: number, lon: number}[]}} cell
* @returns {number[]}
*/
export function gnssCellRing(cell) {
const ring = [];
for (const { lat, lon } of cell.boundary) {
let unwrapped = lon;
while (unwrapped - cell.lon > 180) unwrapped -= 360;
while (unwrapped - cell.lon < -180) unwrapped += 360;
ring.push(unwrapped, lat);
}
return ring;
}
/**
@@ -183,7 +203,7 @@ export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
* @param {Map<string, {cell: string, seenAt: number, degradedAt: number|null}>} store
* @param {ReturnType<typeof normalizeGnssAircraft>} rows
* @param {number} nowMs
* @param {{windowMs?: number, cellDeg?: number, observedAt?: number}} [options]
* @param {{windowMs?: number, resolution?: number, observedAt?: number}} [options]
* `observedAt` is the snapshot's observation time (defaults to `nowMs`;
* a future time is clamped to `nowMs`, a non-finite one adds nothing).
* @returns {Map} The same store, pruned to the window.
@@ -194,7 +214,7 @@ export function accumulateGnssObservations(
nowMs,
{
windowMs = GNSS_WINDOW_MS,
cellDeg = GNSS_CELL_DEG,
resolution = GNSS_H3_RESOLUTION,
observedAt = nowMs,
} = {},
) {
@@ -202,7 +222,7 @@ export function accumulateGnssObservations(
if (Number.isFinite(at) && nowMs - at <= windowMs) {
for (const row of rows || []) {
if (!Number.isFinite(row?.lat) || !Number.isFinite(row?.lon)) continue;
const cell = gnssCellKey(row.lat, row.lon, cellDeg);
const cell = gnssCellKey(row.lat, row.lon, resolution);
const key = `${row.hex}|${cell}`;
const previous = store.get(key);
const previousDegradedAt = previous?.degradedAt ?? null;
@@ -264,16 +284,16 @@ export function gnssIntegrityLevel(total, degraded) {
}
/**
* Aggregate the observation store into displayable cells. Expects a store
* already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`.
* Aggregate the observation store into displayable cells, one per H3 cell
* with at least one aircraft (gpsjam.org has no minimum count). Expects a
* store already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`. `lat`/`lon` is the cell centre and `boundary` its
* vertices in order (six for a hexagon, five for a pentagon), with
* longitudes in -180..180; `gnssCellRing` gives the ring to draw.
*
* @returns {{id: string, south: number, west: number, north: number, east: number, lat: number, lon: number, aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
* @returns {{id: string, lat: number, lon: number, boundary: {lat: number, lon: number}[], aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
*/
export function binGnssCells(
store,
{ cellDeg = GNSS_CELL_DEG, minAircraft = GNSS_MIN_AIRCRAFT } = {},
) {
export function binGnssCells(store) {
const tallies = new Map();
for (const { cell, degradedAt } of store.values()) {
const tally = tallies.get(cell) || { aircraft: 0, degraded: 0 };
@@ -283,22 +303,16 @@ export function binGnssCells(
}
const cells = [];
for (const [id, { aircraft, degraded }] of tallies) {
if (aircraft < minAircraft) continue;
const [row, col] = id.split(':').map(Number);
const south = row * cellDeg - 90;
const west = col * cellDeg - 180;
const [lat, lon] = cellToLatLng(id);
const { percent, level, state, interpretation } = gnssIntegrityLevel(
aircraft,
degraded,
);
cells.push({
id,
south,
west,
north: south + cellDeg,
east: west + cellDeg,
lat: south + cellDeg / 2,
lon: west + cellDeg / 2,
lat,
lon,
boundary: cellToBoundary(id).map(([lat, lon]) => ({ lat, lon })),
aircraft,
degraded,
percentDegraded: Math.round(percent * 10) / 10,
+145 -23
View File
@@ -1,12 +1,17 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getResolution, isPentagon, isValidCell } from 'h3-js';
import {
accumulateGnssObservations,
binGnssCells,
GNSS_CLASSIFIER,
GNSS_H3_RESOLUTION,
GNSS_HIGH_PERCENT,
GNSS_MEDIUM_PERCENT,
GNSS_PROVENANCE,
GNSS_WINDOW_MS,
gnssCellKey,
gnssCellRing,
gnssIntegrityLevel,
gnssProvenance,
normalizeGnssAircraft,
@@ -117,13 +122,87 @@ test('low NIC, low NACp or a readsb GPS-loss flag each mark an aircraft degraded
);
});
test('cell keys are stable half-degree bins, clamped at the poles and antimeridian', () => {
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.4, 19.6));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.6, 19.9));
assert.equal(gnssCellKey(90, 180), gnssCellKey(89.9, 179.9));
assert.equal(gnssCellKey(-90, -180), '0:0');
// Just south-west of the origin falls in the last cell before 0°, not cell 0.
assert.equal(gnssCellKey(-0.1, -0.1), '179:359');
test('cell keys are the H3 resolution-4 cells gpsjam.org uses', () => {
assert.equal(GNSS_H3_RESOLUTION, 4);
// Kraków: a known lat/lon lands in its known res-4 hexagon.
assert.equal(gnssCellKey(50.1, 19.9), '841e2e7ffffffff');
assert.equal(getResolution(gnssCellKey(50.1, 19.9)), 4);
// Nearby points share the hexagon; a point ~50 km north does not.
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.12, 19.95));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.55, 19.9));
// The poles and both sides of the antimeridian still key valid cells.
for (const [lat, lon] of [
[90, 180],
[-90, -180],
[0, 179.99],
[0, -179.99],
]) {
const key = gnssCellKey(lat, lon);
assert.ok(isValidCell(key), `${lat},${lon} → ${key}`);
assert.equal(getResolution(key), 4);
}
});
const cellAt = (lat, lon) => {
const store = new Map();
accumulateGnssObservations(
store,
[{ hex: 'c1', lat, lon, degraded: false }],
0,
);
return binGnssCells(store)[0];
};
test('a cell carries its H3 centre and hexagon boundary', () => {
const cell = cellAt(50.1, 19.9);
assert.equal(cell.id, '841e2e7ffffffff');
assert.ok(Math.abs(cell.lat - 50.17184) < 1e-4);
assert.ok(Math.abs(cell.lon - 20.12566) < 1e-4);
assert.equal(cell.boundary.length, 6);
for (const { lat, lon } of cell.boundary) {
// Res-4 hexagons are about 45 km across.
assert.ok(Math.abs(lat - cell.lat) < 0.4, `lat ${lat}`);
assert.ok(Math.abs(lon - cell.lon) < 0.6, `lon ${lon}`);
}
for (const key of ['south', 'west', 'north', 'east'])
assert.equal(key in cell, false, `no rectangle field ${key}`);
assert.deepEqual(
gnssCellRing(cell),
cell.boundary.flatMap(({ lat, lon }) => [lon, lat]),
);
});
test('a cell across the antimeridian is drawn as one narrow polygon', () => {
for (const lon of [179.99, -179.99]) {
const cell = cellAt(0, lon);
const lons = cell.boundary.map((vertex) => vertex.lon);
assert.ok(
Math.max(...lons) - Math.min(...lons) > 300,
'the raw boundary straddles ±180°',
);
const drawn = gnssCellRing(cell).filter((_, index) => index % 2 === 0);
const width = Math.max(...drawn) - Math.min(...drawn);
assert.ok(width < 1, `drawn width ${width}° stays narrow`);
for (const value of drawn) assert.ok(Math.abs(value - cell.lon) < 1);
}
});
test('pentagon and polar cells give closed rings', () => {
// 8408001ffffffff is one of the twelve res-4 pentagons.
const pentagon = cellAt(64.7, 10.5);
assert.ok(isPentagon(pentagon.id));
assert.equal(pentagon.boundary.length, 5);
assert.equal(gnssCellRing(pentagon).length, 10);
for (const lat of [89.99, -89.99]) {
const polar = cellAt(lat, 10);
assert.ok(polar.boundary.length >= 6);
for (const vertex of polar.boundary)
assert.ok(Math.abs(vertex.lat) > 89 && Math.abs(vertex.lat) <= 90);
// Unwrapped longitudes stay within half a turn of the centre.
gnssCellRing(polar)
.filter((_, index) => index % 2 === 0)
.forEach((value) => assert.ok(Math.abs(value - polar.lon) <= 180));
}
});
test('integrity level follows the gpsjam.org published cell formula and bands', () => {
@@ -156,8 +235,8 @@ test('the primary state is a navigation-integrity anomaly; interference is only
store,
[
{ hex: 'h1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'h2', lat: 10.2, lon: 10.2, degraded: true },
{ hex: 'h3', lat: 10.3, lon: 10.3, degraded: false },
{ hex: 'h2', lat: 10.11, lon: 10.11, degraded: true },
{ hex: 'h3', lat: 10.12, lon: 10.12, degraded: false },
],
0,
);
@@ -182,14 +261,14 @@ test('provenance separates the GEV classifier from the gpsjam aggregation and th
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: [2, 10],
grid: 'h3',
h3Resolution: 4,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
});
assert.deepEqual(GNSS_PROVENANCE.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(GNSS_PROVENANCE.state.id, 'navigation-integrity-anomaly');
@@ -225,14 +304,13 @@ test('observations count each aircraft once per cell and expire after the window
assert.equal(cell.aircraft, 3);
assert.equal(cell.degraded, 1);
assert.equal(cell.level, 'low');
assert.deepEqual(
[cell.south, cell.west, cell.north, cell.east],
[50, 20, 50.5, 20.5],
);
assert.equal(cell.id, gnssCellKey(50.2, 20.1));
accumulateGnssObservations(store, [], 1200, { windowMs: 1000 });
assert.equal(store.size, 1);
assert.deepEqual(binGnssCells(store), []);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1, 'only a1, seen inside the window, remains');
assert.equal(cell.degraded, 0);
});
const MIN = 60_000;
@@ -396,22 +474,66 @@ test('rows without finite coordinates never key a cell', () => {
assert.equal(store.size, 0);
});
test('cells below the minimum aircraft count are withheld', () => {
test('every cell with an aircraft is shown, as on gpsjam.org; only the bad − 1 discount guards small samples', () => {
const store = new Map();
accumulateGnssObservations(
store,
[
{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'b2', lat: 10.2, lon: 10.2, degraded: true },
],
[{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true }],
0,
);
assert.deepEqual(binGnssCells(store), []);
const [cell] = binGnssCells(store, { minAircraft: 2 });
let [cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1);
assert.equal(cell.level, 'low', 'one bad aircraft is discounted');
assert.equal(cell.percentDegraded, 0);
accumulateGnssObservations(
store,
[{ hex: 'b2', lat: 10.12, lon: 10.12, degraded: true }],
0,
);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 2);
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 50);
});
test('the gpsjam bands are unchanged by the hex grid', () => {
assert.equal(GNSS_MEDIUM_PERCENT, 2);
assert.equal(GNSS_HIGH_PERCENT, 10);
// [total, bad] → level, at and either side of both band edges.
for (const [total, bad, level] of [
[100, 0, 'low'],
[100, 1, 'low'],
[100, 2, 'low'],
[100, 3, 'medium'],
[50, 2, 'medium'],
[100, 11, 'medium'],
[100, 12, 'high'],
[10, 2, 'medium'],
[10, 3, 'high'],
])
assert.equal(
gnssIntegrityLevel(total, bad).level,
level,
`${bad}/${total}`,
);
// Binned cells band the same way: 3 bad of 10 in one hexagon is high.
const store = new Map();
accumulateGnssObservations(
store,
Array.from({ length: 10 }, (_, index) => ({
hex: `h${index}`,
lat: 50.1,
lon: 19.9,
degraded: index < 3,
})),
0,
);
const [cell] = binGnssCells(store);
assert.equal(cell.id, '841e2e7ffffffff');
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 20);
});
test('MLAT GPS-loss evidence uses the last good GNSS location and ignores MLAT NIC', () => {
const [row] = normalizeGnssAircraft({
ac: [
+15 -1
View File
@@ -1,5 +1,6 @@
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { stickyText, stickyNumber } from '../../data/aircraftMeta.js';
import { courseFromFixes } from '../../data/courseFromFixes.js';
import { classifyAircraft } from '../../data/aircraftClass.js';
import { aircraftEmergency } from '../../data/aircraftEmergency.js';
import {
@@ -175,6 +176,12 @@ export class MilitaryFlightRecords {
// last-known-good (bounded by the layer's eviction, which deletes the entry).
const stickyType = stickyText(type, prevMeta?.type);
const fixEpochMs = aircraft.positionTimeMs ?? observedAtMs;
const course = courseFromFixes(prevMeta?.courseAnchor, {
lat,
lon,
ms: fixEpochMs,
speedMps: aircraft.speedMps,
});
const meta = {
sourceReference: aircraft.reference,
observedReceiptMs: this.now(),
@@ -206,7 +213,14 @@ export class MilitaryFlightRecords {
onGround ? 0 : prevMeta?.speedMps,
0,
),
track: stickyNumber(aircraft.courseDeg, prevMeta?.track, 0),
// With no reported track or true heading, a moving contact faces the
// way its fixes went (src/data/courseFromFixes.js); else the last one.
track: stickyNumber(
aircraft.courseDeg,
course.courseDeg ?? prevMeta?.track,
0,
),
courseAnchor: course.anchor,
// Analyst seam (additive): sticky like the other kinematics.
verticalRateMps: stickyNumber(
verticalRateMps,
+23
View File
@@ -269,3 +269,26 @@ test('a repeated military fix time marks the contact as not updated; removal is
records.forget('aaa001');
assert.equal(records.fixRepeated.has('aaa001'), false);
});
test('a military contact reported with no course faces the way its newer fixes went', () => {
const records = store();
const T = 1700000000000;
const taxi = (latitude, seconds) =>
records.receive(
observation({
latitude,
onGround: true,
baroAltitudeM: null,
courseDeg: null,
speedMps: 8,
positionTimeMs: T + seconds * 1000,
}),
context({ observedAtMs: T + seconds * 1000 + 500 }),
);
assert.equal(taxi(39, 0).meta.track, 0);
assert.ok(Math.abs(taxi(38.9995, 5).meta.track - 180) < 0.1);
assert.ok(
Math.abs(taxi(39.002, 3).meta.track - 180) < 0.1,
'an older fix gives no course',
);
});
+21 -22
View File
@@ -55,37 +55,36 @@ export function vesselPositionAt(record, tMs) {
const RAD = Math.PI / 180;
/** The point `fraction` of the way from one position to another. */
/** The point `fraction` of the way from one position to another. It runs
* for every drawn vessel as the clock plays, so it builds no arrays. */
function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
const p1 = unit(lat1, lon1);
const p2 = unit(lat2, lon2);
const dot = Math.min(
1,
Math.max(-1, p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]),
);
const phi1 = lat1 * RAD;
const lambda1 = lon1 * RAD;
const phi2 = lat2 * RAD;
const lambda2 = lon2 * RAD;
const cos1 = Math.cos(phi1);
const cos2 = Math.cos(phi2);
const x1 = cos1 * Math.cos(lambda1);
const y1 = cos1 * Math.sin(lambda1);
const z1 = Math.sin(phi1);
const x2 = cos2 * Math.cos(lambda2);
const y2 = cos2 * Math.sin(lambda2);
const z2 = Math.sin(phi2);
const dot = Math.min(1, Math.max(-1, x1 * x2 + y1 * y2 + z1 * z2));
const angle = Math.acos(dot);
if (angle < 1e-12) return { lat: lat2, lon: lon2 };
const a = Math.sin((1 - fraction) * angle) / Math.sin(angle);
const b = Math.sin(fraction * angle) / Math.sin(angle);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
const sinAngle = Math.sin(angle);
const a = Math.sin((1 - fraction) * angle) / sinAngle;
const b = Math.sin(fraction * angle) / sinAngle;
const x = a * x1 + b * x2;
const y = a * y1 + b * y2;
const z = a * z1 + b * z2;
return {
lat: Math.atan2(z, Math.hypot(x, y)) / RAD,
lon: Math.atan2(y, x) / RAD,
};
}
function unit(lat, lon) {
const phi = lat * RAD;
const lambda = lon * RAD;
return [
Math.cos(phi) * Math.cos(lambda),
Math.cos(phi) * Math.sin(lambda),
Math.sin(phi),
];
}
// Whether each fixes array moves, read once per array: records keep theirs
// until a snapshot brings new ones.
const moving = new WeakMap();
+262 -6
View File
@@ -375,8 +375,7 @@ test('following the clock moves drawn vessels in place each world time, prepares
const before = visuals.map((visual) => ({ ...visual.position }));
const positions = visuals.map((visual) => visual.position);
// The first pass also moves hidden vessels, so the next stays within
// HIDDEN_FOLLOW_MS of it.
// The first pass moves hidden vessels too.
layer.testing._runClockPassForTest(10_000);
mono += 16;
layer.testing._runClockPassForTest(20_000);
@@ -390,10 +389,7 @@ test('following the clock moves drawn vessels in place each world time, prepares
);
assert.equal(timers.size, 1, 'moving vessels ask for a frame');
// The hidden vessel waits for HIDDEN_FOLLOW_MS.
mono += 16;
layer.testing._runClockPassForTest(30_000);
assert.deepEqual({ ...visuals[1].position }, hiddenAt);
// Hidden vessels move a share each pass, each within HIDDEN_FOLLOW_MS.
mono += 250;
layer.testing._runClockPassForTest(40_000);
assert.notDeepEqual({ ...visuals[1].position }, hiddenAt);
@@ -466,3 +462,263 @@ test('following the clock, a vessel draws no icon before it was there, and draws
layer.testing._runVisibilityPassForTest(true);
assert.equal(shown(), true, 'half a minute before it: reaching it');
});
/** Motion north along a meridian off Rotterdam, `toMs` after the epoch. */
const northbound = (toLat, toMs) => ({
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat,
toLon: 4.05,
toMs,
});
/** Put the double camera `heightM` above `lon`/`lat`, as Cesium's camera
* reports its position in both forms. */
function placeCamera(camera, lon, lat, heightM) {
camera.positionWC = Cesium.Cartesian3.fromDegrees(lon, lat, heightM);
camera.positionCartographic = Cesium.Cartographic.fromDegrees(
lon,
lat,
heightM,
);
}
/** Stand in a page with no overlay host element, for the label pass. */
function noOverlayDocument(t) {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
}
test('following the clock, drawn vessels move again once the fastest would have moved half a pixel, a second has gone by or the camera changed height', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
noOverlayDocument(t);
const { layer, camera } = setup();
// 20 km above, in a 1,000 px tall view about 57° tall: half a pixel is
// about 11 m. The vessel makes about 1.9 m a second of world time.
placeCamera(camera, 4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: northbound(51.94, 600_000),
};
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
const visual = layer.testing._prepareVesselVisualForTest(record);
// Drawn: on the camera's side of the horizon.
visual.visible = true;
const at = () => ({ ...visual.position });
const pass = (atMs, wallMs = 16) => {
mono += wallMs;
layer.testing._runClockPassForTest(atMs);
};
// Two passes a world second apart measure how fast it moves on screen.
pass(10_000);
pass(11_000);
let drawn = at();
// A few metres more stay under half a pixel: it is left where it is.
pass(12_000);
pass(14_000);
assert.deepEqual(at(), drawn);
// About 13 m on from where it was drawn: it moves.
pass(18_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
// Under half a pixel, but a second later: it moves.
pass(19_000, 1_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
pass(20_000);
assert.deepEqual(at(), drawn);
// Under half a pixel, but the camera came down by half: it moves.
placeCamera(camera, 4.05, 51.93, 10_000);
pass(21_000);
assert.notDeepEqual(at(), drawn);
// Scrubbed well back, it moves back at once.
drawn = at();
pass(1_000);
assert.notDeepEqual(at(), drawn);
});
test('a vessel is drawn lifted above the sea surface, its waterline on it, as Cesium places them', () => {
const { layer, camera } = setup();
const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
const viewer = { camera, scene: {} };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
const visual = layer.testing._prepareVesselVisualForTest(record);
const heightOf = (position) =>
Cesium.Ellipsoid.WGS84.cartesianToCartographic(
new Cesium.Cartesian3(position.x, position.y, position.z),
).height;
const close = (actual, expected) =>
assert.ok(
Cesium.Cartesian3.distance(
new Cesium.Cartesian3(actual.x, actual.y, actual.z),
expected,
) < 1e-6,
`${JSON.stringify(actual)} is not ${expected}`,
);
close(
visual.position,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.position)),
);
close(
visual.waterline,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.waterline)),
);
assert.ok(heightOf(visual.position) > heightOf(visual.waterline));
});
test('following the clock, a pass moves hidden vessels in proportion to the wall time since the last, so all move within HIDDEN_FOLLOW_MS', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
noOverlayDocument(t);
const { layer, camera } = setup();
const records = Array.from({ length: 100 }, (_, i) => ({
mmsi: String(i),
lat: 51.93,
lon: 4.05,
motion: northbound(51.94, 600_000),
}));
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records });
const visuals = records.map((record) =>
layer.testing._prepareVesselVisualForTest(record),
);
// Hidden: past the horizon.
for (const visual of visuals) visual.visible = false;
layer.testing._runClockPassForTest(10_000);
const moved = (atMs) => visuals.filter((v) => v.followedAtMs === atMs).length;
assert.equal(moved(10_000), 100, 'the first pass moves them all');
mono += 25;
layer.testing._runClockPassForTest(20_000);
assert.equal(moved(20_000), 10, 'a tenth of HIDDEN_FOLLOW_MS, a tenth');
for (let i = 0; i < 9; i += 1) {
mono += 25;
layer.testing._runClockPassForTest(20_000);
}
assert.equal(moved(20_000), 100, 'all within HIDDEN_FOLLOW_MS');
});
test('following the clock, the step gate measures each vessel from when it was drawn, and reopens for a pan, a zoom or a pause', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
noOverlayDocument(t);
const { layer, camera } = setup();
placeCamera(camera, 4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: northbound(51.94, 600_000),
};
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
const visual = layer.testing._prepareVesselVisualForTest(record);
visual.visible = true;
const at = () => ({ ...visual.position });
const pass = (atMs) => {
mono += 16;
layer.testing._runClockPassForTest(atMs);
};
// About 0.08 px a world second: measured over a second.
pass(10_000);
pass(11_000);
pass(13_000);
// A snapshot draws it afresh just before the next pass: the pass after
// it measures the move over that short time, not since 11 s.
layer.testing._followClockForTest(17_900);
layer.testing._prepareVesselVisualForTest(record);
pass(18_000);
let drawn = at();
pass(19_000);
assert.deepEqual(at(), drawn, 'the speed it measured is still its own');
pass(24_500);
assert.notDeepEqual(at(), drawn, 'and it moves once half a pixel is up');
// Panned sideways by more than a tenth of the camera's height: it moves.
drawn = at();
pass(25_000);
assert.deepEqual(at(), drawn);
placeCamera(camera, 4.1, 51.93, 20_000);
pass(25_500);
assert.notDeepEqual(at(), drawn);
// Zoomed in by narrowing the view: it moves.
drawn = at();
pass(26_000);
assert.deepEqual(at(), drawn);
camera.frustum = { fovy: 0.5 };
pass(26_500);
assert.notDeepEqual(at(), drawn);
// Paused just after a pass that left it short: the next frame at the same
// time draws it where it is.
drawn = at();
pass(27_000);
assert.deepEqual(at(), drawn);
pass(27_000);
assert.notDeepEqual(at(), drawn);
const where = at();
pass(27_000);
assert.deepEqual(at(), where, 'then holds');
});
test('following the clock, a vessel the visibility pass shows before the clock passes moved it is drawn at the time', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
noOverlayDocument(t);
const { layer, camera } = setup();
placeCamera(camera, 4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const vessel = (mmsi) => ({
mmsi,
lat: 51.93,
lon: 4.05,
motion: northbound(52.93, 3_600_000),
});
const records = Array.from({ length: 40 }, (_, i) => vessel(String(i)));
const last = records.at(-1);
const viewer = { camera, scene: {}, canvas: { clientHeight: 1000 } };
const { query } = bindFakeCesiumScene(viewer);
// Every label off screen: the labels are not placed.
query.projectMany = (_world, screen) => screen.fill(Number.NaN);
layer.testing._setVesselStateForTest({ viewer, records });
layer.testing._followClockForTest(0);
const visual = layer.testing._prepareVesselVisualForTest(last);
for (const record of records.slice(0, -1))
layer.testing._prepareVesselVisualForTest(record);
// Hidden until the visibility pass finds them in view.
for (const record of records)
layer.testing._vesselVisualForTest(record).visible = false;
layer.testing._runClockPassForTest(10_000);
// Paused, a seek far on: the next frame moves only a share of the hidden
// vessels, not the last.
mono += 16;
layer.testing._runClockPassForTest(11_000);
mono += 16;
layer.testing._runClockPassForTest(1_800_000);
assert.notEqual(visual.followedAtMs, 1_800_000);
layer.testing._runVisibilityPassForTest(true);
assert.equal(visual.visible, true);
const { latitude } = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
new Cesium.Cartesian3(
visual.position.x,
visual.position.y,
visual.position.z,
),
);
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
});
+233 -39
View File
@@ -45,8 +45,8 @@ import { isAidToNavigation } from '../../data/vesselTypes.js';
const VESSEL_STEP_PX = 0.5;
/** A frame is asked for at least this often while any drawn vessel moves. */
const PLACEMENT_FRAME_MS = 1000;
/** How often vessels not drawn move on as the world clock plays (wall ms),
* so one that comes into view is judged where it is. */
/** How often each vessel not drawn moves on as the world clock plays (wall
* 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). */
@@ -57,6 +57,14 @@ let instances = 0;
/** How often the vessels near enough for a model are gathered again (wall ms). */
const MODEL_CANDIDATES_MS = 500;
/** How far the camera may move or change height, as a share of its height,
* before vessels following the world clock move again however little they
* moved. */
const CAMERA_STEP = 0.1;
/** The least height that share is taken of (metres), so a camera just above
* the sea, or below the ellipsoid, still lets vessels rest between steps. */
const CAMERA_STEP_FLOOR_M = 100;
/** Scratch for where a moved vessel was drawn. */
const _movedFrom = vec();
@@ -98,6 +106,10 @@ export function createRendering({
visual.waterline = anchorAt(lat, lon, 0);
visual.drawnLat = lat;
visual.drawnLon = lon;
// The world time it is drawn at, while it follows the clock.
visual.drawnAtMs = followsClock(vesselState)
? vesselState.worldNow()
: Number.NaN;
return visual;
}
@@ -523,12 +535,14 @@ export function createRendering({
// The layer does not hold the continuous render loop. Its passes run in
// preRender, which idle mode fires only for rendered frames: moving vessels
// ask for the frame that next moves them visibly (askMotionFrame), a forced
// pass (new data, selection) requests its frame, a frame that moved the
// camera but fell inside the 800 ms cadence leaves a trailing frame so the view the camera stopped on is always
// evaluated, and the continuous hold is kept only while focus emphasis is
// animating. The trailing frame is keyed to camera motion alone: the pass's
// own label publication requests a frame, and scheduling on that would loop.
// ask for the frame that next moves them visibly (askMotionFrame; while the
// world clock plays, the scene draws every frame anyway), a forced pass
// (new data, selection) requests its frame, a frame that moved the camera
// but fell inside the 800 ms cadence leaves a trailing frame so the view
// the camera stopped on is always evaluated, and the continuous hold is
// kept only while focus emphasis is animating. The trailing frame is keyed
// to camera motion alone: the pass's own label publication requests a
// frame, and scheduling on that would loop.
function installRuntime(viewer) {
if (state.preRenderRemover || !viewer) return;
state.preRenderRemover =
@@ -542,37 +556,181 @@ export function createRendering({
}) ?? null;
}
// As the world clock plays, vessels between two fixes move on along them:
// drawn ones every frame, each once per world time, hidden ones (which may
// come into view) every HIDDEN_FOLLOW_MS.
let hiddenFollowedAtWallMs = -Infinity;
// As the world clock plays, vessels between two fixes move on along them.
// Drawn ones move each world time once the fastest would have moved
// VESSEL_STEP_PX on screen, at least once a second, and at once when the
// camera moves or zooms (underClockStep). Hidden ones (which may come into
// view) move a share of them each pass, so each moves at least every
// HIDDEN_FOLLOW_MS without one frame moving them all. The scene renders as
// fast as the display while the clock plays, and moving thousands of
// vessels a fraction of a pixel each frame would take most of every frame.
let hiddenFollowedAtWallMs = null;
let hiddenCursor = 0;
let clockPassAtMs = null;
// Whether the last pass left drawn vessels short of its world time.
let drawnBehind = false;
function followClockPositions() {
const atMs = vesselState.worldNow();
const motion = startMotionPass();
const moveHidden =
motion.wallMs - hiddenFollowedAtWallMs >= HIDDEN_FOLLOW_MS;
if (moveHidden) hiddenFollowedAtWallMs = motion.wallMs;
for (const record of state.records.all) {
if (!record.motion && !fixesMove(record.fixes)) continue;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
syncRecordIcon(record);
continue;
}
if (
visual.followedAtMs === atMs ||
(!drawnNow(record, visual) && !moveHidden)
)
continue;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(record, visual, lat, lon, motion);
const wallMs = performance.now();
const all = state.records.all;
// Each vessel moves once per world time; drawn ones a pass left short
// move to it on the next, so a paused clock shows them where they are.
const sameTime = atMs === clockPassAtMs;
const moveDrawn = sameTime ? drawnBehind : !underClockStep(atMs, wallMs);
clockPassAtMs = atMs;
if (moveDrawn) drawnBehind = false;
else if (!sameTime) {
drawnBehind = true;
askFrameIn(PLACEMENT_FRAME_MS);
}
const motion = moveDrawn ? startMotionPass() : null;
if (moveDrawn)
for (const record of all) followRecord(record, atMs, true, motion);
// As much of the list as the wall time since the last pass is of
// HIDDEN_FOLLOW_MS, going round it.
const sinceMs =
hiddenFollowedAtWallMs === null
? HIDDEN_FOLLOW_MS
: wallMs - hiddenFollowedAtWallMs;
const share = Math.min(
all.length,
Math.ceil((all.length * Math.max(0, sinceMs)) / HIDDEN_FOLLOW_MS),
);
if (share > 0) hiddenFollowedAtWallMs = wallMs;
for (let k = 0; k < share; k += 1) {
if (hiddenCursor >= all.length) hiddenCursor = 0;
followRecord(all[hiddenCursor], atMs, false, motionPass);
hiddenCursor += 1;
}
if (!moveDrawn) return;
askMotionFrame(motion);
noteClockStep(atMs, motion);
}
/**
* Draw a vessel where it is at world time `atMs` if the clock passes have
* not yet; true when it moved.
*/
function catchUpVisual(record, atMs) {
const visual = visualRecords.get(record);
if (!visual?.position || visual.followedAtMs === atMs) return false;
if (!record.motion && !fixesMove(record.fixes)) return false;
visual.followedAtMs = atMs;
visual.drawnAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
if (lat === visual.drawnLat && lon === visual.drawnLon) return false;
moveRecordVisual(record, visual, lat, lon);
return true;
}
/**
* Move a vessel to where it is at world time `atMs`, if it is drawn
* (`drawn`) or hidden (not `drawn`) as asked; one with no visual yet is
* prepared either way. A hidden vessel's move notes nothing in `motion`.
*/
function followRecord(record, atMs, drawn, motion) {
if (!record.motion && !fixesMove(record.fixes)) return;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
syncRecordIcon(record);
return;
}
if (drawnNow(record, visual) !== drawn || visual.followedAtMs === atMs)
return;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
const elapsedMs = Math.abs(atMs - visual.drawnAtMs);
visual.drawnAtMs = atMs;
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) return;
moveDrawnVisual(record, visual, lat, lon, motion, elapsedMs);
}
// The clock pass that last moved drawn vessels: its world time and wall
// time, how fast the fastest drawn vessel moved on screen (pixels per world
// ms), and the camera then: where it was, its height and its view's size.
const clockStep = {
atMs: null,
wallMs: 0,
pxPerMs: Infinity,
heightM: 0,
eye: vec(),
fovy: Number.NaN,
width: Number.NaN,
};
/** Measure, after a pass that moved drawn vessels, how fast the fastest
* moved on screen: each over the world time since it was last drawn. */
function noteClockStep(atMs, motion) {
const pose = motion.pose;
if (!motion.moving || motion.unmeasured || !pose?.position) {
clockStep.atMs = null;
return;
}
const pxPerMs = movedPixels({
pose,
angle: motion.angleRate,
metres: motion.metresRate,
});
clockStep.pxPerMs = pxPerMs > 0 ? pxPerMs : Infinity;
clockStep.atMs = atMs;
clockStep.wallMs = motion.wallMs;
clockStep.heightM = poseHeightM(pose);
copyInto(pose.position, clockStep.eye);
clockStep.fovy = pose.fovy;
clockStep.width = viewWidth(pose);
}
/** Forget how fast vessels moved, so the next clock pass moves the drawn
* ones however little they moved (they were drawn somewhere else). */
function forgetClockStep() {
clockStep.atMs = null;
clockPassAtMs = null;
}
/** The width of the view (metres) of a camera with no field of view (an
* orthographic one, `2 / m00`), NaN for one that has a field of view. */
function viewWidth(pose) {
if (pose.fovy > 0) return Number.NaN;
try {
return 2 / findCamera(state.viewer).matrices().projection[0];
} catch {
return Number.NaN;
}
}
const sameNumber = (a, b) => a === b || (Number.isNaN(a) && Number.isNaN(b));
/** The camera's height above the ellipsoid (metres), NaN without one. */
const poseHeightM = (pose) =>
Number.isFinite(pose?.height) ? pose.height : Number.NaN;
/**
* Whether the fastest drawn vessel would have moved less than
* VESSEL_STEP_PX on screen since the clock pass that last moved them, at
* the speed it moved then: drawn vessels are left where they are. They
* move anyway once PLACEMENT_FRAME_MS has gone by, or once the camera has
* moved or changed height by more than CAMERA_STEP of its height, or its
* view has changed size (a pixel then covers another distance).
*/
function underClockStep(atMs, wallMs) {
if (clockStep.atMs === null || !(clockStep.pxPerMs < Infinity))
return false;
if (wallMs - clockStep.wallMs >= PLACEMENT_FRAME_MS) return false;
const pose = state.viewer ? findCamera(state.viewer)?.pose() : null;
if (!pose?.position) return false;
const limitM =
CAMERA_STEP * Math.max(clockStep.heightM, CAMERA_STEP_FLOOR_M);
if (!(Math.abs(poseHeightM(pose) - clockStep.heightM) <= limitM))
return false;
if (!(distance(pose.position, clockStep.eye) <= limitM)) return false;
if (
!sameNumber(pose.fovy, clockStep.fovy) ||
!sameNumber(viewWidth(pose), clockStep.width)
)
return false;
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
}
// Live with a host-supplied placement, vessels move on between refreshes:
@@ -608,6 +766,9 @@ export function createRendering({
moving: false,
angle: 0,
metres: 0,
angleRate: 0,
metresRate: 0,
unmeasured: false,
};
function startMotionPass() {
const wallMs = performance.now();
@@ -619,6 +780,9 @@ export function createRendering({
motionPass.moving = false;
motionPass.angle = 0;
motionPass.metres = 0;
motionPass.angleRate = 0;
motionPass.metresRate = 0;
motionPass.unmeasured = false;
motionPassWallMs = wallMs;
return motionPass;
}
@@ -641,18 +805,27 @@ export function createRendering({
);
}
/** Move a drawn visual, noting how far it moved as seen from the camera. */
function moveDrawnVisual(record, visual, lat, lon, motion) {
/** Move a drawn visual, noting how far it moved as seen from the camera,
* and, given the world time since it was last drawn (`elapsedMs`), how
* fast. */
function moveDrawnVisual(record, visual, lat, lon, motion, elapsedMs) {
const from = copyInto(visual.position, _movedFrom);
moveRecordVisual(record, visual, lat, lon);
if (!drawnNow(record, visual)) return;
motion.moving = true;
const metres = distance(from, visual.position);
motion.metres = Math.max(motion.metres, metres);
const timed = elapsedMs > 0;
if (elapsedMs !== undefined && !timed) motion.unmeasured = true;
if (timed)
motion.metresRate = Math.max(motion.metresRate, metres / elapsedMs);
const eye = motionPose(motion)?.position;
if (!eye) return;
const range = distance(eye, from);
if (range > 0) motion.angle = Math.max(motion.angle, metres / range);
if (!(range > 0)) return;
motion.angle = Math.max(motion.angle, metres / range);
if (timed)
motion.angleRate = Math.max(motion.angleRate, metres / range / elapsedMs);
}
/** How far the fastest drawn vessel moved on screen in a pass (pixels):
@@ -691,7 +864,12 @@ export function createRendering({
const movedPx = movedPixels(motion);
if (movedPx > 0 && motion.sinceMs > 0)
waitMs = Math.min(waitMs, (VESSEL_STEP_PX * motion.sinceMs) / movedPx);
// A frame already asked for no later than this one stands.
askFrameIn(waitMs);
}
/** Ask for a vessel frame `waitMs` from now; one already asked for no
* later stands. */
function askFrameIn(waitMs) {
const runtime = vesselState._aisRuntime;
const dueMs = runtime.now() + waitMs;
if (placementFrameTimer !== null) {
@@ -708,6 +886,9 @@ export function createRendering({
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
motionPassWallMs = null;
forgetClockStep();
drawnBehind = false;
hiddenFollowedAtWallMs = null;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
@@ -790,9 +971,21 @@ export function createRendering({
if (pose) vesselState._lastCamPoseSig = poseSignature(pose);
const occluder = makeOccluder(pose);
const labelCandidates = [];
// The time the clock pass drew (a playing clock's time moves on within
// the frame), so only vessels it did not reach are moved.
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
for (const record of state.records.all) {
const visual = getVisual(record);
visual.visible = isVisible(visual.cullPosition, occluder, record);
// One in view that the clock passes have not moved to the time yet
// (a seek while paused shows it before its turn) is moved there and
// judged again: no later pass would move it while the clock rests.
if (
visual.visible &&
catchUpAtMs !== null &&
catchUpVisual(record, catchUpAtMs)
)
visual.visible = isVisible(visual.cullPosition, occluder, record);
// A vessel the time drawn reaches (or leaves) shows (or hides) its icon.
if (visual.seen !== seenYet(record)) syncRecordIcon(record);
if (visual.visible) labelCandidates.push(record);
@@ -1080,6 +1273,7 @@ export function createRendering({
return {
getVisual,
iconPosition,
forgetClockStep,
prepareRecordVisual,
anchorPosition,
resetRecordVisuals,
+2
View File
@@ -70,7 +70,9 @@ export function createTracking({
visual.drawnLat = NaN;
visual.drawnLon = NaN;
visual.followedAtMs = undefined;
visual.drawnAtMs = Number.NaN;
}
components.rendering.forgetClockStep();
// The rows moved with no poll behind them: draw the frame that shows it.
governorRequestRender('ais-vessels-refloor');
}
+4 -1
View File
@@ -36,6 +36,7 @@ function setup({ geoidN = 40, track = null } = {}) {
getVisual: (record) => visuals.get(record) ?? record,
anchorPosition: (record) => ({ anchoredAt: [record.lon, record.lat] }),
syncRecordIcon: (record) => synced.push(record),
forgetClockStep: () => synced.push('forgetClockStep'),
},
};
const renders = [];
@@ -135,7 +136,9 @@ test('refloor re-anchors every fixed record through the rendering part', () => {
visuals.set(fixed, visual);
tracking.refloorVesselRecords();
assert.deepEqual(visual.position, { anchoredAt: [4.05, 51.9] });
assert.deepEqual(synced, [fixed]);
// Drawn somewhere else, the vessels move on the next clock pass however
// little they would.
assert.deepEqual(synced, [fixed, 'forgetClockStep']);
assert.deepEqual(renders, ['ais-vessels-refloor']);
});