Files
gods-eye-view/src/layers/vessels/lifecycle.js
T
Sameh Khamis 02d492a079 Take pointer input through one dispatcher per scene
Every layer and tool bound its own ScreenSpaceEventHandler and picked the
same click again: with the usual layers on, one click ran about 26
scene.pick and 2 drillPick passes (120-215 ms in NYC with 18 layers). Pointer
input now comes in through src/input/dispatcher.js, one handler per scene.
A click is picked lazily and at most once per kind of query, and every
subscriber reads the same ClickEvent (pick, hit, id, ownerId, gesture,
drill, ground). The same click now costs 3 picks and 2 drills, 17-70 ms.

- Ambient onClick subscribers run only while no tool holds the pointer,
  checked once per event; tools subscribe with their lease. Moves and
  releases always reach ambient subscribers, so hover and drags end cleanly.
- Camera input and the viewer's stock select/track clicks are ref-counted
  holds (suspendCamera, suppressStockClicks). The dispatcher owns the
  controller's enableInputs, so a Cesium flight that ends no longer turns
  input back on under a drag or the cockpit.
- The draw tool, imagery box, CCTV gizmo, cockpit, directions and every
  selecting layer use it; bindTrackingClickGesture is gone (the gesture is
  on the event). A source scan forbids new handlers, enableInputs writes and
  stock-click removal outside the dispatcher.
- The sensor-style pick correction transit had now applies to every layer.
- Radio's 8-pick near-miss ring is one 17x17 windowed drill.
- A missed pick passed to pickContact is no longer picked again, and a
  touch tap's contact search shares the click's drill.
- A gizmo drag whose release Cesium never reported ends on the next press
  instead of leaving the camera held.

The dispatcher is exported as ./input with the pointer-lease functions, and
documented in docs/APPLICATION.md.
2026-11-04 08:48:51 -08:00

274 lines
9.7 KiB
JavaScript

import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { msg, t } from '../../i18n/index.js';
import { AIS_FIRST_CONNECT_GRACE_MS, AIS_HEALTHY_STATUSES } from './policy.js';
export function createLifecycle({
vesselState,
services,
parts: components,
layer,
options,
}) {
const { state } = vesselState;
const { restoreSpriteOrder, restoreSpriteOrderOnEnable } = services.sprites;
const { releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
function clearFirstConnectTimer() {
if (state.feed.firstConnectTimer === null) return;
vesselState._aisRuntime.clearTimeout(state.feed.firstConnectTimer);
state.feed.firstConnectTimer = null;
}
function invalidateAisSession() {
clearFirstConnectTimer();
state.feed.sessionId = ++vesselState._aisSessionSequence;
state.feed.firstConnectPhase = 'idle';
state.feed.firstConnectStartedAt = null;
state.feed.firstConnectDeadline = null;
}
function beginAisSession() {
clearFirstConnectTimer();
const sessionId = ++vesselState._aisSessionSequence;
const startedAt = vesselState._aisRuntime.now();
state.feed.sessionId = sessionId;
state.feed.firstConnectPhase = 'loading';
state.feed.firstConnectStartedAt = startedAt;
state.feed.firstConnectDeadline = startedAt + AIS_FIRST_CONNECT_GRACE_MS;
state.feed.error = null;
state.feed.loadingLabel = t('awaiting first AIS position…');
scheduleFirstConnectExpiry(sessionId, AIS_FIRST_CONNECT_GRACE_MS);
}
function scheduleFirstConnectExpiry(sessionId, delayMs) {
state.feed.firstConnectTimer = vesselState._aisRuntime.setTimeout(() => {
if (
!state.feed.enabled ||
state.feed.sessionId !== sessionId ||
state.feed.firstConnectPhase !== 'loading'
)
return;
const remainingMs =
state.feed.firstConnectDeadline - vesselState._aisRuntime.now();
if (remainingMs > 0) {
scheduleFirstConnectExpiry(sessionId, remainingMs);
return;
}
state.feed.firstConnectTimer = null;
state.feed.firstConnectPhase = 'unavailable';
state.feed.loadingLabel = '';
state.feed.error = state.feed.lastMessageAt
? t('awaiting usable AIS positions…')
: t('awaiting first AIS message…');
state.feed.stale = state.feed.count > 0;
}, delayMs);
}
function settleFirstConnectPhase(phase) {
clearFirstConnectTimer();
state.feed.firstConnectPhase = phase;
state.feed.loadingLabel = '';
}
function isGraceEligibleTransport(status) {
return AIS_HEALTHY_STATUSES.has(status) || status === 'connecting';
}
function isDefinitiveTransportFailure(status) {
return Boolean(status) && !isGraceEligibleTransport(status);
}
function markAisUnavailable(reason) {
settleFirstConnectPhase('unavailable');
state.feed.error = reason || msg('AIS live load failed');
state.feed.stale = state.feed.count > 0;
}
function resetState() {
components.rendering.resetRecordVisuals();
state.feed.abort?.abort();
state.trailAbort?.abort();
state.trailAbort = null;
clearFirstConnectTimer();
state.viewer = null;
state.feed.enabled = false;
state.feed.loading = false;
state.feed.loaded = false;
state.feed.stale = false;
state.feed.partial = false;
state.feed.error = null;
state.feed.loadingLabel = '';
state.feed.lastUpdate = null;
state.feed.count = 0;
state.feed.newestPositionAt = null;
state.feed.transportStatus = null;
state.feed.nextAttemptAt = null;
state.feed.lastMessageAt = null;
state.feed.rawRowCount = 0;
state.feed.acceptedRowCount = 0;
state.feed.sessionId = ++vesselState._aisSessionSequence;
state.feed.firstConnectPhase = 'idle';
state.feed.firstConnectStartedAt = null;
state.feed.firstConnectDeadline = null;
state.feed.firstConnectTimer = null;
state.feed.abort = null;
state.icons = null;
state.iconPrimitive = null;
state.records.all = [];
state.records.byMmsi = new Map();
state.records.unkeyed = [];
state.clickSubscription = null;
state.keyTarget = null;
state.keydownHandler = null;
state.trackedEntityRemover = null;
state.interactionKeyTarget = null;
state.preRenderRemover = null;
components.rendering.cancelTrailingVisibilityPass();
state.lastVisibilityUpdate = 0;
state.lastFocusUpdate = 0;
state.activeFocusCount = 0;
state.activeLabelCount = 0;
state.selectedRecord = null;
state.trail = null;
state.trailPositions = [];
state.trailMmsi = null;
state.trailBackfillToken = 0;
}
const methods = {
/** Configure the source before initialization; an active layer keeps its owner. */
setSource(source) {
if (state.viewer)
throw new Error('Configure the source before layer initialization');
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('A snapshot source is required');
vesselState._source = source;
this.source = source.label || this.source;
},
init(viewer) {
if (typeof vesselState._source?.getSnapshot !== 'function')
throw new TypeError('A snapshot source is required');
state.viewer = viewer;
components.rendering.ensureCollections(viewer);
vesselState._vesselOverlayHost.setVisible(
VESSEL_OVERLAY_SOURCE_ID,
false,
);
components.selection.installInteraction(viewer);
components.rendering.installRuntime(viewer);
restoreSpriteOrder(viewer);
},
enable(viewer) {
const wasEnabled = state.feed.enabled;
state.feed.enabled = true;
if (!wasEnabled) beginAisSession();
const activeViewer = viewer || state.viewer;
components.rendering.ensureCollections(activeViewer);
components.selection.installInteraction(activeViewer);
components.rendering.setVisible(true);
// Height-datum fix: warm the geoid grid once per layer-enable, never
// blocking a poll. The first refresh may land pre-resolve (N = 0), and
// the next is up to 60 s out — so re-floor in place on resolve. A load
// failure leaves N = 0 forever, which is safe: sprites are depth-test-
// free, so vessels stay visible either way.
if (!vesselState._geoidReady) {
const sessionId = state.feed.sessionId;
ensureGeoidReady()
.then(() => {
if (!state.feed.enabled || state.feed.sessionId !== sessionId)
return;
vesselState._geoidReady = true;
components.tracking.refloorVesselRecords();
})
.catch(() => {
/* grid failed to load — anchors stay at ellipsoid 0 */
});
}
// Pick-ownership (H2): a vessel icon's pick id is its row id, the MMSI.
registerPickOwner('ais-live-vessels', (pickedId) =>
state.records.byMmsi.has(pickedId),
);
restoreSpriteOrderOnEnable('ais', activeViewer);
// Vessels are asked for by view, so ask again when the view moves away.
removeViewListener();
const moveEnd = activeViewer?.camera?.moveEnd;
if (typeof moveEnd?.addEventListener === 'function')
state.feed.removeViewListener = moveEnd.addEventListener(() => {
components.ingestion.refreshIfMoved(activeViewer);
});
return components.ingestion.loadLivePositions(activeViewer);
},
disable() {
removeViewListener();
state.feed.enabled = false;
invalidateAisSession();
releaseContinuousRender('ais-vessels');
components.rendering.cancelTrailingVisibilityPass();
unregisterPickOwner('ais-live-vessels');
components.rendering.setVisible(false);
vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID);
components.selection.clearVesselInspection();
components.tracking.destroySelectedVesselTrail();
components.selection.removeVesselInteraction();
if (state.feed.abort) {
state.feed.abort.abort();
state.feed.abort = null;
}
state.feed.loading = false;
state.feed.loadingLabel = '';
},
destroy(viewer) {
removeViewListener();
const activeViewer = viewer || state.viewer;
invalidateAisSession();
releaseContinuousRender('ais-vessels'); // direct-destroy path (perf wave 2 fix)
components.rendering.cancelTrailingVisibilityPass();
if (state.feed.abort) state.feed.abort.abort();
unregisterPickOwner('ais-live-vessels');
components.selection.clearVesselInspection();
components.tracking.destroySelectedVesselTrail();
if (state.iconPrimitive && activeViewer?.scene?.primitives) {
activeViewer.scene.primitives.remove(state.iconPrimitive);
}
// Not in a scene (or no viewer to remove it from): still stop its atlas
// listener and free its GPU resources.
if (state.iconPrimitive && !state.iconPrimitive.isDestroyed())
state.iconPrimitive.destroy();
vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID);
vesselState._vesselOverlayHost.setVisible(
VESSEL_OVERLAY_SOURCE_ID,
false,
);
components.selection.removeVesselInteraction();
if (state.preRenderRemover) {
state.preRenderRemover();
}
resetState();
},
};
function removeViewListener() {
const remove = state.feed.removeViewListener;
state.feed.removeViewListener = null;
if (typeof remove === 'function') remove();
}
return {
clearFirstConnectTimer,
invalidateAisSession,
beginAisSession,
scheduleFirstConnectExpiry,
settleFirstConnectPhase,
isGraceEligibleTransport,
isDefinitiveTransportFailure,
markAisUnavailable,
resetState,
methods,
};
}