Move the flights and military layers onto the renderer ports

The flights and military layers now reach the renderer only through its
ports: motion, queries, state, tracking, enrichment, evidence and policy
read the camera pose, project through the query port, request and
suspend frames through the frame port, and key per-frame caches on the
frames drawn rather than the scene's frame number. Policy is plain data,
the enrichment view test is pose-based, and the tracked aircraft is an
icon in a draw-port set with a plain holder standing in for the entity
that Cockpit, the tracked card and share links read.

The mesh floor sampler can sample through the query port, excluding
named draw sets, and both layers use it that way. A pick of another
layer's tracked icon is never taken for one of a layer's own contacts.

Twelve layer files leave the Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-07 18:49:23 -08:00
1 parent 00a0a0dbc7
commit 23d56f8393
40 files changed
+1638 -908

No files matched your search

+139 -151
View File
@@ -1,19 +1,30 @@
import { cameraOf } from '../../render/cesium/camera.js';
import { findFrame } from '../../render/rendererOf.js';
import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js';
import {
entityFollowTarget,
onFollowChanged,
stopFollowing,
} from '../../data/followed.js';
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
import { trackedModelZoomActive } from '../../data/trackedModelRegime.js';
import {
screenProjectedRotation,
courseScreenRotation,
stabilizeScreenRotation,
} from '../../data/iconOrientation.js';
} from '../../data/screenRotation.js';
import {
createTrackedAircraftIcon,
isOtherTrackedIconSet,
trackedContactHolder,
} from '../../data/trackedAircraftIcon.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import {
addSeconds,
julianLessThanOrEquals,
julianNow,
julianToEpochMs,
} from '../../geo/julian.js';
import { clone, distanceSquared, vec } from '../../geo/vector.js';
import { trailHeadStart } from '../../data/modelVisualAnchor.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
@@ -41,7 +52,7 @@ function aircraftPickId(picked) {
const id = picked?.id;
if (typeof id === 'string') return id;
if (id && typeof id.set === 'string' && typeof id.id === 'string')
return id.id;
return isOtherTrackedIconSet(id.set, 'military') ? undefined : id.id;
return picked?.primitive?.id;
}
@@ -67,6 +78,21 @@ export function createTracking({
const { clearFocusTarget } = services.focus;
const { FOLLOW_MIN_RANGE_M } = services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
viewer: () => flightState._viewer,
setPrefix: 'military',
});
/** 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 (
@@ -79,7 +105,7 @@ export function createTracking({
}
function _publishTrackedSelection(icao24, origin = 'programmatic') {
const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3());
const position = parts.icons._iconPosition(icao24, vec());
const info = flightState.records.data.get(icao24);
if (!position || !info) return false;
if (flightState._trackedEntity)
@@ -157,10 +183,8 @@ export function createTracking({
/** Refresh the AIR-only Cockpit near band independently from model admission. */
function _refreshCockpitNearContacts() {
if (
!flightState._cockpitContactMode ||
!flightState._viewer?.camera?.positionWC
) {
const eye = flightState._cockpitContactMode ? _pose()?.position : null;
if (!eye) {
if (flightState._cockpitNearContacts.size)
flightState._cockpitNearContacts = new Set();
return;
@@ -176,13 +200,7 @@ export function createTracking({
t,
flightState._scratchCockpitPos,
);
distancesSquared.push([
icao24,
Cesium.Cartesian3.distanceSquared(
flightState._viewer.camera.positionWC,
position,
),
]);
distancesSquared.push([icao24, distanceSquared(eye, position)]);
}
const next = nextCockpitNearContacts(
previous,
@@ -284,12 +302,9 @@ export function createTracking({
refreshTrackedSubjectContext(_contextSubjectMetadata(icao24));
}
/** Re-image the tracked entity's billboard from the current class/conversion. */
function _syncTrackedBillboardImage() {
if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard)
return;
flightState._trackedEntity.billboard.image = aircraftIcon(
/** The tracked billboard's image, from the current class/conversion. */
function _trackedBillboardImage() {
return aircraftIcon(
parts.rendering._iconKind(
flightState._trackedIcao,
flightState.records.data.get(flightState._trackedIcao)?.klass,
@@ -298,6 +313,13 @@ export function createTracking({
);
}
/** Re-image the tracked billboard from the current class/conversion. */
function _syncTrackedBillboardImage() {
if (!flightState._trackedIcao || !flightState._trackedEntity) return;
trackedIcon.setImage(_trackedBillboardImage());
}
/**
* Re-render one contact after its TR-3B conversion (or the active IR style)
* changed. Mirror of flights.js: converting drops any 3D model so the triangle
@@ -325,7 +347,8 @@ export function createTracking({
_syncTrackedBillboardImage();
_updateTrackedLabelModel(id);
}
flightState._viewer?.scene?.requestRender?.();
if (flightState._viewer)
findFrame(flightState._viewer)?.requestRender('military: TR-3B restyle');
return flightState._icons?.has(id) || id === flightState._trackedIcao;
}
@@ -384,7 +407,7 @@ export function createTracking({
return false;
}
flightState._trackedZoomLatched = trackedModelZoomActive(
flightState._viewer?.camera?.positionCartographic?.height,
_pose()?.height,
flightState._trackedZoomLatched,
);
return flightState._trackedZoomLatched;
@@ -396,13 +419,10 @@ export function createTracking({
if (!flightState._trackedIcao || !flightState._viewer) return;
const pos =
parts.motion._trackedDisplayCached() ||
parts.icons._iconPosition(
flightState._trackedIcao,
new Cesium.Cartesian3(),
);
parts.icons._iconPosition(flightState._trackedIcao, vec());
if (!pos) return;
const projected = screenProjectedRotation(
flightState._viewer.scene,
const projected = courseScreenRotation(
_pose(),
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
@@ -423,31 +443,27 @@ export function createTracking({
* invariant), so every position entering the TRAIL subsystem (seed, append,
* per-frame head) goes through this instead — the visible taxi history sits
* on the surface without touching the billboard/model machinery.
* @param {Cesium.Cartesian3} position - Owned position (mutated/replaced freely).
* @returns {Cesium.Cartesian3} The same or a lifted position.
* @param {{x: number, y: number, z: number}} position - Owned ECEF position (mutated/replaced freely).
* @returns {{x: number, y: number, z: number}} The same or a lifted position.
*/
function _trailFloorPosition(position) {
const carto = Cesium.Cartographic.fromCartesian(
position,
Cesium.Ellipsoid.WGS84,
flightState._scratchTrailCarto,
);
const carto = toLonLatH(position);
if (!carto) return position;
const latDeg = Cesium.Math.toDegrees(carto.latitude);
const lonDeg = Cesium.Math.toDegrees(carto.longitude);
const latDeg = carto.lat;
const lonDeg = carto.lon;
const floored = floorAltitudeM(
carto.height,
cachedGroundFloor(latDeg, lonDeg),
);
if (floored == null || floored === carto.height) return position;
return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, floored);
return fromDegrees(lonDeg, latDeg, floored);
}
/**
* Append one fix to the tracked aircraft's trail accumulation and refresh
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
* @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head.
*/
function _appendTrailFix(position) {
@@ -478,7 +494,7 @@ export function createTracking({
/**
* The live head: the last DISPLAYED body point to the delayed head, or no
* positions while there is none.
* @returns {Cesium.Cartesian3[]}
* @returns {Array<{x: number, y: number, z: number}>}
*/
function _trailHeadPositions() {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
@@ -503,7 +519,7 @@ export function createTracking({
// Floor the head too (round 2): a grounded tracked contact's DR
// display height is the pre-datum default — without this the last
// segment dives underground while taxiing.
const end = _trailFloorPosition(Cesium.Cartesian3.clone(head));
const end = _trailFloorPosition(clone(head));
// 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
@@ -541,18 +557,18 @@ export function createTracking({
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
const seedRenderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
const seedRenderTime = addSeconds(
julianNow(),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
for (const fix of history) {
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
if (julianLessThanOrEquals(fix.time, seedRenderTime)) {
// Floor grounded-history seeds (round 2): a grounded contact's stored
// fixes carry the pre-datum default height — the trail copy sits on
// the surface instead (pure lift; airborne fixes pass through).
flightState._trailPositions.push(
_trailFloorPosition(Cesium.Cartesian3.clone(fix.position)),
_trailFloorPosition(clone(fix.position)),
);
}
}
@@ -574,7 +590,7 @@ export function createTracking({
_refreshTrailDisplay();
const oldestFixEpochSec = history.length
? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000
? julianToEpochMs(history[0].time) / 1000
: Infinity;
_backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec);
}
@@ -664,7 +680,7 @@ export function createTracking({
// sentinel (an arbitrary placeholder, never a reported altitude).
if (altM == null) altM = lastAltM != null ? lastAltM : 50;
lastAltM = altM;
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
older.push(fromDegrees(lon, lat, altM));
}
// Stride-thin the backfill so it plus the live fine segment fit the cap.
@@ -749,17 +765,15 @@ export function createTracking({
// release never flips it.
const trackedCourseDeg = flightState._displayCourse.get(clearedIcao);
// Stop tracking and remove the entity. skipViewerUntrack: another layer just grabbed the
// follow-camera, so tear down our state but DON'T clear the camera's follow (they own it now).
// Releasing trackedEntity does NOT move the camera: Cesium resets the lookAt transform in
// place, so the view stays where the follow left it and the user can immediately orbit/zoom.
// Stop tracking and hide the tracked billboard. skipViewerUntrack: another layer just grabbed
// the follow-camera, so tear down our state but DON'T clear the camera's follow (they own it
// now). 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);
}
if (flightState._trackedEntity) {
flightState._viewer.entities.remove(flightState._trackedEntity);
flightState._trackedEntity = null;
}
trackedIcon.hide();
flightState._trackedEntity = null;
parts.rendering._releaseTrackedModel();
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
flightState._trackedIcao = null;
@@ -820,19 +834,14 @@ export function createTracking({
// The tracked limiter continues from the nose the icon was drawn with, and
// the entity starts with the rotation the icon had on screen.
const t = parts.icons._displayMs();
const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3());
const iconPosition = icons.position(icao24, t, vec());
const iconCourse = icons.course(icao24, t);
flightState._displayCourse.set(icao24, iconCourse);
flightState._trackedIcao = icao24;
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
flightState._cachedDRFrame = -1;
flightState._lastTrackedRotation =
screenProjectedRotation(
flightState._viewer.scene,
iconPosition,
iconCourse,
0,
) ?? 0;
courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0;
// Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its
// own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover
// fleet model would be orphaned + double-rendered.
@@ -847,28 +856,20 @@ export function createTracking({
// aircraft has no fix.
const getTrackedPosition = () =>
parts.motion._trackedDisplayPosition(icao24) ||
parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) ||
parts.icons._iconPosition(icao24, vec()) ||
iconPosition;
// Dead-reckoning position property evaluated every render frame.
// isConstant = false so CesiumJS re-evaluates each frame.
const positionProperty = new Cesium.CallbackProperty(() => {
return getTrackedPosition();
}, false);
// World-space orientation for the 3D model: nose along the course heading (ENU, pitch/roll 0).
// Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the
// TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the
// DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
// The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed
// in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on
// the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always
// resolves into an aircraft.
//
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
// show=false: it drops its alpha only once the tracked model is drawing, so
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
// through the camera port, so nothing here frames the camera.
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The tracked plane's 3D
// model is the standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel).
// What the tracked billboard is drawn at, kept in its entity record so the
// show=false: it drops its alpha only once the tracked model is drawing, so there's neither a
// billboard+model double-image nor a gap. The camera follows its own target through the camera
// port, so nothing here frames the camera. The tracked plane's 3D model is a draw-set item
// driven by _updateTrackedModel() (see _trackedModel).
// What the tracked billboard is drawn at, kept in its record so the
// camera guard and screen annotations size it from the app.
const sprite = {
width: 28,
@@ -880,58 +881,49 @@ export function createTracking({
] || 1),
scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
};
flightState._trackedEntity = flightState._viewer.entities.add({
position: positionProperty,
billboard: {
image: aircraftIcon(
parts.rendering._iconKind(
flightState._trackedIcao,
flightState.records.data.get(flightState._trackedIcao)?.klass,
),
TRACKED_ICON_PX,
),
width: sprite.width,
height: sprite.height,
scale: sprite.scale,
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the STANDALONE tracked model is actually up (ready + shown).
color: new Cesium.CallbackProperty(
() =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR,
false,
),
sizeInMeters: false,
scaleByDistance: sprite.scaleByDistance,
alignedAxis: Cesium.Cartesian3.ZERO,
// The tracked target must never vanish into tile geometry — tracking a
// taxiing plane at street level would otherwise bury the amber icon inside
// the runway skin, so it draws depth-test-free like the fleet icon set;
// its shared-host tracked card is top-composited separately.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
// Screen-projected rotation, evaluated per frame: exact in tracked-orbit
// mode where camera.heading lives in the entity's reference frame.
rotation: new Cesium.CallbackProperty(() => {
const tracked = flightState.records.data.get(
flightState._trackedIcao,
);
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
const projected = screenProjectedRotation(
flightState._viewer.scene,
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
);
const rot = stabilizeScreenRotation(
flightState._lastTrackedRotation,
projected,
);
if (rot !== null) flightState._lastTrackedRotation = rot;
// The tracked contact as its readers see it (the tracked card, Cockpit, share links): a
// plain holder of its entity record, drawn while it is the one tracked.
const holder = trackedContactHolder(
`military:${icao24}`,
trackedIcon,
parts.motion._trackedDisplayCached,
);
flightState._trackedEntity = holder;
entityRecord(holder).drawn = () => flightState._trackedEntity === holder;
trackedIcon.show({
id: icao24,
image: _trackedBillboardImage(),
sprite,
position: getTrackedPosition,
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the tracked model is actually up (ready + shown).
color: () =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR,
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
// street level would otherwise bury the amber icon inside the runway
// skin, so it draws over depth like the fleet icon set; its
// shared-host tracked card is top-composited separately.
rotation: () => {
const tracked = flightState.records.data.get(flightState._trackedIcao);
const pos = getTrackedPosition();
if (!tracked || !pos || !flightState._viewer)
return flightState._lastTrackedRotation;
}, false),
const projected = courseScreenRotation(
_pose(),
pos,
parts.motion._trackedDisplayCourse(),
flightState._lastTrackedRotation,
);
const rot = stabilizeScreenRotation(
flightState._lastTrackedRotation,
projected,
);
if (rot !== null) flightState._lastTrackedRotation = rot;
return flightState._lastTrackedRotation;
},
});
entityRecord(flightState._trackedEntity).selectionOrigin = origin;
@@ -940,20 +932,16 @@ export function createTracking({
entityRecord(flightState._trackedEntity).labelModel =
trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166');
// A billboard has a ~zero bounding sphere, so Cesium's default follow distance is
// far too tight (the user had to scroll out to read the plane). Give the entity a
// A billboard has a ~zero bounding sphere, so the renderer's default follow distance is
// far too tight (the user had to scroll out to read the plane). Give the target a
// calibrated viewFrom — behind + above, distance scaled to altitude — for a readable
// initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.)
const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500;
const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000);
const viewFrom = new Cesium.Cartesian3(
0,
-followRange * 0.8,
followRange * 0.55,
);
const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55);
// Cancel any in-progress camera flight first — otherwise Cesium won't apply the tracked
// entity's viewFrom on the first frame, so voice-initiated tracking (which often fires
// Cancel any in-progress camera flight first — otherwise the camera won't apply the follow
// target's viewFrom on the first frame, so voice-initiated tracking (which often fires
// mid-fly_to_location) would follow the plane WITHOUT centering it like a click does.
// Cross-module HUD consumers (tracked-target readout) read the camera's settled position, not a
// postRender recompute, so the label doesn't jitter against the now-stable plane (mirror of flights).
@@ -1011,7 +999,7 @@ export function createTracking({
* Clicking a military billboard starts tracking that aircraft; clicking empty
* space or a non-military object deselects. Also attaches the Escape key
* listener via {@link _onKeyDown}. Idempotent -- no-ops if already installed.
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
* @param {object} viewer - The viewer
*/
function _installClickHandler(viewer) {
@@ -1051,14 +1039,11 @@ export function createTracking({
const picked = event.hit;
if (picked) {
// Clicking the tracked entity itself -- ignore (don't deselect)
if (picked.id === flightState._trackedEntity) return;
// Clicking the plane we're ALREADY tracking (its standalone 3D model or
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
// above. H1: the model used to have no pick id, so this fell through to
// Clicking the plane we're ALREADY tracking (its tracked billboard, its
// 3D model, or any pick carrying its icao) — ignore, don't deselect.
// H1: the model used to have no pick id, so this fell through to
// "empty space" and deselected the very plane being tracked.
// Its models are draw-set items keyed by icao, like its icons.
// Its billboard and models are draw-set items keyed by icao, like its icons.
const pickedIcao = aircraftPickId(picked);
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
return;
@@ -1114,6 +1099,9 @@ export function createTracking({
_backfillTrail,
_clearTrail,
_destroyTrail,
/** Let the tracked billboard's set go (layer teardown). */
_disposeTrackedIcon: () => trackedIcon.dispose(),
/** The tracked billboard's set id, or null before one is made. */
_clearTracking,
_applyPendingTrackingRestore,
_cancelPendingTrackingRestore,