feat(cockpit): an application can add its own cockpit subjects; the Rail and Transit layers expose the read and hold APIs such a subject needs

GEV itself registers no new subject: with no provider, the Cockpit offers
aircraft, satellites and vessels as before, except that the most recently
selected of them now wins entry.

- services.cockpitSubjects: providers ({kind, layerId, entryFace, priority,
  isEntryAllowed, read, hold, release, hud}) are checked once by the
  coordinator; frames and HUD views on every update; a throwing provider
  ends its view or keeps the last HUD.
- Entry: the most recently selected subject wins, across all kinds.
- Camera: a frame may turn the ground clamp off, anchor exactly on the
  subject and update every frame.
- A generic HUD: kicker, title, cards, always-visible source rows, banner,
  a veil with light streaks (off under reduced motion) and a bottom
  progress line whose close ticks merge.
- Text comes from the provider, already in the page's language
  (./i18n/locale: getLocale, onLocaleChange).
- Rail and Transit read and hold APIs (getSelectedTrain/Vehicle,
  getCockpitSubject, setCockpitSubject, focusTrain/Vehicle); a held
  train's marker, card and route line are hidden, and its feed keeps
  polling while held.
- ./layers/rail/paths is exported.
This commit is contained in:
Denis Groshev committed 2026-11-12 10:50:26 +01:00
1 parent 10a788db78
commit f75179eea0
51 files changed
+4059 -129

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
import { pointAtS } from '../../data/railPaths.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
import { displayMotion } from '../transit/movement.js';
/**
* Read access to one train, and a hold on it for a first-person view.
*
* `getSelectedTrain()` and `getCockpitSubject()` describe the selected train
* and the held one as a frozen snapshot, read again on each call: where it is
* along its line, how fast it moves and how that is known, and its stops.
* `setCockpitSubject(key)` holds a train: its marker, card and selected line
* are hidden, it stays selected (so its stops stay fresh and its feed stays
* polled at any distance) and clicks and Escape no longer change the
* selection. The hold ends with `setCockpitSubject(null)`, and on its own
* when the train is removed or the layer is turned off. A train removed while
* held leaves its feed polled until the next `setCockpitSubject` call, so a
* view that waits for it holds it again if the feed lists it again. `focusTrain(key)` selects a train and
* hands it the camera, as a click does.
*
* @param {object} context The layer's state, parts, services and timetable.
* @returns {{methods: object}}
*/
export function createRailCockpitSubject({
state,
parts,
services,
timetable,
}) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
const scratch = {};
/** The catalog's public entry for a feed, else the registry's. */
function feedOf(feedId) {
const listed = state._catalog?.find((feed) => feed.id === feedId);
const feed = listed ?? getRegisteredRailFeed(feedId);
if (!feed) return null;
return Object.freeze({
id: feed.id,
name: feed.name ?? null,
operator: feed.operator ?? null,
region: feed.region ?? null,
positions: listed?.positions ?? feed.positions ?? 'gps',
tripUpdates:
typeof listed?.tripUpdates === 'boolean'
? listed.tripUpdates
: typeof feed.tripUpdatesUrl === 'string',
attribution: feed.attribution ?? null,
license: feed.license ?? null,
licenseUrl: feed.licenseUrl ?? null,
});
}
/** The route's short (else long) name in the feed's timetable, or null. */
function routeNameOf(entry) {
const routeId = entry.record?.routeId;
if (!routeId) return null;
const schedule = timetable?.scheduleFor?.(entry.feedId);
const route = schedule?.routes?.[routeId];
const name = route?.short || route?.long;
return typeof name === 'string' && name ? name : null;
}
/**
* Which way the train runs along its shape: as its binding learnt it from
* successive reports, else from its drawn course against the line's
* bearing there; 0 while neither tells.
*/
function directionOf(entry) {
const binding = entry.path;
if (binding.direction === 1 || binding.direction === -1)
return binding.direction;
const course = finiteOrNull(entry.courseDeg);
const point = pointAtS(binding.path, binding.drawS, scratch);
if (course === null || !Number.isFinite(point?.bearingDeg)) return 0;
const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180);
return turn > 90 ? -1 : 1;
}
/** The train as a frozen snapshot (see the module comment), or null. */
function trainView(entry) {
if (!entry?.record) return null;
const record = entry.record;
const sample = entry.sample ?? null;
const drawn = entry.drawnHeight ?? null;
const binding = entry.path ?? null;
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const trip = state._selectedKey === entry.key ? state._trip : null;
const status = state._feedStatus.get(entry.feedId);
const latitude =
finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat;
const longitude =
finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon;
return Object.freeze({
key: entry.key,
feedId: entry.feedId,
id: String(record.id ?? ''),
tripId: record.tripId || null,
routeId: record.routeId || null,
routeName: routeNameOf(entry),
label: record.label || null,
trainNumber: record.trainNumber || null,
headsign: trip?.headsign || null,
category: entry.category ?? null,
mode: entry.railMode ?? null,
feed: feedOf(entry.feedId),
position: Object.freeze({
latitude,
longitude,
railHeightM: Number.isFinite(drawn?.h) ? drawn.h - liftM : null,
heightQuality: Number.isFinite(drawn?.q) ? drawn.q : 0,
atMs: finiteOrNull(drawn?.at),
}),
path:
binding && binding.path
? Object.freeze({
shapeIndex: binding.shapeIndex,
s: binding.drawS,
direction: directionOf(entry),
lengthM: binding.path.length,
via: binding.via,
builtAt:
state._pathPacks.get(entry.feedId)?.pack?.builtAt ?? null,
line: binding.path,
})
: null,
motion: Object.freeze({
reportedSpeedMps: reported,
derivedSpeedMps: derived,
speedSource:
reported !== null ? 'reported' : derived !== null ? 'derived' : null,
courseDeg: finiteOrNull(entry.courseDeg),
phase: sample?.phase ?? null,
word: displayMotion(entry, Date.now()).word,
reportAgeMs: finiteOrNull(sample?.latestReportAgeMs),
shownBehindMs: finiteOrNull(sample?.actualDelayMs),
feedStale: status?.stale === true,
}),
provenance: Object.freeze({
positionSource: record.positionSource ?? 'gps',
timestampSource: record.timestampSource ?? null,
}),
stops: Object.freeze(Array.isArray(trip?.stops) ? [...trip.stops] : []),
match: trip?.match ?? null,
});
}
const methods = {
/** The selected train (see createRailCockpitSubject), or null. */
getSelectedTrain() {
return trainView(state._trains.get(state._selectedKey));
},
/** The held train, or null when none is held. */
getCockpitSubject() {
return trainView(state._trains.get(state._cockpitSubjectKey));
},
/**
* Hold the train `key` for a first-person view, or release the hold with
* null. A train it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a train the layer does not show.
*/
setCockpitSubject(key) {
const previous = state._trains.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
if (previous) parts.rendering.paint(previous);
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
}
const entry = state._trains.get(key);
if (!entry) return false;
if (state._selectedKey !== key) parts.selection.selectTrain(key);
state._cockpitSubjectKey = key;
state._cockpitLostFeedId = null;
if (previous && previous !== entry) parts.rendering.paint(previous);
parts.rendering.paint(entry);
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
},
/**
* Select the train `key` and hand it the camera, as a click on it does.
* @param {string} key
* @returns {boolean} False for a train the layer does not show.
*/
focusTrain(key) {
if (!state._trains.has(key)) return false;
parts.selection.selectAndFocusTrain(key);
return true;
},
};
return { methods, trainView };
}
+208
View File
@@ -0,0 +1,208 @@
// The Rail layer's read API for a first-person view: the selected or held
// train as a snapshot (where it is along its line and which way it runs, its
// speed and how that is known, its feed's credit, its stops), and a hold that
// hides its marker and card, keeps it selected and ends when it goes.
import test from 'node:test';
import assert from 'node:assert/strict';
import { RAIL_POLL_MS, railTrainKey } from './policy.js';
import {
BOSTON,
railLayerHarness as harness,
railTrain as train,
} from '../../testSupport/railLayerHarness.mjs';
import { RAIL_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
import { publicRailCatalog } from '../../data/railFeeds.js';
const M_PER_DEG = 111_320;
const LAT = 42.36;
const KX = M_PER_DEG * Math.cos((LAT * Math.PI) / 180);
const LON0 = -71.08;
/** A flat [lat, lon, ...] line due east from LON0, one vertex per 100 m. */
function eastLine(lengthM) {
const out = [];
for (let d = 0; d <= lengthM; d += 100) out.push(LAT, LON0 + d / KX);
return out;
}
const PACK = Object.freeze({
version: 1,
feedId: 'mbta-rail',
builtAt: '2026-09-09T00:00:00.000Z',
shapes: [eastLine(6000)],
dist: [[]],
shapeSources: ['operator'],
trips: { 'trip-T1': 0, 'trip-T2': 0 },
routes: { R1: [0] },
});
/** Two trains on the line, T1 running east and T2 west, a step a poll. */
async function onTheLine(t) {
const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON });
let step = 0;
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + (1000 + step * 150) / KX, { speedMps: 15 }),
train('T2', LAT, LON0 + (5000 - step * 150) / KX),
]);
await app.enable();
for (let i = 0; i < 4; i += 1) {
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
}
return app;
}
const T1 = railTrainKey('mbta-rail', 'T1');
const T2 = railTrainKey('mbta-rail', 'T2');
test('the selected train reads as a snapshot of its place, motion and sources', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected');
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, T1);
assert.equal(view.feedId, 'mbta-rail');
assert.equal(view.id, 'T1');
assert.equal(view.tripId, 'trip-T1');
assert.equal(view.routeId, 'R1');
assert.equal(view.category, 'regional');
assert.equal(view.mode, 'rail');
const listed = publicRailCatalog().find((feed) => feed.id === 'mbta-rail');
assert.equal(view.feed.attribution, listed.attribution);
assert.equal(view.feed.license, listed.license);
assert.equal(view.feed.licenseUrl, listed.licenseUrl);
assert.equal(view.feed.positions, 'gps');
assert.equal(view.path.shapeIndex, 0);
assert.equal(view.path.builtAt, PACK.builtAt);
assert.equal(view.path.via, 'trip');
assert.ok(Math.abs(view.path.lengthM - 6000) < 1);
assert.ok(view.path.s > 1000 && view.path.s < 2000, `s ${view.path.s}`);
assert.equal(view.path.direction, 1, 'runs along the shape');
assert.equal(typeof view.path.line.length, 'number');
assert.equal(view.motion.reportedSpeedMps, 15);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.equal(view.provenance.timestampSource, 'vehicle');
const drawn = app.entry(T1).drawnHeight;
assert.equal(view.position.railHeightM, drawn.h - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
assert.ok(Array.isArray(view.stops));
app.parts().selection.selectTrain(T2);
const west = app.layer.getSelectedTrain();
assert.equal(west.path.direction, -1, 'runs against the shape');
assert.equal(west.motion.reportedSpeedMps, null);
assert.equal(
west.motion.speedSource,
west.motion.derivedSpeedMps === null ? null : 'derived',
);
});
test('a held train hides its marker and card and keeps the selection', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.setCockpitSubject('rail:mbta-rail:nope'), false);
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._selectedKey, T1, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, T1);
app.run(1000);
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.entry(T2).marker.show, true);
// From inside the train its selected line would run under the eye.
assert.equal(app.state()._route.primitive.show, false, 'no line');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// Escape is the view's while it holds the train.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, T1);
// It still moves.
const before = app.layer.getCockpitSubject().path.s;
app.run(RAIL_POLL_MS);
await app.poll();
app.run(RAIL_POLL_MS);
assert.ok(app.layer.getCockpitSubject().path.s > before, 'still moving');
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
app.run(1000);
assert.equal(app.entry(T1).marker.show, true);
assert.equal(app.state()._route.primitive.show, true, 'the line is back');
assert.equal(
(app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? []).length,
1,
'the card is back',
);
});
test('a held train that goes takes the hold with it; focusTrain selects', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.feeds.set('mbta-rail', () => [train('T2', LAT, LON0 + 4000 / KX)]);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.focusTrain(T1), false);
assert.equal(app.layer.focusTrain(T2), true);
assert.equal(app.state()._selectedKey, T2);
});
test('a held train its feed drops leaves the feed polled until the view lets go', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
// From the cab the camera looks along the ground, here past the feed's range.
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._heldFeedId, 'mbta-rail', 'held for the train');
const others = () => [train('T2', LAT, LON0 + 4000 / KX)];
app.feeds.set('mbta-rail', others);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
await app.recheck();
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'its feed is polled');
await app.moveCamera({ lat: 40.72, lon: -74.0 });
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'whatever the camera');
// Listed again: the view holds it again.
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + 2500 / KX, { speedMps: 15 }),
...others(),
]);
app.run(RAIL_POLL_MS);
await app.poll();
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.state()._selectedKey, T1);
// Let go, and the feed is the viewport's again: out of range, released.
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.setCockpitSubject(null);
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._activeFeeds.has('mbta-rail'), false);
assert.equal(app.state()._trains.size, 0);
});
test('turning the layer off ends the hold', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.disable(app.viewer);
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+13
View File
@@ -7,6 +7,7 @@ import { createIngestion } from './ingestion.js';
import { createViewport } from './viewport.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createRailCockpitSubject } from './cockpitSubject.js';
import { createRouteDisplay } from './routeDisplay.js';
import { createRailSchedules } from './schedules.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
@@ -84,6 +85,16 @@ function createState({ services }) {
_follow: null,
/** A feed polled only for the selected train (viewport.js), or null. */
_heldFeedId: null,
/**
* The train a first-person view holds (cockpitSubject.js), or null: its
* marker and card are hidden and the selection stays on it.
*/
_cockpitSubjectKey: null,
/**
* The feed of a held train the feed dropped (ingestion.js), polled until
* the view takes a train again or lets go (cockpitSubject.js), or null.
*/
_cockpitLostFeedId: null,
_revision: 0,
_controlsListener: null,
_dataManager: null,
@@ -175,11 +186,13 @@ export function createRailLayer({
parts.ingestion = createIngestion(context);
parts.viewport = createViewport(context);
parts.lifecycle = createLifecycle(context);
parts.cockpit = createRailCockpitSubject(context);
return Object.assign(
{ updateInterval: RAIL_POLL_MS },
parts.lifecycle.methods,
parts.controls.methods,
parts.cockpit.methods,
{
/** Test seams: this instance's own state and parts. */
_railStateForTest: () => state,
+7
View File
@@ -69,6 +69,13 @@ export function createIngestion({ state, services, parts, source }) {
function removeTrain(key) {
const entry = state._trains.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js); its
// feed stays polled until the view lets go, so the train is found again
// if the feed lists it again.
if (state._cockpitSubjectKey === key) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = entry.feedId;
}
if (state._selectedKey === key) parts.selection.clearSelection();
if (entry.marker) state._markers?.remove(entry.marker);
entry.marker = null;
+2
View File
@@ -125,6 +125,8 @@ export function createLifecycle({ state, services, parts, timetable }) {
parts.ingestion.abortAllInFlight();
state._activeFeeds.clear();
state._heldFeedId = null;
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
state._feedStatus.clear();
dropAllTrains();
// Floor cells and track samples queued for trains now gone.
+18
View File
@@ -47,11 +47,26 @@ export function pathWindowM(dtMs) {
return window > PATH_WINDOW_MAX_M ? NaN : window;
}
/** Arc moved between two reports before it says which way a train runs (m). */
const DIRECTION_MIN_M = 1;
/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */
function directionOf(step, known) {
return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M
? Math.sign(step)
: known;
}
function createBinding(shapeIndex, path, via, s, fix) {
return {
shapeIndex,
path,
via,
/**
* Which way the train runs along the shape: +1 along it, -1 against it,
* 0 until two reports or a playback segment tell. Kept until a rebind.
*/
direction: 0,
/** Arc and time of the newest report. */
fixS: s,
fixT: fix.t,
@@ -139,6 +154,7 @@ export function followFix(binding, fix) {
pathWindowM(fix.t - binding.fixT),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
binding.direction = directionOf(hit.s - binding.fixS, binding.direction);
binding.fixS = hit.s;
binding.fixT = fix.t;
binding.fixLat = fix.lat;
@@ -230,6 +246,8 @@ export function placeOnPath(binding, sample, segment, out) {
cache.sFrom = sFrom;
cache.sTo = sTo;
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok)
binding.direction = directionOf(sTo - sFrom, binding.direction ?? 0);
}
if (!cache.ok) return false;
const f = Number.isFinite(sample.fraction)
+33
View File
@@ -201,3 +201,36 @@ test('a segment whose reports do not fit the line keeps the straight line', () =
assert.equal(placeOnPath(binding, stale.sample, stale.segment, out), false);
assert.equal(placeOnPath(null, stale.sample, stale.segment, out), false);
});
test('a binding learns which way its train runs, and keeps it through a stop', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const along = bindTrainPath(p, ids, fix(0, 500, 0));
assert.equal(along.direction, 0, 'one report tells no direction');
assert.ok(followFix(along, fix(10_000, 700, 0)));
assert.equal(along.direction, 1);
// Standing still (under a metre) keeps what it learnt.
assert.ok(followFix(along, fix(20_000, 700.4, 0)));
assert.equal(along.direction, 1);
const against = bindTrainPath(p, ids, fix(0, 1500, 0));
assert.ok(followFix(against, fix(10_000, 1200, 0)));
assert.equal(against.direction, -1);
// A playback segment between two reports tells it too.
const played = bindTrainPath(p, ids, fix(0, 300, 0));
const segment = {
from: { seq: 1, ...fix(0, 300, 0) },
to: { seq: 2, ...fix(10_000, 100, 0) },
};
assert.ok(
placeOnPath(played, { fromSeq: 1, toSeq: 2, fraction: 0.5 }, segment, {}),
);
assert.equal(played.direction, -1);
// A rebind starts again.
const rebound = rebindTrainPath(
p,
{ routeId: 'main' },
along,
fix(30_000, 2000, -300),
);
assert.equal(rebound?.direction ?? 0, 0);
});
+13 -4
View File
@@ -507,6 +507,15 @@ export function createRendering({ state, services, parts }) {
);
}
/**
* Whether the train's marker shows: its category is on, and no
* first-person view rides it (cockpitSubject.js). A held train keeps its
* playback; only its marker hides.
*/
function markerShown(entry) {
return categoryShown(entry) && entry.key !== state._cockpitSubjectKey;
}
/**
* A train bound to its railway line is drawn on the line, at the arc its
* playback has reached; any other train (or a bound train whose reports do
@@ -536,7 +545,7 @@ export function createRendering({ state, services, parts }) {
undefined,
scratchPosition,
);
entry.marker.show = categoryShown(entry);
entry.marker.show = markerShown(entry);
}
/** While a train is selected, every other train is drawn see-through. */
@@ -554,7 +563,7 @@ export function createRendering({ state, services, parts }) {
entry.marker.width = size;
entry.marker.height = size;
entry.marker.color = tintFor(entry);
entry.marker.show = categoryShown(entry);
entry.marker.show = markerShown(entry);
}
/** Re-tint every train after the selection appeared, moved or cleared. */
@@ -658,7 +667,7 @@ export function createRendering({ state, services, parts }) {
function cullSelected() {
const entry = state._trains.get(state._selectedKey);
if (!entry?.marker) return;
const shown = categoryShown(entry) && facesCamera(entry.marker.position);
const shown = markerShown(entry) && facesCamera(entry.marker.position);
if (entry.marker.show !== shown) entry.marker.show = shown;
parts.routes.cullStops(facesCamera);
}
@@ -697,7 +706,7 @@ export function createRendering({ state, services, parts }) {
function applyCategoryVisibility() {
for (const entry of state._trains.values()) {
if (!entry.marker) continue;
entry.marker.show = categoryShown(entry);
entry.marker.show = markerShown(entry);
schedulePlayback(entry);
}
syncRenderHold();
+20
View File
@@ -427,10 +427,29 @@ export function createRouteDisplay({
updateSplit();
}
/**
* Show the selected line unless a first-person view rides its train
* (cockpitSubject.js): from inside the train it would run up the middle of
* the view and under the eye.
*/
function applyHold() {
const route = state._route;
if (!route?.primitive) return;
const shown = !(
state._cockpitSubjectKey !== null &&
state._cockpitSubjectKey === state._selectedKey
);
if (route.primitive.show !== shown) {
route.primitive.show = shown;
governorRequestRender('rail-route');
}
}
/** Move the travelled/ahead split to where the train is drawn now. */
function updateSplit() {
const route = state._route;
if (!route?.primitive) return;
applyHold();
const binding = route.binding;
const s = binding ? binding.drawS : NaN;
if (route.direction === 0 && Number.isFinite(s)) {
@@ -777,6 +796,7 @@ export function createRouteDisplay({
applyNetwork,
onCamera,
syncRoute,
applyHold,
refreshStops,
cullStops,
onSelectionChanged,
+14
View File
@@ -30,6 +30,16 @@ export function createSelection({ state, services, parts }) {
function refreshSelectedCard(force) {
const entry = state._trains.get(state._selectedKey);
if (!entry) return;
// A train a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.setEntries(
RAIL_SELECTED_OVERLAY_SOURCE_ID,
[],
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -131,6 +141,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the train, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -141,6 +153,8 @@ export function createSelection({ state, services, parts }) {
);
state._clickHandler.setInputAction((click) => {
if (!state._enabled || !isPointerFree()) return;
// A held train keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const picked = viewer.scene.pick(click.position);
const id = typeof picked?.id === 'string' ? picked.id : null;
if (id && state._trains.has(id)) selectAndFocusTrain(id);
+6
View File
@@ -148,6 +148,12 @@ export function createViewport({ state, services, parts, source }) {
))
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
// A first-person view whose train its feed dropped keeps the feed polled
// until it lets go (cockpitSubject.js): from the cab the camera looks
// along the ground, often at a point beyond the feed's range.
const lost = state._cockpitLostFeedId;
if (lost && !desired.has(lost) && state._activeFeeds.has(lost))
desired.set(lost, state._activeFeeds.get(lost));
// The selected train's feed stays polled however far out or away the
// camera goes, so the train and its line stay on the map; while nothing
// else would keep the feed, it carries the selected train alone and its
+160
View File
@@ -0,0 +1,160 @@
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
import { transitRouteLabel } from '../../data/transitFeeds.js';
import { displayMotion } from './movement.js';
/**
* Read access to one vehicle, and a hold on it for a first-person view.
*
* `getSelectedVehicle()` and `getCockpitSubject()` describe the selected
* vehicle and the held one as a frozen snapshot, read again on each call:
* where it is drawn, how fast it moves and how that is known. Transit has no
* route shapes or stops, so a snapshot names only the vehicle's last reported
* stop. `setCockpitSubject(key)` holds a vehicle: its sprite, card, trail
* and detection box are hidden, it keeps moving when it is out of the
* camera's view, its feed stays polled, and clicks and Escape no longer
* change the selection. The hold ends with `setCockpitSubject(null)`, and on
* its own when the vehicle is removed or the layer is turned off.
* `focusVehicle(key)` selects a vehicle, as a click does.
*
* @param {object} context The layer's state, parts and services.
* @returns {{methods: object}}
*/
export function createTransitCockpitSubject({ state, parts, services }) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
function feedOf(feedId) {
const feed =
state._activeFeeds.get(feedId) || getRegisteredTransitFeed(feedId);
if (!feed) return null;
return Object.freeze({
id: feed.id,
name: feed.name ?? null,
operator: feed.operator ?? null,
region: feed.region ?? null,
attribution: feed.attribution ?? null,
license: feed.license ?? null,
licenseUrl: feed.licenseUrl ?? null,
});
}
/** The vehicle as a frozen snapshot (see the module comment), or null. */
function vehicleView(entry) {
if (!entry?.record) return null;
const record = entry.record;
const sample = entry.sample ?? null;
const feed =
state._activeFeeds.get(entry.feedId) ||
getRegisteredTransitFeed(entry.feedId);
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const status = state._feedStatus.get(entry.feedId);
const latitude = finiteOrNull(sample?.lat) ?? record.lat;
const longitude = finiteOrNull(sample?.lon) ?? record.lon;
return Object.freeze({
key: entry.key,
feedId: entry.feedId,
id: String(record.id ?? ''),
routeId: record.routeId || null,
routeLabel:
(feed && record.routeId
? transitRouteLabel(feed, record.routeId)
: null) || null,
tripId: record.tripId || null,
directionId: record.directionId ?? null,
label: record.label || null,
mode: entry.mode ?? null,
modeInferred: entry.modeInferred === true,
feed: feedOf(entry.feedId),
position: Object.freeze({
latitude,
longitude,
groundHeightM: Number.isFinite(entry.heightM)
? entry.heightM - liftM
: null,
atMs: finiteOrNull(sample?.displayT),
}),
motion: Object.freeze({
reportedSpeedMps: reported,
derivedSpeedMps: derived,
speedSource:
reported !== null ? 'reported' : derived !== null ? 'derived' : null,
courseDeg: finiteOrNull(entry.courseDeg),
reportedBearingDeg: finiteOrNull(record.bearing),
segmentCourseDeg: finiteOrNull(sample?.segmentCourseDeg),
phase: sample?.phase ?? null,
word: displayMotion(entry, Date.now()).word,
reportAgeMs: finiteOrNull(sample?.latestReportAgeMs),
shownBehindMs: finiteOrNull(sample?.actualDelayMs),
feedStale: status?.stale === true,
}),
stop: Object.freeze({
stopId: record.stopId || null,
status: record.status || null,
}),
provenance: Object.freeze({
positionSource: 'gps',
timestampSource: record.timestampSource ?? null,
}),
});
}
/** Show or hide a vehicle's sprite and trail for the hold. */
function repaint(entry) {
if (!entry?.marker) return;
if (entry.key === state._cockpitSubjectKey) entry.marker.show = false;
else parts.rendering.placeSample(entry);
parts.rendering.schedulePlayback(entry);
parts.trails.update();
state._detectRevision += 1;
}
const methods = {
/** The selected vehicle (see createTransitCockpitSubject), or null. */
getSelectedVehicle() {
return vehicleView(state._vehicles.get(state._selectedKey));
},
/** The held vehicle, or null when none is held. */
getCockpitSubject() {
return vehicleView(state._vehicles.get(state._cockpitSubjectKey));
},
/**
* Hold the vehicle `key` for a first-person view, or release the hold
* with null. A vehicle it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
setCockpitSubject(key) {
const previous = state._vehicles.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
repaint(previous);
parts.selection.refreshSelectedCard(true);
return true;
}
const entry = state._vehicles.get(key);
if (!entry?.marker) return false;
if (state._selectedKey !== key) parts.selection.selectVehicle(key);
state._cockpitSubjectKey = key;
state._visible.add(entry);
if (previous && previous !== entry) repaint(previous);
repaint(entry);
parts.selection.refreshSelectedCard(true);
return true;
},
/**
* Select the vehicle `key`, as a click on it does.
* @param {string} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
focusVehicle(key) {
if (!state._vehicles.get(key)?.marker) return false;
parts.selection.selectVehicle(key);
return true;
},
};
return { methods, vehicleView };
}
+3
View File
@@ -10,6 +10,7 @@ import { createQueries } from './queries.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createTesting } from './testing.js';
import { createTransitCockpitSubject } from './cockpitSubject.js';
import { TRANSIT_POLL_MS } from './policy.js';
/**
@@ -54,12 +55,14 @@ export function createTransitLayer({
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
parts.testing = createTesting(context);
parts.cockpit = createTransitCockpitSubject(context);
return Object.assign(
{ updateInterval: TRANSIT_POLL_MS },
parts.lifecycle.methods,
parts.queries.methods,
parts.controls.methods,
parts.cockpit.methods,
parts.testing,
);
}
+2
View File
@@ -71,6 +71,8 @@ export function createIngestion({ state, services, parts, source }) {
function removeVehicle(key) {
const entry = state._vehicles.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js).
if (state._cockpitSubjectKey === key) state._cockpitSubjectKey = null;
if (state._selectedKey === key) parts.selection.clearSelection();
if (entry.marker) entry.markerCollection?.remove(entry.marker);
entry.marker = null;
+1
View File
@@ -151,6 +151,7 @@ export function createLifecycle({ state, services, parts }) {
state._vehicles.clear();
parts.height.clear();
state._selectedKey = null;
state._cockpitSubjectKey = null;
state._lastUpdate = null;
state._error = null;
state._limitWarned = false;
+118
View File
@@ -7,6 +7,7 @@ import {
FEED_STALE_AFTER_MS,
MISSED_POLLS_TO_DROP,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_ID,
VEHICLE_MAX_FIX_AGE_MS,
} from './policy.js';
import { FLOOR_WARM_PER_POLL } from './policy.js';
@@ -4142,3 +4143,120 @@ test('the prompt names the altitude the gate opens at, not 3,000 km', async (t)
'Fly below 2,850 km to a covered region',
);
});
/** A bus running north a step a poll, polled `polls` times; its key. */
async function busRunningNorth(app, polls = 4, extra = {}) {
let step = 0;
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[
vehicle('bus-1', 42.36 + step * 0.001, -71.06, reported(), {
stopId: 'place-1',
status: 'IN_TRANSIT_TO',
...extra,
}),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
for (let i = 0; i < polls; i += 1) {
step += 1;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
}
return 'mbta:bus-1';
}
test('the selected vehicle reads as a snapshot of its place, motion and source', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app, 4, { speedMps: 9 });
assert.equal(app.layer.getSelectedVehicle(), null);
app.layer._transitPartsForTest().selection.selectVehicle(key);
const view = app.layer.getSelectedVehicle();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, key);
assert.equal(view.feedId, 'mbta');
assert.equal(view.id, 'bus-1');
assert.equal(view.routeId, '1');
assert.equal(typeof view.mode, 'string');
assert.ok(view.feed.attribution, 'the feed names its credit');
assert.equal(view.motion.reportedSpeedMps, 9);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.deepEqual(view.stop, { stopId: 'place-1', status: 'IN_TRANSIT_TO' });
const entry = app.vehicles()[0];
assert.equal(view.position.groundHeightM, entry.heightM - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
});
test('a held vehicle hides, keeps moving out of view, and lets go when it goes', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
assert.equal(app.layer.setCockpitSubject('mbta:nope'), false);
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(app.state()._selectedKey, key, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, key);
assert.equal(
app.overlaySources.has(TRANSIT_SELECTED_OVERLAY_SOURCE_ID),
false,
'no card',
);
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, false);
// The camera's view leaves it, as a view from inside it does: it plays on.
app.lookAt({ west: 10, south: 10, east: 11, north: 11 });
app.settle();
assert.equal(
app.layer._transitPartsForTest().rendering.vehicleInView(entry),
true,
);
const before = app.layer.getCockpitSubject().position.latitude;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
assert.ok(
app.layer.getCockpitSubject().position.latitude > before,
'still moving',
);
// Escape and clicks are the view's while it holds the vehicle.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, key);
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
app.lookAt({
west: -71.2,
south: 42.2,
east: -70.9,
north: 42.5,
});
app.settle();
assert.equal(entry.marker.show, true, 'shown again');
assert.equal(app.layer.focusVehicle('mbta:nope'), false);
assert.equal(app.layer.focusVehicle(key), true);
app.layer.setCockpitSubject(key);
app.silence('mbta');
app.serve('mbta', () => ({
status: 200,
body: snapshot('mbta', 'MBTA', [], { fetchedAt: Date.now() }),
}));
for (let i = 0; i < MISSED_POLLS_TO_DROP + 1; i += 1) {
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
assert.equal(app.vehicles().length, 0, 'the vehicle is gone');
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+12 -4
View File
@@ -100,7 +100,9 @@ export function createRendering({ state, services, parts }) {
);
entry.surfaceReady = !!known;
entry.heightPending = !known;
entry.marker.show = !!known && vehicleInView(entry);
// A vehicle a first-person view rides keeps moving, unseen.
entry.marker.show =
!!known && vehicleInView(entry) && entry.key !== state._cockpitSubjectKey;
if (known) {
entry.marker.position = state._scratchCartesian;
entry.hasRendered = true;
@@ -191,7 +193,7 @@ export function createRendering({ state, services, parts }) {
* @returns {boolean}
*/
function vehicleInView(entry) {
return state._visible.has(entry);
return state._visible.has(entry) || entry.key === state._cockpitSubjectKey;
}
/** Cesium colour for a preset tuple, cached per profile+mode. */
@@ -531,7 +533,10 @@ export function createRendering({ state, services, parts }) {
} else if (frustum)
inFrustum =
frustum.computeVisibility(sphere) !== Cesium.Intersect.OUTSIDE;
const visible = (frustum || bounds) && horizon && inFrustum;
// A held vehicle (cockpitSubject.js) is the camera's own: it stays in
// play wherever the view looks.
const held = entry.key === state._cockpitSubjectKey;
const visible = held || ((frustum || bounds) && horizon && inFrustum);
const visibility = (entry.visibility ||= {});
visibility.bounds = bounds;
visibility.boundsApplied = !frustum;
@@ -556,7 +561,10 @@ export function createRendering({ state, services, parts }) {
}
}
entry.marker.show =
visible && !entry.heightPending && entry.surfaceReady !== false;
!held &&
visible &&
!entry.heightPending &&
entry.surfaceReady !== false;
visibility.heightPending = !!entry.heightPending;
visibility.surfaceReady = entry.surfaceReady ?? null;
schedulePlayback(entry);
+10
View File
@@ -46,6 +46,12 @@ export function createSelection({ state, services, parts }) {
? state._vehicles.get(state._selectedKey)
: null;
if (!entry) return;
// A vehicle a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -111,6 +117,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the vehicle, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -123,6 +131,8 @@ export function createSelection({ state, services, parts }) {
// Ambient selection never competes for a pointer a tool has claimed:
// placing a draw vertex on top of a bus must not also select the bus.
if (!isPointerFree()) return;
// A held vehicle keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const scene = viewer.scene;
// Pick buffers precede post-processing. Map a sensor pixel back through
// the active shader's barrel distortion and quantization before picking.
+7
View File
@@ -95,6 +95,13 @@ export function createState({ services }) {
/** @type {string|null} */
state._selectedKey = null;
/**
* The vehicle a first-person view holds (cockpitSubject.js), or null: its
* sprite, card, trail and detection box are hidden, and it keeps moving
* out of the camera's view.
* @type {string|null}
*/
state._cockpitSubjectKey = null;
state._selectedCardAt = 0;
/** The card text last published, so an unchanged card is not re-sent. */
state._selectedCardText = null;
+4 -1
View File
@@ -235,8 +235,11 @@ export function createTrails({ state, services, parts, source }) {
}
function update() {
if (!selected || !renderer) return;
// A first-person view on the vehicle rides where its trail would start.
renderer.setVisible(
state._enabled && state._vehicles.get(selected.key) === selected,
state._enabled &&
state._vehicles.get(selected.key) === selected &&
selected.key !== state._cockpitSubjectKey,
);
renderer.setDisplaySample(selected.sample, selected.marker?.position);
}
+4
View File
@@ -101,6 +101,10 @@ export function createViewport({ state, services, parts }) {
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
}
// A vehicle a first-person view rides keeps its feed polled.
const held = state._vehicles.get(state._cockpitSubjectKey);
if (held && state._activeFeeds.has(held.feedId))
desired.set(held.feedId, state._activeFeeds.get(held.feedId));
for (const feedId of [...state._activeFeeds.keys()]) {
if (!desired.has(feedId)) {
state._inFlight.get(feedId)?.controller.abort();