feat(transit): live public-transit vehicles from open GTFS-Realtime feeds (#587)

Supersedes #218 by @spcpza, ported onto the current component layout with fixes from review.

Verified before merge: format, package boundaries, unit suite, build, and the browser tracking suite; a browser harness for the change where one applies; adversarial review applied.

Contributor: @spcpza. His original commit is the base of this branch, and his own re-port onto main (2026-09-15, `5b69011`) was consulted while finishing the height work. That port reads every vehicle's surface from the app's shared ground-floor system (`cachedGroundFloor` / `warmGroundFloor` / `GROUND_FLOOR_LIFT_M`) rather than sampling the scene per layer, keeps a vehicle hidden until its cell answers, warms a bounded batch per poll on a timer instead of per frame, and renders at the ellipsoid above the altitude gate. That is the sounder primitive — one floor system for the app, with the rooftop-versus-street question already settled against a datum-correct DEM prior — and this branch's height work was rebuilt on it, replacing a bespoke cell cache, ground prior and rooftop rule written here. Credit for that direction is his.

Future work (not in this PR), both written up in docs/CURRENT-STATE.md:

- Readable route names. The realtime feeds carry only `route_id`; `route_short_name` / `route_long_name` live in each operator's static GTFS `routes.txt`, and headsigns in `trips.txt`. Doing it properly wants a server-side metadata loader beside the transit proxy with fixed registered static sources, bounded indexes built once and persisted, a slow conditional refresh, and a versioned route dictionary the browser caches. Shipped here: ids are never rewritten, and a cut one carries an ellipsis instead of reading as a typo.
- Below-ground rendering. Subway vehicles are drawn on the surface directly above themselves, because the feeds carry no depth and a train nobody can see is not worth drawing; the card says so plainly. Real treatment wants OSM tunnel geometry per city and a ghosted sprite tethered to the surface. The owner recorded it and left it.

Round four and after (2026-09-15). The owner tested round three under FLIR and NVG, and then asked for the design to be taken further: elegant in performance, beautiful on camera, trails with a cache for public transport, Cesium-native, and a core other moving layers can adopt. Codex Astra reviewed the plan (it confirmed the speed fault: a glide started from the drawn position at receipt time but spanned the gap between report times, so with MBTA reporting every ~10 s against a 15 s poll every second glide ran at 1.5x; it rejected a queued-segment patch), then wrote the design, then implemented it in commit-sized passes with adversarial review between them and real-browser harness runs by the integrator.

What this PR now contains beyond the contributor's original port:

- Delayed playback in a contact-agnostic core (`src/data/contactPlayback.js`): each vehicle keeps a typed, bounded fix history and a display clock that runs at one second per second through it, a feed-derived lag behind real time, holding at its newest fix rather than extrapolating and never sprinting to catch up. Marker, course, motion word, card and trail all read the same displayed sample. The clock has an explicit time-offset and seek API so a rewind is a later feature, not a rewrite; flights and vessels are untouched.
- A selected-vehicle trail (`src/data/contactTrailRenderer.js`, `src/layers/transit/trails.js`): the retained history drawn with batched Cesium primitives, clipped at display time so the head is exactly the sprite, faded by age, in the mode colour (white under sensor presets), on the same surface path as the marker.
- Bounded proxy-side history (`server/providers/transitHistory.js`): fifteen minutes and at most 128 fixes per vehicle with hard byte ceilings, MBTA only for now (opt-in per feed), served by a small endpoint that never fetches upstream, so a selected trail survives a browser reload while the server keeps running.
- Scene work bounded to what is visible and moving, an occluder, cached DETECT candidates, holds on the render loop only while something visible moves.
- Sensor presets: white-hot haloed sprites under NVG/FLIR/noir (black-hot inverts), saturated mode colours under CRT, per-mode bracket tiers in every theme, the selected card keeping its mode colour.
- A discriminating browser harness (`scripts/qa-transit.mjs`) that samples postRender frames, reads the real card anchor, and measures fleet budgets at 800 and 3,000 vehicles.

Not built, recorded as follow-ups: curated route display names (lowest priority per the owner), fleet-wide tails, route snapping, a rewind UI, adoption of the playback core by flights and vessels.

Verified at merge (2026-09-15 morning): unit suite 3,896 passing, build clean, format and boundary gates clean, tracking regression 109/109, browser harness keyless 200 pass / 0 fail (13 sensor checks unexercised because the live view offered fewer than six isolated sprites; every judged sprite passed), keyed on Google 3D tiles 198 pass with the per-frame allocation gate as the only failure. Follow-ups recorded: the keyed build's playback sampler still allocates per frame (CPU and frame time stay within budget; the 3,000-vehicle metro view sits at a 27.6 ms frame interval against a 25 ms budget), the shared detection overlay's per-paint allocation, friendlier route names, fleet-wide tails, a rewind UI, and adopting the playback core for vessels and flights.
Co-authored-by: spcpza <[email protected]>
This commit is contained in:
Bilawal Sidhu authored and GitHub committed 2026-09-15 05:18:30 -05:00
1 parent 1ad565c8af
commit 76c20be277
78 files changed
+19842 -186

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
import * as Cesium from 'cesium';
import {
FLOOR_REREAD_ATTEMPTS,
FLOOR_REREAD_MS,
FLOOR_WARM_PER_POLL,
TRANSIT_POLL_MS,
HEIGHT_SAMPLE_MAX_ALTITUDE_M,
withinViewBounds,
} from './policy.js';
/** Surface preparation off the render path, shared by markers and history. */
export function createHeight({ state, services, parts }) {
const { governorRequestRender } = services.render;
const {
cachedGroundFloor,
neighborFloorM,
warmGroundFloor,
coarseFloorCoord,
GROUND_FLOOR_LIFT_M,
} = services.ground;
// The application's rendered-mesh sampler. Optional so a layer built on a
// bare floor stub still runs; the application always supplies it.
const sampleMeshFloorCells = services.mesh?.sampleMeshFloorCells || null;
/** The camera's subpoint in degrees, for the sampler's proximity gate. */
function viewerSubpoint() {
const carto = state._viewer?.camera?.positionCartographic;
if (!carto) return { viewerLat: undefined, viewerLon: undefined };
return {
viewerLat: (carto.latitude * 180) / Math.PI,
viewerLon: (carto.longitude * 180) / Math.PI,
};
}
function cameraAltitude() {
const carto = state._viewer?.camera?.positionCartographic;
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
}
/**
* Whether ground matters at this camera. Above the gate a few metres of
* terrain are invisible, so the fleet renders on the ellipsoid and nothing
* is warmed — a national view must not queue a country's worth of cells.
* @returns {boolean}
*/
function nearGround() {
return cameraAltitude() <= HEIGHT_SAMPLE_MAX_ALTITUDE_M;
}
/**
* The floor under a vehicle, and the best fallback if its own cell is cold.
* @param {number} lat
* @param {number} lon
* @returns {{cell: string, height: number|null, prior: number|null}}
*/
const terrainPoint = new Cesium.Cartographic();
function requestHeight(lat, lon, entry = null) {
const coarse = coarseFloorCoord(lat, lon);
const cell = `${coarse.lat},${coarse.lon}`;
const fixtureFloor =
entry?.qaFloorM ?? state._qaFixtureFloors?.get(entry?.key);
if (Number.isFinite(fixtureFloor))
return { cell, height: fixtureFloor, prior: null };
// On a terrain globe, use the loaded surface under the marker. This is
// synchronous cache work and does not launch a terrain request.
const globe = state._viewer?.scene?.globe;
if (globe?.show === true) {
Cesium.Cartographic.fromDegrees(lon, lat, 0, terrainPoint);
const rendered = globe.getHeight?.(terrainPoint);
const flat =
state._viewer?.terrainProvider instanceof
Cesium.EllipsoidTerrainProvider;
if (Number.isFinite(rendered) || flat)
return {
cell,
height: (flat ? 0 : rendered) + GROUND_FLOOR_LIFT_M,
prior: null,
};
}
const floor = cachedGroundFloor(lat, lon);
if (Number.isFinite(floor)) {
return { cell, height: floor + GROUND_FLOOR_LIFT_M, prior: null };
}
if (!nearGround()) {
// Far enough away that the ellipsoid is indistinguishable from the
// street: draw, do not wait, do not warm.
return { cell, height: null, prior: 0 };
}
const neighbour = neighborFloorM(coarse);
return {
cell,
height: null,
// A neighbouring floor is a coarse prior, never a clearance guarantee.
prior: Number.isFinite(neighbour)
? neighbour + GROUND_FLOOR_LIFT_M
: null,
};
}
/** A vehicle no longer rendered needs nothing released: cells are shared. */
function releaseVehicle() {}
let cellCursors = new WeakMap();
let budgetAt = -Infinity;
let demUsed = new Set(),
meshUsed = 0;
function rereadFloors() {
state._floorTimer = null;
if (!state._enabled) return;
const onGround = nearGround(),
candidates = [];
const entries = [...state._vehicles.values()].filter(
(entry) =>
entry.key === state._selectedKey ||
state._visible.has(entry) ||
withinViewBounds(state._viewBounds, entry.segment?.from || entry.to),
);
entries.sort(
(a, b) =>
Number(b.key === state._selectedKey) -
Number(a.key === state._selectedKey),
);
for (const entry of entries) {
const cells = new Map();
const collect = (point, answer) => {
if (!onGround) return;
if (!cells.has(answer.cell))
cells.set(answer.cell, {
lat: point.lat,
lon: point.lon,
cell: answer.cell,
warm: answer.height !== null,
});
};
parts.trails.prepareEntry(entry, collect);
const newest = entry.fixes.at(-1);
const answer = requestHeight(newest.lat, newest.lon, entry);
entry.heightCell = answer.cell;
if (answer.height !== null) {
entry.heightM = answer.height;
entry.heightResolved = true;
if (entry.heightPending) {
entry.heightPending = false;
state._visibilityDirty = true;
}
}
candidates.push({
entry,
cells: [...cells.values()],
cursor: 0,
start: cellCursors.get(entry) || 0,
});
}
const selectedCells =
candidates[0]?.entry.key === state._selectedKey
? candidates[0].cells.slice(0, 12)
: [];
const ordered = [...selectedCells],
seen = new Set(selectedCells.map((cell) => cell.cell));
const start = candidates.length
? state._floorCursor % candidates.length
: 0;
let remaining = true;
while (remaining) {
remaining = false;
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[(start + i) % candidates.length];
if (candidate.cursor >= candidate.cells.length) continue;
const index =
(candidate.start + candidate.cursor++) % candidate.cells.length;
const cell = candidate.cells[index];
remaining = true;
if (!seen.has(cell.cell)) {
seen.add(cell.cell);
ordered.push({
...cell,
entry: candidate.entry,
next: (index + 1) % candidate.cells.length,
});
}
}
}
state._floorCursor += FLOOR_WARM_PER_POLL;
const dem = [],
mesh = [];
for (const cell of ordered) {
let admitted = false;
if (
!cell.warm &&
(demUsed.has(cell.cell) || demUsed.size < FLOOR_WARM_PER_POLL)
) {
demUsed.add(cell.cell);
dem.push(cell);
admitted = true;
}
if (cell.warm && meshUsed + mesh.length < 40) {
mesh.push(cell);
admitted = true;
}
if (admitted && cell.entry) cellCursors.set(cell.entry, cell.next);
}
meshUsed += mesh.length;
const markers = entries.map((entry) => entry.marker).filter(Boolean);
for (let i = 0; i < dem.length; i += 8)
warmGroundFloor(dem.slice(i, i + 8));
for (let i = 0; i < mesh.length; i += 8)
sampleMeshFloorCells?.(state._viewer?.scene, mesh.slice(i, i + 8), {
excludeObjects: markers,
...viewerSubpoint(),
});
// Cached completions can be adopted now; asynchronous completions are
// adopted by the next bounded reread.
for (const entry of entries) parts.trails.prepareEntry(entry);
parts.rendering.requestVisibility();
governorRequestRender('transit-floor');
if (state._floorAttempts++ < FLOOR_REREAD_ATTEMPTS)
state._floorTimer = setTimeout(rereadFloors, FLOOR_REREAD_MS);
}
/** Start a fresh re-read cycle. Called once per poll, never per frame. */
function anchorFloors() {
if (state._floorTimer) {
clearTimeout(state._floorTimer);
state._floorTimer = null;
}
state._floorAttempts = 0;
const now = performance.now();
if (now - budgetAt >= TRANSIT_POLL_MS) {
demUsed = new Set();
meshUsed = 0;
budgetAt = now;
}
rereadFloors();
}
function clear() {
budgetAt = -Infinity;
cellCursors = new WeakMap();
demUsed.clear();
meshUsed = 0;
if (state._floorTimer) {
clearTimeout(state._floorTimer);
state._floorTimer = null;
}
state._floorAttempts = 0;
state._heightDirty.clear();
}
return {
nearGround,
requestHeight,
releaseVehicle,
anchorFloors,
rereadFloors,
clear,
};
}