Files
gods-eye-view/src/layers/traffic/state.js
T
Sameh Khamis 26633106fc Traffic surface keys and readiness through the globe port; draped lines fall back to overlay where the scene cannot drape
The traffic layer keys its cached road heights by the globe port's
surfaceVersion() and waits on isSettled('surface') instead of reading the
scene through render/cesium/surfaceState.js, which is gone. Heat-lines are
always asked for draped; the layer no longer checks whether the scene can
drape and drops them. The traffic layer and application/sources no longer
reach Cesium, and src/layers/traffic/rendering.js leaves the Cesium list.

Where the Cesium renderer cannot drape (no depth textures), its draw port
now draws every draped line over the surface, as the contract asks: along
the surface's curve between its positions, in its colour where the surface
hides it, hidden past the horizon (tested along its arc, shown in 2D). A
segmented line runs from its first shown segment to its last, in its style
colour. A line whose positions hold what they held takes a new colour in
place, so pulsing jam lines build nothing per frame; one that moves is
built anew alone.
2026-11-09 03:10:29 -08:00

300 lines
9.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { normalizeRoadMode } from './roadModes.js';
import { FLOW_BUCKET_COLORS } from './policy.js';
export function createState({ services }) {
const layerState = {};
layerState._roadMode =
typeof location === 'undefined'
? null
: normalizeRoadMode(
new URLSearchParams(location.search).get('trafficRoads'),
);
// The query override is consumed at construction and shields passive restoration.
layerState._roadModeUrlOverride = layerState._roadMode;
// ─── Module State ──────────────────────────────────────────
/** @type {object|null} The scene's viewer. */
layerState._viewer = null;
/** @type {object|null} The dots' draw set (points), made at init. */
layerState._dotSet = null;
/** @type {Array<{point:object, waypoints:Array<{x:number, y:number, z:number}>, segmentDist:number[], numSegments:number, segIdx:number, t:number, mps:number, direction:number, stoppedUntil:number}>} Active animated dots */
layerState._dots = [];
layerState._nextDotId = 1;
layerState._motion = {
publishes: 0,
rebuilds: 0,
added: 0,
removed: 0,
recycled: 0,
};
/** @type {Array<{coords:number[][], type:string, waypoints:Array<{x:number, y:number, z:number}>, segmentDist:number[]}>} Parsed roads with pre-computed ECEF waypoints */
layerState._roads = [];
/** @type {boolean} Whether the layer is currently enabled */
layerState._enabled = false;
/** @type {Function|null} Disposer of the frame port's preRender listener */
layerState._preRenderRemover = null;
/** @type {Function|null} Disposers of the camera port's changed and moveEnd listeners */
layerState._cameraRemover = null;
layerState._arrivalRemover = null;
/** @type {ReturnType<typeof setTimeout>|null} Debounce timer for camera-change fetch */
layerState._fetchTimeout = null;
/** @type {{south:number,west:number,north:number,east:number}|null} Last fetched clamped bounds */
layerState._lastBounds = null;
/** @type {boolean} True while a road fetch is in flight */
layerState._fetching = false;
/** @type {number} Current count of rendered dots */
layerState._count = 0;
/** @type {number|null} Timestamp of last successful render */
layerState._lastUpdate = null;
/** @type {number} Monotonic generation counter — incremented on each load to discard stale responses */
layerState._loadGeneration = 0;
/** @type {AbortController|null} Controller for the in-flight fetch, so it can be cancelled */
layerState._activeFetchAbort = null;
/** @type {number} User-adjustable density multiplier (clamped 0.2–2.5) */
layerState._densityScale = 1.0;
/** @type {number} User-adjustable speed multiplier (clamped 0.3–3.0) */
layerState._speedScale = 1.0;
/** @type {{lat:number,lon:number}|null} Center of last-fetched viewport for shift gating */
layerState._lastViewCenter = null;
/** @type {boolean} Live TomTom flow mode — true iff /api/tomtom/status reports a key */
layerState._liveMode = false;
/**
* Short user-facing reason live flow is currently unavailable, or null while
* healthy. Only ever set in live mode: keyless simulation is a designed
* fallback, not a fault, and must never read as an error.
* @type {string|null}
*/
layerState._flowError = null;
/**
* True while the drawn flow came from cached proxy tiles (TomTom budget
* spent or upstream failing); `_flowOldestTileAt` is the oldest tile's
* fetch time in ms, or null.
* @type {boolean}
*/
layerState._flowStale = false;
layerState._flowOldestTileAt = null;
/**
* True when `/api/tomtom/status` itself could not be reached, so the layer is
* simulating because it could not ask — not because the server said "no key".
* @type {boolean}
*/
layerState._flowStatusUnavailable = false;
/**
* Flow requests this layer still owns. The 250 ms paint race lets a flow
* fetch outlive the road load that started it (cached roads settle
* instantly), so `_fetching` alone under-reports the work in flight: the
* loading batch would close with LOAD COMPLETE and a failure landing after
* it could never be announced. Counted, not boolean — recolor-after-timeout
* means two loads can overlap.
* @type {number}
*/
layerState._flowPending = 0;
/**
* Rendered-dot counts per flow bucket (sim = white ambient, no flow data).
* Reset with the dots in clearDots; drives the data-panel diagnostics and
* the qa-traffic harness color assertions.
* @type {{free:number, slow:number, jam:number, sim:number}}
*/
layerState._bucketCounts = { free: 0, slow: 0, jam: 0, sim: 0 };
/** @type {number} Roads in the current render skipped entirely as closed. */
layerState._closedRoads = 0;
/** @type {'sim'|'hide'} Live-mode treatment of roads without flow data. */
layerState._uncoveredMode = 'sim';
/**
* Jam-viz prototype mode: 'density' = deep-jam density boost + platoon queues
* + stop-and-go creep; 'heatline' = congestion corridor polylines; 'both';
* 'none' = shipped main behavior. Live mode only — the keyless simulation
* never has `road.flow`, so every jamViz path is unreachable there.
* Default 'density' — owner A/B verdict 2026-07-23 (heatline stays available
* via setParams).
* @type {'none'|'density'|'heatline'|'both'}
*/
layerState._jamViz = 'density';
/**
* Congestion heat-lines: a lines draw set draped onto the rendered 3D
* tiles, made at init.
* @type {object|null}
*/
layerState._heatSet = null;
/** @type {Array} The jam heat-line items, recoloured as they pulse. */
layerState._heatJam = [];
/** @type {number[]} The jam heat-lines' colour, without its alpha. */
layerState._heatJamRgb = [1, 1, 1];
/** @type {number} Heat-lines in the current render (stats). */
layerState._heatLineCount = 0;
/** @type {number} Altitude of the last render, for late-flow heat rebuilds. */
layerState._lastRenderAltitude = 0;
/**
* Active post-FX style (StyleManager preset name), synced from
* `document.documentElement.dataset.gevStyle` at init and the
* `gev:style-change` window event thereafter. Drives the preset-aware dot
* styling (`trafficPresetStyle.js`): NVG/FLIR/noir re-encode congestion in
* luminance + size (their shaders discard hue), retro/CRT gets saturated
* hues + a size boost to survive pixelation. 'normal' → shipped palette.
* @type {string}
*/
layerState._stylePreset = 'normal';
/** @type {'on'|'off'} Kill switch for preset-aware dot styling (A/B). */
layerState._presetDots = 'on';
/** @type {boolean} gev:style-change listener bound (bind once per page). */
layerState._styleListenerBound = false;
/**
* Effective per-bucket dot colors: preset override when one applies, else
* the shipped FLOW_BUCKET_COLORS. Rebuilt on style/param change only —
* spawn/recolor/restyle all read from here, no per-dot allocation.
* Renderer colours (`[r, g, b, a]`, 0..1).
* @type {{free:number[], slow:number[], jam:number[]}}
*/
layerState._activeBucketColors = { ...FLOW_BUCKET_COLORS };
/**
* Dot fade-out distances, recomputed per render from the camera-to-area
* distance. The original constants (8 km scale / 10 km translucency)
* assumed a nadir view; at oblique pitch the loaded area legitimately sits
* 7–12+ km from the CAMERA and every dot faded to invisible (field-test
* round 1: "the screen itself was empty").
*/
layerState._fadeScaleFar = 8000;
layerState._fadeTransFar = 10000;
/** @type {Promise<void>|null} Session-cached status check (one fetch per session) */
layerState._flowStatusPromise = null;
layerState._flowStatusSignal = null;
/** @type {ReturnType<typeof setInterval>|null} Enable-time retry until the first load commits. */
layerState._enableKickTimer = null;
// Failed destinations retry while parked, with a bounded backoff.
layerState._retryTimer = null;
layerState._retryDelayMs = 1500;
layerState._retryBoundsKey = null;
layerState._roadError = null;
layerState._roadSource = 'OpenStreetMap';
layerState._roadPartial = false;
layerState._roadRetryStopped = false;
layerState._retryAttempts = 0;
/** Parsed road set whose current flow request owns the feed status. */
layerState._flowRoads = null;
/** @type {Function|null} Development-only camera moveEnd timing disposer. */
layerState._trafficTimingMoveEndRemover = null;
/** @type {Set<Function>|null} Development-only one-shot postRender disposers. */
layerState._trafficTimingPostRenderRemovers = null;
/** @type {{interactionId:number, timestamp:number}|null} Debug anchor for the pending load. */
layerState._trafficTimingCurrentAnchor = null;
/** @type {number} Development-only unique mark/trace sequence. */
layerState._trafficTimingSequence = 0;
/** @type {number} Development-only count of correlated trace objects created. */
layerState._trafficTimingTracesCreated = 0;
/** @type {number} Development-only count of loads dropped for missing/stale anchors. */
layerState._trafficTimingDroppedTraces = 0;
/**
* Tile cache keyed by "s,w,n,e" string.
* Each entry stores separately fetched major-only and full road sets
* so the major pass can be served from cache while a full fetch continues.
* @type {Map<string, {major: Array|null, full: Array|null}>}
*/
layerState._tileCache = new Map();
// ─── Animation ─────────────────────────────────────────────
/** @type {number} Timestamp of the last animation tick (ms) */
layerState._lastAnimTime = 0;
/** @type {number} Running frame counter (for diagnostics) */
layerState._animFrame = 0;
// Disabled-path contract: these references resolve directly to the original
// functions. Instrumentation adds no load-path callbacks or per-item checks.
return layerState;
}