import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js'; import { entityFollowTarget, onFollowChanged, stopFollowing, } from '../../data/followed.js'; import { formatNumber, t } from '../../i18n/index.js'; import { unitLabel } from '../../ui/unitLabels.js'; import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js'; import { courseScreenRotation, stabilizeScreenRotation, } from '../../data/screenRotation.js'; import { createTrackedAircraftIcon, isOtherTrackedIconSet, trackedContactHolder, } from '../../data/trackedAircraftIcon.js'; import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; import { julianToEpochMs } from '../../geo/julian.js'; import { renderedFrames } from '../../data/renderedFrames.js'; import { clone, distance, distanceSquared, vec } from '../../geo/vector.js'; import { trailHeadStart } from '../../data/modelVisualAnchor.js'; import { routePlausible } from '../../data/routePlausible.js'; import { isTrackingSelectionGesture, isTrackingClickGesture, } from '../../data/trackingClickGesture.js'; import { inputFor } from '../../input/dispatcher.js'; import { TRAIL_MAX_POINTS, DR_CORRECTION_MS, TRAIL_COLOR, CYAN_TRANSPARENT, TRACKED_CYAN, STALE_ALPHA, displayDelayMs, followsClock, } from './policy.js'; import { drawTrailSegments, historyFixEpochMs, insertTrailFix, joinTrailBackfill, recordTrailPoint, trailBackfillFixes, trailBodyCount, trailBodyCountOutsideModel, trailBodySegments, trailHeadStartFix, trailRecordingBlocked, TRAIL_RECORD_STEP_M, TRAIL_RECORD_STEP_MS, } from '../../data/trailContinuity.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord } from '../../data/entityRecords.js'; /** * The icao a click's hit carries (`event.hit`, the contract's `Hit`): a * draw-set item's id (the icon and model sets' rows), or the id of * something drawn outside the draw port (a hit with no set). */ function aircraftPickId(hit) { if (!hit || hit.surface) return undefined; if (!hit.set) return hit.id || undefined; return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id; } const STALE_CYAN = Object.freeze([...TRACKED_CYAN.slice(0, 3), STALE_ALPHA]); export function createTracking({ flightState, services, parts, layer, resolveAsset, }) { const { selectTrackedSubjectContext, clearTrackedSubjectContext, refreshTrackedSubjectContext, } = services.context; const { isTr3b, tr3bTypeLabel, tr3bConvertedIds } = services.aircraftPresentation; const { createTrail } = services.trails; const { ensureGeoidReady, geoidHeight } = services.geoid; const { resolveGroundFloorCellsBounded, floorAltitudeM, cachedGroundFloor } = services.groundFloor; const { clearFocusTarget } = services.focus; const { isMilitaryLayerActive, isMilitaryIcao } = services.militaryRegistry; const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout; const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, keptViewFrom } = services.camera; const { resolvePickId, isOwnedByOtherLayer } = services.picking; const flightsLayer = layer; /** The tracked contact's billboard (an icon set on the draw port). */ const trackedIcon = createTrackedAircraftIcon({ viewer: () => flightState._viewer, setPrefix: 'flights', }); /** The camera's pose, or null without a camera to ask. */ function _pose() { const viewer = flightState._viewer; try { return (viewer && findCamera(viewer)?.pose()) ?? null; } catch { return null; } } function _emitAwarenessEvent(type, detail) { if ( typeof window === 'undefined' || !window.dispatchEvent || typeof CustomEvent === 'undefined' ) return; window.dispatchEvent(new CustomEvent(type, { detail })); } function _publishTrackedSelection(icao24, origin = 'programmatic') { const position = parts.icons._iconPosition(icao24, vec()); const info = flightState.records.data.get(icao24); if (!position || !info) return false; if (flightState._trackedEntity) entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { layerId: 'flights', id: icao24, // Canonical display chain (callsign → registration → hex). Publishing a // bare `callsign || icao24` here resurrected the pre-enrichment behavior: // a callsign-less contact reached Context as its raw hex even once adsbdb // had supplied a registration. Identity below stays `icao24`. label: parts.queries._contactLabel(icao24, info), position, origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(icao24)); return true; } /** * Describe the selected contact for the shared context slot the voice tools * and Cockpit read. Values are the LIVE descriptor, not a selection-time * snapshot, so a long follow never narrates a position the plane has left. * @param {string} icao24 Contact identity. * @returns {object|null} Context metadata, or null when the contact is gone. */ function _contextSubjectMetadata(icao24) { const described = parts.queries._describeFlight(icao24); if (!described) return null; const altFt = Math.round((described.altitudeM || 0) * 3.28084); const route = described.route && _routeIsPlausible(icao24, described.route) ? `${described.route.origin.code} → ${described.route.destination.code}` : null; return { id: icao24, layerId: 'flights', layerName: 'Live Flights', source: flightState.feed._lastSource, label: parts.queries._contactLabel( icao24, flightState.records.data.get(icao24), ), latitude: described.latitude, longitude: described.longitude, // Flat text only: the voice payload compacts properties through a // string cleaner that drops nested objects. properties: { name: parts.queries._contactLabel( icao24, flightState.records.data.get(icao24), ), operator: described.airline || '', callsign: described.callsign || '', registration: described.registration || '', type: described.typeName || described.typeCode || '', altitude: described.onGround ? 'on ground' : `${altFt.toLocaleString('en-US')} ft`, speed: Number.isFinite(described.velocityMps) ? `${Math.round(described.velocityMps * 1.944)} kt` : '', heading: Number.isFinite(described.track) ? `${roundHeadingDegrees(described.track)}°` : '', route: route || '', icao24, // Honesty cue: the contact is coasting on dead reckoning, so the // narrated position/velocity are last-known rather than live. // i18n-ignore: voice-context data, English for the model status: described.stale ? 'stale (missed polls)' : 'live', }, }; } function _isExplicitTrackingOrigin(origin) { return origin === 'user' || origin === 'voice' || origin === 'tool'; } /** * Refresh the Cockpit AIR near/far band without consulting model state. * Near contacts keep their 2D aircraft silhouette when 3D is off, loading, or * capped; only a ready admitted model may take that silhouette over later. */ function _refreshCockpitNearContacts() { const eye = flightState._cockpitContactMode ? _pose()?.position : null; if (!eye) { if (flightState._cockpitNearContacts.size) flightState._cockpitNearContacts = new Set(); return; } const previous = flightState._cockpitNearContacts; const distancesSquared = []; const icons = flightState._icons; const t = parts.icons._displayMs(); for (const icao24 of icons?.ids() ?? []) { if (icao24 === flightState._trackedIcao) continue; const position = icons.position( icao24, t, flightState._scratchCockpitPos, ); distancesSquared.push([icao24, distanceSquared(eye, position)]); } const next = nextCockpitNearContacts( previous, distancesSquared, parts.rendering._modelAddDistM(), parts.rendering._modelKeepDistM(), ); flightState._cockpitNearContacts = next; for (const icao24 of previous) if (!next.has(icao24)) parts.icons._applyIconPresentation(icao24); for (const icao24 of next) if (!previous.has(icao24)) parts.icons._applyIconPresentation(icao24); } /** Switch all current and future ambient contacts between silhouettes and cockpit pips. */ function _setCockpitContactMode(active) { const next = active === true; if (flightState._cockpitContactMode === next) return; flightState._cockpitContactMode = next; if (next) _refreshCockpitNearContacts(); else flightState._cockpitNearContacts = new Set(); // The collection stays visible in cockpit. Near AIR contacts retain their // aircraft silhouette until a ready model takes over; far contacts are pips. // Never destroy on entry: tearing down hundreds of live glTF instances // synchronously blocked Chrome's renderer into Page Unresponsive. parts.rendering._setModelsShown(true); flightState._trail?.setVisible(!next); for (const icao24 of flightState._icons?.ids() ?? []) parts.icons._applyIconPresentation(icao24); flightState._lastFleetTickMs = 0; } function _applyCockpitState(detail = {}) { const active = detail?.active === true; flightState._cockpitSubjectId = active ? String(detail?.subjectId || '') .trim() .toLowerCase() || null : null; _setCockpitContactMode(active); } /** Start a selection's tracked-model state afresh: the model it draws * with (whatever the fleet drew it with, a model or its icon) and the * load-failure budget. Called from each path that changes which contact * is selected — deselect, re-track, cross-layer handoff, init, destroy. */ function _resetTrackedSelectionState() { flightState._trackedModelEligible = Boolean( flightState._trackedIcao && flightState._models?.has(flightState._trackedIcao), ); flightState._trackedModelFailIcao = null; flightState._trackedModelFailCount = 0; flightState._trackedModelRetryAtMs = 0; } /** * Whether the TRACKED aircraft draws as its 3D model: exactly when the * fleet's own rule would draw it so (`_modelRegimeActive` — 3D on and the * camera below the ceiling — and a place in the nearest-first cap, which * the fleet pass keeps in `_trackedModelEligible`). Selecting a contact * therefore never turns its icon into a model or its model into an icon. * A converted TR-3B has no 3D asset, and in cockpit you sit in your own * airframe, so neither draws one. */ function _trackedModelRegimeActive() { if ( !flightState._trackedIcao || flightState._cockpitContactMode || isTr3b(flightState._trackedIcao) ) return false; return ( flightState._trackedModelEligible === true && parts.rendering._modelRegimeActive() ); } /** Seed the tracked billboard's 2D orientation before a 3D→2D handoff. */ function _syncTracked2dRotation() { if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || parts.icons._iconPosition(flightState._trackedIcao, vec()); if (!pos) return; const projected = courseScreenRotation( _pose(), pos, parts.motion._trackedDisplayCourse(), flightState._lastTrackedRotation, ); const rotation = stabilizeScreenRotation( flightState._lastTrackedRotation, projected, 0, ); if (rotation !== null) flightState._lastTrackedRotation = rotation; } /** * Put one report into the tracked aircraft's trail, in time order, and * refresh the rendered trail. Caller passes an owned (cloned) position. A * report that breaks from its neighbour starts a new segment (see * trailContinuity). * @param {{x: number, y: number, z: number}} position - The report's ECEF position. * @param {number} [epochMs] - The report's time; defaults to the tracked * aircraft's newest position-history fix, which every caller has just pushed. * @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report * had no altitude, so its position is not kept and the line breaks there. * A report for a time the display has already passed replaces what was * drawn after it (see `insertTrailFix`). */ function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) { const history = flightState._positionHistory.get(flightState._trackedIcao); const timeMs = Number.isFinite(epochMs) ? epochMs : historyFixEpochMs(history?.[history.length - 1]); insertTrailFix( flightState._trailFixes, position, timeMs, TRAIL_MAX_POINTS, { nullAltitude, displayMs: flightState.now() - displayDelayMs(flightState), settleMs: DR_CORRECTION_MS, }, ); _refreshTrailDisplay(); } /** * Per-frame trail work, run before each frame draws whether or not the * head is visible: record where the tracked icon is drawn (at most once a * second or every 150 m) and move the body on as the display time passes * reports. The head only reads the result. */ function _trailTick() { if (!flightState._trackedIcao || !flightState._trail) return; const displayMs = flightState.now() - displayDelayMs(flightState); let changed = false; if ( flightState._trailFixes.length && !parts.motion._isTrackWarmingUp() && !trailRecordingBlocked(flightState._trailFixes, displayMs) ) { const drawn = parts.motion._trackedDisplayPosition( flightState._trackedIcao, ); const last = flightState._trailRecordPosition; if ( drawn && (!last || displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS || distance(last, drawn) >= TRAIL_RECORD_STEP_M) ) { flightState._trailRecordMs = displayMs; flightState._trailRecordPosition = clone(drawn); changed = recordTrailPoint( flightState._trailFixes, clone(drawn), displayMs, TRAIL_MAX_POINTS, ); } } if (changed || _trailBodyCountNow() !== flightState._trailBodyCount) _refreshTrailDisplay(); } /** * Renders the trail with its head clamped to the render-behind display * position. Raw newest fixes run up to RENDER_DELAY_SEC ahead of the * displayed aircraft (PRD C2 delayed clock) — drawing them verbatim makes * the trail extend in FRONT of the icon. The head is refreshed ~1Hz from * the fleet tick so it stays glued to the moving aircraft. */ function _refreshTrailDisplay() { // The trail BODY is the accumulated fixes at or before the delayed display time // (now − RENDER_DELAY_SEC); newer fixes are AHEAD of the icon, so drawing them // would push the trail in front of the plane. The cheap per-frame trail head // line bridges the last body point to the delayed dead-reckoned head, so the // body rebuilds only on a real fix or when the display time passes one, never // at motion cadence. // A break lifts the pen: each segment is its own line, nothing between them. if (!flightState._trail) return; flightState._trailBodyCount = _trailBodyCountNow(); drawTrailSegments( flightState._trail, trailBodySegments(flightState._trailFixes, flightState._trailBodyCount), ); } /** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC), * less the newest recorded points inside its 3D model. */ function _trailBodyCountNow() { return trailBodyCountOutsideModel( flightState._trailFixes, trailBodyCount( flightState._trailFixes, flightState.now() - displayDelayMs(flightState), ), parts.motion._trackedModelCenterWorld(), parts.motion._trackedModelEnvelopeM(), ); } /** * The live head: the last DISPLAYED body point to the delayed head, or no * positions while there is none. * @returns {Array<{x: number, y: number, z: number}>} */ function _trailHeadPositions() { // The head starts at the last DISPLAYED body point, the newest fix at or // before the delayed display time; a fix ahead of the icon would draw the // segment IN FRONT of the plane. During warm-up the icon predates all real // history, so there is no valid body point behind it. if ( !flightState._trackedIcao || !flightState._trailFixes.length || parts.motion._isTrackWarmingUp() ) return []; const head = parts.motion._trackedTrailCached() || parts.motion._trackedDisplayPosition(flightState._trackedIcao); if (!head) return []; // The last body point (a report, or where the icon was drawn a moment // ago) → the icon. No head across a break: a body point more than 150 km // away, or too long ago or too far to be one path, stays detached; none // while the aircraft holds at its last point. const last = trailHeadStartFix( flightState._trailFixes, head, flightState.now(), flightState._trailBodyCount, ); if (!last) return []; // On a contact that has not moved this segment runs from inside the // model out to its own anchor — a line through the fuselage. The END // never gives, so a moving trail still terminates on the tail; the // START is what slides, from nothing on a parked contact out to the // whole segment once it has cleared its own envelope. // See trailHeadStart. Read `head` in place and clone only on the draw // path — a suppressed parked contact runs this every frame. const from = trailHeadStart( last.position, head, parts.motion._trackedModelCenterWorld(), parts.motion._trackedModelEnvelopeM(), flightState._scratchTrailHead, ); if (!from) return []; return [from, clone(head)]; } /** Each drawn frame, before it draws: the trail moved on, then the live * head where the aircraft is now. */ function _drawTrailHead() { _trailTick(); flightState._trail?.setHead(_trailHeadPositions()); } /** * Start the trail for a newly tracked aircraft: seed it with the short * dead-reckoning history (chronological), render immediately, then * fire-and-forget an OpenSky track backfill. * @param {string} icao24 - ICAO 24-bit transponder address being tracked. */ function _startTrail(icao24) { flightState._trailBackfillToken += 1; flightState._trailFixes = []; flightState._trailRecordPosition = null; flightState._trailRecordMs = -Infinity; const history = flightState._positionHistory.get(icao24) || []; // Seed every report. The body only draws those at or before the delayed // display time (now − RENDER_DELAY_SEC); newer ones join it as the display // passes them. A synthetic forward fix (it carries `reportEpochMs`) is a // motion aid, never a report. A report drawn at an invented height keeps // no position and breaks the line. for (const fix of history) { if (Number.isFinite(fix.reportEpochMs)) continue; insertTrailFix( flightState._trailFixes, clone(fix.position), historyFixEpochMs(fix), TRAIL_MAX_POINTS, { nullAltitude: fix.inventedHeight === true, onGround: fix.onGround }, ); } if (!flightState._trail && flightState._viewer) { flightState._trail = createTrail(flightState._viewer, { color: TRAIL_COLOR, width: 2.5, }); } flightState._trail?.setVisible(!flightState._cockpitContactMode); // Live head segment: last displayed body point → current dead-reckoned icon, drawn // again each frame before it draws, so it stays glued to the 12 Hz icon instead of // lagging ~1 s behind it. Only the head line is rebuilt; the body rebuilds on a real // fix (poll cadence). Dimmed where occluded (round 4), geodesic as the body (round 8). if (!flightState._trailHeadOff && flightState._viewer) { flightState._trailHeadOff = findFrame(flightState._viewer)?.on('preRender', _drawTrailHead) ?? null; } _refreshTrailDisplay(); const oldestFixEpochSec = history.length ? julianToEpochMs(history[0].time) / 1000 : Infinity; _backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec); } /** * Fire-and-forget OpenSky /tracks backfill (PRD F1). On success, splices * waypoints strictly older than the oldest seeded fix AHEAD of the locally * accumulated fine segment, capped at TRAIL_MAX_POINTS (newest kept). Any * failure (404/429/timeout/malformed) silently keeps the local-only trail. * @param {string} icao24 - ICAO 24-bit transponder address being tracked. * @param {number} token - Backfill token captured at request time. * @param {number} oldestFixEpochSec - Epoch seconds of the oldest seeded fix. * @returns {Promise} */ async function _backfillTrail(icao24, token, oldestFixEpochSec) { let path = null; // Following the world clock, the track ends at the world's time. const atMs = followsClock(flightState) ? flightState.now() : undefined; try { const signal = AbortSignal.any([ flightState.lifetime.signal, AbortSignal.timeout(8000), ]); const track = await flightState.feed._source.getTrack?.( flightState.records.data.get(icao24)?.sourceReference ?? icao24, atMs === undefined ? { signal } : { signal, atMs }, ); path = track?.records ?? null; } catch { return; // silent fallback to the accumulated trail } if ( !path || token !== flightState._trailBackfillToken || icao24 !== flightState._trackedIcao ) return; // OpenSky track waypoints: [time, latitude, longitude, baro_altitude, true_track, on_ground] // Height-datum fix (Task 6): /tracks only ever reports barometric/MSL altitude // (no per-waypoint geo_altitude in this endpoint), so waypoint render height is // the documented visual FALLBACK baroM + geoidHeight(waypointLat, waypointLon) // — geometrically approximate, not exact, same honesty caveat as the live // baro-fallback branch of pickRenderAltitudeM. await ensureGeoidReady(); const parsed = []; for (const waypoint of path) { const { observedAtMs, latitude: lat, longitude: lon, baroAltitudeM: baroAlt, } = waypoint; const time = observedAtMs / 1000; if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; if (atMs !== undefined && !(observedAtMs <= atMs)) continue; if (!Number.isFinite(time) || time >= oldestFixEpochSec) continue; parsed.push({ lat, lon, baroAlt, onGround: waypoint.onGround === true, timeMs: observedAtMs, }); } if (!parsed.length) return; // Field-test fix (WAKE01 trail-underground, 2026-07-06 — mirror of // militaryFlights.js): resolve the coarse ellipsoidal ground along the track // and floor every waypoint at it so low baro segments never dive below the // mesh; a no-baro waypoint (predominantly taxi/ground segments in /tracks) // sits ON the surface when the floor is known. // Round-2 fix (owner: "trails suddenly much shorter / not loading"): the // resolve is BOUNDED (≤1.2 s), not a blocking await — a cold Re:Earth // lookup across a long path could stall the paint for seconds-to-timeout. // Paint with whatever cells are warm; the resolve keeps filling the cache // in the background for the next paint/select. await resolveGroundFloorCellsBounded(parsed); // Re-check the backfill token after the await (same guard as post-fetch): // tracking may have moved on while the terrain race was in flight. if ( token !== flightState._trailBackfillToken || icao24 !== flightState._trackedIcao ) return; // Every waypoint is kept, each leg its own segment. A ground waypoint is // at altitude 0, floored at the ground. A waypoint with no altitude is a // break on both sides: it sits on the ground where the floor is known and // is skipped otherwise; a skipped point still breaks the line. const backfill = trailBackfillFixes( parsed.map(({ lat, lon, baroAlt, onGround, timeMs }) => { const known = Number.isFinite(baroAlt) ? baroAlt : onGround ? 0 : null; const altM = floorAltitudeM( known == null ? null : known + geoidHeight(lat, lon), cachedGroundFloor(lat, lon), ); return { position: altM == null ? null : fromDegrees(lon, lat, altM), timeMs, nullAltitude: known == null, }; }), ); // A history that ends in the air does not join an aircraft now on the // ground (or the reverse) across a landing or take-off nobody saw. flightState._trailFixes = joinTrailBackfill( backfill, flightState._trailFixes, TRAIL_MAX_POINTS, { backfillEndsOnGround: parsed[parsed.length - 1].onGround, onGroundNow: flightState.records.data.get(icao24)?.onGround, nowMs: flightState.now(), }, ); _refreshTrailDisplay(); } /** * Clear the rendered trail and accumulation; invalidate pending backfills. */ function _clearTrail() { flightState._trailBackfillToken += 1; flightState._trailFixes = []; flightState._trailRecordPosition = null; flightState._trailRecordMs = -Infinity; if (flightState._trail) flightState._trail.clear(); flightState._trailHeadOff?.(); flightState._trailHeadOff = null; } /** * Destroy the trail primitive entirely (layer disable/teardown). */ function _destroyTrail() { _clearTrail(); if (flightState._trail) { flightState._trail.destroy(); flightState._trail = null; } } /** * Stop tracking the currently followed aircraft. * * Restores the hidden billboard, removes the tracked Entity, resets lerp * state, and RELEASES the camera IN PLACE — no flyTo. Deselect used to fly * an ~80 km pulled-back overview; the owner field-ruled that wrong * (2026-07-02: "it randomly zooms way up and loses my context"). The camera * now simply stays at its current position/orientation, immediately free to * orbit/zoom. Applies to every deselect path: click-empty-space, Escape, * aged-out plane, layer disable, and voice stopTracking. * * @param {boolean} [skipViewerUntrack=false] - ANOTHER layer just grabbed the * follow-camera: tear down our own state but leave the camera's follow * alone (the new owner controls it). * @param {object} [options] - Clear origin. * @param {boolean} [options.evicted=false] - The contact aged out of the feed * rather than being deselected. Consumers that keep a readout on screen * (the Cockpit Contact panel) hold last-known values for an eviction and * only tear down on a deliberate clear. */ function _clearTracking( skipViewerUntrack = false, { evicted = false, origin = 'programmatic' } = {}, ) { flightState._followTarget = null; if (!flightState._trackedIcao) { clearFocusTarget('flights'); return; } const clearedIcao = flightState._trackedIcao; clearFocusTarget('flights', clearedIcao); // The nose the icon continues from (the shared _displayCourse entry), so // release never flips it. const trackedCourseDeg = flightState._displayCourse.get(clearedIcao); // Stop tracking and hide the tracked billboard. skipViewerUntrack: when ANOTHER layer just // grabbed the follow-camera, we tear down our own state but must NOT clear the camera's follow // (the new owner controls it now — clearing it would yank the camera off their plane). // Releasing the follow does NOT move the camera: the view stays where the follow left it and // the user can immediately orbit/zoom. if (flightState._viewer && !skipViewerUntrack) { stopFollowing(flightState._viewer); } trackedIcon.hide(); flightState._trackedEntity = null; parts.rendering._releaseTrackedModel(); _resetTrackedSelectionState(); // the zoom band + load-failure budget belong to the selection we just dropped flightState._trackedIcao = null; // Hand the contact back to its icon only now: settling floors a grounded // contact, and while it still read as tracked its tracked model owned the // visual, so the floor would have stepped aside. if (flightState._icons?.has(clearedIcao)) { flightState._icons.setShown(clearedIcao, true); parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg }); } parts.icons._applyIconPresentation(clearedIcao); clearTrackedSubjectContext('flights'); _emitAwarenessEvent('gev:awareness-subject-cleared', { layerId: 'flights', id: clearedIcao, origin, reason: evicted ? 'evicted' : 'deliberate', }); // Invalidate the per-frame DR cache + reconciliation state so a same-frame re-track // cannot read the previous aircraft's cached/smoothed position. parts.motion._resetTrackedDisplay(); _clearTrail(); } /** * Whether the Military layer suppresses this civil duplicate right now. * * The dedicated Military layer owns icon/track/click for known-military * contacts, so the OpenSky duplicate is dropped while that layer is on. Two * contacts are exempt, both for the same reason — this layer still owns them: * * - the CURRENTLY tracked one, which hands off on untrack; and * - a target this layer is holding on its deferred-restore latch. * * The second exemption is what makes a shared/local Follow of a mil-registry * hex restorable at all. The accepted-snapshot id set is built BEFORE this * suppression runs, so without it the target is provably present in a healthy * feed yet has no billboard, `trackById` fails, and the restore reports * "feed unavailable" about a feed that was perfectly fine. * * @param {string} icao24 - Normalized ICAO 24-bit address. * @returns {boolean} True when the civil duplicate must be dropped. */ function _militaryLayerSuppresses(icao24) { if (!isMilitaryLayerActive()) return false; if (icao24 === flightState._trackedIcao) return false; if (icao24 === flightState._pendingTrackingRestore?.id) return false; return true; } function _applyPendingTrackingRestore() { const pending = flightState._pendingTrackingRestore; if ( !pending || pending.generation !== flightState._trackingIntentGeneration ) return false; if (!flightState._icons?.show || !flightState._icons.has(pending.id)) return false; flightState._pendingTrackingRestore = null; _trackFlight(pending.id, { origin: pending.origin }); return true; } function _cancelPendingTrackingRestore() { flightState._trackingIntentGeneration += 1; flightState._pendingTrackingRestore = null; } /** * The tracked plane's stale cue and whether it is drawn with the stale fade. * - SIGNAL LOST ·