Files
gods-eye-view/src/layers/flights/enrichment.js
T
German Khokhlov 7f13ef4a87 refactor(flights): Cesium rendering behind a renderer interface
Task 10a. The flights logic no longer imports Cesium: every Cesium object it
built moved one for one into the shared aircraft renderer
(src/layers/aircraft/render/cesium.js; contract in render/contract.js), with
the flights' parameters in src/layers/flights/render/cesium.js, registered
for 'cesium' in the renderer registry and created at init(viewer, {engine}).

- Fleet: BillboardCollection + sprite-order slot; sprites stay Billboard
  handles (field vocabulary documented for the Navara renderer).
- Models: fleet/tracked/preload glTF loads (asynchronous:false, MIX tint, IR
  boost as `unlit` → the UNLIT CustomShader), the model collection, setPose
  (same HPR frame with airplane.glb's 180° offset).
- Tracked: the ENU billboard Entity with its position/colour/rotation
  callbacks, viewFrom, followed through viewer.trackedEntity + the one exact
  tracked frame (kept as is; engine.camera.follow on Cesium would also end
  the follow on any camera command, a behaviour change).
- Trail: the entity trail (data/trailRenderer, unchanged: its Primitive
  predecessor failed below the mesh) and the live head segment.
- View: camera/scene reads, frame number, frustum and horizon tests,
  projection, render requests, frame events, evidence render-loop hold.
- Clicks and Escape go through the engine's selection dispatcher (the
  ScreenSpaceEventHandler and keydown listener are gone); the cross-layer
  untrack watches the renderer's follow.
- Colours are engine-neutral Rgba (src/layers/shared/color.js), bit-equal to
  the Cesium.Color constants they replace; NearFarScalar → nearFarScale.
- Cesium math in the logic → src/geo.
- check-import-directions: cesium only in render/cesium*.js and three/Navara
  only in render/navara*.js for flights, aircraft and shared; a layer's
  Navara renderer only through navaraMode's import().

Source-text tests updated with the moved code, same meaning:
- readLayerSource reads a layer's render/*.js and, for the aircraft layers,
  aircraft/render/*.js (GLB-load, tracked-entity, CallbackProperty checks).
- modelScale.test: _normalBillboardScaleByDistance reads nearFarScale(...).
- spriteOrder.test: flights' enable calls fleet.restoreOrderOnEnable(); the
  renderer wires it to restoreSpriteOrderOnEnable('flights', viewer).
- trackingClickGesture.test: the flights gesture rules are the dispatcher's
  (selection gesture before select, click classifier before the empty-space
  clear); flights answers the empty click with a user-origin clear.
- militaryAwareness.test: flights' hasContact guard reads fleet.visible().
- ownership.test: the services fixture names selection and renderer.

New tests: color, the Cesium aircraft renderer (contract, collections, pose,
loads, frustum/horizon, tracked entity, follow, trail head, adopted
collections), the flights logic over a plain-data renderer and a fake engine
(fleet, click-select, no-op on the tracked visual, empty-click release), the
boundary rule.

W1 replay vs 7c7422e2: counts, known objects, screen points (0 px), tracking
poses (0 m), requests and shots (same sha256) identical. Main chunk
2,890,982 B (+6.2 KB, +0.21 %: the renderer indirection).
2026-10-17 01:04:25 +04:00

226 lines
8.1 KiB
JavaScript

import { classifyAircraft } from '../../data/aircraftClass.js';
import * as geo from '../../geo/index.js';
import {
ENRICH_MAX_INFLIGHT,
ENRICH_DISPATCH_GAP_MS,
ENRICH_AMBIENT_BUDGET_CEIL,
ENRICH_AMBIENT_REFILL_TOKENS,
ENRICH_AMBIENT_REFILL_WINDOW_MS,
ENRICH_AMBIENT_PER_SWEEP,
} from './policy.js';
export function createEnrichment({
flightState,
services,
parts,
layer,
resolveAsset,
}) {
function _enqueueEnrich(key, query, onData, priority = false) {
if (flightState.lifetime.signal.aborted) return;
if (flightState._enrichSeen.has(key)) return;
flightState._enrichSeen.add(key);
const job = { query, onData };
// Priority (tracked / model-eligible) goes to the FRONT so a deep ambient
// backlog can never delay the plane the user just clicked or zoomed into.
if (priority) flightState._enrichQueue.unshift(job);
else flightState._enrichQueue.push(job);
_drainEnrich();
}
function _drainEnrich() {
if (flightState.lifetime.signal.aborted) return;
while (
flightState._enrichActive < ENRICH_MAX_INFLIGHT &&
flightState._enrichQueue.length
) {
// Drip: at most one dispatch per ENRICH_DISPATCH_GAP_MS. When the gap
// hasn't elapsed yet, park a single wake-up timer and stop — completions
// and enqueues in the meantime re-enter here harmlessly.
const wait =
ENRICH_DISPATCH_GAP_MS -
(Date.now() - flightState._enrichLastDispatchMs);
if (wait > 0) {
if (!flightState._enrichDripTimer) {
flightState._enrichDripTimer = setTimeout(() => {
flightState._enrichDripTimer = null;
_drainEnrich();
}, wait);
}
return;
}
flightState._enrichLastDispatchMs = Date.now();
const job = flightState._enrichQueue.shift();
flightState._enrichActive += 1;
const lifetime = flightState.lifetime;
Promise.resolve()
.then(() => {
lifetime.signal.throwIfAborted();
return flightState.feed._source.getEnrichment?.(job.query, {
signal: lifetime.signal,
});
})
.then((data) => {
if (!lifetime.signal.aborted && data && data.found) job.onData(data);
})
.catch(() => {
/* enrichment never surfaces errors */
})
.finally(() => {
if (lifetime.signal.aborted) return;
flightState._enrichActive -= 1;
_drainEnrich();
});
}
}
function _requestTypeEnrichment(icao24, priority = false) {
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
_enqueueEnrich(
`t:${icao24}`,
{ kind: 'type', id: icao24.toLowerCase() },
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return; // evicted while the lookup was in flight
meta.typeCode = data.typeCode || meta.typeCode;
meta.typeName = data.typeName || meta.typeName;
meta.registration = data.registration || meta.registration;
if (meta.typeCode) {
const klass = classifyAircraft({
typeCode: meta.typeCode,
category: meta.category,
});
if (klass !== meta.klass) {
meta.klass = klass;
const bb = flightState._billboards.get(icao24);
if (bb)
parts.rendering._applyFleetBillboardPresentation(icao24, bb);
// Hangar fleet: the class's GLB/scale may have changed — resync the
// live model, any in-flight load, and the tracked standalone model.
parts.rendering._syncModelToClass(icao24);
}
}
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
parts.tracking._updateTrackedLabelModel(icao24);
},
priority,
);
}
function _requestRouteEnrichment(icao24) {
const cs = String(flightState.records.data.get(icao24)?.callsign || '')
.trim()
.toUpperCase();
if (!/^[A-Z]{3}\d/.test(cs)) return; // airline-style callsigns only (LLL + digit); GA tails won't resolve
_enqueueEnrich(
`r:${cs}`,
{ kind: 'route', id: cs },
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return;
meta.airline = data.airline || meta.airline;
if (data.origin && data.destination)
meta.route = { origin: data.origin, destination: data.destination };
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
parts.tracking._updateTrackedLabelModel(icao24);
},
true,
); // route lookups only fire for the TRACKED plane — front of the queue
}
/** QA seam: headless harnesses (scripts/qa-enrich-ambient.mjs) shrink the
* bucket knobs via window.__GEV_ENRICH_AMBIENT_QA = {ceil, refillTokens,
* windowMs} — they cannot wait out a real 5-minute window. Read lazily each
* refill so a pre-boot override (or a mid-run windowMs swap) applies.
* Production never sets this; the constants above are the defaults. */
function _ambientBudgetKnobs() {
const o =
(typeof window !== 'undefined' && window.__GEV_ENRICH_AMBIENT_QA) || null;
return {
ceil:
Number.isFinite(o?.ceil) && o.ceil > 0
? o.ceil
: ENRICH_AMBIENT_BUDGET_CEIL,
refillTokens:
Number.isFinite(o?.refillTokens) && o.refillTokens > 0
? o.refillTokens
: ENRICH_AMBIENT_REFILL_TOKENS,
windowMs:
Number.isFinite(o?.windowMs) && o.windowMs > 0
? o.windowMs
: ENRICH_AMBIENT_REFILL_WINDOW_MS,
};
}
/** Advance the token bucket: add refillTokens per FULLY elapsed window since
* the anchor, clamp at the ceiling, and move the anchor forward by the whole
* windows consumed (while the bucket sits full this still advances, so idle
* time never banks more than one bucket's worth of burst). */
function _refillAmbientBudget(nowMs) {
const { ceil, refillTokens, windowMs } = _ambientBudgetKnobs();
if (!flightState._enrichAmbientRefillAnchorMs) {
flightState._enrichAmbientRefillAnchorMs = nowMs;
return;
}
const windows = Math.floor(
(nowMs - flightState._enrichAmbientRefillAnchorMs) / windowMs,
);
if (windows <= 0) return;
flightState._enrichAmbientBudget = Math.min(
ceil,
flightState._enrichAmbientBudget + windows * refillTokens,
);
flightState._enrichAmbientRefillAnchorMs += windows * windowMs;
}
function _sweepAmbientEnrichment() {
_refillAmbientBudget(Date.now());
if (
flightState._enrichAmbientBudget <= 0 ||
!flightState._renderer?.fleet.visible()
)
return;
try {
const view = flightState._renderer.view;
const camPos = view.camera.positionWC;
const occluder = view.horizon();
const inFrustum = view.frustumTester();
const cand = [];
for (const [icao24, bb] of flightState._billboards) {
if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
if (!bb.position || !occluder.isPointVisible(bb.position)) continue; // beyond the limb
if (!inFrustum(bb.position)) continue; // off-screen
cand.push([
icao24,
geo.cartesian3.distanceSquared(camPos, bb.position),
]);
}
cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first
const n = Math.min(
cand.length,
ENRICH_AMBIENT_PER_SWEEP,
flightState._enrichAmbientBudget,
);
for (let i = 0; i < n; i++) {
flightState._enrichAmbientBudget -= 1;
_requestTypeEnrichment(cand[i][0]); // non-priority: fills the back of the queue
}
} catch {
/* ambient enrichment is best-effort — never disturb the poll loop */
}
}
return {
_enqueueEnrich,
_drainEnrich,
_requestTypeEnrichment,
_requestRouteEnrichment,
_ambientBudgetKnobs,
_refillAmbientBudget,
_sweepAmbientEnrichment,
};
}