mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-21 02:32:18 +00:00
Merge upstream main into feat/iss-3d-model
Translation files: kept both sides' new keys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
349b3a04ec
407 files changed
+23411
-2582
No files matched your search
@@ -399,7 +399,12 @@ export function createScreenAnnotationRenderer(
|
||||
// from the host's ACTUAL painted rectangle after final layout; the billboard extent
|
||||
// is unioned for aircraft/satellites that also own a native tracked graphic.
|
||||
const TRACKED_BBOX_MARGIN = 8; // px buffer added around the footprint
|
||||
const TRACKED_FADE_EASE = 0.22; // per-frame ease toward hidden(0) / visible(1)
|
||||
// Ease toward hidden(0) / visible(1): this share of the gap closes in one
|
||||
// 60 Hz frame (about 200 ms to settle), scaled by elapsed time so the fade
|
||||
// takes as long at any refresh rate.
|
||||
const TRACKED_FADE_EASE = 0.22;
|
||||
const TRACKED_FADE_FRAME_MS = 1000 / 60;
|
||||
let trackedFadeAtMs = -Infinity;
|
||||
const TRACKED_HYSTERESIS_PX = 18; // dead-band so the overlap test can't flip-flop
|
||||
const _scratchTrackedWin = new Cesium.Cartesian2();
|
||||
|
||||
@@ -677,6 +682,14 @@ export function createScreenAnnotationRenderer(
|
||||
// safe and not jarring.
|
||||
function fadeTracked(trackedRect) {
|
||||
if (!shown()) return;
|
||||
const nowMs = performance.now();
|
||||
// A gap longer than a slow frame means the fade was not running (nothing
|
||||
// followed): it starts again as from one 60 Hz frame.
|
||||
const gapMs = nowMs - trackedFadeAtMs;
|
||||
const stepMs = gapMs >= 0 && gapMs <= 100 ? gapMs : TRACKED_FADE_FRAME_MS;
|
||||
trackedFadeAtMs = nowMs;
|
||||
const ease =
|
||||
1 - Math.pow(1 - TRACKED_FADE_EASE, stepMs / TRACKED_FADE_FRAME_MS);
|
||||
let changed = false;
|
||||
for (const rec of records.values()) {
|
||||
const { anno, group } = rec;
|
||||
@@ -705,10 +718,10 @@ export function createScreenAnnotationRenderer(
|
||||
}
|
||||
}
|
||||
const target = overlapping ? 0 : 1;
|
||||
const next = cur + (target - cur) * TRACKED_FADE_EASE;
|
||||
const next = cur + (target - cur) * ease;
|
||||
rec._trackedFade = Math.abs(next - target) < 0.02 ? target : next;
|
||||
// The base alpha applies unless faded. (The CSS `transition: opacity` was
|
||||
// removed from .gev-anno so this per-frame JS ease is the ONLY easing —
|
||||
// removed from .gev-anno so this JS ease is the ONLY easing —
|
||||
// previously the two fought and produced an opacity oscillation.)
|
||||
const opacity = String(
|
||||
(anno.alpha ?? 1) * (rec._trackedFade !== 1 ? rec._trackedFade : 1),
|
||||
|
||||
@@ -216,7 +216,7 @@ test('outline upgrade preserves the existing SVG group identity', async (t) => {
|
||||
assert.ok(after === before, 'the rendered group is mutated, not replaced');
|
||||
assert.deepEqual(sampledAnchors.at(-1), [-97.5, 31.2], 'the existing group projects from the re-seated anchor');
|
||||
assert.equal(groups().length, 1);
|
||||
assert.equal(after.querySelector('.gev-anno-ring'), null, 'reticle rings are removed in place');
|
||||
assert.equal(after.querySelector('.gev-anno-ring') === null, true, 'reticle rings are removed in place');
|
||||
assert.ok(after.querySelector('.gev-anno-callout') === callout, 'the original callout remains in the group');
|
||||
assert.ok(after.querySelector('.gev-anno-dot') === dot, 'the anchor dot remains in the group');
|
||||
assert.ok(svg());
|
||||
@@ -330,7 +330,7 @@ test('a removed mark fades out, then leaves the board', async (t) => {
|
||||
assert.equal(group.isConnected, false);
|
||||
renderer.destroy();
|
||||
await settle();
|
||||
assert.equal(document.querySelector('.gev-screen-whiteboard'), null);
|
||||
assert.equal(document.querySelector('.gev-screen-whiteboard') === null, true);
|
||||
});
|
||||
|
||||
// ── Partial-add unwind (review round 2) ───────────────────────────────────────
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createWeatherLayer } from '../layers/weather/index.js';
|
||||
import { createApplicationCyclones } from './layers/cyclones.js';
|
||||
import { createWindLayer } from '../layers/wind/index.js';
|
||||
import { createLayerCatalog } from './catalog.js';
|
||||
import { layerPlacement } from '../data/placementProvider.js';
|
||||
import { LAYER_STATE_REGISTRY } from '../data/layerState.js';
|
||||
import { createMilitaryRegistry } from '../layers/aircraft/classification.js';
|
||||
import { createApplicationFlights } from './layers/flights.js';
|
||||
@@ -63,6 +64,9 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
|
||||
/** Construct the current catalog without choosing any source provider.
|
||||
* Scene engines remain page-owned; layers and classification have this app's lifetime.
|
||||
* The manager owns layer destruction, while abort releases classification even if startup fails.
|
||||
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
|
||||
* places live aircraft, vessels, transit and trains; without one each layer
|
||||
* uses its own motion.
|
||||
*/
|
||||
export function createApplicationCatalog({
|
||||
surface,
|
||||
@@ -74,6 +78,7 @@ export function createApplicationCatalog({
|
||||
resolveAsset,
|
||||
nepalBoundaryResolver,
|
||||
streetLevelProviders,
|
||||
placement = null,
|
||||
}) {
|
||||
if (!signal?.addEventListener)
|
||||
throw new TypeError('An application lifetime signal is required');
|
||||
@@ -97,17 +102,20 @@ export function createApplicationCatalog({
|
||||
const flights = createApplicationFlights({
|
||||
surface,
|
||||
source: sources.flights,
|
||||
placement: layerPlacement(placement, 'aircraft'),
|
||||
militaryRegistry,
|
||||
resolveAsset,
|
||||
});
|
||||
const military = createApplicationMilitary({
|
||||
surface,
|
||||
source: sources.military,
|
||||
placement: layerPlacement(placement, 'military'),
|
||||
militaryRegistry,
|
||||
resolveAsset,
|
||||
});
|
||||
const vessels = createApplicationVessels({
|
||||
source: sources.vessels,
|
||||
placement: layerPlacement(placement, 'vessels'),
|
||||
options: vesselOptions,
|
||||
displayParams: () => flights.getParams(),
|
||||
...(resolveAsset ? { resolveAsset } : {}),
|
||||
@@ -173,6 +181,7 @@ export function createApplicationCatalog({
|
||||
createApplicationTransit({
|
||||
surface,
|
||||
source: sources.transit,
|
||||
placement: layerPlacement(placement, 'transit'),
|
||||
displayParams: () => flights.getParams(),
|
||||
...(resolveAsset ? { resolveAsset } : {}),
|
||||
}),
|
||||
@@ -211,6 +220,7 @@ export function createApplicationCatalog({
|
||||
createApplicationRail({
|
||||
surface,
|
||||
source: sources.rail,
|
||||
placement: layerPlacement(placement, 'rail'),
|
||||
displayParams: () => flights.getParams(),
|
||||
...(resolveAsset ? { resolveAsset } : {}),
|
||||
}),
|
||||
|
||||
@@ -6,6 +6,11 @@ import { createStandaloneLayerSources } from '../standalone/layerSources.js';
|
||||
import { catalogControlServices } from './catalog.js';
|
||||
import { LayerLifecycle } from '../data/lifecycle.js';
|
||||
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
|
||||
import { worldClock } from '../time/worldClock.js';
|
||||
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
};
|
||||
|
||||
function fixtureSources(ids, calls) {
|
||||
const sources = createStandaloneLayerSources();
|
||||
@@ -27,6 +32,7 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
t.after(() => {
|
||||
a.abort();
|
||||
b.abort();
|
||||
worldClock.goLive();
|
||||
});
|
||||
const callsA = [];
|
||||
const callsB = [];
|
||||
@@ -53,7 +59,10 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
'the hardware-local layer is never serialized into links',
|
||||
);
|
||||
assert.notEqual(first.weatherClock, second.weatherClock);
|
||||
await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z');
|
||||
// Time moves on the world clock, which the catalog's weather clock follows.
|
||||
assert.equal(first.weatherClock.world, worldClock);
|
||||
worldClock.seek(Date.parse('2026-09-21T12:00:00.000Z'));
|
||||
await flush();
|
||||
assert.match(
|
||||
first.get('wind').getRowControls().info,
|
||||
/Forecast · does not follow history/,
|
||||
@@ -111,9 +120,16 @@ test('catalogs construct distinct layers and classification from their supplied
|
||||
assert.equal(first.militaryRegistry.isMilitaryIcao('def456'), false);
|
||||
assert.equal(second.militaryRegistry.isMilitaryIcao('def456'), true);
|
||||
a.abort();
|
||||
worldClock.seek(Date.parse('2026-09-21T13:00:00.000Z'));
|
||||
await flush();
|
||||
assert.equal(
|
||||
await first.weatherClock.setTarget('2026-09-21T13:00:00.000Z'),
|
||||
false,
|
||||
first.weatherClock.getState().target,
|
||||
'2026-09-21T12:00:00.000Z',
|
||||
'an aborted catalog no longer follows the world clock',
|
||||
);
|
||||
assert.equal(
|
||||
second.weatherClock.getState().target,
|
||||
'2026-09-21T13:00:00.000Z',
|
||||
);
|
||||
assert.equal(callsA[0].aborted, true);
|
||||
assert.equal(first.militaryRegistry.isMilitaryIcao('abc123'), false);
|
||||
@@ -218,9 +234,8 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
|
||||
};
|
||||
const shows = (layer, minutes) => {
|
||||
assert.equal(layer.provenance.window.minutes, minutes);
|
||||
const { info, legend } = layer.getRowControls();
|
||||
const { info } = layer.getRowControls();
|
||||
assert.match(info, new RegExp(`visited views over ${minutes} min`));
|
||||
assert.match(legend[0].blurb, new RegExp(`over ${minutes} minutes`));
|
||||
};
|
||||
shows(gnssLayer({ windowMs: 65 * 60_000 }), 65);
|
||||
shows(gnssLayer({}), 30);
|
||||
|
||||
Vendored
+2
@@ -11,6 +11,8 @@ import { t } from '../i18n/index.js';
|
||||
* whose address does not carry one. `localePicker: false` removes the language
|
||||
* picker, for a host that offers its own language choice (`switchLocale` from
|
||||
* the `./i18n` entry).
|
||||
* `services.cockpitSubjects` adds the application's own first-person subjects
|
||||
* to the Cockpit (src/cockpitSubjectProviders.js).
|
||||
*/
|
||||
export function createApplicationControls({
|
||||
scene: { viewer, mapStackController, operations },
|
||||
|
||||
@@ -16,9 +16,11 @@ import { fleetModelServices } from './fleetModels.js';
|
||||
* Construct one layer using the application scene owners and a supplied
|
||||
* source. `displayParams` reads the Flights layer's DISPLAY-rail 3D
|
||||
* preference, under which nearby vessels are drawn as fleet models.
|
||||
* `placement`: a host-supplied placement for its live vessels, or null.
|
||||
*/
|
||||
export function createApplicationVessels({
|
||||
source,
|
||||
placement = null,
|
||||
options = {},
|
||||
displayParams = null,
|
||||
resolveAsset,
|
||||
@@ -38,6 +40,7 @@ export function createApplicationVessels({
|
||||
worldFocus,
|
||||
render,
|
||||
readouts,
|
||||
placement,
|
||||
fleet: fleetModelServices({
|
||||
display: displayParams,
|
||||
...(resolveAsset ? { resolveAsset } : {}),
|
||||
|
||||
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
import * as recession from '../../data/aircraftRecession.js';
|
||||
|
||||
/** Construct one layer using the application scene owners and a supplied source. */
|
||||
/** Construct one layer using the application scene owners and a supplied source.
|
||||
* `placement`: a host-supplied placement for its live aircraft, or null. */
|
||||
export function createApplicationFlights({
|
||||
surface,
|
||||
source,
|
||||
militaryRegistry,
|
||||
placement = null,
|
||||
resolveAsset = (url) =>
|
||||
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
|
||||
}) {
|
||||
@@ -41,6 +43,7 @@ export function createApplicationFlights({
|
||||
render,
|
||||
groundSnap,
|
||||
recession,
|
||||
placement,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -12,11 +12,13 @@ import * as context from '../../data/contextStore.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
import * as recession from '../../data/aircraftRecession.js';
|
||||
|
||||
/** Construct one layer using the application scene owners and a supplied source. */
|
||||
/** Construct one layer using the application scene owners and a supplied source.
|
||||
* `placement`: a host-supplied placement for its live aircraft, or null. */
|
||||
export function createApplicationMilitary({
|
||||
surface,
|
||||
source,
|
||||
militaryRegistry,
|
||||
placement = null,
|
||||
resolveAsset = (url) =>
|
||||
`${import.meta.env?.BASE_URL || '/'}${url.replace(/^\//, '')}`,
|
||||
}) {
|
||||
@@ -41,6 +43,7 @@ export function createApplicationMilitary({
|
||||
render,
|
||||
groundSnap,
|
||||
recession,
|
||||
placement,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -16,13 +16,15 @@ import {
|
||||
* ground floor, the same floor Transit and the aircraft stand on.
|
||||
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
|
||||
* which nearby trains are drawn as fleet models.
|
||||
* @param {{surface: object, source?: object,
|
||||
* `placement` is a host-supplied placement for its live trains, or null.
|
||||
* @param {{surface: object, source?: object, placement?: object|null,
|
||||
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createApplicationRail({
|
||||
surface,
|
||||
source,
|
||||
placement = null,
|
||||
displayParams = null,
|
||||
resolveAsset,
|
||||
}) {
|
||||
@@ -36,6 +38,7 @@ export function createApplicationRail({
|
||||
sprites,
|
||||
picking,
|
||||
overlays,
|
||||
placement,
|
||||
credits: { registerDynamicCredit, railFeedCredit },
|
||||
ground: {
|
||||
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
|
||||
|
||||
@@ -23,13 +23,15 @@ import {
|
||||
* `displayParams` reads the Flights layer's DISPLAY-rail 3D preference, under
|
||||
* which nearby vehicles are drawn as fleet models.
|
||||
*
|
||||
* @param {{surface: object, source?: object,
|
||||
* `placement` is a host-supplied placement for its live vehicles, or null.
|
||||
* @param {{surface: object, source?: object, placement?: object|null,
|
||||
* displayParams?: () => object|null, resolveAsset?: (url: string) => string}} options
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createApplicationTransit({
|
||||
surface,
|
||||
source,
|
||||
placement = null,
|
||||
displayParams = null,
|
||||
resolveAsset,
|
||||
}) {
|
||||
@@ -43,6 +45,7 @@ export function createApplicationTransit({
|
||||
sprites,
|
||||
picking,
|
||||
overlays,
|
||||
placement,
|
||||
credits: { registerDynamicCredit, transitFeedCredit },
|
||||
ground: {
|
||||
GROUND_FLOOR_LIFT_M: groundFloor.GROUND_FLOOR_LIFT_M,
|
||||
|
||||
@@ -13,6 +13,8 @@ import { initLogoGaze } from '../logoGaze.js';
|
||||
import {
|
||||
uninstallRenderGovernor,
|
||||
governorRequestRender,
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
} from '../renderGovernor.js';
|
||||
import { describeError } from './errors.js';
|
||||
import { isEmbeddedInline } from './embed.js';
|
||||
@@ -73,6 +75,12 @@ export async function createApplicationScene({
|
||||
followWorldTime(viewer, worldTimeFor('sky'), {
|
||||
subscribe: worldClock.subscribe,
|
||||
requestRender: () => governorRequestRender('world-time'),
|
||||
// A playing world time moves something every frame: draw at the
|
||||
// display's rate meanwhile, not the parked scene's cap.
|
||||
onPlaying: (playing) =>
|
||||
playing
|
||||
? holdContinuousRender('world-time')
|
||||
: releaseContinuousRender('world-time'),
|
||||
}),
|
||||
);
|
||||
defer(installFreeLookHeightLimit(viewer));
|
||||
|
||||
+4
-1
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { IDLE_FRAME_RATE } from '../renderGovernor.js';
|
||||
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js';
|
||||
import { StarrySky } from '../sky/starrySky.js';
|
||||
import {
|
||||
@@ -420,7 +421,9 @@ export function createApplicationViewer({
|
||||
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
|
||||
);
|
||||
try {
|
||||
viewer.targetFrameRate = 60;
|
||||
// Until the render governor takes over (app/tools.js), tick at the idle
|
||||
// rate so the startup load does not compete with drawing at 240 fps.
|
||||
viewer.targetFrameRate = IDLE_FRAME_RATE;
|
||||
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
|
||||
// Keep Cesium's distance-aware zoom and collision limits, with less travel
|
||||
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
|
||||
|
||||
+41
-20
@@ -26,10 +26,7 @@ import {
|
||||
setSignalCollapsed,
|
||||
} from './ui/cockpitLayout.js';
|
||||
import { createBriefState } from './ui/cockpitBriefPages.js';
|
||||
import {
|
||||
publishBriefView,
|
||||
setBriefAutoRotate,
|
||||
} from './ui/cockpitBriefing.js';
|
||||
import { publishBriefView, setBriefAutoRotate } from './ui/cockpitBriefing.js';
|
||||
import { CockpitDisplayPortal } from './ui/cockpitDisplayPortal.js';
|
||||
import { _handleContextLayerChange } from './ui/contextLayerChanges.js';
|
||||
import { clearSelectedLayers } from './ui/contextActions.js';
|
||||
@@ -438,13 +435,10 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
|
||||
/data-cockpit-launcher="radio"[\s\S]*?id="cockpit-radio-toggle-btn"/,
|
||||
);
|
||||
const cockpitRadio = html.match(
|
||||
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<\/aside>/,
|
||||
/id="cockpit-radio-panel"[\s\S]*?<\/div>\s*<\/div>\s*<div class="cockpit-utility-rail/,
|
||||
);
|
||||
assert.ok(cockpitRadio, 'Cockpit compact Radio controls are missing');
|
||||
assert.doesNotMatch(
|
||||
cockpitRadio[0],
|
||||
/radio-filter|radio-tuner/,
|
||||
);
|
||||
assert.doesNotMatch(cockpitRadio[0], /radio-filter|radio-tuner/);
|
||||
assert.match(
|
||||
css,
|
||||
/\.cockpit-utility-controls[\s\S]*?top:\s*var\(\s*--cockpit-utility-top/,
|
||||
@@ -530,12 +524,12 @@ test('Cockpit owns a focused shared Display portal and compact Radio controls',
|
||||
);
|
||||
});
|
||||
|
||||
test('Display orders 3D above Celestial, Clean UI below it, and Parameters below Detection', () => {
|
||||
test('Visual orders Parameters below Detection, 3D below them, and Clean UI above the Effects', () => {
|
||||
const display = html.match(/id="pp-toggles"[\s\S]*?id="clean-view-exit"/);
|
||||
assert.ok(display, 'Display markup is missing');
|
||||
assert.match(
|
||||
display[0],
|
||||
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="celestial-toggle"[\s\S]*?id="clean-view-toggle"/,
|
||||
/id="detection-toggle"[\s\S]*?id="param-slider-panel"[\s\S]*?id="models3d-toggle"[\s\S]*?id="scope-toggle"[\s\S]*?id="clean-view-toggle"[\s\S]*?class="pp-section-heading">Effects<[\s\S]*?id="celestial-toggle"/,
|
||||
);
|
||||
assert.equal(
|
||||
(html.match(/id="param-slider-panel"/g) || []).length,
|
||||
@@ -811,18 +805,27 @@ test('Reset releases Contact camera ownership through its selection-preserving r
|
||||
);
|
||||
assert.match(ui, /onReset: \(\) => this\.resetToGlobeView\(\)/);
|
||||
assert.match(ui, /this\._connectGlobeReset\?\.\(this\._locationControls\)/);
|
||||
assert.match(controls, /reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/);
|
||||
assert.match(
|
||||
controls,
|
||||
/reset\(\) \{\s*if \(!this\.destroyed\) return this\.onReset\(\);/,
|
||||
);
|
||||
// Both reset buttons ask the one reset owner.
|
||||
const globeActions = fs.readFileSync(
|
||||
path.join(ROOT, 'src', 'ui', 'views', 'panels', 'GlobeActions.vue'),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(globeActions, /id="reset-globe-view"[^>]*@click="act\('reset'\)"/);
|
||||
assert.match(
|
||||
globeActions,
|
||||
/id="reset-globe-view"[^>]*@click="act\('reset'\)"/,
|
||||
);
|
||||
const cockpitView = readRadioSource(
|
||||
new URL('./ui/views/CockpitView.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(cockpitView, /id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/);
|
||||
assert.match(
|
||||
cockpitView,
|
||||
/id="cockpit-reset-globe"[^>]*@click="globe\.act\('reset'\)"/,
|
||||
);
|
||||
assert.match(
|
||||
cockpitEnter.toString(),
|
||||
/Object\.assign\(this\.presence, \{\s*active: true,/,
|
||||
@@ -1193,7 +1196,10 @@ test('cockpit summary presents the focused item as Contact', () => {
|
||||
const match = html.match(/<aside id="cockpit-context"[\s\S]*?<\/aside>/);
|
||||
assert.ok(match, 'cockpit Contact summary is missing');
|
||||
assert.match(match[0], /aria-label="Contact cockpit summary"/);
|
||||
assert.match(match[0], /class="cockpit-card-kicker cockpit-context-kicker">CONTACT</);
|
||||
assert.match(
|
||||
match[0],
|
||||
/class="cockpit-card-kicker cockpit-context-kicker">CONTACT</,
|
||||
);
|
||||
assert.match(match[0], /aria-label="Contact navigation"/);
|
||||
assert.match(
|
||||
match[0],
|
||||
@@ -1408,15 +1414,30 @@ test('Contact folded for one Cockpit left panel comes back only once neither is
|
||||
const previous = globalThis.document;
|
||||
const panels = {};
|
||||
globalThis.document = { getElementById: (id) => panels[id] ?? null };
|
||||
const panel = (...classes) => ({ classList: { contains: (name) => classes.includes(name) } });
|
||||
const panel = (...classes) => ({
|
||||
classList: { contains: (name) => classes.includes(name) },
|
||||
});
|
||||
try {
|
||||
const otherOpen = (id) => PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
|
||||
const otherOpen = (id) =>
|
||||
PanelChrome.prototype._otherCockpitLeftPanelOpen(id);
|
||||
panels['data-panel'] = panel('collapsed');
|
||||
assert.equal(otherOpen('utilities-panel'), false, 'Data Layers closed: restore');
|
||||
assert.equal(
|
||||
otherOpen('utilities-panel'),
|
||||
false,
|
||||
'Data Layers closed: restore',
|
||||
);
|
||||
panels['data-panel'] = panel('collapsed', 'layout-auto-collapsed');
|
||||
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers comes back: keep Contact folded');
|
||||
assert.equal(
|
||||
otherOpen('utilities-panel'),
|
||||
true,
|
||||
'Data Layers comes back: keep Contact folded',
|
||||
);
|
||||
panels['data-panel'] = panel();
|
||||
assert.equal(otherOpen('utilities-panel'), true, 'Data Layers open: keep it folded');
|
||||
assert.equal(
|
||||
otherOpen('utilities-panel'),
|
||||
true,
|
||||
'Data Layers open: keep it folded',
|
||||
);
|
||||
} finally {
|
||||
globalThis.document = previous;
|
||||
}
|
||||
|
||||
+68
-2
@@ -32,8 +32,15 @@ export function slewHeading(current, target, maxStepDeg) {
|
||||
* then uses this amount to converge on the layer's delayed display position.
|
||||
* Capping correction below forward speed prevents a late feed fix from
|
||||
* becoming a first-person surge or reversal while still removing drift.
|
||||
* @param {number} [maxDtSec] The longest step corrected for: 0.1 s, or an
|
||||
* application subject's own (cockpitSubjectStepSec).
|
||||
*/
|
||||
export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
|
||||
export function cockpitAnchorCorrectionStep(
|
||||
distanceM,
|
||||
speedMps,
|
||||
dtSec,
|
||||
maxDtSec = 0.1,
|
||||
) {
|
||||
if (
|
||||
!Number.isFinite(distanceM) ||
|
||||
distanceM <= 0 ||
|
||||
@@ -41,13 +48,36 @@ export function cockpitAnchorCorrectionStep(distanceM, speedMps, dtSec) {
|
||||
dtSec <= 0
|
||||
)
|
||||
return 0;
|
||||
const dt = Math.min(0.1, dtSec);
|
||||
const dt = Math.min(
|
||||
Number.isFinite(maxDtSec) && maxDtSec > 0 ? maxDtSec : 0.1,
|
||||
dtSec,
|
||||
);
|
||||
const speed = Number.isFinite(speedMps) ? Math.max(0, speedMps) : 0;
|
||||
const eased = distanceM * (1 - Math.exp(-1.25 * dt));
|
||||
const correctionRateMps = Math.max(0.75, speed * 0.22);
|
||||
return Math.min(distanceM, eased, correctionRateMps * dt);
|
||||
}
|
||||
|
||||
/**
|
||||
* The seconds an application subject's camera update advances its heading
|
||||
* slew, ground lift and anchor by: the time since the last update, at most
|
||||
* its update interval plus 0.1 s. A subject updated every 500 ms then turns
|
||||
* and eases at its configured rates, while a long stall (a hidden tab) still
|
||||
* moves it no further than one late update would.
|
||||
* @param {number} elapsedMs Time since the last camera update.
|
||||
* @param {number} intervalMs The subject's update interval (0: every frame).
|
||||
* @returns {number}
|
||||
*/
|
||||
export function cockpitSubjectStepSec(elapsedMs, intervalMs) {
|
||||
const elapsedSec = Number.isFinite(elapsedMs)
|
||||
? Math.max(0, elapsedMs) / 1000
|
||||
: 0;
|
||||
const intervalSec = Number.isFinite(intervalMs)
|
||||
? Math.max(0, intervalMs) / 1000
|
||||
: 0;
|
||||
return Math.min(intervalSec + 0.1, elapsedSec);
|
||||
}
|
||||
|
||||
/** Return whether a throttled cockpit presentation update is due. */
|
||||
export function cockpitUiUpdateDue(nowMs, lastUpdateMs, intervalMs) {
|
||||
if (!Number.isFinite(nowMs) || !Number.isFinite(intervalMs) || intervalMs < 0)
|
||||
@@ -68,6 +98,42 @@ export function cockpitSurfaceWaitExpired(nowMs, startedMs, timeoutMs = 5000) {
|
||||
return nowMs - startedMs >= timeoutMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* How fast the clearance a ground clamp adds under an application subject's
|
||||
* eye comes and goes (m/s).
|
||||
*/
|
||||
export const COCKPIT_SUBJECT_LIFT_MPS = 1.5;
|
||||
|
||||
/**
|
||||
* The lift the ground clamp gives an application subject's eye this update.
|
||||
* The floor is read from coarse cells that refine as tiles load, so the lift
|
||||
* it asks for jumps; a ridden eye takes the clearance part of it at
|
||||
* `rateMps`, while what it needs to stay out of the floor itself (`hardM`)
|
||||
* applies at once.
|
||||
* @param {number|null} previousM The lift given last update; null on entry.
|
||||
* @param {number} targetM The lift the floor and clearance ask for (m).
|
||||
* @param {number} hardM The lift that keeps the eye out of the floor (m).
|
||||
* @param {number} dtSec Seconds since the last update.
|
||||
* @param {number} [rateMps]
|
||||
* @returns {number} At least 0, at least `hardM`.
|
||||
*/
|
||||
export function easeCockpitLift(
|
||||
previousM,
|
||||
targetM,
|
||||
hardM,
|
||||
dtSec,
|
||||
rateMps = COCKPIT_SUBJECT_LIFT_MPS,
|
||||
) {
|
||||
const target = Number.isFinite(targetM) ? Math.max(0, targetM) : 0;
|
||||
const hard = Number.isFinite(hardM) ? Math.max(0, hardM) : 0;
|
||||
if (!Number.isFinite(previousM)) return Math.max(target, hard);
|
||||
const step =
|
||||
Math.max(0, Number.isFinite(rateMps) ? rateMps : 0) *
|
||||
Math.max(0, Number.isFinite(dtSec) ? dtSec : 0);
|
||||
const eased = previousM + Math.max(-step, Math.min(step, target - previousM));
|
||||
return Math.max(0, hard, eased);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the cockpit camera above the shared rendered-surface floor.
|
||||
* Unknown floors preserve the proposed camera height.
|
||||
|
||||
@@ -8,8 +8,11 @@ import {
|
||||
cockpitAnchorCorrectionStep,
|
||||
cockpitAltitudeDisplayFt,
|
||||
cockpitGroundSafeHeight,
|
||||
cockpitSubjectStepSec,
|
||||
cockpitSurfaceWaitExpired,
|
||||
cockpitUiUpdateDue,
|
||||
COCKPIT_SUBJECT_LIFT_MPS,
|
||||
easeCockpitLift,
|
||||
compassDivisions,
|
||||
compassMarkerSlot,
|
||||
scrollingCompassDivisions,
|
||||
@@ -56,6 +59,28 @@ test('cockpit anchor correction bounds late-fix catch-up and render stalls', ()
|
||||
assert.equal(cockpitAnchorCorrectionStep(Number.NaN, 250, 0.1), 0);
|
||||
});
|
||||
|
||||
test('an application subject on a slow cadence is corrected for its whole step', () => {
|
||||
// The built-in views' step stays capped at 0.1 s...
|
||||
const capped = cockpitAnchorCorrectionStep(100, 0, 0.5);
|
||||
assert.equal(capped, cockpitAnchorCorrectionStep(100, 0, 0.1));
|
||||
// ...while a subject updated every 500 ms is corrected for all of it.
|
||||
const whole = cockpitAnchorCorrectionStep(100, 0, 0.5, 0.5);
|
||||
assert.ok(Math.abs(whole / capped - 5) < 1e-9);
|
||||
assert.equal(cockpitAnchorCorrectionStep(100, 0, 0.5, Number.NaN), capped);
|
||||
});
|
||||
|
||||
test('an application subject steps by its interval, never by a long stall', () => {
|
||||
assert.equal(cockpitSubjectStepSec(16, 0), 0.016);
|
||||
assert.equal(cockpitSubjectStepSec(500, 500), 0.5);
|
||||
assert.equal(cockpitSubjectStepSec(520, 500), 0.52);
|
||||
// A hidden tab's minutes count as one late update.
|
||||
assert.equal(cockpitSubjectStepSec(60_000, 500), 0.6);
|
||||
assert.equal(cockpitSubjectStepSec(60_000, 0), 0.1);
|
||||
assert.equal(cockpitSubjectStepSec(-5, 500), 0);
|
||||
assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0);
|
||||
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1);
|
||||
});
|
||||
|
||||
test('cockpit camera clearance never falls below the rendered ground floor', () => {
|
||||
assert.equal(cockpitGroundSafeHeight(47, 57, 12), 69);
|
||||
assert.equal(cockpitGroundSafeHeight(1200, 57, 12), 1200);
|
||||
@@ -435,3 +460,30 @@ test('cockpit emergency wording states the broadcast code, not a conclusion', ()
|
||||
assert.equal(formatCockpitEmergency(null), null);
|
||||
assert.equal(formatCockpitEmergency({ label: '' }), null);
|
||||
});
|
||||
|
||||
test('an application subject’s ground lift eases its clearance, never the floor', () => {
|
||||
// On entry the lift asked for applies at once.
|
||||
assert.equal(easeCockpitLift(null, 1.5, 0, 0.016), 1.5);
|
||||
// A floor cell that rises by a metre is met at the lift rate...
|
||||
let lift = 0;
|
||||
const frames = [];
|
||||
for (let i = 0; i < 60; i += 1) {
|
||||
lift = easeCockpitLift(lift, 1, 0, 0.016);
|
||||
frames.push(lift);
|
||||
}
|
||||
assert.ok(frames[0] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9);
|
||||
for (let i = 1; i < frames.length; i += 1)
|
||||
assert.ok(
|
||||
frames[i] - frames[i - 1] <= COCKPIT_SUBJECT_LIFT_MPS * 0.016 + 1e-9,
|
||||
);
|
||||
assert.ok(Math.abs(frames.at(-1) - 1) < 1e-9, 'reached in under a second');
|
||||
// ...and given back the same way.
|
||||
assert.ok(Math.abs(easeCockpitLift(1, 0, 0, 0.1) - 0.85) < 1e-9);
|
||||
// What keeps the eye out of the floor itself is never eased.
|
||||
assert.equal(easeCockpitLift(0, 201.5, 200, 0.016), 200);
|
||||
assert.equal(
|
||||
easeCockpitLift(0.2, -3, -3, 0.016),
|
||||
0.2 - COCKPIT_SUBJECT_LIFT_MPS * 0.016,
|
||||
);
|
||||
assert.equal(easeCockpitLift(0, Number.NaN, Number.NaN, 0.016), 0);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* @module cockpitProgress
|
||||
* @description Lay out a subject's progress line (cockpitSubjectProviders.js)
|
||||
* at a width in pixels: where each tick, label and the marker go.
|
||||
*
|
||||
* Ticks sit at fractions of the line, 0 at the left. Ticks closer than
|
||||
* `minTickPx` merge, so a long run still reads as a line: a labelled tick
|
||||
* keeps its place and takes in the bare ticks beside it, and bare ticks merge
|
||||
* with each other at their mean place. A merged tick takes the strongest tone
|
||||
* of those it holds. Labels never overlap: where two would, the one of lower
|
||||
* priority is left out (on a tie, the later one).
|
||||
*
|
||||
* Pure: no DOM.
|
||||
*/
|
||||
|
||||
/** Bare ticks closer than this merge (px). */
|
||||
export const COCKPIT_PROGRESS_MIN_TICK_PX = 6;
|
||||
/** Room kept between two labels (px). */
|
||||
export const COCKPIT_PROGRESS_LABEL_GAP_PX = 8;
|
||||
|
||||
/** Tones from weakest to strongest, for a merged tick. */
|
||||
const TONE_RANK = Object.freeze([
|
||||
'muted',
|
||||
'normal',
|
||||
'live',
|
||||
'estimate',
|
||||
'warning',
|
||||
'alert',
|
||||
]);
|
||||
const stronger = (a, b) =>
|
||||
TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a;
|
||||
|
||||
/** A label's width estimate (px): its longer line in small capitals. */
|
||||
export function estimateProgressLabelPx(label) {
|
||||
const longest = Math.max(
|
||||
String(label?.text ?? '').length,
|
||||
String(label?.detail ?? '').length,
|
||||
);
|
||||
return longest * 6.4 + 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* The progress line at `widthPx`, or null when there is nothing to draw.
|
||||
* @param {{ticks: Array<{at: number, tone: string, label: object|null}>,
|
||||
* marker: {at: number, dwell: boolean}|null, tag: string}|null} progress
|
||||
* As cockpitSubjectHudView gives it: ticks sorted by `at`.
|
||||
* @param {number} widthPx
|
||||
* @param {{minTickPx?: number, gapPx?: number,
|
||||
* measure?: (label: object) => number}} [options]
|
||||
* @returns {{ticks: Array<{x: number, tone: string, count: number,
|
||||
* labelled: boolean}>, labels: Array<{x: number, left: number,
|
||||
* width: number, align: string, text: string, detail: string,
|
||||
* tone: string}>, marker: {x: number, dwell: boolean}|null,
|
||||
* travelledX: number, tag: string}|null}
|
||||
*/
|
||||
export function cockpitProgressLayout(
|
||||
progress,
|
||||
widthPx,
|
||||
{
|
||||
minTickPx = COCKPIT_PROGRESS_MIN_TICK_PX,
|
||||
gapPx = COCKPIT_PROGRESS_LABEL_GAP_PX,
|
||||
measure = estimateProgressLabelPx,
|
||||
} = {},
|
||||
) {
|
||||
const ticks = progress?.ticks;
|
||||
if (!Array.isArray(ticks) || ticks.length < 2) return null;
|
||||
if (!Number.isFinite(widthPx) || widthPx <= 0) return null;
|
||||
const placed = ticks.map((tick, order) => ({
|
||||
x: tick.at * widthPx,
|
||||
tone: tick.tone,
|
||||
label: tick.label,
|
||||
order,
|
||||
}));
|
||||
const labelled = placed.filter((tick) => tick.label);
|
||||
// Bare ticks beside a labelled one go into it.
|
||||
const kept = labelled.map((tick) => ({
|
||||
x: tick.x,
|
||||
tone: tick.tone,
|
||||
count: 1,
|
||||
labelled: true,
|
||||
label: tick.label,
|
||||
order: tick.order,
|
||||
}));
|
||||
const bare = [];
|
||||
for (const tick of placed) {
|
||||
if (tick.label) continue;
|
||||
const host = kept.find((entry) => Math.abs(entry.x - tick.x) < minTickPx);
|
||||
if (host) {
|
||||
host.tone = stronger(host.tone, tick.tone);
|
||||
host.count += 1;
|
||||
} else bare.push(tick);
|
||||
}
|
||||
// Bare ticks in a chain closer than minTickPx merge at their mean place.
|
||||
let cluster = null;
|
||||
const flush = () => {
|
||||
if (!cluster) return;
|
||||
kept.push({
|
||||
x: cluster.sum / cluster.count,
|
||||
tone: cluster.tone,
|
||||
count: cluster.count,
|
||||
labelled: false,
|
||||
label: null,
|
||||
order: cluster.order,
|
||||
});
|
||||
cluster = null;
|
||||
};
|
||||
for (const tick of bare) {
|
||||
if (cluster && tick.x - cluster.last < minTickPx) {
|
||||
cluster.sum += tick.x;
|
||||
cluster.count += 1;
|
||||
cluster.last = tick.x;
|
||||
cluster.tone = stronger(cluster.tone, tick.tone);
|
||||
} else {
|
||||
flush();
|
||||
cluster = {
|
||||
sum: tick.x,
|
||||
count: 1,
|
||||
last: tick.x,
|
||||
tone: tick.tone,
|
||||
order: tick.order,
|
||||
};
|
||||
}
|
||||
}
|
||||
flush();
|
||||
kept.sort((a, b) => a.x - b.x || a.order - b.order);
|
||||
|
||||
// Labels by priority; one that would overlap a placed label is left out.
|
||||
const boxes = [];
|
||||
const candidates = kept
|
||||
.filter((tick) => tick.labelled)
|
||||
.sort((a, b) => b.label.priority - a.label.priority || a.order - b.order);
|
||||
for (const tick of candidates) {
|
||||
const width = Math.min(widthPx, Math.max(0, measure(tick.label)));
|
||||
let left =
|
||||
tick.label.align === 'start'
|
||||
? tick.x
|
||||
: tick.label.align === 'end'
|
||||
? tick.x - width
|
||||
: tick.x - width / 2;
|
||||
left = Math.min(Math.max(0, left), widthPx - width);
|
||||
const right = left + width;
|
||||
if (
|
||||
boxes.some((box) => left < box.right + gapPx && right > box.left - gapPx)
|
||||
)
|
||||
continue;
|
||||
boxes.push({
|
||||
x: tick.x,
|
||||
left,
|
||||
right,
|
||||
width,
|
||||
align: tick.label.align,
|
||||
text: tick.label.text,
|
||||
detail: tick.label.detail,
|
||||
tone: tick.tone,
|
||||
order: tick.order,
|
||||
});
|
||||
}
|
||||
boxes.sort((a, b) => a.left - b.left);
|
||||
const marker = progress.marker
|
||||
? { x: progress.marker.at * widthPx, dwell: progress.marker.dwell }
|
||||
: null;
|
||||
return {
|
||||
ticks: kept.map(({ x, tone, count, labelled: isLabelled }) => ({
|
||||
x,
|
||||
tone,
|
||||
count,
|
||||
labelled: isLabelled,
|
||||
})),
|
||||
labels: boxes.map(({ x, left, width, align, text, detail, tone }) => ({
|
||||
x,
|
||||
left,
|
||||
width,
|
||||
align,
|
||||
text,
|
||||
detail,
|
||||
tone,
|
||||
})),
|
||||
marker,
|
||||
travelledX: marker ? marker.x : 0,
|
||||
tag: progress.tag || '',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// src/cockpitProgress.test.mjs — a subject's progress line laid out at a
|
||||
// width: close bare ticks merge, labelled ticks keep their place, labels never
|
||||
// overlap (the lower priority gives way) and the part before the marker is
|
||||
// the travelled part.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { cockpitProgressLayout } from './cockpitProgress.js';
|
||||
|
||||
const tick = (at, label = null, tone = 'normal') => ({ at, tone, label });
|
||||
const label = (text, priority, align = 'center', detail = '') => ({
|
||||
text,
|
||||
detail,
|
||||
priority,
|
||||
align,
|
||||
});
|
||||
/** Every label is 50 px wide. */
|
||||
const measure = () => 50;
|
||||
|
||||
test('nothing is drawn without two ticks or a width', () => {
|
||||
assert.equal(cockpitProgressLayout(null, 500), null);
|
||||
assert.equal(cockpitProgressLayout({ ticks: [tick(0)] }, 500), null);
|
||||
assert.equal(
|
||||
cockpitProgressLayout({ ticks: [tick(0), tick(1)], marker: null }, 0),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('ticks closer than the minimum spacing merge, keeping the strongest tone', () => {
|
||||
const layout = cockpitProgressLayout(
|
||||
{
|
||||
ticks: [
|
||||
tick(0, label('A', 1, 'start')),
|
||||
tick(0.1),
|
||||
tick(0.101, null, 'warning'),
|
||||
tick(0.102),
|
||||
tick(0.5),
|
||||
tick(1, label('Z', 1, 'end')),
|
||||
],
|
||||
marker: { at: 0.3, dwell: false },
|
||||
tag: 'TIMETABLE',
|
||||
},
|
||||
1000,
|
||||
{ measure },
|
||||
);
|
||||
assert.deepEqual(
|
||||
layout.ticks.map(({ x, count, tone, labelled }) => [
|
||||
Math.round(x),
|
||||
count,
|
||||
tone,
|
||||
labelled,
|
||||
]),
|
||||
[
|
||||
[0, 1, 'normal', true],
|
||||
[101, 3, 'warning', false],
|
||||
[500, 1, 'normal', false],
|
||||
[1000, 1, 'normal', true],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(layout.marker, { x: 300, dwell: false });
|
||||
assert.equal(layout.travelledX, 300);
|
||||
assert.equal(layout.tag, 'TIMETABLE');
|
||||
});
|
||||
|
||||
test('a labelled tick keeps its place and takes in the bare ticks beside it', () => {
|
||||
const layout = cockpitProgressLayout(
|
||||
{
|
||||
ticks: [
|
||||
tick(0, label('A', 1, 'start')),
|
||||
tick(0.498),
|
||||
tick(0.5, label('Next', 3), 'alert'),
|
||||
tick(0.503, null, 'warning'),
|
||||
tick(1, label('Z', 1, 'end')),
|
||||
],
|
||||
marker: null,
|
||||
},
|
||||
1000,
|
||||
{ measure },
|
||||
);
|
||||
const next = layout.ticks.find(({ x }) => Math.round(x) === 500);
|
||||
assert.equal(next.count, 3);
|
||||
assert.equal(next.labelled, true);
|
||||
assert.equal(next.tone, 'alert');
|
||||
assert.equal(layout.ticks.length, 3);
|
||||
assert.equal(layout.marker, null);
|
||||
assert.equal(layout.travelledX, 0);
|
||||
});
|
||||
|
||||
test('labels hang from their ticks inside the line, and overlaps give way by priority', () => {
|
||||
const layout = cockpitProgressLayout(
|
||||
{
|
||||
ticks: [
|
||||
tick(0, label('First', 1, 'start')),
|
||||
tick(0.04, label('Previous', 2)),
|
||||
tick(0.5, label('Next', 3)),
|
||||
tick(0.52, label('Close', 0)),
|
||||
tick(1, label('Last', 1, 'end')),
|
||||
],
|
||||
marker: { at: 0.2, dwell: true },
|
||||
},
|
||||
1000,
|
||||
{ measure },
|
||||
);
|
||||
assert.deepEqual(
|
||||
layout.labels.map(({ text, left }) => [text, Math.round(left)]),
|
||||
[
|
||||
['Previous', 15],
|
||||
['Next', 475],
|
||||
['Last', 950],
|
||||
],
|
||||
);
|
||||
// The first stop's label would cover the previous stop's: it gives way.
|
||||
assert.ok(!layout.labels.some(({ text }) => text === 'First'));
|
||||
assert.ok(!layout.labels.some(({ text }) => text === 'Close'));
|
||||
assert.deepEqual(layout.marker, { x: 200, dwell: true });
|
||||
});
|
||||
|
||||
test('a centred label at an edge is clamped inside the line', () => {
|
||||
const layout = cockpitProgressLayout(
|
||||
{ ticks: [tick(0, label('Edge', 1)), tick(1)], marker: null },
|
||||
300,
|
||||
{ measure },
|
||||
);
|
||||
assert.equal(layout.labels[0].left, 0);
|
||||
const right = cockpitProgressLayout(
|
||||
{ ticks: [tick(0), tick(1, label('Edge', 1))], marker: null },
|
||||
300,
|
||||
{ measure },
|
||||
);
|
||||
assert.equal(right.labels[0].left, 250);
|
||||
});
|
||||
|
||||
test('a long run of calls still lays out, every one a tick or part of one', () => {
|
||||
const ticks = Array.from({ length: 60 }, (_, i) => tick(i / 59));
|
||||
ticks[0].label = label('First', 1, 'start');
|
||||
ticks[59].label = label('Last', 1, 'end');
|
||||
const narrow = cockpitProgressLayout({ ticks, marker: null }, 200);
|
||||
const wide = cockpitProgressLayout({ ticks, marker: null }, 2000);
|
||||
const count = (layout) =>
|
||||
layout.ticks.reduce((sum, entry) => sum + entry.count, 0);
|
||||
assert.equal(count(narrow), 60);
|
||||
assert.equal(count(wide), 60);
|
||||
assert.ok(narrow.ticks.length < wide.ticks.length);
|
||||
assert.equal(wide.ticks.length, 60);
|
||||
});
|
||||
@@ -209,7 +209,7 @@ test('rows render the signals the controller presents', async (t) => {
|
||||
);
|
||||
assert.equal(status.className, 'warning');
|
||||
assert.equal(status.querySelector('div > strong').textContent, 'UNKNOWN');
|
||||
assert.equal(status.querySelector('button'), null);
|
||||
assert.equal(status.querySelector('button') === null, true);
|
||||
});
|
||||
|
||||
test('actual Context refresh retains the focused signal button across unchanged and changed details', async (t) => {
|
||||
@@ -315,7 +315,7 @@ test('removing the focused identity uses the shown briefing tab once and permits
|
||||
assert.equal(document.activeElement === f.signalTab(), true);
|
||||
assert.equal(f.focusCalls(), calls + 1);
|
||||
assert.equal(f.losses(), 0);
|
||||
assert.equal(f.signalTab().closest('[hidden]'), null);
|
||||
assert.equal(f.signalTab().closest('[hidden]') === null, true);
|
||||
// Traversal carries on forward from the footer tab.
|
||||
f.tab();
|
||||
assert.equal(document.activeElement === f.pageTab(1), true);
|
||||
|
||||
@@ -0,0 +1,644 @@
|
||||
/**
|
||||
* @module cockpitSubjectProviders
|
||||
* @description Subject providers: kinds of subject an application adds to the
|
||||
* Cockpit beside its own aircraft, satellite and vessel. A provider names the
|
||||
* subject entry would take, holds it while the view rides it, hands the camera
|
||||
* a frame each update and the HUD a view model, and releases it on exit. Core
|
||||
* knows nothing else about it.
|
||||
*
|
||||
* Everything a provider returns is normalized here before the Cockpit uses
|
||||
* it: a malformed provider is left out, a malformed frame ends the view, and a
|
||||
* malformed HUD view is read field by field, never thrown on.
|
||||
*
|
||||
* Pure: no Cesium, no DOM.
|
||||
*/
|
||||
|
||||
/** The kinds the Cockpit rides itself; no provider may take one. */
|
||||
export const COCKPIT_BUILT_IN_KINDS = Object.freeze([
|
||||
'aircraft',
|
||||
'satellite',
|
||||
'vessel',
|
||||
]);
|
||||
|
||||
/** The tones a provider's HUD texts may take. */
|
||||
export const COCKPIT_SUBJECT_TONES = Object.freeze([
|
||||
'normal',
|
||||
'muted',
|
||||
'live',
|
||||
'estimate',
|
||||
'warning',
|
||||
'alert',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The heights a frame may give (m, ellipsoidal): below the deepest dry
|
||||
* ground, above anything ridden near it; outside, the frame stands on the
|
||||
* floor.
|
||||
*/
|
||||
export const COCKPIT_SUBJECT_MIN_HEIGHT_M = -1_000;
|
||||
export const COCKPIT_SUBJECT_MAX_HEIGHT_M = 50_000;
|
||||
|
||||
/** The most readouts, sources and signals a HUD view shows. */
|
||||
export const COCKPIT_SUBJECT_MAX_READOUTS = 4;
|
||||
export const COCKPIT_SUBJECT_MAX_SOURCES = 4;
|
||||
export const COCKPIT_SUBJECT_MAX_SIGNALS = 4;
|
||||
/** The most ticks a progress line takes. */
|
||||
export const COCKPIT_SUBJECT_MAX_TICKS = 512;
|
||||
|
||||
const KIND_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
|
||||
const LAYER_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
||||
const ICON_PATTERN = /^[a-z0-9_]{1,40}$/;
|
||||
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
||||
const REQUIRED_METHODS = Object.freeze([
|
||||
'candidate',
|
||||
'hold',
|
||||
'read',
|
||||
'hud',
|
||||
'release',
|
||||
]);
|
||||
const RESERVED = new Set(COCKPIT_BUILT_IN_KINDS);
|
||||
const TONES = new Set(COCKPIT_SUBJECT_TONES);
|
||||
|
||||
const isObject = (value) =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
|
||||
|
||||
/**
|
||||
* `value` as display text: trimmed, at most `max` characters (the last one
|
||||
* an ellipsis when cut, the cut never inside a surrogate pair, so an emoji is
|
||||
* kept whole or left out); '' for anything that is not a string or a number.
|
||||
*/
|
||||
export function cockpitSubjectText(value, max) {
|
||||
if (typeof value !== 'string' && !finite(value)) return '';
|
||||
const text = String(value).replace(/\s+/g, ' ').trim();
|
||||
if (text.length <= max) return text;
|
||||
let end = max - 1;
|
||||
const last = text.charCodeAt(end - 1);
|
||||
if (last >= 0xd800 && last <= 0xdbff) end -= 1;
|
||||
return `${text.slice(0, end)}…`;
|
||||
}
|
||||
|
||||
const tone = (value) => (TONES.has(value) ? value : 'normal');
|
||||
|
||||
/** A Material Symbols entry face, or null. */
|
||||
function faceOf(raw) {
|
||||
if (!isObject(raw)) return null;
|
||||
const label = cockpitSubjectText(raw.label, 16);
|
||||
if (typeof raw.icon !== 'string' || !ICON_PATTERN.test(raw.icon) || !label)
|
||||
return null;
|
||||
return Object.freeze({ icon: raw.icon, label });
|
||||
}
|
||||
|
||||
/** The labels a provider gives, normalized, or null without the required. */
|
||||
function labelsOf(raw) {
|
||||
if (!isObject(raw)) return null;
|
||||
const labels = {
|
||||
view: cockpitSubjectText(raw.view, 48),
|
||||
exit: cockpitSubjectText(raw.exit, 48),
|
||||
exitText: cockpitSubjectText(raw.exitText, 24),
|
||||
kicker: cockpitSubjectText(raw.kicker, 48),
|
||||
};
|
||||
return labels.view && labels.exit && labels.exitText
|
||||
? Object.freeze(labels)
|
||||
: null;
|
||||
}
|
||||
|
||||
/** A provider's look, normalized, or null without an aheadLabel. */
|
||||
function lookOf(raw) {
|
||||
if (!isObject(raw)) return null;
|
||||
const aheadLabel = cockpitSubjectText(raw.aheadLabel, 64);
|
||||
if (!aheadLabel) return null;
|
||||
return Object.freeze({
|
||||
restPitchDeg: finite(raw.restPitchDeg)
|
||||
? clamp(raw.restPitchDeg, -90, 90)
|
||||
: 0,
|
||||
aheadLabel,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider's worded member `key` as it reads now, normalized: the value,
|
||||
* or what the function it is returns when called on `provider` (so it can
|
||||
* follow the page's language); null when it is malformed or a read throws.
|
||||
* Reading the member, and reading what it gives, runs provider code too (a
|
||||
* getter), so both are guarded as the call is.
|
||||
*/
|
||||
function wordedNow(provider, key, normalize) {
|
||||
try {
|
||||
const value = provider[key];
|
||||
return (
|
||||
normalize(typeof value === 'function' ? value.call(provider) : value) ??
|
||||
null
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A provider's name in a warning: its kind, cut, or its place in the list. */
|
||||
function providerName(provider, order) {
|
||||
try {
|
||||
if (typeof provider?.kind === 'string') return provider.kind.slice(0, 32);
|
||||
} catch {
|
||||
// A kind getter that throws gives no name.
|
||||
}
|
||||
return `#${order}`;
|
||||
}
|
||||
|
||||
/** Why `provider` cannot be kept, or null. */
|
||||
function refusal(provider, kinds) {
|
||||
if (!isObject(provider)) return 'not an object';
|
||||
if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind))
|
||||
return 'malformed kind';
|
||||
if (RESERVED.has(provider.kind)) return 'reserved kind';
|
||||
if (kinds.has(provider.kind)) return 'repeated kind';
|
||||
if (
|
||||
typeof provider.layerId !== 'string' ||
|
||||
!LAYER_ID_PATTERN.test(provider.layerId)
|
||||
)
|
||||
return 'malformed layer id';
|
||||
for (const method of REQUIRED_METHODS)
|
||||
if (typeof provider[method] !== 'function') return `no ${method}()`;
|
||||
if (
|
||||
provider.isEntryAllowed !== undefined &&
|
||||
typeof provider.isEntryAllowed !== 'function'
|
||||
)
|
||||
return 'isEntryAllowed is not a function';
|
||||
if (!wordedNow(provider, 'entryFace', faceOf)) return 'malformed entry face';
|
||||
if (!wordedNow(provider, 'labels', labelsOf))
|
||||
return 'labels need view, exit and exitText';
|
||||
if (provider.look != null && !wordedNow(provider, 'look', lookOf))
|
||||
return 'look needs an aheadLabel';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The application's subject providers, checked once and frozen, in the order
|
||||
* entry asks them: ascending `priority`, ties in list order. Each has
|
||||
* - `kind`: /^[a-z][a-z0-9-]{1,31}$/, not a built-in kind, unique;
|
||||
* - `layerId`: the catalog layer the subject belongs to (entry needs it on);
|
||||
* - `priority`: a finite number (default 0);
|
||||
* - `entryFace`: `{icon, label}`, a Material Symbols name and a label of at
|
||||
* most 16 characters, in the page's language;
|
||||
* - `labels`: `{view, exit, exitText, kicker?}`, the HUD's and the exit
|
||||
* button's accessible names, the exit button's text and the default kicker,
|
||||
* in the page's language;
|
||||
* - `look` (optional): `{restPitchDeg?, aheadLabel}`, arrow-key look-around as
|
||||
* on a bridge, resting at `restPitchDeg` (default 0, -90..90), its Look
|
||||
* ahead button named `aheadLabel`;
|
||||
* `entryFace`, `labels` and `look` may each be a function returning the
|
||||
* object: it is called on the provider again whenever they are shown and
|
||||
* when the page's language changes, so its words can follow it
|
||||
* (`./i18n`). A read that throws or is malformed keeps the last
|
||||
* good one; `look` is on or off and `restPitchDeg` fixed as first read;
|
||||
* - `cameraIntervalMs` (optional): 0..1000, null for the Cockpit's default; 0
|
||||
* updates the camera every rendered frame;
|
||||
* - `headingSlewDps` (optional): how fast the view turns to a new heading,
|
||||
* positive or Infinity, null for the Cockpit's default;
|
||||
* - `candidate()`, `isEntryAllowed(candidate)` (optional), `hold(id)`,
|
||||
* `read(nowMs, ctx)`, `hud(frame, ctx)` and `release(id, {restore})`, all
|
||||
* synchronous (createCockpitSubjectCaller) and called on the provider, so
|
||||
* a class instance's methods keep their `this`. `isEntryAllowed` allows
|
||||
* entry only by returning `true`. `hold` returns `true` once it holds the
|
||||
* subject, or `false` to refuse entry; any other answer refuses it too,
|
||||
* with one warning. A refused hold, and one that throws or returns a
|
||||
* promise, is followed by `release(id, {restore: false})`, and by another
|
||||
* once that promise settles; `release` must therefore be harmless for a
|
||||
* subject it does not hold or already gave back.
|
||||
*
|
||||
* A provider that is not so, or whose members throw when read (a getter), is
|
||||
* left out with one warning naming it; the providers after it are kept.
|
||||
* @param {unknown} list
|
||||
* @param {{warn?: (message: string) => void}} [options]
|
||||
* @returns {ReadonlyArray<object>}
|
||||
*/
|
||||
export function cockpitSubjectProviders(
|
||||
list = [],
|
||||
{ warn = (message) => console.warn(message) } = {},
|
||||
) {
|
||||
const kept = [];
|
||||
const kinds = new Set();
|
||||
(Array.isArray(list) ? list : []).forEach((provider, order) => {
|
||||
let reason;
|
||||
let copy = null;
|
||||
try {
|
||||
reason = refusal(provider, kinds);
|
||||
if (!reason) copy = keptProvider(provider, order);
|
||||
} catch {
|
||||
reason = 'a member threw when read';
|
||||
}
|
||||
if (reason) {
|
||||
warn(
|
||||
`[Cockpit] subject provider ${providerName(provider, order)} left out: ${reason}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
kinds.add(copy.kind);
|
||||
kept.push(copy);
|
||||
});
|
||||
kept.sort((a, b) => a.priority - b.priority || a.order - b.order);
|
||||
return Object.freeze(kept);
|
||||
}
|
||||
|
||||
/** The frozen copy the Cockpit keeps of a provider `refusal` passed. */
|
||||
function keptProvider(provider, order) {
|
||||
// Worded members are read again on each use (see above); the last good
|
||||
// read stands in for one that is malformed or throws.
|
||||
let face = wordedNow(provider, 'entryFace', faceOf);
|
||||
let labels = wordedNow(provider, 'labels', labelsOf);
|
||||
// On or off, and its rest pitch, as first read.
|
||||
let look = wordedNow(provider, 'look', lookOf);
|
||||
const restPitchDeg = look?.restPitchDeg ?? 0;
|
||||
return Object.freeze({
|
||||
kind: provider.kind,
|
||||
layerId: provider.layerId,
|
||||
priority: finite(provider.priority) ? provider.priority : 0,
|
||||
order,
|
||||
get entryFace() {
|
||||
face = wordedNow(provider, 'entryFace', faceOf) ?? face;
|
||||
return face;
|
||||
},
|
||||
get labels() {
|
||||
labels = wordedNow(provider, 'labels', labelsOf) ?? labels;
|
||||
return labels;
|
||||
},
|
||||
get look() {
|
||||
if (!look) return null;
|
||||
const now = wordedNow(provider, 'look', lookOf);
|
||||
if (now)
|
||||
look = Object.freeze({ restPitchDeg, aheadLabel: now.aheadLabel });
|
||||
return look;
|
||||
},
|
||||
cameraIntervalMs:
|
||||
finite(provider.cameraIntervalMs) &&
|
||||
provider.cameraIntervalMs >= 0 &&
|
||||
provider.cameraIntervalMs <= 1000
|
||||
? provider.cameraIntervalMs
|
||||
: null,
|
||||
headingSlewDps:
|
||||
provider.headingSlewDps === Infinity ||
|
||||
(finite(provider.headingSlewDps) && provider.headingSlewDps > 0)
|
||||
? provider.headingSlewDps
|
||||
: null,
|
||||
// Bound, so a method that uses `this` (a class instance's, say) still
|
||||
// reads its own provider when called on this copy.
|
||||
candidate: provider.candidate.bind(provider),
|
||||
isEntryAllowed: provider.isEntryAllowed
|
||||
? provider.isEntryAllowed.bind(provider)
|
||||
: () => true,
|
||||
hold: provider.hold.bind(provider),
|
||||
read: provider.read.bind(provider),
|
||||
hud: provider.hud.bind(provider),
|
||||
release: provider.release.bind(provider),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider's candidate: `{id, name, face, selectedAt}`, or null without a
|
||||
* usable id. `name` falls back to the id; `face` is null unless well formed;
|
||||
* `selectedAt` (a number or a short string, else null) is a token the
|
||||
* provider changes each time its subject is selected, even again: a
|
||||
* subject selected after the built-in ones takes entry (entryCandidates).
|
||||
* Null too when reading `raw` throws (a getter runs provider code).
|
||||
* @param {unknown} raw What `candidate()` returned.
|
||||
*/
|
||||
export function cockpitSubjectCandidate(raw) {
|
||||
try {
|
||||
return candidateOf(raw);
|
||||
} catch {
|
||||
// A getter on what candidate() returned threw: no candidate.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function candidateOf(raw) {
|
||||
if (!isObject(raw) || typeof raw.id !== 'string') return null;
|
||||
const id = raw.id.trim();
|
||||
if (!id || id.length > 128) return null;
|
||||
const selectedAt =
|
||||
finite(raw.selectedAt) ||
|
||||
(typeof raw.selectedAt === 'string' && raw.selectedAt.length <= 64)
|
||||
? raw.selectedAt
|
||||
: null;
|
||||
return Object.freeze({
|
||||
id,
|
||||
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(id, 64),
|
||||
face: faceOf(raw.face),
|
||||
selectedAt,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One camera frame from a provider, normalized, or null when it cannot place
|
||||
* the camera (the view then ends): not an object, an id other than `heldId`,
|
||||
* a position that is not finite, an eye with no valid `upM` (0..1000), or a
|
||||
* read of it that throws (a getter runs provider code).
|
||||
* A `heightM` that is not finite or lies outside
|
||||
* COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null:
|
||||
* the eye then stands on the shared floor, or where it last stood while that
|
||||
* is cold. The anchor is `'inertial'` only when asked for and the frame
|
||||
* gives a speed; otherwise it is `'exact'`. An id is compared with `heldId`
|
||||
* trimmed, as `cockpitSubjectCandidate` trims it.
|
||||
* @param {unknown} raw What `read()` returned.
|
||||
* @param {string} heldId The subject the view holds.
|
||||
* @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg,
|
||||
* courseDeg, speedMps, stale, groundClamp, anchor, eye: {upM, forwardM,
|
||||
* pitchDeg, minClearanceM}}`.
|
||||
*/
|
||||
export function cockpitSubjectFrame(raw, heldId) {
|
||||
try {
|
||||
return frameOf(raw, heldId);
|
||||
} catch {
|
||||
// A getter on what read() returned threw: as a malformed frame.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function frameOf(raw, heldId) {
|
||||
if (!isObject(raw) || typeof raw.id !== 'string' || raw.id.trim() !== heldId)
|
||||
return null;
|
||||
const latitude = raw.latitude;
|
||||
const longitude = raw.longitude;
|
||||
if (!finite(latitude) || !finite(longitude) || Math.abs(latitude) > 90)
|
||||
return null;
|
||||
const eye = isObject(raw.eye) ? raw.eye : null;
|
||||
if (!eye || !finite(eye.upM) || eye.upM < 0 || eye.upM > 1000) return null;
|
||||
const heading = (value) =>
|
||||
finite(value) ? ((value % 360) + 360) % 360 : null;
|
||||
const headingDeg = heading(raw.headingDeg);
|
||||
const speedMps =
|
||||
finite(raw.speedMps) && raw.speedMps >= 0 ? raw.speedMps : null;
|
||||
return {
|
||||
id: heldId,
|
||||
name: cockpitSubjectText(raw.name, 64) || cockpitSubjectText(heldId, 64),
|
||||
latitude,
|
||||
longitude: ((((longitude + 180) % 360) + 360) % 360) - 180,
|
||||
heightM:
|
||||
finite(raw.heightM) &&
|
||||
raw.heightM >= COCKPIT_SUBJECT_MIN_HEIGHT_M &&
|
||||
raw.heightM <= COCKPIT_SUBJECT_MAX_HEIGHT_M
|
||||
? raw.heightM
|
||||
: null,
|
||||
headingDeg,
|
||||
courseDeg: heading(raw.courseDeg) ?? headingDeg,
|
||||
speedMps,
|
||||
stale: raw.stale === true,
|
||||
groundClamp: raw.groundClamp !== false,
|
||||
// An inertial anchor runs on at the frame's speed; with none it would
|
||||
// close on a moving subject at the correction's floor and fall behind.
|
||||
anchor: raw.anchor === 'exact' || speedMps === null ? 'exact' : 'inertial',
|
||||
eye: {
|
||||
upM: eye.upM,
|
||||
forwardM:
|
||||
finite(eye.forwardM) && Math.abs(eye.forwardM) <= 500
|
||||
? eye.forwardM
|
||||
: 0,
|
||||
pitchDeg: finite(eye.pitchDeg) ? clamp(eye.pitchDeg, -90, 90) : 0,
|
||||
minClearanceM:
|
||||
finite(eye.minClearanceM) && eye.minClearanceM >= 0
|
||||
? eye.minClearanceM
|
||||
: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A list of `{id, ...}` rows, each read by `row`, at most `max` kept. */
|
||||
function rowsOf(raw, max, row) {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const rows = [];
|
||||
const ids = new Set();
|
||||
for (const entry of raw) {
|
||||
if (rows.length >= max) break;
|
||||
if (!isObject(entry)) continue;
|
||||
const id = typeof entry.id === 'string' ? entry.id : '';
|
||||
if (!ID_PATTERN.test(id) || ids.has(id)) continue;
|
||||
const read = row(entry);
|
||||
if (!read) continue;
|
||||
ids.add(id);
|
||||
rows.push({ id, ...read });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** A progress line, or null without at least two ticks. */
|
||||
function progressOf(raw) {
|
||||
if (!isObject(raw) || !Array.isArray(raw.ticks)) return null;
|
||||
const ticks = [];
|
||||
for (const tick of raw.ticks) {
|
||||
if (ticks.length >= COCKPIT_SUBJECT_MAX_TICKS) break;
|
||||
if (!isObject(tick) || !finite(tick.at) || tick.at < 0 || tick.at > 1)
|
||||
continue;
|
||||
let label = null;
|
||||
if (isObject(tick.label)) {
|
||||
const text = cockpitSubjectText(tick.label.text, 40);
|
||||
if (text)
|
||||
label = {
|
||||
text,
|
||||
detail: cockpitSubjectText(tick.label.detail, 64),
|
||||
priority: finite(tick.label.priority)
|
||||
? clamp(Math.round(tick.label.priority), 0, 9)
|
||||
: 0,
|
||||
align: ['start', 'center', 'end'].includes(tick.label.align)
|
||||
? tick.label.align
|
||||
: 'center',
|
||||
};
|
||||
}
|
||||
ticks.push({ at: tick.at, tone: tone(tick.tone), label });
|
||||
}
|
||||
if (ticks.length < 2) return null;
|
||||
ticks.sort((a, b) => a.at - b.at);
|
||||
const marker =
|
||||
isObject(raw.marker) && finite(raw.marker.at)
|
||||
? { at: clamp(raw.marker.at, 0, 1), dwell: raw.marker.dwell === true }
|
||||
: null;
|
||||
return {
|
||||
ticks,
|
||||
marker,
|
||||
tag: cockpitSubjectText(raw.tag, 16),
|
||||
summary: cockpitSubjectText(raw.summary, 160),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider's HUD view model, normalized; never throws. Texts are coerced
|
||||
* and cut to their caps, lists to their lengths, tones to
|
||||
* COCKPIT_SUBJECT_TONES, numbers clamped; a malformed member reads as absent.
|
||||
* Null when reading `raw` throws (a getter runs provider code), so the caller
|
||||
* keeps the view it has, as when `hud()` itself throws.
|
||||
* All text is shown as given: the provider words it in the page's language.
|
||||
* @param {unknown} raw What `hud()` returned.
|
||||
* @returns {object|null} `{kicker, title, meta: {text, tone}, speed: {value,
|
||||
* unit, tag, tone}|null, readouts: [{id, label, value, detail, tone}],
|
||||
* sources: [{id, label, text, tone}],
|
||||
* route: {title, from, to, status}|null,
|
||||
* progress: {ticks: [{at, tone, label: {text, detail, priority,
|
||||
* align}|null}], marker: {at, dwell}|null, tag, summary}|null,
|
||||
* banner: {title, detail, tone}|null, veil: {level, streaks}|null,
|
||||
* lookReadout, signals: [{id, tone, title, detail}]}`.
|
||||
*/
|
||||
export function cockpitSubjectHudView(raw) {
|
||||
try {
|
||||
return hudViewOf(raw);
|
||||
} catch {
|
||||
// A getter on what hud() returned threw: the caller keeps its last view.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function hudViewOf(raw) {
|
||||
const view = isObject(raw) ? raw : {};
|
||||
const meta = isObject(view.meta) ? view.meta : {};
|
||||
const speed =
|
||||
isObject(view.speed) &&
|
||||
(view.speed.value === null ||
|
||||
(finite(view.speed.value) && view.speed.value >= 0))
|
||||
? {
|
||||
value:
|
||||
view.speed.value === null
|
||||
? null
|
||||
: Math.min(view.speed.value, 99_999),
|
||||
unit: cockpitSubjectText(view.speed.unit, 12),
|
||||
tag: cockpitSubjectText(view.speed.tag, 8),
|
||||
tone: tone(view.speed.tone),
|
||||
}
|
||||
: null;
|
||||
const route = isObject(view.route)
|
||||
? {
|
||||
title: cockpitSubjectText(view.route.title, 32),
|
||||
from: cockpitSubjectText(view.route.from, 48),
|
||||
to: cockpitSubjectText(view.route.to, 48),
|
||||
status: cockpitSubjectText(view.route.status, 64),
|
||||
}
|
||||
: null;
|
||||
const bannerTitle = isObject(view.banner)
|
||||
? cockpitSubjectText(view.banner.title, 48)
|
||||
: '';
|
||||
const veil =
|
||||
isObject(view.veil) && finite(view.veil.level)
|
||||
? {
|
||||
level: clamp(view.veil.level, 0, 1),
|
||||
streaks: view.veil.streaks === true,
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
kicker: cockpitSubjectText(view.kicker, 48),
|
||||
title: cockpitSubjectText(view.title, 64),
|
||||
meta: { text: cockpitSubjectText(meta.text, 96), tone: tone(meta.tone) },
|
||||
speed,
|
||||
readouts: rowsOf(view.readouts, COCKPIT_SUBJECT_MAX_READOUTS, (row) => {
|
||||
const label = cockpitSubjectText(row.label, 24);
|
||||
const value = cockpitSubjectText(row.value, 48);
|
||||
return label || value
|
||||
? {
|
||||
label,
|
||||
value,
|
||||
detail: cockpitSubjectText(row.detail, 80),
|
||||
tone: tone(row.tone),
|
||||
}
|
||||
: null;
|
||||
}),
|
||||
sources: rowsOf(view.sources, COCKPIT_SUBJECT_MAX_SOURCES, (row) => {
|
||||
const text = cockpitSubjectText(row.text, 120);
|
||||
return text
|
||||
? {
|
||||
label: cockpitSubjectText(row.label, 16),
|
||||
text,
|
||||
tone: tone(row.tone),
|
||||
}
|
||||
: null;
|
||||
}),
|
||||
route: route && (route.from || route.to) ? route : null,
|
||||
progress: progressOf(view.progress),
|
||||
banner: bannerTitle
|
||||
? {
|
||||
title: bannerTitle,
|
||||
detail: cockpitSubjectText(view.banner.detail, 96),
|
||||
tone: tone(view.banner.tone),
|
||||
}
|
||||
: null,
|
||||
veil: veil && veil.level > 0 ? veil : null,
|
||||
lookReadout: cockpitSubjectText(view.lookReadout, 48),
|
||||
signals: rowsOf(view.signals, COCKPIT_SUBJECT_MAX_SIGNALS, (row) => {
|
||||
const title = cockpitSubjectText(row.title, 48);
|
||||
return title
|
||||
? {
|
||||
title,
|
||||
detail: cockpitSubjectText(row.detail, 96),
|
||||
tone: tone(row.tone),
|
||||
}
|
||||
: null;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A guarded caller for provider methods: `call(provider, method, args,
|
||||
* fallback)` returns what the method returns, or `fallback` when it throws,
|
||||
* warning once per provider and method.
|
||||
*
|
||||
* Provider methods are synchronous: the Cockpit calls them on its render
|
||||
* cadence and uses the answer at once. One that returns a promise (an async
|
||||
* function, say) breaks that contract: the promise is refused as a throw
|
||||
* would be (its rejection, if any, is swallowed), with one warning, and
|
||||
* `onSettled`, when given, runs once the promise has settled, so a caller
|
||||
* can undo work that lands late.
|
||||
*
|
||||
* `call.warnOnce(provider, method, message, error)` warns on the same
|
||||
* once-per-provider-and-method footing, for an answer the caller finds
|
||||
* malformed.
|
||||
* @param {{warn?: (message: string, error: unknown) => void}} [options]
|
||||
*/
|
||||
export function createCockpitSubjectCaller({
|
||||
warn = (message, error) => console.warn(message, error),
|
||||
} = {}) {
|
||||
const warned = new Set();
|
||||
const warnOnce = (provider, method, message, error) => {
|
||||
const key = `${provider.kind}:${method}`;
|
||||
if (warned.has(key)) return;
|
||||
warned.add(key);
|
||||
warn(
|
||||
`[Cockpit] subject provider ${provider.kind} ${method}() ${message}`,
|
||||
error,
|
||||
);
|
||||
};
|
||||
function call(
|
||||
provider,
|
||||
method,
|
||||
args = [],
|
||||
fallback = null,
|
||||
onSettled = null,
|
||||
) {
|
||||
let result;
|
||||
let thenable;
|
||||
try {
|
||||
result = provider[method](...args);
|
||||
// Reading `then` runs provider code too (a getter may throw), so it is
|
||||
// guarded as the call is.
|
||||
thenable =
|
||||
result !== null &&
|
||||
(typeof result === 'object' || typeof result === 'function') &&
|
||||
typeof result.then === 'function';
|
||||
} catch (error) {
|
||||
warnOnce(provider, method, 'failed', error);
|
||||
return fallback;
|
||||
}
|
||||
if (thenable) {
|
||||
// Its work may still land: `onSettled` runs once it has, either way.
|
||||
const settled = () => {
|
||||
if (typeof onSettled === 'function') onSettled();
|
||||
};
|
||||
Promise.resolve(result).then(settled, settled);
|
||||
warnOnce(
|
||||
provider,
|
||||
method,
|
||||
'returned a promise; provider methods are synchronous',
|
||||
null,
|
||||
);
|
||||
return fallback;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
call.warnOnce = warnOnce;
|
||||
return call;
|
||||
}
|
||||
@@ -0,0 +1,698 @@
|
||||
// src/cockpitSubjectProviders.test.mjs — an application's subject providers
|
||||
// are checked once and what they return is normalized before the Cockpit
|
||||
// uses it: a malformed provider is left out, a malformed frame ends the view,
|
||||
// and a malformed HUD view is read field by field and never thrown on.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
COCKPIT_BUILT_IN_KINDS,
|
||||
COCKPIT_SUBJECT_MAX_READOUTS,
|
||||
COCKPIT_SUBJECT_MAX_TICKS,
|
||||
cockpitSubjectCandidate,
|
||||
cockpitSubjectFrame,
|
||||
cockpitSubjectHudView,
|
||||
cockpitSubjectProviders,
|
||||
cockpitSubjectText,
|
||||
createCockpitSubjectCaller,
|
||||
} from './cockpitSubjectProviders.js';
|
||||
|
||||
const noop = () => null;
|
||||
/** A well-formed provider, with `overrides`. */
|
||||
const provider = (overrides = {}) => ({
|
||||
kind: 'example-kind',
|
||||
layerId: 'example-layer',
|
||||
entryFace: { icon: 'commute', label: 'RIDE' },
|
||||
labels: {
|
||||
view: 'First-person view',
|
||||
exit: 'Exit first-person view',
|
||||
exitText: 'EXIT VIEW',
|
||||
},
|
||||
candidate: noop,
|
||||
hold: () => true,
|
||||
read: noop,
|
||||
hud: noop,
|
||||
release: noop,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const keep = (list) => {
|
||||
const warnings = [];
|
||||
const kept = cockpitSubjectProviders(list, {
|
||||
warn: (message) => warnings.push(message),
|
||||
});
|
||||
return { kept, warnings };
|
||||
};
|
||||
|
||||
test('well-formed providers are kept, frozen, in priority then list order', () => {
|
||||
const { kept, warnings } = keep([
|
||||
provider({ kind: 'late', priority: 5 }),
|
||||
provider({ kind: 'first-of-two', priority: 1 }),
|
||||
provider({ kind: 'second-of-two', priority: 1 }),
|
||||
provider({ kind: 'default-priority' }),
|
||||
]);
|
||||
assert.deepEqual(warnings, []);
|
||||
assert.deepEqual(
|
||||
kept.map(({ kind }) => kind),
|
||||
['default-priority', 'first-of-two', 'second-of-two', 'late'],
|
||||
);
|
||||
assert.ok(Object.isFrozen(kept));
|
||||
assert.ok(Object.isFrozen(kept[0]));
|
||||
const [first] = kept;
|
||||
assert.equal(first.priority, 0);
|
||||
assert.equal(first.look, null);
|
||||
assert.equal(first.cameraIntervalMs, null);
|
||||
assert.equal(first.headingSlewDps, null);
|
||||
assert.equal(first.isEntryAllowed(), true, 'no rule of its own allows');
|
||||
assert.deepEqual(first.labels, {
|
||||
view: 'First-person view',
|
||||
exit: 'Exit first-person view',
|
||||
exitText: 'EXIT VIEW',
|
||||
kicker: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('malformed, reserved and repeated providers are left out with one warning each', () => {
|
||||
const cases = [
|
||||
[null, /not an object/],
|
||||
[provider({ kind: 'X' }), /malformed kind/],
|
||||
[provider({ kind: 'a' }), /malformed kind/],
|
||||
[provider({ layerId: 'Bad Layer' }), /malformed layer id/],
|
||||
[provider({ hold: undefined }), /no hold\(\)/],
|
||||
[provider({ read: 'read' }), /no read\(\)/],
|
||||
[provider({ isEntryAllowed: true }), /isEntryAllowed/],
|
||||
[provider({ entryFace: { icon: 'Bad Icon', label: 'X' } }), /entry face/],
|
||||
[provider({ entryFace: { icon: 'commute', label: '' } }), /entry face/],
|
||||
[provider({ labels: { view: 'v', exit: 'e' } }), /labels/],
|
||||
[provider({ look: { restPitchDeg: -3 } }), /aheadLabel/],
|
||||
];
|
||||
for (const [entry, reason] of cases) {
|
||||
const { kept, warnings } = keep([entry]);
|
||||
assert.equal(kept.length, 0, String(reason));
|
||||
assert.equal(warnings.length, 1, String(reason));
|
||||
assert.match(warnings[0], reason);
|
||||
}
|
||||
for (const kind of COCKPIT_BUILT_IN_KINDS) {
|
||||
const { kept, warnings } = keep([provider({ kind })]);
|
||||
assert.equal(kept.length, 0, kind);
|
||||
assert.match(warnings[0], /reserved kind/);
|
||||
}
|
||||
const { kept, warnings } = keep([provider(), provider()]);
|
||||
assert.equal(kept.length, 1);
|
||||
assert.match(warnings[0], /repeated kind/);
|
||||
assert.deepEqual(keep('not a list').kept, []);
|
||||
});
|
||||
|
||||
test('optional settings are kept when in range and defaulted otherwise', () => {
|
||||
const [ranged] = keep([
|
||||
provider({
|
||||
priority: -2,
|
||||
look: { restPitchDeg: -120, aheadLabel: 'Look ahead' },
|
||||
cameraIntervalMs: 0,
|
||||
headingSlewDps: Infinity,
|
||||
labels: {
|
||||
view: 'v',
|
||||
exit: 'e',
|
||||
exitText: 'x',
|
||||
kicker: 'K'.repeat(80),
|
||||
},
|
||||
}),
|
||||
]).kept;
|
||||
assert.equal(ranged.priority, -2);
|
||||
assert.deepEqual(ranged.look, {
|
||||
restPitchDeg: -90,
|
||||
aheadLabel: 'Look ahead',
|
||||
});
|
||||
assert.equal(ranged.cameraIntervalMs, 0);
|
||||
assert.equal(ranged.headingSlewDps, Infinity);
|
||||
assert.equal(ranged.labels.kicker.length, 48);
|
||||
assert.ok(ranged.labels.kicker.endsWith('…'));
|
||||
const [defaulted] = keep([
|
||||
provider({
|
||||
priority: NaN,
|
||||
cameraIntervalMs: 5000,
|
||||
headingSlewDps: -1,
|
||||
}),
|
||||
]).kept;
|
||||
assert.equal(defaulted.priority, 0);
|
||||
assert.equal(defaulted.cameraIntervalMs, null);
|
||||
assert.equal(defaulted.headingSlewDps, null);
|
||||
});
|
||||
|
||||
test('a candidate needs an id; its name and face are read with care', () => {
|
||||
assert.equal(cockpitSubjectCandidate(null), null);
|
||||
assert.equal(cockpitSubjectCandidate({ id: 7 }), null);
|
||||
assert.equal(cockpitSubjectCandidate({ id: ' ' }), null);
|
||||
assert.equal(cockpitSubjectCandidate({ id: 'x'.repeat(129) }), null);
|
||||
assert.deepEqual(cockpitSubjectCandidate({ id: ' a1 ' }), {
|
||||
id: 'a1',
|
||||
name: 'a1',
|
||||
face: null,
|
||||
selectedAt: null,
|
||||
});
|
||||
// A selection token is a number or a short string.
|
||||
assert.equal(
|
||||
cockpitSubjectCandidate({ id: 'a1', selectedAt: 5 }).selectedAt,
|
||||
5,
|
||||
);
|
||||
assert.equal(
|
||||
cockpitSubjectCandidate({ id: 'a1', selectedAt: 'click-2' }).selectedAt,
|
||||
'click-2',
|
||||
);
|
||||
for (const selectedAt of [Number.NaN, {}, 'x'.repeat(65)])
|
||||
assert.equal(
|
||||
cockpitSubjectCandidate({ id: 'a1', selectedAt }).selectedAt,
|
||||
null,
|
||||
);
|
||||
const read = cockpitSubjectCandidate({
|
||||
id: 'a1',
|
||||
name: ' Example 12 ',
|
||||
face: { icon: 'tram', label: 'RIDE' },
|
||||
});
|
||||
assert.equal(read.name, 'Example 12');
|
||||
assert.deepEqual(read.face, { icon: 'tram', label: 'RIDE' });
|
||||
assert.equal(
|
||||
cockpitSubjectCandidate({ id: 'a1', face: { icon: 'BAD' } }).face,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('a frame is the held subject at a finite place with an eye height, else null', () => {
|
||||
const frame = (overrides = {}) => ({
|
||||
id: 'a1',
|
||||
latitude: 47,
|
||||
longitude: 8,
|
||||
eye: { upM: 3.5 },
|
||||
...overrides,
|
||||
});
|
||||
const read = cockpitSubjectFrame(frame(), 'a1');
|
||||
assert.deepEqual(read, {
|
||||
id: 'a1',
|
||||
name: 'a1',
|
||||
latitude: 47,
|
||||
longitude: 8,
|
||||
heightM: null,
|
||||
headingDeg: null,
|
||||
courseDeg: null,
|
||||
speedMps: null,
|
||||
stale: false,
|
||||
groundClamp: true,
|
||||
// No speed to run an inertial anchor on: it sits on the subject.
|
||||
anchor: 'exact',
|
||||
eye: { upM: 3.5, forwardM: 0, pitchDeg: 0, minClearanceM: 0 },
|
||||
});
|
||||
assert.equal(
|
||||
cockpitSubjectFrame(frame({ speedMps: 30 }), 'a1').anchor,
|
||||
'inertial',
|
||||
'with a speed it runs on',
|
||||
);
|
||||
// A held id is trimmed (cockpitSubjectCandidate), and so is a frame's.
|
||||
assert.equal(cockpitSubjectFrame(frame({ id: ' a1 ' }), 'a1')?.id, 'a1');
|
||||
for (const bad of [
|
||||
null,
|
||||
frame({ id: 'other' }),
|
||||
frame({ latitude: 91 }),
|
||||
frame({ latitude: NaN }),
|
||||
frame({ longitude: Infinity }),
|
||||
frame({ eye: null }),
|
||||
frame({ eye: { upM: -1 } }),
|
||||
frame({ eye: { upM: 2000 } }),
|
||||
frame({ eye: { upM: '3' } }),
|
||||
])
|
||||
assert.equal(cockpitSubjectFrame(bad, 'a1'), null, JSON.stringify(bad));
|
||||
const full = cockpitSubjectFrame(
|
||||
frame({
|
||||
name: 'Example',
|
||||
longitude: 190,
|
||||
heightM: 412.5,
|
||||
headingDeg: -10,
|
||||
courseDeg: 725,
|
||||
speedMps: 22,
|
||||
stale: true,
|
||||
groundClamp: false,
|
||||
anchor: 'exact',
|
||||
eye: { upM: 2, forwardM: 600, pitchDeg: -100, minClearanceM: 1.5 },
|
||||
}),
|
||||
'a1',
|
||||
);
|
||||
assert.equal(full.longitude, -170);
|
||||
assert.equal(full.heightM, 412.5);
|
||||
// A height outside any plausible ground reads as none.
|
||||
for (const heightM of [-6_400_000, 1e9, Infinity])
|
||||
assert.equal(cockpitSubjectFrame(frame({ heightM }), 'a1').heightM, null);
|
||||
assert.equal(
|
||||
cockpitSubjectFrame(frame({ heightM: -400 }), 'a1').heightM,
|
||||
-400,
|
||||
);
|
||||
assert.equal(full.headingDeg, 350);
|
||||
assert.equal(full.courseDeg, 5);
|
||||
assert.equal(full.speedMps, 22);
|
||||
assert.equal(full.stale, true);
|
||||
assert.equal(full.groundClamp, false);
|
||||
assert.equal(full.anchor, 'exact');
|
||||
assert.deepEqual(full.eye, {
|
||||
upM: 2,
|
||||
forwardM: 0,
|
||||
pitchDeg: -90,
|
||||
minClearanceM: 1.5,
|
||||
});
|
||||
// Only exactly false turns the ground clamp off; course falls back to heading.
|
||||
const loose = cockpitSubjectFrame(
|
||||
frame({ groundClamp: 0, anchor: 'EXACT', headingDeg: 90, speedMps: -1 }),
|
||||
'a1',
|
||||
);
|
||||
assert.equal(loose.groundClamp, true);
|
||||
assert.equal(
|
||||
cockpitSubjectFrame(frame({ anchor: 'EXACT', speedMps: 5 }), 'a1').anchor,
|
||||
'inertial',
|
||||
);
|
||||
assert.equal(loose.courseDeg, 90);
|
||||
assert.equal(loose.speedMps, null);
|
||||
});
|
||||
|
||||
test('a HUD view is read field by field: caps, tones, clamps, never a throw', () => {
|
||||
const empty = cockpitSubjectHudView(null);
|
||||
assert.deepEqual(empty, {
|
||||
kicker: '',
|
||||
title: '',
|
||||
meta: { text: '', tone: 'normal' },
|
||||
speed: null,
|
||||
readouts: [],
|
||||
sources: [],
|
||||
route: null,
|
||||
progress: null,
|
||||
banner: null,
|
||||
veil: null,
|
||||
lookReadout: '',
|
||||
signals: [],
|
||||
});
|
||||
for (const odd of [42, 'text', [], { readouts: 'x', progress: { ticks: 3 } }])
|
||||
assert.doesNotThrow(() => cockpitSubjectHudView(odd));
|
||||
const view = cockpitSubjectHudView({
|
||||
kicker: 'LINE · OPERATOR',
|
||||
title: 'Name → Destination',
|
||||
meta: { text: 'LIVE', tone: 'bogus' },
|
||||
speed: { value: 84.4, unit: 'km/h', tag: 'LIVE', tone: 'live' },
|
||||
readouts: [
|
||||
...Array.from({ length: 6 }, (_, i) => ({
|
||||
id: `r${i}`,
|
||||
label: 'NEXT',
|
||||
value: `Stop ${i}`,
|
||||
tone: 'warning',
|
||||
})),
|
||||
],
|
||||
sources: [
|
||||
{ id: 'track', label: 'TRACK', text: 'operator shape' },
|
||||
{ id: 'track', label: 'TRACK', text: 'repeated id' },
|
||||
{ id: 'Bad Id', text: 'refused' },
|
||||
{ id: 'empty', label: 'X', text: '' },
|
||||
],
|
||||
route: { title: 'ROUTE', from: 'A', to: 'B', status: '3 stops' },
|
||||
banner: { title: 'BANNER', detail: 'detail', tone: 'alert' },
|
||||
veil: { level: 4, streaks: 1 },
|
||||
lookReadout: 'LOOK RIGHT',
|
||||
signals: [{ id: 's1', title: 'T', detail: 'D', tone: 'warning' }],
|
||||
});
|
||||
assert.equal(view.meta.tone, 'normal');
|
||||
assert.deepEqual(view.speed, {
|
||||
value: 84.4,
|
||||
unit: 'km/h',
|
||||
tag: 'LIVE',
|
||||
tone: 'live',
|
||||
});
|
||||
assert.equal(view.readouts.length, COCKPIT_SUBJECT_MAX_READOUTS);
|
||||
assert.equal(view.readouts[0].tone, 'warning');
|
||||
assert.deepEqual(
|
||||
view.sources.map(({ id }) => id),
|
||||
['track'],
|
||||
);
|
||||
assert.deepEqual(view.route, {
|
||||
title: 'ROUTE',
|
||||
from: 'A',
|
||||
to: 'B',
|
||||
status: '3 stops',
|
||||
});
|
||||
assert.equal(view.banner.tone, 'alert');
|
||||
assert.deepEqual(view.veil, { level: 1, streaks: false });
|
||||
assert.equal(view.lookReadout, 'LOOK RIGHT');
|
||||
assert.equal(view.signals[0].tone, 'warning');
|
||||
// A veil at 0, a speed below 0 and a route with no ends are absent.
|
||||
const absent = cockpitSubjectHudView({
|
||||
veil: { level: 0 },
|
||||
speed: { value: -3 },
|
||||
route: { from: '', to: '' },
|
||||
});
|
||||
assert.equal(absent.veil, null);
|
||||
assert.equal(absent.speed, null);
|
||||
assert.equal(absent.route, null);
|
||||
// A speed of null is a speed not yet known.
|
||||
assert.equal(
|
||||
cockpitSubjectHudView({ speed: { value: null } }).speed.value,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('a progress line keeps ticks in 0..1, sorted and capped, and needs two', () => {
|
||||
const read = cockpitSubjectHudView({
|
||||
progress: {
|
||||
ticks: [
|
||||
{ at: 1, label: { text: 'End', align: 'end', priority: 1 } },
|
||||
{ at: 0.5, tone: 'warning' },
|
||||
{ at: 2 },
|
||||
{ at: -0.1 },
|
||||
{ at: 0, label: { text: 'Start', align: 'start', priority: 12 } },
|
||||
{ at: 0.25, label: { text: '', detail: 'no text, no label' } },
|
||||
],
|
||||
marker: { at: 1.4, dwell: true },
|
||||
tag: 'TIMETABLE',
|
||||
summary: 'From Start to End',
|
||||
},
|
||||
}).progress;
|
||||
assert.deepEqual(
|
||||
read.ticks.map(({ at }) => at),
|
||||
[0, 0.25, 0.5, 1],
|
||||
);
|
||||
assert.equal(read.ticks[0].label.priority, 9);
|
||||
assert.equal(read.ticks[0].label.align, 'start');
|
||||
assert.equal(read.ticks[1].label, null);
|
||||
assert.equal(read.ticks[2].tone, 'warning');
|
||||
assert.deepEqual(read.marker, { at: 1, dwell: true });
|
||||
assert.equal(read.tag, 'TIMETABLE');
|
||||
assert.equal(read.summary, 'From Start to End');
|
||||
assert.equal(
|
||||
cockpitSubjectHudView({ progress: { ticks: [{ at: 0.5 }] } }).progress,
|
||||
null,
|
||||
);
|
||||
const many = cockpitSubjectHudView({
|
||||
progress: {
|
||||
ticks: Array.from({ length: COCKPIT_SUBJECT_MAX_TICKS + 40 }, (_, i) => ({
|
||||
at: i / (COCKPIT_SUBJECT_MAX_TICKS + 40),
|
||||
})),
|
||||
},
|
||||
}).progress;
|
||||
assert.equal(many.ticks.length, COCKPIT_SUBJECT_MAX_TICKS);
|
||||
});
|
||||
|
||||
test('texts are trimmed, collapsed and cut with an ellipsis', () => {
|
||||
assert.equal(cockpitSubjectText(' a \n b ', 10), 'a b');
|
||||
assert.equal(cockpitSubjectText('abcdef', 4), 'abc…');
|
||||
assert.equal(cockpitSubjectText(12.5, 10), '12.5');
|
||||
assert.equal(cockpitSubjectText({}, 10), '');
|
||||
assert.equal(cockpitSubjectText(NaN, 10), '');
|
||||
});
|
||||
|
||||
test('a cut never splits a surrogate pair', () => {
|
||||
// The cut would fall between the emoji's halves: it is left out whole.
|
||||
assert.equal(cockpitSubjectText('abcd😀efgh', 6), 'abcd…');
|
||||
// One that fits before the cut is kept whole.
|
||||
assert.equal(cockpitSubjectText('abc😀efgh', 6), 'abc😀…');
|
||||
const lone =
|
||||
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
||||
for (let max = 2; max <= 24; max += 1)
|
||||
assert.equal(
|
||||
lone.test(cockpitSubjectText('🚆 Example 12 🚉 Central', max)),
|
||||
false,
|
||||
`cut at ${max}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a provider method that throws returns the fallback and warns once', () => {
|
||||
const warnings = [];
|
||||
const call = createCockpitSubjectCaller({
|
||||
warn: (message) => warnings.push(message),
|
||||
});
|
||||
const failing = {
|
||||
kind: 'example-kind',
|
||||
read() {
|
||||
throw new Error('boom');
|
||||
},
|
||||
hud: (value) => value * 2,
|
||||
};
|
||||
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
|
||||
assert.equal(call(failing, 'read', [], 'fallback'), 'fallback');
|
||||
assert.equal(call(failing, 'hud', [21]), 42);
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /example-kind read\(\) failed/);
|
||||
});
|
||||
|
||||
test('a provider method that returns a promise is refused as a throw is, warning once', async () => {
|
||||
const warnings = [];
|
||||
const call = createCockpitSubjectCaller({
|
||||
warn: (message) => warnings.push(message),
|
||||
});
|
||||
const asynchronous = {
|
||||
kind: 'example-kind',
|
||||
hold: async () => true,
|
||||
read: () => Promise.reject(new Error('late')),
|
||||
};
|
||||
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
|
||||
assert.equal(call(asynchronous, 'hold', ['a1'], 'refused'), 'refused');
|
||||
assert.equal(call(asynchronous, 'read', [], null), null);
|
||||
assert.equal(warnings.length, 2, 'once per method');
|
||||
assert.match(warnings[0], /hold\(\) returned a promise/);
|
||||
// The rejected promise is not left unhandled.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
test('an answer whose `then` throws when read is handled as a throw', () => {
|
||||
const warnings = [];
|
||||
const call = createCockpitSubjectCaller({
|
||||
warn: (message) => warnings.push(message),
|
||||
});
|
||||
const tricky = {
|
||||
kind: 'example-kind',
|
||||
hold: () => ({
|
||||
get then() {
|
||||
throw new Error('no then');
|
||||
},
|
||||
}),
|
||||
};
|
||||
assert.equal(call(tricky, 'hold', ['a1'], 'refused'), 'refused');
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0], /example-kind hold\(\) failed/);
|
||||
});
|
||||
|
||||
test('the caller’s warnOnce shares its once-per-provider-and-method record', () => {
|
||||
const warnings = [];
|
||||
const call = createCockpitSubjectCaller({
|
||||
warn: (message) => warnings.push(message),
|
||||
});
|
||||
const ride = {
|
||||
kind: 'example-kind',
|
||||
hold() {
|
||||
throw new Error('boom');
|
||||
},
|
||||
};
|
||||
call.warnOnce(ride, 'read', 'is odd');
|
||||
call.warnOnce(ride, 'read', 'is odd again');
|
||||
call(ride, 'hold', ['a1']);
|
||||
call.warnOnce(ride, 'hold', 'is odd');
|
||||
assert.deepEqual(warnings, [
|
||||
'[Cockpit] subject provider example-kind read() is odd',
|
||||
'[Cockpit] subject provider example-kind hold() failed',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a class-based provider keeps its `this`, in its methods and its worded members', () => {
|
||||
class Ride {
|
||||
#word = 'RIDE';
|
||||
#held = null;
|
||||
kind = 'example-kind';
|
||||
layerId = 'example-layer';
|
||||
speak(word) {
|
||||
this.#word = word;
|
||||
}
|
||||
entryFace() {
|
||||
return { icon: 'commute', label: this.#word };
|
||||
}
|
||||
get labels() {
|
||||
return {
|
||||
view: `${this.#word} view`,
|
||||
exit: 'Exit ride view',
|
||||
exitText: 'EXIT RIDE',
|
||||
};
|
||||
}
|
||||
look() {
|
||||
return { aheadLabel: `Look ahead, ${this.#word}` };
|
||||
}
|
||||
candidate() {
|
||||
return { id: 'a1', name: this.#word };
|
||||
}
|
||||
isEntryAllowed(candidate) {
|
||||
return candidate.id === 'a1' && this.#held === null;
|
||||
}
|
||||
hold(id) {
|
||||
this.#held = id;
|
||||
return true;
|
||||
}
|
||||
read() {
|
||||
return this.#held;
|
||||
}
|
||||
hud(frame) {
|
||||
return { title: `${this.#word} ${frame}` };
|
||||
}
|
||||
release() {
|
||||
this.#held = null;
|
||||
return 'released';
|
||||
}
|
||||
}
|
||||
const instance = new Ride();
|
||||
const { kept, warnings } = keep([instance]);
|
||||
assert.deepEqual(warnings, []);
|
||||
const [ride] = kept;
|
||||
assert.equal(ride.entryFace.label, 'RIDE');
|
||||
assert.equal(ride.labels.view, 'RIDE view');
|
||||
assert.equal(ride.look.aheadLabel, 'Look ahead, RIDE');
|
||||
instance.speak('FAHRT');
|
||||
assert.equal(ride.entryFace.label, 'FAHRT', 'read again, on the instance');
|
||||
assert.equal(ride.look.aheadLabel, 'Look ahead, FAHRT');
|
||||
// Called on the kept copy, as the Cockpit calls them.
|
||||
const failures = [];
|
||||
const call = createCockpitSubjectCaller({
|
||||
warn: (message) => failures.push(message),
|
||||
});
|
||||
assert.deepEqual(call(ride, 'candidate'), { id: 'a1', name: 'FAHRT' });
|
||||
assert.equal(ride.isEntryAllowed({ id: 'a1' }), true);
|
||||
assert.equal(call(ride, 'hold', ['a1']), true);
|
||||
assert.equal(ride.isEntryAllowed({ id: 'a1' }), false);
|
||||
assert.equal(call(ride, 'read', [0, {}]), 'a1');
|
||||
assert.deepEqual(call(ride, 'hud', ['a1', {}]), { title: 'FAHRT a1' });
|
||||
assert.equal(call(ride, 'release', ['a1', { restore: true }]), 'released');
|
||||
assert.equal(call(ride, 'read', [0, {}]), null);
|
||||
assert.deepEqual(failures, []);
|
||||
});
|
||||
|
||||
test('labels, entry face and look given as functions are read again on each use', () => {
|
||||
let lang = 'en';
|
||||
const words = {
|
||||
en: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT RIDE' },
|
||||
de: { view: 'Fahrtansicht', exit: 'Verlassen', exitText: 'VERLASSEN' },
|
||||
};
|
||||
const { kept, warnings } = keep([
|
||||
provider({
|
||||
labels: () => words[lang],
|
||||
entryFace: () => ({
|
||||
icon: 'commute',
|
||||
label: { en: 'RIDE', de: 'FAHRT' }[lang],
|
||||
}),
|
||||
look: () => ({
|
||||
restPitchDeg: lang === 'de' ? 40 : -3,
|
||||
aheadLabel: lang === 'de' ? 'Nach vorn' : 'Look ahead',
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
assert.deepEqual(warnings, []);
|
||||
const [ride] = kept;
|
||||
assert.equal(ride.labels.exitText, 'EXIT RIDE');
|
||||
assert.equal(ride.entryFace.label, 'RIDE');
|
||||
assert.equal(ride.look.aheadLabel, 'Look ahead');
|
||||
lang = 'de';
|
||||
assert.equal(ride.labels.exitText, 'VERLASSEN');
|
||||
assert.equal(ride.entryFace.label, 'FAHRT');
|
||||
assert.equal(ride.look.aheadLabel, 'Nach vorn');
|
||||
assert.equal(ride.look.restPitchDeg, -3, 'the rest pitch is as first read');
|
||||
// A read that fails or is malformed keeps the last good one.
|
||||
lang = 'xx';
|
||||
assert.equal(ride.labels.exitText, 'VERLASSEN');
|
||||
assert.equal(ride.entryFace.label, 'FAHRT');
|
||||
// Functions that are malformed from the start leave the provider out.
|
||||
const bad = keep([
|
||||
provider({ kind: 'bad-labels', labels: () => null }),
|
||||
provider({
|
||||
kind: 'thrown-face',
|
||||
entryFace: () => {
|
||||
throw new Error('no face');
|
||||
},
|
||||
}),
|
||||
]);
|
||||
assert.deepEqual(bad.kept, []);
|
||||
assert.equal(bad.warnings.length, 2);
|
||||
});
|
||||
|
||||
/** `target` with a getter for `key` that throws (provider code runs on a read). */
|
||||
const throwingGetter = (target, key) =>
|
||||
Object.defineProperty(target, key, {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new Error(`${key} unavailable`);
|
||||
},
|
||||
});
|
||||
|
||||
test('a provider whose getter throws is left out with one warning; the next is kept', () => {
|
||||
const { kept, warnings } = keep([
|
||||
throwingGetter(provider({ kind: 'thrown-face' }), 'entryFace'),
|
||||
throwingGetter(provider({ kind: 'thrown-labels' }), 'labels'),
|
||||
throwingGetter(provider({ kind: 'thrown-look' }), 'look'),
|
||||
throwingGetter(provider(), 'kind'),
|
||||
throwingGetter(provider({ kind: 'thrown-method' }), 'read'),
|
||||
// Read only once the provider is accepted, so its kind must stay free.
|
||||
throwingGetter(provider({ kind: 'example-kind' }), 'priority'),
|
||||
provider({ kind: 'example-kind' }),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
kept.map(({ kind }) => kind),
|
||||
['example-kind'],
|
||||
);
|
||||
assert.deepEqual(warnings, [
|
||||
'[Cockpit] subject provider thrown-face left out: malformed entry face',
|
||||
'[Cockpit] subject provider thrown-labels left out: labels need view, exit and exitText',
|
||||
'[Cockpit] subject provider thrown-look left out: a member threw when read',
|
||||
'[Cockpit] subject provider #3 left out: a member threw when read',
|
||||
'[Cockpit] subject provider thrown-method left out: a member threw when read',
|
||||
'[Cockpit] subject provider example-kind left out: a member threw when read',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a worded getter that starts throwing keeps the last good words', () => {
|
||||
let failing = false;
|
||||
const words = (value) => () => {
|
||||
if (failing) throw new Error('translations unavailable');
|
||||
return value;
|
||||
};
|
||||
const definition = provider();
|
||||
for (const [key, value] of Object.entries({
|
||||
labels: { view: 'Ride view', exit: 'Exit ride view', exitText: 'EXIT' },
|
||||
entryFace: { icon: 'commute', label: 'RIDE' },
|
||||
look: { restPitchDeg: 10, aheadLabel: 'Look ahead' },
|
||||
}))
|
||||
Object.defineProperty(definition, key, { get: words(value) });
|
||||
const { kept, warnings } = keep([definition]);
|
||||
assert.deepEqual(warnings, []);
|
||||
const [ride] = kept;
|
||||
failing = true;
|
||||
assert.equal(ride.labels.view, 'Ride view');
|
||||
assert.equal(ride.entryFace.label, 'RIDE');
|
||||
assert.deepEqual(ride.look, { restPitchDeg: 10, aheadLabel: 'Look ahead' });
|
||||
// So does a worded object whose own member throws when read.
|
||||
failing = false;
|
||||
Object.defineProperty(definition, 'labels', {
|
||||
get: () => throwingGetter({ view: 'v', exit: 'e', exitText: 'x' }, 'view'),
|
||||
});
|
||||
assert.equal(ride.labels.view, 'Ride view');
|
||||
});
|
||||
|
||||
test('a candidate, frame or HUD view whose getter throws reads as null', () => {
|
||||
assert.equal(
|
||||
cockpitSubjectCandidate(throwingGetter({ name: 'Example' }, 'id')),
|
||||
null,
|
||||
);
|
||||
const frame = { id: 'a1', latitude: 1, longitude: 2, eye: { upM: 3 } };
|
||||
assert.ok(cockpitSubjectFrame(frame, 'a1'), 'well formed');
|
||||
assert.equal(
|
||||
cockpitSubjectFrame(throwingGetter({ ...frame }, 'latitude'), 'a1'),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
cockpitSubjectFrame({ ...frame, eye: throwingGetter({}, 'upM') }, 'a1'),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
cockpitSubjectHudView(throwingGetter({ title: 'T' }, 'meta')),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
cockpitSubjectHudView({ title: 'T', readouts: [throwingGetter({}, 'id')] }),
|
||||
null,
|
||||
);
|
||||
// Nothing to read is still the empty view, never null.
|
||||
assert.equal(cockpitSubjectHudView(null).title, '');
|
||||
});
|
||||
@@ -481,6 +481,24 @@ export function orbitEntryAllowed({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an application subject provider's candidate can be ridden. Like the
|
||||
* bridge and orbit it needs only its own layer on, and waits out a Context
|
||||
* change in flight; the provider then has its own say (`isEntryAllowed`).
|
||||
* @param {{layerEnabled: boolean, contextModeChanging: boolean,
|
||||
* providerAllows: boolean}} state
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function subjectEntryAllowed({
|
||||
layerEnabled,
|
||||
contextModeChanging,
|
||||
providerAllows,
|
||||
}) {
|
||||
return (
|
||||
Boolean(layerEnabled) && !contextModeChanging && providerAllows === true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal context-mode id → the word the voice tools accept for it.
|
||||
*
|
||||
|
||||
+127
-36
@@ -4,18 +4,31 @@ import { _selectContextMode } from './ui/contextTransactions.js';
|
||||
import { _initGlobalContextPanel } from './ui/contextBindings.js';
|
||||
import { clearSelectedLayers } from './ui/contextActions.js';
|
||||
import { readFileSync as readRadioSource } from 'node:fs';
|
||||
const radioBindings = readRadioSource(new URL('./ui/radioBindings.js', import.meta.url), 'utf8');
|
||||
const contextView = readRadioSource(new URL('./ui/views/ContextView.vue', import.meta.url), 'utf8');
|
||||
const radioBindings = readRadioSource(
|
||||
new URL('./ui/radioBindings.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const contextView = readRadioSource(
|
||||
new URL('./ui/views/ContextView.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const html = await renderApplicationHtml(readFileSync(new URL('../index.html', import.meta.url), 'utf8'));
|
||||
const html = await renderApplicationHtml(
|
||||
readFileSync(new URL('../index.html', import.meta.url), 'utf8'),
|
||||
);
|
||||
const css = readStylesheet(new URL('../style.css', import.meta.url));
|
||||
|
||||
test('Contacts and Space Missions both participate in the ordinary Tab sequence', () => {
|
||||
for (const id of ['global-context-flights-btn', 'global-context-missions-btn']) {
|
||||
const button = html.match(new RegExp(`<button id="${id}"[\\s\\S]*?</button>`));
|
||||
for (const id of [
|
||||
'global-context-flights-btn',
|
||||
'global-context-missions-btn',
|
||||
]) {
|
||||
const button = html.match(
|
||||
new RegExp(`<button id="${id}"[\\s\\S]*?</button>`),
|
||||
);
|
||||
assert.ok(button, `${id} is missing`);
|
||||
assert.match(button[0], /role="tab"/);
|
||||
assert.match(button[0], /tabindex="0"/);
|
||||
@@ -23,7 +36,10 @@ test('Contacts and Space Missions both participate in the ordinary Tab sequence'
|
||||
|
||||
// The view keeps both tabs' tabindex static and never disables them; the
|
||||
// transition itself is covered over happy-dom in ui/contextPanel.test.mjs.
|
||||
for (const id of ['global-context-flights-btn', 'global-context-missions-btn']) {
|
||||
for (const id of [
|
||||
'global-context-flights-btn',
|
||||
'global-context-missions-btn',
|
||||
]) {
|
||||
const tag = contextView.match(new RegExp(`<button id="${id}"[^>]*>`))?.[0];
|
||||
assert.ok(tag, `${id} is missing from the view`);
|
||||
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
|
||||
@@ -34,9 +50,22 @@ test('Context activation and Clear All never native-disable tabs and guard repea
|
||||
const init = _initGlobalContextPanel.toString();
|
||||
const select = _selectContextMode.toString();
|
||||
const clear = clearSelectedLayers.toString();
|
||||
assert.equal((init.match(/if \(\s*this\.destroyed\s*\|\|\s*this\._contextModeChanging\s*\|\|\s*this\._clearSelectedLayersPromise\s*\)\s*return;/g) || []).length, 2);
|
||||
assert.doesNotMatch(select, /_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/);
|
||||
assert.doesNotMatch(clear, /_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/);
|
||||
assert.equal(
|
||||
(
|
||||
init.match(
|
||||
/if \(\s*this\.destroyed\s*\|\|\s*this\._contextModeChanging\s*\|\|\s*this\._clearSelectedLayersPromise\s*\)\s*return;/g,
|
||||
) || []
|
||||
).length,
|
||||
2,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
select,
|
||||
/_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
clear,
|
||||
/_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/,
|
||||
);
|
||||
});
|
||||
|
||||
test('Context tablist retains Left, Right, Home, and End keyboard navigation', () => {
|
||||
@@ -45,40 +74,62 @@ test('Context tablist retains Left, Right, Home, and End keyboard navigation', (
|
||||
assert.match(initSource, /event\.key === 'ArrowLeft'/);
|
||||
assert.match(initSource, /event\.key === 'Home'/);
|
||||
assert.match(initSource, /event\.key === 'End'/);
|
||||
assert.match(initSource, /contextTabs\[nextIndex\]\.focus\(\{ preventScroll: true \}\)/);
|
||||
assert.match(
|
||||
initSource,
|
||||
/contextTabs\[nextIndex\]\.focus\(\{ preventScroll: true \}\)/,
|
||||
);
|
||||
assert.match(initSource, /contextTabs\[nextIndex\]\.click\(\)/);
|
||||
});
|
||||
|
||||
test('Context tabs draw a visible keyboard-focus outline including active tabs', () => {
|
||||
const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
|
||||
const focusRule = rules.find(([, selector, body]) => (
|
||||
selector.trim().endsWith('.context-mode-button:focus-visible')
|
||||
&& /outline:\s*2px solid var\(--text-primary\)/.test(body)
|
||||
));
|
||||
assert.ok(focusRule, 'Context focus-visible rule must draw a two-pixel outline');
|
||||
const focusRule = rules.find(
|
||||
([, selector, body]) =>
|
||||
selector.trim().endsWith('.context-mode-button:focus-visible') &&
|
||||
/outline:\s*2px solid var\(--text-primary\)/.test(body),
|
||||
);
|
||||
assert.ok(
|
||||
focusRule,
|
||||
'Context focus-visible rule must draw a two-pixel outline',
|
||||
);
|
||||
assert.match(focusRule[2], /outline-offset:\s*-3px/);
|
||||
|
||||
const activeRule = rules.find(([, selector]) => selector.trim().endsWith('.context-mode-button.active'));
|
||||
const activeRule = rules.find(([, selector]) =>
|
||||
selector.trim().endsWith('.context-mode-button.active'),
|
||||
);
|
||||
assert.ok(activeRule, 'Context active-state rule is missing');
|
||||
assert.doesNotMatch(activeRule[2], /outline:\s*none/);
|
||||
});
|
||||
|
||||
test('Context async action buttons remain focused while busy', () => {
|
||||
const init = _initGlobalContextPanel.toString();
|
||||
const radio = radioBindings.slice(radioBindings.indexOf('const toggleRadio = async (trigger) => {'), radioBindings.indexOf('this._storeToken = this.store?.connect?.('));
|
||||
const radioPanel = readFileSync(new URL('./ui/views/panels/RadioPanel.vue', import.meta.url), 'utf8');
|
||||
const radio = radioBindings.slice(
|
||||
radioBindings.indexOf('const toggleRadio = async (trigger) => {'),
|
||||
radioBindings.indexOf('this._storeToken = this.store?.connect?.('),
|
||||
);
|
||||
const radioPanel = readFileSync(
|
||||
new URL('./ui/views/panels/RadioPanel.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const clear = clearSelectedLayers.toString();
|
||||
|
||||
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
|
||||
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
|
||||
const search = contextView.match(/<button id="installations-search-btn"[^>]*>/)?.[0];
|
||||
const search = contextView.match(
|
||||
/<button id="installations-search-btn"[^>]*>/,
|
||||
)?.[0];
|
||||
assert.ok(search, 'nearby sites search is missing');
|
||||
assert.doesNotMatch(search, /:disabled|\sdisabled/);
|
||||
assert.match(search, /:aria-busy=/);
|
||||
assert.match(radio, /trigger\.getAttribute\('aria-busy'\) === 'true'/);
|
||||
assert.doesNotMatch(radio, /trigger\.disabled\s*=\s*true/);
|
||||
const cockpitRadio = readFileSync(new URL('./ui/views/panels/CockpitUtilityControls.vue', import.meta.url), 'utf8');
|
||||
const cockpitEnable = cockpitRadio.match(/<UiButton id="cockpit-radio-enable-btn"[^>]*>/)?.[0];
|
||||
const cockpitRadio = readFileSync(
|
||||
new URL('./ui/views/panels/CockpitUtilityControls.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const cockpitEnable = cockpitRadio.match(
|
||||
/<UiButton id="cockpit-radio-enable-btn"[^>]*>/,
|
||||
)?.[0];
|
||||
assert.ok(cockpitEnable, 'Cockpit Radio Enable button is missing');
|
||||
assert.doesNotMatch(cockpitEnable, /disabled(?!=")|:disabled/);
|
||||
assert.match(cockpitEnable, /:aria-busy=/);
|
||||
@@ -89,44 +140,84 @@ test('Context async action buttons remain focused while busy', () => {
|
||||
assert.match(enable, /:aria-busy=/);
|
||||
assert.match(clear, /this\.setClearBusy\(true\)/);
|
||||
// The globe actions view marks the clear button busy, never disabled.
|
||||
const globeActions = readFileSync(new URL('./ui/views/panels/GlobeActions.vue', import.meta.url), 'utf8');
|
||||
const clearButton = globeActions.match(/<button id="clear-selected-layers"[^>]*>/)?.[0];
|
||||
const globeActions = readFileSync(
|
||||
new URL('./ui/views/panels/GlobeActions.vue', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const clearButton = globeActions.match(
|
||||
/<button id="clear-selected-layers"[^>]*>/,
|
||||
)?.[0];
|
||||
assert.ok(clearButton, 'Clear selected layers button is missing');
|
||||
assert.doesNotMatch(clearButton, /disabled(?!=")|:disabled=/);
|
||||
assert.match(clearButton, /:aria-busy=/);
|
||||
});
|
||||
|
||||
test('Context header holds only its title and collapse control', () => {
|
||||
const panel = html.match(/<div id="global-context-panel"[\s\S]*?<div class="cyber-panel-body[ "]/);
|
||||
test('Context header holds only its title, edge switch and collapse control', () => {
|
||||
const panel = html.match(
|
||||
/<div id="global-context-panel"[\s\S]*?<div class="cyber-panel-body[ "]/,
|
||||
);
|
||||
assert.ok(panel, 'Global Context panel is missing');
|
||||
const header = panel[0].match(/<div class="ui-panel__head panel-header">([\s\S]*?)<\/div>\s*<div class="cyber-panel-body[ "]/);
|
||||
const header = panel[0].match(
|
||||
/<div class="ui-panel__head panel-header">([\s\S]*?)<\/div>\s*<div class="cyber-panel-body[ "]/,
|
||||
);
|
||||
assert.ok(header, 'Global Context header is missing');
|
||||
// The kit's own ui-* classes carry no Core styles.
|
||||
const tags = [...header[1].matchAll(/<(\w+)\s+(?:type="button"\s+)?class="([^"]+)"/g)].map(([, tag, cls]) =>
|
||||
`${tag}.${cls.split(' ').filter((name) => !/^ui-/.test(name)).join(' ')}`);
|
||||
assert.deepEqual(tags, ['span.panel-title', 'span.panel-divider', 'button.panel-collapse-btn']);
|
||||
const tags = [
|
||||
...header[1].matchAll(/<(\w+)\s+(?:type="button"\s+)?class="([^"]+)"/g),
|
||||
].map(
|
||||
([, tag, cls]) =>
|
||||
`${tag}.${cls
|
||||
.split(' ')
|
||||
.filter((name) => !/^ui-/.test(name))
|
||||
.join(' ')}`,
|
||||
);
|
||||
assert.deepEqual(tags, [
|
||||
'span.panel-title',
|
||||
'span.panel-divider',
|
||||
'button.panel-edge-btn',
|
||||
'span.material-symbols-outlined',
|
||||
'button.panel-collapse-btn',
|
||||
]);
|
||||
});
|
||||
|
||||
test('Context reads as one segmented control with legible type and no halo', () => {
|
||||
const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
|
||||
const clean = (selector) => selector.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim();
|
||||
const rule = (selector) => rules.find(([, s]) => clean(s) === selector)?.[2] || '';
|
||||
const px = (body, prop) => Number(body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0);
|
||||
const clean = (selector) =>
|
||||
selector
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
const rule = (selector) =>
|
||||
rules.find(([, s]) => clean(s) === selector)?.[2] || '';
|
||||
const px = (body, prop) =>
|
||||
Number(
|
||||
body.match(new RegExp(`${prop}:[^;]*?(\\d+(?:\\.\\d+)?)px`))?.[1] || 0,
|
||||
);
|
||||
|
||||
assert.match(rule('#global-context-panel .panel-glow'), /display:\s*none/);
|
||||
const modes = rule('.global-context-modes');
|
||||
assert.match(modes, /border:\s*1px solid/);
|
||||
assert.match(modes, /padding:\s*2px/);
|
||||
assert.ok(px(rule('.context-mode-button'), 'font') >= 10, 'mode labels must stay at least 10px');
|
||||
assert.ok(
|
||||
px(rule('.context-mode-button'), 'font') >= 10,
|
||||
'mode labels must stay at least 10px',
|
||||
);
|
||||
assert.doesNotMatch(rule('.context-mode-button.active'), /box-shadow/);
|
||||
const standby = rule('.context-mode-standby');
|
||||
assert.ok(px(standby, 'font') >= 10, 'standby guidance must stay at least 10px');
|
||||
assert.ok(
|
||||
px(standby, 'font') >= 10,
|
||||
'standby guidance must stay at least 10px',
|
||||
);
|
||||
assert.doesNotMatch(standby, /dashed/);
|
||||
assert.ok(px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10);
|
||||
assert.ok(
|
||||
px(rule('.global-context-actions .panel-layer-toggle'), 'font-size') >= 10,
|
||||
);
|
||||
// The shared rail title colour (brighter than --text-secondary) keeps the
|
||||
// open Context title legible; no Context-only rule dims it again.
|
||||
assert.equal(
|
||||
rule(":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title"),
|
||||
rule(
|
||||
":root:not([data-ui-theme='cyber']) #global-context-panel:not(.collapsed) .panel-title",
|
||||
),
|
||||
'',
|
||||
);
|
||||
});
|
||||
@@ -64,7 +64,11 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
|
||||
const geometricFeet = finiteNumber(aircraft?.alt_geom);
|
||||
const groundSpeedKnots = finiteNumber(aircraft?.gs);
|
||||
const verticalRateFpm = readAdsbVerticalRateFpm(aircraft);
|
||||
const track = finiteNumber(aircraft?.track);
|
||||
// A parked or slow aircraft reports no ground track, but often its true
|
||||
// heading (surface messages): the way its nose points, which is what an
|
||||
// aircraft standing still is drawn by. Magnetic heading is not true north.
|
||||
const track =
|
||||
finiteNumber(aircraft?.track) ?? finiteNumber(aircraft?.true_heading);
|
||||
|
||||
return [
|
||||
hex,
|
||||
|
||||
@@ -49,3 +49,15 @@ test('keeps grounded fallback contacts and rejects rows without positions', () =
|
||||
assert.equal(normalized.states[0][7], null);
|
||||
assert.equal(normalized.states[0][8], true);
|
||||
});
|
||||
|
||||
test('an aircraft with no track takes its true heading, never its magnetic one', () => {
|
||||
const at = (extra) =>
|
||||
normalizeAdsbLolAircraftState(
|
||||
{ hex: 'abc123', lat: 37.7, lon: -122.2, alt_baro: 'ground', ...extra },
|
||||
1000,
|
||||
)[10];
|
||||
assert.equal(at({ track: 56.25, true_heading: 40 }), 56.25, 'track first');
|
||||
assert.equal(at({ true_heading: 244.69 }), 244.69, 'true heading');
|
||||
assert.equal(at({ mag_heading: 278.44 }), null, 'not magnetic');
|
||||
assert.equal(at({}), null, 'none');
|
||||
});
|
||||
@@ -458,7 +458,8 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
|
||||
);
|
||||
flightState._trackedIcao = null;
|
||||
flightState.records.data.set('civil', { emergency: null });
|
||||
assert.equal(rendering._modelColor('civil'), normal);
|
||||
// An ordinary model draws its mesh's own colours, whatever the billboard's.
|
||||
assert.equal(rendering._modelColor('civil'), Cesium.Color.WHITE);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* Lighting options shared by every aircraft 3D model (Flights, Military
|
||||
* Flights, Local ADS-B).
|
||||
@@ -6,12 +8,24 @@
|
||||
* the model and reads the result back from the GPU (`readPixels`) to light it,
|
||||
* when the model is first placed and again when it moves more than 1 km, when
|
||||
* the scene's atmosphere settings change, or every scene hour under sunlight
|
||||
* lighting. Aircraft models take 94% of their surface from the class colour
|
||||
* (`colorBlendAmount`), so that lighting contributes little; without it they
|
||||
* are lit from Cesium's default spherical harmonics. Measured 2026-10-24
|
||||
* (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest
|
||||
* 14.3-14.8 -> 12.1-12.5 ms.
|
||||
* lighting. Without it they are lit from Cesium's default spherical
|
||||
* harmonics. Measured 2026-10-24 (Intel Arc, Google 3D, ~150 models in the
|
||||
* scene): GPU per frame at rest 14.3-14.8 -> 12.1-12.5 ms.
|
||||
*/
|
||||
export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* How an aircraft model's colour meets its mesh. HIGHLIGHT multiplies, so
|
||||
* white draws the mesh's own colours as built, and the tracked or emergency
|
||||
* colour tints the mesh without hiding its paint. The IR boost draws the
|
||||
* model flat white instead (MIX at 1, with its unlit shader).
|
||||
* @param {boolean} irBoost
|
||||
* @returns {{colorBlendMode: Cesium.ColorBlendMode, colorBlendAmount: number}}
|
||||
*/
|
||||
export function aircraftModelBlend(irBoost) {
|
||||
return irBoost
|
||||
? { colorBlendMode: Cesium.ColorBlendMode.MIX, colorBlendAmount: 1 }
|
||||
: { colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0 };
|
||||
}
|
||||
@@ -243,7 +243,7 @@ export function applyAircraftBillboardTreatment({
|
||||
|
||||
/**
|
||||
* Apply layer-owned hue and composed aircraft alpha to an ambient glTF model without
|
||||
* disturbing Cesium's existing MIX/colorBlendAmount presentation semantics.
|
||||
* changing the model's colour blend mode or amount.
|
||||
* @param {object} input
|
||||
* @param {object} input.model
|
||||
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
|
||||
|
||||
@@ -1882,3 +1882,57 @@ test('detection objects name the vessel card their callout gives way to', () =>
|
||||
_setVesselStateForTest({ enabled: false });
|
||||
}
|
||||
});
|
||||
|
||||
test('an aid to navigation card shows its kind, never a speed or heading', () => {
|
||||
const aid = makeRecord({
|
||||
name: 'SF APPROACH N',
|
||||
mmsi: '993672001',
|
||||
type: 'Cardinal Mark N',
|
||||
speed: 0,
|
||||
course: 135,
|
||||
heading: 135,
|
||||
});
|
||||
const card = buildVesselCard(aid);
|
||||
assert.deepEqual(card.details, ['CARDINAL MARK N']);
|
||||
assert.equal(card.accent, '217, 210, 192');
|
||||
const selected = buildSelectedVesselCard(aid);
|
||||
assert.equal(selected.details[0], 'CARDINAL MARK N');
|
||||
assert.equal(selected.accent, '217, 210, 192');
|
||||
// Known only by its MMSI, an aid is named as one.
|
||||
const unnamed = buildSelectedVesselCard({ ...aid, type: '' });
|
||||
assert.equal(unnamed.details[0], 'AID TO NAVIGATION');
|
||||
assert.deepEqual(buildVesselCard({ ...aid, type: '' }).details, []);
|
||||
});
|
||||
|
||||
test('the HUD of a selected aid to navigation shows no speed or heading', () => {
|
||||
const harness = installWireHarness(undefined, { selectedRecord: null });
|
||||
try {
|
||||
Object.assign(harness.record, {
|
||||
type: 'Port hand Mark',
|
||||
speed: 0,
|
||||
heading: 135,
|
||||
course: 135,
|
||||
});
|
||||
assert.equal(aisLiveVesselsLayer.selectById(harness.record.mmsi), true);
|
||||
assert.match(harness.hud.readout.text, /\nPort hand Mark\n/);
|
||||
assert.doesNotMatch(harness.hud.readout.text, /SPD|HDG|KT/);
|
||||
harness.record.virtual = true;
|
||||
aisLiveVesselsLayer.selectById(harness.record.mmsi);
|
||||
assert.match(harness.hud.readout.text, /\nPort hand Mark · VIRTUAL\n/);
|
||||
} finally {
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation card says it is virtual', () => {
|
||||
const aid = makeRecord({
|
||||
mmsi: '993672001',
|
||||
type: 'Isolated danger',
|
||||
virtual: true,
|
||||
});
|
||||
assert.deepEqual(buildVesselCard(aid).details, ['ISOLATED DANGER · VIRTUAL']);
|
||||
assert.equal(
|
||||
buildSelectedVesselCard(aid).details[0],
|
||||
'ISOLATED DANGER · VIRTUAL',
|
||||
);
|
||||
});
|
||||
@@ -316,3 +316,97 @@ test('a Class B report carries its dimensions in part B', () => {
|
||||
assert.equal(row.length, 12);
|
||||
assert.equal(row.beam, 4);
|
||||
});
|
||||
|
||||
test('an aid-to-navigation report is a row named by its kind of aid, not a ship type', () => {
|
||||
assert.equal(
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: 'AidsToNavigationReport',
|
||||
Message: {
|
||||
AidsToNavigationReport: {
|
||||
UserID: 993672001,
|
||||
Type: 20,
|
||||
Name: 'SF APPROACH N',
|
||||
},
|
||||
},
|
||||
MetaData: {
|
||||
MMSI: '993672001',
|
||||
latitude: 37.79,
|
||||
longitude: -122.52,
|
||||
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const row = rowFor('993672001');
|
||||
assert.equal(row.type, 'Cardinal Mark N');
|
||||
assert.equal(row.name, 'SF APPROACH N');
|
||||
assert.equal(row.speed, null);
|
||||
});
|
||||
|
||||
test("an aid's name runs on into its name extension", () => {
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: 'AidsToNavigationReport',
|
||||
Message: {
|
||||
AidsToNavigationReport: {
|
||||
UserID: 993672002,
|
||||
Type: 13,
|
||||
Name: 'SAN FRANCISCO MAIN S',
|
||||
NameExtension: 'HIP CHANNEL 2',
|
||||
},
|
||||
},
|
||||
MetaData: {
|
||||
MMSI: '993672002',
|
||||
ShipName: 'SAN FRANCISCO MAIN S',
|
||||
latitude: 37.79,
|
||||
longitude: -122.52,
|
||||
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
|
||||
},
|
||||
});
|
||||
assert.equal(rowFor('993672002').name, 'SAN FRANCISCO MAIN SHIP CHANNEL 2');
|
||||
});
|
||||
|
||||
test('a capped row request keeps every vessel ahead of aids to navigation', () => {
|
||||
// The aid reports last, so it is the newest row.
|
||||
ingestAisStreamEnvelope(positionReport('244060901', { Sog: 3 }));
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: 'AidsToNavigationReport',
|
||||
Message: { AidsToNavigationReport: { UserID: 993672003, Type: 24 } },
|
||||
MetaData: {
|
||||
MMSI: '993672003',
|
||||
latitude: 37.79,
|
||||
longitude: -122.52,
|
||||
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
|
||||
},
|
||||
});
|
||||
const rows = aisStreamRows(50000);
|
||||
const firstAid = rows.findIndex((row) => row.mmsi.startsWith('99'));
|
||||
const lastVessel = rows.findLastIndex((row) => !row.mmsi.startsWith('99'));
|
||||
assert.ok(firstAid > lastVessel, `${firstAid} > ${lastVessel}`);
|
||||
const vesselCount =
|
||||
rows.length - rows.filter((row) => row.mmsi.startsWith('99')).length;
|
||||
assert.ok(
|
||||
aisStreamRows(vesselCount).every((row) => !row.mmsi.startsWith('99')),
|
||||
);
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation is marked virtual; a real one carries no flag', () => {
|
||||
const aidReport = (mmsi, VirtualAtoN) => ({
|
||||
MessageType: 'AidsToNavigationReport',
|
||||
Message: {
|
||||
AidsToNavigationReport: { UserID: Number(mmsi), Type: 28, VirtualAtoN },
|
||||
},
|
||||
MetaData: {
|
||||
MMSI: mmsi,
|
||||
latitude: 37.79,
|
||||
longitude: -122.52,
|
||||
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
|
||||
},
|
||||
});
|
||||
ingestAisStreamEnvelope(aidReport('993672004', true));
|
||||
ingestAisStreamEnvelope(aidReport('993672005', false));
|
||||
assert.equal(rowFor('993672004').virtual, true);
|
||||
assert.equal('virtual' in rowFor('993672005'), false);
|
||||
// A later real report of the same aid drops the flag.
|
||||
ingestAisStreamEnvelope(aidReport('993672004', false));
|
||||
assert.equal('virtual' in rowFor('993672004'), false);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* The course of a contact whose feed reports neither a ground track nor a
|
||||
* true heading, read from its own fixes.
|
||||
*
|
||||
* The course runs from an anchor fix to the newest fix once they are at least
|
||||
* COURSE_FROM_FIXES_MIN_M apart; the anchor then moves to the newest fix.
|
||||
* Nearer fixes leave the anchor where it is, so frequent fixes of a slow
|
||||
* aircraft still add up to a course, while position noise on a parked one
|
||||
* never makes one. A fix that does not move time on by a second (a repeat, or
|
||||
* an older position from another feed) never moves the anchor or gives a
|
||||
* course, and neither does one reported slower than
|
||||
* COURSE_FROM_FIXES_MIN_SPEED_MPS.
|
||||
*/
|
||||
import { approxDistanceKm } from './approxDistance.js';
|
||||
|
||||
/** Metres between fixes before a course is read from them. */
|
||||
export const COURSE_FROM_FIXES_MIN_M = 30;
|
||||
/** A contact reported slower than this (m/s) is standing: no course is read. */
|
||||
export const COURSE_FROM_FIXES_MIN_SPEED_MPS = 2;
|
||||
|
||||
/**
|
||||
* Initial great-circle bearing from one point to another, in degrees from
|
||||
* true north (0–360), or null when either is missing or they are less than
|
||||
* COURSE_FROM_FIXES_MIN_M apart.
|
||||
*/
|
||||
export function courseBetweenFixes(fromLat, fromLon, toLat, toLon) {
|
||||
if (![fromLat, fromLon, toLat, toLon].every(Number.isFinite)) return null;
|
||||
if (
|
||||
approxDistanceKm(fromLat, fromLon, toLat, toLon) * 1000 <
|
||||
COURSE_FROM_FIXES_MIN_M
|
||||
)
|
||||
return null;
|
||||
const φ1 = (fromLat * Math.PI) / 180;
|
||||
const φ2 = (toLat * Math.PI) / 180;
|
||||
const Δλ = ((toLon - fromLon) * Math.PI) / 180;
|
||||
const y = Math.sin(Δλ) * Math.cos(φ2);
|
||||
const x =
|
||||
Math.cos(φ1) * Math.sin(φ2) - Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ);
|
||||
return ((Math.atan2(y, x) * 180) / Math.PI + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a course from a new fix.
|
||||
* @param {{lat: number, lon: number, ms: number}|null|undefined} anchor The
|
||||
* anchor fix kept from the last call (null at first).
|
||||
* @param {{lat: number, lon: number, ms: number, speedMps?: number|null}} fix
|
||||
* @returns {{courseDeg: number|null, anchor: {lat: number, lon: number, ms: number}|null}}
|
||||
* The course, or null when none can be read, and the anchor to keep.
|
||||
*/
|
||||
export function courseFromFixes(anchor, { lat, lon, ms, speedMps = null }) {
|
||||
const keep = anchor ?? null;
|
||||
if (![lat, lon, ms].every(Number.isFinite))
|
||||
return { courseDeg: null, anchor: keep };
|
||||
if (!keep) return { courseDeg: null, anchor: { lat, lon, ms } };
|
||||
if (ms < keep.ms + 1000) return { courseDeg: null, anchor: keep };
|
||||
if (Number.isFinite(speedMps) && speedMps < COURSE_FROM_FIXES_MIN_SPEED_MPS)
|
||||
return { courseDeg: null, anchor: keep };
|
||||
const courseDeg = courseBetweenFixes(keep.lat, keep.lon, lat, lon);
|
||||
if (courseDeg === null) return { courseDeg: null, anchor: keep };
|
||||
return { courseDeg, anchor: { lat, lon, ms } };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { courseBetweenFixes, courseFromFixes } from './courseFromFixes.js';
|
||||
|
||||
test('course between fixes reads true bearings, across the antimeridian too', () => {
|
||||
assert.ok(Math.abs(courseBetweenFixes(0, 0, 0, 0.01) - 90) < 1e-6);
|
||||
assert.ok(Math.abs(courseBetweenFixes(0, 0, -0.01, 0) - 180) < 1e-6);
|
||||
assert.ok(
|
||||
Math.abs(courseBetweenFixes(0, 179.9997, 0, -179.9997) - 90) < 1e-6,
|
||||
);
|
||||
assert.equal(courseBetweenFixes(30, -97, 30.0001, -97), null, 'about 11 m');
|
||||
assert.equal(courseBetweenFixes(null, 0, 0, 0.01), null);
|
||||
});
|
||||
|
||||
test('the anchor moves only with a course, and only forward in time', () => {
|
||||
let state = courseFromFixes(null, { lat: 0, lon: 0, ms: 0 });
|
||||
assert.equal(state.courseDeg, null);
|
||||
assert.deepEqual(state.anchor, { lat: 0, lon: 0, ms: 0 });
|
||||
const first = state.anchor;
|
||||
state = courseFromFixes(first, { lat: 0, lon: 0.0001, ms: 1000 });
|
||||
assert.equal(state.courseDeg, null, '11 m: no course');
|
||||
assert.equal(state.anchor, first, 'the anchor stays');
|
||||
state = courseFromFixes(first, { lat: 0, lon: 0.0005, ms: 500 });
|
||||
assert.equal(state.courseDeg, null, 'not a second newer');
|
||||
state = courseFromFixes(first, {
|
||||
lat: 0,
|
||||
lon: 0.0005,
|
||||
ms: 2000,
|
||||
speedMps: 1,
|
||||
});
|
||||
assert.equal(state.courseDeg, null, 'standing');
|
||||
state = courseFromFixes(first, {
|
||||
lat: 0,
|
||||
lon: 0.0005,
|
||||
ms: 2000,
|
||||
speedMps: 8,
|
||||
});
|
||||
assert.ok(Math.abs(state.courseDeg - 90) < 1e-6);
|
||||
assert.deepEqual(state.anchor, { lat: 0, lon: 0.0005, ms: 2000 });
|
||||
state = courseFromFixes(first, { lat: NaN, lon: 0, ms: 3000 });
|
||||
assert.equal(state.anchor, first);
|
||||
});
|
||||
@@ -712,6 +712,15 @@ export const NATURAL_EARTH_CREDIT = {
|
||||
'<a href="https://www.naturalearthdata.com" target="_blank" rel="noopener">Natural Earth</a> (public domain)',
|
||||
};
|
||||
|
||||
/** Registered when a name from the bundled Wikidata places packs is first
|
||||
* shown (CC0 — no attribution required; credited as a courtesy). */
|
||||
export const WIKIDATA_PLACES_CREDIT = {
|
||||
key: 'wikidata-places',
|
||||
html:
|
||||
'City, town and village names from ' +
|
||||
'<a href="https://www.wikidata.org" target="_blank" rel="noopener">Wikidata</a> (CC0)',
|
||||
};
|
||||
|
||||
/** Registered when the first bundled US county or place outline resolves
|
||||
* (public domain — credited as a courtesy). */
|
||||
export const US_CENSUS_CREDIT = {
|
||||
|
||||
+142
-14
@@ -11,6 +11,9 @@
|
||||
* vehicle's road or rail top), and is drawn life size: a type's published
|
||||
* length over the model's built length is its scale.
|
||||
*
|
||||
* An aid to navigation (a buoy, beacon, mark, RACON or light) is drawn as
|
||||
* the set's buoy of its IALA mark, by the mark its type names.
|
||||
*
|
||||
* The resolvers are plain functions over the parsed JSON; `loadFleetModelSet`
|
||||
* fetches the JSON and every GLB once, up front, so no model is fetched
|
||||
* mid-session.
|
||||
@@ -18,6 +21,7 @@
|
||||
|
||||
import { classifyAircraft } from './aircraftClass.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
/** Where the model set is served, relative to the application base. */
|
||||
export const FLEET_MODEL_BASE = '/models/fleet/';
|
||||
@@ -85,16 +89,62 @@ const TEXT_SHIP_TYPES = [
|
||||
];
|
||||
|
||||
/**
|
||||
* The model for an aircraft of ICAO type `type` (A320, B738, R44) and ADS-B
|
||||
* emitter category `category`: the type's, else the category's, else
|
||||
* `default_aircraft`.
|
||||
* The buoy an aid to navigation is drawn as, by the mark its type names
|
||||
* ("Cardinal Mark N", "Beacon, Port hand", "Safe Water"): the first pattern
|
||||
* that matches. Beacons, lights, RACONs and reference points with no mark of
|
||||
* their own are the special mark.
|
||||
*/
|
||||
const AID_MODELS = [
|
||||
[/cardinal\b.*\bn(orth)?$/i, 'buoy_cardinal_north'],
|
||||
[/cardinal\b.*\be(ast)?$/i, 'buoy_cardinal_east'],
|
||||
[/cardinal\b.*\bs(outh)?$/i, 'buoy_cardinal_south'],
|
||||
[/cardinal\b.*\bw(est)?$/i, 'buoy_cardinal_west'],
|
||||
[/isolated danger/i, 'buoy_isolated_danger'],
|
||||
[/safe water/i, 'buoy_safe_water'],
|
||||
[/port hand/i, 'buoy_lateral_port'],
|
||||
[/starboard hand/i, 'buoy_lateral_starboard'],
|
||||
[/special mark|light vessel|lanby/i, 'buoy_special'],
|
||||
[
|
||||
/^(beacon|light\b|leading light|racon|reference point|navigation aid)/i,
|
||||
'buoy_special',
|
||||
],
|
||||
];
|
||||
|
||||
/** The buoy an aid to navigation whose type names no mark is drawn as. */
|
||||
export const DEFAULT_AID_MODEL = 'can_red';
|
||||
|
||||
/**
|
||||
* The buoy model of an aid to navigation's type, else undefined when the
|
||||
* type names no mark.
|
||||
* @param {string|null} [type]
|
||||
* @returns {string|undefined}
|
||||
*/
|
||||
export function aidToNavigationModel(type) {
|
||||
const text = String(type ?? '').trim();
|
||||
for (const [pattern, model] of AID_MODELS)
|
||||
if (pattern.test(text)) return model;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model for an aircraft of ICAO type `type` (A320, B738, R44), ADS-B
|
||||
* emitter category `category` and callsign `callsign`: the first of the
|
||||
* type's callsign rules (`aircraft_callsign`) the callsign matches, else the
|
||||
* type's, else the category's, else `default_aircraft`. An airport vehicle
|
||||
* (type ZVEH) is a fire truck, tug or van by its callsign, else a car.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string} [type]
|
||||
* @param {string} [category]
|
||||
* @param {string} [callsign]
|
||||
* @returns {{model: string, length: number|null}}
|
||||
*/
|
||||
export function resolveAircraft(types, type, category) {
|
||||
export function resolveAircraft(types, type, category, callsign) {
|
||||
const t = type?.trim().toUpperCase();
|
||||
const index = aircraftCallsignRule(types, t, callsign);
|
||||
if (index >= 0) {
|
||||
const rule = types.aircraft_callsign[t][index];
|
||||
return { model: rule.model, length: rule.length };
|
||||
}
|
||||
const [model, length] =
|
||||
(t && (types.aircraft[t] ?? types.helicopters[t])) ||
|
||||
(category && types.categories[category]) ||
|
||||
@@ -102,6 +152,51 @@ export function resolveAircraft(types, type, category) {
|
||||
return { model, length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A callsign as the rules read it: upper case, spaces removed.
|
||||
* @param {string} callsign
|
||||
* @returns {string}
|
||||
*/
|
||||
function callsignKey(callsign) {
|
||||
return String(callsign).toUpperCase().replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of type `type`'s callsign rules (`types.json`'s
|
||||
* `aircraft_callsign[type]`, each `{prefixes, model, length}`, first match
|
||||
* wins) `callsign` matches: its index, -1 when none does or the type has
|
||||
* none. A callsign matches a rule when, upper-cased with spaces removed, it
|
||||
* starts with one of the rule's prefixes.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string|null} [type] ICAO type.
|
||||
* @param {string|null} [callsign]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function aircraftCallsignRule(types, type, callsign) {
|
||||
const t = String(type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const rules = t ? types.aircraft_callsign?.[t] : undefined;
|
||||
if (!rules || !callsign) return -1;
|
||||
const c = callsignKey(callsign);
|
||||
return rules.findIndex((rule) =>
|
||||
rule.prefixes.some((prefix) => c.startsWith(callsignKey(prefix))),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft of ICAO type `type` picks its model by callsign.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string|null} [type]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function aircraftModelByCallsign(types, type) {
|
||||
const t = String(type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
return Boolean(t && types.aircraft_callsign?.[t]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A reported length as one a hull can have, else undefined (drawn as built).
|
||||
* @param {number} [length]
|
||||
@@ -306,24 +401,32 @@ function specOf(set, resolved, fallback, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The model an aircraft is drawn with. The type's entry first; then, for a
|
||||
* The model an aircraft is drawn with. The type's callsign rules (an airport
|
||||
* vehicle by its callsign), then the type's entry; then, for a
|
||||
* type the map lacks, the model of its class (a fast jet, a helicopter, a
|
||||
* glider) when the type names one; then the emitter category's; then
|
||||
* `default_aircraft`.
|
||||
* @param {{catalog: object, types: object}} set
|
||||
* @param {{typeCode?: string|null, type?: string|null,
|
||||
* category?: string|number|null}} aircraft
|
||||
* category?: string|number|null, callsign?: string|null}} aircraft
|
||||
* @returns {object} {@link fleetModelSpec}
|
||||
*/
|
||||
export function aircraftModelSpec(set, { typeCode, type, category } = {}) {
|
||||
export function aircraftModelSpec(
|
||||
set,
|
||||
{ typeCode, type, category, callsign } = {},
|
||||
) {
|
||||
const { types, catalog } = set;
|
||||
const code = String(typeCode ?? type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const emitter = emitterCategory(category);
|
||||
let resolved = resolveAircraft(types, code, emitter);
|
||||
const sign = callsign ? String(callsign) : undefined;
|
||||
let resolved = resolveAircraft(types, code, emitter, sign);
|
||||
// A callsign rule names the model outright; a type's class only stands in
|
||||
// for a type the map lacks.
|
||||
const ruled = aircraftCallsignRule(types, code, sign) >= 0;
|
||||
const typed = code && (types.aircraft[code] || types.helicopters[code]);
|
||||
if (!typed && code) {
|
||||
if (!ruled && !typed && code) {
|
||||
const model = CLASS_MODELS[classifyAircraft({ typeCode: code })];
|
||||
if (model && catalog[model])
|
||||
resolved = { model, length: catalog[model].length };
|
||||
@@ -336,13 +439,33 @@ export function aircraftModelSpec(set, { typeCode, type, category } = {}) {
|
||||
|
||||
/**
|
||||
* The model a vessel is drawn with, from its AIS ship type (a code or a text
|
||||
* family), reported length and beam (metres) and name.
|
||||
* family), reported length and beam (metres) and name. An aid to navigation
|
||||
* ({@link isAidToNavigation}: its type names a buoy, beacon, mark, RACON or
|
||||
* light, or its MMSI is an aid's) is the buoy of its mark
|
||||
* ({@link aidToNavigationModel}), else {@link DEFAULT_AID_MODEL}, drawn as
|
||||
* built and flagged `fixed`: it has no heading to turn to. A virtual aid
|
||||
* (`virtual`) is broadcast where nothing physical stands, so it has no model.
|
||||
* @param {{catalog: object, types: object}} set
|
||||
* @param {{type?: string|number|null, length?: number|null,
|
||||
* beam?: number|null, name?: string|null}} vessel
|
||||
* @returns {object} {@link fleetModelSpec}
|
||||
* @param {{type?: string|number|null, mmsi?: string|number|null,
|
||||
* virtual?: boolean, length?: number|null, beam?: number|null,
|
||||
* name?: string|null}} vessel
|
||||
* @returns {object|null} {@link fleetModelSpec}, with `fixed` for an aid;
|
||||
* null for a virtual aid
|
||||
*/
|
||||
export function vesselModelSpec(set, { type, length, beam, name } = {}) {
|
||||
export function vesselModelSpec(
|
||||
set,
|
||||
{ type, mmsi, virtual, length, beam, name } = {},
|
||||
) {
|
||||
if (virtual === true) return null;
|
||||
if (isAidToNavigation({ type, mmsi })) {
|
||||
const model = aidToNavigationModel(type);
|
||||
const known = model && set.catalog[model] ? model : DEFAULT_AID_MODEL;
|
||||
if (set.catalog[known])
|
||||
return Object.freeze({
|
||||
...fleetModelSpec(set, known, null),
|
||||
fixed: true,
|
||||
});
|
||||
}
|
||||
// A beam counts only beside a reported length: a vessel drawn at its type's
|
||||
// typical length keeps the model's proportions.
|
||||
const reported = hullLength(length ?? undefined);
|
||||
@@ -387,6 +510,9 @@ export function namedFleetModels(types) {
|
||||
...pairs(types.aircraft),
|
||||
...pairs(types.helicopters),
|
||||
...pairs(types.categories),
|
||||
...Object.values(types.aircraft_callsign ?? {}).flatMap((rules) =>
|
||||
rules.map((rule) => rule.model),
|
||||
),
|
||||
...types.vessels.flatMap((group) => group.rules.map((rule) => rule.model)),
|
||||
types.default_aircraft[0],
|
||||
types.default_vessel,
|
||||
@@ -396,6 +522,8 @@ export function namedFleetModels(types) {
|
||||
transit.default[0],
|
||||
...Object.keys(transit.elevation),
|
||||
...Object.values(CLASS_MODELS),
|
||||
...AID_MODELS.map(([, model]) => model),
|
||||
DEFAULT_AID_MODEL,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
DEFAULT_AID_MODEL,
|
||||
FLEET_MODEL_BASE,
|
||||
aidToNavigationModel,
|
||||
aircraftModelSpec,
|
||||
aisShipTypeCode,
|
||||
emitterCategory,
|
||||
@@ -23,6 +25,7 @@ import {
|
||||
vesselModelSpec,
|
||||
} from './fleetModels.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { TRANSIT_MODES } from './transitFeeds.js';
|
||||
import {
|
||||
centrelineSegments,
|
||||
distanceToSurface,
|
||||
@@ -51,8 +54,17 @@ const sliceTypes = {
|
||||
A21N: ['a320', 44.51],
|
||||
A319: ['a320', 33.84],
|
||||
B38M: ['b738', 39.52],
|
||||
ZVEH: ['car', 4.61],
|
||||
GRND: ['radio_mast', 1.9],
|
||||
},
|
||||
helicopters: { EC35: ['ec35', 10.2] },
|
||||
aircraft_callsign: {
|
||||
ZVEH: [
|
||||
{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 },
|
||||
{ prefixes: ['PUSH', 'TUG'], model: 'pushback', length: 6 },
|
||||
{ prefixes: ['DEICER', 'SQUID', 'SQB'], model: 'van', length: 5.51 },
|
||||
],
|
||||
},
|
||||
categories: { A1: ['c172', 8.3] },
|
||||
vessels: [
|
||||
{
|
||||
@@ -112,6 +124,33 @@ test('aircraft resolve by type, then emitter category, then the generic plane',
|
||||
});
|
||||
});
|
||||
|
||||
test('airport vehicles (ZVEH) by callsign, first rule wins, else the type: spaces and case ignored', () => {
|
||||
const zveh = (callsign) =>
|
||||
resolveAircraft(sliceTypes, 'ZVEH', undefined, callsign);
|
||||
assert.deepEqual(zveh('FIRE 2'), { model: 'fire_truck', length: 11.01 });
|
||||
assert.deepEqual(resolveAircraft(sliceTypes, 'zveh', undefined, ' fire2 '), {
|
||||
model: 'fire_truck',
|
||||
length: 11.01,
|
||||
});
|
||||
assert.equal(zveh('PUSH 14').model, 'pushback');
|
||||
assert.equal(zveh('TUG3').model, 'pushback');
|
||||
assert.deepEqual(zveh('DEICER 4'), { model: 'van', length: 5.51 });
|
||||
assert.equal(zveh('SQUID20').model, 'van');
|
||||
assert.equal(zveh('SQB9').model, 'van');
|
||||
assert.equal(zveh('S Q B 9').model, 'van');
|
||||
assert.deepEqual(zveh('LEADER 7'), { model: 'car', length: 4.61 });
|
||||
assert.deepEqual(zveh(undefined), { model: 'car', length: 4.61 });
|
||||
// Callsign rules belong to their type: a fire-named airliner is still an airliner.
|
||||
assert.equal(
|
||||
resolveAircraft(sliceTypes, 'A320', undefined, 'FIRE1').model,
|
||||
'a320',
|
||||
);
|
||||
assert.deepEqual(resolveAircraft(sliceTypes, 'GRND', undefined, 'RX5'), {
|
||||
model: 'radio_mast',
|
||||
length: 1.9,
|
||||
});
|
||||
});
|
||||
|
||||
test('vessels: the first matching rule of the first type range with one, else the generic vessel', () => {
|
||||
assert.equal(resolveVessel(sliceTypes, 70, 366, 51).model, 'container_ship');
|
||||
assert.equal(
|
||||
@@ -225,6 +264,46 @@ test('transit bodies mark the share of the route colour they take; other models
|
||||
}
|
||||
});
|
||||
|
||||
test('aircraft specs: airport vehicles by callsign, ground stations as a mast, as the set says', () => {
|
||||
const zveh = (callsign) =>
|
||||
aircraftModelSpec(set, { typeCode: 'ZVEH', category: 'UNKNOWN', callsign })
|
||||
.model;
|
||||
assert.equal(zveh('FIRE 2'), 'fire_truck');
|
||||
assert.equal(zveh('PUSHBACK1'), 'pushback');
|
||||
assert.equal(zveh('TUG 4'), 'pushback');
|
||||
assert.equal(zveh('DEICER 4'), 'van');
|
||||
assert.equal(zveh('SQUID20'), 'van');
|
||||
assert.equal(zveh('SQB9'), 'van');
|
||||
assert.equal(zveh('LEADER 7'), 'car');
|
||||
assert.equal(zveh('AOPS'), 'car');
|
||||
assert.equal(zveh(null), 'car');
|
||||
const mast = aircraftModelSpec(set, { typeCode: 'GRND', callsign: 'RX5' });
|
||||
assert.equal(mast.model, 'radio_mast');
|
||||
assert.equal(mast.scale, 1);
|
||||
});
|
||||
|
||||
test('a callsign rule outranks the class model of a type the map lacks', () => {
|
||||
const ruled = {
|
||||
...set,
|
||||
types: {
|
||||
...set.types,
|
||||
aircraft_callsign: {
|
||||
...set.types.aircraft_callsign,
|
||||
PUMA: [{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 }],
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.equal(
|
||||
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'FIRE 1' }).model,
|
||||
'fire_truck',
|
||||
);
|
||||
// No rule matched: the class model, as before.
|
||||
assert.equal(
|
||||
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'RESCUE1' }).model,
|
||||
'generic_heli',
|
||||
);
|
||||
});
|
||||
|
||||
test('aircraft specs: by type, then class for an unlisted type, then emitter category', () => {
|
||||
assert.equal(aircraftModelSpec(set, { typeCode: 'A320' }).model, 'a320');
|
||||
assert.equal(aircraftModelSpec(set, { type: 'b744' }).model, 'b744');
|
||||
@@ -305,6 +384,99 @@ test('vessel specs read AIS codes and text families, stretched to the reported b
|
||||
assert.equal(unknown.scale, 1);
|
||||
});
|
||||
|
||||
test('aids to navigation are the buoy of the mark their type names', () => {
|
||||
const cases = [
|
||||
['Cardinal Mark N', 'buoy_cardinal_north'],
|
||||
['Beacon, Cardinal E', 'buoy_cardinal_east'],
|
||||
['Cardinal Mark S', 'buoy_cardinal_south'],
|
||||
['Beacon, Cardinal W', 'buoy_cardinal_west'],
|
||||
['Port Hand Mark', 'buoy_lateral_port'],
|
||||
['Beacon, Port hand', 'buoy_lateral_port'],
|
||||
['Starboard Hand Mark', 'buoy_lateral_starboard'],
|
||||
['Preferred Channel Starboard hand', 'buoy_lateral_starboard'],
|
||||
['Safe Water', 'buoy_safe_water'],
|
||||
['Isolated danger', 'buoy_isolated_danger'],
|
||||
['Beacon, Special Mark', 'buoy_special'],
|
||||
['Special Mark', 'buoy_special'],
|
||||
['Light Vessel / LANBY / Rigs', 'buoy_special'],
|
||||
['RACON', 'buoy_special'],
|
||||
['Light, with Sectors', 'buoy_special'],
|
||||
['Reference point', 'buoy_special'],
|
||||
['Navigation aid', 'buoy_special'],
|
||||
];
|
||||
for (const [type, model] of cases) {
|
||||
assert.equal(aidToNavigationModel(type), model, type);
|
||||
assert.ok(catalog[model], model);
|
||||
const spec = vesselModelSpec(set, { type, mmsi: '993672001' });
|
||||
assert.equal(spec.model, model, type);
|
||||
assert.equal(spec.category, 'buoys', type);
|
||||
assert.equal(spec.fixed, true, type);
|
||||
// A buoy is drawn as built, whatever length the report gives.
|
||||
assert.equal(spec.scale, 1, type);
|
||||
}
|
||||
assert.equal(
|
||||
vesselModelSpec(set, { type: 'Safe Water', length: 120, beam: 30 }).scale,
|
||||
1,
|
||||
);
|
||||
// An aid of no stated kind, known only by its MMSI, is the default can.
|
||||
assert.ok(catalog[DEFAULT_AID_MODEL]);
|
||||
const unnamed = vesselModelSpec(set, { type: '', mmsi: '993660123' });
|
||||
assert.equal(unnamed.model, DEFAULT_AID_MODEL);
|
||||
assert.equal(unnamed.fixed, true);
|
||||
assert.equal(aidToNavigationModel('Fixed structure off shore'), undefined);
|
||||
// A virtual aid is broadcast where nothing stands: it keeps its disc.
|
||||
assert.equal(
|
||||
vesselModelSpec(set, {
|
||||
type: 'Cardinal Mark N',
|
||||
mmsi: '993672001',
|
||||
virtual: true,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
// Vessels, including those that work on buoys, keep their hulls.
|
||||
for (const vessel of [
|
||||
{ type: 'Buoy Tender', mmsi: '366999001', length: 60 },
|
||||
{ type: '70', mmsi: '366999002' },
|
||||
{ type: 'Tug', mmsi: '' },
|
||||
]) {
|
||||
const spec = vesselModelSpec(set, vessel);
|
||||
assert.notEqual(spec.category, 'buoys', vessel.type);
|
||||
assert.equal(spec.fixed, undefined, vessel.type);
|
||||
}
|
||||
});
|
||||
|
||||
test('every transit mode but unknown draws its own model, and a route type a finer one', () => {
|
||||
for (const mode of TRANSIT_MODES.filter((m) => m !== 'unknown')) {
|
||||
assert.ok(types.transit.modes[mode], `${mode} has a model`);
|
||||
assert.equal(
|
||||
resolveTransit(types, { mode }).model,
|
||||
types.transit.modes[mode][0],
|
||||
);
|
||||
}
|
||||
for (const [mode, model] of [
|
||||
['trolleybus', 'trolleybus'],
|
||||
['cable_tram', 'cable_tram'],
|
||||
['aerial_lift', 'gondola'],
|
||||
['funicular', 'funicular'],
|
||||
['monorail', 'monorail'],
|
||||
])
|
||||
assert.equal(resolveTransit(types, { mode }).model, model, mode);
|
||||
// A route type outranks the mode: a coach and a high-speed set are still
|
||||
// the bus and rail modes.
|
||||
for (const [routeType, mode, model] of [
|
||||
[200, 'bus', 'coach'],
|
||||
[101, 'rail', 'high_speed'],
|
||||
[106, 'rail', 'regional_dmu'],
|
||||
[710, 'bus', 'double_decker'],
|
||||
])
|
||||
assert.equal(resolveTransit(types, { routeType, mode }).model, model);
|
||||
// A type the table lacks falls back to the mode.
|
||||
assert.equal(
|
||||
resolveTransit(types, { routeType: 300, mode: 'rail' }).model,
|
||||
'commuter_emu',
|
||||
);
|
||||
});
|
||||
|
||||
test('transit specs: rail category and mode, then route type, then mode, then the default', () => {
|
||||
assert.deepEqual(resolveTransit(types, { railCategory: 'national' }), {
|
||||
model: 'intercity',
|
||||
|
||||
@@ -32,7 +32,7 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
c172: Object.freeze([4.0507, 0.4481, 0]),
|
||||
c30j: Object.freeze([13.568, 0.9917, 0]),
|
||||
c56x: Object.freeze([7.4627, 0.4526, 0]),
|
||||
car: Object.freeze([2.3, 0.418, 0]),
|
||||
car: Object.freeze([2.1851, 0.301, 0]),
|
||||
cl35: Object.freeze([10.4607, 0.8247, 0]),
|
||||
crj9: Object.freeze([17.8413, 0.8624, 0]),
|
||||
dh8d: Object.freeze([15.7902, 0.7501, 0]),
|
||||
@@ -40,7 +40,7 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
e55p: Object.freeze([7.6566, 0.503, 0]),
|
||||
ec35: Object.freeze([5.1003, 0.1471, 0]),
|
||||
ec45: Object.freeze([5.8004, 0.555, 0]),
|
||||
fire_truck: Object.freeze([5.5, 0.6051, 0]),
|
||||
fire_truck: Object.freeze([5.39, 0.4227, 0]),
|
||||
generic_heli: Object.freeze([5.4997, 0.1604, 0]),
|
||||
generic_plane: Object.freeze([16.5228, 0.712, 0]),
|
||||
glf4: Object.freeze([13.4603, 0.8243, 0]),
|
||||
@@ -53,8 +53,9 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
mq9: Object.freeze([5.8498, -0.062, 0]),
|
||||
p28a: Object.freeze([3.3695, 0.3959, 0]),
|
||||
pc12: Object.freeze([6.6416, 0.5288, 0]),
|
||||
pushback: Object.freeze([3, 0.2499, 0]),
|
||||
pushback: Object.freeze([2.9536, 0.388, 0]),
|
||||
r44: Object.freeze([4.4219, -0.3001, 0]),
|
||||
radio_mast: Object.freeze([1.2, 0, 0]),
|
||||
s76: Object.freeze([6.6001, 0.1915, 0]),
|
||||
sr22: Object.freeze([3.6762, 0.2376, 0]),
|
||||
t38: Object.freeze([7.0246, -0.3791, 0]),
|
||||
@@ -62,5 +63,5 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
tower: Object.freeze([1.2952, -0.0007, 0]),
|
||||
ultralight: Object.freeze([3.2271, 0.3259, 0]),
|
||||
v22: Object.freeze([7.9868, 0.2956, 0]),
|
||||
van: Object.freeze([2.75, 0.418, 0]),
|
||||
van: Object.freeze([2.695, 0.2812, 0]),
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
# Wikidata cities pack
|
||||
|
||||
World cities and towns for naming a spot (the nearest city), the places
|
||||
around it and finding a place by name, read by `src/data/wikidataCities.js`. The app reads this file; it
|
||||
does not call Wikidata or any place service for these.
|
||||
|
||||
| File | Contents |
|
||||
|------|----------|
|
||||
| `cities.json` | Human settlements with coordinates and a population at or above the cut-off (see `meta.minPopulation`), largest first |
|
||||
|
||||
Each row is `[name, lat, lon, population, country, wikidata]`: the English
|
||||
label, coordinates to three decimals, the largest stated population, the
|
||||
ISO 3166-1 alpha-2 country code (empty when Wikidata gives none) and the
|
||||
Wikidata id.
|
||||
|
||||
**Source:** Wikidata, read once from the Wikidata Query Service by
|
||||
`scripts/build-wikidata-cities.mjs`. The build time and row count are in the
|
||||
file's `meta` header.
|
||||
|
||||
**License:** CC0 1.0 (https://www.wikidata.org/wiki/Wikidata:Licensing). No
|
||||
attribution is legally required.
|
||||
|
||||
**What is left out:** metropolitan areas, urban agglomerations, conurbations
|
||||
and similar groupings of settlements, so a view is named after the city
|
||||
rather than the area around it (an item of a narrower grouping kind that is
|
||||
also a city stays: Istanbul is a metropolitan municipality and a megacity);
|
||||
places that no longer stand (former entities, ghost towns, abandoned
|
||||
villages, archaeological sites) unless they are also a living settlement;
|
||||
and places Wikidata states as dissolved or abolished (P576) where another
|
||||
place within 15 km still names the spot. A dissolved unit with nothing
|
||||
else near it stays: many of Vietnam's provincial cities ended as units in
|
||||
2025 and still stand under their names. Also left out: places below the population cut-off and
|
||||
places without an English label.
|
||||
|
||||
**Rebuild:** `node scripts/build-wikidata-cities.mjs [--min-population 15000]`.
|
||||
The build runs one query at a time with pauses and honours the service's
|
||||
Retry-After; it takes about ten minutes. It fails if a short list of
|
||||
well-known cities is missing from the result, or a known grouping gets in.
|
||||
|
||||
**Limits:** populations are whatever Wikidata states and differ in date and
|
||||
definition between places (city proper, municipality, urban district). Some
|
||||
districts and suburbs appear as their own rows.
|
||||
@@ -0,0 +1 @@
|
||||
{"meta":{"source":"Wikidata (https://www.wikidata.org), via the Wikidata Query Service","license":"CC0 1.0","built":"2026-11-15T02:59:26.673Z","minPopulation":15000,"count":31827,"columns":["name","lat","lon","population","country","wikidata"]},"rows":[["Chongqing",29.55,106.507,32054159,"CN","Q11725"],["Delhi",28.667,77.217,26495000,"IN","Q1353"],["Shanghai",31.233,121.469,24870895,"CN","Q8686"],["Beijing",39.904,116.408,21893095,"CN","Q956"],["Chengdu",30.66,104.063,20937757,"CN","Q30002"],["Guangzhou",23.13,113.26,18676605,"CN","Q16572"],["Shenzhen",22.547,114.054,17494398,"CN","Q15174"],["Dhaka",23.729,90.394,16800000,"BD","Q1354"],["Istanbul",41.01,28.96,15655924,"TR","Q406"],["Mumbai",19.076,72.877,15414288,"IN","Q1156"],["Karachi",24.86,67.01,14910352,"PK","Q8660"],["Kinshasa",-4.322,15.312,14565700,"CD","Q3838"],["Tokyo",35.689,139.692,14264798,"JP","Q1490"],["Ho Chi Minh City",10.776,106.702,14002598,"VN","Q1854"],["Tianjin",39.147,117.206,13866009,"CN","Q11736"],["Moscow",55.751,37.617,13274285,"RU","Q649"],["Xi'an",34.261,108.942,12952907,"CN","Q5826"],["Suzhou",31.3,120.619,12748262,"CN","Q42622"],["Zhengzhou",34.749,113.661,12600574,"CN","Q30340"],["Bengaluru",12.979,77.591,12327000,"IN","Q1355"],["Wuhan",30.595,114.297,12326518,"CN","Q11746"],["Hangzhou",30.25,120.168,11936010,"CN","Q4970"],["Baoding",38.867,115.485,11544036,"CN","Q58584"],["São Paulo",-23.55,-46.634,11451999,"BR","Q174"],["Jakarta",-6.175,106.827,11135191,"ID","Q3630"],["Lahore",31.55,74.344,11126285,"PK","Q11739"],["Linyi",35.104,118.35,11018365,"CN","Q373346"],["Shijiazhuang",38.042,114.51,10640458,"CN","Q58401"],["Dongguan",23.047,113.749,10466625,"CN","Q59218"],["Qingdao",36.117,120.4,10071722,"CN","Q170322"],["Changsha",28.199,112.971,10047914,"CN","Q174091"],["Harbin",45.75,126.633,10009854,"CN","Q42956"],["Lima",-12.06,-77.037,9943800,"PE","Q2868"],["Cairo",30.044,31.236,9801536,"EG","Q85"],["Nanyang",32.999,112.529,9713112,"CN","Q404763"],["Seoul",37.56,126.99,9668465,"KR","Q8684"],["Tokyo",35.684,139.774,9640742,"JP","Q7473516"],["Wenzhou",27.999,120.656,9572903,"CN","Q42635"],["Foshan",23.029,113.106,9498863,"CN","Q34412"],["Handan",36.612,114.489,9413990,"CN","Q58570"],["Ningbo",29.875,121.549,9404283,"CN","Q42780"],["Weifang",36.717,119.1,9386705,"CN","Q217698"],["Hefei",31.864,117.281,9369881,"CN","Q185684"],["Nanjing",32.061,118.779,9314685,"CN","Q16666"],["Mexico City",19.354,-99.136,9209944,"MX","Q1489"],["Jinan",36.667,116.983,9202432,"CN","Q170247"],["Hyderabad",17.362,78.475,9191000,"IN","Q1361"],["Xuzhou",34.261,117.186,9083790,"CN","Q57719"],["Shenyang",41.803,123.428,9070093,"CN","Q11720"],["Changchun",43.88,125.323,9066906,"CN","Q92161"],["Zhoukou",33.625,114.642,9026015,"CN","Q198061"],["Kuala Lumpur",3.148,101.695,9000280,"MY","Q1865"],["Ganzhou",25.829,114.934,8970014,"CN","Q363166"],["New York City",40.713,-74.006,8804190,"US","Q60"],["London",51.507,-0.128,8799728,"GB","Q84"],["Heze",35.233,115.433,8795939,"CN","Q332753"],["Quanzhou",24.914,118.586,8782285,"CN","Q68695"],["Nanning",22.819,108.315,8741584,"CN","Q179608"],["Hanoi",21.024,105.841,8717600,"VN","Q1858"],["Tehran",35.689,51.39,8693706,"IR","Q3616"],["Kunming",25.043,102.706,8460088,"CN","Q182852"],["Jining",35.4,116.567,8357897,"CN","Q372791"],["Fuzhou",26.077,119.292,8291268,"CN","Q68481"],["Fuyang",32.899,115.804,8200264,"CN","Q360584"],["Baghdad",33.315,44.366,8126755,"IQ","Q1530"],["Veracruz",19.19,-96.153,8062579,"MX","Q173270"],["Bogotá",4.61,-74.082,8034649,"CO","Q2841"],["Shangqiu",34.426,115.647,7816831,"CN","Q404817"],["Nantong",31.983,120.887,7726635,"CN","Q57947"],["Tangshan",39.629,118.174,7717983,"CN","Q58422"],["Ahmedabad",23.022,72.58,7645000,"IN","Q1070"],["Wuxi",31.567,120.283,7462135,"CN","Q42651"],["Dalian",38.9,121.6,7450785,"CN","Q74881"],["Hong Kong",22.278,114.159,7413070,"CN","Q8646"],["Cangzhou",38.304,116.845,7300783,"CN","Q58695"],["Xingtai",37.066,114.475,7111106,"CN","Q58576"],["Yantai",37.464,121.448,7102116,"CN","Q210493"],["Luoyang",34.659,112.424,7056699,"CN","Q187136"],["Jinhua",29.105,119.649,7050683,"CN","Q58210"],["Riyadh",24.638,46.715,7009100,"SA","Q3692"],["Zhumadian",32.977,114.025,7008427,"CN","Q198240"],["Zhanjiang",21.197,110.403,6981236,"CN","Q59144"],["Bijie",27.302,105.286,6899636,"CN","Q486319"],["Yangon",16.795,96.16,6874000,"MM","Q37995"],["Yancheng",33.35,120.157,6709629,"CN","Q57866"],["Hengyang",26.897,112.586,6645243,"CN","Q144663"],["Taizhou",28.658,121.422,6622888,"CN","Q58273"],["Zunyi",27.705,106.934,6606675,"CN","Q28994"],["Chennai",13.082,80.275,6599000,"IN","Q1352"],["Shaoyang",27.242,111.472,6563520,"CN","Q194531"],["Shangrao",28.442,117.963,6491088,"CN","Q363479"],["Huanggang",30.45,114.875,6333000,"CN","Q71355"],["Moro",-6,144,6310129,"PG","Q103927888"],["Santiago",-33.438,-70.65,6257516,"CL","Q2887"],["Nanchang",28.684,115.887,6255007,"CN","Q171943"],["Xinxiang",35.299,113.885,6251929,"CN","Q404362"],["Xinyang",32.126,114.067,6234401,"CN","Q404873"],["Rio de Janeiro",-2Line truncated
|
||||
@@ -57,7 +57,14 @@ test('every typed aircraft renders at its published length, a real-world aircraf
|
||||
);
|
||||
// A grounded aircraft stands on its wheels: its origin the scaled
|
||||
// clearance above the ground, never below it.
|
||||
assert.ok(spec.clearanceM > 0, `${type}: clearance ${spec.clearanceM}`);
|
||||
// A model built standing on its origin (a ground vehicle, a ground
|
||||
// station's mast: its lowest point at z 0) has no clearance.
|
||||
if (set.catalog[model].min[2] > -0.05)
|
||||
assert.ok(
|
||||
spec.clearanceM >= 0 && spec.clearanceM < 0.05 * spec.scale,
|
||||
`${type}: built standing, clearance ${spec.clearanceM}`,
|
||||
);
|
||||
else assert.ok(spec.clearanceM > 0, `${type}: clearance ${spec.clearanceM}`);
|
||||
assert.ok(spec.clearanceM < radius, `${type}: clearance larger than the aircraft`);
|
||||
}
|
||||
}
|
||||
@@ -296,3 +303,41 @@ test('a layer asking every tick gets one cached spec per type and category', asy
|
||||
assert.notEqual(aircraftLayerModelSpec({ typeCode: 'B744' }, set), a);
|
||||
assert.ok(Object.isFrozen(a));
|
||||
});
|
||||
|
||||
test('an airport vehicle is cached by its callsign; other aircraft by type and category only', async () => {
|
||||
const { aircraftLayerModelSpec, aircraftModelSpecCacheKey } = await import(
|
||||
'../layers/flights/modelSpec.js'
|
||||
);
|
||||
const tender = aircraftLayerModelSpec(
|
||||
{ typeCode: 'ZVEH', callsign: 'FIRE 2' },
|
||||
set,
|
||||
);
|
||||
const car = aircraftLayerModelSpec(
|
||||
{ typeCode: 'ZVEH', callsign: 'LEADER 7' },
|
||||
set,
|
||||
);
|
||||
assert.equal(tender.model, 'fire_truck');
|
||||
assert.equal(car.model, 'car');
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'A320', callsign: 'BAW1' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'A320', callsign: 'DLH2' }, set),
|
||||
);
|
||||
assert.notEqual(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 2' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'LEADER 7' }, set),
|
||||
);
|
||||
// Keyed by the rule matched, not the callsign: at most one entry per rule
|
||||
// and one for the type's own model.
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 2' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 9' }, set),
|
||||
);
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'LEADER 7' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'ASD' }, set),
|
||||
);
|
||||
assert.equal(
|
||||
aircraftLayerModelSpec({ typeCode: 'ZVEH', callsign: 'FIRE 9' }, set),
|
||||
tender,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* A host-supplied placement provider: an application embedding the catalog
|
||||
* may decide where its moving contacts are drawn while live. Each layer that
|
||||
* takes one tells it every fix it accepts (`observe`) and asks it, each time
|
||||
* it draws a contact, where to draw it now (`place`). A layer given none, or
|
||||
* asking about a contact the provider does not place (`null`), draws the
|
||||
* contact with its own motion, exactly as without a provider. A provider
|
||||
* that throws is treated as having no answer for that call.
|
||||
*
|
||||
* Layers consult a provider only while live: following the world clock, the
|
||||
* layer's own motion places every contact.
|
||||
*
|
||||
* @typedef {'aircraft'|'military'|'vessels'|'transit'|'rail'} PlacementKind
|
||||
*
|
||||
* @typedef {object} PlacementFix
|
||||
* @property {number} timeMs The fix's own time, Unix ms.
|
||||
* @property {number} lat
|
||||
* @property {number} lon
|
||||
* @property {number} [altitudeM] The height the layer draws the fix at,
|
||||
* metres above the ellipsoid; NaN when the layer keeps its own height.
|
||||
* @property {number} [speedMps] Reported ground speed, NaN for none.
|
||||
* @property {number} [courseDeg] Reported course over ground, NaN for none.
|
||||
* @property {number} [headingDeg] Reported heading, NaN for none.
|
||||
* @property {boolean} [onGround] Reported on the ground (aircraft).
|
||||
* @property {string} [feedId] The feed the contact belongs to (transit, rail).
|
||||
*
|
||||
* @typedef {object} Placement
|
||||
* @property {number} lat
|
||||
* @property {number} lon
|
||||
* @property {number} altitudeM Metres above the ellipsoid, as the observed
|
||||
* fixes' `altitudeM`; NaN keeps the layer's own height.
|
||||
* @property {number} courseDeg Direction of travel, NaN for none.
|
||||
* @property {number} speedMps NaN for none.
|
||||
* @property {boolean} extrapolating Past the contact's newest fix.
|
||||
*
|
||||
* @typedef {object} LayerPlacement What a layer is handed: never throws.
|
||||
* @property {(id: string, fix: PlacementFix) => void} observe
|
||||
* @property {(id: string, wallMs: number) => Placement|null} place The
|
||||
* answer is one object reused by every call: read it before the next.
|
||||
* @property {(id: string) => void} forget The contact left the layer.
|
||||
*
|
||||
* @typedef {object} PlacementProvider
|
||||
* @property {(kind: PlacementKind) => object|null|undefined} layer The
|
||||
* placement for one kind of contact: an object with `place(id, wallMs)`
|
||||
* and optionally `observe(id, fix)` and `forget(id)`, or null to leave that
|
||||
* kind to its layer's own motion.
|
||||
*/
|
||||
|
||||
/** The kinds of contact a provider may place. */
|
||||
export const PLACEMENT_KINDS = Object.freeze([
|
||||
'aircraft',
|
||||
'military',
|
||||
'vessels',
|
||||
'transit',
|
||||
'rail',
|
||||
]);
|
||||
|
||||
const finiteOr = (value, fallback) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||
|
||||
/**
|
||||
* One kind's placement from a provider, guarded so a layer can call it every
|
||||
* frame: null when there is no provider or it does not place `kind`.
|
||||
* @param {PlacementProvider|null|undefined} provider
|
||||
* @param {PlacementKind} kind
|
||||
* @returns {LayerPlacement|null}
|
||||
*/
|
||||
export function layerPlacement(provider, kind) {
|
||||
if (!PLACEMENT_KINDS.includes(kind))
|
||||
throw new TypeError(`Unknown placement kind: ${kind}`);
|
||||
if (provider == null) return null;
|
||||
if (typeof provider.layer !== 'function')
|
||||
throw new TypeError('A placement provider needs a layer(kind) function');
|
||||
const placement = provider.layer(kind);
|
||||
if (placement == null) return null;
|
||||
if (typeof placement.place !== 'function')
|
||||
throw new TypeError(`The ${kind} placement needs a place(id, wallMs)`);
|
||||
const observe =
|
||||
typeof placement.observe === 'function' ? placement.observe : null;
|
||||
const forget =
|
||||
typeof placement.forget === 'function' ? placement.forget : null;
|
||||
// Asked for every drawn contact every frame: one answer, reused.
|
||||
const answer = {
|
||||
lat: NaN,
|
||||
lon: NaN,
|
||||
altitudeM: NaN,
|
||||
courseDeg: NaN,
|
||||
speedMps: NaN,
|
||||
extrapolating: false,
|
||||
};
|
||||
return Object.freeze({
|
||||
observe(id, fix) {
|
||||
if (!observe) return;
|
||||
try {
|
||||
observe.call(placement, id, fix);
|
||||
} catch {
|
||||
// A provider that fails to take a fix only answers less.
|
||||
}
|
||||
},
|
||||
place(id, wallMs) {
|
||||
let placed;
|
||||
try {
|
||||
placed = placement.place(id, wallMs);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!placed ||
|
||||
!Number.isFinite(placed.lat) ||
|
||||
!Number.isFinite(placed.lon) ||
|
||||
Math.abs(placed.lat) > 90
|
||||
)
|
||||
return null;
|
||||
answer.lat = placed.lat;
|
||||
answer.lon = placed.lon;
|
||||
answer.altitudeM = finiteOr(placed.altitudeM, NaN);
|
||||
answer.courseDeg = finiteOr(placed.courseDeg, NaN);
|
||||
answer.speedMps = finiteOr(placed.speedMps, NaN);
|
||||
answer.extrapolating = placed.extrapolating === true;
|
||||
return answer;
|
||||
},
|
||||
forget(id) {
|
||||
if (!forget) return;
|
||||
try {
|
||||
forget.call(placement, id);
|
||||
} catch {
|
||||
// Nothing to undo.
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PLACEMENT_KINDS, layerPlacement } from './placementProvider.js';
|
||||
|
||||
test('no provider, or a provider that leaves a kind alone, gives no placement', () => {
|
||||
for (const kind of PLACEMENT_KINDS) {
|
||||
assert.equal(layerPlacement(null, kind), null);
|
||||
assert.equal(layerPlacement(undefined, kind), null);
|
||||
assert.equal(layerPlacement({ layer: () => null }, kind), null);
|
||||
}
|
||||
assert.throws(() => layerPlacement(null, 'satellites'), TypeError);
|
||||
assert.throws(() => layerPlacement({}, 'aircraft'), TypeError);
|
||||
assert.throws(
|
||||
() => layerPlacement({ layer: () => ({ observe() {} }) }, 'aircraft'),
|
||||
TypeError,
|
||||
);
|
||||
});
|
||||
|
||||
test('a placement is asked by id and wall time, and its answer is checked', () => {
|
||||
const asked = [];
|
||||
const seen = [];
|
||||
const forgotten = [];
|
||||
const answers = new Map([
|
||||
[
|
||||
'a',
|
||||
{ lat: 51.5, lon: -0.1, altitudeM: 900, courseDeg: 270, speedMps: 80 },
|
||||
],
|
||||
['partial', { lat: 10, lon: 20, altitudeM: 'high', extrapolating: true }],
|
||||
['off-globe', { lat: 91, lon: 0 }],
|
||||
['nan', { lat: NaN, lon: 0 }],
|
||||
]);
|
||||
const provider = {
|
||||
layer: (kind) =>
|
||||
kind === 'aircraft'
|
||||
? {
|
||||
observe: (id, fix) => seen.push([id, fix.timeMs]),
|
||||
place(id, wallMs) {
|
||||
asked.push([id, wallMs]);
|
||||
return answers.get(id) ?? null;
|
||||
},
|
||||
forget: (id) => forgotten.push(id),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
assert.equal(layerPlacement(provider, 'vessels'), null);
|
||||
const placement = layerPlacement(provider, 'aircraft');
|
||||
placement.observe('a', { timeMs: 5, lat: 0, lon: 0 });
|
||||
assert.deepEqual(seen, [['a', 5]]);
|
||||
const placed = placement.place('a', 1000);
|
||||
assert.deepEqual(
|
||||
{ ...placed },
|
||||
{
|
||||
lat: 51.5,
|
||||
lon: -0.1,
|
||||
altitudeM: 900,
|
||||
courseDeg: 270,
|
||||
speedMps: 80,
|
||||
extrapolating: false,
|
||||
},
|
||||
);
|
||||
const partial = placement.place('partial', 2000);
|
||||
assert.equal(partial, placed, 'one answer object, reused');
|
||||
assert.ok(Number.isNaN(partial.altitudeM));
|
||||
assert.ok(Number.isNaN(partial.courseDeg));
|
||||
assert.ok(Number.isNaN(partial.speedMps));
|
||||
assert.equal(partial.extrapolating, true);
|
||||
assert.equal(placement.place('off-globe', 3000), null);
|
||||
assert.equal(placement.place('nan', 3000), null);
|
||||
assert.equal(placement.place('unknown', 3000), null);
|
||||
assert.deepEqual(
|
||||
asked.map(([id]) => id),
|
||||
['a', 'partial', 'off-globe', 'nan', 'unknown'],
|
||||
);
|
||||
placement.forget('a');
|
||||
assert.deepEqual(forgotten, ['a']);
|
||||
});
|
||||
|
||||
test('a provider that throws has no answer, and observe and forget are optional', () => {
|
||||
const placement = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place() {
|
||||
throw new Error('not ready');
|
||||
},
|
||||
}),
|
||||
},
|
||||
'transit',
|
||||
);
|
||||
assert.equal(placement.place('x', 0), null);
|
||||
assert.doesNotThrow(() => placement.observe('x', { timeMs: 0 }));
|
||||
assert.doesNotThrow(() => placement.forget('x'));
|
||||
const failing = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place: () => null,
|
||||
observe() {
|
||||
throw new Error('full');
|
||||
},
|
||||
forget() {
|
||||
throw new Error('gone');
|
||||
},
|
||||
}),
|
||||
},
|
||||
'rail',
|
||||
);
|
||||
assert.doesNotThrow(() => failing.observe('x', { timeMs: 0 }));
|
||||
assert.doesNotThrow(() => failing.forget('x'));
|
||||
});
|
||||
@@ -1244,7 +1244,15 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
|
||||
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
|
||||
await rocketLaunchesLayer.update();
|
||||
const at = Date.parse(launchTime);
|
||||
assert.deepEqual(worldClock.coverage(), { start: at, end: at, marks: [at] });
|
||||
// The launch is a mark labelled with its mission's name.
|
||||
assert.deepEqual(worldClock.coverage(), {
|
||||
start: at,
|
||||
end: at,
|
||||
marks: [at],
|
||||
markDetails: [
|
||||
{ time: at, label: 'GAUNTLET PAYLOAD', id: 'mission-runtime', kind: 'launch' },
|
||||
],
|
||||
});
|
||||
assert.equal(worldClock.isSupported(), true, 'loaded launches bring up the timeline');
|
||||
|
||||
const entities = dataSources[0].entities.values;
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
mergeTimelineRuns,
|
||||
readTimelineFixes,
|
||||
TIMELINE_UNSEEN_MS,
|
||||
} from '../time/timelineFixes.js';
|
||||
|
||||
/** Fixes nearer than this are too close to read a course between. */
|
||||
const COURSE_MIN_M = 5;
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
|
||||
/** The initial great-circle course from one fix to another (degrees from
|
||||
* north), or null when they are too close to tell. */
|
||||
function courseBetween(from, to) {
|
||||
const lat1 = Cesium.Math.toRadians(from.lat);
|
||||
const lat2 = Cesium.Math.toRadians(to.lat);
|
||||
const dLon = Cesium.Math.toRadians(to.lon - from.lon);
|
||||
const dLat = lat2 - lat1;
|
||||
const a =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||||
if (2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(a))) < COURSE_MIN_M)
|
||||
return null;
|
||||
const y = Math.sin(dLon) * Math.cos(lat2);
|
||||
const x =
|
||||
Math.cos(lat1) * Math.sin(lat2) -
|
||||
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
|
||||
return (Cesium.Math.toDegrees(Math.atan2(y, x)) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's motion history with the fixes its record carries at a time
|
||||
* (`observation.fixes`, see src/time/timelineFixes.js) merged in, so the
|
||||
* layer places it on its own track at any time they span; null when the
|
||||
* record carries none. Each fix is drawn at the record's render height,
|
||||
* moved by the fix's own barometric change from the record's, and heads
|
||||
* where its track goes next (the last, where it came from). Entries are
|
||||
* marked `timeline`.
|
||||
* @param {object[]|undefined} history The contact's history entries.
|
||||
* @param {object} observation The record, with `fixes` and `baroAltitudeM`.
|
||||
* @param {{renderAltitudeM: number, renderAltitudeInvented?: boolean}} meta
|
||||
* @param {number|null} velocity The record's ground speed (m/s).
|
||||
* @param {number} centreMs The snapshot's time: the fixes kept are nearest it.
|
||||
* @returns {object[]|null}
|
||||
*/
|
||||
export function mergeAircraftTimelineFixes(
|
||||
history,
|
||||
observation,
|
||||
meta,
|
||||
velocity,
|
||||
centreMs,
|
||||
) {
|
||||
const fixes = readTimelineFixes(observation?.fixes);
|
||||
if (!fixes) return null;
|
||||
const baroM = Number.isFinite(observation.baroAltitudeM)
|
||||
? observation.baroAltitudeM
|
||||
: null;
|
||||
const entries = fixes.map((fix, index) => {
|
||||
const course =
|
||||
index + 1 < fixes.length
|
||||
? courseBetween(fix, fixes[index + 1])
|
||||
: courseBetween(fixes[index - 1], fix);
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(fix.atMs)),
|
||||
epochMs: fix.atMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(
|
||||
fix.lon,
|
||||
fix.lat,
|
||||
baroM !== null && fix.altitudeM !== null
|
||||
? meta.renderAltitudeM + (fix.altitudeM - baroM)
|
||||
: meta.renderAltitudeM,
|
||||
),
|
||||
velocity,
|
||||
// No reported track per fix: the course is read from the fixes.
|
||||
track: course ?? undefined,
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
timeline: true,
|
||||
};
|
||||
});
|
||||
return mergeTimelineRuns(
|
||||
history ?? [],
|
||||
entries,
|
||||
(entry) => entry.epochMs,
|
||||
centreMs,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The index of the first history entry at or after `renderTime` (the last
|
||||
* entry when none is), by halving: a contact following the clock keeps up to
|
||||
* TIMELINE_FIXES_LIMIT entries, and it is placed on every fleet tick. The
|
||||
* bracketing pair is the entry before it and it.
|
||||
* @param {Array<{time: Cesium.JulianDate}>} history In time order.
|
||||
* @param {Cesium.JulianDate} renderTime
|
||||
* @returns {number}
|
||||
*/
|
||||
export function historyBracketIndex(history, renderTime) {
|
||||
let low = 0;
|
||||
let high = history.length - 1;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (Cesium.JulianDate.lessThan(history[mid].time, renderTime))
|
||||
low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact following the clock is not to be drawn at `renderTime`:
|
||||
* its history is its own fixes around the time (`timeline` entries), and the
|
||||
* time is more than TIMELINE_UNSEEN_MS before the first, when it was not
|
||||
* there yet.
|
||||
* @param {Array<{time: Cesium.JulianDate, timeline?: boolean}>|undefined} history
|
||||
* @param {Cesium.JulianDate} renderTime
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function historyUnseenAt(history, renderTime) {
|
||||
const first = history?.[0];
|
||||
return (
|
||||
first?.timeline === true &&
|
||||
Cesium.JulianDate.secondsDifference(first.time, renderTime) >
|
||||
TIMELINE_UNSEEN_MS / 1000
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift a grounded contact's history onto the floor: its newest fix to
|
||||
* `position`, or, when the history is its own fixes around the time
|
||||
* (`timeline` entries, the newest of them later than the time drawn), every
|
||||
* fix by the lift from `fromM` to `toM`, so it is not drawn rising to it.
|
||||
* @param {object[]|undefined} history
|
||||
* @param {Cesium.Cartesian3} position The newest fix lifted.
|
||||
* @param {number|null} fromM The height it was drawn at.
|
||||
* @param {number} toM The height it is lifted to.
|
||||
*/
|
||||
export function liftGroundedHistory(history, position, fromM, toM) {
|
||||
const newest = history?.[history.length - 1];
|
||||
if (!newest) return;
|
||||
if (history[0].timeline !== true || !Number.isFinite(fromM)) {
|
||||
newest.position = Cesium.Cartesian3.clone(position, newest.position);
|
||||
return;
|
||||
}
|
||||
for (const entry of history) {
|
||||
const carto = Cesium.Cartographic.fromCartesian(entry.position);
|
||||
if (!carto) continue;
|
||||
entry.position = Cesium.Cartesian3.fromRadians(
|
||||
carto.longitude,
|
||||
carto.latitude,
|
||||
carto.height + (toM - fromM),
|
||||
undefined,
|
||||
entry.position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The history entries a tracked contact's trail has yet to take: those after
|
||||
* its newest point (`trail` entries have `timeMs`) up to `untilMs`, the
|
||||
* snapshot's time, so the trail grows as the snapshots bring fixes.
|
||||
* @param {Array<{epochMs: number}>} history
|
||||
* @param {Array<{timeMs: number}>} trail
|
||||
* @param {number} untilMs
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function historyAfterTrail(history, trail, untilMs) {
|
||||
const lastMs = trail.length ? trail[trail.length - 1].timeMs : -Infinity;
|
||||
return history.filter(
|
||||
(entry) => entry.epochMs > lastMs && entry.epochMs <= untilMs,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
historyBracketIndex,
|
||||
historyUnseenAt,
|
||||
liftGroundedHistory,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from './timelineHistory.js';
|
||||
|
||||
const META = { renderAltitudeM: 3_000 };
|
||||
const fix = (atMs, lat, altitudeM = null, lon = 0) => ({
|
||||
atMs,
|
||||
lat,
|
||||
lon,
|
||||
altitudeM,
|
||||
});
|
||||
const julian = (ms) => Cesium.JulianDate.fromDate(new Date(ms));
|
||||
|
||||
test('an aircraft with no fixes merges nothing', () => {
|
||||
assert.equal(
|
||||
mergeAircraftTimelineFixes([], { fixes: null }, META, 100, 0),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("an aircraft's fixes join its history in order, each at the render height moved by its own climb", () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
baroAltitudeM: 1_000,
|
||||
fixes: [fix(120_000, 1, 1_200), fix(60_000, 0, 1_000), fix(180_000, 2)],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
history.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000],
|
||||
);
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
assert.ok(Math.abs(height(history[0]) - 3_000) < 1e-3);
|
||||
assert.ok(Math.abs(height(history[1]) - 3_200) < 1e-3);
|
||||
assert.ok(
|
||||
Math.abs(height(history[2]) - 3_000) < 1e-3,
|
||||
'no altitude: the render height',
|
||||
);
|
||||
// A later snapshot's fixes add to the earlier ones.
|
||||
const more = mergeAircraftTimelineFixes(
|
||||
history,
|
||||
{ baroAltitudeM: 1_000, fixes: [fix(180_000, 2), fix(240_000, 3)] },
|
||||
META,
|
||||
100,
|
||||
180_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
more.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000, 240_000],
|
||||
);
|
||||
});
|
||||
|
||||
test('the bracketing entry is the first at or after the time, else the last', () => {
|
||||
const history = [1_000, 2_000, 3_000].map((ms) => ({
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
}));
|
||||
const at = (ms) =>
|
||||
historyBracketIndex(history, Cesium.JulianDate.fromDate(new Date(ms)));
|
||||
assert.equal(at(500), 0);
|
||||
assert.equal(at(1_000), 0);
|
||||
assert.equal(at(1_500), 1);
|
||||
assert.equal(at(3_000), 2);
|
||||
assert.equal(at(9_000), 2);
|
||||
});
|
||||
|
||||
test('each fix heads where the track goes next, the last where it came from', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
fixes: [
|
||||
fix(0, 0, null, 0),
|
||||
fix(60_000, 0, null, 0.01),
|
||||
fix(120_000, 0.01, null, 0.01),
|
||||
fix(180_000, 0.01, null, 0.01),
|
||||
],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
0,
|
||||
);
|
||||
const tracks = history.map((entry) => entry.track);
|
||||
assert.ok(Math.abs(tracks[0] - 90) < 0.5, 'east');
|
||||
assert.ok(Math.abs(tracks[1]) < 0.5, 'north');
|
||||
assert.equal(tracks[2], undefined, 'no move to read');
|
||||
assert.equal(tracks[3], undefined);
|
||||
assert.ok(history.every((entry) => entry.timeline === true));
|
||||
});
|
||||
|
||||
test('a contact is unseen only well before the first of its own fixes', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(600_000, 0), fix(660_000, 1)] },
|
||||
META,
|
||||
100,
|
||||
600_000,
|
||||
);
|
||||
assert.equal(historyUnseenAt(history, julian(0)), true);
|
||||
assert.equal(historyUnseenAt(history, julian(560_000)), false);
|
||||
const live = [{ time: julian(600_000) }];
|
||||
assert.equal(historyUnseenAt(live, julian(0)), false, 'not on its fixes');
|
||||
assert.equal(historyUnseenAt(undefined, julian(0)), false);
|
||||
});
|
||||
|
||||
test('a grounded contact on its own fixes is lifted whole; else its newest fix', () => {
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 0.001)] },
|
||||
{ renderAltitudeM: 5 },
|
||||
0,
|
||||
0,
|
||||
);
|
||||
const lifted = Cesium.Cartesian3.fromDegrees(0, 0.001, 30);
|
||||
liftGroundedHistory(history, lifted, 5, 30);
|
||||
assert.ok(history.every((entry) => Math.abs(height(entry) - 30) < 1e-3));
|
||||
const live = [
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0, 5) },
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0.001, 5) },
|
||||
];
|
||||
liftGroundedHistory(live, lifted, 5, 30);
|
||||
assert.ok(Math.abs(height(live[0]) - 5) < 1e-3);
|
||||
assert.ok(Math.abs(height(live[1]) - 30) < 1e-3);
|
||||
});
|
||||
|
||||
test("a tracked trail takes the fixes after its newest point, up to the snapshot's time", () => {
|
||||
const history = [0, 60_000, 120_000, 180_000].map((epochMs) => ({ epochMs }));
|
||||
assert.deepEqual(
|
||||
historyAfterTrail(history, [{ timeMs: 60_000 }], 120_000).map(
|
||||
(entry) => entry.epochMs,
|
||||
),
|
||||
[120_000],
|
||||
);
|
||||
assert.equal(historyAfterTrail(history, [], 120_000).length, 3);
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFrameWait } from '../time/frameWait.js';
|
||||
|
||||
const MAX_FRAME_ATTEMPTS = 120;
|
||||
/** Drawn time (ms) to wait for the tracked entity's first position. */
|
||||
const MAX_POSITION_WAIT_MS = 2_000;
|
||||
const MIN_TRACKED_RANGE_M = 150;
|
||||
const ZOOM_INERTIA_STATES = new WeakMap();
|
||||
|
||||
@@ -154,7 +156,7 @@ export function clampTrackedCameraPosition(
|
||||
*/
|
||||
export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
if (!viewer || !entity || !viewFrom) return;
|
||||
let attempts = 0;
|
||||
const positionWait = createFrameWait(MAX_POSITION_WAIT_MS);
|
||||
const trackedTransform = new Cesium.Matrix4();
|
||||
const trackedPosition = new Cesium.Cartesian3();
|
||||
const resolvedViewFrom = new Cesium.Cartesian3();
|
||||
@@ -184,7 +186,6 @@ export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
attempts += framed ? 0 : 1;
|
||||
// Prefer the display cache exposed by the flight layer. Calling the
|
||||
// CallbackProperty from preUpdate can advance dead reckoning again while
|
||||
// Cesium's billboard/label still holds the prior visualizer sample. At a
|
||||
@@ -198,7 +199,7 @@ export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
trackedPosition,
|
||||
);
|
||||
if (!position) {
|
||||
if (attempts >= MAX_FRAME_ATTEMPTS) stop();
|
||||
if (positionWait.tick()) stop();
|
||||
return;
|
||||
}
|
||||
const transform = Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
|
||||
@@ -291,7 +291,7 @@ test('tracking layers write gevLabelModel and expose only their cached display p
|
||||
assert.equal(sources['satellites.js'].includes('_trackedEntity.label.text'), false);
|
||||
});
|
||||
|
||||
test('civilian and military trail heads use the lower-centre model anchor and weak-texture tint', async () => {
|
||||
test('civilian and military trail heads use the lower-centre model anchor', async () => {
|
||||
const files = await Promise.all(['flights.js', 'militaryFlights.js'].map(async (name) => (
|
||||
[name, readLayerSource(new URL(`./${name}`, import.meta.url))]
|
||||
)));
|
||||
@@ -300,7 +300,5 @@ test('civilian and military trail heads use the lower-centre model anchor and we
|
||||
(/const\s*head\s*=\s*(?:parts\.motion\.)?_trackedTrailCached\(\s*,?\s*\)\s*\|\|\s*(?:parts\.motion\.)?_trackedDisplayPosition\(\s*(?:flightState\.)?_trackedIcao,?\s*\);/).test(source),
|
||||
`${name} trail head uses the dedicated lower-centre model anchor`,
|
||||
);
|
||||
assert.ok(source.includes('const MODEL_COLOR_BLEND_AMOUNT = 0.94;'),
|
||||
`${name} keeps diffuse texture contribution weak through code-side MIX`);
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,7 @@
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { registerPickOwner } from './pickRegistry.js';
|
||||
import { createFrameWait } from '../time/frameWait.js';
|
||||
|
||||
// Round 6: trail ENTITIES are pickable (the old Primitive had
|
||||
// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would
|
||||
@@ -58,9 +59,9 @@ const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
const NO_POSITIONS = Object.freeze([]);
|
||||
/** @constant {number} Points per chunk; adjacent chunks share one point. */
|
||||
export const CHUNK_POINTS = 128;
|
||||
/** @constant {number} Visible frames a frozen chunk's stand-in waits for its
|
||||
* static geometry before it is dropped anyway. */
|
||||
const STAND_IN_MAX_FRAMES = 600;
|
||||
/** @constant {number} Drawn time (ms) a frozen chunk's stand-in waits for its
|
||||
* static geometry while the trail is shown before it is dropped anyway. */
|
||||
const STAND_IN_MAX_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Create an always-visible polyline trail bound to a viewer.
|
||||
@@ -80,7 +81,7 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
const depthFailMaterial = baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA);
|
||||
let destroyed = false;
|
||||
let visible = true;
|
||||
/** @type {{positions: Cesium.Cartesian3[], entity: Cesium.Entity, standIn: boolean, frames: number}[]} */
|
||||
/** @type {{positions: Cesium.Cartesian3[], entity: Cesium.Entity, standIn: boolean, wait: {tick: () => boolean, pause: () => void}}[]} */
|
||||
let frozen = [];
|
||||
/** Newest chunk of the newest segment: the only part that changes. */
|
||||
let tail = NO_POSITIONS;
|
||||
@@ -152,9 +153,11 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
function staticReady(chunk) {
|
||||
const display = viewer.dataSourceDisplay;
|
||||
if (typeof display?.getBoundingSphere !== 'function') return true;
|
||||
if (!visible) return false;
|
||||
chunk.frames += 1;
|
||||
if (chunk.frames > STAND_IN_MAX_FRAMES) return true;
|
||||
if (!visible) {
|
||||
chunk.wait.pause();
|
||||
return false;
|
||||
}
|
||||
if (chunk.wait.tick()) return true;
|
||||
try {
|
||||
return (
|
||||
display.getBoundingSphere(chunk.entity, false, scratchSphere) ===
|
||||
@@ -262,7 +265,7 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
positions,
|
||||
entity: addEntity(positions),
|
||||
standIn: true,
|
||||
frames: 0,
|
||||
wait: createFrameWait(STAND_IN_MAX_MS),
|
||||
});
|
||||
i = end;
|
||||
}
|
||||
|
||||
@@ -287,3 +287,38 @@ test('replacing the newest point and removing points inside the trail draws exac
|
||||
for (const run of drawnRuns(viewer))
|
||||
for (let i = 1; i < run.length; i++) assert.equal(next.get(run[i - 1]), run[i]);
|
||||
});
|
||||
|
||||
test('a stand-in is dropped after ten seconds of drawn time, whatever the frame rate', () => {
|
||||
const viewer = fakeViewer();
|
||||
const trail = createTrail(viewer, { color: '#ffffff' });
|
||||
const realNow = performance.now;
|
||||
let clock = 1_000;
|
||||
performance.now = () => clock;
|
||||
try {
|
||||
trail.setPositions(line(CHUNK_POINTS + 5));
|
||||
// 2,000 frames at 240 Hz is about 8.3 s: still waiting for the geometry.
|
||||
for (let i = 0; i < 2_000; i++) {
|
||||
viewer.frame();
|
||||
clock += 1000 / 240;
|
||||
}
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
// Hidden time does not count toward the wait.
|
||||
trail.setVisible(false);
|
||||
clock += 60_000;
|
||||
viewer.frame();
|
||||
trail.setVisible(true);
|
||||
viewer.frame();
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
// A background tab draws nothing: a long gap adds at most one frame step.
|
||||
clock += 60_000;
|
||||
viewer.frame();
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
for (let i = 0; i < 480 && trail._chunksForTest().frozen[0].standIn; i++) {
|
||||
clock += 1000 / 240;
|
||||
viewer.frame();
|
||||
}
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, false);
|
||||
} finally {
|
||||
performance.now = realNow;
|
||||
}
|
||||
});
|
||||
+239
-16
@@ -29,12 +29,21 @@ import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
|
||||
* node:test. No Cesium, no Node built-ins.
|
||||
*/
|
||||
|
||||
/** Transit modes the layer colors. `routeMode` hints refine a feed's default. */
|
||||
/**
|
||||
* Transit modes the layer colors: the GTFS basic route types, by name. A
|
||||
* vehicle's GTFS `route_type` settles its mode when its record carries one;
|
||||
* otherwise `routeMode` hints refine a feed's default.
|
||||
*/
|
||||
export const TRANSIT_MODES = Object.freeze([
|
||||
'bus',
|
||||
'trolleybus',
|
||||
'tram',
|
||||
'cable_tram',
|
||||
'subway',
|
||||
'monorail',
|
||||
'rail',
|
||||
'funicular',
|
||||
'aerial_lift',
|
||||
'ferry',
|
||||
'unknown',
|
||||
]);
|
||||
@@ -42,13 +51,81 @@ export const TRANSIT_MODES = Object.freeze([
|
||||
/** Per-mode icon used in labels and the selection card. */
|
||||
export const TRANSIT_MODE_ICON = Object.freeze({
|
||||
bus: '🚌',
|
||||
trolleybus: '🚎',
|
||||
tram: '🚊',
|
||||
cable_tram: '🚋',
|
||||
subway: '🚇',
|
||||
monorail: '🚝',
|
||||
rail: '🚆',
|
||||
funicular: '🚞',
|
||||
aerial_lift: '🚡',
|
||||
ferry: '⛴️',
|
||||
unknown: '🚏',
|
||||
});
|
||||
|
||||
/** The basic GTFS route types (0–7, 11, 12) by mode. */
|
||||
const BASIC_ROUTE_TYPE_MODES = Object.freeze({
|
||||
0: 'tram',
|
||||
1: 'subway',
|
||||
2: 'rail',
|
||||
3: 'bus',
|
||||
4: 'ferry',
|
||||
5: 'cable_tram',
|
||||
6: 'aerial_lift',
|
||||
7: 'funicular',
|
||||
11: 'trolleybus',
|
||||
12: 'monorail',
|
||||
});
|
||||
|
||||
/**
|
||||
* A GTFS `route_type` as an integer: a basic type (0–12) or an extended one
|
||||
* (100–1799), as a number or its decimal text. Null for anything else.
|
||||
* @param {unknown} value
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function transitRouteType(value) {
|
||||
const n =
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: typeof value === 'string' && /^\d{1,4}$/.test(value.trim())
|
||||
? Number(value.trim())
|
||||
: NaN;
|
||||
return Number.isInteger(n) && n >= 0 && n < 1800 ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode of a GTFS `route_type`: the basic types, and the extended ones
|
||||
* mapped to the basic mode they are a kind of (a coach, 200, is a bus; a
|
||||
* high-speed train, 101, is rail; 405 is a monorail). Air, taxi and other
|
||||
* services, and a value GTFS does not define, are `unknown`.
|
||||
* @param {unknown} routeType
|
||||
* @returns {string} One of TRANSIT_MODES.
|
||||
*/
|
||||
export function transitModeOfRouteType(routeType) {
|
||||
const n = transitRouteType(routeType);
|
||||
if (n === null) return 'unknown';
|
||||
if (n < 100) return BASIC_ROUTE_TYPE_MODES[n] ?? 'unknown';
|
||||
if (n === 405) return 'monorail';
|
||||
const family = Math.floor(n / 100);
|
||||
return (
|
||||
{
|
||||
1: 'rail', // railway
|
||||
2: 'bus', // coach
|
||||
3: 'rail', // suburban railway
|
||||
4: 'subway', // urban railway
|
||||
5: 'subway', // metro
|
||||
6: 'subway', // underground
|
||||
7: 'bus',
|
||||
8: 'trolleybus',
|
||||
9: 'tram',
|
||||
10: 'ferry', // water transport
|
||||
12: 'ferry', // ferry
|
||||
13: 'aerial_lift',
|
||||
14: 'funicular',
|
||||
}[family] ?? 'unknown'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* MBTA route ids are human-readable and mode-typed: rapid-transit lines carry
|
||||
* colour names, commuter rail is prefixed `CR-`, ferries `Boat-`, buses are
|
||||
@@ -443,7 +520,7 @@ const liaRouteLabel = routeIdPattern(/^8-0*(\w.*)$/);
|
||||
function liaRouteMode(routeId) {
|
||||
if (!routeId) return 'unknown';
|
||||
const line = liaRouteLabel(routeId);
|
||||
if (line === 'FUNI') return 'rail';
|
||||
if (line === 'FUNI') return 'funicular';
|
||||
return /^[AB]$/.test(line) ? 'tram' : 'bus';
|
||||
}
|
||||
|
||||
@@ -470,10 +547,14 @@ function astuceRouteLabel(routeId) {
|
||||
return ASTUCE_ROUTES[routeId ?? '']?.label ?? astuceNetworkLabel(routeId);
|
||||
}
|
||||
|
||||
/** PID trolleybus lines: route_type 11 in PID's routes.txt (checked 2026-11-14). */
|
||||
const PID_TROLLEYBUS_LINES = new Set([51, 52, 53, 58, 59, 232, 275]);
|
||||
|
||||
/**
|
||||
* Prague PID route ids are `L` plus a number whose range says what runs it,
|
||||
* per PID's GTFS routes.txt (data.pid.cz, checked 2026-11-09): 1–99 trams
|
||||
* (50–59 trolleybuses, 49 the Petřín funicular `LD`), 100–990 buses (the
|
||||
* trolleybus routes 232 and 275 among them, GTFS route type 11; the
|
||||
* 800s are the X replacement lines, `L803` is X3), 991–993 metro A–C,
|
||||
* 1000s and 1100s the S and R trains (`L1004` is S4, `L1109` R9), the rest
|
||||
* of 1200–1399 other trains, 1700s town buses, 1800s the P ferries, and from
|
||||
@@ -487,7 +568,9 @@ function pidRoute(routeId) {
|
||||
if (!match) return { mode: 'unknown', label: routeId };
|
||||
const n = Number(match[1]);
|
||||
// i18n-ignore: line code, as signed
|
||||
if (n === 49) return { mode: 'rail', label: 'LD' };
|
||||
if (n === 49) return { mode: 'funicular', label: 'LD' };
|
||||
if (PID_TROLLEYBUS_LINES.has(n))
|
||||
return { mode: 'trolleybus', label: String(n) };
|
||||
if (n >= 50 && n <= 59) return { mode: 'bus', label: String(n) };
|
||||
if (n < 100) return { mode: 'tram', label: String(n) };
|
||||
if (n >= 800 && n < 900) return { mode: 'bus', label: `X${n - 800}` };
|
||||
@@ -512,6 +595,102 @@ function pidRouteLabel(routeId) {
|
||||
return pidRoute(routeId).label;
|
||||
}
|
||||
|
||||
/**
|
||||
* A feed's route hint from its static GTFS routes.txt: the route ids of
|
||||
* every mode but `bus`, which is everything else.
|
||||
* @param {Record<string, string[]>} idsByMode
|
||||
* @returns {(routeId: string|null) => string}
|
||||
*/
|
||||
function routeModeTable(idsByMode) {
|
||||
const modes = new Map(
|
||||
Object.entries(idsByMode).flatMap(([mode, ids]) =>
|
||||
ids.map((id) => [id, mode]),
|
||||
),
|
||||
);
|
||||
return (routeId) => (routeId ? (modes.get(routeId) ?? 'bus') : 'unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucharest TPBI by route id, from its routes.txt (checked 2026-11-14): the
|
||||
* trams (route type 0), metro lines M1–M5 (1) and trolleybuses (11); every
|
||||
* other route is a bus. Realtime route ids are the static ones.
|
||||
*/
|
||||
const tpbiRouteMode = routeModeTable({
|
||||
tram: [
|
||||
'54',
|
||||
'55',
|
||||
'57',
|
||||
'61',
|
||||
'63',
|
||||
'65',
|
||||
'66',
|
||||
'67',
|
||||
'68',
|
||||
'69',
|
||||
'70',
|
||||
'814',
|
||||
'915',
|
||||
'1013',
|
||||
],
|
||||
subway: ['968', '969', '970', '971', '999'],
|
||||
trolleybus: [
|
||||
'72',
|
||||
'73',
|
||||
'74',
|
||||
'75',
|
||||
'76',
|
||||
'78',
|
||||
'81',
|
||||
'83',
|
||||
'84',
|
||||
'85',
|
||||
'86',
|
||||
'87',
|
||||
'247',
|
||||
'910',
|
||||
'916',
|
||||
'924',
|
||||
'925',
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Cluj-Napoca CTP by route id, from its routes.txt (checked 2026-11-14): the
|
||||
* trams 100–102L (route type 0) and the trolleybuses (11).
|
||||
*/
|
||||
const ctpClujRouteMode = routeModeTable({
|
||||
tram: ['2', '3', '4', '5'],
|
||||
trolleybus: [
|
||||
'1',
|
||||
'10',
|
||||
'14',
|
||||
'15',
|
||||
'22',
|
||||
'36',
|
||||
'49',
|
||||
'53',
|
||||
'54',
|
||||
'55',
|
||||
'117',
|
||||
'119',
|
||||
'120',
|
||||
'153',
|
||||
'166',
|
||||
'187',
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Turin GTT by route id, from its routes.txt (checked 2026-11-14): the trams
|
||||
* (route type 0), metro M1, and the Sassi–Superga rack tramway `79U`, which
|
||||
* the file types as a funicular (7).
|
||||
*/
|
||||
const gttRouteMode = routeModeTable({
|
||||
tram: ['3U', '4U', '7U', '9U', '10U', '13U', '15U', '16CDU', '16CSU'],
|
||||
subway: ['METROU'],
|
||||
funicular: ['79U'],
|
||||
});
|
||||
|
||||
/**
|
||||
* Bordeaux TBM tram and boat lines by route id, from TBM's static GTFS
|
||||
* routes.txt (checked 2026-11-09): the trams are numbered ids, not letters.
|
||||
@@ -571,6 +750,7 @@ function transitFeed(fields) {
|
||||
* url: string, headers?: Record<string, string>,
|
||||
* license: string, licenseUrl: string, attribution: string,
|
||||
* defaultMode: string, routeMode?: (routeId: string|null) => string,
|
||||
* routeCorrections?: Readonly<Record<string, string>>,
|
||||
* speedUnit?: 'km/h', refreshMs?: number, sourceUrl?: string,
|
||||
* creditDated?: boolean,
|
||||
* }>>}
|
||||
@@ -579,6 +759,9 @@ function transitFeed(fields) {
|
||||
* stretches the proxy's cache for an upstream that rate-limits below one
|
||||
* request per 15 s TTL. `sourceUrl` and `creditDated` add a link and a date
|
||||
* to the credit for licences that ask for them (`transitFeedCredit`).
|
||||
* `routeCorrections` names the routes whose `route_type` the operator's own
|
||||
* routes.txt gets wrong, `route_id` to the mode they really are; a correction
|
||||
* outranks the route type, which would otherwise outrank the route hint.
|
||||
*/
|
||||
export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
Object.freeze({
|
||||
@@ -1264,6 +1447,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Keyless public endpoint from the metropolitan transport authority; no licence found. Same basis as Metro Transit and OVapi.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: tpbiRouteMode,
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'roma-mobilita',
|
||||
@@ -1296,6 +1480,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Official keyless endpoint; no licence found. Same basis as Metro Transit and OVapi. Route ids append `U` for urban lines.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: gttRouteMode,
|
||||
routeLabel: gttRouteLabel,
|
||||
}),
|
||||
transitFeed({
|
||||
@@ -1401,6 +1586,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: ctpClujRouteMode,
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'ctp-iasi',
|
||||
@@ -1567,6 +1753,8 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
defaultMode: 'bus',
|
||||
routeLabel: liaRouteLabel,
|
||||
routeMode: liaRouteMode,
|
||||
// LiA's routes.txt types the funicular (`8-FUNI`) as a bus (3).
|
||||
routeCorrections: Object.freeze({ '8-FUNI': 'funicular' }),
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'filbleu-tours',
|
||||
@@ -1664,54 +1852,89 @@ export function transitFeedsInRange(lat, lon, slackKm = 0) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The feed's own hint for a vehicle: its fleet number when the feed maps
|
||||
* those (`vehicleMode`), else its route (`routeMode`). Null when neither knows.
|
||||
* What settles a vehicle's mode, most specific first: the feed's fleet hint
|
||||
* (`vehicleMode`, which knows a bus standing in on a tram route), else the
|
||||
* feed's correction for a route its routes.txt mistypes (`routeCorrections`),
|
||||
* else the GTFS `route_type` of its route when the record carries one, else
|
||||
* the feed's route hint (`routeMode`). Null when none of them knows.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId
|
||||
* @param {string|null} vehicleId
|
||||
* @param {unknown} routeType GTFS `route_type`, when the record has one.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function hintedMode(feed, routeId, vehicleId) {
|
||||
function hintedMode(feed, routeId, vehicleId, routeType) {
|
||||
const byVehicle =
|
||||
typeof feed?.vehicleMode === 'function'
|
||||
? feed.vehicleMode(vehicleId)
|
||||
: null;
|
||||
if (byVehicle && byVehicle !== 'unknown') return byVehicle;
|
||||
const corrections = feed?.routeCorrections;
|
||||
if (routeId && corrections && Object.hasOwn(corrections, routeId))
|
||||
return corrections[routeId];
|
||||
const byType = transitModeOfRouteType(routeType);
|
||||
if (byType !== 'unknown') return byType;
|
||||
return typeof feed?.routeMode === 'function' ? feed.routeMode(routeId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode for a vehicle: the feed's fleet or route hint when it has one, else
|
||||
* its default.
|
||||
* Mode for a vehicle: its fleet hint, route type or route hint when one
|
||||
* knows ({@link hintedMode}), else its feed's default.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId GTFS route_id from the vehicle's trip.
|
||||
* @param {string|null} [vehicleId] GTFS-RT vehicle id.
|
||||
* @param {unknown} [routeType] GTFS `route_type` of the route, when known.
|
||||
* @returns {string} One of TRANSIT_MODES.
|
||||
*/
|
||||
export function transitModeFor(feed, routeId, vehicleId = null) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId);
|
||||
export function transitModeFor(
|
||||
feed,
|
||||
routeId,
|
||||
vehicleId = null,
|
||||
routeType = null,
|
||||
) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId, routeType);
|
||||
const mode =
|
||||
hinted && hinted !== 'unknown' ? hinted : feed?.defaultMode || 'unknown';
|
||||
return TRANSIT_MODES.includes(mode) ? mode : 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the mode came from the route id rather than the feed's default. A
|
||||
* default is a guess about a fleet — TransLink's is "bus" while it publishes
|
||||
* rail in the same feed — so a consumer judging physical plausibility must
|
||||
* not hold a defaulted vehicle to a bus's limits.
|
||||
* Whether the mode came from the vehicle, its route type or its route id
|
||||
* rather than the feed's default. A default is a guess about a fleet —
|
||||
* TransLink's is "bus" while it publishes rail in the same feed — so a
|
||||
* consumer judging physical plausibility must not hold a defaulted vehicle
|
||||
* to a bus's limits.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId
|
||||
* @param {string|null} [vehicleId]
|
||||
* @param {unknown} [routeType]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function transitModeResolved(feed, routeId, vehicleId = null) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId);
|
||||
export function transitModeResolved(
|
||||
feed,
|
||||
routeId,
|
||||
vehicleId = null,
|
||||
routeType = null,
|
||||
) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId, routeType);
|
||||
return (
|
||||
Boolean(hinted) && hinted !== 'unknown' && TRANSIT_MODES.includes(hinted)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The route type a vehicle's model is chosen by: its record's, when that type
|
||||
* is a kind of the mode it was given. A fleet hint can overrule the route (a
|
||||
* bus on a tram route), and then the route's type does not describe it.
|
||||
* @param {string} mode The vehicle's mode ({@link transitModeFor}).
|
||||
* @param {unknown} routeType
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function transitModelRouteType(mode, routeType) {
|
||||
const n = transitRouteType(routeType);
|
||||
return n !== null && transitModeOfRouteType(n) === mode ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The route as a rider would say it. Most feeds publish that already, so this
|
||||
* is identity for them; a feed that publishes internal keys supplies its own
|
||||
|
||||
@@ -11,9 +11,13 @@ import {
|
||||
haversineKm,
|
||||
publicTransitCatalog,
|
||||
transitFeedsInRange,
|
||||
TRANSIT_MODE_ICON,
|
||||
transitModeFor,
|
||||
transitModeOfRouteType,
|
||||
transitModeResolved,
|
||||
transitModelRouteType,
|
||||
transitRouteLabel,
|
||||
transitRouteType,
|
||||
} from './transitFeeds.js';
|
||||
import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
|
||||
|
||||
@@ -729,8 +733,10 @@ test('Prague route-id ranges give metro, trains, ferries and trolleybuses their
|
||||
transitRouteLabel(feed, routeId),
|
||||
];
|
||||
assert.deepEqual(read('L22'), ['tram', '22']);
|
||||
assert.deepEqual(read('L58'), ['bus', '58'], 'trolleybus');
|
||||
assert.deepEqual(read('L49'), ['rail', 'LD'], 'Petřín funicular');
|
||||
assert.deepEqual(read('L58'), ['trolleybus', '58']);
|
||||
assert.deepEqual(read('L55'), ['bus', '55'], 'not a PID trolleybus line');
|
||||
assert.deepEqual(read('L275'), ['trolleybus', '275'], 'route type 11');
|
||||
assert.deepEqual(read('L49'), ['funicular', 'LD'], 'Petřín funicular');
|
||||
assert.deepEqual(read('L135'), ['bus', '135']);
|
||||
assert.deepEqual(read('L803'), ['bus', 'X3']);
|
||||
assert.deepEqual(read('L991'), ['subway', 'A']);
|
||||
@@ -767,7 +773,7 @@ test('Rouen Métro and Calypso are not buses; Le Havre reads its own ids', () =>
|
||||
assert.equal(transitModeFor(feed, 'TCAR:93'), 'bus');
|
||||
assert.equal(transitRouteLabel(feed, 'TAE:F'), 'F');
|
||||
const lia = getTransitFeed('lia-le-havre');
|
||||
assert.equal(transitModeFor(lia, '8-FUNI'), 'rail');
|
||||
assert.equal(transitModeFor(lia, '8-FUNI'), 'funicular');
|
||||
assert.equal(transitRouteLabel(lia, '8-C3'), 'C3');
|
||||
assert.equal(transitRouteLabel(lia, '8-09'), '9');
|
||||
assert.equal(transitRouteLabel(lia, '8-A'), 'A');
|
||||
@@ -778,3 +784,114 @@ test('data.gov.my feeds ask the proxy for no more than its 4 a minute', () => {
|
||||
assert.ok(getTransitFeed(id).refreshMs >= 30_000, id);
|
||||
}
|
||||
});
|
||||
|
||||
test('a GTFS route type names its mode, basic and extended alike', () => {
|
||||
for (const [routeType, mode] of [
|
||||
[0, 'tram'],
|
||||
[1, 'subway'],
|
||||
[2, 'rail'],
|
||||
[3, 'bus'],
|
||||
[4, 'ferry'],
|
||||
[5, 'cable_tram'],
|
||||
[6, 'aerial_lift'],
|
||||
[7, 'funicular'],
|
||||
[11, 'trolleybus'],
|
||||
[12, 'monorail'],
|
||||
[101, 'rail'],
|
||||
[106, 'rail'],
|
||||
[200, 'bus'],
|
||||
[300, 'rail'],
|
||||
[401, 'subway'],
|
||||
[405, 'monorail'],
|
||||
[702, 'bus'],
|
||||
[800, 'trolleybus'],
|
||||
[900, 'tram'],
|
||||
[1000, 'ferry'],
|
||||
[1200, 'ferry'],
|
||||
[1300, 'aerial_lift'],
|
||||
[1400, 'funicular'],
|
||||
['11', 'trolleybus'],
|
||||
])
|
||||
assert.equal(transitModeOfRouteType(routeType), mode, String(routeType));
|
||||
// Air, taxi and other services, and values GTFS does not define.
|
||||
for (const other of [8, 1100, 1500, 1700, 1800, -1, 2.5, '', 'tram', null])
|
||||
assert.equal(transitModeOfRouteType(other), 'unknown', String(other));
|
||||
assert.equal(transitRouteType(' 200 '), 200);
|
||||
assert.equal(transitRouteType('2e2'), null);
|
||||
});
|
||||
|
||||
test('every mode has an icon, and every mode a route type names is a mode', () => {
|
||||
for (const mode of TRANSIT_MODES) assert.ok(TRANSIT_MODE_ICON[mode], mode);
|
||||
for (let routeType = 0; routeType < 1800; routeType++)
|
||||
assert.ok(TRANSIT_MODES.includes(transitModeOfRouteType(routeType)));
|
||||
});
|
||||
|
||||
test('a route type settles the mode before a route hint or the default', () => {
|
||||
const mbta = getTransitFeed('mbta');
|
||||
// The hint calls every numbered MBTA route a bus; a route type is finer.
|
||||
assert.equal(transitModeFor(mbta, '71'), 'bus');
|
||||
assert.equal(transitModeFor(mbta, '71', 'y1', 11), 'trolleybus');
|
||||
assert.equal(transitModeResolved(mbta, '71', 'y1', 11), true);
|
||||
// A default-only feed is resolved by a route type alone.
|
||||
const durham = getTransitFeed('durham-region');
|
||||
assert.equal(transitModeResolved(durham, '915', 'b1'), false);
|
||||
assert.equal(transitModeFor(durham, '915', 'b1', 200), 'bus');
|
||||
assert.equal(transitModeResolved(durham, '915', 'b1', 200), true);
|
||||
// A type that names no mode leaves the hints in charge.
|
||||
assert.equal(transitModeFor(mbta, 'Red', null, 1700), 'subway');
|
||||
assert.equal(transitModeFor(mbta, 'Red', null, 'x'), 'subway');
|
||||
});
|
||||
|
||||
test('a fleet hint outranks the route type, and then the type picks no model', () => {
|
||||
const ttc = getTransitFeed('ttc-toronto');
|
||||
// A bus standing in on the 501 streetcar route (route type 0).
|
||||
const mode = transitModeFor(ttc, '501', '8400', 0);
|
||||
assert.equal(mode, 'bus');
|
||||
assert.equal(transitModelRouteType(mode, 0), null);
|
||||
assert.equal(transitModelRouteType('tram', 0), 0);
|
||||
assert.equal(transitModelRouteType('bus', 200), 200, 'a coach is a bus');
|
||||
assert.equal(transitModelRouteType('bus', null), null);
|
||||
});
|
||||
|
||||
test('a route correction outranks a mistyped route type, and only for its route', () => {
|
||||
const lia = getTransitFeed('lia-le-havre');
|
||||
// LiA's routes.txt types the funicular as a bus (3).
|
||||
assert.equal(transitModeFor(lia, '8-FUNI', null, 3), 'funicular');
|
||||
assert.equal(transitModeResolved(lia, '8-FUNI', null, 3), true);
|
||||
// A correction is a mode, so the bus type picks no model for it.
|
||||
assert.equal(transitModelRouteType('funicular', 3), null);
|
||||
// Every other route still takes its route type.
|
||||
assert.equal(transitModeFor(lia, '8-A', null, 0), 'tram');
|
||||
assert.equal(transitModeFor(lia, '8-C3', null, 3), 'bus');
|
||||
assert.equal(transitModeFor(lia, null, null, 3), 'bus');
|
||||
// Corrections are narrow: a few named routes, each to a known mode.
|
||||
for (const feed of TRANSIT_FEED_REGISTRY) {
|
||||
if (!feed.routeCorrections) continue;
|
||||
assert.ok(Object.isFrozen(feed.routeCorrections), feed.id);
|
||||
for (const [route, mode] of Object.entries(feed.routeCorrections)) {
|
||||
assert.ok(TRANSIT_MODES.includes(mode), `${feed.id} ${route}`);
|
||||
assert.notEqual(mode, 'unknown', `${feed.id} ${route}`);
|
||||
}
|
||||
}
|
||||
// An inherited key is not a correction.
|
||||
assert.equal(transitModeFor(lia, 'toString', null, 3), 'bus');
|
||||
});
|
||||
|
||||
// Route ids as each realtime feed and its operator's routes.txt carried them
|
||||
// on 2026-11-14.
|
||||
test('Bucharest, Cluj and Turin route ids give trams, trolleybuses and a funicular', () => {
|
||||
const mode = (id, routeId) => transitModeFor(getTransitFeed(id), routeId);
|
||||
assert.equal(mode('tpbi-bucuresti', '85'), 'trolleybus', 'line 74');
|
||||
assert.equal(mode('tpbi-bucuresti', '1013'), 'tram', 'line 4');
|
||||
assert.equal(mode('tpbi-bucuresti', '968'), 'subway', 'M1');
|
||||
assert.equal(mode('tpbi-bucuresti', '828'), 'bus');
|
||||
assert.equal(mode('tpbi-bucuresti', 'PV1_407'), 'bus');
|
||||
assert.equal(mode('ctp-cluj', '1'), 'trolleybus');
|
||||
assert.equal(mode('ctp-cluj', '2'), 'tram', 'line 100');
|
||||
assert.equal(mode('ctp-cluj', '6'), 'bus', 'line 19');
|
||||
assert.equal(mode('gtt-torino', '79U'), 'funicular', 'Sassi–Superga');
|
||||
assert.equal(mode('gtt-torino', '16CDU'), 'tram');
|
||||
assert.equal(mode('gtt-torino', 'METROU'), 'subway');
|
||||
assert.equal(mode('gtt-torino', '6U'), 'bus');
|
||||
assert.equal(mode('gtt-torino', null), 'bus', 'no route: the default');
|
||||
});
|
||||
@@ -21,7 +21,9 @@ import {
|
||||
* at the ~18 px the fleet renders at, by shape and not only by colour: a bus is
|
||||
* short and blunt, a tram is long and slender with articulation joints, a metro
|
||||
* car is squared off, a mainline train has a tapered nose, and a ferry is a
|
||||
* hull with a bow.
|
||||
* hull with a bow. A trolleybus trails its two poles, a cable car is a short
|
||||
* single car, a monorail the slimmest bullet, a funicular hangs off its rope,
|
||||
* and a gondola is a cabin on its cable.
|
||||
*
|
||||
* Interior detail is drawn with the same dark hairline as the edge — windscreen
|
||||
* lines, articulation joints, a deck line — because a solid dark panel would
|
||||
@@ -103,6 +105,49 @@ const HEADING_BODIES = {
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-7.5,-6 L7.5,-6 L7.5,20 L-7.5,20 Z" ${DETAIL}/>`,
|
||||
|
||||
// ── Trolleybus: a bus a little narrower, trailing the two trolley poles
|
||||
// that reach back to its wires. Body and poles are one outline, so no
|
||||
// edge is drawn across the body.
|
||||
trolleybus: `
|
||||
<path d="M0,-41 L15,-26 L15,25 C15,28.5 13,30 9,30 L7.5,30 L7.5,42 L4,42
|
||||
L4,30 L-4,30 L-4,42 L-7.5,42 L-7.5,30 L-9,30 C-13,30 -15,28.5 -15,25
|
||||
L-15,-26 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-10,-21 L10,-21" ${DETAIL}/>`,
|
||||
|
||||
// ── Cable car (street cable railway): a short single car, under half a
|
||||
// tram, with open platforms at both ends.
|
||||
cable_tram: `
|
||||
<path d="M0,-30 L11,-21 L11,26 C11,28 9,29 0,29 C-9,29 -11,28 -11,26
|
||||
L-11,-21 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-12 L11,-12" ${DETAIL}/>
|
||||
<path d="M-11,18 L11,18" ${DETAIL}/>`,
|
||||
|
||||
// ── Monorail: the slimmest train in the set, a rounded bullet nose over
|
||||
// its beam.
|
||||
monorail: `
|
||||
<path d="M0,-45 C3,-45 8.5,-36 8.5,-22 L8.5,42 L-8.5,42 L-8.5,-22
|
||||
C-8.5,-36 -3,-45 0,-45 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M0,-18 L0,38" ${DETAIL}/>`,
|
||||
|
||||
// ── Funicular: a squat car hauled by the rope at its upper end.
|
||||
funicular: `
|
||||
<path d="M-6,-30 L6,-30 L11,-24 L11,36 L-11,36 L-11,-24 Z
|
||||
M-1.75,-46 L1.75,-46 L1.75,-30 L-1.75,-30 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-8 L11,-8" ${DETAIL}/>
|
||||
<path d="M-11,14 L11,14" ${DETAIL}/>`,
|
||||
|
||||
// ── Gondola (aerial lift): a cabin hung on the cable that runs through
|
||||
// it; the cabin's nose is its front.
|
||||
aerial_lift: `
|
||||
<path d="M0,-18 L12,-7 L12,14 C12,16 10,17 0,17 C-10,17 -12,16 -12,14
|
||||
L-12,-7 Z
|
||||
M-2.5,-40 L2.5,-40 L2.5,46 L-2.5,46 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
// ── Unknown: a plain marker with a nose and nothing else, so an
|
||||
// unclassified vehicle never pretends to be a mode it is not.
|
||||
unknown: `
|
||||
@@ -146,6 +191,40 @@ const NEUTRAL_BODIES = {
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-7.5,-13 L7.5,-13 L7.5,13 L-7.5,13 Z" ${DETAIL}/>`,
|
||||
|
||||
trolleybus: `
|
||||
<path d="M-15,-26 C-15,-30 -13,-32 -9,-32 L-7.5,-32 L-7.5,-42 L-4,-42
|
||||
L-4,-32 L4,-32 L4,-42 L7.5,-42 L7.5,-32 L9,-32 C13,-32 15,-30 15,-26
|
||||
L15,26 C15,30 13,32 9,32 L7.5,32 L7.5,42 L4,42 L4,32 L-4,32 L-4,42
|
||||
L-7.5,42 L-7.5,32 L-9,32 C-13,32 -15,30 -15,26 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
cable_tram: `
|
||||
<path d="M-11,-25 C-11,-27 -9,-28 0,-28 C9,-28 11,-27 11,-25
|
||||
L11,25 C11,27 9,28 0,28 C-9,28 -11,27 -11,25 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-17 L11,-17" ${DETAIL}/>
|
||||
<path d="M-11,17 L11,17" ${DETAIL}/>`,
|
||||
|
||||
monorail: `
|
||||
<path d="M0,-44 C5,-44 8.5,-38 8.5,-28 L8.5,28 C8.5,38 5,44 0,44
|
||||
C-5,44 -8.5,38 -8.5,28 L-8.5,-28 C-8.5,-38 -5,-44 0,-44 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M0,-24 L0,24" ${DETAIL}/>`,
|
||||
|
||||
funicular: `
|
||||
<path d="M-11,-30 L11,-30 L11,30 L-11,30 Z
|
||||
M-1.75,-46 L1.75,-46 L1.75,-30 L-1.75,-30 Z
|
||||
M-1.75,30 L1.75,30 L1.75,46 L-1.75,46 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-10 L11,-10" ${DETAIL}/>
|
||||
<path d="M-11,10 L11,10" ${DETAIL}/>`,
|
||||
|
||||
aerial_lift: `
|
||||
<path d="M-12,-14 C-12,-16 -10,-17 0,-17 C10,-17 12,-16 12,-14
|
||||
L12,14 C12,16 10,17 0,17 C-10,17 -12,16 -12,14 Z
|
||||
M-2.5,-46 L2.5,-46 L2.5,46 L-2.5,46 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
unknown: `
|
||||
<path d="M-10,-26 C-10,-30 -7,-32 0,-32 C7,-32 10,-30 10,-26
|
||||
L10,26 C10,30 7,32 0,32 C-7,32 -10,30 -10,26 Z"
|
||||
|
||||
@@ -62,7 +62,7 @@ test('the raster cache is bounded by kind, size and halo — never by call count
|
||||
assert.ok(transitIconCacheSize() <= before + 3 + TRANSIT_ICON_KINDS.length);
|
||||
});
|
||||
|
||||
test('all 72 variants retain the specified final halo at both display sizes', async () => {
|
||||
test('every variant retains the specified final halo at both display sizes', async () => {
|
||||
const { presetSpriteScale, presetSpriteOutlinePx } =
|
||||
await import('./transitPresetStyle.js');
|
||||
for (const kind of TRANSIT_ICON_KINDS) {
|
||||
@@ -97,7 +97,8 @@ test('all 72 variants retain the specified final halo at both display sizes', as
|
||||
}
|
||||
for (let i = 0; i < 100; i++)
|
||||
transitIcon('invalid', i, { haloScreenPx: i, screenPx: i });
|
||||
assert.equal(transitIconCacheSize(), 72);
|
||||
// Every kind at two sizes, three profiles, with and without a course.
|
||||
assert.equal(transitIconCacheSize(), TRANSIT_ICON_KINDS.length * 12);
|
||||
});
|
||||
|
||||
test('every mono raster preserves the normal silhouette mask and aspect at CRT display size', async () => {
|
||||
@@ -197,6 +198,11 @@ test('sensor raster halo stays dark across its screen-space band on a white roof
|
||||
subway: 11.5,
|
||||
rail: 10.5,
|
||||
ferry: 12.5,
|
||||
trolleybus: 15,
|
||||
cable_tram: 11,
|
||||
monorail: 8.5,
|
||||
funicular: 11,
|
||||
aerial_lift: 12,
|
||||
unknown: 10,
|
||||
};
|
||||
for (const selected of [false, true]) {
|
||||
|
||||
@@ -60,9 +60,14 @@ const SPRITE_STYLE = Object.freeze({
|
||||
outlinePx: 1.25,
|
||||
rgbaByMode: Object.freeze({
|
||||
bus: Object.freeze([0, 255, 102, 1]),
|
||||
trolleybus: Object.freeze([170, 255, 0, 1]),
|
||||
tram: Object.freeze([255, 179, 0, 1]),
|
||||
cable_tram: Object.freeze([255, 120, 0, 1]),
|
||||
subway: Object.freeze([255, 59, 48, 1]),
|
||||
monorail: Object.freeze([255, 64, 170, 1]),
|
||||
rail: Object.freeze([215, 139, 255, 1]),
|
||||
funicular: Object.freeze([255, 214, 140, 1]),
|
||||
aerial_lift: Object.freeze([90, 140, 255, 1]),
|
||||
ferry: Object.freeze([58, 208, 255, 1]),
|
||||
unknown: Object.freeze([255, 255, 255, 1]),
|
||||
}),
|
||||
@@ -72,9 +77,14 @@ const SPRITE_STYLE = Object.freeze({
|
||||
/** Modes with a bracket tier of their own. */
|
||||
const TIER_MODES = Object.freeze([
|
||||
'bus',
|
||||
'trolleybus',
|
||||
'tram',
|
||||
'cable_tram',
|
||||
'subway',
|
||||
'monorail',
|
||||
'rail',
|
||||
'funicular',
|
||||
'aerial_lift',
|
||||
'ferry',
|
||||
'unknown',
|
||||
]);
|
||||
@@ -128,7 +138,7 @@ export function presetSpriteOutlinePx(styleName, selected = false) {
|
||||
|
||||
/**
|
||||
* Detection-overlay tier key for a transit mode. Every theme's `tiers`
|
||||
* table carries these six, so the bracket colour is per mode in every
|
||||
* table carries one per mode, so the bracket colour is per mode in every
|
||||
* preset. Unlike traffic, transit sets its tier keyless as well: the feeds
|
||||
* are keyless, and there is no separate keyless experience to keep
|
||||
* byte-identical.
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
decodeVehiclePositions,
|
||||
} from './gtfsRealtime.js';
|
||||
import { getTransitFeed } from './transitFeeds.js';
|
||||
export { transitModeFor, transitRouteType } from './transitFeeds.js';
|
||||
|
||||
/** Fresh window: a snapshot younger than this is served without refetching. */
|
||||
export const TRANSIT_PROXY_TTL_MS = 15_000;
|
||||
|
||||
@@ -46,6 +46,15 @@ const TYPE_STYLES = [
|
||||
];
|
||||
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
|
||||
|
||||
/**
|
||||
* An aid to navigation's disc and card accent: a bone white apart from every
|
||||
* ship type's colour.
|
||||
*/
|
||||
export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
css: '#d9d2c0',
|
||||
accent: '217, 210, 192',
|
||||
});
|
||||
|
||||
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
|
||||
// and tests match on them.
|
||||
const TYPE_DISPLAY_KEYS = Object.freeze({
|
||||
|
||||
@@ -45,3 +45,110 @@ export function normalizeVesselType(type) {
|
||||
if (NUMERIC_TYPE_SPECIALS[code]) return NUMERIC_TYPE_SPECIALS[code];
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
|
||||
/**
|
||||
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
|
||||
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
|
||||
* floating marks by their cardinal quadrant, lateral side, safe water,
|
||||
* isolated danger or special mark, and the lights, RACONs and reference
|
||||
* points around them. Code 0 names no kind.
|
||||
*/
|
||||
const AID_TYPE_NAMES = Object.freeze([
|
||||
'Navigation aid',
|
||||
'Reference point',
|
||||
'RACON',
|
||||
'Fixed structure off shore',
|
||||
'Emergency wreck marking buoy',
|
||||
'Light, without sectors',
|
||||
'Light, with sectors',
|
||||
'Leading light front',
|
||||
'Leading light rear',
|
||||
'Beacon, Cardinal N',
|
||||
'Beacon, Cardinal E',
|
||||
'Beacon, Cardinal S',
|
||||
'Beacon, Cardinal W',
|
||||
'Beacon, Port hand',
|
||||
'Beacon, Starboard hand',
|
||||
'Beacon, Preferred channel port hand',
|
||||
'Beacon, Preferred channel starboard hand',
|
||||
'Beacon, Isolated danger',
|
||||
'Beacon, Safe water',
|
||||
'Beacon, Special mark',
|
||||
'Cardinal Mark N',
|
||||
'Cardinal Mark E',
|
||||
'Cardinal Mark S',
|
||||
'Cardinal Mark W',
|
||||
'Port hand Mark',
|
||||
'Starboard hand Mark',
|
||||
'Preferred Channel Port hand',
|
||||
'Preferred Channel Starboard hand',
|
||||
'Isolated danger',
|
||||
'Safe Water',
|
||||
'Special Mark',
|
||||
'Light Vessel / LANBY / Rigs',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The kind an AIS aid-to-navigation type code names ("19" → "Beacon, Special
|
||||
* mark"); "Navigation aid" for code 0 and for a code outside 0 to 31.
|
||||
* @param {string|number|null|undefined} code
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aidToNavigationTypeName(code) {
|
||||
const text = String(code ?? '').trim();
|
||||
const index = /^\d+$/.test(text) ? Number(text) : -1;
|
||||
return AID_TYPE_NAMES[index] ?? AID_TYPE_NAMES[0];
|
||||
}
|
||||
|
||||
/** Every kind {@link aidToNavigationTypeName} names, lowercased. */
|
||||
const AID_TYPE_NAME_SET = new Set(
|
||||
AID_TYPE_NAMES.map((name) => name.toLowerCase()),
|
||||
);
|
||||
|
||||
/**
|
||||
* Words a vessel type uses for an aid to navigation. A vessel that works on
|
||||
* one ("Buoy Tender", "Buoy-Laying Vessel", "Buoy Layer") is a ship underway,
|
||||
* not a mark on the water.
|
||||
*/
|
||||
const AID_TYPE_TEXT =
|
||||
/navaid|\baton\b|aids? to nav|nav(igation)? aid|racon|lighthouse|lightship|light vessel|reference point|hand mark|cardinal|safe water|preferred channel|isolated danger|special mark|beacon|buoy/i;
|
||||
const AID_WORKER_TEXT = /tender|lay(ing|er)\b/i;
|
||||
|
||||
/** ITU MID 99: the MMSI of an AIS aid-to-navigation station (99MIDxxxx). */
|
||||
const AID_MMSI = /^99\d{7}$/;
|
||||
|
||||
/**
|
||||
* Whether each type text seen names an aid. Vessel layers ask per vessel on
|
||||
* their draw passes, and a feed uses few distinct type texts, so each is
|
||||
* matched once; the memo is bounded against a feed of free-form types.
|
||||
*/
|
||||
const AID_TYPE_MEMO = new Map();
|
||||
const AID_TYPE_MEMO_MAX = 1024;
|
||||
|
||||
function typeNamesAid(text) {
|
||||
let aid = AID_TYPE_MEMO.get(text);
|
||||
if (aid !== undefined) return aid;
|
||||
aid =
|
||||
AID_TYPE_NAME_SET.has(text.toLowerCase()) ||
|
||||
(AID_TYPE_TEXT.test(text) && !AID_WORKER_TEXT.test(text));
|
||||
if (AID_TYPE_MEMO.size >= AID_TYPE_MEMO_MAX) AID_TYPE_MEMO.clear();
|
||||
AID_TYPE_MEMO.set(text, aid);
|
||||
return aid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a vessel record is an aid to navigation (a buoy, beacon, mark,
|
||||
* RACON or light) rather than a vessel: its type is one of the kinds an aid
|
||||
* report names or uses a word for one, or its MMSI is an aid-to-navigation
|
||||
* station's, or it is a virtual aid. A numeric AIS ship type never names one.
|
||||
* @param {{type?: string|number|null, mmsi?: string|number|null,
|
||||
* virtual?: boolean}} vessel
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isAidToNavigation({ type, mmsi, virtual } = {}) {
|
||||
if (virtual === true) return true;
|
||||
const text = typeof type === 'string' ? type.trim() : String(type ?? '');
|
||||
if (text && typeNamesAid(text)) return true;
|
||||
if (mmsi === null || mmsi === undefined || mmsi === '') return false;
|
||||
return AID_MMSI.test(typeof mmsi === 'string' ? mmsi.trim() : String(mmsi));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aidToNavigationTypeName, isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
test('an aid-to-navigation type code names its kind of aid', () => {
|
||||
assert.equal(aidToNavigationTypeName(20), 'Cardinal Mark N');
|
||||
assert.equal(aidToNavigationTypeName('13'), 'Beacon, Port hand');
|
||||
assert.equal(aidToNavigationTypeName(2), 'RACON');
|
||||
assert.equal(aidToNavigationTypeName(29), 'Safe Water');
|
||||
assert.equal(aidToNavigationTypeName(31), 'Light Vessel / LANBY / Rigs');
|
||||
// Code 0, a code past 31 and no code name no kind.
|
||||
for (const code of [0, 32, -1, '', null, undefined, 'x'])
|
||||
assert.equal(aidToNavigationTypeName(code), 'Navigation aid', code);
|
||||
});
|
||||
|
||||
test('aids to navigation are known by their type, else their MMSI', () => {
|
||||
for (const type of [
|
||||
'Beacon, Special Mark',
|
||||
'Cardinal Mark N',
|
||||
'Port Hand Mark',
|
||||
'Starboard Hand Mark',
|
||||
'Safe Water',
|
||||
'Isolated danger',
|
||||
'Preferred Channel Port hand',
|
||||
'RACON',
|
||||
'Light Vessel / LANBY / Rigs',
|
||||
'Reference point',
|
||||
'Navigation aid',
|
||||
'AtoN',
|
||||
'Lighthouse',
|
||||
'Buoy',
|
||||
// Every kind an aid report names is an aid, whatever its MMSI.
|
||||
'Light, with sectors',
|
||||
'Leading light rear',
|
||||
'Fixed structure off shore',
|
||||
'Emergency wreck marking buoy',
|
||||
])
|
||||
assert.equal(isAidToNavigation({ type, mmsi: '' }), true, type);
|
||||
// A virtual aid is an aid whatever its type or MMSI.
|
||||
assert.equal(
|
||||
isAidToNavigation({ type: '', mmsi: '', virtual: true }),
|
||||
true,
|
||||
);
|
||||
// AIS aid-to-navigation stations are numbered 99MIDxxxx.
|
||||
assert.equal(isAidToNavigation({ type: '', mmsi: '993672001' }), true);
|
||||
assert.equal(isAidToNavigation({ type: '0', mmsi: ' 992351234 ' }), true);
|
||||
for (const vessel of [
|
||||
{ type: 'Buoy Tender', mmsi: '366999001' },
|
||||
{ type: 'Buoy-Laying Vessel', mmsi: '' },
|
||||
{ type: 'Buoy Layer', mmsi: '' },
|
||||
{ type: 'Lighter', mmsi: '' },
|
||||
{ type: 'Flight deck', mmsi: '' },
|
||||
{ type: 70, mmsi: 366999002 },
|
||||
{ type: '70', mmsi: '366999002' },
|
||||
{ type: '0', mmsi: '' },
|
||||
{ type: 'Cargo', mmsi: '99' },
|
||||
{ type: 'Passenger', mmsi: '9936720011' },
|
||||
{},
|
||||
])
|
||||
assert.equal(isAidToNavigation(vessel), false, JSON.stringify(vessel));
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* The bundled world cities pack (Wikidata, CC0), read from
|
||||
* `local_data/wikidata_cities/cities.json` (built by
|
||||
* scripts/build-wikidata-cities.mjs). The file loads once, on first use, and
|
||||
* every answer comes from it: no place service is called.
|
||||
*
|
||||
* Rows are `[name, lat, lon, population, country, wikidata]`, largest first.
|
||||
*/
|
||||
|
||||
const CELL_DEG = 1;
|
||||
|
||||
// Letters that are not a base letter plus an accent, so NFD leaves them.
|
||||
const PLAIN_LETTERS = {
|
||||
ł: 'l',
|
||||
ø: 'o',
|
||||
đ: 'd',
|
||||
ð: 'd',
|
||||
ı: 'i',
|
||||
ß: 'ss',
|
||||
æ: 'ae',
|
||||
œ: 'oe',
|
||||
þ: 'th',
|
||||
};
|
||||
|
||||
/**
|
||||
* A name as the lookups compare it: lower case, without accents, so
|
||||
* "sao paulo" finds São Paulo, "zurich" Zürich, "lodz" Łódź and "tromso"
|
||||
* Tromsø.
|
||||
*/
|
||||
export const foldName = (name) =>
|
||||
String(name || '')
|
||||
.normalize('NFD')
|
||||
.replace(/\p{M}/gu, '')
|
||||
.toLocaleLowerCase('en')
|
||||
.replace(/[łøđðıßæœþ]/g, (letter) => PLAIN_LETTERS[letter])
|
||||
.trim();
|
||||
const EARTH_KM = 6371;
|
||||
const rad = (deg) => (deg * Math.PI) / 180;
|
||||
|
||||
function distanceKm(lat1, lon1, lat2, lon2) {
|
||||
const a =
|
||||
Math.sin(rad(lat2 - lat1) / 2) ** 2 +
|
||||
Math.cos(rad(lat1)) *
|
||||
Math.cos(rad(lat2)) *
|
||||
Math.sin(rad(lon2 - lon1) / 2) ** 2;
|
||||
return 2 * EARTH_KM * Math.asin(Math.min(1, Math.sqrt(a)));
|
||||
}
|
||||
|
||||
const cellKey = (lat, lon) =>
|
||||
`${Math.floor(lat / CELL_DEG)},${Math.floor(((((lon % 360) + 540) % 360) - 180) / CELL_DEG)}`;
|
||||
|
||||
/** Group rows by one-degree cell so a lookup reads only the cells near it. */
|
||||
export function indexCities(rows) {
|
||||
const cells = new Map();
|
||||
for (const row of rows) {
|
||||
const key = cellKey(row[1], row[2]);
|
||||
const cell = cells.get(key);
|
||||
if (cell) cell.push(row);
|
||||
else cells.set(key, [row]);
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
/** Rows by folded name, each list in the rows' own order (largest first). */
|
||||
export function indexNames(rows) {
|
||||
const names = new Map();
|
||||
for (const row of rows) {
|
||||
const key = foldName(row[0]);
|
||||
const list = names.get(key);
|
||||
if (list) list.push(row);
|
||||
else names.set(key, [row]);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function toCity(row, km) {
|
||||
return {
|
||||
name: row[0],
|
||||
latitude: row[1],
|
||||
longitude: row[2],
|
||||
population: row[3],
|
||||
country: row[4] || null,
|
||||
wikidata: row[5],
|
||||
distanceKm: km,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Half the longitude a circle spans, in degrees: 180 when it reaches a pole,
|
||||
* where every meridian passes through it.
|
||||
*/
|
||||
export function lonHalfSpan(latitude, radiusKm) {
|
||||
const angle = radiusKm / EARTH_KM;
|
||||
const fromPole = Math.PI / 2 - Math.abs(rad(latitude));
|
||||
if (angle >= fromPole) return 180;
|
||||
return (Math.asin(Math.sin(angle) / Math.cos(rad(latitude))) * 180) / Math.PI;
|
||||
}
|
||||
const latHalfSpan = (radiusKm) => ((radiusKm / EARTH_KM) * 180) / Math.PI;
|
||||
|
||||
/** Rows within `radiusKm` of a point, each with its distance. */
|
||||
export function citiesWithin(cells, latitude, longitude, radiusKm) {
|
||||
const latSpan = Math.ceil(latHalfSpan(radiusKm) / CELL_DEG);
|
||||
const lonSpan = Math.ceil(lonHalfSpan(latitude, radiusKm) / CELL_DEG);
|
||||
const found = [];
|
||||
const seen = new Set();
|
||||
for (let dLat = -latSpan; dLat <= latSpan; dLat++) {
|
||||
const lat = latitude + dLat * CELL_DEG;
|
||||
if (lat < -90 - CELL_DEG || lat > 90 + CELL_DEG) continue;
|
||||
for (
|
||||
let dLon = -Math.min(lonSpan, 180);
|
||||
dLon <= Math.min(lonSpan, 180);
|
||||
dLon++
|
||||
) {
|
||||
const key = cellKey(lat, longitude + dLon * CELL_DEG);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
for (const row of cells.get(key) || []) {
|
||||
const km = distanceKm(latitude, longitude, row[1], row[2]);
|
||||
if (km <= radiusKm) found.push(toCity(row, km));
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Each country in the pack by what a qualifier may call it: its code, its
|
||||
// English name and its name in the page language, folded.
|
||||
function countryNames(rows) {
|
||||
const names = new Map();
|
||||
for (const code of new Set(rows.map((row) => row[4]).filter(Boolean))) {
|
||||
for (const name of [code, countryName(code, 'en'), countryName(code)])
|
||||
names.set(foldName(name), code);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
let loading = null;
|
||||
/** The indexed pack; a failed load is retried on the next call. */
|
||||
export function loadCities(fetchImpl = (...args) => globalThis.fetch(...args)) {
|
||||
loading ??= fetchImpl(
|
||||
new URL('./local_data/wikidata_cities/cities.json', import.meta.url),
|
||||
)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`cities pack: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
})
|
||||
.then((pack) => ({
|
||||
meta: pack.meta,
|
||||
rows: pack.rows,
|
||||
cells: indexCities(pack.rows),
|
||||
names: indexNames(pack.rows),
|
||||
countries: countryNames(pack.rows),
|
||||
}))
|
||||
.catch((error) => {
|
||||
loading = null;
|
||||
throw error;
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
/**
|
||||
* The city a point is in or nearest to: the largest within `nearKm`, else the
|
||||
* nearest within `radiusKm`, else null. Preferring the largest nearby keeps a
|
||||
* view over a metropolis from being named after one of its suburbs.
|
||||
*/
|
||||
export async function nearestCity(
|
||||
latitude,
|
||||
longitude,
|
||||
{ radiusKm = 60, nearKm = 12 } = {},
|
||||
) {
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
const { cells } = await loadCities();
|
||||
const found = citiesWithin(cells, latitude, longitude, radiusKm);
|
||||
if (!found.length) return null;
|
||||
const near = found.filter((city) => city.distanceKm <= nearKm);
|
||||
if (near.length)
|
||||
return near.reduce((a, b) => (b.population > a.population ? b : a));
|
||||
return found.reduce((a, b) => (b.distanceKm < a.distanceKm ? b : a));
|
||||
}
|
||||
|
||||
/** Cities around a point, most populous first. */
|
||||
export async function citiesAround({
|
||||
latitude,
|
||||
longitude,
|
||||
radiusKm = 50,
|
||||
limit = 8,
|
||||
minPopulation = 0,
|
||||
}) {
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return [];
|
||||
const { cells } = await loadCities();
|
||||
return citiesWithin(cells, latitude, longitude, radiusKm)
|
||||
.filter((city) => city.population >= minPopulation)
|
||||
.sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/** A country's name in the page language, from its ISO code. */
|
||||
export function countryName(
|
||||
code,
|
||||
language = globalThis.document?.documentElement?.lang || 'en',
|
||||
) {
|
||||
if (!code) return null;
|
||||
try {
|
||||
return (
|
||||
new Intl.DisplayNames([language], { type: 'region' }).of(code) || code
|
||||
);
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The city with this name, or null. A qualifier after a comma that names a
|
||||
* country ("Paris, France", "Paris, US") keeps only cities there, and finds
|
||||
* nothing when none is; one that names no country ("Paris, Texas") is
|
||||
* ignored. A city of that name within `radiusKm` of `near` (the view) wins,
|
||||
* the nearest first, else the largest city of that name anywhere.
|
||||
*/
|
||||
export async function findPlace(
|
||||
name,
|
||||
{ near = null, radiusKm = 150 } = {},
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
) {
|
||||
const [head, ...rest] = String(name || '').split(',');
|
||||
const wanted = foldName(head);
|
||||
if (!wanted) return null;
|
||||
const qualifier = foldName(rest.join(','));
|
||||
const { names, countries } = await loadCities(fetchImpl);
|
||||
const country = qualifier ? countries.get(qualifier) : undefined;
|
||||
const cities = (names.get(wanted) || []).filter(
|
||||
(row) => !country || row[4] === country,
|
||||
);
|
||||
if (!cities.length) return null;
|
||||
if (Number.isFinite(near?.latitude) && Number.isFinite(near?.longitude)) {
|
||||
let best = null;
|
||||
for (const row of cities) {
|
||||
const km = distanceKm(near.latitude, near.longitude, row[1], row[2]);
|
||||
if (km <= radiusKm && (!best || km < best.distanceKm))
|
||||
best = toCity(row, km);
|
||||
}
|
||||
if (best) return best;
|
||||
}
|
||||
return toCity(cities[0], 0);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// src/data/wikidataCities.test.mjs — lookups over the bundled Wikidata
|
||||
// places packs, with the packs served from memory.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
citiesWithin,
|
||||
foldName,
|
||||
indexCities,
|
||||
lonHalfSpan,
|
||||
} from './wikidataCities.js';
|
||||
|
||||
const ROWS = [
|
||||
['São Paulo', -23.55, -46.633, 11451999, 'BR', 'Q174'],
|
||||
['Austin', 30.267, -97.743, 961855, 'US', 'Q16559'],
|
||||
['Round Rock', 30.508, -97.679, 119468, 'US', 'Q128269'],
|
||||
['Zürich', 47.374, 8.541, 421878, 'CH', 'Q72'],
|
||||
];
|
||||
|
||||
test('names compare without case or accents', () => {
|
||||
assert.equal(foldName('São Paulo'), 'sao paulo');
|
||||
assert.equal(foldName(' ZÜRICH '), 'zurich');
|
||||
assert.equal(foldName(null), '');
|
||||
});
|
||||
|
||||
test('a lookup reads the cells around a point and measures each place', () => {
|
||||
const cells = indexCities(ROWS);
|
||||
const near = citiesWithin(cells, 30.27, -97.74, 40).sort(
|
||||
(a, b) => a.distanceKm - b.distanceKm,
|
||||
);
|
||||
assert.deepEqual(
|
||||
near.map((city) => city.name),
|
||||
['Austin', 'Round Rock'],
|
||||
);
|
||||
assert.ok(near[0].distanceKm < 1);
|
||||
assert.equal(near[1].country, 'US');
|
||||
assert.deepEqual(citiesWithin(cells, 0, 0, 50), []);
|
||||
});
|
||||
|
||||
test('findPlace finds a city by its name without accents', async () => {
|
||||
// A fresh module, so its pack cache starts empty.
|
||||
const { findPlace } = await import(`./wikidataCities.js?case=${Date.now()}`);
|
||||
const fetchImpl = async (url) => ({
|
||||
ok: true,
|
||||
json: async () =>
|
||||
String(url).includes('cities.json') ? { meta: {}, rows: ROWS } : null,
|
||||
});
|
||||
const found = await findPlace('sao paulo, Brazil', {}, fetchImpl);
|
||||
assert.equal(found?.wikidata, 'Q174');
|
||||
assert.equal(await findPlace('Atlantis', {}, fetchImpl), null);
|
||||
});
|
||||
|
||||
test('names fold letters that carry no separate accent', () => {
|
||||
assert.equal(foldName('Łódź'), 'lodz');
|
||||
assert.equal(foldName('Tromsø'), 'tromso');
|
||||
assert.equal(foldName('Đà Nẵng'), 'da nang');
|
||||
assert.equal(foldName('Diyarbakır'), 'diyarbakir');
|
||||
assert.equal(foldName('Straße'), 'strasse');
|
||||
});
|
||||
|
||||
const PARIS = [
|
||||
['Paris', 48.857, 2.352, 2145906, 'FR', 'Q90'],
|
||||
['Paris', 33.661, -95.556, 24476, 'US', 'Q830149'],
|
||||
];
|
||||
|
||||
async function freshPack(rows) {
|
||||
const module = await import(
|
||||
`./wikidataCities.js?case=${Date.now()}-${Math.random()}`
|
||||
);
|
||||
const fetchImpl = async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ meta: {}, rows }),
|
||||
});
|
||||
return { ...module, fetchImpl };
|
||||
}
|
||||
|
||||
test('findPlace takes a country qualifier and prefers a namesake in view', async () => {
|
||||
const { findPlace, fetchImpl } = await freshPack(PARIS);
|
||||
const texas = { latitude: 33.2, longitude: -96.0 };
|
||||
assert.equal((await findPlace('Paris', {}, fetchImpl)).wikidata, 'Q90');
|
||||
assert.equal(
|
||||
(await findPlace('Paris', { near: texas }, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
assert.equal(
|
||||
(await findPlace('Paris, United States', {}, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
assert.equal(
|
||||
(await findPlace('paris, us', {}, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
// A qualifier the packs cannot place is ignored.
|
||||
assert.equal(
|
||||
(await findPlace('Paris, Texas', { near: texas }, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
});
|
||||
|
||||
test('a circle that reaches a pole spans every longitude', () => {
|
||||
assert.equal(lonHalfSpan(89, 150), 180);
|
||||
assert.ok(lonHalfSpan(60, 150) < 3);
|
||||
const cells = indexCities([['Pole camp', 89.9, 179, 1, '', 'Q1']]);
|
||||
assert.equal(citiesWithin(cells, 89, 0, 150).length, 1);
|
||||
});
|
||||
|
||||
test('a country qualifier that matches no namesake finds nothing', async () => {
|
||||
const { findPlace, fetchImpl } = await freshPack([
|
||||
...PARIS,
|
||||
['Berlin', 52.52, 13.405, 3755251, 'DE', 'Q64'],
|
||||
]);
|
||||
assert.equal(await findPlace('Paris, Germany', {}, fetchImpl), null);
|
||||
assert.equal(
|
||||
(await findPlace('Paris, France', {}, fetchImpl)).wikidata,
|
||||
'Q90',
|
||||
);
|
||||
});
|
||||
|
||||
test('a lookup wraps at the antimeridian', () => {
|
||||
const cells = indexCities([['Taveuni', -16.8, -179.9, 15000, 'FJ', 'Q2']]);
|
||||
assert.equal(citiesWithin(cells, -16.8, 179.9, 40).length, 1);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* A projector from world positions to window coordinates for one pass over
|
||||
* many positions under one camera, giving what
|
||||
* `Cesium.SceneTransforms.worldToWindowCoordinates` gives: in a 3D scene with
|
||||
* a perspective camera it runs the same arithmetic in the same order once the
|
||||
* camera's matrices and the canvas size are read, so the results are the same
|
||||
* numbers; otherwise it asks Cesium for each.
|
||||
*
|
||||
* Read the camera again (a new projector) whenever it may have moved.
|
||||
* @param {Cesium.Scene} scene
|
||||
* @returns {(position: Cesium.Cartesian3, result: Cesium.Cartesian2) =>
|
||||
* Cesium.Cartesian2|undefined} The window position in `result`, or
|
||||
* undefined behind the camera.
|
||||
*/
|
||||
export function createWindowProjector(scene) {
|
||||
const camera = scene?.camera;
|
||||
const frustum = camera?.frustum;
|
||||
if (
|
||||
scene?.frameState?.mode !== Cesium.SceneMode.SCENE3D ||
|
||||
!camera ||
|
||||
frustum instanceof Cesium.OrthographicFrustum ||
|
||||
frustum instanceof Cesium.OrthographicOffCenterFrustum
|
||||
)
|
||||
return (position, result) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result);
|
||||
const v = camera.viewMatrix;
|
||||
const p = frustum.projectionMatrix;
|
||||
const width = scene.canvas.clientWidth;
|
||||
const height = scene.canvas.clientHeight;
|
||||
const halfWidth = width * 0.5;
|
||||
const halfHeight = height * 0.5;
|
||||
return (position, result) => {
|
||||
if (!position)
|
||||
return Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
result,
|
||||
);
|
||||
const { x, y, z } = position;
|
||||
// Eye coordinates, as Matrix4.multiplyByVector computes them (w = 1).
|
||||
const ex = v[0] * x + v[4] * y + v[8] * z + v[12];
|
||||
const ey = v[1] * x + v[5] * y + v[9] * z + v[13];
|
||||
const ez = v[2] * x + v[6] * y + v[10] * z + v[14];
|
||||
const ew = v[3] * x + v[7] * y + v[11] * z + v[15];
|
||||
// At the eye itself Cesium's own steps have no direction to take.
|
||||
if (ex === 0 && ey === 0 && ez === 0)
|
||||
return Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
result,
|
||||
);
|
||||
// Clip coordinates.
|
||||
const cx = p[0] * ex + p[4] * ey + p[8] * ez + p[12] * ew;
|
||||
const cy = p[1] * ex + p[5] * ey + p[9] * ez + p[13] * ew;
|
||||
const cz = p[2] * ex + p[6] * ey + p[10] * ez + p[14] * ew;
|
||||
const cw = p[3] * ex + p[7] * ey + p[11] * ez + p[15] * ew;
|
||||
if (cz < 0) return undefined;
|
||||
// The viewport transform of the canvas, then window y downward.
|
||||
result.x = halfWidth * (cx / cw) + halfWidth;
|
||||
result.y = height - (halfHeight * (cy / cw) + halfHeight);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createWindowProjector } from './windowProjection.js';
|
||||
|
||||
function sceneLooking(
|
||||
lon,
|
||||
lat,
|
||||
heightM,
|
||||
pitchDeg,
|
||||
mode = Cesium.SceneMode.SCENE3D,
|
||||
) {
|
||||
const scene = {
|
||||
canvas: { clientWidth: 1713, clientHeight: 941 },
|
||||
drawingBufferWidth: 1713,
|
||||
drawingBufferHeight: 941,
|
||||
mapProjection: new Cesium.GeographicProjection(),
|
||||
ellipsoid: Cesium.Ellipsoid.WGS84,
|
||||
frameState: { mode, mapProjection: new Cesium.GeographicProjection() },
|
||||
globe: undefined,
|
||||
tweens: { add() {} },
|
||||
screenSpaceCameraController: { minimumZoomDistance: 1 },
|
||||
};
|
||||
scene.camera = new Cesium.Camera(scene);
|
||||
scene.camera.frustum.aspectRatio = 1713 / 941;
|
||||
scene.camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
orientation: {
|
||||
heading: 0.3,
|
||||
pitch: Cesium.Math.toRadians(pitchDeg),
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
return scene;
|
||||
}
|
||||
|
||||
function positionsAround(lon, lat, spreadDeg, count) {
|
||||
let seed = 7;
|
||||
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
|
||||
return Array.from({ length: count }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
lon + (rnd() - 0.5) * spreadDeg,
|
||||
lat + (rnd() - 0.5) * spreadDeg,
|
||||
rnd() * 50,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
test('a 3D perspective projector gives the same numbers Cesium gives', () => {
|
||||
for (const [pitch, spread, heightM] of [
|
||||
[-90, 1, 60_000],
|
||||
[-35, 4, 60_000],
|
||||
[-5, 40, 60_000],
|
||||
// Just above the sea, points near and behind the near plane.
|
||||
[-10, 0.002, 3],
|
||||
]) {
|
||||
const scene = sceneLooking(4.1, 51.95, heightM, pitch);
|
||||
const project = createWindowProjector(scene);
|
||||
let behind = 0;
|
||||
for (const position of positionsAround(4.1, 51.95, spread, 2000)) {
|
||||
const expected = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
new Cesium.Cartesian2(),
|
||||
);
|
||||
const actual = project(position, new Cesium.Cartesian2());
|
||||
if (!expected) {
|
||||
behind++;
|
||||
assert.equal(actual, undefined);
|
||||
continue;
|
||||
}
|
||||
assert.equal(actual.x, expected.x);
|
||||
assert.equal(actual.y, expected.y);
|
||||
}
|
||||
if (pitch === -5)
|
||||
assert.ok(behind > 0, 'some positions fall behind the camera');
|
||||
}
|
||||
});
|
||||
|
||||
test('outside a 3D scene the projector asks Cesium', () => {
|
||||
const scene = sceneLooking(
|
||||
4.1,
|
||||
51.95,
|
||||
60_000,
|
||||
-90,
|
||||
Cesium.SceneMode.COLUMBUS_VIEW,
|
||||
);
|
||||
const calls = [];
|
||||
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = (...args) => {
|
||||
calls.push(args);
|
||||
return args[2];
|
||||
};
|
||||
try {
|
||||
const result = new Cesium.Cartesian2();
|
||||
const position = Cesium.Cartesian3.fromDegrees(4.1, 51.95);
|
||||
assert.equal(createWindowProjector(scene)(position, result), result);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][1], position);
|
||||
} finally {
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = original;
|
||||
}
|
||||
});
|
||||
|
||||
test('at the eye itself, or with no position, the projector asks Cesium', () => {
|
||||
const scene = sceneLooking(4.1, 51.95, 60_000, -90);
|
||||
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
const asked = [];
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => {
|
||||
asked.push(position);
|
||||
return undefined;
|
||||
};
|
||||
try {
|
||||
const project = createWindowProjector(scene);
|
||||
const eye = Cesium.Cartesian3.clone(scene.camera.positionWC);
|
||||
assert.equal(project(eye, new Cesium.Cartesian2()), undefined);
|
||||
assert.equal(project(undefined, new Cesium.Cartesian2()), undefined);
|
||||
assert.deepEqual(asked, [eye, undefined]);
|
||||
} finally {
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = original;
|
||||
}
|
||||
});
|
||||
@@ -165,7 +165,7 @@ test('the DISMISS button closes the card the way ESC does', async (t) => {
|
||||
assert.notEqual(sessionStorageRef.read(), null, 'dismissed for the session');
|
||||
root.dispatchEvent(new Event('transitionend'));
|
||||
await nextTick();
|
||||
assert.equal(document.getElementById('first-run-launcher'), null);
|
||||
assert.equal(document.getElementById('first-run-launcher') === null, true);
|
||||
});
|
||||
|
||||
test('the scroll fade clears when the tiles fit after a resize', async (t) => {
|
||||
@@ -191,5 +191,5 @@ test('ESC closes the card, returns focus, and removes it without a transition',
|
||||
// Reduced motion: no transitionend, so the bounded fallback removes it.
|
||||
t.mock.timers.tick(400);
|
||||
await nextTick();
|
||||
assert.equal(document.getElementById('first-run-launcher'), null);
|
||||
assert.equal(document.getElementById('first-run-launcher') === null, true);
|
||||
});
|
||||
+74
-2
@@ -177,7 +177,69 @@ function interpolate(pattern, values) {
|
||||
/** A catalog string with something to show; an empty one counts as missing. */
|
||||
const filled = (value) => typeof value === 'string' && value.trim() !== '';
|
||||
|
||||
// A host application's own text for messages Core shows (setMessageOverrides),
|
||||
// by locale: { en: { 'English key': 'Its text' }, de: { … } }.
|
||||
let overrides = Object.freeze({});
|
||||
|
||||
/**
|
||||
* Show a host application's own text for Core's messages. `messages` maps a
|
||||
* locale (`en` included) to entries keyed as the catalogs are: the English
|
||||
* text, `context|text` for a t() context, the English plural for tn() (whose
|
||||
* entry is a `{one, other, …}` object). An overridden message shows the host's
|
||||
* text in the active locale, else the host's English, else Core's. Each call
|
||||
* replaces the previous overrides; `{}` removes them. Call it before views
|
||||
* render: onLocaleChange listeners word their text again at once, but a view
|
||||
* already drawn keeps its text until it next renders. A t() entry is text, a
|
||||
* tn() entry `{one, other, …}` forms worded in its locale; any other entry is
|
||||
* ignored.
|
||||
* @param {Record<string, Record<string, string|Record<string, string>>>} messages
|
||||
*/
|
||||
export function setMessageOverrides(messages) {
|
||||
const next = {};
|
||||
for (const [locale, entries] of Object.entries(messages ?? {})) {
|
||||
const code = normalizeLocale(locale);
|
||||
if (!code || !entries || typeof entries !== 'object') continue;
|
||||
const own = Object.fromEntries(
|
||||
Object.entries(entries).map(([key, entry]) => [
|
||||
key,
|
||||
entry && typeof entry === 'object'
|
||||
? Object.freeze({ ...entry })
|
||||
: entry,
|
||||
]),
|
||||
);
|
||||
next[code] = Object.freeze({ ...next[code], ...own });
|
||||
}
|
||||
overrides = Object.freeze(next);
|
||||
notifyLocaleChange();
|
||||
}
|
||||
|
||||
/** A host's entry for t() is text; for tn() plural forms with an `other`. */
|
||||
const usable = (entry, plural) =>
|
||||
plural
|
||||
? Boolean(entry) && typeof entry === 'object' && filled(entry.other)
|
||||
: filled(entry);
|
||||
|
||||
/**
|
||||
* The host's entry for a message, in the active locale or else in English,
|
||||
* with the locale it is worded in (whose plural rules pick its form).
|
||||
*/
|
||||
function overridden(text, plural = false) {
|
||||
for (const locale of new Set([getLocale(), DEFAULT_LOCALE])) {
|
||||
const entries = overrides[locale];
|
||||
const entry =
|
||||
entries && Object.hasOwn(entries, text) ? entries[text] : undefined;
|
||||
if (usable(entry, plural)) return { entry, locale };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function lookup(text) {
|
||||
const host = overridden(text);
|
||||
return host ? host.entry : catalogEntry(text);
|
||||
}
|
||||
|
||||
/** Core's own catalog entry for a message in the active locale. */
|
||||
function catalogEntry(text) {
|
||||
const catalog = CATALOGS[getLocale()];
|
||||
if (!catalog) return undefined;
|
||||
const entry = Object.hasOwn(catalog, text) ? catalog[text] : undefined;
|
||||
@@ -212,7 +274,14 @@ export function t(text, values) {
|
||||
* @returns {string}
|
||||
*/
|
||||
export function tn(count, one, other, values) {
|
||||
const entry = lookup(other);
|
||||
const host = overridden(other, true);
|
||||
if (host) {
|
||||
const forms = host.entry;
|
||||
const category = pluralRules(host.locale).select(count);
|
||||
const pattern = filled(forms[category]) ? forms[category] : forms.other;
|
||||
return interpolate(pattern, { count, ...values });
|
||||
}
|
||||
const entry = catalogEntry(other);
|
||||
const category = pluralRules(getLocale()).select(count);
|
||||
let pattern;
|
||||
const forms = entry && typeof entry === 'object' ? entry : null;
|
||||
@@ -230,8 +299,11 @@ export function tn(count, one, other, values) {
|
||||
* missing-translation warning.
|
||||
*/
|
||||
export function translateKnown(text) {
|
||||
if (typeof text !== 'string') return text;
|
||||
const host = overridden(text);
|
||||
if (host) return host.entry;
|
||||
const catalog = CATALOGS[getLocale()];
|
||||
if (!catalog || typeof text !== 'string') return text;
|
||||
if (!catalog) return text;
|
||||
const entry = Object.hasOwn(catalog, text) ? catalog[text] : undefined;
|
||||
return filled(entry) ? entry : text;
|
||||
}
|
||||
|
||||
@@ -776,6 +776,8 @@
|
||||
"TANKER": "ناقلة",
|
||||
"OTHER": "أخرى",
|
||||
"VESSEL": "سفينة",
|
||||
"AID TO NAVIGATION": "مساعدة ملاحية",
|
||||
"VIRTUAL": "افتراضي",
|
||||
"POS: LIVE": "الموضع: مباشر",
|
||||
"POS: {time}Z": "الموضع: {time}Z",
|
||||
"AIS: --": "AIS: --",
|
||||
@@ -1695,8 +1697,8 @@
|
||||
"GNSS integrity source unavailable": "مصدر سلامة GNSS غير متاح",
|
||||
"Retrying automatically at {time} UTC": "إعادة المحاولة تلقائيًا عند {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "إعادة المحاولة تلقائيًا بعد انتهاء مهلة المزوّد",
|
||||
"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.": "يُحدَّث تلقائيًا بعد التحريك أو التكبير/التصغير ومرة كل دقيقة. يغطي المصدر العام دائرة نصف قطرها 250 ميلًا بحريًا حول مركز العرض؛ والتصغير لا يجعله لقطة عالمية. الخلايا الفارغة خارج نطاق العيّنة أو أرصادها غير كافية.",
|
||||
"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.": "مؤشر ضعف الدقة = 100 × max(0, الضعيفة − 1) / الإجمالي: تُستبعد طائرة واحدة، لذا فهو ليس النسبة الخام. تحتاج كل خلية إلى {aircraft} طائرات خلال {minutes} دقيقة. شذوذ سلامة الملاحة ليس كشفًا للتشويش أو الانتحال.",
|
||||
"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.": "يُحدَّث تلقائيًا بعد التحريك أو التكبير/التصغير ومرة كل دقيقة. يغطي المصدر العام دائرة نصف قطرها 250 ميلًا بحريًا حول مركز العرض؛ والتصغير لا يجعله لقطة عالمية. المناطق الفارغة لم تُبلغ فيها أي طائرة عن دقة الملاحة خلال النافذة الزمنية.",
|
||||
"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.": "مؤشر ضعف الدقة = 100 × max(0, الضعيفة − 1) / الإجمالي: تُستبعد طائرة واحدة، لذا فهو ليس النسبة الخام. شذوذ سلامة الملاحة ليس كشفًا للتشويش أو الانتحال.",
|
||||
"GNSS snapshot needs a view anchor": "لقطة GNSS تحتاج إلى نقطة ارتكاز للعرض",
|
||||
"GNSS feed rate limited (HTTP 429)": "مصدر GNSS تجاوز حد الطلبات (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "لقطة سلامة GNSS مشوّهة",
|
||||
@@ -2030,7 +2032,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60° ج–60° ش · بتأخير 2–3 س عادةً",
|
||||
"North America · infrared imagery": "أمريكا الشمالية · صور بالأشعة تحت الحمراء",
|
||||
"Reduced motion · history playback unavailable": "تقليل الحركة · تشغيل السجل غير متاح",
|
||||
"Reduced motion · manual history available": "تقليل الحركة · التصفح اليدوي للسجل متاح",
|
||||
"Rain radar · US": "رادار الأمطار · الولايات المتحدة",
|
||||
"Lightning density · 15 min": "كثافة البرق · 15 د",
|
||||
"Satellite clouds": "الغيوم من الأقمار الصناعية",
|
||||
@@ -2540,12 +2541,8 @@
|
||||
"PAUSE": "إيقاف مؤقت",
|
||||
"RESUME": "استئناف",
|
||||
"Clear reading": "مسح القراءة",
|
||||
"Earlier observation": "رصد أسبق",
|
||||
"Observed history": "سجل الأرصاد",
|
||||
"Later observation": "رصد لاحق",
|
||||
"Latest": "الأحدث",
|
||||
"Newest frame per product": "أحدث إطار لكل منتج",
|
||||
"Replay observed history": "إعادة تشغيل سجل الأرصاد",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "الصور على Esri · تعود Google 3D عند المسح",
|
||||
"Point the camera at the ground to use the view": "وجّه الكاميرا نحو الأرض لاستخدام العرض",
|
||||
"That point cannot anchor a box": "لا يمكن تثبيت منطقة على تلك النقطة",
|
||||
@@ -2846,7 +2843,6 @@
|
||||
"dB": "dB",
|
||||
"{time} · {minutes} min ago": "{time} · قبل {minutes} د",
|
||||
"Active weather": "الطقس النشط",
|
||||
"LATEST · newest per product": "الأحدث · آخر إطار لكل منتج",
|
||||
"Forecast · valid {valid} · issued {issued}": "توقع عند {valid} · صدر {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · لا يتبع السجل",
|
||||
"Forecast · valid {valid}": "توقع عند {valid}",
|
||||
@@ -3961,6 +3957,31 @@
|
||||
"Reload": "إعادة التحميل",
|
||||
"Retry": "إعادة المحاولة",
|
||||
"Reset view": "إعادة ضبط العرض",
|
||||
"Trolleybus": "ترولي باص",
|
||||
"Cable car": "ترام كابلي",
|
||||
"Monorail": "قطار أحادي السكة",
|
||||
"Funicular": "قطار جبلي مائل",
|
||||
"Gondola": "تلفريك",
|
||||
"Move panels back beside the rail": "إعادة اللوحات إلى جانب الشريط",
|
||||
"Move panels over the rail, to the edge": "نقل اللوحات فوق الشريط إلى الحافة",
|
||||
"panel|VISUAL": "المرئيات",
|
||||
"Look": "المظهر",
|
||||
"Overlay": "التراكب",
|
||||
"Effects": "المؤثرات",
|
||||
"Scope opacity": "عتامة المنظار",
|
||||
"How dark the scope shades the view outside the keyhole": "مدى تعتيم المنظار للعرض خارج الفتحة",
|
||||
"Reset to default": "إعادة التعيين إلى الافتراضي",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "إعادة المرئيات إلى إعداداتها الافتراضية: المظهر العادي وHUD والمنظار والتسميات والمؤثرات",
|
||||
"All layers": "كل الطبقات",
|
||||
"On": "تشغيل",
|
||||
"Off": "إيقاف",
|
||||
"Search layers": "البحث في الطبقات",
|
||||
"Filter layers": "تصفية الطبقات",
|
||||
"Status": "الحالة",
|
||||
"Search layers…": "ابحث في الطبقات…",
|
||||
"Layer groups": "مجموعات الطبقات",
|
||||
"Jump to {name}": "الانتقال إلى {name}",
|
||||
"No layers match": "لا توجد طبقات مطابقة",
|
||||
"ISS live video": "بث مباشر من محطة الفضاء الدولية",
|
||||
"ISS LIVE · NASA": "محطة الفضاء الدولية مباشر · NASA",
|
||||
"Open on YouTube": "فتح على YouTube",
|
||||
|
||||
@@ -416,6 +416,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "SCHIFF",
|
||||
"AID TO NAVIGATION": "SEEZEICHEN",
|
||||
"VIRTUAL": "VIRTUELL",
|
||||
"POS: LIVE": "POS: LIVE",
|
||||
"POS: {time}Z": "POS: {time}Z",
|
||||
"awaiting first AIS position…": "warten auf erste AIS-Position…",
|
||||
@@ -1622,8 +1624,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Regionale Stichprobe · Radius 250 NM · Zellen aus besuchten Ansichten der letzten {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Automatischer neuer Versuch um {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Automatischer neuer Versuch nach der Sperrzeit des Anbieters",
|
||||
"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.": "Aktualisiert sich nach Schwenken oder Zoomen und einmal pro Minute automatisch. Der öffentliche Feed deckt einen Kreis von 250 Seemeilen um die Bildmitte ab; Herauszoomen macht daraus keinen weltweiten Snapshot. Leere Zellen liegen außerhalb der Stichprobe oder haben zu wenige Beobachtungen.",
|
||||
"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.": "Ungenauigkeitswert = 100 × max(0, schlecht − 1) / gesamt: Ein Luftfahrzeug wird abgezogen, das ist also nicht der reine Anteil. Zellen brauchen {aircraft} Luftfahrzeuge über {minutes} Minuten. Anomalien der Navigationsintegrität sind kein Nachweis von Jamming oder Spoofing.",
|
||||
"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.": "Aktualisiert sich nach Schwenken oder Zoomen und einmal pro Minute automatisch. Der öffentliche Feed deckt einen Kreis von 250 Seemeilen um die Bildmitte ab; Herauszoomen macht daraus keinen weltweiten Snapshot. In leeren Bereichen hat im Zeitfenster kein Flugzeug seine Navigationsgenauigkeit gemeldet.",
|
||||
"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.": "Ungenauigkeitswert = 100 × max(0, schlecht − 1) / gesamt: Ein Luftfahrzeug wird abgezogen, das ist also nicht der reine Anteil. Anomalien der Navigationsintegrität sind kein Nachweis von Jamming oder Spoofing.",
|
||||
"GNSS snapshot needs a view anchor": "GNSS-Snapshot braucht einen Ansichtsanker",
|
||||
"GNSS feed rate limited (HTTP 429)": "GNSS-Feed hat das Anfragelimit erreicht (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Fehlerhafter GNSS-Integritäts-Snapshot",
|
||||
@@ -1934,7 +1936,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · meist 2–3 h verzögert",
|
||||
"North America · infrared imagery": "Nordamerika · Infrarotbilder",
|
||||
"Reduced motion · history playback unavailable": "Reduzierte Bewegung · Verlaufswiedergabe nicht verfügbar",
|
||||
"Reduced motion · manual history available": "Reduzierte Bewegung · manueller Verlauf verfügbar",
|
||||
"Rain radar · US": "Regenradar · USA",
|
||||
"Lightning density · 15 min": "Blitzdichte · 15 min",
|
||||
"Satellite clouds": "Wolken (Satellit)",
|
||||
@@ -2400,12 +2401,8 @@
|
||||
"PAUSE": "PAUSE",
|
||||
"RESUME": "FORTSETZEN",
|
||||
"Clear reading": "Wert ausblenden",
|
||||
"Earlier observation": "Frühere Beobachtung",
|
||||
"Observed history": "Beobachteter Verlauf",
|
||||
"Later observation": "Spätere Beobachtung",
|
||||
"Latest": "Neueste",
|
||||
"Newest frame per product": "Neuester Frame je Produkt",
|
||||
"Replay observed history": "Beobachteten Verlauf abspielen",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Bilder auf Esri · nach LÖSCHEN wieder Google 3D",
|
||||
"Point the camera at the ground to use the view": "Kamera auf den Boden richten, um die Ansicht zu verwenden",
|
||||
"That point cannot anchor a box": "Dieser Punkt kann keinen Bereich verankern",
|
||||
@@ -2654,7 +2651,6 @@
|
||||
"dB": "dB",
|
||||
"{time} · {minutes} min ago": "{time} · vor {minutes} min",
|
||||
"Active weather": "Aktives Wetter",
|
||||
"LATEST · newest per product": "NEUESTE · je Produkt",
|
||||
"Forecast · valid {valid} · issued {issued}": "Vorhersage · gültig {valid} · ausgegeben {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · Folgt nicht dem Verlauf",
|
||||
"Forecast · valid {valid}": "Vorhersage · gültig {valid}",
|
||||
@@ -3613,6 +3609,31 @@
|
||||
"Reload": "Neu laden",
|
||||
"Retry": "Erneut versuchen",
|
||||
"Reset view": "Ansicht zurücksetzen",
|
||||
"Trolleybus": "Oberleitungsbus",
|
||||
"Cable car": "Kabelstraßenbahn",
|
||||
"Monorail": "Einschienenbahn",
|
||||
"Funicular": "Standseilbahn",
|
||||
"Gondola": "Gondelbahn",
|
||||
"Move panels back beside the rail": "Bedienfelder zurück neben die Leiste",
|
||||
"Move panels over the rail, to the edge": "Bedienfelder über die Leiste an den Rand verschieben",
|
||||
"panel|VISUAL": "DARSTELLUNG",
|
||||
"Look": "Look",
|
||||
"Overlay": "Overlay",
|
||||
"Effects": "Effekte",
|
||||
"Scope opacity": "Scope-Deckkraft",
|
||||
"How dark the scope shades the view outside the keyhole": "Wie stark der Scope die Ansicht außerhalb des Schlüssellochs abdunkelt",
|
||||
"Reset to default": "Auf Standard zurücksetzen",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Darstellung auf die Standardwerte zurücksetzen: normaler Look, HUD, Scope, Beschriftungen und Effekte",
|
||||
"All layers": "Alle Ebenen",
|
||||
"On": "An",
|
||||
"Off": "Aus",
|
||||
"Search layers": "Ebenen suchen",
|
||||
"Filter layers": "Ebenen filtern",
|
||||
"Status": "Status",
|
||||
"Search layers…": "Ebenen suchen…",
|
||||
"Layer groups": "Ebenengruppen",
|
||||
"Jump to {name}": "Zu {name} springen",
|
||||
"No layers match": "Keine passenden Ebenen",
|
||||
"ISS live video": "ISS-Livevideo",
|
||||
"ISS LIVE · NASA": "ISS LIVE · NASA",
|
||||
"Open on YouTube": "Auf YouTube öffnen",
|
||||
|
||||
@@ -650,6 +650,8 @@
|
||||
"TANKER": "PETROLERO",
|
||||
"OTHER": "OTRO",
|
||||
"VESSEL": "BUQUE",
|
||||
"AID TO NAVIGATION": "AYUDA A LA NAVEGACIÓN",
|
||||
"VIRTUAL": "VIRTUAL",
|
||||
"POS: LIVE": "POS: EN VIVO",
|
||||
"POS: {time}Z": "POS: {time}Z",
|
||||
"AIS: --": "AIS: --",
|
||||
@@ -1434,7 +1436,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente con 2–3 h de retraso",
|
||||
"North America · infrared imagery": "Norteamérica · imágenes infrarrojas",
|
||||
"Reduced motion · history playback unavailable": "Movimiento reducido · reproducción del historial no disponible",
|
||||
"Reduced motion · manual history available": "Movimiento reducido · puedes recorrer el historial a mano",
|
||||
"Rain radar · US": "Radar de lluvia · EE. UU.",
|
||||
"Lightning density · 15 min": "Densidad de rayos · 15 min",
|
||||
"Satellite clouds": "Nubes por satélite",
|
||||
@@ -1665,12 +1666,8 @@
|
||||
"CH {index} / {total}": "CANAL {index} / {total}",
|
||||
"Station unavailable after directory refresh": "Emisora no disponible tras actualizar el directorio",
|
||||
"Clear reading": "Borrar lectura",
|
||||
"Earlier observation": "Observación anterior",
|
||||
"Observed history": "Historial observado",
|
||||
"Later observation": "Observación posterior",
|
||||
"Latest": "Último",
|
||||
"Newest frame per product": "Fotograma más reciente por producto",
|
||||
"Replay observed history": "Reproducir el historial observado",
|
||||
"S on another day replaces it · × unpins": "S en otro día lo reemplaza · × quita la fijación",
|
||||
"← → preview · S shows the focused day": "← → vista previa · S muestra el día enfocado",
|
||||
"Recent imagery": "Imágenes recientes",
|
||||
@@ -1834,7 +1831,6 @@
|
||||
"Reset map bearing to north": "Restablecer la orientación del mapa al norte",
|
||||
"Rain radar": "Radar de lluvia",
|
||||
"Lightning density": "Densidad de rayos",
|
||||
"LATEST · newest per product": "ÚLTIMO · más reciente por producto",
|
||||
"Forecast · valid {valid} · issued {issued}": "Pronóstico · válido {valid} · emitido {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · No sigue el historial",
|
||||
"Forecast · valid {valid}": "Pronóstico · válido {valid}",
|
||||
@@ -2339,8 +2335,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Muestra regional · radio de 250 NM · celdas de las vistas visitadas en {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Reintento automático a las {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Reintento automático tras la pausa del proveedor",
|
||||
"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.": "Se actualiza automáticamente al desplazar el mapa o hacer zoom y una vez por minuto. La fuente pública cubre un círculo de 250 millas náuticas alrededor del centro de la vista; alejarte no la convierte en una instantánea mundial. Las celdas vacías están fuera de la cobertura muestreada o no tienen observaciones suficientes.",
|
||||
"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.": "Índice de baja precisión = 100 × max(0, malas − 1) / total: se descuenta una aeronave, así que no es la proporción bruta. Cada celda necesita {aircraft} aeronaves en {minutes} minutos. Las anomalías de integridad de navegación no son una detección de interferencias ni de suplantación.",
|
||||
"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.": "Se actualiza automáticamente al desplazar el mapa o hacer zoom y una vez por minuto. La fuente pública cubre un círculo de 250 millas náuticas alrededor del centro de la vista; alejarte no la convierte en una instantánea mundial. En las zonas vacías ningún avión informó su precisión de navegación durante la ventana.",
|
||||
"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.": "Índice de baja precisión = 100 × max(0, malas − 1) / total: se descuenta una aeronave, así que no es la proporción bruta. Las anomalías de integridad de navegación no son una detección de interferencias ni de suplantación.",
|
||||
"SQUAWK {code} · {status}": "SQUAWK {code} · {status}",
|
||||
"ADS-B PRIORITY · {status}": "ADS-B PRIORIDAD · {status}",
|
||||
"ADS-B EMERGENCY · {status}": "ADS-B EMERGENCIA · {status}",
|
||||
@@ -3700,6 +3696,31 @@
|
||||
"Reload": "Recargar",
|
||||
"Retry": "Reintentar",
|
||||
"Reset view": "Restablecer la vista",
|
||||
"Trolleybus": "Trolebús",
|
||||
"Cable car": "Tranvía de cable",
|
||||
"Monorail": "Monorraíl",
|
||||
"Funicular": "Funicular",
|
||||
"Gondola": "Góndola",
|
||||
"Move panels back beside the rail": "Devolver los paneles junto a la barra",
|
||||
"Move panels over the rail, to the edge": "Mover los paneles sobre la barra, hasta el borde",
|
||||
"panel|VISUAL": "VISUAL",
|
||||
"Look": "Aspecto",
|
||||
"Overlay": "Superposición",
|
||||
"Effects": "Efectos",
|
||||
"Scope opacity": "Opacidad de la mirilla",
|
||||
"How dark the scope shades the view outside the keyhole": "Cuánto oscurece la mirilla la vista fuera del ojo de cerradura",
|
||||
"Reset to default": "Restablecer valores predeterminados",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Restablecer Visual a sus valores predeterminados: aspecto Normal, HUD, mirilla, etiquetas y efectos",
|
||||
"All layers": "Todas las capas",
|
||||
"On": "Activadas",
|
||||
"Off": "Desactivadas",
|
||||
"Search layers": "Buscar capas",
|
||||
"Filter layers": "Filtrar capas",
|
||||
"Status": "Estado",
|
||||
"Search layers…": "Buscar capas…",
|
||||
"Layer groups": "Grupos de capas",
|
||||
"Jump to {name}": "Ir a {name}",
|
||||
"No layers match": "Ninguna capa coincide",
|
||||
"ISS live video": "Vídeo en directo de la ISS",
|
||||
"ISS LIVE · NASA": "ISS EN DIRECTO · NASA",
|
||||
"Open on YouTube": "Abrir en YouTube",
|
||||
|
||||
@@ -862,8 +862,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Échantillon régional · rayon de 250 NM · cellules des vues visitées sur {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Nouvel essai automatique à {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Nouvel essai automatique après la pause du fournisseur",
|
||||
"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.": "Mise à jour automatique après un déplacement ou un zoom, et une fois par minute. Le flux public couvre un cercle de 250 milles nautiques autour du centre de la vue ; dézoomer n'en fait pas un instantané mondial. Les cellules vides sont hors de la couverture échantillonnée ou manquent d'observations.",
|
||||
"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.": "Indice de faible précision = 100 × max(0, mauvais − 1) / total : un aéronef est déduit, ce n'est donc pas la proportion brute. Chaque cellule exige {aircraft} aéronefs sur {minutes} minutes. Les anomalies d'intégrité de navigation ne constituent pas une détection de brouillage ou de leurrage.",
|
||||
"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.": "Mise à jour automatique après un déplacement ou un zoom, et une fois par minute. Le flux public couvre un cercle de 250 milles nautiques autour du centre de la vue ; dézoomer n'en fait pas un instantané mondial. Dans les zones vides, aucun avion n'a signalé sa précision de navigation pendant la fenêtre.",
|
||||
"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.": "Indice de faible précision = 100 × max(0, mauvais − 1) / total : un aéronef est déduit, ce n'est donc pas la proportion brute. Les anomalies d'intégrité de navigation ne constituent pas une détection de brouillage ou de leurrage.",
|
||||
"GNSS snapshot needs a view anchor": "L'instantané GNSS nécessite un point d'ancrage de la vue",
|
||||
"GNSS feed rate limited (HTTP 429)": "Flux GNSS : limite de requêtes atteinte (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Instantané d'intégrité GNSS mal formé",
|
||||
@@ -1291,6 +1291,8 @@
|
||||
"AIS: {name}": "AIS : {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD : {speed} HDG : {heading}",
|
||||
"VESSEL": "NAVIRE",
|
||||
"AID TO NAVIGATION": "AIDE À LA NAVIGATION",
|
||||
"VIRTUAL": "VIRTUEL",
|
||||
"{speed}KT": "{speed} ND",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS : DIRECT",
|
||||
@@ -1348,7 +1350,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · retard habituel de 2 à 3 h",
|
||||
"North America · infrared imagery": "Amérique du Nord · imagerie infrarouge",
|
||||
"Reduced motion · history playback unavailable": "Animations réduites · lecture de l'historique indisponible",
|
||||
"Reduced motion · manual history available": "Animations réduites · historique parcourable manuellement",
|
||||
"Rain radar · US": "Radar de pluie · États-Unis",
|
||||
"Lightning density · 15 min": "Densité de foudre · 15 min",
|
||||
"Satellite clouds": "Nuages par satellite",
|
||||
@@ -2148,12 +2149,8 @@
|
||||
"Radio is disabling…": "Désactivation de la Radio…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "État de la Radio incertain — utilisez Activer ou Désactiver pour le rétablir",
|
||||
"Clear reading": "Effacer le relevé",
|
||||
"Earlier observation": "Observation précédente",
|
||||
"Observed history": "Historique des observations",
|
||||
"Later observation": "Observation suivante",
|
||||
"Latest": "Dernière",
|
||||
"Newest frame per product": "Image la plus récente par produit",
|
||||
"Replay observed history": "Rejouer l'historique des observations",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Sur Esri · EFFACER rétablit Google 3D",
|
||||
"Point the camera at the ground to use the view": "Orientez la caméra vers le sol pour utiliser la vue",
|
||||
"That point cannot anchor a box": "Ce point ne peut pas ancrer une zone",
|
||||
@@ -2444,7 +2441,6 @@
|
||||
"DETECT": "DÉTECT.",
|
||||
"{time} · {minutes} min ago": "{time} · il y a {minutes} min",
|
||||
"Active weather": "Couches météo actives",
|
||||
"LATEST · newest per product": "DERNIÈRE · la plus récente par produit",
|
||||
"Forecast · valid {valid} · issued {issued}": "Prévision · valide {valid} · émise {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · Ne suit pas l'historique",
|
||||
"Forecast · valid {valid}": "Prévision · valide {valid}",
|
||||
@@ -3700,6 +3696,31 @@
|
||||
"Reload": "Recharger",
|
||||
"Retry": "Réessayer",
|
||||
"Reset view": "Réinitialiser la vue",
|
||||
"Trolleybus": "Trolleybus",
|
||||
"Cable car": "Tramway à câble",
|
||||
"Monorail": "Monorail",
|
||||
"Funicular": "Funiculaire",
|
||||
"Gondola": "Télécabine",
|
||||
"Move panels back beside the rail": "Remettre les panneaux à côté de la barre",
|
||||
"Move panels over the rail, to the edge": "Déplacer les panneaux par-dessus la barre, jusqu’au bord",
|
||||
"panel|VISUAL": "VISUEL",
|
||||
"Look": "Aspect",
|
||||
"Overlay": "Surcouche",
|
||||
"Effects": "Effets",
|
||||
"Scope opacity": "Opacité de la lunette",
|
||||
"How dark the scope shades the view outside the keyhole": "À quel point la lunette assombrit la vue hors de l'ouverture",
|
||||
"Reset to default": "Rétablir les valeurs par défaut",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Rétablir les valeurs par défaut de Visuel : aspect Normal, HUD, lunette, libellés et effets",
|
||||
"All layers": "Toutes les couches",
|
||||
"On": "Actives",
|
||||
"Off": "Inactives",
|
||||
"Search layers": "Rechercher des couches",
|
||||
"Filter layers": "Filtrer les couches",
|
||||
"Status": "État",
|
||||
"Search layers…": "Rechercher des couches…",
|
||||
"Layer groups": "Groupes de couches",
|
||||
"Jump to {name}": "Aller à {name}",
|
||||
"No layers match": "Aucune couche ne correspond",
|
||||
"ISS live video": "Vidéo en direct de l’ISS",
|
||||
"ISS LIVE · NASA": "ISS EN DIRECT · NASA",
|
||||
"Open on YouTube": "Ouvrir sur YouTube",
|
||||
|
||||
@@ -789,8 +789,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "דגימה אזורית · רדיוס 250 מייל ימי · תאים מתצפיות שביקרת על פני {minutes} דק׳",
|
||||
"Retrying automatically at {time} UTC": "מנסה שוב אוטומטית ב-{time} UTC",
|
||||
"Retrying automatically after provider cooldown": "מנסה שוב אוטומטית אחרי תקופת ההמתנה של הספק",
|
||||
"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.": "מתעדכן אוטומטית אחרי הזזה או זום ופעם בדקה. הפיד הציבורי מכסה מעגל של 250 מייל ימי סביב מרכז התצוגה; זום החוצה לא הופך אותו לתמונת-מצב עולמית. תאים ריקים נמצאים מחוץ לדגימה או שאין בהם די תצפיות.",
|
||||
"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.": "ציון דיוק נמוך = 100 × מקס(0, פגומים − 1) / סה\"כ: מטוס אחד מנוכה, ולכן זה אינו השבר הגולמי. לתאים דרושים {aircraft} מטוסים על פני {minutes} דקות. אנומליות שלמות ניווט אינן זיהוי של שיבוש או הטעיה.",
|
||||
"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.": "מתעדכן אוטומטית אחרי הזזה או זום ופעם בדקה. הפיד הציבורי מכסה מעגל של 250 מייל ימי סביב מרכז התצוגה; זום החוצה לא הופך אותו לתמונת-מצב עולמית. באזורים ריקים אף מטוס לא דיווח על דיוק הניווט שלו בחלון הזמן.",
|
||||
"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.": "ציון דיוק נמוך = 100 × מקס(0, פגומים − 1) / סה\"כ: מטוס אחד מנוכה, ולכן זה אינו השבר הגולמי. אנומליות שלמות ניווט אינן זיהוי של שיבוש או הטעיה.",
|
||||
"GNSS snapshot needs a view anchor": "תמונת מצב GNSS דורשת עוגן תצוגה",
|
||||
"GNSS feed rate limited (HTTP 429)": "פיד GNSS מוגבל בקצב (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "תמונת מצב שלמות GNSS פגומה",
|
||||
@@ -1149,6 +1149,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "אונייה",
|
||||
"AID TO NAVIGATION": "עזר ניווט",
|
||||
"VIRTUAL": "וירטואלי",
|
||||
"{speed}KT": "{speed} קשר",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS: חי",
|
||||
@@ -1206,7 +1208,6 @@
|
||||
"Color: strikes/km²/min ×10³": "צבע: פגיעות ברק/קמ\"ר/דק׳ ×10³",
|
||||
"Color: {units}": "צבע: {units}",
|
||||
"Reduced motion · history playback unavailable": "תנועה מופחתת · הצגת ההיסטוריה אינה זמינה",
|
||||
"Reduced motion · manual history available": "תנועה מופחתת · היסטוריה ידנית זמינה",
|
||||
"Rain radar · US": "רדאר גשם · ארה\"ב",
|
||||
"Lightning density · 15 min": "צפיפות ברקים · 15 דק׳",
|
||||
"Satellite clouds": "עננים מלוויין",
|
||||
@@ -1994,11 +1995,7 @@
|
||||
"READY": "מוכן",
|
||||
"Clear reading": "ניקוי הקריאה",
|
||||
"Observed history": "היסטוריה נצפית",
|
||||
"Earlier observation": "תצפית קודמת",
|
||||
"Later observation": "תצפית מאוחרת",
|
||||
"Newest frame per product": "השקופית החדשה לכל מוצר",
|
||||
"Latest": "האחרונה",
|
||||
"Replay observed history": "הצגת ההיסטוריה הנצפית שוב",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "צילומים ב-Esri · Google 3D חוזר כשמנקים",
|
||||
"Point the camera at the ground to use the view": "כוון את המצלמה אל הקרקע כדי להשתמש בתצוגה",
|
||||
"That point cannot anchor a box": "אין אפשרות לעגן תיבה באותה נקודה",
|
||||
@@ -2781,7 +2778,6 @@
|
||||
"Detection overlay: off": "שכבת הזיהוי: כבויה",
|
||||
"Active weather": "מזג אוויר פעיל",
|
||||
"{time} · {minutes} min ago": "{time} · לפני {minutes} דק׳",
|
||||
"LATEST · newest per product": "האחרון · החדש ביותר לכל מוצר",
|
||||
"Forecast · valid {valid} · issued {issued}": "תחזית · תקפה {valid} · פורסמה {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · אינו נע עם ההיסטוריה",
|
||||
"Forecast · valid {valid}": "תחזית · תקפה {valid}",
|
||||
@@ -3700,6 +3696,31 @@
|
||||
"Reload": "טען מחדש",
|
||||
"Retry": "נסה שוב",
|
||||
"Reset view": "איפוס תצוגה",
|
||||
"Trolleybus": "טרוליבוס",
|
||||
"Cable car": "חשמלית כבלים",
|
||||
"Monorail": "מונורייל",
|
||||
"Funicular": "פוניקולר",
|
||||
"Gondola": "רכבל",
|
||||
"Move panels back beside the rail": "החזרת הלוחות לצד הסרגל",
|
||||
"Move panels over the rail, to the edge": "הזזת הלוחות מעל הסרגל, אל הקצה",
|
||||
"panel|VISUAL": "חזותי",
|
||||
"Look": "מראה",
|
||||
"Overlay": "שכבת על",
|
||||
"Effects": "אפקטים",
|
||||
"Scope opacity": "אטימות הסקופ",
|
||||
"How dark the scope shades the view outside the keyhole": "עד כמה הסקופ מכהה את התצוגה מחוץ לחור המנעול",
|
||||
"Reset to default": "איפוס לברירת המחדל",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "איפוס החזותי לברירות המחדל: מראה רגיל, HUD, סקופ, תוויות ואפקטים",
|
||||
"All layers": "כל השכבות",
|
||||
"On": "פעילות",
|
||||
"Off": "כבויות",
|
||||
"Search layers": "חיפוש שכבות",
|
||||
"Filter layers": "סינון שכבות",
|
||||
"Status": "מצב",
|
||||
"Search layers…": "חיפוש שכבות…",
|
||||
"Layer groups": "קבוצות שכבות",
|
||||
"Jump to {name}": "מעבר אל {name}",
|
||||
"No layers match": "אין שכבות תואמות",
|
||||
"ISS live video": "שידור חי מתחנת החלל",
|
||||
"ISS LIVE · NASA": "ISS בשידור חי · NASA",
|
||||
"Open on YouTube": "פתיחה ב-YouTube",
|
||||
|
||||
@@ -862,8 +862,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Campione regionale · raggio di 250 NM · celle dalle viste visitate negli ultimi {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Nuovo tentativo automatico alle {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Nuovo tentativo automatico dopo la pausa del provider",
|
||||
"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.": "Si aggiorna automaticamente dopo uno spostamento o uno zoom e una volta al minuto. Il feed pubblico copre un cerchio di 250 miglia nautiche attorno al centro della vista; allontanare lo zoom non lo rende un'istantanea mondiale. Le celle vuote sono fuori dalla copertura campionata o hanno osservazioni insufficienti.",
|
||||
"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.": "Indice di bassa precisione = 100 × max(0, anomali − 1) / totale: dal conteggio degli aerei anomali si sottrae un aereo, quindi non è la percentuale grezza. Le celle richiedono {aircraft} aerei in {minutes} minuti. Le anomalie di integrità della navigazione non costituiscono un rilevamento di jamming o spoofing.",
|
||||
"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.": "Si aggiorna automaticamente dopo uno spostamento o uno zoom e una volta al minuto. Il feed pubblico copre un cerchio di 250 miglia nautiche attorno al centro della vista; allontanare lo zoom non lo rende un'istantanea mondiale. Nelle aree vuote nessun aereo ha comunicato la propria precisione di navigazione nella finestra.",
|
||||
"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.": "Indice di bassa precisione = 100 × max(0, anomali − 1) / totale: dal conteggio degli aerei anomali si sottrae un aereo, quindi non è la percentuale grezza. Le anomalie di integrità della navigazione non costituiscono un rilevamento di jamming o spoofing.",
|
||||
"GNSS snapshot needs a view anchor": "Lo snapshot GNSS richiede un punto di riferimento della vista",
|
||||
"GNSS feed rate limited (HTTP 429)": "Limite di richieste del feed GNSS raggiunto (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Snapshot di integrità GNSS non valido",
|
||||
@@ -1291,6 +1291,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} VEL: {speed} HDG: {heading}",
|
||||
"VESSEL": "NAVE",
|
||||
"AID TO NAVIGATION": "AIUTO ALLA NAVIGAZIONE",
|
||||
"VIRTUAL": "VIRTUALE",
|
||||
"{speed}KT": "{speed}KT",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS: LIVE",
|
||||
@@ -1348,7 +1350,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · di solito 2–3 h di ritardo",
|
||||
"North America · infrared imagery": "Nord America · immagini all'infrarosso",
|
||||
"Reduced motion · history playback unavailable": "Movimento ridotto · riproduzione dello storico non disponibile",
|
||||
"Reduced motion · manual history available": "Movimento ridotto · storico manuale disponibile",
|
||||
"Rain radar · US": "Radar pioggia · USA",
|
||||
"Lightning density · 15 min": "Densità di fulmini · 15 min",
|
||||
"Satellite clouds": "Nuvole da satellite",
|
||||
@@ -2148,12 +2149,8 @@
|
||||
"Radio is disabling…": "Disattivazione della Radio…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Il ciclo di vita della Radio è incerto: usa Attiva o Disattiva per riconciliare",
|
||||
"Clear reading": "Cancella la lettura",
|
||||
"Earlier observation": "Osservazione precedente",
|
||||
"Observed history": "Storico osservato",
|
||||
"Later observation": "Osservazione successiva",
|
||||
"Latest": "Più recente",
|
||||
"Newest frame per product": "Fotogramma più recente per prodotto",
|
||||
"Replay observed history": "Rivedi lo storico osservato",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Immagini su Esri · Google 3D torna con CANCELLA",
|
||||
"Point the camera at the ground to use the view": "Punta la camera verso il suolo per usare la vista",
|
||||
"That point cannot anchor a box": "Quel punto non può ancorare un riquadro",
|
||||
@@ -2444,7 +2441,6 @@
|
||||
"DETECT": "RILEV.",
|
||||
"{time} · {minutes} min ago": "{time} · {minutes} min fa",
|
||||
"Active weather": "Meteo attivo",
|
||||
"LATEST · newest per product": "ULTIMO · il più recente per prodotto",
|
||||
"Forecast · valid {valid} · issued {issued}": "Previsione · valida {valid} · emessa {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · Non segue lo storico",
|
||||
"Forecast · valid {valid}": "Previsione · valida {valid}",
|
||||
@@ -3700,6 +3696,31 @@
|
||||
"Reload": "Ricarica",
|
||||
"Retry": "Riprova",
|
||||
"Reset view": "Ripristina vista",
|
||||
"Trolleybus": "Filobus",
|
||||
"Cable car": "Tram a fune",
|
||||
"Monorail": "Monorotaia",
|
||||
"Funicular": "Funicolare",
|
||||
"Gondola": "Cabinovia",
|
||||
"Move panels back beside the rail": "Riporta i pannelli accanto alla barra",
|
||||
"Move panels over the rail, to the edge": "Sposta i pannelli sopra la barra, fino al bordo",
|
||||
"panel|VISUAL": "VISUALE",
|
||||
"Look": "Aspetto",
|
||||
"Overlay": "Overlay",
|
||||
"Effects": "Effetti",
|
||||
"Scope opacity": "Opacità dello scope",
|
||||
"How dark the scope shades the view outside the keyhole": "Quanto lo scope scurisce la vista fuori dal foro",
|
||||
"Reset to default": "Ripristina predefiniti",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Ripristina Visuale ai valori predefiniti: aspetto Normale, HUD, scope, etichette ed effetti",
|
||||
"All layers": "Tutti i livelli",
|
||||
"On": "Attivi",
|
||||
"Off": "Disattivati",
|
||||
"Search layers": "Cerca livelli",
|
||||
"Filter layers": "Filtra livelli",
|
||||
"Status": "Stato",
|
||||
"Search layers…": "Cerca livelli…",
|
||||
"Layer groups": "Gruppi di livelli",
|
||||
"Jump to {name}": "Vai a {name}",
|
||||
"No layers match": "Nessun livello corrisponde",
|
||||
"ISS live video": "Video in diretta dalla ISS",
|
||||
"ISS LIVE · NASA": "ISS IN DIRETTA · NASA",
|
||||
"Open on YouTube": "Apri su YouTube",
|
||||
|
||||
@@ -834,8 +834,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "地域サンプル · 半径250海里 · 過去{minutes}分間に表示したビューのセル",
|
||||
"Retrying automatically at {time} UTC": "{time} UTCに自動で再試行します",
|
||||
"Retrying automatically after provider cooldown": "プロバイダーのクールダウン後に自動で再試行します",
|
||||
"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.": "パンやズームの後、および1分ごとに自動で更新されます。公開フィードは表示中心から半径250海里の円をカバーします。ズームアウトしても全世界のスナップショットにはなりません。空白のセルは、サンプリング範囲外か観測が不十分です。",
|
||||
"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.": "低精度スコア = 100 × max(0, bad − 1) / total:航空機1機分を差し引くため、単純な割合ではありません。セルには{minutes}分間で{aircraft}機の航空機が必要です。航法インテグリティの異常は、妨害(ジャミング)やなりすまし(スプーフィング)を検出したことを意味しません。",
|
||||
"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.": "パンやズームの後、および1分ごとに自動で更新されます。公開フィードは表示中心から半径250海里の円をカバーします。ズームアウトしても全世界のスナップショットにはなりません。空白の区域では、期間内に航法精度を報告した航空機がありませんでした。",
|
||||
"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.": "低精度スコア = 100 × max(0, bad − 1) / total:航空機1機分を差し引くため、単純な割合ではありません。航法インテグリティの異常は、妨害(ジャミング)やなりすまし(スプーフィング)を検出したことを意味しません。",
|
||||
"GNSS snapshot needs a view anchor": "GNSSスナップショットにはビューのアンカーが必要です",
|
||||
"GNSS feed rate limited (HTTP 429)": "GNSSフィードがレート制限中です(HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "GNSSインテグリティのスナップショットの形式が不正です",
|
||||
@@ -1253,6 +1253,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "船舶",
|
||||
"AID TO NAVIGATION": "航路標識",
|
||||
"VIRTUAL": "仮想",
|
||||
"{speed}KT": "{speed} kt",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS: ライブ",
|
||||
@@ -1310,7 +1312,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常2–3時間遅れ",
|
||||
"North America · infrared imagery": "北米 · 赤外画像",
|
||||
"Reduced motion · history playback unavailable": "動きを減らす設定 · 履歴再生は利用不可",
|
||||
"Reduced motion · manual history available": "動きを減らす設定 · 履歴は手動で表示可能",
|
||||
"Rain radar · US": "降水レーダー · 米国",
|
||||
"Lightning density · 15 min": "雷密度 · 15分",
|
||||
"Satellite clouds": "衛星雲画像",
|
||||
@@ -2074,12 +2075,8 @@
|
||||
"Radio is disabling…": "ラジオを無効化しています…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "ラジオのライフサイクルが不明確です。有効化または無効化で再調整してください",
|
||||
"Clear reading": "読み取り値を消去",
|
||||
"Earlier observation": "前の観測",
|
||||
"Observed history": "観測履歴",
|
||||
"Later observation": "次の観測",
|
||||
"Latest": "最新",
|
||||
"Newest frame per product": "プロダクトごとの最新フレーム",
|
||||
"Replay observed history": "観測履歴を再生",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "画像はEsri上に表示 · 消去するとGoogle 3Dに戻ります",
|
||||
"Point the camera at the ground to use the view": "このビューを使うにはカメラを地面に向けてください",
|
||||
"That point cannot anchor a box": "その地点は範囲の基点にできません",
|
||||
@@ -2344,7 +2341,6 @@
|
||||
"DETECT": "検出",
|
||||
"{time} · {minutes} min ago": "{time} · {minutes}分前",
|
||||
"Active weather": "有効な気象レイヤー",
|
||||
"LATEST · newest per product": "最新 · プロダクトごとの最新",
|
||||
"Forecast · valid {valid} · issued {issued}": "予報 · 対象時刻 {valid} · 発表 {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · 履歴とは連動しません",
|
||||
"Forecast · valid {valid}": "予報 · 対象時刻 {valid}",
|
||||
@@ -3526,6 +3522,31 @@
|
||||
"Reload": "再読み込み",
|
||||
"Retry": "再試行",
|
||||
"Reset view": "ビューをリセット",
|
||||
"Trolleybus": "トロリーバス",
|
||||
"Cable car": "ケーブルトラム",
|
||||
"Monorail": "モノレール",
|
||||
"Funicular": "ケーブルカー",
|
||||
"Gondola": "ゴンドラ",
|
||||
"Move panels back beside the rail": "パネルをレールの横に戻す",
|
||||
"Move panels over the rail, to the edge": "パネルをレールの上、画面端へ移動",
|
||||
"panel|VISUAL": "ビジュアル",
|
||||
"Look": "見た目",
|
||||
"Overlay": "オーバーレイ",
|
||||
"Effects": "エフェクト",
|
||||
"Scope opacity": "スコープの不透明度",
|
||||
"How dark the scope shades the view outside the keyhole": "キーホール外のビューをスコープがどれだけ暗くするか",
|
||||
"Reset to default": "既定に戻す",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "ビジュアルを既定に戻す:標準の見た目、HUD、スコープ、ラベル、エフェクト",
|
||||
"All layers": "すべてのレイヤー",
|
||||
"On": "オン",
|
||||
"Off": "オフ",
|
||||
"Search layers": "レイヤーを検索",
|
||||
"Filter layers": "レイヤーを絞り込む",
|
||||
"Status": "状態",
|
||||
"Search layers…": "レイヤーを検索…",
|
||||
"Layer groups": "レイヤーのグループ",
|
||||
"Jump to {name}": "{name} へ移動",
|
||||
"No layers match": "一致するレイヤーはありません",
|
||||
"ISS live video": "ISSのライブ映像",
|
||||
"ISS LIVE · NASA": "ISS ライブ · NASA",
|
||||
"Open on YouTube": "YouTubeで開く",
|
||||
|
||||
@@ -860,8 +860,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Amostra regional · raio de 250 NM · células das áreas visualizadas nos últimos {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Nova tentativa automática às {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Nova tentativa automática após a pausa do provedor",
|
||||
"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.": "Atualiza automaticamente após mover ou dar zoom e uma vez por minuto. O feed público cobre um círculo de 250 milhas náuticas ao redor do centro da vista; afastar o zoom não o transforma em um snapshot mundial. Células vazias estão fora da cobertura amostrada ou não têm observações suficientes.",
|
||||
"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.": "Índice de baixa precisão = 100 × max(0, ruins − 1) / total: uma aeronave é descontada, então não é a proporção bruta. Cada célula precisa de {aircraft} aeronaves em {minutes} minutos. Anomalias de integridade de navegação não são detecção de interferência (jamming) nem de falsificação (spoofing).",
|
||||
"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.": "Atualiza automaticamente após mover ou dar zoom e uma vez por minuto. O feed público cobre um círculo de 250 milhas náuticas ao redor do centro da vista; afastar o zoom não o transforma em um snapshot mundial. Nas áreas vazias, nenhuma aeronave informou sua precisão de navegação na janela.",
|
||||
"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.": "Índice de baixa precisão = 100 × max(0, ruins − 1) / total: uma aeronave é descontada, então não é a proporção bruta. Anomalias de integridade de navegação não são detecção de interferência (jamming) nem de falsificação (spoofing).",
|
||||
"GNSS snapshot needs a view anchor": "O snapshot GNSS precisa de um ponto de referência da vista",
|
||||
"GNSS feed rate limited (HTTP 429)": "Feed GNSS: limite de requisições atingido (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Snapshot de integridade GNSS malformado",
|
||||
@@ -1289,6 +1289,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "EMBARCAÇÃO",
|
||||
"AID TO NAVIGATION": "AUXÍLIO À NAVEGAÇÃO",
|
||||
"VIRTUAL": "VIRTUAL",
|
||||
"{speed}KT": "{speed} KT",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS: AO VIVO",
|
||||
@@ -1346,7 +1348,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente com 2–3 h de atraso",
|
||||
"North America · infrared imagery": "América do Norte · imagens infravermelhas",
|
||||
"Reduced motion · history playback unavailable": "Movimento reduzido · reprodução do histórico indisponível",
|
||||
"Reduced motion · manual history available": "Movimento reduzido · é possível percorrer o histórico manualmente",
|
||||
"Rain radar · US": "Radar de chuva · EUA",
|
||||
"Lightning density · 15 min": "Densidade de raios · 15 min",
|
||||
"Satellite clouds": "Nuvens por satélite",
|
||||
@@ -2148,12 +2149,8 @@
|
||||
"Radio is disabling…": "O rádio está sendo desativado…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "O ciclo de vida do rádio é incerto — use Ativar ou Desativar para reconciliar",
|
||||
"Clear reading": "Limpar leitura",
|
||||
"Earlier observation": "Observação anterior",
|
||||
"Observed history": "Histórico observado",
|
||||
"Later observation": "Observação posterior",
|
||||
"Latest": "Mais recente",
|
||||
"Newest frame per product": "Quadro mais recente por produto",
|
||||
"Replay observed history": "Reproduzir o histórico observado",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Imagens sobre o Esri · LIMPAR restaura o Google 3D",
|
||||
"Point the camera at the ground to use the view": "Aponte a câmera para o chão para usar a vista",
|
||||
"That point cannot anchor a box": "Esse ponto não pode ancorar uma área",
|
||||
@@ -2444,7 +2441,6 @@
|
||||
"DETECT": "DETECÇÃO",
|
||||
"{time} · {minutes} min ago": "{time} · há {minutes} min",
|
||||
"Active weather": "Camadas de clima ativas",
|
||||
"LATEST · newest per product": "MAIS RECENTE · último por produto",
|
||||
"Forecast · valid {valid} · issued {issued}": "Previsão · válida para {valid} · emitida em {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · Não acompanha o histórico",
|
||||
"Forecast · valid {valid}": "Previsão · válida para {valid}",
|
||||
@@ -3700,6 +3696,31 @@
|
||||
"Reload": "Recarregar",
|
||||
"Retry": "Tentar novamente",
|
||||
"Reset view": "Redefinir vista",
|
||||
"Trolleybus": "Trólebus",
|
||||
"Cable car": "Bonde a cabo",
|
||||
"Monorail": "Monotrilho",
|
||||
"Funicular": "Funicular",
|
||||
"Gondola": "Teleférico",
|
||||
"Move panels back beside the rail": "Voltar os painéis para junto da barra",
|
||||
"Move panels over the rail, to the edge": "Mover os painéis sobre a barra, até a borda",
|
||||
"panel|VISUAL": "VISUAL",
|
||||
"Look": "Aparência",
|
||||
"Overlay": "Sobreposição",
|
||||
"Effects": "Efeitos",
|
||||
"Scope opacity": "Opacidade da mira",
|
||||
"How dark the scope shades the view outside the keyhole": "Quanto a mira escurece a vista fora do visor",
|
||||
"Reset to default": "Redefinir para o padrão",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Redefinir o Visual para o padrão: aparência Normal, HUD, mira, rótulos e efeitos",
|
||||
"All layers": "Todas as camadas",
|
||||
"On": "Ativadas",
|
||||
"Off": "Desativadas",
|
||||
"Search layers": "Pesquisar camadas",
|
||||
"Filter layers": "Filtrar camadas",
|
||||
"Status": "Estado",
|
||||
"Search layers…": "Pesquisar camadas…",
|
||||
"Layer groups": "Grupos de camadas",
|
||||
"Jump to {name}": "Ir para {name}",
|
||||
"No layers match": "Nenhuma camada corresponde",
|
||||
"ISS live video": "Vídeo ao vivo da ISS",
|
||||
"ISS LIVE · NASA": "ISS AO VIVO · NASA",
|
||||
"Open on YouTube": "Abrir no YouTube",
|
||||
|
||||
@@ -394,6 +394,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} СКОР: {speed} КУРС: {heading}",
|
||||
"VESSEL": "СУДНО",
|
||||
"AID TO NAVIGATION": "СРЕДСТВО НАВИГАЦИИ",
|
||||
"VIRTUAL": "ВИРТУАЛЬНЫЙ",
|
||||
"AIS: --": "AIS: --",
|
||||
"awaiting first AIS position…": "ожидание первой позиции AIS…",
|
||||
"awaiting usable AIS positions…": "ожидание пригодных позиций AIS…",
|
||||
@@ -1456,7 +1458,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60° ю. ш.–60° с. ш. · обычно задержка 2–3 ч",
|
||||
"North America · infrared imagery": "Северная Америка · ИК-снимки",
|
||||
"Reduced motion · history playback unavailable": "Уменьшение движения · воспроизведение истории недоступно",
|
||||
"Reduced motion · manual history available": "Уменьшение движения · историю можно листать вручную",
|
||||
"Rain radar · US": "Радар осадков · США",
|
||||
"Lightning density · 15 min": "Плотность молний · 15 мин",
|
||||
"Satellite clouds": "Спутниковая облачность",
|
||||
@@ -1695,12 +1696,8 @@
|
||||
"CH {index} / {total}": "КАН. {index} / {total}",
|
||||
"Station unavailable after directory refresh": "Станция недоступна после обновления каталога",
|
||||
"Clear reading": "Очистить показания",
|
||||
"Earlier observation": "Более раннее наблюдение",
|
||||
"Observed history": "История наблюдений",
|
||||
"Later observation": "Более позднее наблюдение",
|
||||
"Latest": "Последние",
|
||||
"Newest frame per product": "Самый свежий кадр каждого продукта",
|
||||
"Replay observed history": "Воспроизвести историю наблюдений",
|
||||
"S on another day replaces it · × unpins": "S в другой день заменяет его · × открепляет",
|
||||
"← → preview · S shows the focused day": "← → просмотр · S показывает выбранный день",
|
||||
"Recent imagery": "Свежие снимки",
|
||||
@@ -1865,7 +1862,6 @@
|
||||
"Reset map bearing to north": "Сбросить азимут карты на север",
|
||||
"Rain radar": "Радар осадков",
|
||||
"Lightning density": "Плотность молний",
|
||||
"LATEST · newest per product": "ПОСЛЕДНИЕ · самые свежие по каждому продукту",
|
||||
"Forecast · valid {valid} · issued {issued}": "Прогноз · действует на {valid} · выпущен {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · не следует за историей",
|
||||
"Forecast · valid {valid}": "Прогноз · действует на {valid}",
|
||||
@@ -2377,8 +2373,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Региональная выборка · радиус 250 мор. миль · ячейки из просмотренных видов за {minutes} мин",
|
||||
"Retrying automatically at {time} UTC": "Автоматический повтор в {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Автоматический повтор после паузы провайдера",
|
||||
"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.": "Обновляется автоматически после сдвига или масштабирования карты и раз в минуту. Публичный поток данных охватывает круг радиусом 250 морских миль вокруг центра вида; при отдалении карта не становится снимком всего мира. Пустые ячейки — вне охвата выборки или с недостаточным числом наблюдений.",
|
||||
"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.": "Доля неточных = 100 × max(0, неточные − 1) / всего: один самолёт не учитывается, поэтому это не прямая доля. Для ячейки нужно самолётов: {aircraft} за {minutes} мин. Аномалии целостности навигации — не обнаружение глушения или подмены сигнала.",
|
||||
"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.": "Обновляется автоматически после сдвига или масштабирования карты и раз в минуту. Публичный поток данных охватывает круг радиусом 250 морских миль вокруг центра вида; при отдалении карта не становится снимком всего мира. В пустых областях за это окно ни один самолёт не сообщил точность навигации.",
|
||||
"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.": "Доля неточных = 100 × max(0, неточные − 1) / всего: один самолёт не учитывается, поэтому это не прямая доля. Аномалии целостности навигации — не обнаружение глушения или подмены сигнала.",
|
||||
"SQUAWK {code} · {status}": "СКВОК {code} · {status}",
|
||||
"ADS-B PRIORITY · {status}": "ADS-B ПРИОРИТЕТ · {status}",
|
||||
"ADS-B EMERGENCY · {status}": "ADS-B АВАРИЯ · {status}",
|
||||
@@ -3787,6 +3783,31 @@
|
||||
"Reload": "Перезагрузить",
|
||||
"Retry": "Повторить",
|
||||
"Reset view": "Сбросить вид",
|
||||
"Trolleybus": "Троллейбус",
|
||||
"Cable car": "Канатный трамвай",
|
||||
"Monorail": "Монорельс",
|
||||
"Funicular": "Фуникулёр",
|
||||
"Gondola": "Канатная дорога",
|
||||
"Move panels back beside the rail": "Вернуть панели к боковой панели",
|
||||
"Move panels over the rail, to the edge": "Переместить панели поверх боковой панели к краю",
|
||||
"panel|VISUAL": "ВИЗУАЛ",
|
||||
"Look": "Вид",
|
||||
"Overlay": "Наложение",
|
||||
"Effects": "Эффекты",
|
||||
"Scope opacity": "Непрозрачность прицела",
|
||||
"How dark the scope shades the view outside the keyhole": "Насколько прицел затемняет вид за пределами маски",
|
||||
"Reset to default": "Сбросить по умолчанию",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Сбросить «Визуал» к настройкам по умолчанию: обычный вид, HUD, прицел, подписи и эффекты",
|
||||
"All layers": "Все слои",
|
||||
"On": "Включены",
|
||||
"Off": "Выключены",
|
||||
"Search layers": "Поиск слоёв",
|
||||
"Filter layers": "Фильтр слоёв",
|
||||
"Status": "Состояние",
|
||||
"Search layers…": "Поиск слоёв…",
|
||||
"Layer groups": "Группы слоёв",
|
||||
"Jump to {name}": "Перейти к «{name}»",
|
||||
"No layers match": "Нет подходящих слоёв",
|
||||
"ISS live video": "Прямая трансляция с МКС",
|
||||
"ISS LIVE · NASA": "МКС В ЭФИРЕ · NASA",
|
||||
"Open on YouTube": "Открыть на YouTube",
|
||||
|
||||
@@ -382,6 +382,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "FARTYG",
|
||||
"AID TO NAVIGATION": "SJÖMÄRKE",
|
||||
"VIRTUAL": "VIRTUELL",
|
||||
"POS: LIVE": "POS: LIVE",
|
||||
"POS: {time}Z": "POS: {time}Z",
|
||||
"awaiting first AIS position…": "väntar på första AIS-positionen …",
|
||||
@@ -1544,8 +1546,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Regionalt urval · radie 250 NM · celler från besökta vyer under {minutes} min",
|
||||
"Retrying automatically at {time} UTC": "Försöker igen automatiskt kl. {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Försöker igen automatiskt när leverantörens spärrtid är över",
|
||||
"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.": "Uppdateras automatiskt efter panorering eller zoomning och en gång i minuten. Det öppna flödet täcker en cirkel på 250 nautiska mil runt vyns mitt; att zooma ut gör det inte till en global ögonblicksbild. Tomma celler ligger utanför den samplade täckningen eller har för få observationer.",
|
||||
"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.": "Värdet för låg noggrannhet = 100 × max(0, dåliga − 1) / totalt: ett luftfartyg räknas bort, så detta är inte den råa andelen. Cellerna kräver {aircraft} luftfartyg under {minutes} minuter. Avvikelser i navigeringsintegriteten innebär inte att störsändning eller vilseledning (jamming eller spoofing) har upptäckts.",
|
||||
"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.": "Uppdateras automatiskt efter panorering eller zoomning och en gång i minuten. Det öppna flödet täcker en cirkel på 250 nautiska mil runt vyns mitt; att zooma ut gör det inte till en global ögonblicksbild. I tomma områden rapporterade inget flygplan sin navigeringsnoggrannhet under fönstret.",
|
||||
"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.": "Värdet för låg noggrannhet = 100 × max(0, dåliga − 1) / totalt: ett luftfartyg räknas bort, så detta är inte den råa andelen. Avvikelser i navigeringsintegriteten innebär inte att störsändning eller vilseledning (jamming eller spoofing) har upptäckts.",
|
||||
"GNSS snapshot needs a view anchor": "GNSS-ögonblicksbilden behöver ett vyankare",
|
||||
"GNSS feed rate limited (HTTP 429)": "GNSS-flödet har nått gränsen för förfrågningar (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Felformaterad ögonblicksbild av GNSS-integritet",
|
||||
@@ -1856,7 +1858,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60° S–60° N · oftast 2–3 h fördröjning",
|
||||
"North America · infrared imagery": "Nordamerika · infraröda bilder",
|
||||
"Reduced motion · history playback unavailable": "Minskad rörelse · uppspelning av historik otillgänglig",
|
||||
"Reduced motion · manual history available": "Minskad rörelse · manuell historik tillgänglig",
|
||||
"Rain radar · US": "Regnradar · USA",
|
||||
"Lightning density · 15 min": "Blixttäthet · 15 min",
|
||||
"Satellite clouds": "Satellitmoln",
|
||||
@@ -2322,12 +2323,8 @@
|
||||
"PAUSE": "PAUSA",
|
||||
"RESUME": "FORTSÄTT",
|
||||
"Clear reading": "Rensa avläsningen",
|
||||
"Earlier observation": "Tidigare observation",
|
||||
"Observed history": "Observerad historik",
|
||||
"Later observation": "Senare observation",
|
||||
"Latest": "Senaste",
|
||||
"Newest frame per product": "Senaste bildruta per produkt",
|
||||
"Replay observed history": "Spela upp observerad historik",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Bilder på Esri · Google 3D återkommer när de rensas",
|
||||
"Point the camera at the ground to use the view": "Rikta kameran mot marken för att använda vyn",
|
||||
"That point cannot anchor a box": "Den punkten kan inte förankra ett område",
|
||||
@@ -2576,7 +2573,6 @@
|
||||
"dB": "dB",
|
||||
"{time} · {minutes} min ago": "{time} · för {minutes} min sedan",
|
||||
"Active weather": "Aktuellt väder",
|
||||
"LATEST · newest per product": "SENASTE · nyaste per produkt",
|
||||
"Forecast · valid {valid} · issued {issued}": "Prognos · gäller {valid} · utfärdad {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · Följer inte historiken",
|
||||
"Forecast · valid {valid}": "Prognos · gäller {valid}",
|
||||
@@ -3613,6 +3609,31 @@
|
||||
"Reload": "Ladda om",
|
||||
"Retry": "Försök igen",
|
||||
"Reset view": "Återställ vy",
|
||||
"Trolleybus": "Trådbuss",
|
||||
"Cable car": "Kabelspårvagn",
|
||||
"Monorail": "Enskensbana",
|
||||
"Funicular": "Bergbana",
|
||||
"Gondola": "Kabinbana",
|
||||
"Move panels back beside the rail": "Flytta tillbaka panelerna bredvid listen",
|
||||
"Move panels over the rail, to the edge": "Flytta panelerna över listen, till kanten",
|
||||
"panel|VISUAL": "VISUELLT",
|
||||
"Look": "Utseende",
|
||||
"Overlay": "Överlägg",
|
||||
"Effects": "Effekter",
|
||||
"Scope opacity": "Scope-opacitet",
|
||||
"How dark the scope shades the view outside the keyhole": "Hur mycket scopet mörkar vyn utanför nyckelhålet",
|
||||
"Reset to default": "Återställ till standard",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Återställ Visuellt till standard: Normal stil, HUD, scope, etiketter och effekter",
|
||||
"All layers": "Alla lager",
|
||||
"On": "På",
|
||||
"Off": "Av",
|
||||
"Search layers": "Sök lager",
|
||||
"Filter layers": "Filtrera lager",
|
||||
"Status": "Status",
|
||||
"Search layers…": "Sök lager…",
|
||||
"Layer groups": "Lagergrupper",
|
||||
"Jump to {name}": "Gå till {name}",
|
||||
"No layers match": "Inga lager matchar",
|
||||
"ISS live video": "Livevideo från ISS",
|
||||
"ISS LIVE · NASA": "ISS LIVE · NASA",
|
||||
"Open on YouTube": "Öppna på YouTube",
|
||||
|
||||
@@ -875,8 +875,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "Регіональна вибірка · радіус 250 мор. миль · комірки з переглянутих ділянок карти за {minutes} хв",
|
||||
"Retrying automatically at {time} UTC": "Автоматичний повтор о {time} UTC",
|
||||
"Retrying automatically after provider cooldown": "Автоматичний повтор після паузи постачальника",
|
||||
"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.": "Оновлюється автоматично після зсуву чи масштабування карти та раз на хвилину. Публічний потік даних охоплює коло радіусом 250 морських миль навколо центру карти; у разі віддалення карта не стає знімком усього світу. Порожні комірки — поза охопленням вибірки або з недостатньою кількістю спостережень.",
|
||||
"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.": "Показник неточності = 100 × max(0, неточні − 1) / усього: один літак не враховується, тож це не пряма частка літаків із неточними навігаційними даними. Мінімальна кількість літаків у комірці за {minutes} хв: {aircraft}. Аномалії цілісності навігації не означають виявлення глушіння чи підміни сигналу.",
|
||||
"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.": "Оновлюється автоматично після зсуву чи масштабування карти та раз на хвилину. Публічний потік даних охоплює коло радіусом 250 морських миль навколо центру карти; у разі віддалення карта не стає знімком усього світу. У порожніх областях за це вікно жоден літак не повідомив точність навігації.",
|
||||
"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.": "Показник неточності = 100 × max(0, неточні − 1) / усього: один літак не враховується, тож це не пряма частка літаків із неточними навігаційними даними. Аномалії цілісності навігації не означають виявлення глушіння чи підміни сигналу.",
|
||||
"GNSS snapshot needs a view anchor": "Для знімка GNSS потрібна опорна точка на карті",
|
||||
"GNSS feed rate limited (HTTP 429)": "Потік GNSS: перевищено ліміт запитів (HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "Некоректний знімок цілісності GNSS",
|
||||
@@ -1309,6 +1309,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} ШВИД: {speed} КУРС: {heading}",
|
||||
"VESSEL": "СУДНО",
|
||||
"AID TO NAVIGATION": "ЗАСІБ НАВІГАЦІЇ",
|
||||
"VIRTUAL": "ВІРТУАЛЬНИЙ",
|
||||
"{speed}KT": "{speed} ВУЗ",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "ПОЗ.: ОНЛАЙН",
|
||||
@@ -1366,7 +1368,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60° пд. ш.–60° пн. ш. · зазвичай затримка 2–3 год",
|
||||
"North America · infrared imagery": "Північна Америка · ІЧ-знімки",
|
||||
"Reduced motion · history playback unavailable": "Зменшення руху · відтворення історії недоступне",
|
||||
"Reduced motion · manual history available": "Зменшення руху · історію можна гортати вручну",
|
||||
"Rain radar · US": "Радар опадів · США",
|
||||
"Lightning density · 15 min": "Щільність блискавок · 15 хв",
|
||||
"Satellite clouds": "Супутникова хмарність",
|
||||
@@ -2184,12 +2185,8 @@
|
||||
"Radio is disabling…": "Радіо вимикається…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Стан радіо невизначений — звірте через «Увімкнути» або «Вимкнути»",
|
||||
"Clear reading": "Очистити покази",
|
||||
"Earlier observation": "Попереднє спостереження",
|
||||
"Observed history": "Історія спостережень",
|
||||
"Later observation": "Наступне спостереження",
|
||||
"Latest": "Останні",
|
||||
"Newest frame per product": "Найсвіжіший кадр кожного продукту",
|
||||
"Replay observed history": "Відтворити історію спостережень",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "Підкладка: Esri · скидання поверне Google 3D",
|
||||
"Point the camera at the ground to use the view": "Наведіть камеру на землю, щоб вибрати видиму область",
|
||||
"That point cannot anchor a box": "Від цієї точки не можна побудувати область",
|
||||
@@ -2493,7 +2490,6 @@
|
||||
"DETECT": "ВИЯВЛЕННЯ",
|
||||
"{time} · {minutes} min ago": "{time} · {minutes} хв тому",
|
||||
"Active weather": "Активні погодні шари",
|
||||
"LATEST · newest per product": "ОСТАННІ · найсвіжіші для кожного продукту",
|
||||
"Forecast · valid {valid} · issued {issued}": "Прогноз · чинний на {valid} · випущено {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · не синхронізується з історією",
|
||||
"Forecast · valid {valid}": "Прогноз · чинний на {valid}",
|
||||
@@ -3787,6 +3783,31 @@
|
||||
"Reload": "Перезавантажити",
|
||||
"Retry": "Повторити",
|
||||
"Reset view": "Скинути вигляд",
|
||||
"Trolleybus": "Тролейбус",
|
||||
"Cable car": "Канатний трамвай",
|
||||
"Monorail": "Монорейка",
|
||||
"Funicular": "Фунікулер",
|
||||
"Gondola": "Канатна дорога",
|
||||
"Move panels back beside the rail": "Повернути панелі до бічної смуги",
|
||||
"Move panels over the rail, to the edge": "Перемістити панелі поверх бічної смуги до краю",
|
||||
"panel|VISUAL": "ВІЗУАЛ",
|
||||
"Look": "Вигляд",
|
||||
"Overlay": "Накладка",
|
||||
"Effects": "Ефекти",
|
||||
"Scope opacity": "Непрозорість прицілу",
|
||||
"How dark the scope shades the view outside the keyhole": "Наскільки приціл затемнює вигляд за межами прицілу",
|
||||
"Reset to default": "Скинути до типових",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "Скинути «Візуал» до типових налаштувань: звичайний вигляд, HUD, приціл, підписи та ефекти",
|
||||
"All layers": "Усі шари",
|
||||
"On": "Увімкнені",
|
||||
"Off": "Вимкнені",
|
||||
"Search layers": "Пошук шарів",
|
||||
"Filter layers": "Фільтр шарів",
|
||||
"Status": "Стан",
|
||||
"Search layers…": "Пошук шарів…",
|
||||
"Layer groups": "Групи шарів",
|
||||
"Jump to {name}": "Перейти до «{name}»",
|
||||
"No layers match": "Немає відповідних шарів",
|
||||
"ISS live video": "Пряма трансляція з МКС",
|
||||
"ISS LIVE · NASA": "МКС НАЖИВО · NASA",
|
||||
"Open on YouTube": "Відкрити на YouTube",
|
||||
|
||||
@@ -811,8 +811,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "区域采样 · 半径 250 海里 · {minutes} 分钟内浏览过的视野中的网格",
|
||||
"Retrying automatically at {time} UTC": "将于 {time} UTC 自动重试",
|
||||
"Retrying automatically after provider cooldown": "服务商冷却结束后自动重试",
|
||||
"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.": "平移或缩放后以及每分钟自动更新。公共数据源覆盖以视野中心为圆心、半径 250 海里的范围;缩小地图并不会使其成为全球快照。空白网格位于采样覆盖范围之外,或观测数据不足。",
|
||||
"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.": "低精度评分 = 100 × max(0, bad − 1) / total:扣除一架飞机,因此并非原始占比。每个网格需在 {minutes} 分钟内有 {aircraft} 架飞机。导航完好性异常不等于检测到干扰或欺骗。",
|
||||
"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.": "平移或缩放后以及每分钟自动更新。公共数据源覆盖以视野中心为圆心、半径 250 海里的范围;缩小地图并不会使其成为全球快照。空白区域在该时间窗内没有飞机报告导航精度。",
|
||||
"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.": "低精度评分 = 100 × max(0, bad − 1) / total:扣除一架飞机,因此并非原始占比。导航完好性异常不等于检测到干扰或欺骗。",
|
||||
"GNSS snapshot needs a view anchor": "GNSS 快照需要视图锚点",
|
||||
"GNSS feed rate limited (HTTP 429)": "GNSS 数据源已被限流(HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "GNSS 完好性快照格式错误",
|
||||
@@ -1229,6 +1229,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "船舶",
|
||||
"AID TO NAVIGATION": "助航标志",
|
||||
"VIRTUAL": "虚拟",
|
||||
"{speed}KT": "{speed} kn",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS:实时",
|
||||
@@ -1286,7 +1288,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常延迟 2–3 小时",
|
||||
"North America · infrared imagery": "北美洲 · 红外影像",
|
||||
"Reduced motion · history playback unavailable": "减弱动效 · 历史回放不可用",
|
||||
"Reduced motion · manual history available": "减弱动效 · 可手动浏览历史",
|
||||
"Rain radar · US": "降雨雷达 · 美国",
|
||||
"Lightning density · 15 min": "闪电密度 · 15 分钟",
|
||||
"Satellite clouds": "卫星云图",
|
||||
@@ -2044,12 +2045,8 @@
|
||||
"Radio is disabling…": "电台正在停用…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "电台生命周期状态不确定——请使用“启用”或“停用”进行核对",
|
||||
"Clear reading": "清除读数",
|
||||
"Earlier observation": "较早观测",
|
||||
"Observed history": "观测历史",
|
||||
"Later observation": "较晚观测",
|
||||
"Latest": "最新",
|
||||
"Newest frame per product": "每个产品的最新一帧",
|
||||
"Replay observed history": "回放观测历史",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "影像显示在 Esri 底图上 · 清除后恢复 Google 3D",
|
||||
"Point the camera at the ground to use the view": "将相机对准地面才能使用当前视野",
|
||||
"That point cannot anchor a box": "该点无法作为框选锚点",
|
||||
@@ -2308,7 +2305,6 @@
|
||||
"DETECT": "探测",
|
||||
"{time} · {minutes} min ago": "{time} · {minutes} 分钟前",
|
||||
"Active weather": "已启用的天气图层",
|
||||
"LATEST · newest per product": "最新 · 每个产品的最新一帧",
|
||||
"Forecast · valid {valid} · issued {issued}": "预报 · 有效时间 {valid} · 发布时间 {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · 不随观测历史变化",
|
||||
"Forecast · valid {valid}": "预报 · 有效时间 {valid}",
|
||||
@@ -3526,6 +3522,31 @@
|
||||
"Reload": "重新加载",
|
||||
"Retry": "重试",
|
||||
"Reset view": "重置视图",
|
||||
"Trolleybus": "无轨电车",
|
||||
"Cable car": "缆索电车",
|
||||
"Monorail": "单轨列车",
|
||||
"Funicular": "缆索铁路",
|
||||
"Gondola": "缆车",
|
||||
"Move panels back beside the rail": "将面板移回侧栏旁",
|
||||
"Move panels over the rail, to the edge": "将面板移到侧栏上方,贴靠边缘",
|
||||
"panel|VISUAL": "视觉",
|
||||
"Look": "外观",
|
||||
"Overlay": "叠加层",
|
||||
"Effects": "效果",
|
||||
"Scope opacity": "视域不透明度",
|
||||
"How dark the scope shades the view outside the keyhole": "视域遮罩使视域之外的画面变暗的程度",
|
||||
"Reset to default": "恢复默认",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "将视觉恢复为默认设置:常规外观、HUD、视域、标签和效果",
|
||||
"All layers": "全部图层",
|
||||
"On": "已开启",
|
||||
"Off": "已关闭",
|
||||
"Search layers": "搜索图层",
|
||||
"Filter layers": "筛选图层",
|
||||
"Status": "状态",
|
||||
"Search layers…": "搜索图层…",
|
||||
"Layer groups": "图层分组",
|
||||
"Jump to {name}": "跳转到{name}",
|
||||
"No layers match": "没有匹配的图层",
|
||||
"ISS live video": "国际空间站直播视频",
|
||||
"ISS LIVE · NASA": "国际空间站直播 · NASA",
|
||||
"Open on YouTube": "在 YouTube 上打开",
|
||||
|
||||
@@ -806,8 +806,8 @@
|
||||
"Regional sample · 250 nm radius · cells from visited views over {minutes} min": "區域採樣 · 半徑 250 海里 · {minutes} 分鐘內瀏覽過的視野中的網格",
|
||||
"Retrying automatically at {time} UTC": "將於 {time} UTC 自動重試",
|
||||
"Retrying automatically after provider cooldown": "服務商冷卻結束後自動重試",
|
||||
"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.": "平移或縮放後以及每分鐘自動更新。公共數據源覆蓋以視野中心為圓心、半徑 250 海里的範圍;縮小地圖並不會使其成為全球快照。空白網格位於採樣覆蓋範圍之外,或觀測數據不足。",
|
||||
"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.": "低精度評分 = 100 × max(0, bad − 1) / total:扣除一架飛機,因此並非原始佔比。每個網格需在 {minutes} 分鐘內有 {aircraft} 架飛機。導航完好性異常不等於檢測到干擾或欺騙。",
|
||||
"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.": "平移或縮放後以及每分鐘自動更新。公共數據源覆蓋以視野中心為圓心、半徑 250 海里的範圍;縮小地圖並不會使其成為全球快照。空白區域在該時間窗內沒有飛機報告導航精度。",
|
||||
"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.": "低精度評分 = 100 × max(0, bad − 1) / total:扣除一架飛機,因此並非原始佔比。導航完好性異常不等於檢測到干擾或欺騙。",
|
||||
"GNSS snapshot needs a view anchor": "GNSS 快照需要視圖錨點",
|
||||
"GNSS feed rate limited (HTTP 429)": "GNSS 數據源已被限流(HTTP 429)",
|
||||
"Malformed GNSS integrity snapshot": "GNSS 完好性快照格式錯誤",
|
||||
@@ -1224,6 +1224,8 @@
|
||||
"AIS: {name}": "AIS: {name}",
|
||||
"{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
|
||||
"VESSEL": "船舶",
|
||||
"AID TO NAVIGATION": "助航標誌",
|
||||
"VIRTUAL": "虛擬",
|
||||
"{speed}KT": "{speed} kn",
|
||||
"{heading}DEG": "{heading}°",
|
||||
"POS: LIVE": "POS:實時",
|
||||
@@ -1281,7 +1283,6 @@
|
||||
"60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常延遲 2–3 小時",
|
||||
"North America · infrared imagery": "北美洲 · 紅外影像",
|
||||
"Reduced motion · history playback unavailable": "減弱動效 · 歷史回放不可用",
|
||||
"Reduced motion · manual history available": "減弱動效 · 可手動瀏覽歷史",
|
||||
"Rain radar · US": "降雨雷達 · 美國",
|
||||
"Lightning density · 15 min": "閃電密度 · 15 分鐘",
|
||||
"Satellite clouds": "衛星雲圖",
|
||||
@@ -2034,12 +2035,8 @@
|
||||
"Radio is disabling…": "電臺正在停用…",
|
||||
"Radio lifecycle is uncertain — use Enable or Disable to reconcile": "電臺生命週期狀態不確定——請使用“啟用”或“停用”進行核對",
|
||||
"Clear reading": "清除讀數",
|
||||
"Earlier observation": "較早觀測",
|
||||
"Observed history": "觀測歷史",
|
||||
"Later observation": "較晚觀測",
|
||||
"Latest": "最新",
|
||||
"Newest frame per product": "每個產品的最新一幀",
|
||||
"Replay observed history": "回放觀測歷史",
|
||||
"Imagery on Esri · Google 3D returns when cleared": "影像顯示在 Esri 底圖上 · 清除後恢復 Google 3D",
|
||||
"Point the camera at the ground to use the view": "將相機對準地面才能使用當前視野",
|
||||
"That point cannot anchor a box": "該點無法作為框選錨點",
|
||||
@@ -2298,7 +2295,6 @@
|
||||
"DETECT": "探測",
|
||||
"{time} · {minutes} min ago": "{time} · {minutes} 分鐘前",
|
||||
"Active weather": "已啟用的天氣圖層",
|
||||
"LATEST · newest per product": "最新 · 每個產品的最新一幀",
|
||||
"Forecast · valid {valid} · issued {issued}": "預報 · 有效時間 {valid} · 發布時間 {issued}",
|
||||
"{detail} · Does not follow history": "{detail} · 不隨觀測歷史變化",
|
||||
"Forecast · valid {valid}": "預報 · 有效時間 {valid}",
|
||||
@@ -3526,6 +3522,31 @@
|
||||
"Reload": "重新加載",
|
||||
"Retry": "重試",
|
||||
"Reset view": "重置視圖",
|
||||
"Trolleybus": "無軌電車",
|
||||
"Cable car": "纜索電車",
|
||||
"Monorail": "單軌列車",
|
||||
"Funicular": "纜索鐵路",
|
||||
"Gondola": "纜車",
|
||||
"Move panels back beside the rail": "將面板移回側欄旁",
|
||||
"Move panels over the rail, to the edge": "將面板移到側欄上方,貼齊邊緣",
|
||||
"panel|VISUAL": "視覺",
|
||||
"Look": "外觀",
|
||||
"Overlay": "疊加層",
|
||||
"Effects": "效果",
|
||||
"Scope opacity": "視域不透明度",
|
||||
"How dark the scope shades the view outside the keyhole": "視域遮罩使視域之外的畫面變暗的程度",
|
||||
"Reset to default": "還原預設",
|
||||
"Reset Visual to its defaults: Normal look, HUD, scope, labels and effects": "將視覺還原為預設設定:常規外觀、HUD、視域、標籤和效果",
|
||||
"All layers": "全部圖層",
|
||||
"On": "已開啟",
|
||||
"Off": "已關閉",
|
||||
"Search layers": "搜尋圖層",
|
||||
"Filter layers": "篩選圖層",
|
||||
"Status": "狀態",
|
||||
"Search layers…": "搜尋圖層…",
|
||||
"Layer groups": "圖層分組",
|
||||
"Jump to {name}": "跳至{name}",
|
||||
"No layers match": "沒有符合的圖層",
|
||||
"ISS live video": "國際太空站直播影片",
|
||||
"ISS LIVE · NASA": "國際太空站直播 · NASA",
|
||||
"Open on YouTube": "在 YouTube 上開啟",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { test, afterEach } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
onLocaleChange,
|
||||
setLocale,
|
||||
setMessageOverrides,
|
||||
t,
|
||||
tn,
|
||||
translateKnown,
|
||||
} from './index.js';
|
||||
import * as page from './page.js';
|
||||
|
||||
afterEach(() => {
|
||||
setMessageOverrides({});
|
||||
setLocale('en');
|
||||
});
|
||||
|
||||
test('a host shows its own text for a Core message, in English and each locale', () => {
|
||||
setMessageOverrides({
|
||||
en: { 'Download scene JSON': 'Download scene file' },
|
||||
de: { 'Download scene JSON': 'Szenendatei herunterladen' },
|
||||
});
|
||||
assert.equal(t('Download scene JSON'), 'Download scene file');
|
||||
setLocale('de');
|
||||
assert.equal(t('Download scene JSON'), 'Szenendatei herunterladen');
|
||||
// A locale the host did not word shows the host's English, not Core's text.
|
||||
setLocale('fr');
|
||||
assert.equal(t('Download scene JSON'), 'Download scene file');
|
||||
// Messages it does not name stay Core's.
|
||||
assert.equal(t('Share selected scene'), 'Partager la scène sélectionnée');
|
||||
});
|
||||
|
||||
test('overrides interpolate, take contexts and plurals, and reach translateKnown', () => {
|
||||
setMessageOverrides({
|
||||
en: {
|
||||
'Imported {file}': 'Opened {file}',
|
||||
'action|CLEAR': 'WIPE',
|
||||
'{count} cameras': { one: '{count} feed', other: '{count} feeds' },
|
||||
},
|
||||
});
|
||||
assert.equal(t('Imported {file}', { file: 'a.zip' }), 'Opened a.zip');
|
||||
assert.equal(t('CLEAR', { context: 'action' }), 'WIPE');
|
||||
assert.equal(t('CLEAR'), 'CLEAR');
|
||||
assert.equal(tn(1, '{count} camera', '{count} cameras'), '1 feed');
|
||||
assert.equal(tn(3, '{count} camera', '{count} cameras'), '3 feeds');
|
||||
assert.equal(translateKnown('Imported {file}'), 'Opened {file}');
|
||||
// English forms follow English plural rules in any locale.
|
||||
for (const locale of ['ru', 'zh-CN', 'fr']) {
|
||||
setLocale(locale);
|
||||
assert.equal(tn(1, '{count} camera', '{count} cameras'), '1 feed');
|
||||
assert.equal(tn(21, '{count} camera', '{count} cameras'), '21 feeds');
|
||||
assert.equal(tn(0, '{count} camera', '{count} cameras'), '0 feeds');
|
||||
}
|
||||
});
|
||||
|
||||
test('an entry of the wrong kind is ignored, and Core translates', () => {
|
||||
setLocale('ru');
|
||||
const core = {
|
||||
t: t('Share selected scene'),
|
||||
tn: tn(3, '{count} camera', '{count} cameras'),
|
||||
};
|
||||
setMessageOverrides({
|
||||
en: { 'Share selected scene': {}, '{count} cameras': 'cams' },
|
||||
});
|
||||
assert.equal(t('Share selected scene'), core.t);
|
||||
assert.equal(tn(3, '{count} camera', '{count} cameras'), core.tn);
|
||||
});
|
||||
|
||||
test('each call replaces the overrides, words listeners again, and ignores junk', () => {
|
||||
let calls = 0;
|
||||
const stop = onLocaleChange(() => calls++);
|
||||
setMessageOverrides({
|
||||
en: { EXPORT: 'SAVE' },
|
||||
xx: { EXPORT: 'no' },
|
||||
de: null,
|
||||
});
|
||||
assert.equal(t('EXPORT'), 'SAVE');
|
||||
setMessageOverrides({ en: { IMPORT: 'OPEN' } });
|
||||
assert.equal(t('EXPORT'), 'EXPORT');
|
||||
assert.equal(t('IMPORT'), 'OPEN');
|
||||
// An empty entry counts as none.
|
||||
setMessageOverrides({ en: { IMPORT: '' } });
|
||||
assert.equal(t('IMPORT'), 'IMPORT');
|
||||
assert.equal(calls, 3);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('the package entry exports the translator and the overrides', () => {
|
||||
for (const name of [
|
||||
't',
|
||||
'tn',
|
||||
'msg',
|
||||
'translateKnown',
|
||||
'setMessageOverrides',
|
||||
'formatNumber',
|
||||
])
|
||||
assert.equal(typeof page[name], 'function', name);
|
||||
});
|
||||
+15
-1
@@ -5,7 +5,9 @@
|
||||
* page) instead of the globe picker. It starts the language the standalone
|
||||
* application starts, keeps `<html lang>`/`<html dir>` and the page's
|
||||
* `data-i18n` markup in step, and switches in place, stored for the next
|
||||
* visit, exactly as the picker does. Guide: docs/I18N.md.
|
||||
* visit, exactly as the picker does. It also exports the translator itself,
|
||||
* and lets the application show its own text for Core's messages
|
||||
* (`setMessageOverrides`). Guide: docs/I18N.md.
|
||||
*/
|
||||
import {
|
||||
DEFAULT_LOCALE,
|
||||
@@ -33,6 +35,18 @@ export {
|
||||
isRtlLocale,
|
||||
onLocaleChange,
|
||||
};
|
||||
// The translator Core's own text goes through, for an application's text and
|
||||
// for showing its own wording of Core's messages (setMessageOverrides).
|
||||
export {
|
||||
formatDate,
|
||||
formatNumber,
|
||||
formatRelativeTime,
|
||||
msg,
|
||||
setMessageOverrides,
|
||||
t,
|
||||
tn,
|
||||
translateKnown,
|
||||
} from './index.js';
|
||||
|
||||
/**
|
||||
* Start the page in its language: `?lang=`, then the stored choice, then the
|
||||
|
||||
@@ -113,6 +113,7 @@
|
||||
"Layout",
|
||||
"Live",
|
||||
"London",
|
||||
"Look",
|
||||
"Los Angeles",
|
||||
"MIL",
|
||||
"MINI",
|
||||
@@ -140,6 +141,7 @@
|
||||
"Oldies",
|
||||
"OpenStreetMap + optional Google Maps Places",
|
||||
"Operator",
|
||||
"Overlay",
|
||||
"PAUSE",
|
||||
"PLAY",
|
||||
"POS: LIVE",
|
||||
@@ -250,6 +252,7 @@
|
||||
"OPT-IN",
|
||||
"{minutes} min",
|
||||
"1 min/s",
|
||||
"Status",
|
||||
"ISS LIVE · NASA"
|
||||
],
|
||||
"es": [
|
||||
@@ -292,6 +295,7 @@
|
||||
"FOV {value}°",
|
||||
"FT",
|
||||
"Folk",
|
||||
"Funicular",
|
||||
"Funk",
|
||||
"GEO",
|
||||
"GOOGLE STREET VIEW",
|
||||
@@ -383,6 +387,7 @@
|
||||
"mph",
|
||||
"nominal",
|
||||
"panel",
|
||||
"panel|VISUAL",
|
||||
"view band|GLOBAL",
|
||||
"voice|ERROR",
|
||||
"{hours} h",
|
||||
@@ -413,6 +418,7 @@
|
||||
"NORAD: {id}",
|
||||
"Regional",
|
||||
"{datasets} · {tiles} · {packs}",
|
||||
"VIRTUAL",
|
||||
"Manual"
|
||||
],
|
||||
"fr": [
|
||||
@@ -502,6 +508,7 @@
|
||||
"MINI",
|
||||
"MISSION",
|
||||
"MM",
|
||||
"Monorail",
|
||||
"MSG/S",
|
||||
"Metal",
|
||||
"Minimal",
|
||||
@@ -572,6 +579,7 @@
|
||||
"TAGS · {tags}",
|
||||
"TEMP",
|
||||
"TLE",
|
||||
"Trolleybus",
|
||||
"TYPE",
|
||||
"Tallinn",
|
||||
"Techno",
|
||||
@@ -730,6 +738,7 @@
|
||||
"ON",
|
||||
"ON/OFF",
|
||||
"Oldies",
|
||||
"Overlay",
|
||||
"PAYLOAD",
|
||||
"PLAY",
|
||||
"POS: LIVE",
|
||||
@@ -951,6 +960,7 @@
|
||||
"FOV {value}°",
|
||||
"FT",
|
||||
"Folk",
|
||||
"Funicular",
|
||||
"Funk",
|
||||
"GEO",
|
||||
"GOOGLE STREET VIEW",
|
||||
@@ -1044,6 +1054,7 @@
|
||||
"mini",
|
||||
"mph",
|
||||
"nominal",
|
||||
"panel|VISUAL",
|
||||
"via {source}",
|
||||
"view band|GLOBAL",
|
||||
"{hours} h",
|
||||
@@ -1070,6 +1081,7 @@
|
||||
"MMSI: {id}",
|
||||
"NORAD: {id}",
|
||||
"Regional",
|
||||
"VIRTUAL",
|
||||
"Manual"
|
||||
],
|
||||
"ru": [
|
||||
@@ -1268,6 +1280,7 @@
|
||||
"ICAO: {id}",
|
||||
"NORAD: {id}",
|
||||
"MMSI: {id}",
|
||||
"Status",
|
||||
"ISS LIVE · NASA"
|
||||
],
|
||||
"uk": [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
import {
|
||||
EARTHQUAKE_OVERLAY_SOURCE_ID,
|
||||
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
createEarthquakeOverlayEntry,
|
||||
selectEarthquakeOverlayCohort,
|
||||
mapAnalystRecord,
|
||||
earthquakeCoverage,
|
||||
} from './model.js';
|
||||
export * from './model.js';
|
||||
export { createUsgsEarthquakeSource } from './source.js';
|
||||
@@ -27,6 +29,21 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
let _lastUpdate = null;
|
||||
let _lastError = null;
|
||||
let _enabled = false;
|
||||
// The quakes last drawn, as the timeline reads them
|
||||
// ({ mag, time, place, usgsId }).
|
||||
let _events = [];
|
||||
let _uncover = null;
|
||||
// The marks last told to the clock, so a refresh with the same strong
|
||||
// quakes does not tell it again.
|
||||
let _marksKey = null;
|
||||
const coverage = () => (_enabled ? earthquakeCoverage(_events) : null);
|
||||
const coverageChanged = () => {
|
||||
const covered = coverage();
|
||||
const key = covered ? JSON.stringify(covered.marks) : null;
|
||||
if (key === _marksKey) return;
|
||||
_marksKey = key;
|
||||
worldClock.coverageChanged();
|
||||
};
|
||||
|
||||
const layer = {
|
||||
id: 'earthquakes',
|
||||
@@ -41,6 +58,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
_dataSource = new Cesium.CustomDataSource('earthquakes');
|
||||
_dataSource.show = false;
|
||||
viewer.dataSources.add(_dataSource);
|
||||
// While on, the strong quakes are marks on the world clock's timeline.
|
||||
// Registered once; off, the layer has no time to show.
|
||||
_marksKey = null;
|
||||
_uncover = worldClock.register({ id: 'earthquakes', coverage });
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
@@ -55,6 +76,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
// layer has no per-frame animator to keep the render loop alive for.
|
||||
if (_dataSource) _dataSource.show = true;
|
||||
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
|
||||
coverageChanged();
|
||||
},
|
||||
|
||||
disable(viewer) {
|
||||
@@ -64,6 +86,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
if (_dataSource) _dataSource.show = false;
|
||||
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
|
||||
coverageChanged();
|
||||
},
|
||||
|
||||
async update(viewer) {
|
||||
@@ -77,6 +100,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
return false;
|
||||
|
||||
const nextEntities = [];
|
||||
const nextEvents = [];
|
||||
let count = 0;
|
||||
const overlayEntries = [];
|
||||
|
||||
@@ -91,6 +115,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
time,
|
||||
} of rows) {
|
||||
count++;
|
||||
nextEvents.push({ mag, time, place, usgsId });
|
||||
const baseRadius = Math.pow(2, mag) * 1000;
|
||||
const color = depthColor(depthKm || 0);
|
||||
const isSignificant = mag >= 5.0;
|
||||
@@ -137,6 +162,8 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
|
||||
_dataSource.entities.removeAll();
|
||||
for (const entity of nextEntities) _dataSource.entities.add(entity);
|
||||
_events = nextEvents;
|
||||
coverageChanged();
|
||||
if (_enabled) {
|
||||
overlayHost.setEntries(
|
||||
EARTHQUAKE_OVERLAY_SOURCE_ID,
|
||||
@@ -176,6 +203,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
viewer.dataSources.remove(_dataSource, true);
|
||||
_dataSource = null;
|
||||
}
|
||||
_events = [];
|
||||
_uncover?.();
|
||||
_uncover = null;
|
||||
_marksKey = null;
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
|
||||
@@ -3,6 +3,64 @@ export const EARTHQUAKE_OVERLAY_SOURCE_ID = 'earthquakes';
|
||||
export const EARTHQUAKE_OVERLAY_COHORT_LIMIT = 96;
|
||||
export const EARTHQUAKE_OVERLAY_COLLISION_CAPACITY = 48;
|
||||
|
||||
/**
|
||||
* The smallest magnitude the timeline marks. Most quakes are small shakes;
|
||||
* M6 and up come about once every two days worldwide, so each is an event
|
||||
* worth stepping to. The map still draws every quake.
|
||||
*/
|
||||
export const EARTHQUAKE_MARK_MAGNITUDE = 6;
|
||||
|
||||
/** The longest place a timeline mark's label carries, ellipsis and all. */
|
||||
const MARK_PLACE_LENGTH = 40;
|
||||
|
||||
/** A magnitude as the map's labels show it: `M6.4`. */
|
||||
export const earthquakeMagnitudeTitle = (magnitude) =>
|
||||
`M${Number(magnitude).toFixed(1)}`;
|
||||
|
||||
/**
|
||||
* A strong quake's timeline label: its magnitude and, where the feed names
|
||||
* one, its place, cut short (`M6.4 · 113 km SSE of Lata, Solomon Islands`).
|
||||
* @param {{mag: number, place?: string | null}} event
|
||||
* @returns {string}
|
||||
*/
|
||||
export function earthquakeMarkLabel({ mag, place }) {
|
||||
const title = earthquakeMagnitudeTitle(mag);
|
||||
const where =
|
||||
typeof place === 'string' ? place.replace(/\s+/g, ' ').trim() : '';
|
||||
if (!where) return title;
|
||||
const short =
|
||||
where.length > MARK_PLACE_LENGTH
|
||||
? `${where.slice(0, MARK_PLACE_LENGTH - 1).trimEnd()}…`
|
||||
: where;
|
||||
return `${title} · ${short}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The time a world clock's timeline can show for `events` (`{mag, time,
|
||||
* place?, usgsId?}`, time in ms): the span of the quakes of
|
||||
* EARTHQUAKE_MARK_MAGNITUDE and up, each one a mark labelled with its
|
||||
* magnitude and place, or null with none, so the layer never stretches the
|
||||
* timeline past what its feed covers.
|
||||
* @returns {{start: number, end: number, marks: Array<{time: number, label: string, id?: string, kind: string}>} | null}
|
||||
*/
|
||||
export function earthquakeCoverage(events) {
|
||||
const marks = events
|
||||
.filter(
|
||||
({ mag, time }) =>
|
||||
mag >= EARTHQUAKE_MARK_MAGNITUDE && Number.isFinite(time),
|
||||
)
|
||||
.map((event) => ({
|
||||
time: event.time,
|
||||
label: earthquakeMarkLabel(event),
|
||||
...(event.usgsId ? { id: String(event.usgsId) } : {}),
|
||||
kind: 'earthquake',
|
||||
}))
|
||||
.sort((a, b) => a.time - b.time);
|
||||
return marks.length
|
||||
? { start: marks[0].time, end: marks.at(-1).time, marks }
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Color by depth:
|
||||
* - Shallow (<70km): Red
|
||||
@@ -37,7 +95,7 @@ export function createEarthquakeOverlayEntry({
|
||||
id: String(id),
|
||||
position,
|
||||
variant: 'label',
|
||||
title: `M${mag.toFixed(1)}`,
|
||||
title: earthquakeMagnitudeTitle(mag),
|
||||
accent,
|
||||
priority: Math.round(mag * 1000),
|
||||
collisionGroup: 'ambient-label',
|
||||
|
||||
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createEarthquakesLayer } from './index.js';
|
||||
import { createUsgsEarthquakeSource } from './source.js';
|
||||
import { EARTHQUAKE_MARK_MAGNITUDE, earthquakeMarkLabel } from './model.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
function harness(source) {
|
||||
const sources = [];
|
||||
const events = [];
|
||||
@@ -88,3 +90,71 @@ test('USGS body completion honors cancellation even with an uncooperative transp
|
||||
name: 'AbortError',
|
||||
});
|
||||
});
|
||||
test('the timeline marks only strong quakes, while the layer is on', async () => {
|
||||
assert.equal(EARTHQUAKE_MARK_MAGNITUDE, 6);
|
||||
const rows = [
|
||||
{ ...row, stableId: 'small', mag: 4.5, time: 1_000 },
|
||||
{ ...row, stableId: 'strong', usgsId: 'us-strong', mag: 6, time: 5_000 },
|
||||
{
|
||||
...row,
|
||||
stableId: 'great',
|
||||
usgsId: 'us-great',
|
||||
mag: 7.2,
|
||||
place: ' 113 km SSE of Lata, Solomon Islands region of the Pacific ',
|
||||
time: 3_000,
|
||||
},
|
||||
{ ...row, stableId: 'untimed', mag: 6.5, time: null },
|
||||
];
|
||||
let snapshot = rows;
|
||||
const h = harness({ getSnapshot: async () => snapshot });
|
||||
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
|
||||
let changes = 0;
|
||||
const unsubscribe = worldClock.subscribe(() => changes++);
|
||||
await h.layer.update(h.viewer);
|
||||
// Every quake is drawn; only M6 and up are marks, spanning their own time.
|
||||
assert.equal(h.sources[0].entities.values.length, 4);
|
||||
// Each labelled with its magnitude and, cut short, its place.
|
||||
assert.deepEqual(worldClock.coverage(), {
|
||||
start: 3_000,
|
||||
end: 5_000,
|
||||
marks: [3_000, 5_000],
|
||||
markDetails: [
|
||||
{
|
||||
time: 3_000,
|
||||
label: 'M7.2 · 113 km SSE of Lata, Solomon Islands reg…',
|
||||
id: 'us-great',
|
||||
kind: 'earthquake',
|
||||
},
|
||||
{
|
||||
time: 5_000,
|
||||
label: 'M6.0 · Fixture',
|
||||
id: 'us-strong',
|
||||
kind: 'earthquake',
|
||||
},
|
||||
],
|
||||
});
|
||||
const told = changes;
|
||||
await h.layer.update(h.viewer);
|
||||
assert.equal(changes, told, 'the same strong quakes are not told again');
|
||||
snapshot = rows.slice(0, 1);
|
||||
await h.layer.update(h.viewer);
|
||||
assert.equal(worldClock.coverage(), null, 'small shakes alone cover no time');
|
||||
snapshot = rows;
|
||||
await h.layer.update(h.viewer);
|
||||
h.layer.disable(h.viewer);
|
||||
assert.equal(worldClock.coverage(), null, 'off, no time to show');
|
||||
h.layer.enable(h.viewer);
|
||||
assert.deepEqual(worldClock.coverage().marks, [3_000, 5_000]);
|
||||
h.layer.destroy();
|
||||
assert.equal(worldClock.coverage(), null);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('a strong quake with no place is labelled with its magnitude alone', () => {
|
||||
assert.equal(earthquakeMarkLabel({ mag: 6.44, place: null }), 'M6.4');
|
||||
assert.equal(earthquakeMarkLabel({ mag: 6, place: ' ' }), 'M6.0');
|
||||
assert.equal(
|
||||
earthquakeMarkLabel({ mag: 8.1, place: 'Off the coast' }),
|
||||
'M8.1 · Off the coast',
|
||||
);
|
||||
});
|
||||
@@ -31,7 +31,8 @@ export function createCards({
|
||||
function rebuildAmbientLabels() {
|
||||
if (!layerState._viewer) return;
|
||||
const scene = layerState._viewer.scene;
|
||||
const now = Date.now();
|
||||
// Ages count back from the time shown: the window's end, or now when live.
|
||||
const now = components.model.ageReferenceMs();
|
||||
const entries = [];
|
||||
/** @type {Array<{x: number, y: number}>} Screen positions of accepted labels. */
|
||||
const accepted = [];
|
||||
|
||||
@@ -343,7 +343,7 @@ export function createModel({
|
||||
* (on top) and never distance-faded by the overlay.
|
||||
* Exported for unit tests.
|
||||
* @param {Object} fire - Detection record.
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {number} nowMs - Epoch milliseconds ages count back from.
|
||||
* @returns {Object} firmsLabels entry.
|
||||
*/
|
||||
|
||||
@@ -384,9 +384,10 @@ export function createModel({
|
||||
* Card model for an ambient fire detection, e.g. title "▲ 47 MW", detail
|
||||
* "high · 14h · N20". Ages are computed against each detection's acquisition
|
||||
* time — with the live feed everything reads under 24 h (and a stale cache
|
||||
* reads truthfully old). Exported for unit tests.
|
||||
* reads truthfully old); `nowMs` is the time ages count back from, the end
|
||||
* of the window shown (see {@link ageReferenceMs}). Exported for unit tests.
|
||||
* @param {{fire: Object, position: Cesium.Cartesian3}} candidate - Label candidate.
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {number} nowMs - Epoch milliseconds ages count back from.
|
||||
* @returns {Object} firmsLabels entry.
|
||||
*/
|
||||
|
||||
@@ -418,7 +419,7 @@ export function createModel({
|
||||
* "max 210 MW · new 3h". Accent comes from the candidate (renderHeat sets
|
||||
* it with {@link cellCardAccent}). Exported for unit tests.
|
||||
* @param {{cell: Object, position: Cesium.Cartesian3, accent: string}} candidate
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {number} nowMs - Epoch milliseconds ages count back from.
|
||||
* @returns {Object} firmsLabels entry.
|
||||
*/
|
||||
|
||||
@@ -549,6 +550,19 @@ export function createModel({
|
||||
return { unit: 'd', count: Math.round(hours / 24) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The time a card's ages count back from: the end of the 24 hours shown
|
||||
* when the snapshot ends at a set time, now while it runs to now. A window
|
||||
* that ended months ago then reads its fires as hours old, as they were.
|
||||
* @param {number} [nowMs] - Current epoch milliseconds.
|
||||
* @returns {number}
|
||||
*/
|
||||
|
||||
function ageReferenceMs(nowMs = Date.now()) {
|
||||
const at = layerState?._at;
|
||||
return Number.isFinite(at) ? at : nowMs;
|
||||
}
|
||||
|
||||
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
|
||||
|
||||
function formatAge(deltaMs) {
|
||||
@@ -624,6 +638,7 @@ export function createModel({
|
||||
cellCardAccent,
|
||||
formatLatLon,
|
||||
formatFrp,
|
||||
ageReferenceMs,
|
||||
formatAge,
|
||||
formatAgeLabel,
|
||||
formatAgoMinutes,
|
||||
|
||||
@@ -202,7 +202,9 @@ export function createSelection({
|
||||
confidence: components.model.confidenceBucket(fire.confidence),
|
||||
age:
|
||||
fire.acqMs > 0
|
||||
? components.model.formatAge(Date.now() - fire.acqMs)
|
||||
? components.model.formatAge(
|
||||
components.model.ageReferenceMs() - fire.acqMs,
|
||||
)
|
||||
: 'unknown',
|
||||
sensor: fire.sensor || 'unknown',
|
||||
},
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { getLocale, setLocale } from '../../i18n/index.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createCards } from './cards.js';
|
||||
|
||||
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
|
||||
const now = 1800000000000;
|
||||
@@ -42,3 +44,54 @@ test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (conte
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
});
|
||||
|
||||
test('fire cards count ages from the end of the window shown, and from now when live', (context) => {
|
||||
const now = Date.UTC(2026, 10, 14, 12);
|
||||
context.mock.method(Date, 'now', () => now);
|
||||
// A window that ended months before now: its newest fire three hours earlier.
|
||||
const at = Date.UTC(2026, 7, 1, 12);
|
||||
const layerState = { _at: at };
|
||||
const model = createModel({ layerState, services: { anchors: {} } });
|
||||
const cell = {
|
||||
count: 4,
|
||||
maxFrp: 210,
|
||||
newestAcqMs: at - 3 * 3_600_000,
|
||||
latCell: 1,
|
||||
lonCell: 2,
|
||||
};
|
||||
const previousLocale = getLocale();
|
||||
try {
|
||||
setLocale('en');
|
||||
assert.equal(model.ageReferenceMs(), at);
|
||||
const card = model.buildCellCard({ cell, position: {} }, model.ageReferenceMs());
|
||||
assert.equal(card.details[0], 'max 210 MW · new 3h', 'not months old');
|
||||
|
||||
// The cards the scene shows use the same time.
|
||||
const entries = [];
|
||||
context.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 400, y: 300 }));
|
||||
layerState._viewer = { scene: { canvas: { clientWidth: 800, clientHeight: 600 } } };
|
||||
layerState._fireByCardId = new Map();
|
||||
layerState._selectedFire = null;
|
||||
layerState._labelCandidates = [{ cell, position: {} }];
|
||||
layerState._labelLodDistance = 0;
|
||||
const { rebuildAmbientLabels } = createCards({
|
||||
layerState,
|
||||
services: {},
|
||||
components: { model, rendering: { fireHorizonOccluder: () => null } },
|
||||
config: { overlayHost: { setEntries: (source, shown) => entries.push(...shown) } },
|
||||
});
|
||||
rebuildAmbientLabels();
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].details[0], 'max 210 MW · new 3h');
|
||||
|
||||
// Live, they count from now.
|
||||
layerState._at = null;
|
||||
cell.newestAcqMs = now - 5 * 3_600_000;
|
||||
assert.equal(model.ageReferenceMs(), now);
|
||||
entries.length = 0;
|
||||
rebuildAmbientLabels();
|
||||
assert.equal(entries[0].details[0], 'max 210 MW · new 5h');
|
||||
} finally {
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
});
|
||||
@@ -1,14 +1,20 @@
|
||||
import { forgetPlacedAircraft } from './placed.js';
|
||||
|
||||
/**
|
||||
* What the layer drops when the world clock moves it to another time (its
|
||||
* source declares a timeline; see src/time/snapshotTimeline.js).
|
||||
*/
|
||||
export function createClockFollow({ flightState, parts }) {
|
||||
export function createClockFollow({ flightState, services, parts }) {
|
||||
/**
|
||||
* Forget how every contact moved, before the snapshot at another time takes
|
||||
* the place of every contact: their fixes, courses, floors and the tracked
|
||||
* trail belong to the time the clock left.
|
||||
*/
|
||||
function resetMotion() {
|
||||
forgetPlacedAircraft(
|
||||
services?.placement,
|
||||
flightState._positionHistory.keys(),
|
||||
);
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
|
||||
@@ -217,6 +217,25 @@ test('a jump forgets how contacts moved; clearing drops every contact', () => {
|
||||
assert.ok(calls.includes('model:abc123'));
|
||||
});
|
||||
|
||||
test('leaving the live edge forgets every contact a host placement was told of', () => {
|
||||
const forgotten = [];
|
||||
const flightState = {
|
||||
records: records(),
|
||||
_positionHistory: new Map([
|
||||
['abc123', []],
|
||||
['def456', []],
|
||||
]),
|
||||
_displayCourse: new Map(),
|
||||
_groundSnap: { clear() {} },
|
||||
_displayFloorState: new Map(),
|
||||
};
|
||||
const parts = { tracking: { _clearTrail() {} } };
|
||||
const services = { placement: { forget: (id) => forgotten.push(id) } };
|
||||
createClockFollow({ flightState, services, parts }).resetMotion();
|
||||
assert.deepEqual(forgotten, ['abc123', 'def456']);
|
||||
assert.equal(flightState._positionHistory.size, 0);
|
||||
});
|
||||
|
||||
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
|
||||
@@ -35,6 +35,7 @@ export function createCivilFlightLayer({
|
||||
parts.clockFollow = createClockFollow(context);
|
||||
const applySnapshot = createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
placement: services.placement ?? null,
|
||||
records: flightState.records,
|
||||
militaryRegistry: services.militaryRegistry,
|
||||
groundFloor: services.groundFloor,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
import { forgetPlacedAircraft } from './placed.js';
|
||||
|
||||
export function createLifecycle({
|
||||
flightState,
|
||||
@@ -72,6 +73,10 @@ export function createLifecycle({
|
||||
flightState._cullPositions.clear();
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map();
|
||||
forgetPlacedAircraft(
|
||||
services.placement,
|
||||
flightState._positionHistory.keys(),
|
||||
);
|
||||
flightState._positionHistory = new Map();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
@@ -291,6 +296,10 @@ export function createLifecycle({
|
||||
flightState._cullPositions.clear();
|
||||
flightState._detectionObjects.clear();
|
||||
flightState.records.data.clear();
|
||||
forgetPlacedAircraft(
|
||||
services.placement,
|
||||
flightState._positionHistory.keys(),
|
||||
);
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { aircraftModelSpec, fleetModelSet } from '../../data/fleetModels.js';
|
||||
import { MODEL_COLOR_BLEND_AMOUNT } from './policy.js';
|
||||
import {
|
||||
aircraftCallsignRule,
|
||||
aircraftModelByCallsign,
|
||||
aircraftModelSpec,
|
||||
fleetModelSet,
|
||||
} from '../../data/fleetModels.js';
|
||||
|
||||
/**
|
||||
* What an aircraft draws with before the fleet model set has loaded: no
|
||||
@@ -17,7 +21,6 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
|
||||
bellyM: 0,
|
||||
elevationM: 0,
|
||||
tinted: false,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: Object.freeze([0, 0, 0]),
|
||||
trailAnchorNative: Object.freeze([0, 0, 0]),
|
||||
key: 'unloaded',
|
||||
@@ -25,12 +28,14 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
|
||||
|
||||
/**
|
||||
* The fleet model, life-size scale and measured geometry an aircraft draws
|
||||
* with, chosen by its ICAO type and emitter category (`fleetModels.js`).
|
||||
* with, chosen by its ICAO type and emitter category, and by its callsign
|
||||
* for the types that pick by callsign (`fleetModels.js`).
|
||||
* Shared by the Flights, Military Flights and Local ADS-B layers so all three
|
||||
* draw the same model for the same aircraft. `bellyM` is the model's scaled
|
||||
* clearance: how far a grounded aircraft's origin stands above the ground.
|
||||
* @param {{typeCode?: string|null, type?: string|null,
|
||||
* category?: string|number|null}|null|undefined} aircraft
|
||||
* category?: string|number|null,
|
||||
* callsign?: string|null}|null|undefined} aircraft
|
||||
* @param {object|null} [set] The loaded fleet model set.
|
||||
* @returns {object} The spec, or {@link UNLOADED_AIRCRAFT_MODEL_SPEC} before
|
||||
* the set has loaded.
|
||||
@@ -40,17 +45,17 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
|
||||
// Layers ask on every tick; each type and category is resolved once per set.
|
||||
let cache = specCaches.get(set);
|
||||
if (!cache) specCaches.set(set, (cache = new Map()));
|
||||
const key = aircraftModelSpecCacheKey(aircraft);
|
||||
const key = aircraftModelSpecCacheKey(aircraft, set);
|
||||
let layerSpec = cache.get(key);
|
||||
if (!layerSpec) {
|
||||
const spec = aircraftModelSpec(set, {
|
||||
typeCode: aircraft?.typeCode ?? aircraft?.type ?? null,
|
||||
category: aircraft?.category ?? null,
|
||||
callsign: aircraft?.callsign ?? null,
|
||||
});
|
||||
layerSpec = Object.freeze({
|
||||
...spec,
|
||||
bellyM: spec.clearanceM,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
});
|
||||
cache.set(key, layerSpec);
|
||||
}
|
||||
@@ -61,10 +66,18 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
|
||||
const specCaches = new WeakMap();
|
||||
|
||||
/**
|
||||
* Cache key of an aircraft's model spec: what selects its model.
|
||||
* Cache key of an aircraft's model spec: what selects its model. For a type
|
||||
* that picks its model by callsign (an airport vehicle) the key adds the
|
||||
* rule its callsign matches, or `type` for none, so such a type caches at
|
||||
* most one entry per rule and one for its own model.
|
||||
* @param {object|null|undefined} aircraft
|
||||
* @param {object|null} [set] The loaded fleet model set.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aircraftModelSpecCacheKey(aircraft) {
|
||||
return `${aircraft?.typeCode ?? aircraft?.type ?? ''}|${aircraft?.category ?? ''}`;
|
||||
export function aircraftModelSpecCacheKey(aircraft, set = fleetModelSet()) {
|
||||
const type = aircraft?.typeCode ?? aircraft?.type ?? '';
|
||||
const key = `${type}|${aircraft?.category ?? ''}`;
|
||||
if (!set || !aircraftModelByCallsign(set.types, type)) return key;
|
||||
const rule = aircraftCallsignRule(set.types, type, aircraft?.callsign);
|
||||
return `${key}|${rule >= 0 ? `r${rule}` : 'type'}`;
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
historyBracketIndex,
|
||||
historyUnseenAt,
|
||||
liftGroundedHistory,
|
||||
} from '../../data/timelineHistory.js';
|
||||
import { julianAt } from '../../time/julian.js';
|
||||
import {
|
||||
COURSE_HOLD_SPEED_MPS,
|
||||
@@ -16,6 +21,7 @@ import {
|
||||
COAST_MAX_SPEED_MPS,
|
||||
} from '../../data/motionModel.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { placeLiveAircraft } from './placed.js';
|
||||
import {
|
||||
modelVisualAnchor,
|
||||
modelAnchorWorld,
|
||||
@@ -119,6 +125,7 @@ export function createMotion({
|
||||
info.renderAltitudeM >= floor - 1
|
||||
)
|
||||
continue;
|
||||
const drawnM = info.renderAltitudeM;
|
||||
info.renderAltitudeM = lifted;
|
||||
flightState._cullPositions.delete(icao24); // above the ellipsoid now (or floors say otherwise next poll)
|
||||
const position = Cesium.Cartesian3.fromDegrees(
|
||||
@@ -126,10 +133,12 @@ export function createMotion({
|
||||
info.rawLat,
|
||||
lifted,
|
||||
);
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history?.[history.length - 1];
|
||||
if (newest)
|
||||
newest.position = Cesium.Cartesian3.clone(position, newest.position);
|
||||
liftGroundedHistory(
|
||||
flightState._positionHistory.get(icao24),
|
||||
position,
|
||||
drawnM,
|
||||
lifted,
|
||||
);
|
||||
const bb = flightState._billboards.get(icao24);
|
||||
if (bb) bb.position = position;
|
||||
}
|
||||
@@ -152,6 +161,7 @@ export function createMotion({
|
||||
|
||||
function _deadReckon(icao24, result, sampledRenderTime) {
|
||||
const info = flightState.records.data.get(icao24);
|
||||
flightState._drUnseen = false;
|
||||
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
|
||||
const position = flightState._billboards.get(icao24)?.position;
|
||||
flightState._drCourseDeg = info?.true_track || 0;
|
||||
@@ -173,6 +183,19 @@ export function createMotion({
|
||||
}
|
||||
|
||||
const out = result || new Cesium.Cartesian3();
|
||||
// A host-supplied placement decides where a live contact is drawn; with
|
||||
// none, or no answer for this contact, the layer's own motion below does.
|
||||
if (
|
||||
placeLiveAircraft(
|
||||
flightState,
|
||||
services.placement,
|
||||
icao24,
|
||||
info,
|
||||
history,
|
||||
out,
|
||||
)
|
||||
)
|
||||
return out;
|
||||
// Render one poll interval behind real time so we interpolate between
|
||||
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
|
||||
const renderTime =
|
||||
@@ -184,7 +207,15 @@ export function createMotion({
|
||||
);
|
||||
|
||||
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
|
||||
for (let i = history.length - 1; i >= 1; i--) {
|
||||
// The pair around the render time (and the one before it, for a fix at
|
||||
// exactly that time), found by halving: a contact following the clock
|
||||
// keeps a long history.
|
||||
for (
|
||||
let i = historyBracketIndex(history, renderTime),
|
||||
stop = Math.max(1, i - 1);
|
||||
i >= stop;
|
||||
i--
|
||||
) {
|
||||
const a = history[i - 1];
|
||||
const b = history[i];
|
||||
if (
|
||||
@@ -240,6 +271,9 @@ export function createMotion({
|
||||
// the oldest fix froze the icon; extrapolating the NEWEST fix to wall-clock now made
|
||||
// the icon jump back ~one poll interval the instant interpolation took over.)
|
||||
const oldest = history[0];
|
||||
// Following the clock, a time well before its first fix is before it
|
||||
// was there: the fleet pass hides it.
|
||||
flightState._drUnseen = historyUnseenAt(history, renderTime);
|
||||
const lookbackSec = Cesium.JulianDate.secondsDifference(
|
||||
oldest.time,
|
||||
renderTime,
|
||||
|
||||
@@ -3,8 +3,11 @@ import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createMotion } from './motion.js';
|
||||
import { arcOffsetEnu } from '../../data/motionModel.js';
|
||||
import { createMotion as createMilitaryMotion } from '../military/motion.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import { observeLiveAircraft } from './placed.js';
|
||||
|
||||
function fixture() {
|
||||
function fixture(placement = null) {
|
||||
const flightState = {
|
||||
records: { data: new Map() },
|
||||
_positionHistory: new Map(),
|
||||
@@ -16,7 +19,7 @@ function fixture() {
|
||||
};
|
||||
const motion = createMotion({
|
||||
flightState,
|
||||
services: { groundFloor: {}, camera: {}, focus: {} },
|
||||
services: { groundFloor: {}, camera: {}, focus: {}, placement },
|
||||
parts: {},
|
||||
});
|
||||
return { flightState, motion };
|
||||
@@ -184,3 +187,189 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
|
||||
);
|
||||
assert.equal(reads, 2);
|
||||
});
|
||||
|
||||
/** Two fixes a minute apart, read across the minute from a clock at `start`. */
|
||||
function placedScenario(create, placement, record) {
|
||||
const flightState = {
|
||||
records: { data: new Map() },
|
||||
_positionHistory: new Map(),
|
||||
_focusEvidenceIds: new Set(),
|
||||
_scratchArc: {},
|
||||
_scratchOffset: new Cesium.Cartesian3(),
|
||||
_scratchRenderTime: new Cesium.JulianDate(),
|
||||
now: () => 0,
|
||||
};
|
||||
const motion = create({
|
||||
flightState,
|
||||
services: { groundFloor: {}, camera: {}, focus: {}, placement },
|
||||
parts: {},
|
||||
});
|
||||
const start = Date.parse('2026-10-24T12:00:00Z');
|
||||
const at = (seconds) =>
|
||||
Cesium.JulianDate.fromDate(new Date(start + seconds * 1000));
|
||||
flightState.records.data.set('abc123', record);
|
||||
flightState._positionHistory.set('abc123', [
|
||||
{
|
||||
time: at(0),
|
||||
position: Cesium.Cartesian3.fromDegrees(-97, 30, 1000),
|
||||
track: 90,
|
||||
velocity: 100,
|
||||
},
|
||||
{
|
||||
time: at(60),
|
||||
position: Cesium.Cartesian3.fromDegrees(-96.99, 30, 1000),
|
||||
track: 90,
|
||||
velocity: 100,
|
||||
},
|
||||
]);
|
||||
const drawn = [];
|
||||
for (let seconds = 0; seconds <= 150; seconds += 7.5) {
|
||||
flightState.now = () => start + seconds * 1000;
|
||||
const position = motion._deadReckon('abc123', new Cesium.Cartesian3());
|
||||
drawn.push({
|
||||
position,
|
||||
course: flightState._drCourseDeg,
|
||||
speed: flightState._drSpeedMps,
|
||||
hold: flightState._drCourseHold,
|
||||
});
|
||||
}
|
||||
return { flightState, motion, drawn, start };
|
||||
}
|
||||
|
||||
const declining = (asked) =>
|
||||
layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place: (id, wallMs) => {
|
||||
asked.push([id, wallMs]);
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
},
|
||||
'aircraft',
|
||||
);
|
||||
|
||||
// Each kind's record carries only its own kinematics fields.
|
||||
for (const [name, create, record] of [
|
||||
[
|
||||
'civil',
|
||||
createMotion,
|
||||
{ velocity: 100, true_track: 90, renderAltitudeM: 1234 },
|
||||
],
|
||||
[
|
||||
'military',
|
||||
createMilitaryMotion,
|
||||
{ speedMps: 100, track: 90, renderAltitudeM: 1234 },
|
||||
],
|
||||
]) {
|
||||
test(`${name} aircraft move as before without a placement or with one that places nothing`, () => {
|
||||
const own = placedScenario(create, null, record).drawn;
|
||||
const asked = [];
|
||||
const declined = placedScenario(create, declining(asked), record).drawn;
|
||||
assert.equal(asked.length, own.length);
|
||||
assert.equal(declined.length, own.length);
|
||||
for (let i = 0; i < own.length; i++) {
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.equals(declined[i].position, own[i].position),
|
||||
);
|
||||
assert.equal(declined[i].course, own[i].course);
|
||||
assert.equal(declined[i].speed, own[i].speed);
|
||||
assert.equal(declined[i].hold, own[i].hold);
|
||||
}
|
||||
});
|
||||
|
||||
test(`${name} aircraft are drawn where a placement places them, live only`, () => {
|
||||
const asked = [];
|
||||
const placement = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place(id, wallMs) {
|
||||
asked.push(wallMs);
|
||||
return wallMs % 2 === 0
|
||||
? {
|
||||
lat: 30.5,
|
||||
lon: -96.5,
|
||||
altitudeM: 2000,
|
||||
courseDeg: 45,
|
||||
speedMps: 0.5,
|
||||
extrapolating: true,
|
||||
}
|
||||
: { lat: 30.6, lon: -96.4 };
|
||||
},
|
||||
}),
|
||||
},
|
||||
'aircraft',
|
||||
);
|
||||
const { flightState, motion, start } = placedScenario(
|
||||
create,
|
||||
placement,
|
||||
record,
|
||||
);
|
||||
flightState.now = () => start + 2000;
|
||||
const out = motion._deadReckon('abc123', new Cesium.Cartesian3());
|
||||
close(out, Cesium.Cartesian3.fromDegrees(-96.5, 30.5, 2000));
|
||||
assert.equal(flightState._drCourseDeg, 45);
|
||||
assert.equal(flightState._drSpeedMps, 0.5);
|
||||
assert.equal(flightState._drCourseHold, true);
|
||||
// No height, course or speed placed: the record's drawn height and kinematics.
|
||||
flightState.now = () => start + 2001;
|
||||
close(
|
||||
motion._deadReckon('abc123', new Cesium.Cartesian3()),
|
||||
Cesium.Cartesian3.fromDegrees(-96.4, 30.6, 1234),
|
||||
);
|
||||
assert.equal(flightState._drCourseDeg, 90);
|
||||
assert.equal(flightState._drSpeedMps, 100);
|
||||
// Following the world clock the layer's own motion places it, unasked.
|
||||
const before = asked.length;
|
||||
flightState.timeline = { active: () => true };
|
||||
const own = motion._deadReckon('abc123', new Cesium.Cartesian3());
|
||||
assert.equal(asked.length, before);
|
||||
assert.ok(Cesium.Cartesian3.distance(own, out) > 1000);
|
||||
});
|
||||
}
|
||||
|
||||
test('an aircraft fix is told to the placement live, with its drawn height', () => {
|
||||
const told = [];
|
||||
const placement = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place: () => null,
|
||||
observe: (id, fix) => told.push([id, fix]),
|
||||
}),
|
||||
},
|
||||
'aircraft',
|
||||
);
|
||||
const state = { timeline: { active: () => false } };
|
||||
const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false };
|
||||
observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270);
|
||||
observeLiveAircraft(
|
||||
state,
|
||||
placement,
|
||||
'abc123',
|
||||
6000,
|
||||
{ ...meta, renderAltitudeInvented: true, onGround: true },
|
||||
null,
|
||||
undefined,
|
||||
);
|
||||
observeLiveAircraft(state, null, 'abc123', 7000, meta, 80, 270);
|
||||
state.timeline.active = () => true;
|
||||
observeLiveAircraft(state, placement, 'abc123', 8000, meta, 80, 270);
|
||||
assert.equal(told.length, 2);
|
||||
assert.deepEqual(told[0], [
|
||||
'abc123',
|
||||
{
|
||||
timeMs: 5000,
|
||||
lat: 1,
|
||||
lon: 2,
|
||||
altitudeM: 300,
|
||||
speedMps: 80,
|
||||
courseDeg: 270,
|
||||
headingDeg: NaN,
|
||||
onGround: false,
|
||||
},
|
||||
]);
|
||||
assert.ok(Number.isNaN(told[1][1].altitudeM));
|
||||
assert.ok(Number.isNaN(told[1][1].speedMps));
|
||||
assert.ok(Number.isNaN(told[1][1].courseDeg));
|
||||
assert.equal(told[1][1].onGround, true);
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { COURSE_HOLD_SPEED_MPS } from '../../data/motionModel.js';
|
||||
import { followsClock } from './policy.js';
|
||||
|
||||
/** Scratch for a placed contact's held height. */
|
||||
const _placedCarto = new Cesium.Cartographic();
|
||||
|
||||
/**
|
||||
* Where the host-supplied placement (`services.placement`,
|
||||
* ../../data/placementProvider.js) draws a live aircraft now, written into
|
||||
* `out` with the course scratches `_deadReckon` sets on `flightState`; false
|
||||
* when there is no placement, the layer follows the world clock, or it has
|
||||
* no answer for this aircraft, and the layer's own motion places it. A
|
||||
* placement without a height keeps the aircraft's newest drawn height.
|
||||
* @param {object} flightState The civil or military flight state.
|
||||
* @param {object|null|undefined} placement
|
||||
* @param {string} icao24
|
||||
* @param {object|undefined} info The aircraft's record.
|
||||
* @param {{position: Cesium.Cartesian3}[]} history Its fixes, newest last.
|
||||
* @param {Cesium.Cartesian3} out
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function placeLiveAircraft(
|
||||
flightState,
|
||||
placement,
|
||||
icao24,
|
||||
info,
|
||||
history,
|
||||
out,
|
||||
) {
|
||||
if (!placement || followsClock(flightState)) return false;
|
||||
const placed = placement.place(icao24, flightState.now());
|
||||
if (!placed) return false;
|
||||
let heightM = placed.altitudeM;
|
||||
if (!Number.isFinite(heightM)) heightM = info?.renderAltitudeM;
|
||||
if (!Number.isFinite(heightM))
|
||||
heightM = Cesium.Cartographic.fromCartesian(
|
||||
history[history.length - 1].position,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
_placedCarto,
|
||||
).height;
|
||||
const speed = Number.isFinite(placed.speedMps)
|
||||
? placed.speedMps
|
||||
: // Civil records carry velocity and true_track, military speedMps and track.
|
||||
Number.isFinite(info?.velocity)
|
||||
? info.velocity
|
||||
: info?.speedMps || 0;
|
||||
flightState._drCourseDeg = Number.isFinite(placed.courseDeg)
|
||||
? placed.courseDeg
|
||||
: Number.isFinite(info?.true_track)
|
||||
? info.true_track
|
||||
: info?.track || 0;
|
||||
flightState._drSpeedMps = speed;
|
||||
flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS;
|
||||
flightState._drExtrapolating = placed.extrapolating;
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
placed.lon,
|
||||
placed.lat,
|
||||
heightM,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
out,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the host-supplied placement, if any, that the aircraft `ids` left the
|
||||
* layer (removed, the layer off, or the world clock moved it to another time).
|
||||
* @param {object|null|undefined} placement
|
||||
* @param {Iterable<string>} ids
|
||||
*/
|
||||
export function forgetPlacedAircraft(placement, ids) {
|
||||
if (!placement) return;
|
||||
for (const id of ids) placement.forget(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the host-supplied placement an aircraft's fix as the layer took it
|
||||
* (nothing while the layer follows the world clock): its own time, its
|
||||
* position, the height the layer draws it at (NaN when that height is
|
||||
* invented), and its reported speed, course and ground state.
|
||||
* @param {object} flightState
|
||||
* @param {object|null|undefined} placement
|
||||
* @param {string} icao24
|
||||
* @param {number} fixEpochMs
|
||||
* @param {{rawLat: number, rawLon: number, renderAltitudeM: number,
|
||||
* renderAltitudeInvented?: boolean, onGround?: boolean}} meta
|
||||
* @param {number|null|undefined} speedMps
|
||||
* @param {number|null|undefined} courseDeg
|
||||
*/
|
||||
export function observeLiveAircraft(
|
||||
flightState,
|
||||
placement,
|
||||
icao24,
|
||||
fixEpochMs,
|
||||
meta,
|
||||
speedMps,
|
||||
courseDeg,
|
||||
) {
|
||||
if (!placement || followsClock(flightState)) return;
|
||||
placement.observe(icao24, {
|
||||
timeMs: fixEpochMs,
|
||||
lat: meta.rawLat,
|
||||
lon: meta.rawLon,
|
||||
altitudeM:
|
||||
meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM,
|
||||
speedMps: Number.isFinite(speedMps) ? speedMps : NaN,
|
||||
courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN,
|
||||
headingDeg: NaN,
|
||||
onGround: meta.onGround === true,
|
||||
});
|
||||
}
|
||||
@@ -85,10 +85,6 @@ export const MODEL_ALL_KEEP_M = 450000;
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// every fleet model is nose -X: opposite Cesium heading 0
|
||||
// Owner launch-polish direction: models should read as clean light silhouettes,
|
||||
// with only a weak diffuse contribution from the models' own colours.
|
||||
|
||||
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
|
||||
|
||||
export const CYAN_TRANSPARENT = Cesium.Color.CYAN.withAlpha(0);
|
||||
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { stickyNumber, stickyText } from '../../data/aircraftMeta.js';
|
||||
import { courseFromFixes } from '../../data/courseFromFixes.js';
|
||||
import {
|
||||
geoidSurfaceLastResortM,
|
||||
pickRenderAltitudeM,
|
||||
} from '../../data/renderAltitude.js';
|
||||
import { classifyAircraft } from '../../data/aircraftClass.js';
|
||||
import { aircraftEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
aircraftCallsignRule,
|
||||
aircraftModelSpec,
|
||||
fleetModelSet,
|
||||
} from '../../data/fleetModels.js';
|
||||
import {
|
||||
approxDistanceKm,
|
||||
GROUND_FLOOR_CLAMP_RADIUS_KM,
|
||||
@@ -21,6 +27,7 @@ export class FlightRecords {
|
||||
cachedGroundFloor,
|
||||
floorAltitudeM,
|
||||
now = () => Date.now(),
|
||||
fleetModels = fleetModelSet,
|
||||
}) {
|
||||
this.services = {
|
||||
geoidHeight,
|
||||
@@ -29,6 +36,8 @@ export class FlightRecords {
|
||||
};
|
||||
/** The time records are judged at: the layer's clock. */
|
||||
this.now = now;
|
||||
/** The loaded fleet model set, or null before it loads. */
|
||||
this.fleetModels = fleetModels;
|
||||
this.data = new Map();
|
||||
// Facts about an airframe, not a moment, kept across a reset.
|
||||
this.airframes = new Map();
|
||||
@@ -92,7 +101,6 @@ export class FlightRecords {
|
||||
verticalRateMps: vertical_rate,
|
||||
} = observation;
|
||||
|
||||
const onGround = on_ground === true;
|
||||
this.missingPolls.delete(icao24);
|
||||
// Sticky merge: OpenSky intermittently drops callsign/velocity/track for
|
||||
// aircraft it still positions — hold last-known-good instead of
|
||||
@@ -102,6 +110,27 @@ export class FlightRecords {
|
||||
// The airframe's facts: this record's, or those kept across a reset.
|
||||
const airframe = prevMeta ?? this.airframes.get(icao24);
|
||||
this.airframes.delete(icao24);
|
||||
// A ground vehicle or ground station (a feed's ZVEH or GRND: a model
|
||||
// built standing, catalog category `other`) takes the feed's own type,
|
||||
// which no airframe lookup knows; every other aircraft keeps waiting for
|
||||
// its looked-up type. With no altitude at all it stands on the ground,
|
||||
// where it is, instead of at the airborne default.
|
||||
const groundModel = (typeCode) =>
|
||||
drawnAsGroundModel(
|
||||
this.fleetModels(),
|
||||
typeCode,
|
||||
category,
|
||||
stickyText(callsign, prevMeta?.callsign),
|
||||
);
|
||||
const feedType = observation.typeCode || null;
|
||||
const typeCode =
|
||||
airframe?.typeCode ??
|
||||
(feedType && groundModel(feedType) ? feedType : null);
|
||||
const onGround =
|
||||
on_ground === true ||
|
||||
(!Number.isFinite(baro_alt) &&
|
||||
!Number.isFinite(geo_alt) &&
|
||||
groundModel(typeCode));
|
||||
// Grounded planes with no baro reading sit at 0 m, not the 10 km
|
||||
// airborne default (a parked plane must never float).
|
||||
// NOTE (height-datum fix): `alt` stays the AVIATION field — the sticky
|
||||
@@ -263,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(),
|
||||
@@ -281,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({
|
||||
@@ -319,8 +361,9 @@ export class FlightRecords {
|
||||
prevMeta?.lastContactEpochMs,
|
||||
null,
|
||||
),
|
||||
// adsbdb enrichment — written by the enrichment callbacks, carried across polls:
|
||||
typeCode: airframe?.typeCode ?? null,
|
||||
// adsbdb enrichment — written by the enrichment callbacks, carried
|
||||
// across polls; a ground vehicle's or station's from the feed:
|
||||
typeCode,
|
||||
typeName: airframe?.typeName ?? null,
|
||||
registration: airframe?.registration ?? null,
|
||||
airline: routeHeld ? (airframe.airline ?? null) : null,
|
||||
@@ -408,3 +451,33 @@ export class FlightRecords {
|
||||
this.geoidNCache.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
|
||||
const groundModelCaches = new WeakMap();
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Answered once per type, category and callsign rule matched.
|
||||
* @param {object|null} set The loaded fleet model set.
|
||||
* @param {string|null} typeCode
|
||||
* @param {string|number|null} category
|
||||
* @param {string|null} callsign
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function drawnAsGroundModel(set, typeCode, category, callsign) {
|
||||
if (!set || !typeCode) return false;
|
||||
let cache = groundModelCaches.get(set);
|
||||
if (!cache) groundModelCaches.set(set, (cache = new Map()));
|
||||
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
|
||||
const key = `${typeCode}|${category ?? ''}|${rule}`;
|
||||
let ground = cache.get(key);
|
||||
if (ground === undefined) {
|
||||
ground =
|
||||
aircraftModelSpec(set, { typeCode, category, callsign }).category ===
|
||||
'other';
|
||||
cache.set(key, ground);
|
||||
}
|
||||
return ground;
|
||||
}
|
||||
@@ -1,13 +1,28 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { FlightRecords } from './records.js';
|
||||
|
||||
function records() {
|
||||
const FLEET = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
'../../../public/models/fleet',
|
||||
);
|
||||
const fleetSet = {
|
||||
catalog: JSON.parse(
|
||||
fs.readFileSync(path.join(FLEET, 'catalog.json'), 'utf8'),
|
||||
),
|
||||
types: JSON.parse(fs.readFileSync(path.join(FLEET, 'types.json'), 'utf8')),
|
||||
};
|
||||
|
||||
function records(fleetModels = () => null) {
|
||||
return new FlightRecords({
|
||||
geoidHeight: () => 40,
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
approxDistanceKm: () => 0,
|
||||
fleetModels,
|
||||
});
|
||||
}
|
||||
const view = () => ({
|
||||
@@ -260,3 +275,93 @@ test('a repeated fix time marks the contact as not updated; removal is unchanged
|
||||
store.forget('abc123');
|
||||
assert.equal(store.fixRepeated.has('abc123'), false);
|
||||
});
|
||||
|
||||
test('a ground vehicle or station with no altitude stands on the ground; an aircraft does not', () => {
|
||||
const store = records(() => fleetSet);
|
||||
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
|
||||
const vehicle = store.receive(
|
||||
observation({
|
||||
id: 'v1',
|
||||
typeCode: 'ZVEH',
|
||||
callsign: 'FIRE 2',
|
||||
...noAltitude,
|
||||
}),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(vehicle.onGround, true);
|
||||
assert.equal(vehicle.typeCode, 'ZVEH');
|
||||
assert.equal(vehicle.altitude, 0);
|
||||
const mast = store.receive(
|
||||
observation({ id: 'm1', typeCode: 'GRND', callsign: 'RX5', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(mast.onGround, true);
|
||||
assert.equal(mast.typeCode, 'GRND');
|
||||
// An airliner with no altitude keeps the airborne default, and its feed
|
||||
// type still waits for the airframe lookup.
|
||||
const plane = store.receive(
|
||||
observation({ id: 'p1', typeCode: 'A320', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(plane.onGround, false);
|
||||
assert.equal(plane.altitude, 10000);
|
||||
assert.equal(plane.typeCode, null);
|
||||
// A vehicle reporting an altitude is placed by it.
|
||||
const reported = store.receive(
|
||||
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(reported.onGround, false);
|
||||
// Before the model set loads nothing is grounded by its model.
|
||||
const unloaded = records().receive(
|
||||
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
|
||||
view(),
|
||||
).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);
|
||||
});
|
||||
@@ -45,7 +45,10 @@ import {
|
||||
STALE_ALPHA,
|
||||
displayDelayMs,
|
||||
} from './policy.js';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
|
||||
import {
|
||||
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
aircraftModelBlend,
|
||||
} from '../../data/aircraftModelLighting.js';
|
||||
|
||||
export function createRendering({
|
||||
flightState,
|
||||
@@ -192,11 +195,12 @@ export function createRendering({
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
/** Model tint, mirroring the billboard color rules. */
|
||||
/** Model colour: the mesh's own (white), tinted cyan while tracked and red
|
||||
* while broadcasting an emergency. */
|
||||
|
||||
function _modelColor(icao24) {
|
||||
if (icao24 === flightState._trackedIcao) return Cesium.Color.CYAN;
|
||||
return _fleetBillboardColor(icao24);
|
||||
return _isEmergency(icao24) ? EMERGENCY_TINT : Cesium.Color.WHITE;
|
||||
}
|
||||
|
||||
/** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude
|
||||
@@ -526,10 +530,7 @@ export function createRendering({
|
||||
minimumPixelSize: MODEL_MIN_PX,
|
||||
scale: spec.scale,
|
||||
color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24),
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
// Launch presentation keeps the code-side tint dominant for every approved
|
||||
// model; IR boost removes the remaining diffuse hint with flat UNLIT white.
|
||||
colorBlendAmount: flightState._irBoost ? 1.0 : spec.blendAmount,
|
||||
...aircraftModelBlend(flightState._irBoost),
|
||||
customShader: flightState._irBoost
|
||||
? flightState._IR_UNLIT_SHADER
|
||||
: undefined,
|
||||
@@ -748,10 +749,7 @@ export function createRendering({
|
||||
minimumPixelSize: TRACKED_MODEL_MIN_PX,
|
||||
scale: trackedSpec.scale,
|
||||
color: flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN,
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
// The tracked aircraft uses the same dominant light tint as the fleet;
|
||||
// IR boost removes the remaining diffuse hint with flat UNLIT white.
|
||||
colorBlendAmount: flightState._irBoost ? 1.0 : trackedSpec.blendAmount,
|
||||
...aircraftModelBlend(flightState._irBoost),
|
||||
customShader: flightState._irBoost
|
||||
? flightState._IR_UNLIT_SHADER
|
||||
: undefined,
|
||||
@@ -1034,6 +1032,7 @@ export function createRendering({
|
||||
flightState._scratchFleetPos,
|
||||
renderTime,
|
||||
);
|
||||
const unseen = flightState._drUnseen;
|
||||
// The dead-reckoned point drifts away from the fix whose cell supplied the
|
||||
// height, so a grounded contact's sprite ends up under the mesh it taxied
|
||||
// (or coasted) over. Re-floor at the DISPLAYED coordinate — read-only, and
|
||||
@@ -1059,9 +1058,12 @@ export function createRendering({
|
||||
// sub-ellipsoid point near the limb "beyond the horizon" and the fleet
|
||||
// pass would hide a plane that is really just low over high-N terrain
|
||||
// waiting for its floor to warm (ATL grounded contacts at geoid −31 m).
|
||||
const beyondHorizon = !occluder.isPointVisible(
|
||||
flightState._cullPositions.get(icao24) || bb.position,
|
||||
);
|
||||
// A contact not there yet at the time drawn is hidden as one beyond it.
|
||||
const beyondHorizon =
|
||||
unseen ||
|
||||
!occluder.isPointVisible(
|
||||
flightState._cullPositions.get(icao24) || bb.position,
|
||||
);
|
||||
// A billboard flipping INTO view (horizon reveal while the camera idles)
|
||||
// gets its rotation refreshed THIS tick even without a pose change —
|
||||
// otherwise it reappears wearing its stale (often creation-north) nose for
|
||||
|
||||
@@ -9,10 +9,16 @@ import {
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { observeLiveAircraft } from './placed.js';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from '../../data/timelineHistory.js';
|
||||
|
||||
/** Apply reconciled aircraft records to Cesium resources and follow state. */
|
||||
export function createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
placement = null,
|
||||
records,
|
||||
militaryRegistry,
|
||||
groundFloor,
|
||||
@@ -65,6 +71,7 @@ export function createFlightSnapshotRenderer({
|
||||
flightState._billboards.delete(icao24);
|
||||
rendering._releaseModel(icao24); // military-suppression: drop any 3D model too
|
||||
records.forget(icao24);
|
||||
placement?.forget(icao24);
|
||||
flightState._cullPositions.delete(icao24);
|
||||
flightState._positionHistory.delete(icao24);
|
||||
flightState._displayCourse.delete(icao24);
|
||||
@@ -98,79 +105,116 @@ export function createFlightSnapshotRenderer({
|
||||
);
|
||||
const isTracked = icao24 === flightState._trackedIcao;
|
||||
|
||||
// Append to position history stamped with the FEED's fix epoch
|
||||
// (time_position), not client receipt time — OpenSky positions arrive
|
||||
// 5-15s stale and receipt-time stamping is what caused the
|
||||
// back/forward oscillation. Only append when the fix actually
|
||||
// advances, so stale repeats don't create zero-dt segments.
|
||||
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
history.push({
|
||||
time: fixTime,
|
||||
epochMs: fixEpochMs,
|
||||
position: position.clone(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
if (history.length > POSITION_HISTORY_LIMIT) {
|
||||
history.shift();
|
||||
}
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
|
||||
// so the visible trail keeps growing while tracked. Ground traffic
|
||||
// appends nothing — a touchdown freezes the existing trail.
|
||||
// Round 2 (owner): ground traffic appends too — taxi history stays
|
||||
// live after touchdown (grounded flights positions are already
|
||||
// surface-clamped via the surfaceM chain, so the ground leg drapes).
|
||||
// Following the clock, a record may carry its own track around the
|
||||
// time: the contact is placed on it, so the clock can move within it,
|
||||
// back as well as on, without another snapshot.
|
||||
const timelineHistory = followsClock(flightState)
|
||||
? mergeAircraftTimelineFixes(
|
||||
flightState._positionHistory.get(icao24),
|
||||
observation,
|
||||
meta,
|
||||
meta.velocity,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
)
|
||||
: null;
|
||||
// A host-supplied placement, if any, is told every fix as taken.
|
||||
observeLiveAircraft(
|
||||
flightState,
|
||||
placement,
|
||||
icao24,
|
||||
fixEpochMs,
|
||||
meta,
|
||||
meta.velocity,
|
||||
meta.true_track,
|
||||
);
|
||||
if (timelineHistory) {
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(position.clone(), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
for (const entry of historyAfterTrail(
|
||||
timelineHistory,
|
||||
flightState._trailFixes,
|
||||
snapshot.observedAtMs ?? fixEpochMs,
|
||||
))
|
||||
tracking._appendTrailFix(entry.position.clone(), entry.epochMs, {
|
||||
nullAltitude: entry.inventedHeight,
|
||||
});
|
||||
flightState._positionHistory.set(icao24, timelineHistory);
|
||||
meta.turnRateDps = 0;
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
// Append to position history stamped with the FEED's fix epoch
|
||||
// (time_position), not client receipt time — OpenSky positions arrive
|
||||
// 5-15s stale and receipt-time stamping is what caused the
|
||||
// back/forward oscillation. Only append when the fix actually
|
||||
// advances, so stale repeats don't create zero-dt segments.
|
||||
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
|
||||
if (!flightState._positionHistory.has(icao24)) {
|
||||
flightState._positionHistory.set(icao24, []);
|
||||
}
|
||||
// Apply fresh kinematics only from a forward synthetic fix. Mutating
|
||||
// the historical fix reprojects the entire stale interval and snaps
|
||||
// the rendered aircraft when course or speed changes late. The stale
|
||||
// rules apply: none for a contact that holds at its report, a coast
|
||||
// capped from the real report, never below the ground. It is a motion
|
||||
// aid, not a report, so it never joins the trail.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.velocity || newest.track !== meta.true_track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
const history = flightState._positionHistory.get(icao24);
|
||||
const newest = history[history.length - 1];
|
||||
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
|
||||
// Per-fix kinematics: the fix's own velocity/track ride along so the
|
||||
// extrapolation paths use the values that BELONG to the fix they
|
||||
// extend, not whatever the latest poll reported.
|
||||
history.push({
|
||||
time: fixTime,
|
||||
epochMs: fixEpochMs,
|
||||
position: position.clone(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
// Drawn at an invented height: a trail seeded from history keeps no
|
||||
// position for it.
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
if (history.length > POSITION_HISTORY_LIMIT) {
|
||||
history.shift();
|
||||
}
|
||||
// Turn rate from the fix-track history — computed once per new fix
|
||||
// (≤5 samples), consumed by the extrapolation paths at tick rate.
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
|
||||
// so the visible trail keeps growing while tracked. Ground traffic
|
||||
// appends nothing — a touchdown freezes the existing trail.
|
||||
// Round 2 (owner): ground traffic appends too — taxi history stays
|
||||
// live after touchdown (grounded flights positions are already
|
||||
// surface-clamped via the surfaceM chain, so the ground leg drapes).
|
||||
if (isTracked)
|
||||
tracking._appendTrailFix(position.clone(), fixEpochMs, {
|
||||
nullAltitude: meta.renderAltitudeInvented === true,
|
||||
});
|
||||
} else {
|
||||
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
|
||||
if (!modelOwnsGroundVisual) {
|
||||
liftRepeatedGroundFix(newest, position, meta.onGround);
|
||||
}
|
||||
// Apply fresh kinematics only from a forward synthetic fix. Mutating
|
||||
// the historical fix reprojects the entire stale interval and snaps
|
||||
// the rendered aircraft when course or speed changes late. The stale
|
||||
// rules apply: none for a contact that holds at its report, a coast
|
||||
// capped from the real report, never below the ground. It is a motion
|
||||
// aid, not a report, so it never joins the trail.
|
||||
const kinematicsChanged =
|
||||
newest.velocity !== meta.velocity ||
|
||||
newest.track !== meta.true_track;
|
||||
const holds = staleHoldsForFix(newest, {
|
||||
onGround: meta.onGround,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
if (kinematicsChanged && !holds) {
|
||||
const synthetic = synthesizeForwardKinematicsFix(newest, {
|
||||
// Following the clock, the snapshot's time is the moment it moves on from.
|
||||
epochMs: followsClock(flightState)
|
||||
? snapshot.observedAtMs
|
||||
: Date.now(),
|
||||
velocity: meta.velocity,
|
||||
track: meta.true_track,
|
||||
turnRateDps: meta.turnRateDps,
|
||||
cachedGroundFloor,
|
||||
});
|
||||
if (synthetic) {
|
||||
history.push(synthetic);
|
||||
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
|
||||
meta.turnRateDps = turnRateFromFixHistory(history);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,6 +258,7 @@ export function createFlightSnapshotRenderer({
|
||||
// the raw fix drew it ahead until the next fleet tick snapped it back;
|
||||
// skipping the floor started a taxiing contact low and then raised it.
|
||||
const delayed = motion._deadReckon(icao24, new Cesium.Cartesian3());
|
||||
const unseenAtStart = flightState._drUnseen;
|
||||
const displayed =
|
||||
(delayed &&
|
||||
motion._floorGroundedDisplayPosition(
|
||||
@@ -242,7 +287,9 @@ export function createFlightSnapshotRenderer({
|
||||
// close (_groundDepthDistance).
|
||||
disableDepthTestDistance: rendering._groundDepthDistance(),
|
||||
id: icao24,
|
||||
show: !isTracked, // hidden if currently tracked (entity replaces it)
|
||||
// Hidden if currently tracked (entity replaces it), or not there yet
|
||||
// at the time drawn (see historyUnseenAt).
|
||||
show: !isTracked && !unseenAtStart,
|
||||
});
|
||||
flightState._billboards.set(icao24, bb);
|
||||
rendering._applyFleetBillboardPresentation(icao24, bb);
|
||||
@@ -311,6 +358,7 @@ export function createFlightSnapshotRenderer({
|
||||
flightState._billboards.delete(icao24);
|
||||
rendering._releaseModel(icao24); // aged-out aircraft: drop its 3D model (no orphan / cap leak)
|
||||
records.forget(icao24);
|
||||
placement?.forget(icao24);
|
||||
flightState._cullPositions.delete(icao24);
|
||||
flightState._positionHistory.delete(icao24);
|
||||
flightState._displayCourse.delete(icao24);
|
||||
|
||||
@@ -321,6 +321,11 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drExtrapolating = false;
|
||||
|
||||
/** Set by `_deadReckon`: following the clock, the time drawn is well
|
||||
* before the contact's first fix, so the fleet pass does not draw it. */
|
||||
|
||||
flightState._drUnseen = false;
|
||||
|
||||
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
|
||||
|
||||
flightState._cachedDRCourse = null;
|
||||
|
||||
@@ -1289,6 +1289,7 @@ export function createTracking({
|
||||
flightState._billboards.delete(icao24);
|
||||
parts.rendering._releaseModel(icao24); // military-suppression: drop any 3D model too
|
||||
flightState.records.data.delete(icao24);
|
||||
services.placement?.forget(icao24);
|
||||
flightState._cullPositions.delete(icao24);
|
||||
flightState._positionHistory.delete(icao24);
|
||||
flightState._displayCourse.delete(icao24);
|
||||
|
||||
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user