Files
gods-eye-view/src/layers/military/queries.js
T
Sameh Khamis 5f98f8bdf3 Aircraft drawn as far behind real time as their feed is late, along one curve their trail follows
Civil and military aircraft were drawn a fixed 30 s (15 s) behind real time
while anonymous feed reports arrive about 90 s old every 30 s, so every
contact dead reckoned about a minute past its newest report and snapped
when the next one landed (several km on a turn), and the tracked trail,
recorded from those drawn positions and patched as reports arrived, kinked.

- The display delay (data/displayDelay.js) is the 90th percentile of the
  newest 256 report lags plus 5 s, between the layer's floor (30 s, 15 s)
  and five minutes, slewed at most 0.2 s/s up and 0.05 s/s down. Icons,
  the renderer's live motion clock, labels, HUD, detection, the tracked
  camera and the trail read the one delay; following the world clock
  draws with none and deliveries leave it alone.
- Between two reports an aircraft flies a biarc (data/fixCurve.js) that
  passes through both and leaves each along its track, sent as contract
  arc segments; the trail is the reports joined along the same curve, so
  the icon sits on it. Nothing drawn between reports is kept.
- A report a coasting contact missed is eased onto from where it would
  have been that frame (at least 3 s, at most 30% over its speed, within
  20 s); over 5 km it jumps. Past its newest report a contact coasts
  straight on: a turn rate averaged over earlier reports outlived the turn.
- Forward synthetic fixes no longer block real reports older than them,
  and a history keeps 24 fixes.
- A feed simulation (testSupport/aircraftFeedSim.mjs) checks both layers
  against a 90 s late feed, a fallback switch, repeated reports, outages
  and the world clock.
2026-11-14 00:31:29 -08:00

829 lines
33 KiB
JavaScript

import { cameraOf } from '../../render/rendererOf.js';
import { followedOf } from '../../data/followed.js';
import { displayedKinematics } from '../../data/motionModel.js';
import { t } from '../../i18n/index.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { clone, distance as distanceBetween, vec } from '../../geo/vector.js';
import { isExplicitLayerStateOrigin } from '../../data/layerState.js';
import { aircraftIncludedInNearby } from '../../data/aircraftNearbyPolicy.js';
import { modelVisualAnchor } from '../../data/modelVisualAnchor.js';
import {
rankContactMatch,
contactMatchWins,
CONTACT_MATCH_TIER,
} from '../../data/contactMatch.js';
import {
LANDED_ALT_MAX_FT,
LANDED_SPEED_MAX_MPS,
POLL_INTERVAL_MS,
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
export function createQueries({
flightState,
services,
parts,
layer,
resolveAsset,
}) {
const { tr3bAircraftClass, tr3bTypeLabel } = services.aircraftPresentation;
const { formatFlightLevel } = services.labels;
/**
* Coerce a value to a finite number, returning null if not possible.
* Handles both numeric and string inputs (e.g. API fields that may arrive as strings).
* @param {*} value - Raw value from the API response
* @returns {number|null} Finite number or null
*/
function _toFiniteNumber(value) {
if (typeof value === 'number' && Number.isFinite(value)) return value;
if (typeof value === 'string') {
const n = Number.parseFloat(value.trim());
return Number.isFinite(n) ? n : null;
}
return null;
}
/**
* Safely convert a value to a trimmed string, defaulting to '' for falsy inputs.
* @param {*} value - Raw value to stringify
* @returns {string} Trimmed string
*/
function _toCleanText(value) {
return String(value || '').trim();
}
/**
* Format an altitude value in feet for display, with fallback text.
* @param {number|null|undefined} altitudeFt - Barometric altitude in feet
* @returns {string} Formatted altitude string (e.g. "35000 ft" or "Alt unknown")
*/
function _formatAltitude(altitudeFt) {
if (!Number.isFinite(altitudeFt)) return t('Alt unknown');
return `${Math.round(altitudeFt)} ft`;
}
/**
* True when the aircraft's latest metadata reads "on or about the runway"
* (low + slow) — see the landed fast-cull rationale above. Both gates must
* hold, so a plane missing either datum keeps the normal grace.
* @param {string} icao24 - ICAO hex identifier of the aircraft
* @returns {boolean}
*/
function _likelyLanded(icao24) {
const info = flightState.records.data.get(icao24);
if (!info) return false;
// Round 7 (mirror of flights.js): fast cull only for contacts seen
// AIRBORNE this session — parked contacts ride the normal grace so feed
// flaps don't churn their identity/floor state.
if (info.wasAirborne !== true) return false;
if (info.onGround) return true;
return (
Number.isFinite(info.altitudeFt) &&
info.altitudeFt < LANDED_ALT_MAX_FT &&
Number.isFinite(info.speedMps) &&
info.speedMps < LANDED_SPEED_MAX_MPS
);
}
/**
* Build a public descriptor for one aircraft using its best current position
* (dead-reckoned when history exists, icon position otherwise).
* @param {string} icao24 - ICAO hex identifier of the aircraft.
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* Descriptor with a cloned position, or null if the aircraft is unknown.
*/
function _describeFlight(icao24) {
const info = flightState.records.data.get(icao24);
const basePos =
parts.motion._deadReckon(icao24) ||
parts.icons._iconPosition(icao24, vec());
if (!basePos) return null;
const displayed = displayedKinematics({
derivedSpeedMps: flightState._drSpeedMps,
derivedTrackDeg: flightState._drCourseDeg,
reportedSpeedMps: info?.speedMps,
reportedTrackDeg: info?.track,
});
const carto = toLonLatH(basePos);
if (!carto) return null;
return {
icao24,
callsign: _toCleanText(info?.callsign) || null,
// Additive: the label chain's middle link, trimmed like `callsign`, so
// getTrackedSubject and the voice narration can read it straight off the
// descriptor instead of reaching back into `_flightData`.
registration: _toCleanText(info?.registration) || null,
position: clone(basePos),
latitude: carto.lat,
longitude: carto.lon,
// Keep the cockpit readout on the reported aviation altitude. Render
// terrain height is a separate visual datum and may be below zero.
altitudeM: Number.isFinite(info?.altitudeM)
? info.altitudeM
: carto.height,
renderAltitudeM: Number.isFinite(info?.renderAltitudeM)
? info.renderAltitudeM
: carto.height,
onGround: info?.onGround === true,
velocityMps: displayed.speedMps,
track: displayed.trackDeg,
// Same field, same name, same null-when-absent rule as the civil
// descriptor — the two layers store the record under different keys
// (`verticalRateMps` here, `verticalRate` there), so only the mapping
// makes `resolveTrackedAircraftInfo` hand back one shape for both.
verticalRateMps: Number.isFinite(info?.verticalRateMps)
? info.verticalRateMps
: null,
stale: Boolean(
flightState.records.missingPolls.get(icao24) ||
flightState.feed._backoff,
),
// This poll's transponder broadcast (not sticky; see records.js).
squawk: info?.squawk ?? null,
emergency: info?.emergency ? { ...info.emergency } : null,
emergencyBroadcast: emergencyBroadcastPhrase(info?.emergency),
};
}
function _normalizeTrackedIcao(candidate) {
const normalized = String(candidate ?? '')
.trim()
.toLowerCase();
return normalized || null;
}
/**
* Map one military aircraft's internal poll record to a plain JSON-safe
* analyst record (analyst query engine seam) — same shape as the flights
* layer's mapAnalystRecord, with `military` always true. Pure — no Cesium
* types, no fetches. Missing/unknown fields are null, never NaN/undefined.
* adsb.lol carries no origin-country field and this layer has no route
* enrichment, so originCountry/routeOrigin/routeDestination are always null.
* @param {string} icao24 - ICAO hex identifier of the aircraft.
* @param {Object|null|undefined} info - `_flightData` record for this aircraft.
* @returns {{id: string, icao24: string, callsign: string|null, lat: number|null,
* lon: number|null, altitudeM: number|null, speedMps: number|null,
* heading: number|null, verticalRateMps: number|null, onGround: boolean,
* military: boolean, aircraftClass: string|null, originCountry: null,
* operator: string|null, squawk: string|null, emergency: boolean,
* emergencyKind: string|null, emergencySource: 'squawk'|'ads-b'|null,
* emergencyBroadcast: string|null, lastContactAtMs: number|null, routeOrigin: null, routeDestination: null}}
*/
function mapAnalystRecord(icao24, info) {
const num = (v) => (Number.isFinite(v) ? v : null);
const text = (v) => {
const t = String(v ?? '').trim();
return t || null;
};
const callsign = text(info?.callsign);
return {
id: callsign || text(info?.registration) || icao24,
icao24,
callsign,
lat: num(info?.rawLat),
lon: num(info?.rawLon),
// altitudeFt is the sticky barometric/MSL aviation field — converted to
// meters here for shape parity with the flights layer.
altitudeM: Number.isFinite(info?.altitudeFt)
? info.altitudeFt * 0.3048
: null,
speedMps: num(info?.speedMps),
heading: num(info?.track),
verticalRateMps: num(info?.verticalRateMps),
onGround: info?.onGround === true,
military: true,
// A converted contact reports the class it RENDERS as (mirror of
// flights.js), so an analyst filter/superlative agrees with the triangle.
aircraftClass: tr3bAircraftClass(icao24, text(info?.klass)),
originCountry: null,
operator: text(info?.operator),
squawk: text(info?.squawk),
// True while this poll broadcast an emergency (7500/7600/7700 or the
// ADS-B status); priority statuses (lifeguard, minfuel) report the kind
// without the flag.
emergency: info?.emergency?.severity === 'emergency',
emergencyKind: text(info?.emergency?.kind),
// Provenance, so a summary can say "broadcasting squawk 7700" rather
// than "ADS-B reports general emergency" (or flatten both): 'squawk'
// when the Mode A code names the status, 'ads-b' for the readsb field.
emergencySource: text(info?.emergency?.source),
emergencyBroadcast: emergencyBroadcastPhrase(info?.emergency),
// Latest known general aircraft-message contact, retained if a poll
// has no time. This is not the receipt time of the current status.
lastContactAtMs: num(info?.lastContactEpochMs),
routeOrigin: null,
routeDestination: null,
};
}
const methods = {
mapAnalystRecord,
id: 'military',
name: 'Military Flights',
icon: '🎖️',
source: flightState.feed._lastSource,
/** @type {number} Polling interval in ms between API fetches */
updateInterval: POLL_INTERVAL_MS,
/** @deprecated Compatibility alias for {@link enable}. */
show(viewer) {
this.enable(viewer);
},
/** @deprecated Compatibility alias for {@link disable}. */
hide(viewer) {
this.disable(viewer);
},
/**
* Live layer params.
* `models3d` toggles 3D glTF jet-model rendering for the FLEET (altitude-gated): when on,
* surrounding military aircraft become 3D models once the camera is zoomed in past
* MODEL_ALT_CEIL_M. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`),
* so selecting a contact never turns its icon into a model or its model into an icon.
* `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane).
* @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedMilitaryTrackingId?: string|null}} params
*/
setParams(params = {}, { origin = 'programmatic' } = {}) {
if (
isExplicitLayerStateOrigin(origin) &&
!Object.hasOwn(params, 'selectedMilitaryTrackingId')
) {
parts.tracking._cancelPendingTrackingRestore();
}
if (
typeof params.models3d === 'boolean' &&
params.models3d !== flightState._models3dEnabled
) {
flightState._models3dEnabled = params.models3d;
if (!flightState._models3dEnabled) {
parts.rendering._releaseModels();
parts.tracking._syncTracked2dRotation();
// (Releasing the models handed each fleet contact back to its icon, never
// the tracked plane's own — its tracked entity is the visual.)
}
}
if (
(params.models3dMode === 'proximity' ||
params.models3dMode === 'all') &&
params.models3dMode !== flightState._models3dMode
) {
// The next fleet tick re-derives the eligible set under the new cap and releases the overflow.
flightState._models3dMode = params.models3dMode;
if (flightState._cockpitContactMode) {
parts.tracking._refreshCockpitNearContacts();
flightState._lastFleetTickMs = 0;
}
}
if (
typeof params.irBoost === 'boolean' &&
params.irBoost !== flightState._irBoost
) {
flightState._irBoost = params.irBoost;
parts.rendering._reloadModelsForIrBoost();
// Sprites don't reload with the models — swap the TR-3B glyph between its
// cold and thermal-reactive variants directly (mirror of flights.js).
parts.tracking._refreshTr3bForStyle();
}
if (Object.hasOwn(params, 'selectedMilitaryTrackingId')) {
const requested = _normalizeTrackedIcao(
params.selectedMilitaryTrackingId,
);
if (requested === flightState._trackedIcao) {
flightState._pendingTrackingRestore = null;
} else if (requested === null) {
parts.tracking._cancelPendingTrackingRestore();
if (flightState._trackedIcao)
parts.tracking._clearTracking(false, { origin });
} else {
const generation = ++flightState._trackingIntentGeneration;
flightState._pendingTrackingRestore = {
id: requested,
generation,
origin,
};
if (flightState._trackedIcao)
parts.tracking._clearTracking(false, { origin });
parts.tracking._applyPendingTrackingRestore();
}
}
return true;
},
getParams() {
return {
models3d: flightState._models3dEnabled,
models3dMode: flightState._models3dMode,
irBoost: flightState._irBoost,
selectedMilitaryTrackingId: flightState._trackedIcao,
};
},
/**
* Re-render a contact whose TR-3B conversion just flipped (Easter egg).
* Callers own the registry write; this only re-derives what renders.
* @param {string} icao24 - ICAO 24-bit address.
* @returns {boolean} True when this layer owns the contact.
*/
refreshTr3b(icao24) {
return parts.tracking._refreshTr3bContact(icao24);
},
/**
* Find military aircraft near a given ECEF position, sorted by distance.
* Used by proximity-based features (e.g. detection overlay, spatial queries).
* @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates
* @param {number} range - Maximum distance in meters (Infinity if not specified)
* @param {number} [maxCount=50] - Maximum number of results to return
* @param {object} [options] Query membership options.
* @param {boolean} [options.includeHidden=false] Include loaded horizon-hidden aircraft.
* @returns {Array<Object>} Sorted array of nearby aircraft descriptors
*/
getNearby(center, range, maxCount = 50, { includeHidden = false } = {}) {
const icons = flightState._icons;
if (!center || !icons || !icons.show) return [];
const occluder = parts.icons._occluder();
const t = parts.icons._displayMs();
const scratch = flightState._scratchNearbyPos;
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 50;
const maxRange =
Number.isFinite(range) && range > 0 ? range : Number.POSITIVE_INFINITY;
const nearby = [];
for (const icao24 of icons.ids()) {
const isTracked = icao24 === flightState._trackedIcao;
const trackedPos = isTracked
? parts.motion._trackedDisplayCached()
: null; // cached, no recompute (anti-jitter)
const drawn = trackedPos || icons.position(icao24, t, scratch);
// Keep planes rendered as a 3D model (icon hidden) so proximity counts
// don't drop to zero on the 2D→3D handoff.
if (
!aircraftIncludedInNearby({
isTracked,
billboardShown:
icons.shown(icao24) && parts.icons._aboveHorizon(drawn, occluder),
modelRendering: parts.rendering._modelOwnsVisual(icao24),
includeHidden,
})
)
continue;
const distance = distanceBetween(center, drawn);
if (distance > maxRange) continue;
const pos = trackedPos || clone(drawn);
const info = flightState.records.data.get(icao24);
nearby.push({
id: info?.callsign?.trim() || info?.registration?.trim() || icao24,
icao24,
position: pos,
distance,
// Filter surface (mirror of flights.js): the cockpit next/previous path
// matches on this field, so it follows the conversion.
aircraftClass: tr3bAircraftClass(
icao24,
String(info?.klass || info?.type || '')
.trim()
.toLowerCase() || null,
),
track: info?.track ?? null,
// Display type — converted too, so a Contacts row can't still name the
// airframe the triangle replaced (the filter matcher reads this as a
// fallback candidate as well).
type: tr3bTypeLabel(icao24, info?.type || null),
registration: info?.registration || null,
operator: info?.operator || null,
altitudeFt: info?.altitudeFt ?? null,
});
}
nearby.sort((a, b) => a.distance - b.distance);
return nearby.slice(0, limit);
},
/**
* Return a subset of aircraft suitable for the detection overlay system.
* Uses a deterministic stride-based sampling to keep the count manageable
* while distributing selections evenly across the collection.
* @param {Object} [options={}] - Options
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all)
* @param {number} [options.seed] - Seed offset for stride sampling (for frame variation)
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
*/
getDetectableObjects(options = {}) {
const icons = flightState._icons;
if (!icons || !icons.show) return [];
const maxCount = Number.isFinite(options.maxCount)
? Math.max(1, Math.floor(options.maxCount))
: icons.count;
const seed = Number.isFinite(options.seed) ? Math.floor(options.seed) : 0;
// Deterministic stride: evenly space selections across the icon rows
const stride = Math.max(1, Math.ceil(icons.count / maxCount));
const start = seed % stride;
const occluder = parts.icons._occluder();
const t = parts.icons._displayMs();
const result = [];
const ids = icons.ids();
/** One camera and viewport for every model's drawn scale. */
let view = null;
for (let i = start; i < ids.length; i += stride) {
const icao24 = ids[i];
if (
flightState._cockpitContactMode &&
icao24.toLowerCase() === flightState._cockpitSubjectId
)
continue;
const isTracked = icao24 === flightState._trackedIcao;
// Keep planes rendered as a 3D model (icon hidden) so the detection box
// doesn't vanish on the 2D→3D handoff.
const record = flightState._models.get(icao24);
const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24);
if (!isTracked && !icons.shown(icao24) && !modelOwnsVisual) continue;
const info = flightState.records.data.get(icao24);
const callsign = info?.callsign?.trim();
const registration = info?.registration?.trim();
let object = flightState._detectionObjects.get(icao24);
if (!object) {
object = {
sourceId: icao24,
type: 'AIR',
tier: 'military',
_weldPos: vec(),
_iconPos: vec(),
};
flightState._detectionObjects.set(icao24, object);
}
// WELD (mirror of flights.js): anchor to whatever owns the visual. Model-owned
// contacts read the translation the fleet tick already wrote into their
// modelMatrix; icon-owned contacts keep the drawn icon position, where icon and
// bracket are co-located anyway.
const spec = modelOwnsVisual ? parts.rendering._modelSpec(info) : null;
const pos = isTracked
? parts.motion._trackedVisualCached() ||
icons.position(icao24, t, object._iconPos)
: modelOwnsVisual
? modelVisualAnchor(
record.matrix,
spec.visualCenterNative,
parts.rendering._modelDrawnScale(
record,
spec,
(view ??= parts.rendering._drawnScaleView()),
),
object._weldPos || (object._weldPos = vec()),
)
: icons.position(icao24, t, object._iconPos);
// An icon past the horizon is not drawn, so it is not detectable.
if (
!pos ||
(!isTracked &&
!modelOwnsVisual &&
!parts.icons._aboveHorizon(pos, occluder))
)
continue;
object.position = pos;
object.skipLabel = isTracked;
const id = callsign || registration || icao24;
if (object.id !== id) object.id = id;
// Card surface: detectionDraw composes its secondary line from
// `[src.klass, src.metric]`, so a converted contact's card must name the
// TR-3B, not the airframe underneath it.
const klass = tr3bTypeLabel(icao24, info?.type || 'MIL');
if (object.klass !== klass) object.klass = klass;
const altitudeFt = info?.altitudeFt ?? 0;
if (object._altitudeFt !== altitudeFt) {
object._altitudeFt = altitudeFt;
// military metadata stores altitudeFt (feet); the helper takes metres
object.metric = formatFlightLevel(altitudeFt * 0.3048);
}
result.push(object);
if (result.length >= maxCount) break;
}
if (flightState._detectionObjects.size > icons.count + 512) {
for (const icao24 of flightState._detectionObjects.keys()) {
if (!icons.has(icao24)) flightState._detectionObjects.delete(icao24);
}
}
return result;
},
/**
* Find a single aircraft by free-text query.
* Match priority: exact icao24 hex, exact callsign, callsign prefix,
* then callsign substring (all case-insensitive, trimmed).
* @param {string} query - ICAO hex or full/partial callsign.
* @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null}
* Best match with a cloned, dead-reckoned position, or null if none.
*/
findByQuery(query) {
if (!flightState.records.data || flightState.records.data.size === 0)
return null;
const q = String(query || '')
.trim()
.toLowerCase();
if (!q) return null;
// Registration is searched alongside callsign because it is what the
// operator SEES: a callsign-less contact reads as its tail number on the
// card, in the analyst's answer, and in the Contacts list. Matching only
// callsigns meant "follow 6606" — and the analyst → track_entity handoff
// the tool instructions prescribe — answered "nothing matched" for the
// very identity the app had just shown (owner field session 2026-08-21,
// 23:48: three failed track_entity retries before a fallback stuck).
// Ranking is shared with the flights layer (contactMatch.js) so the two
// cannot disagree, and it is strictly tiered so a registration can never
// out-rank a real callsign on feed order alone.
let best = null;
for (const [icao24, info] of flightState.records.data) {
const candidate = {
tier: rankContactMatch({
query: q,
hex: icao24,
callsign: info?.callsign,
registration: info?.registration,
}),
id: icao24,
};
if (!contactMatchWins(candidate, best)) continue;
best = candidate;
if (candidate.tier === CONTACT_MATCH_TIER.HEX_EXACT) break;
}
return best ? _describeFlight(best.id) : null;
},
/**
* Return id/label/position for up to maxCount currently rendered aircraft.
* Cheap snapshot for voice-tool framing — drawn icon positions, no
* extra dead reckoning.
* @param {number} [maxCount=500] - Maximum number of entries to return.
* @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>}
*/
/**
* Whether this layer still carries a contact, in O(1).
*
* Mirror of `flights.hasContact`: presence consumers must not infer absence
* from the capped `getAllPositions` rows. Id matching follows trackById —
* exact key first, then lowercase.
* A disabled layer keeps its records but hides the collection, so it must
* decline rather than answer from data the user can no longer see.
* @param {string} icao24 Contact identifier.
* @returns {boolean|null} Presence, or null when the layer is disabled or
* holds no data and therefore cannot answer.
*/
hasContact(icao24) {
const icons = flightState._icons;
if (!icons || !icons.show || icons.count === 0) return null;
if (!icao24) return false;
const id = String(icao24).trim();
return icons.has(id) || icons.has(id.toLowerCase());
},
getAllPositions(maxCount = 500) {
const icons = flightState._icons;
if (!icons || icons.count === 0) return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 500;
const t = parts.icons._displayMs();
const result = [];
for (const icao24 of icons.ids()) {
const pos = icons.position(icao24, t, vec());
const carto = toLonLatH(pos);
if (!carto) continue;
const info = flightState.records.data.get(icao24);
result.push({
id: icao24, // identity (trackById/Context resolve this)
// Last surface still reading as the raw hex for a callsign-less
// contact — same chain as getNearby/getDetectableObjects/getTrackedSubject.
label:
_toCleanText(info?.callsign) ||
_toCleanText(info?.registration) ||
icao24,
position: pos,
latitude: carto.lat,
longitude: carto.lon,
altitudeM: carto.height,
});
if (result.length >= limit) break;
}
return result;
},
/**
* Snapshot the layer's in-memory records as plain JSON-safe objects for
* the analyst query engine. On-demand only (called at most once per
* spoken query) — zero per-frame cost, no listeners, no caching. Returns
* [] while the layer is disabled or empty.
* @param {number} [maxCount=2000] - Maximum records to return (truncation).
* @returns {Array<Object>} See mapAnalystRecord for the record shape.
*/
getAnalystRecords(maxCount = 2000) {
if (!flightState._icons?.show || flightState.records.data.size === 0)
return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const [icao24, info] of flightState.records.data) {
result.push(mapAnalystRecord(icao24, info));
if (result.length >= limit) break;
}
return result;
},
/**
* Start camera-tracking an aircraft by ICAO hex identifier.
* @param {string} icao24 - ICAO hex identifier of the aircraft.
* @returns {boolean} True if the aircraft exists and tracking started.
*/
trackById(icao24, { origin = 'programmatic' } = {}) {
if (!icao24) return false;
let id = String(icao24).trim();
if (!flightState._icons?.has(id)) id = id.toLowerCase();
if (!flightState._icons?.has(id)) return false;
if (parts.tracking._isExplicitTrackingOrigin(origin))
parts.tracking._cancelPendingTrackingRestore();
if (flightState._trackedIcao === id)
return parts.tracking._publishTrackedSelection(id, origin);
parts.tracking._trackFlight(id, { origin });
return true;
},
/** Resolve a shared Follow target only against the latest accepted refresh. */
async resolveTrackingRestoreTarget(
icao24,
{ signal = null, origin = 'share-restore' } = {},
) {
if (signal?.aborted)
return {
status: 'cancelled',
reason: String(signal.reason || 'aborted'),
};
const id = String(icao24 ?? '')
.trim()
.toLowerCase();
if (!id) return { status: 'missing', reason: 'invalid-target' };
const outcome = flightState.feed._lastTrackingRefreshOutcome;
if (outcome.status !== 'accepted') {
return {
status: 'source-unavailable',
reason: `${flightState.feed._lastSource} snapshot unavailable`,
refreshEpoch: outcome.epoch,
source: outcome.source,
};
}
if (!outcome.ids.has(id)) {
return {
status: 'missing',
reason: 'target-absent-from-snapshot',
refreshEpoch: outcome.epoch,
source: outcome.source,
};
}
if (signal?.aborted)
return {
status: 'cancelled',
reason: String(signal.reason || 'aborted'),
};
const followed = this.trackById(id, { origin });
return followed
? {
status: 'found',
refreshEpoch: outcome.epoch,
source: outcome.source,
}
: {
status: 'source-unavailable',
reason: 'target-not-renderable',
refreshEpoch: outcome.epoch,
};
},
/** Reapply the canonical follow frame without recreating the selected flight. */
refocusTrackedById(icao24, { origin = 'programmatic' } = {}) {
if (
!icao24 ||
flightState._cockpitContactMode ||
!flightState._viewer ||
!flightState._trackedEntity
)
return false;
let id = String(icao24).trim();
if (!flightState._icons?.has(id)) id = id.toLowerCase();
if (
id !== flightState._trackedIcao ||
followedOf(flightState._viewer) !== flightState._followTarget
)
return false;
// Following the same target again frames it afresh.
const camera = cameraOf(flightState._viewer);
camera.cancelFlight();
camera.follow(flightState._followTarget);
parts.tracking._publishTrackedSelection(id, origin);
return true;
},
/**
* Stop tracking the currently followed aircraft (no-op if none).
* @returns {boolean} Always true.
*/
stopTracking({ origin = 'programmatic' } = {}) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._clearTracking(false, { origin });
return true;
},
cancelPendingTrackingRestore() {
parts.tracking._cancelPendingTrackingRestore();
},
/**
* Describe the currently tracked aircraft at its dead-reckoned position.
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* Tracked aircraft info, or null when nothing is tracked.
*/
getTrackedInfo() {
if (!flightState._trackedIcao) return null;
const described = _describeFlight(flightState._trackedIcao);
if (!described) return null;
const { position, ...rest } = described;
return rest;
},
/**
* Return the current aircraft as a Context subject without changing
* tracking or camera ownership.
* @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null}
* Detached subject descriptor, or null when no aircraft is tracked.
*/
getTrackedSubject() {
if (!flightState._trackedIcao) return null;
const described = _describeFlight(flightState._trackedIcao);
if (!described?.position) return null;
return {
layerId: 'military',
id: described.icao24,
// Same label chain as getNearby/getDetectableObjects: a callsign-less
// contact reads as its registration, never as the raw ICAO hex.
label: described.callsign || described.registration || described.icao24,
position: clone(described.position),
};
},
/**
* Return current layer health/status for the HUD status chip.
* @returns {{count: number, lastUpdate: number|null, stale: boolean, error: string|null, status: number|null, retryInSec: number}}
*/
getStats() {
const retryInSec = flightState.feed._retryAt
? Math.max(
0,
Math.ceil((flightState.feed._retryAt - Date.now()) / 1000),
)
: 0;
return {
count: flightState.feed._count,
lastUpdate: flightState.feed._lastUpdate,
stale: flightState.feed._backoff,
error: flightState.feed._lastError,
status: flightState.feed._lastStatus,
retryInSec,
source: flightState.feed._lastSource,
fallback: false,
// Following the world clock, the snapshot's age is told from its time.
...(followsClock(flightState) && { atMs: flightState.now() }),
};
},
};
return {
_toFiniteNumber,
_toCleanText,
_formatAltitude,
_likelyLanded,
_describeFlight,
_normalizeTrackedIcao,
mapAnalystRecord,
methods,
};
}