Files
gods-eye-view/src/layers/military/lifecycle.js
T
German Khokhlov 7c0891deda refactor(military): Cesium rendering behind a renderer interface
Task 11a. The military flights logic no longer imports Cesium: it draws
through the shared aircraft renderer (src/layers/aircraft/render/cesium.js)
with the military's parameters in src/layers/military/render/cesium.js
(sprite-order slot 'military', jet.glb's 180° nose offset), registered for
'cesium' in the renderer registry and created at init(viewer, {engine}).
The same pure move as flights in 10a:

- Fleet: the BillboardCollection and its sprite-order slot (enable keeps
  restoreSpriteOrder, as before); sprites stay Billboard handles.
- Models: fleet/tracked/preload glTF loads (asynchronous:false, MIX tint at
  MODEL_COLOR_BLEND_AMOUNT, IR boost as `unlit` → the UNLIT CustomShader),
  the model collection, setPose. The per-class specs keep their own nose
  offset: setPose takes an optional offsetDeg (default the layer's), on
  both aircraft renderers (same arithmetic, test added).
- Tracked: the ENU billboard Entity with its position/colour/rotation
  callbacks (#FFD166, transparent amber once the model owns the visual),
  viewFrom, followed through viewer.trackedEntity + the one exact tracked
  frame; refocusTrackedById through follow.refocus.
- Trail: the entity trail and the floored live head segment.
- View: camera/scene reads, frame number, frustum and horizon tests,
  render requests, frame events.
- 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. Same rules: cockpit clicks are
  inert, the tracked visual/model is a no-op, another layer's pick is not
  empty space, an unowned pick is.
- Colours are engine-neutral Rgba (MIL_ICON_COLOR #FFB800,
  TRACKED_ICON_COLOR #FFD166, AMBER_TRANSPARENT), NearFarScalar →
  nearFarScale; Cesium math → src/geo.
- check-import-directions: src/layers/military/ joins the rendered layers
  (cesium only in render/cesium*.js).
- The military registry and the flights' duplicate suppression are
  untouched.

Source-text tests updated with the moved code, same meaning:
- militaryAwareness.test: military's hasContact guard reads fleet.visible().
- trackingClickGesture.test: the military gesture rules are the
  dispatcher's (selection gesture before select, click classifier before
  the empty-space clear), military answers the empty click with a
  user-origin clear — the same assertion flights already had.
- ownership.test: the services fixture names selection and renderer; the
  app-composed services build the layer's Cesium renderer.
- renderers.test: flights and military have extracted Cesium renderers.

New tests: the military logic over a plain-data renderer and a fake engine
(amber fleet, click-select, #FFD166 tracked glyph, no-op on the tracked
visual, empty-click and Escape release, the keyboard left on destroy); the
plain-data renderer moved to src/testSupport for both aircraft layers;
setPose with a per-model offset.

W1 replay vs 7c7422e2 (the 10a reference run): every layer's counts, known
objects, screen points, tracking pose after 2 s, requests and the
city/global/orbit shots (sha256) identical. qa-military-names (it checks
the installations layer): the same verdict as 7c7422e2 (the zoom-markers
assertion fails on both). Main chunk 2,890,763 B (−2.9 KB).
2026-10-17 04:52:15 +04:00

266 lines
11 KiB
JavaScript

import { JET_MODEL_URL } from './policy.js';
export function createLifecycle({
flightState,
services,
parts,
layer,
resolveAsset,
}) {
const { clearFocusTarget } = services.focus;
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
const { setMilitaryLayerActive } = services.militaryRegistry;
const methods = {
/** Configure the source before initialization; an active layer keeps its owner. */
setSource(source) {
if (flightState._renderer)
throw new Error('Configure the source before layer initialization');
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('A snapshot source is required');
flightState.feed._source = source;
flightState.feed._lastSource =
source.label || flightState.feed._lastSource;
this.source = flightState.feed._lastSource;
},
/**
* Initialize the layer: create the engine's aircraft renderer (fleet
* sprites, models), reset all state, and join the engine's selection
* dispatcher.
* @param {object|null} viewer - The Cesium viewer (null on an engine
* without one).
* @param {{ engine?: object }} [context] - LayerLifecycle's context.
*/
init(viewer, { engine = null } = {}) {
if (flightState._renderer)
throw new Error('Flight layer is already initialized');
if (typeof flightState.feed._source?.getSnapshot !== 'function')
throw new TypeError('A snapshot source is required');
if (flightState.lifetime.signal.aborted)
flightState.lifetime = new AbortController();
clearFocusTarget('militaryFlights');
const renderer = services.renderer.create({ viewer, engine });
flightState._renderer = renderer;
renderer.fleet.attach();
// Warm the glTF cache so the tracked plane's model instantiates instantly when first needed
// (keeps the retained instance referenced; never rendered). Captured against this epoch so a
// destroy/re-init mid-load doesn't flip the flag for a torn-down lifecycle.
if (!flightState._preloadModel) {
const epoch = flightState._modelEpoch;
renderer.models
.preload(resolveAsset(JET_MODEL_URL))
.then((m) => {
if (epoch === flightState._modelEpoch) {
flightState._preloadModel = m;
flightState._planeModelLoaded = true;
} else {
renderer.models.destroy(m);
}
})
.catch(() => {
/* tracked plane just stays a billboard a beat longer */
});
}
flightState._billboards = new Map();
flightState._cullPositions.clear();
flightState._detectionObjects = new Map();
flightState.records.data = new Map();
flightState._positionHistory = new Map();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState.feed._count = 0;
flightState.feed._lastUpdate = null;
flightState.feed._backoff = false;
flightState.feed._retryAt = 0;
flightState.feed._lastError = null;
flightState.feed._lastStatus = null;
flightState._trackedIcao = null;
parts.tracking._resetTrackedSelectionState();
flightState._trackedEntity = null;
flightState._cockpitSubjectId = null;
flightState._cockpitContactMode =
document.body.classList.contains('cockpit-mode');
flightState._cockpitNearContacts = new Set();
if (!flightState._cockpitModeListener) {
flightState._cockpitModeListener = (event) =>
parts.tracking._applyCockpitState(event?.detail);
window.addEventListener(
'gev:cockpit-mode-changed',
flightState._cockpitModeListener,
);
}
parts.tracking._installClickHandler();
renderer.fleet.restoreOrder();
console.log('[Data:Military] Initialized with billboard icons');
},
/**
* Show the layer and re-join the selection dispatcher.
*/
enable() {
const renderer = flightState._renderer;
renderer?.fleet.setVisible(true);
holdContinuousRender('military'); // per-frame animator (perf wave 2)
renderer?.models.setVisible(true);
parts.tracking._setCockpitContactMode(
document.body.classList.contains('cockpit-mode'),
);
// Height-datum fix: warm the geoid grid once per layer-enable. The poll loop
// only reads geoidHeight() synchronously after this resolves (guarded by
// _geoidReady) — never awaited per-aircraft, never blocking a poll tick.
if (!flightState.records.geoidReady) {
const lifetime = flightState.lifetime;
ensureGeoidReady()
.then(() => {
if (!lifetime.signal.aborted) flightState.records.geoidReady = true;
})
.catch(() => {
/* geoid grid failed to load — baro path stays un-geoid-corrected until retried */
});
}
parts.tracking._installClickHandler();
registerPickOwner('military', (pickedId) =>
flightState._billboards.has(pickedId),
);
// The flights layer suppresses its military duplicates while we render them
setMilitaryLayerActive(true);
// Force a fresh rotation pass on the first tick after re-enable
flightState._lastCamPoseSig = '';
if (!flightState._preRenderRemove && renderer) {
flightState._preRenderRemove = renderer.view.on(
'preRender',
parts.rendering._fleetTick,
);
}
if (!flightState._trackedModelPreUpdateRemove && renderer) {
flightState._trackedModelPreUpdateRemove = renderer.view.on(
'preUpdate',
parts.rendering._updateTrackedModel,
);
}
if (!flightState._moveEndRemove && renderer) {
// Arrival polish (mirror of flights.js — see the comment there): a settled
// camera move forces a full rotation pass on the very next frame, because
// the pose-signature gate can eat the settle (final easing frames land
// inside one quantization bucket) and leave stale noses for up to
// ROTATION_REFRESH_MS. One extra pass per gesture — nothing per-frame.
flightState._moveEndRemove = renderer.view.on('moveEnd', () => {
flightState._lastCamPoseSig = '';
flightState._lastFleetTickMs = 0;
});
}
renderer?.fleet.restoreOrder();
},
/**
* Hide the layer, clear any active tracking, and leave the selection
* dispatcher so clicks do not get intercepted while the layer is off.
*/
disable() {
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
flightState._renderer?.fleet.setVisible(false);
releaseContinuousRender('military');
parts.rendering._releaseModels();
flightState._renderer?.models.setVisible(false);
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
// Leave the selection dispatcher (clicks, Escape) while disabled to
// avoid intercepting input when the layer is off
parts.tracking._removeClickHandler();
unregisterPickOwner('military');
// Flights layer takes over rendering known-military aircraft (amber)
setMilitaryLayerActive(false);
if (flightState._preRenderRemove) {
flightState._preRenderRemove();
flightState._preRenderRemove = null;
}
if (flightState._trackedModelPreUpdateRemove) {
flightState._trackedModelPreUpdateRemove();
flightState._trackedModelPreUpdateRemove = null;
}
if (flightState._moveEndRemove) {
flightState._moveEndRemove();
flightState._moveEndRemove = null;
}
},
/**
* Tear down the layer: clear tracking, remove handlers, remove its
* drawings, and release all state.
* @param {object|null} viewer - The viewer the layer was drawn on.
*/
destroy(viewer) {
flightState.lifetime.abort();
parts.controller._abortActiveUpdates();
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._removeClickHandler();
if (flightState._cockpitModeListener) {
window.removeEventListener(
'gev:cockpit-mode-changed',
flightState._cockpitModeListener,
);
flightState._cockpitModeListener = null;
}
unregisterPickOwner('military');
if (flightState._preRenderRemove) {
flightState._preRenderRemove();
flightState._preRenderRemove = null;
}
if (flightState._trackedModelPreUpdateRemove) {
flightState._trackedModelPreUpdateRemove();
flightState._trackedModelPreUpdateRemove = null;
}
if (flightState._moveEndRemove) {
flightState._moveEndRemove();
flightState._moveEndRemove = null;
}
parts.rendering._releaseModels();
// Removing the model collection destroys it and its models.
flightState._renderer?.fleet.detach(viewer);
flightState._modelEpoch += 1; // invalidate any in-flight load from this lifecycle (settles post-destroy)
flightState._modelPending.clear();
flightState._modelGen.clear();
if (flightState._preloadModel) {
flightState._renderer?.models.destroy(flightState._preloadModel);
flightState._preloadModel = null;
}
flightState._planeModelLoaded = false;
flightState._billboards.clear();
flightState._cullPositions.clear();
flightState._detectionObjects.clear();
flightState.records.data.clear();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState.records.missingPolls.clear();
flightState.feed._count = 0;
flightState.feed._lastUpdate = null;
flightState._cockpitContactMode = false;
flightState._cockpitNearContacts = new Set();
flightState._cockpitSubjectId = null;
flightState.feed._trackingRefreshEpoch += 1;
flightState.feed._lastTrackingRefreshOutcome = {
epoch: flightState.feed._trackingRefreshEpoch,
status: 'destroyed',
ids: new Set(),
source: flightState.feed._lastSource,
};
parts.tracking._resetTrackedSelectionState(); // next lifecycle re-evaluates against the ENTER ceiling
flightState._renderer?.destroy();
flightState._renderer = null;
},
};
return { methods };
}