From b1333d8d93bfcb8bd44d617710fa87269d7aa5f9 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 04:47:18 -0800 Subject: [PATCH] Read the camera through its port when applying military snapshots The military snapshot renderer took the camera's ground point from the Cesium camera, built fix positions and history entries with Cesium types, re-floored stale grounded contacts with Cesium positions and handed the scene to the mesh floor sampler itself. It now reads the ground point from the camera port's pose, compares fix times in whole milliseconds as before, and leaves positions, the stale re-floor and the mesh floor probe to the military motion part. The file no longer touches Cesium and leaves the allow-list. The fix position, copy and history entry helpers the flights and military motion parts both need now live once in the aircraft motion regime module. --- src/data/aircraftEmergencyAnalyst.test.mjs | 12 +- src/data/aircraftMotionRegime.js | 24 +++ src/layers/flights/motion.js | 30 +-- src/layers/military/index.js | 2 +- src/layers/military/motion.js | 68 +++++++ src/layers/military/snapshotRenderer.js | 95 +++------- src/layers/military/snapshotRenderer.test.mjs | 174 ++++++++++++++++++ src/render/cesiumAllowList.json | 1 - 8 files changed, 312 insertions(+), 94 deletions(-) create mode 100644 src/layers/military/snapshotRenderer.test.mjs diff --git a/src/data/aircraftEmergencyAnalyst.test.mjs b/src/data/aircraftEmergencyAnalyst.test.mjs index 8530fd47b..aa1257248 100644 --- a/src/data/aircraftEmergencyAnalyst.test.mjs +++ b/src/data/aircraftEmergencyAnalyst.test.mjs @@ -9,6 +9,9 @@ import { aircraftMotionRegime, createMotionRegime, fixEpochMs, + fixPosition, + copyPosition, + historyFix, julianAt, } from './aircraftMotionRegime.js'; import { aircraftEmergency } from './aircraftEmergency.js'; @@ -504,6 +507,11 @@ test('GERMAN: an existing untracked military icon repaints each poll without los ), _displayTimeAt: julianAt, _fixEpochMs: fixEpochMs, + _fixPosition: fixPosition, + _copyPosition: copyPosition, + _historyFix: historyFix, + _refloorStaleGroundedContacts() {}, + _sampleMeshFloor() {}, }, }; const icons = createMilitaryIcons({ @@ -522,10 +530,10 @@ test('GERMAN: an existing untracked military icon repaints each poll without los const apply = createMilitarySnapshotRenderer({ flightState, records, - groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null }, - meshFloor: { sampleMeshFloorCells() {} }, + groundFloor: { warmGroundFloor() {} }, militaryRegistry: { registerMilitaryIcaos() {} }, rendering: parts.rendering, + motion: parts.motion, icons, tracking: {}, queries: {}, diff --git a/src/data/aircraftMotionRegime.js b/src/data/aircraftMotionRegime.js index af1aa522f..948b46474 100644 --- a/src/data/aircraftMotionRegime.js +++ b/src/data/aircraftMotionRegime.js @@ -40,6 +40,30 @@ export function fixEpochMs(fix) { : Cesium.JulianDate.toDate(fix.time).getTime(); } +/** A feed fix's ECEF position, from its degrees and render altitude. */ +export function fixPosition(lonDeg, latDeg, heightM) { + return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, heightM); +} + +/** A copy of a fix position, for a trail that keeps it. */ +export function copyPosition(position) { + return Cesium.Cartesian3.clone(position); +} + +/** + * A position-history entry for a feed fix at `epochMs`, carrying the fix's + * own speed and track; it keeps a copy of `position`. + */ +export function historyFix(epochMs, position, velocity, track) { + return { + time: julianAt(epochMs), + epochMs, + position: Cesium.Cartesian3.clone(position), + velocity, + track, + }; +} + /** A reusable result for `aircraftMotionRegime`. */ export function createMotionRegime() { return { diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index b78469f41..736b835e7 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -37,6 +37,9 @@ import { aircraftMotionRegime, createMotionRegime, fixEpochMs, + fixPosition, + copyPosition, + historyFix, julianAt, fixSpeedMps, fixTrackDeg, @@ -1064,35 +1067,14 @@ export function createMotion({ /** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */ const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result); - /** A feed fix's ECEF position, from its degrees and render altitude. */ - const _fixPosition = (lonDeg, latDeg, heightM) => - Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, heightM); - - /** A copy of a fix position, for a trail that keeps it. */ - const _copyPosition = (position) => Cesium.Cartesian3.clone(position); - - /** - * A position-history entry for a feed fix at `epochMs`, carrying the fix's - * own velocity and track; it keeps a copy of `position`. - */ - function _historyFix(epochMs, position, velocity, track) { - return { - time: julianAt(epochMs), - epochMs, - position: Cesium.Cartesian3.clone(position), - velocity, - track, - }; - } - return { _refloorStaleGroundedContacts, _deadReckon, _displayTimeAt, _fixEpochMs: fixEpochMs, - _fixPosition, - _copyPosition, - _historyFix, + _fixPosition: fixPosition, + _copyPosition: copyPosition, + _historyFix: historyFix, _motionRegime, _extrapolateFix, _isTrackWarmingUp, diff --git a/src/layers/military/index.js b/src/layers/military/index.js index f5c9a6ac7..3ec9c6ac7 100644 --- a/src/layers/military/index.js +++ b/src/layers/military/index.js @@ -31,10 +31,10 @@ export function createMilitaryFlightLayer({ flightState, records: flightState.records, groundFloor: services.groundFloor, - meshFloor: services.meshFloor, militaryRegistry: services.militaryRegistry, rendering: parts.rendering, tracking: parts.tracking, + motion: parts.motion, icons: parts.icons, queries: parts.queries, }); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 6d91e5786..9f253afac 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -26,6 +26,9 @@ import { aircraftMotionRegime, createMotionRegime, fixEpochMs, + fixPosition, + copyPosition, + historyFix, julianAt, fixSpeedMps, fixTrackDeg, @@ -472,8 +475,73 @@ export function createMotion({ /** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */ const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result); + /** + * Re-floor STALE grounded contacts (mirror of the flights layer): a parked + * contact whose feed went quiet froze at its pre-warm height. The + * model-ownership gate matches the live grounded-clamp path (a + * tileset-snapped model owns its visual; moving its icon would disturb + * groundSnap's input, the one-shot invariant). + */ + function _refloorStaleGroundedContacts(currentIcaos) { + const { cachedGroundFloor, GROUND_FLOOR_LIFT_M } = services.groundFloor; + for (const [icao24, info] of flightState.records.data) { + if (!info?.onGround || currentIcaos.has(icao24)) continue; + if (parts.rendering._modelOwnsVisual(icao24)) continue; + if (!Number.isFinite(info.rawLat) || !Number.isFinite(info.rawLon)) + continue; + const floor = cachedGroundFloor(info.rawLat, info.rawLon); + if (!Number.isFinite(floor)) continue; + const lifted = floor + GROUND_FLOOR_LIFT_M; + if ( + Number.isFinite(info.renderAltitudeM) && + info.renderAltitudeM >= floor - 1 + ) + continue; + info.renderAltitudeM = lifted; + const liftedPos = Cesium.Cartesian3.fromDegrees( + info.rawLon, + info.rawLat, + lifted, + ); + const hist = flightState._positionHistory.get(icao24); + const newest = hist?.[hist.length - 1]; + if (newest) + newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position); + if (flightState._icons.has(icao24)) { + parts.icons._applyIconPresentation(icao24); + parts.icons._planIcon(icao24); + } + } + } + + /** + * Sample the rendered mesh under the collected floor cells (see + * meshFloorSampler.js), leaving this layer's own icons and models out of + * the probe so it cannot land on an aircraft instead of the pavement. + */ + function _sampleMeshFloor(points, viewerLat, viewerLon) { + services.meshFloor.sampleMeshFloorCells( + flightState._viewer?.scene, + points, + { + excludeObjects: [ + ...parts.icons._iconIds(), + ...[...flightState._models.values()].map((record) => record.model), + flightState._trackedModel?.model, + ].filter(Boolean), + viewerLat, + viewerLon, + }, + ); + } + return { _deadReckon, + _fixPosition: fixPosition, + _copyPosition: copyPosition, + _historyFix: historyFix, + _refloorStaleGroundedContacts, + _sampleMeshFloor, _motionRegime, _displayTimeAt, _fixEpochMs: fixEpochMs, diff --git a/src/layers/military/snapshotRenderer.js b/src/layers/military/snapshotRenderer.js index 21f3738fa..e6e0db5bb 100644 --- a/src/layers/military/snapshotRenderer.js +++ b/src/layers/military/snapshotRenderer.js @@ -1,4 +1,4 @@ -import * as Cesium from 'cesium'; +import { findCamera } from '../../render/rendererOf.js'; import { turnRateFromFixHistory, liftRepeatedGroundFix, @@ -6,21 +6,19 @@ import { } from '../../data/motionModel.js'; import { POSITION_HISTORY_LIMIT } from './recordPolicy.js'; -/** Apply military record changes to Cesium resources and existing follow operations. */ +/** Apply military record changes to the layer's drawing and existing follow operations. */ export function createMilitarySnapshotRenderer({ flightState, records, groundFloor, - meshFloor, militaryRegistry, rendering, tracking, + motion, icons, queries, }) { - const { warmGroundFloor, cachedGroundFloor, GROUND_FLOOR_LIFT_M } = - groundFloor; - const { sampleMeshFloorCells } = meshFloor; + const { warmGroundFloor } = groundFloor; const { registerMilitaryIcaos } = militaryRegistry; return function applySnapshot(snapshot, viewer) { // Before init (or after destroy) there is no icon set to draw into. @@ -46,7 +44,7 @@ export function createMilitarySnapshotRenderer({ : false, }, ); - const position = Cesium.Cartesian3.fromDegrees( + const position = motion._fixPosition( meta.rawLon, meta.rawLat, meta.renderAltitudeM, @@ -59,23 +57,22 @@ export function createMilitarySnapshotRenderer({ // report, so the fix epoch is receipt time minus that age. Only // append when the fix actually advances, so stale repeats don't // create zero-dt segments. - const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs)); if (!flightState._positionHistory.has(icao24)) { flightState._positionHistory.set(icao24, []); } const history = flightState._positionHistory.get(icao24); const newest = history[history.length - 1]; - if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) { + // Whole milliseconds, as the fix times are kept. + if ( + !newest || + Math.trunc(fixEpochMs) > Math.trunc(motion._fixEpochMs(newest)) + ) { // Per-fix kinematics: the fix's own velocity/track ride along so the // extrapolation paths use the values that BELONG to the fix they // extend, not whatever the latest poll reported. - history.push({ - time: fixTime, - epochMs: fixEpochMs, - position: position.clone(), - velocity: meta.speedMps, - track: meta.track, - }); + history.push( + motion._historyFix(fixEpochMs, position, meta.speedMps, meta.track), + ); if (history.length > POSITION_HISTORY_LIMIT) { history.shift(); } @@ -87,7 +84,7 @@ export function createMilitarySnapshotRenderer({ // (owner): ground traffic appends too — taxi history stays live // after touchdown; _appendTrailFix floors grounded positions at // the surface so the ground leg drapes instead of diving. - if (isTracked) tracking._appendTrailFix(position.clone()); + if (isTracked) tracking._appendTrailFix(motion._copyPosition(position)); } else { const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24); if (!modelOwnsGroundVisual) { @@ -106,7 +103,10 @@ export function createMilitarySnapshotRenderer({ history.push(synthetic); if (history.length > POSITION_HISTORY_LIMIT) history.shift(); meta.turnRateDps = turnRateFromFixHistory(history); - if (isTracked) tracking._appendTrailFix(synthetic.position.clone()); + if (isTracked) + tracking._appendTrailFix( + motion._copyPosition(synthetic.position), + ); } } } @@ -144,58 +144,21 @@ export function createMilitarySnapshotRenderer({ // synchronously by NEXT poll's clamp (same contract as flights.js's // grounded-surface warm). warmGroundFloor(_floorWarmPoints); - // Round 6: re-floor STALE grounded contacts (mirror of flights.js) — - // a parked contact whose feed went quiet froze at its pre-warm height. - // The model-ownership gate matches the live grounded-clamp path (a - // tileset-snapped model owns its visual; moving its icon would - // disturb groundSnap's input — the T7 one-shot invariant). - for (const [icao24, info] of flightState.records.data) { - if (!info?.onGround || currentIcaos.has(icao24)) continue; - if (rendering._modelOwnsVisual(icao24)) continue; - if (!Number.isFinite(info.rawLat) || !Number.isFinite(info.rawLon)) - continue; - const floor = cachedGroundFloor(info.rawLat, info.rawLon); - if (!Number.isFinite(floor)) continue; - const lifted = floor + GROUND_FLOOR_LIFT_M; - if ( - Number.isFinite(info.renderAltitudeM) && - info.renderAltitudeM >= floor - 1 - ) - continue; - info.renderAltitudeM = lifted; - const liftedPos = Cesium.Cartesian3.fromDegrees( - info.rawLon, - info.rawLat, - lifted, - ); - const hist = flightState._positionHistory.get(icao24); - const newest = hist?.[hist.length - 1]; - if (newest) - newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position); - if (flightState._icons.has(icao24)) { - icons._applyIconPresentation(icao24); - icons._planIcon(icao24); - } - } + // Round 6: re-floor STALE grounded contacts (mirror of flights.js); the + // motion part owns the positions it rewrites. + motion._refloorStaleGroundedContacts(currentIcaos); // Round 4: sample the RENDERED mesh for those cells (one-shot per cell, // budget-capped, viewer-proximate, google-3d regime only), excluding // this layer's own icons/models from the probe. { - const viewerCarto = - flightState._viewer?.camera?.positionCartographic || null; - sampleMeshFloorCells(flightState._viewer?.scene, _floorWarmPoints, { - excludeObjects: [ - ...icons._iconIds(), - ...[...flightState._models.values()].map((record) => record.model), - flightState._trackedModel?.model, - ].filter(Boolean), - viewerLat: viewerCarto - ? Cesium.Math.toDegrees(viewerCarto.latitude) - : undefined, - viewerLon: viewerCarto - ? Cesium.Math.toDegrees(viewerCarto.longitude) - : undefined, - }); + const pose = findCamera(flightState._viewer)?.pose() ?? null; + const hasSubpoint = + Number.isFinite(pose?.lat) && Number.isFinite(pose?.lon); + motion._sampleMeshFloor( + _floorWarmPoints, + hasSubpoint ? pose.lat : undefined, + hasSubpoint ? pose.lon : undefined, + ); } // Remove aircraft only after MISSING_POLL_LIMIT consecutive absences. diff --git a/src/layers/military/snapshotRenderer.test.mjs b/src/layers/military/snapshotRenderer.test.mjs new file mode 100644 index 000000000..ed170583e --- /dev/null +++ b/src/layers/military/snapshotRenderer.test.mjs @@ -0,0 +1,174 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createMilitarySnapshotRenderer } from './snapshotRenderer.js'; +import { createMotion } from './motion.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { fromDegrees } from '../../geo/ellipsoid.js'; + +/** + * A military snapshot renderer over the real motion part and fakes for the + * rest: one contact per snapshot, the mesh floor probe and stale re-floor + * recorded. + */ +function harness({ viewer = null, floor = null } = {}) { + const iconIds = new Set(); + const meshCalls = []; + const presented = []; + const flightState = { + _viewer: viewer, + _icons: { + has: (id) => iconIds.has(id), + ids: () => [...iconIds], + get count() { + return iconIds.size; + }, + }, + _positionHistory: new Map(), + _groundSnap: { forget() {} }, + _models: new Map(), + _trackedModel: null, + _trackedIcao: null, + records: { data: new Map() }, + }; + const parts = { + rendering: { _modelOwnsVisual: () => false, _syncModelToClass() {} }, + icons: { + _iconIds: () => ['icon-primitive'], + _addIcon: (id) => iconIds.add(id), + _applyIconPresentation: (id) => presented.push(id), + _planIcon() {}, + _forgetContact: (id) => iconIds.delete(id), + }, + }; + const services = { + camera: { trackedModelScaleForPixelCap: () => 1 }, + focus: {}, + groundFloor: { + cachedGroundFloor: () => floor, + GROUND_FLOOR_LIFT_M: 0.5, + }, + meshFloor: { + sampleMeshFloorCells: (scene, points, options) => + meshCalls.push({ scene, points, options }), + }, + }; + parts.motion = createMotion({ flightState, services, parts, layer: {} }); + let fix = null; + const records = { + receive(aircraft) { + const meta = { + rawLon: aircraft.lon, + rawLat: aircraft.lat, + renderAltitudeM: aircraft.altM, + speedMps: aircraft.speedMps, + track: aircraft.track, + onGround: false, + klass: 'jet', + }; + flightState.records.data.set(aircraft.id, meta); + return { prevMeta: null, meta, groundFlipped: false, fixEpochMs: fix }; + }, + absence: () => 'retain', + }; + const apply = createMilitarySnapshotRenderer({ + flightState, + records, + groundFloor: { warmGroundFloor() {} }, + militaryRegistry: { registerMilitaryIcaos() {} }, + rendering: parts.rendering, + tracking: {}, + motion: parts.motion, + icons: parts.icons, + queries: { _likelyLanded: () => false }, + }); + return { + flightState, + meshCalls, + presented, + apply(aircraft, fixEpochMs) { + fix = fixEpochMs; + return apply({ + observedAtMs: fixEpochMs, + records: [aircraft], + complete: true, + }); + }, + }; +} + +const CONTACT = Object.freeze({ + id: 'ae1234', + lon: -97.5, + lat: 30.25, + altM: 3000, + speedMps: 200, + track: 90, +}); + +test('the mesh floor probe takes the camera subpoint from the camera port', () => { + const viewer = { scene: { id: 'scene' } }; + bindRenderer(viewer, { + camera: fakeCameraPort({ pose: { lat: 30.5, lon: -97.25 } }).port, + }); + const h = harness({ viewer }); + h.apply(CONTACT, 1_700_000_000_000); + assert.equal(h.meshCalls.length, 1); + const [call] = h.meshCalls; + assert.equal(call.scene, viewer.scene); + assert.equal(call.options.viewerLat, 30.5); + assert.equal(call.options.viewerLon, -97.25); + assert.deepEqual(call.options.excludeObjects, ['icon-primitive']); +}); + +test('without a viewer the mesh floor probe has no camera subpoint', () => { + const h = harness(); + h.apply(CONTACT, 1_700_000_000_000); + assert.equal(h.meshCalls[0].options.viewerLat, undefined); + assert.equal(h.meshCalls[0].options.viewerLon, undefined); +}); + +test('a fix appends to the history only when it advances a whole millisecond', () => { + const h = harness(); + const t0 = 1_700_000_000_000; + h.apply(CONTACT, t0); + const history = h.flightState._positionHistory.get(CONTACT.id); + assert.equal(history.length, 1); + const [entry] = history; + assert.equal(entry.epochMs, t0); + assert.equal(entry.velocity, CONTACT.speedMps); + assert.equal(entry.track, CONTACT.track); + const expected = fromDegrees(CONTACT.lon, CONTACT.lat, CONTACT.altM); + for (const axis of ['x', 'y', 'z']) + assert.ok(Math.abs(entry.position[axis] - expected[axis]) < 1e-6, axis); + // The same instant within its millisecond is a repeat, not a new fix. + h.apply(CONTACT, t0 + 0.4); + assert.equal(history.length, 1); + h.apply({ ...CONTACT, lon: CONTACT.lon + 0.01 }, t0 + 1_000); + assert.equal(history.length, 2); + assert.equal(history[1].epochMs, t0 + 1_000); + assert.notEqual(history[1].position, history[0].position); +}); + +test('a stale grounded contact is lifted onto its floor', () => { + const h = harness({ floor: 100 }); + const t0 = 1_700_000_000_000; + h.apply(CONTACT, t0); + const parked = 'ae9999'; + const before = fromDegrees(-97.4, 30.2, 10); + h.flightState.records.data.set(parked, { + onGround: true, + rawLat: 30.2, + rawLon: -97.4, + renderAltitudeM: 10, + }); + const newest = { epochMs: t0, position: { ...before } }; + h.flightState._positionHistory.set(parked, [newest]); + h.flightState._icons.has = (id) => id === parked || id === CONTACT.id; + h.apply(CONTACT, t0 + 1_000); + assert.equal(h.flightState.records.data.get(parked).renderAltitudeM, 100.5); + const lifted = fromDegrees(-97.4, 30.2, 100.5); + for (const axis of ['x', 'y', 'z']) + assert.ok(Math.abs(newest.position[axis] - lifted[axis]) < 1e-6, axis); + assert.ok(h.presented.includes(parked)); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 03b5353a3..5a495f165 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -58,7 +58,6 @@ "src/layers/military/motion.js", "src/layers/military/policy.js", "src/layers/military/queries.js", - "src/layers/military/snapshotRenderer.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js",