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

+150 -14
View File
@@ -49,7 +49,12 @@ const _scratchWorldForward = new Cesium.Cartesian3();
* unavailable (off-screen/behind camera/degenerate).
* @returns {number|null} Rotation in radians, or `previous` when unknown.
*/
export function screenProjectedRotation(scene, position, courseDeg, previous = null) {
export function screenProjectedRotation(
scene,
position,
courseDeg,
previous = null,
) {
const camera = scene?.camera;
if (!camera?.rightWC || !camera?.upWC || !position) return previous;
@@ -58,20 +63,26 @@ export function screenProjectedRotation(scene, position, courseDeg, previous = n
Math.sin(courseRad) * FORWARD_PROBE_M,
Math.cos(courseRad) * FORWARD_PROBE_M,
0,
_scratchForward
_scratchForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
position,
Cesium.Ellipsoid.WGS84,
_scratchEnu,
);
Cesium.Matrix4.multiplyByPointAsVector(
enu,
_scratchForward,
_scratchWorldForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position, Cesium.Ellipsoid.WGS84, _scratchEnu);
Cesium.Matrix4.multiplyByPointAsVector(enu, _scratchForward, _scratchWorldForward);
// Screen x follows camera-right. Window y grows downward, the opposite of
// camera-up. Projecting the vector itself avoids clipping/behind-camera
// failure modes from the old forward-point worldToWindowCoordinates probe.
const dx = Cesium.Cartesian3.dot(_scratchWorldForward, camera.rightWC);
const dy = -Cesium.Cartesian3.dot(_scratchWorldForward, camera.upWC);
if (
(dx * dx + dy * dy)
< MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M
) return previous;
if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M)
return previous;
// Window y grows downward; rotation 0 = icon pointing screen-up.
// Icon direction in window coords after CCW rotation r is (-sin r, -cos r),
@@ -94,13 +105,20 @@ export function stabilizeScreenRotation(
next,
deadbandRad = ROTATION_DEADBAND_RAD,
) {
if (!Number.isFinite(next)) return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(next))
return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(previous)) return next;
const delta = Math.atan2(Math.sin(next - previous), Math.cos(next - previous));
const delta = Math.atan2(
Math.sin(next - previous),
Math.cos(next - previous),
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
const _occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, new Cesium.Cartesian3());
const _occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(),
);
/**
* Half-width of the crossfade band centred on the ellipsoid silhouette, in
@@ -169,7 +187,11 @@ const _wgs84OneOverRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
* @param {number} [featherRad=HORIZON_FEATHER_RAD] Half-width of the blend band.
* @returns {number} 0 (ground behind) … 1 (sky behind).
*/
export function skyBackdropFactor(cameraPosition, position, featherRad = HORIZON_FEATHER_RAD) {
export function skyBackdropFactor(
cameraPosition,
position,
featherRad = HORIZON_FEATHER_RAD,
) {
if (!cameraPosition || !position) return 0;
const s = _wgs84OneOverRadii;
@@ -236,6 +258,120 @@ export function horizonOccluder(camera) {
*/
export function cameraPoseSignature(camera) {
const p = camera.positionWC;
return `${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${camera.heading.toFixed(3)}:${camera.pitch.toFixed(3)}:${camera.roll.toFixed(3)}`;
return (
`${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${camera.heading.toFixed(3)}:${camera.pitch.toFixed(3)}:${camera.roll.toFixed(3)}`
);
}
/**
* Meters ahead used by the exact projection below. Short on purpose: the point
* of a perspective projection is that it is LOCAL to the contact, and a two
* kilometre probe on a bus at six hundred metres would sample a part of the
* frustum the vehicle is nowhere near.
*/
const NEAR_PROBE_M = 30;
const _scratchProbe = new Cesium.Cartesian3();
const _scratchWindowAt = new Cesium.Cartesian2();
const _scratchWindowAhead = new Cesium.Cartesian2();
/**
* Billboard rotation for a SURFACE contact, projected exactly — perspective
* division included — instead of through the camera-basis approximation.
*
* `screenProjectedRotation` above deliberately projects the course vector onto
* the camera's right/up basis, which is orthographic: exact at the viewport
* centre and an approximation away from it. That is the right trade for
* aircraft, where the alternative loses continuity through a tracked orbit and
* the contacts are far enough away for the error to be small.
*
* It is the wrong trade for street-level vehicles. A probe with a real Cesium
* camera at 600 m and −45° pitch, on a northbound contact 350 m right of
* centre, put the orthographic answer at 0° where the true screen direction of
* travel was 22.5°. At that pitch and that range the vehicles fill the frame
* away from the centre, and every one of them points visibly wrong.
*
* So this projects two nearby world points through the actual view-projection
* and reads the angle between them on screen. When either point cannot be
* projected — behind the camera, off the frustum, degenerate — it falls back to
* the camera-basis answer rather than inventing one.
*
* @param {Cesium.Scene} scene The scene (projection source).
* @param {Cesium.Cartesian3} position Entity world position.
* @param {number} courseDeg Course in degrees clockwise from north.
* @param {number|null} previous Rotation to keep when projection is unavailable.
* @returns {number|null} Rotation in radians, or the fallback.
*/
export function perspectiveProjectedRotation(
scene,
position,
courseDeg,
previous = null,
) {
if (!scene?.camera || !position || !Number.isFinite(courseDeg)) {
return previous;
}
const courseRad = Cesium.Math.toRadians(courseDeg);
Cesium.Cartesian3.fromElements(
Math.sin(courseRad) * NEAR_PROBE_M,
Math.cos(courseRad) * NEAR_PROBE_M,
0,
_scratchForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
position,
Cesium.Ellipsoid.WGS84,
_scratchEnu,
);
Cesium.Matrix4.multiplyByPointAsVector(
enu,
_scratchForward,
_scratchWorldForward,
);
Cesium.Cartesian3.add(position, _scratchWorldForward, _scratchProbe);
const at = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
_scratchWindowAt,
);
const ahead = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
_scratchProbe,
_scratchWindowAhead,
);
if (!at || !ahead) {
return screenProjectedRotation(scene, position, courseDeg, previous);
}
const dx = ahead.x - at.x;
const dy = ahead.y - at.y;
const separation = Math.hypot(dx, dy);
// Window y grows downward; rotation 0 = icon pointing screen-up.
const exact = Math.atan2(-dx, -dy);
if (separation >= PERSPECTIVE_BLEND_MAX_PX) return exact;
// Below a pixel or so of separation the exact answer is dominated by
// projection noise, and above it the camera-basis answer is the wrong one
// by up to twenty-odd degrees. A hard cutoff between the two flipped a
// sprite by 23° for a 20 m change of camera altitude; the two answers are
// blended across the band instead, the short way round, so the rotation is
// continuous through it.
const basis = screenProjectedRotation(scene, position, courseDeg, previous);
if (!Number.isFinite(basis)) return exact;
if (separation <= PERSPECTIVE_BLEND_MIN_PX) return basis;
const weight =
(separation - PERSPECTIVE_BLEND_MIN_PX) /
(PERSPECTIVE_BLEND_MAX_PX - PERSPECTIVE_BLEND_MIN_PX);
const delta = Math.atan2(Math.sin(exact - basis), Math.cos(exact - basis));
return basis + delta * weight;
}
/**
* Probe separations (px) between which the exact and camera-basis answers
* are blended. At or below the floor the camera-basis answer is used alone;
* at or above the ceiling the exact one.
*/
export const PERSPECTIVE_BLEND_MIN_PX = 0.5;
export const PERSPECTIVE_BLEND_MAX_PX = 3;
/** Exported for tests: how far ahead the exact projection probes. */
export const PERSPECTIVE_PROBE_M = NEAR_PROBE_M;