From 65587f6c080b74a30f01c7a9ff81311d0b6d8d61 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 08:09:00 -0800 Subject: [PATCH 001/470] Keep tracked-entity state in app records instead of on Cesium entities Flights, military, satellites, installations, local ADS-B and ALPR hung gevTrackedId, gevDisplayPosition, gevVisualPosition, gevSelectionOrigin and gevLabelModel on the Cesium entities they draw, and the tracked readout, follow camera, cockpit, share links and awareness read them back. They now live in src/data/entityRecords.js, an app-owned record per entity: layers write entityRecord(entity), readers use readEntityRecord(entity). Nothing changes on screen. This is the first slice of the renderer plan's state mirror (P1). The module is exported as ./data/entity-records so callers can read the same records, and window.__godsEyeView.entityRecords gives the QA scripts the same access from the page. --- docs/CURRENT-STATE.md | 10 ++- package.json | 1 + scripts/package-boundaries.json | 38 ++++++--- scripts/qa-cockpit-utility.mjs | 4 +- scripts/qa-context-arrivals.mjs | 9 ++- scripts/qa-heading-b3.mjs | 6 +- scripts/qa-installation-polish.mjs | 2 +- scripts/qa-radio.mjs | 12 +-- scripts/track-regression.mjs | 28 +++---- src/annotations/screenAnnotationRenderer.js | 6 +- src/app/tools.js | 2 + src/cockpitMarkup.test.mjs | 4 +- src/cockpitMath.js | 2 +- src/cockpitMath.test.mjs | 2 +- src/cockpitTracking.js | 2 +- src/cockpitTracking.test.mjs | 5 +- src/data/alprCameras.test.mjs | 19 ++--- src/data/entityRecords.js | 52 +++++++++++++ src/data/entityRecords.test.mjs | 31 ++++++++ src/data/flights.test.mjs | 27 +++---- src/data/militaryAwareness.test.mjs | 19 +++-- src/data/militaryFlights.test.mjs | 25 +++--- src/data/militaryInstallations.test.mjs | 9 ++- src/data/radio.test.mjs | 7 +- src/data/satellitesTrackedRefresh.test.mjs | 19 ++--- src/data/tr3bRegistry.test.mjs | 9 ++- src/data/trackedCamera.js | 3 +- src/data/trackedCamera.test.mjs | 8 +- src/data/trackedCardLocale.test.mjs | 5 +- src/data/trackedReadout.js | 24 +++--- src/data/trackedReadout.test.mjs | 78 +++++++------------ src/layers/alpr/presentation.js | 17 ++-- src/layers/awareness/subject.js | 14 ++-- src/layers/flights/motion.js | 2 +- src/layers/flights/tracking.js | 31 ++++---- src/layers/installations/rendering.js | 9 ++- src/layers/localAdsb/index.js | 11 +-- src/layers/localAdsb/index.test.mjs | 18 +++-- src/layers/military/motion.js | 2 +- src/layers/military/tracking.js | 34 ++++---- src/layers/satellites/interaction.js | 5 +- src/layers/satellites/tracking.js | 12 +-- .../worldOverlayAllocation.worker.mjs | 22 +++--- src/ui/cameraOrientationControls.js | 3 +- src/ui/cameraOrientationControls.test.mjs | 3 +- src/ui/cockpitController.test.mjs | 11 ++- src/ui/cockpitCoordinator.js | 7 +- src/ui/cockpitTrackingController.js | 3 +- src/ui/mobileShell.test.mjs | 3 +- src/ui/shareFollow.js | 3 +- src/ui/shareLinks.test.mjs | 15 ++-- src/ui/shareRestoration.js | 3 +- src/voice/gevActions.test.mjs | 3 +- 53 files changed, 408 insertions(+), 291 deletions(-) create mode 100644 src/data/entityRecords.js create mode 100644 src/data/entityRecords.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index e95e445786..9f17cc3838 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3513,7 +3513,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > ambient-label host source. Its getter reads the already-propagated point > cache, preserving the 1 Hz fleet epoch and eliminating the former second ISS > propagation. Satellite tracking continues to publish exactly one protected -> tracked-lane card through `gevLabelModel` and `_trackedDisplayCached`; the +> tracked-lane card through its entity record's `labelModel` and `_trackedDisplayCached`; the > tracked entity is point-only. Tracking ISS suppresses the ambient entry and > untracking restores it, preventing duplicate ISS text. Disable, orbit-text > preference changes, catalog rebuild, and destroy clear/hide the source. @@ -3528,7 +3528,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Phase 5 tracked civil aircraft label:** A tracked flight's Cesium entity > is a billboard-only camera target with no native label. The flight source > retains callsign/registration fallback, flight-level/altitude, speed, stale -> state, airline/type, and plausible-route formatting in `gevLabelModel`; the +> state, airline/type, and plausible-route formatting in the entity record's `labelModel`; the > one protected tracked-lane host card renders that complete model. Its > position getter reads only `_trackedDisplayCached`, the same authoritative > Cartesian already consumed by the tracked visual and camera, and never @@ -3635,8 +3635,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > - **Tracked-readout ownership:** `trackedReadout.js` is now a presentation-model > bridge only; it owns no canvas, projection, post-render listener, layout, > keyhole fade, or paint path. Civilian flights, military flights, satellites, -> and mapped installations write explicit `gevLabelModel` objects and expose -> `gevDisplayPosition` getters backed by their layer-owned frame/display cache. +> and mapped installations write explicit `labelModel` objects and +> `displayPosition` getters, backed by their layer-owned frame/display cache, +> into the app's entity records (`src/data/entityRecords.js`), never onto the +> Cesium entity. > Selected AIS vessels continue using the vessel source's protected selected > card, so they do not create a duplicate tracked readout. The host registers > the active readout in the protected tracked lane with a zero ambient quota; diff --git a/package.json b/package.json index 7dda05144c..802fe88fd1 100644 --- a/package.json +++ b/package.json @@ -227,6 +227,7 @@ "./standalone/catalog": "./src/standalone/catalog.js", "./application/layers": "./src/app/constructCatalog.js", "./application/operations": "./src/app/operations.js", + "./data/entity-records": "./src/data/entityRecords.js", "./data/lifecycle": "./src/data/lifecycle.js", "./ui/navigation": "./src/ui/navigationController.js", "./ui/share-restoration": "./src/ui/shareRestoration.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 8ed8b859a4..8e75167158 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -871,7 +871,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/entityRecords.js" ], "external": ["cesium"] }, @@ -1124,7 +1125,8 @@ "src/ui/kit/UiBadge.vue", "src/ui/stores/globeActions.js", "src/ui/stores/recording.js", - "src/ui/i18n.js" + "src/ui/i18n.js", + "src/data/entityRecords.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -1335,7 +1337,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/entityRecords.js" ], "external": ["cesium"] }, @@ -1391,7 +1394,8 @@ "src/i18n/locales/ru.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js" ], "external": ["cesium"] }, @@ -1576,7 +1580,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/entityRecords.js" ], "external": ["cesium", "satellite.js"] }, @@ -1667,7 +1672,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/layers/installations/classLabel.js" + "src/layers/installations/classLabel.js", + "src/data/entityRecords.js" ], "external": ["cesium", "@mapbox/vector-tile", "pbf"] }, @@ -1713,7 +1719,8 @@ "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", - "src/ui/unitLabels.js" + "src/ui/unitLabels.js", + "src/data/entityRecords.js" ], "external": ["cesium"] }, @@ -1973,7 +1980,8 @@ "src/i18n/locales/ru.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js" ], "external": ["cesium", "@mapbox/vector-tile", "pbf"] }, @@ -3184,7 +3192,8 @@ "src/data/placeBoundaries.js", "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", - "src/data/local_data/wof_neighborhoods/files.js" + "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js" ], "external": [ "hls.js", @@ -3792,7 +3801,8 @@ "src/data/placeBoundaries.js", "src/data/placeNames.js", "src/data/local_data/us_census_places/files.js", - "src/data/local_data/wof_neighborhoods/files.js" + "src/data/local_data/wof_neighborhoods/files.js", + "src/data/entityRecords.js" ], "external": [ "hls.js", @@ -3890,6 +3900,11 @@ "mgrs" ] }, + "entity-records": { + "exports": ["./data/entity-records"], + "modules": ["src/data/entityRecords.js"], + "external": [] + }, "layer-lifecycle": { "exports": ["./data/lifecycle"], "modules": ["src/data/lifecycle.js", "src/data/cameraArrival.js"], @@ -3944,7 +3959,8 @@ "src/i18n/locales/ru.json", "src/i18n/locales/uk.json", "src/i18n/locales/zh-CN.json", - "src/i18n/locales/zh-Hant.json" + "src/i18n/locales/zh-Hant.json", + "src/data/entityRecords.js" ], "external": [] }, diff --git a/scripts/qa-cockpit-utility.mjs b/scripts/qa-cockpit-utility.mjs index c5a94018fa..47065d6586 100644 --- a/scripts/qa-cockpit-utility.mjs +++ b/scripts/qa-cockpit-utility.mjs @@ -763,7 +763,7 @@ try { } : null, navigation: snapshot?.navigation || null, afterId: trackedInfo?.icao24 || null, - viewerTrackedId: viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, contextVisible: !document.getElementById('military-awareness-panel')?.hidden, entryAvailableAfterSettlement: Boolean(entry && !entry.hidden), blockerStillRegistered: dataManager.layers.has(blockerId), @@ -1362,7 +1362,7 @@ try { contextMode: styleManager._contextControls._contextMode, contextChanging: styleManager._contextControls._contextModeChanging, subject: context?.subject ? `${context.subject.layerId}:${context.subject.id}` : null, - tracked: tracker?.gevTrackedId || null, + tracked: window.__godsEyeView.entityRecords.read(tracker)?.trackedId || null, density: styleManager.getDetectionState().densityPct, detectionMode: styleManager.getDetectionState().detectionMode, installations: dataManager.getLayerLifecycleState('military-installations'), diff --git a/scripts/qa-context-arrivals.mjs b/scripts/qa-context-arrivals.mjs index 72a6ffab8a..09780c3ff5 100644 --- a/scripts/qa-context-arrivals.mjs +++ b/scripts/qa-context-arrivals.mjs @@ -360,7 +360,9 @@ async function contacts() { entities: ds?.entities.values.length ?? 0, created, tracked: - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId ?? null, + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId ?? null, cockpit: document.body.classList.contains('cockpit-mode'), }); if (samples.length > 5000) samples.splice(0, 1000); @@ -375,8 +377,9 @@ async function contacts() { await page .waitForFunction( () => - window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === - 'flights:aaa051', + window.__godsEyeView.entityRecords.read( + window.__godsEyeView.viewer.trackedEntity, + )?.trackedId === 'flights:aaa051', { timeout: 60_000 }, ) .catch(() => {}); diff --git a/scripts/qa-heading-b3.mjs b/scripts/qa-heading-b3.mjs index cbba1b88ef..0f515fe5cc 100644 --- a/scripts/qa-heading-b3.mjs +++ b/scripts/qa-heading-b3.mjs @@ -169,8 +169,8 @@ async function observeTrackedHostPaint(page, timeoutMs = 5000) { const tracked = viewer?.trackedEntity; const current = { elapsedMs: Math.round(performance.now() - startedAt), - entryId: tracked?.gevTrackedId || null, - hasPresentationModel: Boolean(tracked?.gevLabelModel?.title), + entryId: window.__godsEyeView?.entityRecords?.read(tracked)?.trackedId || null, + hasPresentationModel: Boolean(window.__godsEyeView?.entityRecords?.read(tracked)?.labelModel?.title), candidateCount: diagnostics.candidateCount || 0, projectedCount: diagnostics.projectedCount || 0, selectedCount: diagnostics.selectedCount || 0, @@ -610,7 +610,7 @@ async function main() { if (!pool.length) return null; const ent = v.trackedEntity; let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function') tracked = window.__godsEyeView.entityRecords.read(ent)?.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { diff --git a/scripts/qa-installation-polish.mjs b/scripts/qa-installation-polish.mjs index 6971d85ba5..bda5f0dfee 100644 --- a/scripts/qa-installation-polish.mjs +++ b/scripts/qa-installation-polish.mjs @@ -333,7 +333,7 @@ export async function checkInstallationSelection( for (let y = 250; y < 650; y += 75) for (let x = 400; x < 850; x += 75) { const pick = g.viewer.scene.pick({ x, y }); - if (!pick?.id?.installationId && !pick?.id?.gevTrackedId) + if (!pick?.id?.installationId && !window.__godsEyeView.entityRecords.read(pick?.id)?.trackedId) return { x, y }; } throw new Error('No empty map point'); diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index 83b3596053..957144a508 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -3817,7 +3817,7 @@ async function main() { id: `qa:${ownerPrefix}:radio-camera-owner`, position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = `${ownerPrefix}:qa-radio-camera-owner`; + window.__godsEyeView.entityRecords.write(owner).trackedId = `${ownerPrefix}:qa-radio-camera-owner`; viewer.trackedEntity = owner; await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const beforeStationId = radio.getUIState().selected?.id || null; @@ -3831,7 +3831,7 @@ async function main() { afterStationId: radio.getUIState().selected?.id || null, flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, }; viewer.trackedEntity = undefined; viewer.entities.remove(owner); @@ -3867,11 +3867,11 @@ async function main() { id: 'qa:flights:delayed-radio-fallback-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-delayed-radio-fallback-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-delayed-radio-fallback-owner'; viewer.trackedEntity = owner; window.__qaDelayedRadioTrackingOwner = owner; window.__qaRejectRadioPlay(); - return owner.gevTrackedId; + return window.__godsEyeView.entityRecords.read(owner)?.trackedId; }); await page.waitForFunction(() => window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().audioState === 'playing'); const delayedFallbackOwnership = await page.evaluate((beforeFlyToCalls) => { @@ -3880,7 +3880,7 @@ async function main() { const result = { flyToDelta: window.__qaRadioFlyToCalls.length - beforeFlyToCalls, trackedIdentityPreserved: viewer.trackedEntity === owner, - trackedId: viewer.trackedEntity?.gevTrackedId || null, + trackedId: window.__godsEyeView.entityRecords.read(viewer.trackedEntity)?.trackedId || null, selectedId: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().selected?.id || null, }; viewer.trackedEntity = undefined; @@ -4222,7 +4222,7 @@ async function main() { id: 'qa:flights:radio-recenter-stage-owner', position: viewer.camera.positionWC.clone(), }); - owner.gevTrackedId = 'flights:qa-radio-recenter-stage-owner'; + window.__godsEyeView.entityRecords.write(owner).trackedId = 'flights:qa-radio-recenter-stage-owner'; viewer.trackedEntity = owner; completeFlight(0); const trackingBetweenStagesCalls = calls.length; diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index e00dadfc3a..4792d57a3b 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -701,7 +701,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__godsEyeView.entityRecords.read(window.__godsEyeView.viewer.trackedEntity)?.trackedId === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -712,7 +712,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(window.__godsEyeView.viewer.trackedEntity)?.trackedId || null, }; }); record( @@ -742,7 +742,7 @@ async function main() { const tracked = manager?.layers?.get('flights')?.module?.getTrackedInfo?.(); return manager?.isEnabled?.('flights') && tracked?.icao24 === 'aaa001' - && window.__godsEyeView.viewer.trackedEntity?.gevTrackedId === 'flights:aaa001'; + && window.__godsEyeView.entityRecords.read(window.__godsEyeView.viewer.trackedEntity)?.trackedId === 'flights:aaa001'; }, { timeout: 30000, polling: 100 }, ); @@ -753,7 +753,7 @@ async function main() { flightsEnabled: manager.isEnabled('flights'), trackedId: flights.getTrackedInfo()?.icao24 || null, durableId: flights.getParams()?.selectedFlightsTrackingId || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(window.__godsEyeView.viewer.trackedEntity)?.trackedId || null, }; }); record( @@ -815,7 +815,7 @@ async function main() { const latchedShare = await evalPage(() => ({ tracked: window.__godsEyeView.dataManager.layers .get('flights').module.getTrackedInfo()?.icao24 || null, - viewerTrackedId: window.__godsEyeView.viewer.trackedEntity?.gevTrackedId || null, + viewerTrackedId: window.__godsEyeView.entityRecords.read(window.__godsEyeView.viewer.trackedEntity)?.trackedId || null, })); record( 'share-v2: the pending subject latches on when it arrives on a later poll', @@ -1380,7 +1380,7 @@ async function main() { if (exactPickModel) return exactPickModel; const ent = window.__godsEyeView.viewer.trackedEntity; let tracked = null; - if (ent && typeof ent.gevDisplayPosition === 'function') tracked = ent.gevDisplayPosition(); + if (ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function') tracked = window.__godsEyeView.entityRecords.read(ent)?.displayPosition(); if (!tracked) return pool[0]; let best = null, bestD = Infinity; for (const m of pool) { @@ -1427,7 +1427,7 @@ async function main() { const dm = window.__godsEyeView.dataManager; const fl = dm.layers.get('flights').module; const ent = window.__godsEyeView.viewer.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const disp = ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function' ? window.__godsEyeView.entityRecords.read(ent)?.displayPosition() : null; const dets = fl.getDetectableObjects({ maxCount: 1000 }); const me = dets.find((d) => d.id === icao || d.id === (fl.getTrackedInfo() && fl.getTrackedInfo().callsign)); if (!disp || !me || !me.position) return null; @@ -1656,7 +1656,7 @@ async function main() { const ti = fl.getTrackedInfo(); if (!ti) return null; const ent = v.trackedEntity; - const disp = ent && typeof ent.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const disp = ent && typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function' ? window.__godsEyeView.entityRecords.read(ent)?.displayPosition() : null; const pos = disp || ti.position; if (!pos) return null; const center = v.scene.cartesianToCanvasCoordinates(pos); @@ -1908,7 +1908,7 @@ async function main() { // presentation model (entities are asserted native-label-free); // the native read stays as a fallback so this probe still fails // loudly if BOTH surfaces are ever absent. - const model = ent.gevLabelModel; + const model = window.__godsEyeView.entityRecords.read(ent)?.labelModel; if (model) return [model.title, ...(model.details || [])].filter(Boolean).join('\n'); if (!ent.label || !ent.label.text) return null; const t = ent.label.text; @@ -2553,7 +2553,7 @@ async function main() { } // WELD (tracked): the tracked CARD anchors to the model you can see. - // `gevVisualPosition` is a SEPARATE accessor from `gevDisplayPosition` on + // the record's `visualPosition` is a SEPARATE accessor from its `displayPosition` on // purpose — the latter carries the follow-camera anti-jitter contract and // must keep returning the cached dead-reckoned value the camera settled // on. So this asserts both halves: the visual accessor is welded to the @@ -2580,10 +2580,10 @@ async function main() { const at = (p) => (p ? Math.hypot( p.x - anchor.x, p.y - anchor.y, p.z - anchor.z, ) : null); - const visual = typeof ent?.gevVisualPosition === 'function' ? ent.gevVisualPosition() : null; - const display = typeof ent?.gevDisplayPosition === 'function' ? ent.gevDisplayPosition() : null; + const visual = typeof window.__godsEyeView.entityRecords.read(ent)?.visualPosition === 'function' ? window.__godsEyeView.entityRecords.read(ent)?.visualPosition() : null; + const display = typeof window.__godsEyeView.entityRecords.read(ent)?.displayPosition === 'function' ? window.__godsEyeView.entityRecords.read(ent)?.displayPosition() : null; return { - hasVisualAccessor: typeof ent?.gevVisualPosition === 'function', + hasVisualAccessor: typeof window.__godsEyeView.entityRecords.read(ent)?.visualPosition === 'function', visualDelta: at(visual), displayDelta: at(display), }; @@ -2599,7 +2599,7 @@ async function main() { // anti-jitter accessor has been repurposed and the follow camera is at // risk. Skipped (not failed) when the DR cache is momentarily invalid. const displayDelta = trackedWeld.displayDelta; - record('weld: gevDisplayPosition still reports the dead-reckoned position (anti-jitter intact)', + record('weld: the record displayPosition still reports the dead-reckoned position (anti-jitter intact)', !Number.isFinite(displayDelta) || displayDelta > ACCESSOR_SEPARATION_EPSILON_M, Number.isFinite(displayDelta) ? `displayΔ=${displayDelta.toFixed(3)} m (must stay > ${ACCESSOR_SEPARATION_EPSILON_M} m — the ground-snap split)` diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index 0509a47a56..54ca3205fe 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -8,6 +8,7 @@ import { t } from '../i18n/index.js'; import { nextTick } from 'vue'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { applicationPinia } from '../ui/vueRuntime.js'; +import { readEntityRecord } from '../data/entityRecords.js'; /** A label whose detailed outline could not be resolved. */ function outlineUnavailableLabel(label) { @@ -424,10 +425,9 @@ export function createScreenAnnotationRenderer( const ent = viewer.trackedEntity; const now = Cesium.JulianDate.now(); + const displayPosition = readEntityRecord(ent)?.displayPosition; const world = - typeof ent?.gevDisplayPosition === 'function' - ? ent.gevDisplayPosition() - : null; + typeof displayPosition === 'function' ? displayPosition() : null; const win = world ? Cesium.SceneTransforms.worldToWindowCoordinates( scene, diff --git a/src/app/tools.js b/src/app/tools.js index 9d91f70a98..0556ccc55d 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -17,6 +17,7 @@ import { holdContinuousRender, releaseContinuousRender, } from '../renderGovernor.js'; +import { entityRecord, readEntityRecord } from '../data/entityRecords.js'; /** Attach scene tools, rendering listeners and the application debug handle. */ export function createApplicationTools({ @@ -194,6 +195,7 @@ export function createApplicationTools({ getRenderGovernorDiagnostics, surfaceServices: operations.surface, requestRender: governorRequestRender, + entityRecords: { read: readEntityRecord, write: entityRecord }, }; const debug = window.__godsEyeView; defer(() => { diff --git a/src/cockpitMarkup.test.mjs b/src/cockpitMarkup.test.mjs index 64d03914bd..580920d819 100644 --- a/src/cockpitMarkup.test.mjs +++ b/src/cockpitMarkup.test.mjs @@ -227,7 +227,7 @@ test('Cockpit Escape handling precedes form-control shortcut suppression and foc assert.doesNotMatch(exit, /applyTrackedCameraFrame/); assert.match( ui, - /restoreTrackingFrame: \(entity\) => \{[\s\S]*?gevTrackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, + /restoreTrackingFrame: \(entity\) => \{[\s\S]*?readEntityRecord\(entity\)\?\.trackedId[\s\S]*?flightsLayer\.refocusTrackedById[\s\S]*?militaryFlightsLayer\.refocusTrackedById/, 'Cockpit exit must return camera-frame ownership through the source layer so Contact Focus cannot accumulate a second owner', ); }); @@ -299,7 +299,7 @@ test('the cockpit reads its aircraft from the layer that owns Cesium tracking', const read = readAircraftInfo.toString(); assert.ok(read, 'readAircraftInfo is missing'); assert.match(read, /resolveTrackedAircraftInfo\(\{/); - assert.match(read, /gevTrackedId/); + assert.match(read, /readEntityRecord\([^)]*\)\?\.trackedId/); // In cockpit mode the controller moves the entity off viewer.trackedEntity, // so its own handle is the tracked identity there. assert.match(read, /this\.viewer\?\.trackedEntity \|\| this\.trackedEntity/); diff --git a/src/cockpitMath.js b/src/cockpitMath.js index 3186b1f3c0..dc60785001 100644 --- a/src/cockpitMath.js +++ b/src/cockpitMath.js @@ -306,7 +306,7 @@ export function relativeBearing(bearing, heading) { * Resolve which flight layer owns the cockpit's tracked aircraft. * * Both layers can briefly describe a tracked aircraft during a cross-layer - * handoff, so the viewer's normalized tracked identity (`gevTrackedId`) is the + * handoff, so the viewer's normalized tracked identity (the entity record's `trackedId`) is the * tie-breaker — the same rule `militaryAwareness.currentTrackedFlightSubject` * uses. Layer precedence remains the fallback when no normalized identity is * available, so tracking paths that never stamp one keep working. diff --git a/src/cockpitMath.test.mjs b/src/cockpitMath.test.mjs index 5a7f029c01..41c99f6cde 100644 --- a/src/cockpitMath.test.mjs +++ b/src/cockpitMath.test.mjs @@ -365,7 +365,7 @@ test('tracked-identity resolution falls back to layer precedence', () => { const civilian = { icao24: 'aaa077' }; const military = { icao24: 'ae01ce' }; // No stamped identity (or one that matches neither layer) keeps the historic - // civilian-first order so tracking paths without gevTrackedId still work. + // civilian-first order so tracking paths without an entity record trackedId still work. assert.equal(resolveTrackedAircraftInfo({ civilian, military }).layerId, 'flights'); assert.equal( resolveTrackedAircraftInfo({ civilian, military, trackedId: 'satellites:25544' }).layerId, diff --git a/src/cockpitTracking.js b/src/cockpitTracking.js index 3671e3a363..07c32fcf2c 100644 --- a/src/cockpitTracking.js +++ b/src/cockpitTracking.js @@ -1,7 +1,7 @@ /* * Cockpit aircraft metadata itself is resolved by `resolveTrackedAircraftInfo` * in `cockpitMath.js` — the landed owner of that rule. It keeps layer - * precedence as the fallback when no normalized `gevTrackedId` is available, + * precedence as the fallback when the entity record has no normalized `trackedId`, * so tracking paths that never stamp one keep working; `readAircraftInfo` is * pinned to it by `cockpitMarkup.test.mjs`. This module owns only the * multi-step ENTRY TRANSACTION (adopt → enter → roll back). diff --git a/src/cockpitTracking.test.mjs b/src/cockpitTracking.test.mjs index fd6a171cc0..b3a711167b 100644 --- a/src/cockpitTracking.test.mjs +++ b/src/cockpitTracking.test.mjs @@ -5,6 +5,7 @@ import { enterCockpitWithTracking, restoreAircraftTrackingOwner, } from './cockpitTracking.js'; +import { readEntityRecord, withEntityRecord } from './data/entityRecords.js'; /** * Model the two production stamping seams that sit under this transaction: @@ -22,7 +23,7 @@ function stampingWorld({ entryAllowed = true } = {}) { layerId, trackById(id) { if (!trackable) return false; - world.trackedEntity = { gevTrackedId: `${layerId}:${id}` }; + world.trackedEntity = withEntityRecord({}, { trackedId: `${layerId}:${id}` }); stamp('trackedEntityChanged'); // the ui.js listener return true; }, @@ -80,7 +81,7 @@ test('a refused Cockpit entry still stamps for the tracker it already moved', () // Adoption stamped, and the rollback re-track stamped again. assert.deepEqual(world.stamps, ['trackedEntityChanged', 'trackedEntityChanged']); assert.equal(world.generation, 2); - assert.equal(world.trackedEntity.gevTrackedId, 'military:ae01ce'); + assert.equal(readEntityRecord(world.trackedEntity)?.trackedId, 'military:ae01ce'); }); test('a Cockpit entry that mutates nothing takes no camera authority', () => { diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 549adde96d..977ae8e1f4 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -31,6 +31,7 @@ import { isAlprSurveillanceType, normalizeAlprNode, } from './alprCameras.js'; +import { readEntityRecord } from './entityRecords.js'; test('normalizeAlprNode: maps a full OSM node to a plain record', () => { const record = normalizeAlprNode({ @@ -443,25 +444,25 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a const entities = h.source.entities.values; assert.equal(alprCamerasLayer.name, 'ALPR Cameras'); assert.deepEqual( - entities.map((entity) => entity.gevLabelModel.title), + entities.map((entity) => readEntityRecord(entity)?.labelModel.title), ['ALPR-0042', 'ALPR-0043', 'ALPR-0044'], ); assert.equal( new Set(entities.map((entity) => entity.billboard.image.getValue())).size, 1, ); - assert.deepEqual(entities[0].gevLabelModel.details, [ + assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [ 'OSM MAPPED', 'FLOCK SAFETY · CITY POLICE · FIXED', 'PUBLIC MAP DATA', ]); - assert.deepEqual(entities[1].gevLabelModel.details, [ + assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [ 'OSM MAPPED', 'MOTOROLA SOLUTIONS', 'PUBLIC MAP DATA', ]); assert.deepEqual( - entities[2].gevLabelModel.details, + readEntityRecord(entities[2])?.labelModel.details, ['OSM MAPPED', 'PUBLIC MAP DATA'], 'unknown metadata is not guessed, but the source is always named', ); @@ -813,7 +814,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di h.click('alpr:42'); const entity = h.source.entities.getById('alpr:42'); const anchor = Cesium.Cartographic.fromCartesian( - entity.gevDisplayPosition(), + readEntityRecord(entity)?.displayPosition(), ); assert.ok(Math.abs(anchor.height - 187) < 0.001); assert.ok( @@ -821,7 +822,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di ); for (let i = 0; i < 60; i++) { h.viewer.scene.postRender.raiseEvent(); - entity.gevDisplayPosition(); + readEntityRecord(entity)?.displayPosition(); } assert.equal(samples, 1, 'no per-frame raycasts'); h.advance(1000); @@ -921,9 +922,9 @@ test('two factories keep their requests, records and destruction independent', a assert.equal(b.source.entities.values[0].id, 'directory:99'); assert.equal(second.source, 'Test camera directory'); assert.ok( - b.source.entities.values[0].gevLabelModel.details.includes( - 'Source: Test directory', - ), + readEntityRecord( + b.source.entities.values[0], + )?.labelModel.details.includes('Source: Test directory'), ); assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0); assert.equal(a.viewer.scene.postRender.numberOfListeners, 0); diff --git a/src/data/entityRecords.js b/src/data/entityRecords.js new file mode 100644 index 0000000000..f0ac03c8e4 --- /dev/null +++ b/src/data/entityRecords.js @@ -0,0 +1,52 @@ +/** + * @module entityRecords + * @description Records for the entities layers draw, so layer state lives in the app + * rather than on the renderer's objects. A layer writes the record for an entity it draws; + * the tracked readout, follow camera, cockpit, share links and awareness read it back + * through the entity the renderer hands them (a pick or the tracked entity). + * + * Fields a record may hold: + * - `trackedId`: the normalized `layer:id` identity, e.g. `flights:a1b2c3`. + * - `displayPosition()`: the layer's cached display position (the follow camera's + * anti-jitter contract: the value the camera settled on, never recomputed late). + * - `visualPosition()`: where a 3D model is actually drawn, for the tracked card. + * - `labelModel`: the tracked card's `{ title, details, accent, … }`. + * - `selectionOrigin`: what started the selection (`'user'`, …). + */ + +const records = new WeakMap(); + +/** + * The record for `entity`, made empty on first use. For layers writing their own state. + * @param {Object} entity An entity the layer draws. + * @returns {Object} + */ +export function entityRecord(entity) { + let record = records.get(entity); + if (!record) { + record = {}; + records.set(entity, record); + } + return record; +} + +/** + * The record for `entity`, or null when it has none (or there is no entity). For readers. + * @param {Object|null|undefined} entity + * @returns {Object|null} + */ +export function readEntityRecord(entity) { + if (!entity || typeof entity !== 'object') return null; + return records.get(entity) ?? null; +} + +/** + * Write `fields` into `entity`'s record and return the entity. + * @param {Object} entity + * @param {Object} fields Record fields to set. + * @returns {Object} `entity` + */ +export function withEntityRecord(entity, fields) { + Object.assign(entityRecord(entity), fields); + return entity; +} diff --git a/src/data/entityRecords.test.mjs b/src/data/entityRecords.test.mjs new file mode 100644 index 0000000000..c59b829ace --- /dev/null +++ b/src/data/entityRecords.test.mjs @@ -0,0 +1,31 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { entityRecord, readEntityRecord, withEntityRecord } from './entityRecords.js'; + +test('an entity record is made on first write and read back by the same entity', () => { + const entity = {}; + assert.equal(readEntityRecord(entity), null); + entityRecord(entity).trackedId = 'flights:a1b2c3'; + assert.equal(entityRecord(entity), entityRecord(entity), 'one record per entity'); + assert.equal(readEntityRecord(entity)?.trackedId, 'flights:a1b2c3'); + assert.equal(readEntityRecord({}), null, 'another entity has its own record'); +}); + +test('the record lives in the app, not on the entity', () => { + const entity = {}; + entityRecord(entity).labelModel = { title: 'DAL123', details: [] }; + assert.deepEqual(Object.keys(entity), []); +}); + +test('reading without an entity gives null', () => { + assert.equal(readEntityRecord(null), null); + assert.equal(readEntityRecord(undefined), null); + assert.equal(readEntityRecord('flights:a1b2c3'), null); +}); + +test('withEntityRecord writes fields into the record and returns the entity', () => { + const entity = withEntityRecord({ id: 'alpr:42' }, { trackedId: 'alpr:42' }); + assert.equal(entity.id, 'alpr:42'); + assert.equal(readEntityRecord(entity)?.trackedId, 'alpr:42'); + assert.equal(Object.hasOwn(entity, 'trackedId'), false); +}); diff --git a/src/data/flights.test.mjs b/src/data/flights.test.mjs index 7fe197c303..d6a06e5b9a 100644 --- a/src/data/flights.test.mjs +++ b/src/data/flights.test.mjs @@ -28,6 +28,7 @@ import { destroyTrackedReadout, initTrackedReadout, } from './trackedReadout.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; test('share-Follow absence requires an accepted OpenSky snapshot', async () => { _setFlightTrackingRefreshOutcomeForTest({ status: 'source-unavailable' }); @@ -184,7 +185,7 @@ test('flights first update forwards caller cancellation into the feed request', test('nonempty OpenSky payload with zero usable rows cannot prove share target absence', async () => { _setTrackedFlightRefreshStateForTest({ icao24: 'abc123', - entity: { gevLabelModel: { title: 'WARM', details: [] } }, + entity: withEntityRecord({}, { labelModel: { title: 'WARM', details: [] } }), billboard: { show: false }, billboardCollection: { show: true, remove() {} }, viewer: { camera: { positionCartographic: null }, scene: {} }, @@ -317,7 +318,7 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STALE', async () => { const icao24 = 'a1b2c3'; - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } }); const billboard = { position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000), color: Cesium.Color.WHITE, @@ -388,13 +389,13 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA try { await flightsLayer.update(viewer); - assert.equal(entity.gevLabelModel.title, 'DAL123'); - assert.match(entity.gevLabelModel.details.join(' · '), /FL350/); - assert.match(entity.gevLabelModel.details.join(' · '), /486 kts/); + assert.equal(readEntityRecord(entity)?.labelModel.title, 'DAL123'); + assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /FL350/); + assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /486 kts/); await flightsLayer.update(viewer); assert.match( - [entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '), + [readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · '), /STALE/, ); } finally { @@ -527,7 +528,7 @@ test('real civil track path creates no native label and publishes every cached h assert.ok( entities.values.every((candidate) => candidate.label === undefined), ); - assert.deepEqual(entity.gevLabelModel, { + assert.deepEqual(readEntityRecord(entity)?.labelModel, { title: 'N12345 · FL350 · 486 kts', details: ['TEST AIR · A320', 'AUS → LAX'], accent: '#39d0ff', @@ -546,7 +547,7 @@ test('real civil track path creates no native label and publishes every cached h 'user', 'same-target selection upgrades durable authority', ); - assert.equal(entity.gevSelectionOrigin, 'user'); + assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user'); assert.equal(flightsLayer.refocusTrackedById('different-flight'), false); assert.equal( flightsLayer.refocusTrackedById(icao24, { origin: 'voice' }), @@ -579,8 +580,8 @@ test('real civil track path creates no native label and publishes every cached h const entry = publication.entries[0]; assert.equal(entry.protected, true); assert.equal(entry.paintLane, 'tracked'); - assert.equal(entry.title, entity.gevLabelModel.title); - assert.deepEqual(entry.details, entity.gevLabelModel.details); + assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title); + assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details); const display = entity.position.getValue(now); assert.ok(display, 'tracked position callback must seed its frame cache'); @@ -941,7 +942,7 @@ test('civil label chain: the awareness selection EVENT uses the canonical chain' }); test('civil tracked readout: a callsign-less enriched contact reads as its registration', async () => { - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } }); seedLabelContact({ callsign: ' ', registration: ' N123AB ', tracked: true }); _setTrackedFlightRefreshStateForTest({ icao24: LABEL_ICAO, @@ -981,9 +982,9 @@ test('civil tracked readout: a callsign-less enriched contact reads as its regis camera: { positionCartographic: null }, scene: {}, }); - assert.match(entity.gevLabelModel.title, /^N123AB\b/); + assert.match(readEntityRecord(entity)?.labelModel.title, /^N123AB\b/); assert.doesNotMatch( - [entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '), + [readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · '), /ae1fa4/, ); } finally { diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index 05fd97dc0a..5a17be256c 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -46,6 +46,7 @@ import { presentAwarenessDistance, } from '../layers/awareness/panel.js'; import { NAVIGATION_AUTHORITY_EVENT } from '../navigationPolicy.js'; +import { withEntityRecord } from './entityRecords.js'; const militaryAwarenessSource = readLayerSource( new URL('./militaryAwareness.js', import.meta.url), @@ -823,9 +824,7 @@ for (const fixture of [ let retrackCalls = 0; try { - const trackedEntity = { - gevTrackedId: `${subject.layerId}:${subject.id}`, - }; + const trackedEntity = withEntityRecord({}, { trackedId: `${subject.layerId}:${subject.id}` }); runtime.viewer.trackedEntity = trackedEntity; replaceMethod( fixture.layer, @@ -927,7 +926,7 @@ test('Contacts activation adopts the production military tracked-subject descrip ), 'mutating one accessor result must not alter the tracked source position', ); - runtime.viewer.trackedEntity = { gevTrackedId: `military:${id}` }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `military:${id}` }); replaceMethod(flightsLayer, 'getTrackedSubject', () => null, restores); replaceMethod( flightsLayer, @@ -1032,7 +1031,7 @@ test('production military tracked-subject label falls back to registration befor 'getAllPositions id stays the identity hex', ); - runtime.viewer.trackedEntity = { gevTrackedId: `military:${id}` }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `military:${id}` }); replaceMethod(flightsLayer, 'getTrackedSubject', () => null, restores); replaceMethod(flightsLayer, 'trackById', () => true, restores); replaceMethod(militaryFlightsLayer, 'trackById', () => true, restores); @@ -1104,7 +1103,7 @@ test('a cached Context subject re-reads its label when enrichment lands after se meta, }); - runtime.viewer.trackedEntity = { gevTrackedId: `flights:${id}` }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `flights:${id}` }); replaceMethod( militaryFlightsLayer, 'getTrackedSubject', @@ -1247,7 +1246,7 @@ test('Contacts activation adopts the production civilian tracked-subject descrip ), 'mutating one accessor result must not alter the tracked source position', ); - runtime.viewer.trackedEntity = { gevTrackedId: `flights:${id}` }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: `flights:${id}` }); replaceMethod( militaryFlightsLayer, 'getTrackedSubject', @@ -1334,7 +1333,7 @@ test('Contacts activation reconciles to a newer cross-layer tracked flight after const restores = []; try { - runtime.viewer.trackedEntity = { gevTrackedId: 'flights:first' }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'flights:first' }); replaceMethod( flightsLayer, 'getTrackedSubject', @@ -1357,7 +1356,7 @@ test('Contacts activation reconciles to a newer cross-layer tracked flight after civilianTracked = null; militaryTracked = awarenessSubject('military', 'latest', positions.latest); - runtime.viewer.trackedEntity = { gevTrackedId: 'military:latest' }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'military:latest' }); releaseDependencies(); await nextTurn(); await nextTurn(); @@ -1401,7 +1400,7 @@ test('tracked flight cleared during Contacts activation suppresses fallback auto const focused = []; try { - runtime.viewer.trackedEntity = { gevTrackedId: 'flights:selected' }; + runtime.viewer.trackedEntity = withEntityRecord({}, { trackedId: 'flights:selected' }); replaceMethod(flightsLayer, 'getTrackedSubject', () => tracked, restores); replaceMethod( militaryFlightsLayer, diff --git a/src/data/militaryFlights.test.mjs b/src/data/militaryFlights.test.mjs index d04061793c..3ea1c5f69c 100644 --- a/src/data/militaryFlights.test.mjs +++ b/src/data/militaryFlights.test.mjs @@ -17,6 +17,7 @@ import { destroyTrackedReadout, initTrackedReadout, } from './trackedReadout.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; test('share-Follow absence requires an accepted adsb.lol snapshot', async () => { _setMilitaryTrackingRefreshOutcomeForTest({ status: 'source-unavailable' }); @@ -147,7 +148,7 @@ test('military first update forwards caller cancellation into the feed request', test('nonempty adsb.lol payload with zero usable rows cannot prove share target absence', async () => { _setTrackedMilitaryRefreshStateForTest({ icao24: 'ae1234', - entity: { gevLabelModel: { title: 'WARM', details: [] } }, + entity: withEntityRecord({}, { labelModel: { title: 'WARM', details: [] } }), billboard: { show: false }, billboardCollection: { show: true, remove() {} }, viewer: { camera: { positionCartographic: null }, scene: {} }, @@ -183,7 +184,7 @@ test('nonempty adsb.lol payload with zero usable rows cannot prove share target test('military poll refreshes tracked callsign/altitude/kts and marks a missed poll STALE', async () => { const icao24 = 'ae01ce'; - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } }); const billboard = { position: Cesium.Cartesian3.fromDegrees(-97.0, 31.0, 8_000), color: Cesium.Color.WHITE, @@ -246,12 +247,12 @@ test('military poll refreshes tracked callsign/altitude/kts and marks a missed p try { await militaryFlightsLayer.update(viewer); - assert.equal(entity.gevLabelModel.title, 'RCH451'); - assert.match(entity.gevLabelModel.details.join(' · '), /28000 ft/); - assert.match(entity.gevLabelModel.details.join(' · '), /400 kt/); + assert.equal(readEntityRecord(entity)?.labelModel.title, 'RCH451'); + assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /28000 ft/); + assert.match(readEntityRecord(entity)?.labelModel.details.join(' · '), /400 kt/); await militaryFlightsLayer.update(viewer); - assert.match(entity.gevLabelModel.title, /STALE/); + assert.match(readEntityRecord(entity)?.labelModel.title, /STALE/); } finally { globalThis.fetch = realFetch; } @@ -264,7 +265,7 @@ test('cached military snapshots retain their observation time and expose stale f const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedMilitaryRefreshStateForTest({ icao24: 'ae01ce', - entity: { gevLabelModel: { title: 'RCH451', details: [] } }, + entity: withEntityRecord({}, { labelModel: { title: 'RCH451', details: [] } }), billboard: { position: Cesium.Cartesian3.fromDegrees(-97, 31, 8000), show: false, @@ -442,7 +443,7 @@ test('real military track path creates no native label and publishes every cache assert.ok( entities.values.every((candidate) => candidate.label === undefined), ); - assert.deepEqual(entity.gevLabelModel, { + assert.deepEqual(readEntityRecord(entity)?.labelModel, { title: 'RCH451', details: ['C17 · 05-8152', 'United States Air Force · 28000 ft · 450 kt'], accent: '#ffd166', @@ -464,7 +465,7 @@ test('real military track path creates no native label and publishes every cache 'user', 'same-target selection upgrades durable authority', ); - assert.equal(entity.gevSelectionOrigin, 'user'); + assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user'); assert.equal( militaryFlightsLayer.refocusTrackedById('different-flight'), false, @@ -500,8 +501,8 @@ test('real military track path creates no native label and publishes every cache const entry = publication.entries[0]; assert.equal(entry.protected, true); assert.equal(entry.paintLane, 'tracked'); - assert.equal(entry.title, entity.gevLabelModel.title); - assert.deepEqual(entry.details, entity.gevLabelModel.details); + assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title); + assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details); const display = entity.position.getValue(now); assert.ok(display, 'tracked position callback must seed its frame cache'); @@ -845,7 +846,7 @@ test('the military tracked descriptor publishes the reported vertical rate', () const seedRate = (verticalRateMps) => _setTrackedMilitaryRefreshStateForTest({ icao24: 'ae7f01', - entity: { gevLabelModel: { title: 'TEST', details: [] } }, + entity: withEntityRecord({}, { labelModel: { title: 'TEST', details: [] } }), billboard: { position: Cesium.Cartesian3.fromDegrees(-97.0, 31.0, 8_000), color: Cesium.Color.WHITE, diff --git a/src/data/militaryInstallations.test.mjs b/src/data/militaryInstallations.test.mjs index c3f9cdb895..ff1d2dc1b9 100644 --- a/src/data/militaryInstallations.test.mjs +++ b/src/data/militaryInstallations.test.mjs @@ -25,6 +25,7 @@ import { } from '../renderGovernor.js'; import * as Cesium from 'cesium'; import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js'; +import { readEntityRecord } from './entityRecords.js'; test('clicking a selected installation again or empty map clears it through refresh', async () => { const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42, @@ -435,7 +436,7 @@ test('a footprint-less relation just outside the viewport still renders', async }); try { assert.deepEqual( - harness.entities().map((entity) => entity.gevLabelModel?.title), + harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title), ['Straddling Range'], ); } finally { @@ -475,7 +476,7 @@ test('a legacy-shaped payload at the cap fires the exact-viewport retry end to e assert.equal(harness.requests.length, 2, 'a legacy entry must not skip the retry'); assert.equal(harness.requests[1].includes('exact=1'), true); assert.deepEqual( - harness.entities().map((entity) => entity.gevLabelModel?.title), + harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title), ['Rescued From Legacy'], ); } finally { @@ -506,7 +507,7 @@ test('off-viewport records from the snapped superset never render or enter conte ], }); try { - const titles = harness.entities().map((entity) => entity.gevLabelModel?.title); + const titles = harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title); assert.deepEqual(titles, ['In View'], 'only the in-viewport site renders'); assert.equal(harness.contextLabels().includes('Off View'), false, 'and none enters context'); assert.equal(harness.stats().count, 1); @@ -534,7 +535,7 @@ test('a saturated snapped tile refetches the exact viewport before rendering', a assert.equal(harness.requests[0].includes('exact=1'), false, 'first ask uses the shared snapped tile'); assert.equal(harness.requests[1].includes('exact=1'), true, 'retry opts out of the snap'); assert.deepEqual( - harness.entities().map((entity) => entity.gevLabelModel?.title), + harness.entities().map((entity) => readEntityRecord(entity)?.labelModel?.title), ['Rescued'], 'the in-viewport site is no longer starved by off-view ones', ); diff --git a/src/data/radio.test.mjs b/src/data/radio.test.mjs index de5717a11f..e9a07d6d2c 100644 --- a/src/data/radio.test.mjs +++ b/src/data/radio.test.mjs @@ -52,6 +52,7 @@ import { stationMatchesRadioCategory, } from './radio.js'; import { radioStationRow, withRadioLayer } from '../testSupport/radioLayerHarness.mjs'; +import { withEntityRecord } from './entityRecords.js'; const stations = [ { id: 'news', tags: ['News', 'Weather Radio', 'air traffic'] }, @@ -1652,10 +1653,10 @@ test('Radio recovery preserves closer altitude and caps extreme full-globe zoom' test('Radio camera navigation yields to every live tracked-entity owner', () => { const viewer = { camera: {} }; assert.equal(radioCameraNavigationAllowed(viewer), true); - for (const gevTrackedId of ['flights:abc123', 'military:def456']) { - const trackedEntity = { gevTrackedId }; + for (const trackedId of ['flights:abc123', 'military:def456']) { + const trackedEntity = withEntityRecord({}, { trackedId }); viewer.trackedEntity = trackedEntity; - assert.equal(radioCameraNavigationAllowed(viewer), false, gevTrackedId); + assert.equal(radioCameraNavigationAllowed(viewer), false, trackedId); assert.equal(viewer.trackedEntity, trackedEntity); } viewer.trackedEntity = undefined; diff --git a/src/data/satellitesTrackedRefresh.test.mjs b/src/data/satellitesTrackedRefresh.test.mjs index cf70b373c2..9a6e3b26e6 100644 --- a/src/data/satellitesTrackedRefresh.test.mjs +++ b/src/data/satellitesTrackedRefresh.test.mjs @@ -18,6 +18,7 @@ import { } from './satellites.js'; import satellitesLayer from './satellites.js'; import { createTrackedOverlayEntry } from './trackedReadout.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; const L1 = '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927'; @@ -117,7 +118,7 @@ test('selected satellite params survive delayed arrival and yield to newer expli satellitesLayer.setParams({ selectedSatTrackingId: 25544 }), ); assert.equal(satellitesLayer.getParams().selectedSatTrackingId, 25544); - assert.equal(viewer.trackedEntity?.gevTrackedId, 'satellites:25544'); + assert.equal(readEntityRecord(viewer.trackedEntity)?.trackedId, 'satellites:25544'); satellitesLayer.stopTracking(); _removeSatelliteTrackingCandidateForTest(25544); @@ -194,7 +195,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () => // so their ambient labels stack underneath the tracked card. Owner ruling: // consolidate them as secondary info on that card, and suppress only those // members — never unrelated satellites that merely happen to be nearby. - const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); const point = { position: new Cesium.Cartesian3() }; const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } }; let nowMs = Date.UTC(2008, 8, 20, 12, 30); @@ -229,7 +230,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () => viewer.scene.frameState.frameNumber = 2; _runSatellitePreRenderForTest(); - const details = entity.gevLabelModel.details; + const details = readEntityRecord(entity)?.labelModel.details; // Class leads the detail block; the altitude line follows it, and the // consolidated companions stay last. assert.equal( @@ -252,7 +253,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () => assert.doesNotMatch(details[2], /\+2/); }); test('satellite pre-render refreshes the tracked altitude on each propagated frame', () => { - const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); const point = { position: new Cesium.Cartesian3() }; const viewer = { camera: null, @@ -271,17 +272,17 @@ test('satellite pre-render refreshes the tracked altitude on each propagated fra }); _runSatellitePreRenderForTest(); - assert.equal(entity.gevLabelModel.title, 'ISS (ZARYA)'); - assert.equal(entity.gevLabelModel.details[0], 'STATION · ISS'); + assert.equal(readEntityRecord(entity)?.labelModel.title, 'ISS (ZARYA)'); + assert.equal(readEntityRecord(entity)?.labelModel.details[0], 'STATION · ISS'); // formatQuantity keeps the number and its unit together with a no-break space. - assert.equal(entity.gevLabelModel.details[1], '353\u00a0km · NORAD 25544'); + assert.equal(readEntityRecord(entity)?.labelModel.details[1], '353\u00a0km · NORAD 25544'); epochIndex = 1; viewer.scene.frameState.frameNumber = 2; _runSatellitePreRenderForTest(); - assert.equal(entity.gevLabelModel.details[1], '366\u00a0km · NORAD 25544'); + assert.equal(readEntityRecord(entity)?.labelModel.details[1], '366\u00a0km · NORAD 25544'); assert.equal( - entity.gevLabelModel.details[0], + readEntityRecord(entity)?.labelModel.details[0], 'STATION · ISS', 'the class line survives an altitude-only republish', ); diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index 98fd534c4e..9ba8c25c21 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -33,6 +33,7 @@ import militaryFlightsLayer, { import { findCompatibleHistoryIndex } from './militaryAwareness.js'; import { createGevActionRunner } from '../voice/gevActions.js'; import { ANALYST_LAYERS, createAnalystEngine } from './analystEngine.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; /** Strip block and line comments so source pins scan CODE, not prose. */ function stripComments(source) { @@ -149,7 +150,7 @@ test('a conversion survives a poll refresh, in both the billboard and the tracke const icao24 = 'a1b2c3'; setTr3b(icao24, true); - const entity = { gevLabelModel: { title: 'OLD', details: [] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: [] } }); const billboard = { position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000), color: Cesium.Color.WHITE, @@ -212,11 +213,11 @@ test('a conversion survives a poll refresh, in both the billboard and the tracke assert.equal(billboard.image, aircraftIcon('tr3b'), 'the poll reconciler re-images through the TR-3B resolver, not the raw class'); // Live telemetry keeps flowing; only the class label is the operator's fiction. - assert.match(entity.gevLabelModel.title, /^DAL123 · FL350 · 486 kts$/); - assert.deepEqual(entity.gevLabelModel.details.slice(0, 1), ['TR-3B'], + assert.match(readEntityRecord(entity)?.labelModel.title, /^DAL123 · FL350 · 486 kts$/); + assert.deepEqual(readEntityRecord(entity)?.labelModel.details.slice(0, 1), ['TR-3B'], 'the tracked card class line reports TR-3B, replacing operator/type'); assert.equal( - [entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · ').includes('Southwest'), + [readEntityRecord(entity)?.labelModel.title, ...readEntityRecord(entity)?.labelModel.details].join(' · ').includes('Southwest'), false, 'the real operator is not shown alongside the TR-3B classification', ); diff --git a/src/data/trackedCamera.js b/src/data/trackedCamera.js index b5991835d2..37b04de897 100644 --- a/src/data/trackedCamera.js +++ b/src/data/trackedCamera.js @@ -1,4 +1,5 @@ import * as Cesium from 'cesium'; +import { readEntityRecord } from './entityRecords.js'; const MAX_FRAME_ATTEMPTS = 120; const MIN_TRACKED_RANGE_M = 150; @@ -57,7 +58,7 @@ export function trackedModelScaleForPixelCap({ * @returns {Cesium.Cartesian3|undefined} Camera-frame position. */ export function trackedDisplayPositionForCamera(entity, time, result) { - const displayedPosition = entity?.gevDisplayPosition?.(); + const displayedPosition = readEntityRecord(entity)?.displayPosition?.(); return displayedPosition ? Cesium.Cartesian3.clone(displayedPosition, result) : entity?.position?.getValue(time, result); diff --git a/src/data/trackedCamera.test.mjs b/src/data/trackedCamera.test.mjs index 50e93b3679..fc436507b0 100644 --- a/src/data/trackedCamera.test.mjs +++ b/src/data/trackedCamera.test.mjs @@ -6,6 +6,7 @@ import { trackedDisplayPositionForCamera, trackedModelScaleForPixelCap, } from './trackedCamera.js'; +import { withEntityRecord } from './entityRecords.js'; test('tracked camera origin crossing returns to the prior side at the minimum range', () => { const camera = { @@ -74,15 +75,12 @@ test('tracked model shrinks smoothly when close enough to exceed the pixel cap', test('tracked camera prefers the already-rendered display cache', () => { let callbackReads = 0; const cached = new Cesium.Cartesian3(1, 2, 3); - const entity = { - gevDisplayPosition: () => cached, - position: { + const entity = withEntityRecord({ position: { getValue: () => { callbackReads += 1; return new Cesium.Cartesian3(4, 5, 6); }, - }, - }; + } }, { displayPosition: () => cached }); const result = trackedDisplayPositionForCamera( entity, Cesium.JulianDate.now(), diff --git a/src/data/trackedCardLocale.test.mjs b/src/data/trackedCardLocale.test.mjs index 6877ea41f3..ac26ed61dc 100644 --- a/src/data/trackedCardLocale.test.mjs +++ b/src/data/trackedCardLocale.test.mjs @@ -8,6 +8,7 @@ import { _trackedFrameCartesianForTest, } from './satellites.js'; import { setLocale } from '../i18n/index.js'; +import { readEntityRecord, withEntityRecord } from './entityRecords.js'; const L1 = '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927'; @@ -16,7 +17,7 @@ const L2 = function run(locale) { setLocale(locale); - const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } }; + const entity = withEntityRecord({}, { labelModel: { title: 'OLD', details: ['? km'] } }); const point = { position: new Cesium.Cartesian3() }; const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } }; let nowMs = Date.UTC(2008, 8, 20, 12, 30); @@ -43,7 +44,7 @@ function run(locale) { nowMs += 2000; viewer.scene.frameState.frameNumber = 2; _runSatellitePreRenderForTest(); - const details = entity.gevLabelModel.details; + const details = readEntityRecord(entity)?.labelModel.details; setLocale('en'); return details; } diff --git a/src/data/trackedReadout.js b/src/data/trackedReadout.js index 486967bf3d..921449866d 100644 --- a/src/data/trackedReadout.js +++ b/src/data/trackedReadout.js @@ -4,6 +4,7 @@ import { setOverlaySourceVisible, } from '../overlays/worldOverlay.js'; import { WORLD_OVERLAY_STYLE } from '../overlays/worldOverlayTokens.js'; +import { readEntityRecord } from './entityRecords.js'; /** * @module trackedReadout @@ -79,9 +80,10 @@ export function trackedLabelModelFromText( * @returns {Object|null} */ export function cachedTrackedDisplayPosition(entity) { - if (!entity || typeof entity.gevDisplayPosition !== 'function') return null; + const displayPosition = readEntityRecord(entity)?.displayPosition; + if (typeof displayPosition !== 'function') return null; try { - return entity.gevDisplayPosition() || null; + return displayPosition() || null; } catch { return null; } @@ -91,22 +93,23 @@ export function cachedTrackedDisplayPosition(entity) { * Anchor for the tracked CARD: the position the target is visually at. * * A layer that renders its tracked contact as a 3D model publishes - * `gevVisualPosition`, which returns the translation that model is actually rendering + * the entity record's `visualPosition`, which returns the translation that model is actually rendering * with. For a grounded aircraft that differs from the display position by the full * ground-snap offset (~100 m at an inland airport), so a card anchored to the display * position sits below the aircraft and climbs slowly as the coarse floor cell warms. * * Falls back to the display position, so layers without a 3D visual (and any layer * before its model is ready) are unchanged. This deliberately does NOT repurpose - * `gevDisplayPosition`: that accessor carries the follow-camera anti-jitter contract + * the entity record's `displayPosition`: that accessor carries the follow-camera anti-jitter contract * and must keep returning the value the camera settled on. * @param {Object|null} entity Tracked or selected presentation entity. * @returns {Object|null} */ export function cachedTrackedVisualPosition(entity) { - if (entity && typeof entity.gevVisualPosition === 'function') { + const visualPosition = readEntityRecord(entity)?.visualPosition; + if (typeof visualPosition === 'function') { try { - const visual = entity.gevVisualPosition(); + const visual = visualPosition(); if (visual) return visual; } catch { /* fall through to the display position */ @@ -116,7 +119,7 @@ export function cachedTrackedVisualPosition(entity) { } function entryIdFor(entity) { - const explicit = String(entity?.gevTrackedId || '').trim(); + const explicit = String(readEntityRecord(entity)?.trackedId || '').trim(); if (explicit) return explicit; const fallback = String(entity?.id || '').trim(); return fallback ? `entity:${fallback}` : null; @@ -132,9 +135,10 @@ function activeEntity() { * @returns {Object|null} */ export function createTrackedOverlayEntry(entity) { - const model = entity?.gevLabelModel; + const record = readEntityRecord(entity); + const model = record?.labelModel; const id = entryIdFor(entity); - if (!id || !model || typeof entity.gevDisplayPosition !== 'function') { + if (!id || !model || typeof record.displayPosition !== 'function') { return null; } const title = String(model.title || '').trim(); @@ -204,7 +208,7 @@ function syncActiveEntity() { } /** - * Republish a layer's newly assigned `gevLabelModel` when that entity owns the + * Republish an entity record's newly assigned `labelModel` when that entity owns the * active tracked readout. Layers call this only when presentation text changes; * position remains the live frame-cache getter already registered with host. * @param {Object} entity Entity whose model changed. diff --git a/src/data/trackedReadout.test.mjs b/src/data/trackedReadout.test.mjs index 425a69ceb4..2bd160b9a2 100644 --- a/src/data/trackedReadout.test.mjs +++ b/src/data/trackedReadout.test.mjs @@ -13,6 +13,7 @@ import { refreshTrackedReadout, trackedLabelModelFromText, } from './trackedReadout.js'; +import { entityRecord, readEntityRecord, withEntityRecord } from './entityRecords.js'; function makeCesiumEvent() { const listeners = new Set(); @@ -53,15 +54,12 @@ test('tracked label text becomes an explicit title/details/accent model', () => ); }); -test('tracked position source reads only gevDisplayPosition and never entity.position', () => { +test('tracked position source reads only the record\'s displayPosition and never entity.position', () => { const cached = { x: 1, y: 2, z: 3 }; let propertyReads = 0; - const entity = { - gevDisplayPosition: () => cached, - position: { + const entity = withEntityRecord({ position: { getValue() { propertyReads += 1; throw new Error('fresh position read is forbidden'); }, - }, - }; + } }, { displayPosition: () => cached }); assert.equal(cachedTrackedDisplayPosition(entity), cached); assert.equal(propertyReads, 0); assert.equal(cachedTrackedDisplayPosition({ position: entity.position }), null); @@ -71,17 +69,12 @@ test('tracked position source reads only gevDisplayPosition and never entity.pos test('the tracked card anchors to the visual position without repurposing the display accessor', () => { // A grounded aircraft's 3D model rides a ground snap while its billboard stays // at the reported (buried) altitude — ~100 m apart. The card must follow the - // model you can see, while `gevDisplayPosition` keeps returning the cached + // model you can see, while the record's `displayPosition` keeps returning the cached // dead-reckoned value the follow camera settled on (anti-jitter contract). const display = { x: 1, y: 2, z: 3 }; const visual = { x: 1, y: 2, z: 103 }; let displayReads = 0; - const entity = { - gevTrackedId: 'flights:aaa077', - gevDisplayPosition: () => { displayReads += 1; return display; }, - gevVisualPosition: () => visual, - gevLabelModel: { title: 'SWA143', details: ['ON GROUND'], accent: '#6be8ff' }, - }; + const entity = withEntityRecord({}, { trackedId: 'flights:aaa077', displayPosition: () => { displayReads += 1; return display; }, visualPosition: () => visual, labelModel: { title: 'SWA143', details: ['ON GROUND'], accent: '#6be8ff' } }); assert.equal(cachedTrackedVisualPosition(entity), visual); assert.equal(displayReads, 0, 'the visual accessor short-circuits the display read'); assert.equal(cachedTrackedDisplayPosition(entity), display, @@ -91,15 +84,12 @@ test('the tracked card anchors to the visual position without repurposing the di // Layers with no 3D visual, and any layer before its model is ready, are // unchanged: the accessor falls back to the display position. - const spriteOnly = { gevDisplayPosition: () => display }; + const spriteOnly = withEntityRecord({}, { displayPosition: () => display }); assert.equal(cachedTrackedVisualPosition(spriteOnly), display); - assert.equal(cachedTrackedVisualPosition({ ...spriteOnly, gevVisualPosition: () => null }), display, + assert.equal(cachedTrackedVisualPosition(withEntityRecord({}, { displayPosition: () => display, visualPosition: () => null })), display, 'a null visual position falls back rather than blanking the card'); assert.equal( - cachedTrackedVisualPosition({ - gevDisplayPosition: () => display, - gevVisualPosition: () => { throw new Error('model gone'); }, - }), + cachedTrackedVisualPosition(withEntityRecord({}, { displayPosition: () => display, visualPosition: () => { throw new Error('model gone'); } })), display, 'a throwing visual accessor falls back instead of dropping the card', ); @@ -108,11 +98,7 @@ test('the tracked card anchors to the visual position without repurposing the di test('tracked entry factory pins the production protected-lane policy', () => { const display = { x: 4, y: 5, z: 6 }; - const entry = createTrackedOverlayEntry({ - gevTrackedId: 'satellites:25544', - gevDisplayPosition: () => display, - gevLabelModel: { title: 'ISS', details: ['420 km · NORAD 25544'], accent: '#ffd84d' }, - }); + const entry = createTrackedOverlayEntry(withEntityRecord({}, { trackedId: 'satellites:25544', displayPosition: () => display, labelModel: { title: 'ISS', details: ['420 km · NORAD 25544'], accent: '#ffd84d' } })); assert.equal(entry.id, 'satellites:25544'); assert.equal(entry.position(), display); assert.equal(entry.protected, true); @@ -122,15 +108,12 @@ test('tracked entry factory pins the production protected-lane policy', () => { }); test('selected camera readout carries tactical animation and fixed badge clearance', () => { - const entry = createTrackedOverlayEntry({ - id: 'alpr:42', gevDisplayPosition: () => ({ x: 1, y: 2, z: 3 }), - gevLabelModel: { + const entry = createTrackedOverlayEntry(withEntityRecord({ id: 'alpr:42' }, { displayPosition: () => ({ x: 1, y: 2, z: 3 }), labelModel: { title: 'ALPR-0042', details: ['OSM MAPPED'], accent: '#ff6474', cardStyle: 'tactical', selected: true, leaderStyle: 'elbow', leaderAnimationMs: 440, leaderAnimationStartedAt: 100, leaderDrawRatio: 0.68, anchorRadiusPx: 30, anchorRadiusScale: null, - }, - }); + } })); assert.equal(entry.cardStyle, 'tactical'); assert.equal(entry.selected, true); assert.equal(entry.leaderStyle, 'elbow'); @@ -146,12 +129,7 @@ test('tracked entity publishes a protected host entry backed by the frame cache' const fakeWindow = new EventTarget(); const changed = makeCesiumEvent(); const display = { x: 10, y: 20, z: 30 }; - const entity = { - id: 'generated', - gevTrackedId: 'flights:abc123', - gevDisplayPosition: () => display, - gevLabelModel: { title: 'UAL123', details: ['FL350 · 451 kts'], accent: '#39d0ff' }, - }; + const entity = withEntityRecord({ id: 'generated' }, { trackedId: 'flights:abc123', displayPosition: () => display, labelModel: { title: 'UAL123', details: ['FL350 · 451 kts'], accent: '#39d0ff' } }); const viewer = { trackedEntity: entity, trackedEntityChanged: changed }; const recorder = makeHostRecorder(); globalThis.window = fakeWindow; @@ -174,7 +152,7 @@ test('tracked entity publishes a protected host entry backed by the frame cache' assert.equal(publication.options.hideInCockpit, true); assert.equal(getActiveTrackedReadoutId(), 'flights:abc123'); - entity.gevLabelModel = { ...entity.gevLabelModel, details: ['FL360 · 455 kts'] }; + entityRecord(entity).labelModel = { ...readEntityRecord(entity)?.labelModel, details: ['FL360 · 455 kts'] }; refreshTrackedReadout(entity); assert.deepEqual(recorder.calls.filter(({ op }) => op === 'set').at(-1).entries[0].details, [ 'FL360 · 455 kts', @@ -197,11 +175,7 @@ test('selection lifecycle leaves installations to their own entry and retains AL const changed = makeCesiumEvent(); const viewer = { trackedEntity: null, trackedEntityChanged: changed }; const recorder = makeHostRecorder(); - const installation = { - gevTrackedId: 'installations:fort-test', - gevDisplayPosition: () => ({ x: 1, y: 2, z: 3 }), - gevLabelModel: { title: 'FORT TEST', details: ['AIRFIELD'], accent: '#5aa9ff' }, - }; + const installation = withEntityRecord({}, { trackedId: 'installations:fort-test', displayPosition: () => ({ x: 1, y: 2, z: 3 }), labelModel: { title: 'FORT TEST', details: ['AIRFIELD'], accent: '#5aa9ff' } }); globalThis.window = fakeWindow; _setTrackedOverlayHostForTest(recorder.host); try { @@ -219,11 +193,7 @@ test('selection lifecycle leaves installations to their own entry and retains AL assert.equal(recorder.calls.filter(({ op }) => op === 'set').length, setsBefore, 'installation selection cannot create a second overlay'); // ALPR cameras are static context too: a click publishes the same card. - const camera = { - gevTrackedId: 'alpr:42', - gevDisplayPosition: () => ({ x: 4, y: 5, z: 6 }), - gevLabelModel: { title: 'FLOCK SAFETY ALPR', details: ['CITY PD'], accent: '#ff66c4' }, - }; + const camera = withEntityRecord({}, { trackedId: 'alpr:42', displayPosition: () => ({ x: 4, y: 5, z: 6 }), labelModel: { title: 'FLOCK SAFETY ALPR', details: ['CITY PD'], accent: '#ff66c4' } }); fakeWindow.dispatchEvent(new CustomEvent('gev:entity-selected', { detail: { layerId: 'alpr-cameras', entity: camera }, })); @@ -271,7 +241,7 @@ test('trackedReadout cannot resurrect a dedicated canvas or render listener', as } }); -test('tracking layers write gevLabelModel and expose only their cached display positions', async () => { +test('tracking layers write the record\'s labelModel and expose only their cached display positions', async () => { const files = await Promise.all([ 'flights.js', 'militaryFlights.js', @@ -280,12 +250,16 @@ test('tracking layers write gevLabelModel and expose only their cached display p ].map(async (name) => [name, readLayerSource(new URL(`./${name}`, import.meta.url))])); const sources = Object.fromEntries(files); for (const [name, source] of files) { - assert.ok(source.includes('.gevLabelModel ='), `${name} writes the explicit model directly`); - assert.ok(source.includes('.gevDisplayPosition ='), `${name} exposes a display-position cache`); + assert.match(source, /entityRecord\([^)]*\)\.labelModel\s*=/, `${name} writes the explicit model into the entity record`); + assert.match(source, /entityRecord\([^)]*\)\.displayPosition\s*=/, `${name} exposes a display-position cache in the entity record`); + assert.doesNotMatch(source, /\.gev(LabelModel|DisplayPosition|VisualPosition|TrackedId|SelectionOrigin)\b/, `${name} hangs no tracked state on the entity`); } - assert.match(sources['flights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/); - assert.match(sources['militaryFlights.js'], /gevDisplayPosition\s*=\s*parts\.motion\._trackedDisplayCached/); - assert.ok(sources['satellites.js'].includes('gevDisplayPosition = _trackedDisplayCached')); + assert.match(sources['flights.js'], /entityRecord\([^)]*\)\.displayPosition\s*=\s*parts\.motion\._trackedDisplayCached/); + assert.match(sources['militaryFlights.js'], /entityRecord\([^)]*\)\.displayPosition\s*=\s*parts\.motion\._trackedDisplayCached/); + assert.match( + sources['satellites.js'], + /entityRecord\([^)]*\)\.displayPosition\s*=\s*_trackedDisplayCached/, + ); assert.equal(sources['flights.js'].includes('_trackedEntity.label.text'), false); assert.equal(sources['militaryFlights.js'].includes('_trackedEntity.label.text'), false); assert.equal(sources['satellites.js'].includes('_trackedEntity.label.text'), false); diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index c7343d5738..8fa6d416bf 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -23,6 +23,7 @@ import { alprLabelDetails, validAlprGroundHeight, } from './visuals.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; export function createAlprPresentation({ state, services, source }) { const { governorRequestRender } = services.render; @@ -236,11 +237,10 @@ export function createAlprPresentation({ state, services, source }) { entity.billboard.width = entity.billboard.height = selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE; - if (entity.gevLabelModel) { - entity.gevLabelModel.accent = color.toCssColorString(); - entity.gevLabelModel.leaderAnimationStartedAt = selected - ? selectionStartedAt - : 0; + const labelModel = readEntityRecord(entity)?.labelModel; + if (labelModel) { + labelModel.accent = color.toCssColorString(); + labelModel.leaderAnimationStartedAt = selected ? selectionStartedAt : 0; } } @@ -425,13 +425,14 @@ export function createAlprPresentation({ state, services, source }) { } } entity.gevAlprRecord = record; - entity.gevTrackedId = record.id; + entityRecord(entity).trackedId = record.id; // The mapped camera datum has no elevation; it is not the clamped marker's // visual anchor. Only the selected marker samples the rendered surface, // at most once per second, through Cesium's public height APIs. entity.gevAlprDisplayPosition ??= null; - entity.gevDisplayPosition = () => entity.gevAlprDisplayPosition; - entity.gevLabelModel = { + entityRecord(entity).displayPosition = () => + entity.gevAlprDisplayPosition; + entityRecord(entity).labelModel = { title: alprDisplayId(record), details: alprLabelDetails(record, source), accent: color.toCssColorString(), diff --git a/src/layers/awareness/subject.js b/src/layers/awareness/subject.js index 1baf54ec4f..f116b6b92a 100644 --- a/src/layers/awareness/subject.js +++ b/src/layers/awareness/subject.js @@ -10,6 +10,7 @@ import { SUBJECT_PRESENCE, AWARENESS_PAGE_SIZE, } from './policy.js'; +import { readEntityRecord } from '../../data/entityRecords.js'; // coverageLabel is machine-composed English from installations/controls.js // (pinned by src/data/militaryInstallations.test.mjs); translate the known @@ -192,7 +193,7 @@ export function createSubject({ state: layerState, services, parts, source }) { function currentTrackedFlightSubject() { const trackedKey = normalizeContextId( - layerState.viewer?.trackedEntity?.gevTrackedId, + readEntityRecord(layerState.viewer?.trackedEntity)?.trackedId, ); if (!trackedKey) return null; const subjects = [ @@ -260,16 +261,19 @@ export function createSubject({ state: layerState, services, parts, source }) { ) { if (!subject?.position) return null; if (subject.layerId === 'flights' || subject.layerId === 'military') { - const trackedPosition = - layerState.viewer?.trackedEntity?.gevDisplayPosition?.(); + const trackedPosition = readEntityRecord( + layerState.viewer?.trackedEntity, + )?.displayPosition?.(); if (trackedPosition) { return { position: Cesium.Cartesian3.clone(trackedPosition), // Only the follow camera's own contact proves presence this way; a // different tracked entity says nothing about this subject. presence: - String(layerState.viewer?.trackedEntity?.gevTrackedId || '') === - subjectKey(subject) + String( + readEntityRecord(layerState.viewer?.trackedEntity)?.trackedId || + '', + ) === subjectKey(subject) ? SUBJECT_PRESENCE.LIVE : SUBJECT_PRESENCE.UNCHECKED, }; diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index b66775f1ea..87a0a402b9 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -515,7 +515,7 @@ export function createMotion({ * * It reads `modelMatrix`, which `_updateTrackedModel` already wrote this frame — no * sampling, no `_modelDisplayPosition` call from postRender, and no new dead reckoning, - * so the follow-camera anti-jitter contract on `gevDisplayPosition` is untouched. + * so the follow-camera anti-jitter contract on the entity record's `displayPosition` is untouched. */ function _trackedVisualCached() { diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 59270892e5..064fce011f 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -25,6 +25,7 @@ import { CYAN_TRANSPARENT, } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; export function createTracking({ flightState, @@ -66,7 +67,7 @@ export function createTracking({ const info = flightState.records.data.get(icao24); if (!bb?.position || !info) return false; if (flightState._trackedEntity) - flightState._trackedEntity.gevSelectionOrigin = origin; + entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { layerId: 'flights', id: icao24, @@ -788,10 +789,8 @@ export function createTracking({ function _updateTrackedLabelModel(icao24) { if (!flightState._trackedEntity || icao24 !== flightState._trackedIcao) return; - flightState._trackedEntity.gevLabelModel = trackedLabelModelFromText( - _trackedLabelText(icao24), - '#39d0ff', - ); + entityRecord(flightState._trackedEntity).labelModel = + trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff'); refreshTrackedReadout(flightState._trackedEntity); // The readout and the context slot describe the same contact — refresh them // together so voice never narrates a fix the card has already replaced. @@ -1007,12 +1006,10 @@ export function createTracking({ }, false), }, }); - flightState._trackedEntity.gevSelectionOrigin = origin; - flightState._trackedEntity.gevTrackedId = `flights:${icao24}`; - flightState._trackedEntity.gevLabelModel = trackedLabelModelFromText( - _trackedLabelText(icao24), - '#39d0ff', - ); + entityRecord(flightState._trackedEntity).selectionOrigin = origin; + entityRecord(flightState._trackedEntity).trackedId = `flights:${icao24}`; + entityRecord(flightState._trackedEntity).labelModel = + trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff'); // 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 @@ -1035,12 +1032,12 @@ export function createTracking({ // Expose the camera's already-settled position to cross-module HUD consumers (the tracked-target // readout) so they draw at the SAME spot the camera framed, without recomputing the dead-reckon in // postRender (which would jitter the label against the now-stable plane). - flightState._trackedEntity.gevDisplayPosition = + entityRecord(flightState._trackedEntity).displayPosition = parts.motion._trackedDisplayCached; - // Separate accessor on purpose: `gevDisplayPosition` carries the follow-camera + // Separate accessor on purpose: the entity record's `displayPosition` carries the follow-camera // anti-jitter contract and must keep returning the cached DR position. Presentation - // that should weld to the AIRCRAFT YOU SEE reads `gevVisualPosition` instead. - flightState._trackedEntity.gevVisualPosition = + // that should weld to the AIRCRAFT YOU SEE reads the entity record's `visualPosition` instead. + entityRecord(flightState._trackedEntity).visualPosition = parts.motion._trackedVisualCached; refreshTrackedReadout(flightState._trackedEntity); flightState._viewer.camera.cancelFlight(); @@ -1155,8 +1152,8 @@ export function createTracking({ ) { _clearTracking(true, { origin: - flightState._viewer.trackedEntity?.gevSelectionOrigin || - 'programmatic', + readEntityRecord(flightState._viewer.trackedEntity) + ?.selectionOrigin || 'programmatic', }); } }); diff --git a/src/layers/installations/rendering.js b/src/layers/installations/rendering.js index 43489e3f2f..94c679b489 100644 --- a/src/layers/installations/rendering.js +++ b/src/layers/installations/rendering.js @@ -2,6 +2,7 @@ import { installationClassLabel, installationTitle } from './classLabel.js'; import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js'; +import { entityRecord } from '../../data/entityRecords.js'; export function createRendering({ state: layerState, @@ -221,7 +222,7 @@ export function createRendering({ if (retained.gevInstallationHeightM !== surfaceHeightM) { retained.gevInstallationHeightM = surfaceHeightM; retained.position = displayPosition; - retained.gevDisplayPosition = () => displayPosition; + entityRecord(retained).displayPosition = () => displayPosition; } if (retained.gevInstallationSelected !== selectedRecord) { retained.gevInstallationSelected = selectedRecord; @@ -269,9 +270,9 @@ export function createRendering({ } entity.gevInstallationHeightM = surfaceHeightM; entity.gevInstallationSelected = selectedRecord; - entity.gevTrackedId = `installations:${record.id}`; - entity.gevDisplayPosition = () => displayPosition; - entity.gevLabelModel = { + entityRecord(entity).trackedId = `installations:${record.id}`; + entityRecord(entity).displayPosition = () => displayPosition; + entityRecord(entity).labelModel = { title: installationTitle(record.name) || t('MAPPED INSTALLATION'), details: [ installationClassLabel(record.class), diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index de4215387c..2eb13b80a4 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -35,6 +35,7 @@ import { LOCAL_ADSB_UAT_RING_COLOR, } from './policy.js'; import { localAdsbStatus } from './status.js'; +import { entityRecord } from '../../data/entityRecords.js'; export { HEARD_BY_RECEIVER } from './policy.js'; export { localAdsbCardModel, localAdsbReceiverLine } from './card.js'; @@ -458,14 +459,14 @@ export function createLocalAdsbLayer({ ), }, }); - marker.entity.gevTrackedId = id; - marker.entity.gevDisplayPosition = () => marker.position; + entityRecord(marker.entity).trackedId = id; + entityRecord(marker.entity).displayPosition = () => marker.position; } refreshClass(marker); const uat = localAdsbIsUat(record); if (uat !== Boolean(marker.entity.point)) marker.entity.point = uat ? uatRing(marker) : undefined; - marker.entity.gevLabelModel = cardModel(marker, at); + entityRecord(marker.entity).labelModel = cardModel(marker, at); registerEntityContext(marker.entity, contextMetadata(id, marker)); if (newFix && id === selectedId) refreshTrail(); return id; @@ -481,7 +482,7 @@ export function createLocalAdsbLayer({ function refreshSelectedCard() { const marker = selectedId ? markers.get(selectedId) : null; if (!marker) return; - marker.entity.gevLabelModel = cardModel(marker, now()); + entityRecord(marker.entity).labelModel = cardModel(marker, now()); services.overlays?.refreshReadout?.(marker.entity); } @@ -567,7 +568,7 @@ export function createLocalAdsbLayer({ const reselect = id === selectedId && selectedTrail?.id === id; selectedId = id; enrichment.request(marker.record, { selected: true }); - marker.entity.gevLabelModel = cardModel(marker, now()); + entityRecord(marker.entity).labelModel = cardModel(marker, now()); selectEntityContext(marker.entity); if (!reselect) startTrail(marker); governorRequestRender('local-adsb-selection'); diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 263c212106..11596d6031 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -12,6 +12,7 @@ import { localAdsbReceiverLine, localAdsbStatus, } from './index.js'; +import { readEntityRecord } from '../../data/entityRecords.js'; function fakeReceiver(initial = {}) { const state = { @@ -252,8 +253,8 @@ test('local aircraft use their class silhouette and scale in magenta', async (t) ), ); assert.equal(entity.billboard.rotation.getValue(), 0); - assert.equal(entity.gevLabelModel.title, 'LOCAL1'); - assert.equal(typeof entity.gevDisplayPosition, 'function'); + assert.equal(readEntityRecord(entity)?.labelModel.title, 'LOCAL1'); + assert.equal(typeof readEntityRecord(entity)?.displayPosition, 'function'); const heli = sources[0].entities.getById('local-adsb:a0b702'); assert.equal(heli.billboard.image.getValue(), aircraftIcon('helicopter')); @@ -265,7 +266,10 @@ test('local aircraft use their class silhouette and scale in magenta', async (t) ), 'the helicopter keeps the local magenta', ); - assert.equal(heli.gevLabelModel.details[1], 'Helicopter · A7'); + assert.equal( + readEntityRecord(heli)?.labelModel.details[1], + 'Helicopter · A7', + ); // On the ground the silhouette shrinks like a grounded public flight. receiver.set({ @@ -479,14 +483,14 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o await new Promise((resolve) => setTimeout(resolve, 400)); assert.deepEqual([...queries].sort(), ['route:EVC145', 'type:a0b702']); const entity = sources[0].entities.getById('local-adsb:a0b702'); - assert.deepEqual(entity.gevLabelModel.details.slice(0, 4), [ + assert.deepEqual(readEntityRecord(entity)?.labelModel.details.slice(0, 4), [ 'ICAO A0B702 · EVC145', 'Helicopter · A7', 'Air Evac · Bell 407', 'AUS → SAT', ]); assert.equal( - entity.gevLabelModel.details.at(-1), + readEntityRecord(entity)?.labelModel.details.at(-1), 'Heard by your receiver · 1090 MHz · browser SDR', ); layer.selectAircraft('a0b702'); @@ -760,7 +764,7 @@ test('feed records merge with browser SDR records by ICAO and UAT-only aircraft ); assert.equal(shared.point, undefined, 'heard on 1090 too: no UAT ring'); assert.equal( - shared.gevLabelModel.details.at(-1), + readEntityRecord(shared)?.labelModel.details.at(-1), 'Heard by your receiver · 1090 MHz + 978 MHz UAT · browser SDR + decoder feed', ); assert.ok(uat.point, 'a UAT-only aircraft carries the ring'); @@ -776,7 +780,7 @@ test('feed records merge with browser SDR records by ICAO and UAT-only aircraft 'same magenta marker family', ); assert.equal( - uat.gevLabelModel.details.at(-1), + readEntityRecord(uat)?.labelModel.details.at(-1), 'Heard by your receiver · 978 MHz UAT · decoder feed', ); const stats = layer.getStats(); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 27489400bc..06dce15444 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -370,7 +370,7 @@ export function createMotion({ * model is actually rendering with when the model owns the visual, otherwise the cached * dead-reckoned position. Mirror of flights.js; see that copy for the full rationale. * Reads the modelMatrix the tracked-model update already wrote this frame: no sampling, - * no `_modelDisplayPosition` from postRender, and `gevDisplayPosition` keeps its + * no `_modelDisplayPosition` from postRender, and the entity record's `displayPosition` keeps its * follow-camera anti-jitter contract untouched. */ diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 5ad60adf93..16252caca1 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -26,6 +26,7 @@ import { TRACKED_ICON_COLOR, } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; export function createTracking({ flightState, @@ -65,7 +66,7 @@ export function createTracking({ const info = flightState.records.data.get(icao24); if (!bb?.position || !info) return false; if (flightState._trackedEntity) - flightState._trackedEntity.gevSelectionOrigin = origin; + entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { layerId: 'military', id: icao24, @@ -252,10 +253,11 @@ export function createTracking({ function _updateTrackedLabelModel(icao24) { if (!flightState._trackedEntity || icao24 !== flightState._trackedIcao) return; - flightState._trackedEntity.gevLabelModel = trackedLabelModelFromText( - _buildTrackedLabel(flightState.records.data.get(icao24), icao24), - '#ffd166', - ); + entityRecord(flightState._trackedEntity).labelModel = + trackedLabelModelFromText( + _buildTrackedLabel(flightState.records.data.get(icao24), icao24), + '#ffd166', + ); refreshTrackedReadout(flightState._trackedEntity); // The readout and the context slot describe the same contact — refresh them // together so voice never narrates a fix the card has already replaced. @@ -966,12 +968,10 @@ export function createTracking({ }, false), }, }); - flightState._trackedEntity.gevSelectionOrigin = origin; - flightState._trackedEntity.gevTrackedId = `military:${icao24}`; - flightState._trackedEntity.gevLabelModel = trackedLabelModelFromText( - _buildTrackedLabel(info, icao24), - '#ffd166', - ); + entityRecord(flightState._trackedEntity).selectionOrigin = origin; + entityRecord(flightState._trackedEntity).trackedId = `military:${icao24}`; + 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 @@ -990,12 +990,12 @@ export function createTracking({ // 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). - flightState._trackedEntity.gevDisplayPosition = + entityRecord(flightState._trackedEntity).displayPosition = parts.motion._trackedDisplayCached; - // Separate accessor on purpose (mirror of flights.js): `gevDisplayPosition` keeps the + // Separate accessor on purpose (mirror of flights.js): the entity record's `displayPosition` keeps the // follow-camera anti-jitter contract; presentation that must weld to the aircraft you - // can see reads `gevVisualPosition`. - flightState._trackedEntity.gevVisualPosition = + // can see reads the entity record's `visualPosition`. + entityRecord(flightState._trackedEntity).visualPosition = parts.motion._trackedVisualCached; refreshTrackedReadout(flightState._trackedEntity); flightState._viewer.camera.cancelFlight(); @@ -1060,8 +1060,8 @@ export function createTracking({ ) { _clearTracking(true, { origin: - flightState._viewer.trackedEntity?.gevSelectionOrigin || - 'programmatic', + readEntityRecord(flightState._viewer.trackedEntity) + ?.selectionOrigin || 'programmatic', }); } }); diff --git a/src/layers/satellites/interaction.js b/src/layers/satellites/interaction.js index 7ef8816c6a..9715d9166c 100644 --- a/src/layers/satellites/interaction.js +++ b/src/layers/satellites/interaction.js @@ -1,5 +1,6 @@ import * as Cesium from 'cesium'; import { isPointerFree } from '../../data/inputOwnership.js'; +import { readEntityRecord } from '../../data/entityRecords.js'; export function createInteraction({ state: layerState, @@ -36,8 +37,8 @@ export function createInteraction({ ) { parts.tracking._clearTracking(true, { origin: - layerState._viewer.trackedEntity?.gevSelectionOrigin || - 'programmatic', + readEntityRecord(layerState._viewer.trackedEntity) + ?.selectionOrigin || 'programmatic', }); } }); diff --git a/src/layers/satellites/tracking.js b/src/layers/satellites/tracking.js index 2b2624ff7e..c39ed0aac9 100644 --- a/src/layers/satellites/tracking.js +++ b/src/layers/satellites/tracking.js @@ -9,6 +9,7 @@ import { TRACK_VIEW_FROM_HIGH_SCALE, TRACK_VIEW_FROM_LEO, } from './policy.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; export function createTracking({ state: layerState, services, parts, source }) { const { clearFocusTarget, publishFocusTargetFromCachedPosition } = @@ -384,7 +385,7 @@ export function createTracking({ state: layerState, services, parts, source }) { : t('DOCKED · {name}', { name: companions[0] }), ); } - const current = layerState._trackedEntity.gevLabelModel; + const current = readEntityRecord(layerState._trackedEntity)?.labelModel; // Compare the WHOLE detail array: comparing only `details[0]` swallowed any // change confined to the companions line, so the card would never republish. const unchanged = @@ -392,7 +393,7 @@ export function createTracking({ state: layerState, services, parts, source }) { current?.details?.length === details.length && details.every((line, index) => current.details[index] === line); if (unchanged) return; - layerState._trackedEntity.gevLabelModel = { + entityRecord(layerState._trackedEntity).labelModel = { title, details, accent: '#ffd84d', @@ -456,9 +457,10 @@ export function createTracking({ state: layerState, services, parts, source }) { disableDepthTestDistance: Number.POSITIVE_INFINITY, }, }); - layerState._trackedEntity.gevSelectionOrigin = origin; - layerState._trackedEntity.gevTrackedId = `satellites:${noradId}`; - layerState._trackedEntity.gevDisplayPosition = _trackedDisplayCached; + entityRecord(layerState._trackedEntity).selectionOrigin = origin; + entityRecord(layerState._trackedEntity).trackedId = `satellites:${noradId}`; + entityRecord(layerState._trackedEntity).displayPosition = + _trackedDisplayCached; _updateTrackedSatelliteLabelModel(initialPos?.altitude ?? null); _emitAwarenessEvent('gev:awareness-subject-selected', { diff --git a/src/overlays/worldOverlayAllocation.worker.mjs b/src/overlays/worldOverlayAllocation.worker.mjs index e2a4c6240d..30ee4d7f11 100644 --- a/src/overlays/worldOverlayAllocation.worker.mjs +++ b/src/overlays/worldOverlayAllocation.worker.mjs @@ -84,6 +84,7 @@ import { setDetectionTuning, setMode as setDetectionMode, } from '../data/detection.js'; +import { withEntityRecord } from '../data/entityRecords.js'; /** * @module worldOverlayAllocation.worker @@ -650,16 +651,19 @@ function buildPhase3TrackedWorkload(count) { ({ selected }) => selected, ); const selected = vesselRegistration.entries.splice(selectedIndex, 1)[0]; - const trackedEntity = { - gevTrackedId: 'flights:allocation-probe', - gevDisplayPosition: selected.position, - gevLabelModel: { - // i18n-ignore: benchmark fixture - title: 'ALLOC01', - details: ['FL350 · 451 kts', 'TEST AIR · A320'], - accent: '#39d0ff', + const trackedEntity = withEntityRecord( + {}, + { + trackedId: 'flights:allocation-probe', + displayPosition: selected.position, + labelModel: { + // i18n-ignore: benchmark fixture + title: 'ALLOC01', + details: ['FL350 · 451 kts', 'TEST AIR · A320'], + accent: '#39d0ff', + }, }, - }; + ); const tracked = createTrackedOverlayEntry(trackedEntity); tracked.horizonCull = false; vesselRegistration.options = { diff --git a/src/ui/cameraOrientationControls.js b/src/ui/cameraOrientationControls.js index 8b7857784f..21a40b867d 100644 --- a/src/ui/cameraOrientationControls.js +++ b/src/ui/cameraOrientationControls.js @@ -1,13 +1,14 @@ import * as Cesium from 'cesium'; import { isPickedWorldPosition } from '../data/scenePick.js'; import { t } from '../i18n/index.js'; +import { readEntityRecord } from '../data/entityRecords.js'; function trackedTarget(viewer) { const entity = viewer.trackedEntity; // Read the visual's sample first; sampling a flight CallbackProperty twice // can advance dead reckoning ahead of the displayed aircraft. return ( - entity?.gevDisplayPosition?.() || + readEntityRecord(entity)?.displayPosition?.() || entity?.position?.getValue(viewer.clock?.currentTime) ); } diff --git a/src/ui/cameraOrientationControls.test.mjs b/src/ui/cameraOrientationControls.test.mjs index 68ba5ac496..6a5820a8fc 100644 --- a/src/ui/cameraOrientationControls.test.mjs +++ b/src/ui/cameraOrientationControls.test.mjs @@ -12,6 +12,7 @@ import { toggleCameraTilt, } from './cameraOrientationControls.js'; import { NavigationController } from './navigationController.js'; +import { entityRecord } from '../data/entityRecords.js'; function createViewer({ cameraPosition, target, pickPosition = null } = {}) { const calls = []; @@ -523,7 +524,7 @@ for (const [label, altitude, range] of [ position: new Cesium.CallbackPositionProperty(() => target, false), trackingReferenceFrame: Cesium.TrackingReferenceFrame.ENU, }); - entity.gevDisplayPosition = () => target; + entityRecord(entity).displayPosition = () => target; viewer.trackedEntity = entity; const follow = new Cesium.EntityView(entity, viewer.scene); follow.update(viewer.clock.currentTime); diff --git a/src/ui/cockpitController.test.mjs b/src/ui/cockpitController.test.mjs index 2162005965..6a4c0d13ac 100644 --- a/src/ui/cockpitController.test.mjs +++ b/src/ui/cockpitController.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { CockpitViewController } from './cockpitController.js'; +import { withEntityRecord } from '../data/entityRecords.js'; function environment() { const original = { document: globalThis.document, window: globalThis.window }; @@ -95,9 +96,15 @@ test('aircraft identity is read from the supplied layer instances', () => { militaryFlightsLayer: { getTrackedInfo: () => military }, }, }); - env.viewer.trackedEntity = { gevTrackedId: 'military:def456' }; + env.viewer.trackedEntity = withEntityRecord( + {}, + { trackedId: 'military:def456' }, + ); assert.deepEqual(owner.readAircraftInfo(), military); - env.viewer.trackedEntity = { gevTrackedId: 'flights:abc123' }; + env.viewer.trackedEntity = withEntityRecord( + {}, + { trackedId: 'flights:abc123' }, + ); assert.deepEqual(owner.readAircraftInfo(), civilian); owner.dispose(); } finally { diff --git a/src/ui/cockpitCoordinator.js b/src/ui/cockpitCoordinator.js index b71889b4ca..3c61688009 100644 --- a/src/ui/cockpitCoordinator.js +++ b/src/ui/cockpitCoordinator.js @@ -4,6 +4,7 @@ import { cockpitEntryAllowed } from '../contextModePolicy.js'; import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js'; import { enterCockpitWithTracking } from '../cockpitTracking.js'; import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js'; +import { readEntityRecord } from '../data/entityRecords.js'; /** Own Cockpit entry/rollback, readouts and the single Display portal. */ export class CockpitCoordinator { @@ -90,9 +91,9 @@ export class CockpitCoordinator { onEntered: () => this.enterPanels(), onExited: () => this.exitPanels(), restoreTrackingFrame: (entity) => { - const [layerId, ...idParts] = String(entity?.gevTrackedId || '').split( - ':', - ); + const [layerId, ...idParts] = String( + readEntityRecord(entity)?.trackedId || '', + ).split(':'); const trackedId = idParts.join(':'); if (!trackedId) return false; if (layerId === 'flights') diff --git a/src/ui/cockpitTrackingController.js b/src/ui/cockpitTrackingController.js index f308b0d2f8..f7f4a7e6eb 100644 --- a/src/ui/cockpitTrackingController.js +++ b/src/ui/cockpitTrackingController.js @@ -5,6 +5,7 @@ import { normalizeHeading, resolveTrackedAircraftInfo, } from '../cockpitMath.js'; +import { readEntityRecord } from '../data/entityRecords.js'; export function readAircraftInfo() { // In cockpit mode the controller takes the entity off `viewer.trackedEntity` @@ -13,7 +14,7 @@ export function readAircraftInfo() { return resolveTrackedAircraftInfo({ civilian: this.services.flightsLayer.getTrackedInfo?.() || null, military: this.services.militaryFlightsLayer.getTrackedInfo?.() || null, - trackedId: trackedEntity?.gevTrackedId || '', + trackedId: readEntityRecord(trackedEntity)?.trackedId || '', }); } diff --git a/src/ui/mobileShell.test.mjs b/src/ui/mobileShell.test.mjs index a391a6ba73..910993f120 100644 --- a/src/ui/mobileShell.test.mjs +++ b/src/ui/mobileShell.test.mjs @@ -10,6 +10,7 @@ import { nextSheet, sheetForPanelId, } from './mobileShell.js'; +import { withEntityRecord } from '../data/entityRecords.js'; function element(tag, document) { const node = new EventTarget(); @@ -824,7 +825,7 @@ test('the tab-open callback reports only a successful manual opening', () => { test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => { const calls = []; const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' }; - const viewer = { trackedEntity: { gevTrackedId: 'flights:abc123' } }; + const viewer = { trackedEntity: withEntityRecord({}, { trackedId: 'flights:abc123' }) }; const entity = viewer.trackedEntity; const enabled = new Set(['flights', 'weather']); const controls = new ContextControls({ diff --git a/src/ui/shareFollow.js b/src/ui/shareFollow.js index ba5851da62..e9380c17c0 100644 --- a/src/ui/shareFollow.js +++ b/src/ui/shareFollow.js @@ -5,6 +5,7 @@ import { followOffsetFromEnu, followOffsetToEnu, } from '../share/follow.js'; +import { readEntityRecord } from '../data/entityRecords.js'; /** * The bridge between the camera following an entity and a share link's thing @@ -39,7 +40,7 @@ export function readShareFollowSubject({ viewer, nowMs = Date.now() }) { const cameraPosition = viewer?.camera?.positionWC; if (!cameraPosition) return null; const tracked = viewer.trackedEntity; - const trackedId = String(tracked?.gevTrackedId || ''); + const trackedId = String(readEntityRecord(tracked)?.trackedId || ''); const separator = trackedId.indexOf(':'); if (separator <= 0) return null; const kind = KIND_BY_LAYER.get(trackedId.slice(0, separator)); diff --git a/src/ui/shareLinks.test.mjs b/src/ui/shareLinks.test.mjs index d7b747d660..7347ce1cf1 100644 --- a/src/ui/shareLinks.test.mjs +++ b/src/ui/shareLinks.test.mjs @@ -18,6 +18,7 @@ import { followCameraFor, followOffsetToEnu, } from '../share/viewCodec.js'; +import { entityRecord, withEntityRecord } from '../data/entityRecords.js'; const NOW_MS = Date.now(); const FIX = { lat: 37.6213, lon: -122.379, alt: 3200 }; @@ -278,10 +279,7 @@ test('a thing view turns its layer on, follows by id and frames the shared offse this.position = Cesium.Cartesian3.clone(offset); }, }); - entity = { - gevTrackedId: 'flights:a1b2c3', - gevDisplayPosition: () => target, - }; + entity = withEntityRecord({}, { trackedId: 'flights:a1b2c3', displayPosition: () => target }); const parsed = page.manager._parseShareCode(aircraftCode()); assert.deepEqual(parsed.layerState.enabledLayerIds, ['flights']); @@ -452,10 +450,7 @@ test('the followed entity is read in the share format, and its offset round-trip const viewer = { camera: { positionWC: cameraPosition }, clock: { currentTime: Cesium.JulianDate.now() }, - trackedEntity: { - gevTrackedId: 'military:ae1234', - gevDisplayPosition: () => target, - }, + trackedEntity: withEntityRecord({}, { trackedId: 'military:ae1234', displayPosition: () => target }), }; const subject = readShareFollowSubject({ viewer, nowMs: NOW_MS }); assert.equal(subject.kind, 'military_aircraft'); @@ -464,7 +459,7 @@ test('the followed entity is read in the share format, and its offset round-trip assert.ok(Math.abs(subject.lastKnown.lat - FIX.lat) < 1e-9); assert.ok(Math.abs(subject.lastKnown.alt - FIX.alt) < 1e-3); // A followed entity the share format has no kind for is not a thing view. - viewer.trackedEntity.gevTrackedId = 'local-adsb:abc'; + entityRecord(viewer.trackedEntity).trackedId = 'local-adsb:abc'; assert.equal(readShareFollowSubject({ viewer }), null); // Nor is a camera that follows nothing (a selected vessel is not followed). viewer.trackedEntity = undefined; @@ -475,7 +470,7 @@ test('a shared offset on the far side swings round, never jumping through the en const target = Cesium.Cartesian3.fromDegrees(FIX.lon, FIX.lat, FIX.alt); const listeners = []; const looks = []; - const entity = { gevDisplayPosition: () => target }; + const entity = withEntityRecord({}, { displayPosition: () => target }); const viewer = { clock: { currentTime: Cesium.JulianDate.now() }, scene: { diff --git a/src/ui/shareRestoration.js b/src/ui/shareRestoration.js index 12f09c18b8..966318f846 100644 --- a/src/ui/shareRestoration.js +++ b/src/ui/shareRestoration.js @@ -4,6 +4,7 @@ import { canPresentDeferredStatusNotice } from '../loadingFeedback.js'; import { t, msg, formatDate } from '../i18n/index.js'; import { SHARE_VIEW_ENTITY_KINDS } from '../share/follow.js'; import { UiLifetime } from './uiLifetime.js'; +import { readEntityRecord } from '../data/entityRecords.js'; /** How long a shared vessel may take to appear in the vessel feed. */ export const SHARED_VESSEL_WAIT_MS = 120_000; @@ -424,7 +425,7 @@ export class ShareRestoration { // a long link's follow keeps the app's own framing. if ( !view?.lastKnown || - String(entity?.gevTrackedId || '') !== + String(readEntityRecord(entity)?.trackedId || '') !== `${result.layerId}:${result.targetId}` ) return; diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index f11abc5aef..96a24edc68 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -23,6 +23,7 @@ import { MAP_STACKS } from '../mapStackController.js'; import { GEV_REALTIME_TOOLS } from '../../server/providers/openai/tools.js'; import { presentResult } from './resultDisplay.js'; import { attachVoiceResult } from './speech.js'; +import { withEntityRecord } from '../data/entityRecords.js'; test('every live basemap is reachable by its own id — no enum value without a voice alias', () => { // B1 regression: a stack added to MAP_STACKS (and the set_map_stack enum) @@ -474,7 +475,7 @@ test('voice Stop Tracking reports exact layers whose active or durable clear fai getAll: () => [], }; const viewer = { - trackedEntity: { gevTrackedId: 'flights:active' }, + trackedEntity: withEntityRecord({}, { trackedId: 'flights:active' }), scene: { canvas: { addEventListener() {}, removeEventListener() {} }, preRender: { addEventListener() {} }, From 393a14513768cc59ac22fbd3aab5b4d124d28995 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 08:24:33 -0800 Subject: [PATCH 002/470] Keep ALPR marker state in a layer store instead of on Cesium entities The ALPR layer's private per-entity fields (record, clamp, canvas and display anchors, wedge, native appearance, pick position, shown, surface check) move from gevAlpr* expandos into alprMarkers, a store made by the new createEntityStore(). The shared entity records are built on the same factory. --- docs/CURRENT-STATE.md | 3 +- scripts/package-boundaries.json | 3 ++ src/data/alprCameras.test.mjs | 9 ++--- src/data/entityRecords.js | 37 ++++++++++++++----- src/data/entityRecords.test.mjs | 19 +++++++++- src/layers/alpr/markerState.js | 14 ++++++++ src/layers/alpr/overlay.js | 60 ++++++++++++++++--------------- src/layers/alpr/overlay.test.mjs | 13 ++++--- src/layers/alpr/presentation.js | 61 ++++++++++++++++++-------------- 9 files changed, 144 insertions(+), 75 deletions(-) create mode 100644 src/layers/alpr/markerState.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9f17cc3838..02acb54036 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -3638,7 +3638,8 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > and mapped installations write explicit `labelModel` objects and > `displayPosition` getters, backed by their layer-owned frame/display cache, > into the app's entity records (`src/data/entityRecords.js`), never onto the -> Cesium entity. +> Cesium entity. A layer's private per-entity state goes in its own store from +> `createEntityStore()` (ALPR markers: `src/layers/alpr/markerState.js`). > Selected AIS vessels continue using the vessel source's protected selected > card, so they do not create a duplicate tracked readout. The host registers > the active readout in the protected tracked lane with a zero ambient quota; diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 8e75167158..5fbd466104 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1957,6 +1957,7 @@ "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", "src/layers/alpr/records.js", @@ -2442,6 +2443,7 @@ "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -3347,6 +3349,7 @@ "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", "src/layers/alpr/overlay.js", + "src/layers/alpr/markerState.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 977ae8e1f4..a09dd6887a 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -32,6 +32,7 @@ import { normalizeAlprNode, } from './alprCameras.js'; import { readEntityRecord } from './entityRecords.js'; +import { alprMarkers } from '../layers/alpr/markerState.js'; test('normalizeAlprNode: maps a full OSM node to a plain record', () => { const record = normalizeAlprNode({ @@ -1445,12 +1446,12 @@ test('map-source changes reposition all ALPR entities and saved native appearanc await layer.update(); const entities = [...h.source.entities.values]; const saved = entities[1]; - saved.gevAlprNativeAppearance = { + alprMarkers.write(saved).nativeAppearance = { position: saved.position, heightReference: saved.billboard.heightReference, }; saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190); - saved.gevAlprPickPosition = saved.position; + alprMarkers.write(saved).pickPosition = saved.position; for (const next of [150, 120, null, 180]) { floor = next; // Includes a provider switch with the same globe.show value. @@ -1471,10 +1472,10 @@ test('map-source changes reposition all ALPR entities and saved native appearanc ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE, ); - assert.equal(entity.gevAlprCanvasPosition, null); + assert.equal(alprMarkers.read(entity)?.canvasPosition, null); } assert.equal( - saved.gevAlprNativeAppearance, + alprMarkers.read(saved)?.nativeAppearance, null, 'saved appearance restores at the new floor', ); diff --git a/src/data/entityRecords.js b/src/data/entityRecords.js index f0ac03c8e4..6de9c409e4 100644 --- a/src/data/entityRecords.js +++ b/src/data/entityRecords.js @@ -12,9 +12,34 @@ * - `visualPosition()`: where a 3D model is actually drawn, for the tracked card. * - `labelModel`: the tracked card's `{ title, details, accent, … }`. * - `selectionOrigin`: what started the selection (`'user'`, …). + * + * A layer's private per-entity state goes in its own store ({@link createEntityStore}). */ -const records = new WeakMap(); +/** + * A store of one record per renderer object, held by the app and dropped with the object. + * @returns {{ write: (entity: Object) => Object, read: (entity: unknown) => Object|null }} + * `write` makes the record empty on first use; `read` gives null when there is none. + */ +export function createEntityStore() { + const records = new WeakMap(); + return { + write(entity) { + let record = records.get(entity); + if (!record) { + record = {}; + records.set(entity, record); + } + return record; + }, + read(entity) { + if (!entity || typeof entity !== 'object') return null; + return records.get(entity) ?? null; + }, + }; +} + +const shared = createEntityStore(); /** * The record for `entity`, made empty on first use. For layers writing their own state. @@ -22,12 +47,7 @@ const records = new WeakMap(); * @returns {Object} */ export function entityRecord(entity) { - let record = records.get(entity); - if (!record) { - record = {}; - records.set(entity, record); - } - return record; + return shared.write(entity); } /** @@ -36,8 +56,7 @@ export function entityRecord(entity) { * @returns {Object|null} */ export function readEntityRecord(entity) { - if (!entity || typeof entity !== 'object') return null; - return records.get(entity) ?? null; + return shared.read(entity); } /** diff --git a/src/data/entityRecords.test.mjs b/src/data/entityRecords.test.mjs index c59b829ace..e6259a99d9 100644 --- a/src/data/entityRecords.test.mjs +++ b/src/data/entityRecords.test.mjs @@ -1,6 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { entityRecord, readEntityRecord, withEntityRecord } from './entityRecords.js'; +import { + createEntityStore, + entityRecord, + readEntityRecord, + withEntityRecord, +} from './entityRecords.js'; test('an entity record is made on first write and read back by the same entity', () => { const entity = {}; @@ -29,3 +34,15 @@ test('withEntityRecord writes fields into the record and returns the entity', () assert.equal(readEntityRecord(entity)?.trackedId, 'alpr:42'); assert.equal(Object.hasOwn(entity, 'trackedId'), false); }); + +test('a layer store is separate from the shared records and from other stores', () => { + const entity = {}; + const a = createEntityStore(); + const b = createEntityStore(); + a.write(entity).canvasPosition = 1; + assert.equal(a.read(entity)?.canvasPosition, 1); + assert.equal(b.read(entity), null); + assert.equal(readEntityRecord(entity), null); + assert.equal(a.read(null), null); + assert.deepEqual(Object.keys(entity), []); +}); diff --git a/src/layers/alpr/markerState.js b/src/layers/alpr/markerState.js new file mode 100644 index 0000000000..496d348ebe --- /dev/null +++ b/src/layers/alpr/markerState.js @@ -0,0 +1,14 @@ +/** + * @module alpr/markerState + * @description The ALPR layer's own per-marker state, held in the app rather than on the + * Cesium entities it draws: + * - `record`: the camera record the marker shows. + * - `clamped`: whether the marker sits on the surface rather than at its height. + * - `canvasPosition`, `displayPosition`: the canvas anchor and the position the card reads. + * - `wedge`: the direction wedge's positions. + * - `nativeAppearance`, `pickPosition`: the native look saved while the canvas draws it. + * - `shown`, `surfaceCheckedFor`: the last visibility applied and the anchor last checked. + */ +import { createEntityStore } from '../../data/entityRecords.js'; + +export const alprMarkers = createEntityStore(); diff --git a/src/layers/alpr/overlay.js b/src/layers/alpr/overlay.js index 202a98ed7a..ea62468c96 100644 --- a/src/layers/alpr/overlay.js +++ b/src/layers/alpr/overlay.js @@ -18,6 +18,7 @@ import { paintDirectionWedge, validAlprGroundHeight, } from './visuals.js'; +import { alprMarkers } from './markerState.js'; /** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */ export function createAlprOverlay({ @@ -48,29 +49,30 @@ export function createAlprOverlay({ function canvasOwned(entity, owned) { const visible = !owned; const billboard = entity.billboard; + const marker = alprMarkers.write(entity); // Keep a faint native pick target under the canvas badge so sibling layer // handlers recognize ALPR ownership instead of treating the click as empty. - if (!visible && !entity.gevAlprNativeAppearance) { - entity.gevAlprNativeAppearance = { + if (!visible && !marker.nativeAppearance) { + marker.nativeAppearance = { position: entity.position, heightReference: billboard.heightReference, scaleByDistance: billboard.scaleByDistance, color: billboard.color, }; - entity.position = entity.gevAlprCanvasPosition; - entity.gevAlprPickPosition = entity.position; + entity.position = marker.canvasPosition; + marker.pickPosition = entity.position; billboard.heightReference = Cesium.HeightReference.NONE; billboard.scaleByDistance = undefined; billboard.color = Cesium.Color.WHITE.withAlpha(0.01); - } else if (visible && entity.gevAlprNativeAppearance) { - const saved = entity.gevAlprNativeAppearance; - if (entity.position === entity.gevAlprPickPosition) + } else if (visible && marker.nativeAppearance) { + const saved = marker.nativeAppearance; + if (entity.position === marker.pickPosition) entity.position = saved.position; billboard.heightReference = saved.heightReference; billboard.scaleByDistance = saved.scaleByDistance; billboard.color = saved.color; - entity.gevAlprNativeAppearance = null; - entity.gevAlprPickPosition = null; + marker.nativeAppearance = null; + marker.pickPosition = null; } } @@ -78,8 +80,9 @@ export function createAlprOverlay({ // and raises definitionChanged, which paint used to do for every overlay // camera on every frame. function setShown(entity, visible) { - if (entity.gevAlprShown === visible) return; - entity.gevAlprShown = visible; + const marker = alprMarkers.write(entity); + if (marker.shown === visible) return; + marker.shown = visible; entity.billboard.show = visible; if (entity.polyline) entity.polyline.show = visible; if (entity.polygon) entity.polygon.show = visible; @@ -87,9 +90,10 @@ export function createAlprOverlay({ function resetAnchors() { for (const entity of state.dataSource.entities.values) { - entity.gevAlprCanvasPosition = null; - entity.gevAlprWedge = null; - entity.gevAlprDisplayPosition = null; + const marker = alprMarkers.write(entity); + marker.canvasPosition = null; + marker.wedge = null; + marker.displayPosition = null; nativeVisible(entity, true); } state.lastAnchorSampleAt = 0; @@ -98,7 +102,8 @@ export function createAlprOverlay({ } function anchorFor(record, entity, budget) { - if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition; + const cached = alprMarkers.read(entity)?.canvasPosition; + if (cached) return cached; const scene = state.viewer.scene; const location = Cesium.Cartographic.fromDegrees( record.longitude, @@ -126,7 +131,7 @@ export function createAlprOverlay({ height = scene.globe.getHeight?.(location); if (!validAlprGroundHeight(height)) return null; setAnchor(record, entity, height); - return entity.gevAlprCanvasPosition; + return alprMarkers.read(entity)?.canvasPosition; } function floorHeightAt(latitude, longitude) { @@ -135,16 +140,13 @@ export function createAlprOverlay({ } function setAnchor(record, entity, height) { - entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees( + const marker = alprMarkers.write(entity); + marker.canvasPosition = Cesium.Cartesian3.fromDegrees( record.longitude, record.latitude, height, ); - entity.gevAlprWedge = directionWedgePositions( - record, - height, - floorHeightAt, - ); + marker.wedge = directionWedgePositions(record, height, floorHeightAt); } /** Whether the visible photoreal tiles (or globe) have finished streaming. */ @@ -192,8 +194,9 @@ export function createAlprOverlay({ let pending = false; for (const record of records) { const entity = state.dataSource.entities.getById(record.id); - const anchor = entity?.gevAlprCanvasPosition; - if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue; + const marker = alprMarkers.read(entity); + const anchor = marker?.canvasPosition; + if (!anchor || marker.surfaceCheckedFor === anchor) continue; if (!still || !surfaceSettled(scene) || budget.samples <= 0) { pending = true; continue; @@ -220,9 +223,10 @@ export function createAlprOverlay({ sample <= floor + SURFACE_ABOVE_FLOOR_M)); if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1) setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M); - entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition; + // setAnchor rewrote the same record, so this is the new anchor. + marker.surfaceCheckedFor = marker.canvasPosition; if (entity.id === state.selectedId) - entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition; + marker.displayPosition = marker.canvasPosition; } return pending; } @@ -272,7 +276,7 @@ export function createAlprOverlay({ setShown(entity, false); continue; } - const wedge = entity.gevAlprWedge; + const wedge = alprMarkers.read(entity)?.wedge; if (wedge) { const left = Cesium.SceneTransforms.worldToWindowCoordinates( scene, @@ -309,7 +313,7 @@ export function createAlprOverlay({ Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor), ), }); - if (selected) entity.gevAlprDisplayPosition = anchor; + if (selected) alprMarkers.write(entity).displayPosition = anchor; } // Paint all glyphs after the wedges so one camera's cone cannot wash out another. for (const { record, origin, selected, image, alpha, scale } of painted) { diff --git a/src/layers/alpr/overlay.test.mjs b/src/layers/alpr/overlay.test.mjs index c9aa8e5f57..a84510aacd 100644 --- a/src/layers/alpr/overlay.test.mjs +++ b/src/layers/alpr/overlay.test.mjs @@ -8,6 +8,7 @@ import { alprLabelDetails, markerScale, } from './visuals.js'; +import { alprMarkers } from './markerState.js'; function harness(t, count = 2, { floor = null } = {}) { const previousImage = globalThis.Image; @@ -144,7 +145,9 @@ test('the overlay bounds its cohort and promotes selection while leaving farther h.state.selectedId = 'camera:69'; h.overlay.sync(h.records); h.paint(); - const hidden = h.entities.values.filter((e) => e.gevAlprNativeAppearance); + const hidden = h.entities.values.filter( + (e) => alprMarkers.read(e)?.nativeAppearance, + ); assert.equal(hidden.length, 64); assert.ok(hidden.some((e) => e.id === 'camera:69')); assert.equal( @@ -161,16 +164,16 @@ test('surface changes invalidate cached anchors, and disable/disposal release pa h.overlay.sync(h.records); h.paint(); const entity = h.entities.getById('camera:0'); - const first = entity.gevAlprCanvasPosition; + const first = alprMarkers.read(entity)?.canvasPosition; h.paint(); assert.equal( - entity.gevAlprCanvasPosition, + alprMarkers.read(entity)?.canvasPosition, first, 'stable anchor across frames', ); h.state.viewer.scene.globe.show = false; h.mapChanged(); - assert.equal(entity.gevAlprCanvasPosition, null); + assert.equal(alprMarkers.read(entity)?.canvasPosition, null); h.state.enabled = false; h.overlay.clear(); assert.equal(h.active, false); @@ -260,7 +263,7 @@ test('a still view replaces floor anchors with the rendered surface, within the h.paint(); const height = (id) => Cesium.Cartographic.fromCartesian( - h.entities.getById(id).gevAlprCanvasPosition, + alprMarkers.read(h.entities.getById(id))?.canvasPosition, ).height; assert.equal( samples, diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index 8fa6d416bf..9df584a7a3 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -24,6 +24,7 @@ import { validAlprGroundHeight, } from './visuals.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; +import { alprMarkers } from './markerState.js'; export function createAlprPresentation({ state, services, source }) { const { governorRequestRender } = services.render; @@ -171,7 +172,7 @@ export function createAlprPresentation({ state, services, source }) { const heightReference = clamped ? Cesium.HeightReference.CLAMP_TO_GROUND : Cesium.HeightReference.NONE; - const saved = entity.gevAlprNativeAppearance; + const saved = alprMarkers.read(entity)?.nativeAppearance; if (saved) { saved.position = position; saved.heightReference = heightReference; @@ -179,7 +180,7 @@ export function createAlprPresentation({ state, services, source }) { entity.position = position; entity.billboard.heightReference = heightReference; } - entity.gevAlprClamped = clamped; + alprMarkers.write(entity).clamped = clamped; } /** Refresh all native placements, including the appearances held by the canvas. */ @@ -187,7 +188,9 @@ export function createAlprPresentation({ state, services, source }) { if (!state.enabled || !state.dataSource) return; clampedMarkers.clear(); for (const entity of state.dataSource.entities.values) { - const { position, clamped } = markerPlacement(entity.gevAlprRecord); + const { position, clamped } = markerPlacement( + alprMarkers.read(entity)?.record, + ); setMarkerPosition(entity, position, clamped); if (clamped) clampedMarkers.set(entity.id, entity); } @@ -203,10 +206,10 @@ export function createAlprPresentation({ state, services, source }) { const batch = [...clampedMarkers.values()]; const request = Promise.resolve( floors.resolve( - batch.map((entity) => ({ - lat: entity.gevAlprRecord.latitude, - lon: entity.gevAlprRecord.longitude, - })), + batch.map((entity) => { + const { record } = alprMarkers.read(entity); + return { lat: record.latitude, lon: record.longitude }; + }), ), ) .catch(() => {}) @@ -218,7 +221,9 @@ export function createAlprPresentation({ state, services, source }) { for (const entity of batch) { if (clampedMarkers.get(entity.id) !== entity) continue; clampedMarkers.delete(entity.id); - const { position, clamped } = markerPlacement(entity.gevAlprRecord); + const { position, clamped } = markerPlacement( + alprMarkers.read(entity)?.record, + ); if (clamped) continue; setMarkerPosition(entity, position, false); moved = true; @@ -370,7 +375,7 @@ export function createAlprPresentation({ state, services, source }) { removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds }); for (const record of visible) { const existing = state.dataSource.entities.getById(record.id); - if (existing?.gevAlprRecord === record) { + if (alprMarkers.read(existing)?.record === record) { updateAppearance(existing, record.id === state.selectedId); continue; } @@ -401,37 +406,39 @@ export function createAlprPresentation({ state, services, source }) { let entity = existing; // Keep the Cesium entity and its ground-clamping subscription while its // geometry is unchanged. Updating metadata must not rebuild the marker. - const previous = entity?.gevAlprRecord; + const previous = alprMarkers.read(entity)?.record; if (!entity) { entity = state.dataSource.entities.add(entityDef); - entity.gevAlprClamped = clamped; changed = true; + } + const marker = alprMarkers.write(entity); + if (!existing) { + marker.clamped = clamped; } else { if ( previous.latitude !== record.latitude || previous.longitude !== record.longitude ) { setMarkerPosition(entity, position, clamped); - entity.gevAlprCanvasPosition = null; - entity.gevAlprDisplayPosition = null; + marker.canvasPosition = null; + marker.displayPosition = null; } if ( previous.latitude !== record.latitude || previous.longitude !== record.longitude || previous.directionDeg !== record.directionDeg ) { - entity.gevAlprCanvasPosition = null; - entity.gevAlprWedge = null; + marker.canvasPosition = null; + marker.wedge = null; } } - entity.gevAlprRecord = record; + marker.record = record; entityRecord(entity).trackedId = record.id; // The mapped camera datum has no elevation; it is not the clamped marker's // visual anchor. Only the selected marker samples the rendered surface, // at most once per second, through Cesium's public height APIs. - entity.gevAlprDisplayPosition ??= null; - entityRecord(entity).displayPosition = () => - entity.gevAlprDisplayPosition; + marker.displayPosition ??= null; + entityRecord(entity).displayPosition = () => marker.displayPosition; entityRecord(entity).labelModel = { title: alprDisplayId(record), details: alprLabelDetails(record, source), @@ -473,7 +480,8 @@ export function createAlprPresentation({ state, services, source }) { if (changed) state.renderRevision += 1; state.onScreen = countOnScreen(); for (const entity of state.dataSource.entities.values) - if (entity.gevAlprClamped) clampedMarkers.set(entity.id, entity); + if (alprMarkers.read(entity)?.clamped) + clampedMarkers.set(entity.id, entity); resolveClampedFloors(); const selectedEntity = state.selectedId ? state.dataSource.entities.getById(state.selectedId) @@ -577,8 +585,9 @@ export function createAlprPresentation({ state, services, source }) { } const entity = state.dataSource?.entities.getById(state.selectedId); const record = state.recordById.get(state.selectedId); - if (entity?.gevAlprCanvasPosition) { - entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition; + const marker = alprMarkers.read(entity); + if (marker?.canvasPosition) { + marker.displayPosition = marker.canvasPosition; return; } if (!entity || !record || Date.now() - state.lastAnchorSampleAt < 1000) @@ -607,11 +616,9 @@ export function createAlprPresentation({ state, services, source }) { record.latitude, height, ); - if ( - !entity.gevAlprDisplayPosition || - Cesium.Cartesian3.distance(next, entity.gevAlprDisplayPosition) > 0.1 - ) { - entity.gevAlprDisplayPosition = next; + const shown = marker?.displayPosition; + if (!shown || Cesium.Cartesian3.distance(next, shown) > 0.1) { + alprMarkers.write(entity).displayPosition = next; governorRequestRender('alpr-anchor'); } } From 2394703c1444d17c4cb955af10e1a19eb6d09815 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 09:40:15 -0800 Subject: [PATCH 003/470] Keep the context id in the app's entity records instead of on picked objects registerEntityContext stamped __gevContextId on the entities, primitives and carriers it registered, and selection and pick resolution read it back. It is now the contextId field of the entity's own record. --- src/data/contextStore.js | 8 +++++--- src/data/contextStore.test.mjs | 4 ++-- src/data/pickedContext.js | 8 ++++---- src/layers/localAdsb/index.test.mjs | 6 +++--- src/voice/gevActions.test.mjs | 8 ++++---- 5 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/data/contextStore.js b/src/data/contextStore.js index e0b14b2ba9..2f2847b245 100644 --- a/src/data/contextStore.js +++ b/src/data/contextStore.js @@ -1,3 +1,5 @@ +import { entityRecord, readEntityRecord } from './entityRecords.js'; + const STORE_KEY = '__gevContextStore'; function createStore() { @@ -36,14 +38,14 @@ export function registerEntityContext(entity, metadata) { entity, updatedAt: Date.now(), }; - entity.__gevContextId = metadata.id; + entityRecord(entity).contextId = metadata.id; store.entities.set(metadata.id, record); return record; } export function selectEntityContext(entity) { const store = getContextStore(); - const contextId = entity?.__gevContextId; + const contextId = readEntityRecord(entity)?.contextId; if (!contextId || !store.entities.has(contextId)) return null; store.selectedEntityId = contextId; store.selectedAt = Date.now(); @@ -84,7 +86,7 @@ export function selectTrackedSubjectContext(metadata) { store.entities.delete(key); } // Reuse the existing carrier so a per-poll refresh does not churn identity. - const carrier = store.entities.get(id)?.entity || { __gevContextId: id }; + const carrier = store.entities.get(id)?.entity || {}; const record = registerEntityContext(carrier, { ...metadata, id }); if (!record) return null; store.selectedEntityId = id; diff --git a/src/data/contextStore.test.mjs b/src/data/contextStore.test.mjs index e9631133d4..cb9f75eeda 100644 --- a/src/data/contextStore.test.mjs +++ b/src/data/contextStore.test.mjs @@ -96,7 +96,7 @@ test('a sibling tracking layer keeps its own subject slot', () => { test('the per-poll refresh updates values without stealing the selection', () => { withWindow(() => { selectTrackedSubjectContext(flightSubject('aaa001')); - const other = registerEntityContext({ __gevContextId: 'dc-7' }, { + const other = registerEntityContext({}, { id: 'dc-7', layerId: 'local-datacenters', label: 'Datacenter 7', }); selectEntityContext(other.entity); @@ -130,7 +130,7 @@ test('deselecting a contact releases the shared slot', () => { test('clearing one tracking layer leaves another layer selection alone', () => { withWindow(() => { - const other = registerEntityContext({ __gevContextId: 'dam-3' }, { + const other = registerEntityContext({}, { id: 'dam-3', layerId: 'local-dams', label: 'Dam 3', }); selectEntityContext(other.entity); diff --git a/src/data/pickedContext.js b/src/data/pickedContext.js index 28c3035640..fb79c3f3af 100644 --- a/src/data/pickedContext.js +++ b/src/data/pickedContext.js @@ -1,4 +1,5 @@ import { getContextStore, isContextRecordActive } from './contextStore.js'; +import { readEntityRecord } from './entityRecords.js'; import { findPickOwner, resolvePickId } from './pickRegistry.js'; /** @@ -7,8 +8,8 @@ import { findPickOwner, resolvePickId } from './pickRegistry.js'; * * Two lanes, in order: * 1. Context-store carriers. Entity-backed layers (infrastructure GeoJSON, - * selected vessels, fires, installations) stamp `__gevContextId` on the - * picked object, and the store record already carries the label and + * selected vessels, fires, installations) write a `contextId` into the + * picked object's entity record, and the store record already carries the label and * position voice uses everywhere else. * 2. Pick owners. Primitive-backed layers (aircraft, satellites, vessels) * register an ownership predicate in `pickRegistry`; the owning layer's @@ -52,8 +53,7 @@ function contextCarrierRecord(picked, dataManager) { picked?.primitive?.id, picked?.primitive, ]) { - const contextId = - carrier && typeof carrier === 'object' ? carrier.__gevContextId : null; + const contextId = readEntityRecord(carrier)?.contextId; if (!contextId) continue; const record = store.entities.get(contextId); if (record && isContextRecordActive(record, dataManager)) return record; diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 11596d6031..566433950f 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -12,7 +12,7 @@ import { localAdsbReceiverLine, localAdsbStatus, } from './index.js'; -import { readEntityRecord } from '../../data/entityRecords.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; function fakeReceiver(initial = {}) { const state = { @@ -56,11 +56,11 @@ function fakeServices() { render: { governorRequestRender() {} }, context: { registerEntityContext(entity, metadata) { - entity.__gevContextId = metadata.id; + entityRecord(entity).contextId = metadata.id; calls.registered.push(metadata); }, selectEntityContext(entity) { - selected = { id: entity.__gevContextId, entity }; + selected = { id: readEntityRecord(entity)?.contextId, entity }; calls.selected.push(selected.id); return selected; }, diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 96a24edc68..cc7602cbef 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -1303,7 +1303,7 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, camera: { moveEnd: { addEventListener() {} } }, }; - const recordCarrier = { __gevContextId: 'selected-flight-for-cockpit-enter' }; + const recordCarrier = {}; const record = registerEntityContext(recordCarrier, { id: 'abc123', layerId: 'flights', @@ -1444,10 +1444,10 @@ test('control_cockpit rolls Contacts back when the turn becomes stale at commit' test('control_cockpit adopts the newest selection after Contacts settles', async () => { globalThis.window = globalThis.window || { clearTimeout, setTimeout, requestIdleCallback: null }; const contextStore = getContextStore(); - const first = registerEntityContext({ __gevContextId: 'cockpit-selection-first' }, { + const first = registerEntityContext({}, { id: 'first', layerId: 'flights', label: 'FIRST', }); - const second = registerEntityContext({ __gevContextId: 'cockpit-selection-second' }, { + const second = registerEntityContext({}, { id: 'second', layerId: 'flights', label: 'SECOND', }); contextStore.selectedEntityId = first.id; @@ -1713,7 +1713,7 @@ test('control_cockpit enter skips selected non-flight context', async () => { scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, camera: { moveEnd: { addEventListener() {} } }, }; - const recordCarrier = { __gevContextId: 'selected-non-flight-cockpit-enter' }; + const recordCarrier = {}; const record = registerEntityContext(recordCarrier, { id: 'poi-001', layerId: 'local-datacenters', From 04a70d59e975b9bd43fd21ab917dc9a3231525fb Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 09:54:41 -0800 Subject: [PATCH 004/470] Keep aircraft, installation and viewshed state off Cesium objects The aircraft layers' model spec key, IR boost and belly offset and the billboards' large-icon flag move into aircraftVisuals, one store shared by flights, military and local ADS-B. Installation markers' last drawn height and selection move into installationMarkers. The CCTV viewshed QA tag is now the viewshedCameraId record field, which qa-cctv-v2 reads through entityRecords. Test fixtures drop a placement flag nothing reads. --- scripts/package-boundaries.json | 8 ++++++++ scripts/qa-cctv-v2.mjs | 6 +++--- src/data/cockpitModels.test.mjs | 2 +- src/data/nearbyModelHandoff.test.mjs | 5 +---- src/layers/aircraft/visualState.js | 11 ++++++++++ src/layers/cctv/geometry.js | 5 +++-- src/layers/flights/rendering.js | 27 ++++++++++++++++--------- src/layers/installations/markerState.js | 7 +++++++ src/layers/installations/rendering.js | 16 +++++++++------ src/layers/localAdsb/models.js | 10 +++++---- src/layers/military/rendering.js | 27 ++++++++++++++++--------- 11 files changed, 84 insertions(+), 40 deletions(-) create mode 100644 src/layers/aircraft/visualState.js create mode 100644 src/layers/installations/markerState.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 5fbd466104..1450306f92 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1315,6 +1315,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", @@ -1374,6 +1375,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/aircraft/visualState.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -1639,6 +1641,7 @@ "src/layers/installations/model.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", + "src/layers/installations/markerState.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -1834,6 +1837,7 @@ "src/layers/cctv/controls.js", "src/layers/cctv/frames.js", "src/layers/cctv/geometry.js", + "src/data/entityRecords.js", "src/layers/cctv/geometryQueue.js", "src/layers/cctv/ground.js", "src/layers/cctv/headingConfidence.js", @@ -2529,6 +2533,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", @@ -2539,6 +2544,7 @@ "src/layers/installations/model.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", + "src/layers/installations/markerState.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -3435,6 +3441,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", @@ -3445,6 +3452,7 @@ "src/layers/installations/model.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", + "src/layers/installations/markerState.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", diff --git a/scripts/qa-cctv-v2.mjs b/scripts/qa-cctv-v2.mjs index 88e0a5a2c4..d315d3163d 100644 --- a/scripts/qa-cctv-v2.mjs +++ b/scripts/qa-cctv-v2.mjs @@ -1669,7 +1669,7 @@ async function main() { const prims = window.__godsEyeView.viewer.scene.primitives; let n = 0; for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) n += 1; + if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) n += 1; } return n; }); @@ -1729,7 +1729,7 @@ async function main() { const prims = window.__godsEyeView.viewer.scene.primitives; window.__qaViewshedRefs = []; for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) + if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) window.__qaViewshedRefs.push(prims.get(i)); } }); @@ -1738,7 +1738,7 @@ async function main() { const prims = window.__godsEyeView.viewer.scene.primitives; const now = []; for (let i = 0; i < prims.length; i++) { - if (prims.get(i) && prims.get(i)._gevViewshed) now.push(prims.get(i)); + if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) now.push(prims.get(i)); } const before = window.__qaViewshedRefs || []; const sameCount = now.length === before.length; diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 8177b74145..fcadcfa51d 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -88,7 +88,7 @@ for (const layer of LAYERS) { // `_iconKind` is identity for every unconverted contact (see // tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the // operator explicitly converted into a TR-3B. - assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*bb\._gevIconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/, + assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*aircraftVisuals\.read\(bb\)\?\.iconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); assert.match(source, /bb\.rotation\s*=\s*0;/, 'far dots are reset to a rotation-free presentation'); diff --git a/src/data/nearbyModelHandoff.test.mjs b/src/data/nearbyModelHandoff.test.mjs index 98b32341f0..665ef72b58 100644 --- a/src/data/nearbyModelHandoff.test.mjs +++ b/src/data/nearbyModelHandoff.test.mjs @@ -97,7 +97,7 @@ for (const fixture of LAYERS) { // The handoff state: the fleet tick hid the sprite and showed the model. fixture.seed({ billboardShow: false, - models: [[ICAO, { ready: true, show: true, _gevPlacementReady: true }]], + models: [[ICAO, { ready: true, show: true }]], }); assert.ok( nearbyIcaos(fixture.layer).includes(ICAO), @@ -136,7 +136,6 @@ for (const fixture of LAYERS) { ready: false, show: true, scale: 0, - _gevPlacementReady: false, }]], }); assert.ok( @@ -160,7 +159,6 @@ for (const fixture of LAYERS) { models: [[ICAO, { ready: true, show: true, - _gevPlacementReady: true, modelMatrix, computedScale: COMPUTED_SCALE, }]], @@ -191,7 +189,6 @@ for (const fixture of LAYERS) { ready: false, show: true, scale: 0, - _gevPlacementReady: false, modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY), }]], }); diff --git a/src/layers/aircraft/visualState.js b/src/layers/aircraft/visualState.js new file mode 100644 index 0000000000..b9b1f191c7 --- /dev/null +++ b/src/layers/aircraft/visualState.js @@ -0,0 +1,11 @@ +import { createEntityStore } from '../../data/entityRecords.js'; + +/** + * What the aircraft layers (flights, military, local ADS-B) remember about the + * models and billboards they draw, kept beside them rather than on them. + * - `specKey`: the model spec a model was loaded for; a class change reloads. + * - `irBoost`: the IR boost a model was loaded with; a flip reloads. + * - `bellyM`: metres from the model origin to its belly, to sit it on the ground. + * - `iconLarge`: whether a billboard shows the large icon raster. + */ +export const aircraftVisuals = createEntityStore(); diff --git a/src/layers/cctv/geometry.js b/src/layers/cctv/geometry.js index 362ad47897..808ddda250 100644 --- a/src/layers/cctv/geometry.js +++ b/src/layers/cctv/geometry.js @@ -1,5 +1,6 @@ import * as Cesium from 'cesium'; import { createFrustumVolumePrimitive } from '../../data/cctvViewshed.js'; +import { entityRecord } from '../../data/entityRecords.js'; import { FRUSTUM_GROUND_CLEARANCE_M, PROBE_MIN_RANGE_M, @@ -564,8 +565,8 @@ export function createGeometry({ state: layerState, services, parts, source }) { record.frustumPositions, color, ); - // QA tag: the harness counts viewshed volumes by this marker. - primitive._gevViewshed = record.camera.id; + // QA tag: the harness counts viewshed volumes by this record field. + entityRecord(primitive).viewshedCameraId = record.camera.id; record.viewshedPrimitive = layerState._viewer.scene.primitives.add(primitive); record.viewshedActiveTint = !!isActive; diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index d4075a5652..147d730ad3 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -38,6 +38,7 @@ import { COURSE_MAX_DPS, } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; +import { aircraftVisuals } from '../aircraft/visualState.js'; export function createRendering({ flightState, @@ -162,7 +163,7 @@ export function createRendering({ const meta = flightState.records.data.get(icao24); bb.image = aircraftIcon( _iconKind(icao24, meta?.klass), - bb._gevIconLarge ? TRACKED_ICON_PX : undefined, + aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, ); bb.width = icao24 === flightState._trackedIcao ? 24 : 20; bb.height = icao24 === flightState._trackedIcao ? 24 : 20; @@ -432,7 +433,7 @@ export function createRendering({ const key = _specKeyFor(flightState.records.data.get(icao24)?.klass); const current = flightState._models.get(icao24); if ( - (current && current._gevSpecKey !== key) || + (current && aircraftVisuals.read(current)?.specKey !== key) || (!current && flightState._modelPending.has(icao24)) ) { const bb = flightState._billboards.get(icao24); @@ -442,7 +443,7 @@ export function createRendering({ if ( icao24 === flightState._trackedIcao && flightState._trackedModel && - flightState._trackedModel._gevSpecKey !== key + aircraftVisuals.read(flightState._trackedModel)?.specKey !== key ) { _releaseTrackedModel(); } @@ -465,7 +466,11 @@ export function createRendering({ const batch = flightState._irReloadQueue.splice(0, IR_RELOAD_BATCH); for (const icao of batch) { const model = flightState._models.get(icao); - if (!model || model._gevIrBoost === flightState._irBoost) continue; // already right state + if ( + !model || + aircraftVisuals.read(model)?.irBoost === flightState._irBoost + ) + continue; // already right state const bb = flightState._billboards.get(icao); if (bb && icao !== flightState._trackedIcao) bb.show = true; _releaseModel(icao); @@ -571,8 +576,9 @@ export function createRendering({ // Keep the pick identity explicit on the resolved primitive. This also // protects injected/custom loaders that do not copy the creation option. model.id = icao24; - model._gevSpecKey = specKey; // class-change sync compares against this - model._gevIrBoost = loadIrBoost; // boost-flip reload queue compares against this + const visual = aircraftVisuals.write(model); + visual.specKey = specKey; // class-change sync compares against this + visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this // Admitted, not yet the visual. Cesium's default is show=true, which would let // an unplaced primitive claim ownership from the billboard for the frames // between admission and the next fleet tick (and draw at the identity matrix, @@ -764,7 +770,7 @@ export function createRendering({ // Assign after resolution as well as in the creation options so the // standalone primitive always exposes the tracked aircraft pick id. m.id = flightState._trackedIcao; - m._gevSpecKey = trackedKey; // class-change sync compares against this + aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this m.show = false; // admitted, not yet the visual — the driver shows it once placed // Seed the world transform before the primitive enters the scene. A model // can become ready+shown between render phases; leaving Cesium's identity @@ -1075,9 +1081,10 @@ export function createRendering({ (bb.scale || 1) * distanceScale * (globalThis.devicePixelRatio || 1); - const wantLarge = bb._gevIconLarge ? glyphDevPx > 56 : glyphDevPx > 76; - if (wantLarge !== !!bb._gevIconLarge) { - bb._gevIconLarge = wantLarge; + const visual = aircraftVisuals.write(bb); + const wantLarge = visual.iconLarge ? glyphDevPx > 56 : glyphDevPx > 76; + if (wantLarge !== !!visual.iconLarge) { + visual.iconLarge = wantLarge; bb.image = aircraftIcon( _iconKind(icao24, info?.klass), wantLarge ? TRACKED_ICON_PX : undefined, diff --git a/src/layers/installations/markerState.js b/src/layers/installations/markerState.js new file mode 100644 index 0000000000..7738011acf --- /dev/null +++ b/src/layers/installations/markerState.js @@ -0,0 +1,7 @@ +import { createEntityStore } from '../../data/entityRecords.js'; + +/** + * What the installations layer last drew for a retained marker entity, so an + * unchanged record leaves it alone: `heightM` (surface height) and `selected`. + */ +export const installationMarkers = createEntityStore(); diff --git a/src/layers/installations/rendering.js b/src/layers/installations/rendering.js index 94c679b489..e1a46f7005 100644 --- a/src/layers/installations/rendering.js +++ b/src/layers/installations/rendering.js @@ -3,6 +3,7 @@ import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js'; import { entityRecord } from '../../data/entityRecords.js'; +import { installationMarkers } from './markerState.js'; export function createRendering({ state: layerState, @@ -219,13 +220,14 @@ export function createRendering({ : null; if (retained) { // Same geometry: update the marker in place (selection, floor height). - if (retained.gevInstallationHeightM !== surfaceHeightM) { - retained.gevInstallationHeightM = surfaceHeightM; + const marker = installationMarkers.write(retained); + if (marker.heightM !== surfaceHeightM) { + marker.heightM = surfaceHeightM; retained.position = displayPosition; entityRecord(retained).displayPosition = () => displayPosition; } - if (retained.gevInstallationSelected !== selectedRecord) { - retained.gevInstallationSelected = selectedRecord; + if (marker.selected !== selectedRecord) { + marker.selected = selectedRecord; retained.point.pixelSize = selectedRecord ? 13 : 9; retained.point.color = selectedRecord ? Cesium.Color.WHITE : color; } @@ -268,8 +270,10 @@ export function createRendering({ outline.installationId = record.id; entityIds.push(outline.id); } - entity.gevInstallationHeightM = surfaceHeightM; - entity.gevInstallationSelected = selectedRecord; + Object.assign(installationMarkers.write(entity), { + heightM: surfaceHeightM, + selected: selectedRecord, + }); entityRecord(entity).trackedId = `installations:${record.id}`; entityRecord(entity).displayPosition = () => displayPosition; entityRecord(entity).labelModel = { diff --git a/src/layers/localAdsb/models.js b/src/layers/localAdsb/models.js index 55fc2d11a2..c9b9a03ae8 100644 --- a/src/layers/localAdsb/models.js +++ b/src/layers/localAdsb/models.js @@ -15,6 +15,7 @@ import { MODEL_PROX_KEEP_M, } from '../flights/policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; +import { aircraftVisuals } from '../aircraft/visualState.js'; const specKey = (spec) => `${spec.url}@${spec.scale}`; @@ -78,7 +79,7 @@ export function createLocalAdsbModels({ const spec = civilAircraftModelSpec(marker.klass); const key = specKey(spec); const current = models.get(id); - if (current && current._gevSpecKey === key) return; + if (current && aircraftVisuals.read(current)?.specKey === key) return; if (current) release(id); if (pending.has(id) || models.size + pending.size >= cap) return; const loadGeneration = generation; @@ -113,8 +114,9 @@ export function createLocalAdsbModels({ return; } model.id = id; - model._gevSpecKey = key; - model._gevBellyM = spec.bellyM; + const visual = aircraftVisuals.write(model); + visual.specKey = key; + visual.bellyM = spec.bellyM; // Admitted, not yet the visual: placement turns it on. model.show = false; collection.add(model); @@ -182,7 +184,7 @@ export function createLocalAdsbModels({ return Cesium.Cartesian3.fromRadians( carto.longitude, carto.latitude, - height + (model?._gevBellyM || 0), + height + (aircraftVisuals.read(model)?.bellyM || 0), Cesium.Ellipsoid.WGS84, scratchGround, ); diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index 504d79c80b..f65103887e 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -54,6 +54,7 @@ import { COURSE_MAX_DPS, } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; +import { aircraftVisuals } from '../aircraft/visualState.js'; export function createRendering({ flightState, @@ -170,7 +171,7 @@ export function createRendering({ const meta = flightState.records.data.get(icao24); bb.image = aircraftIcon( _iconKind(icao24, meta?.klass), - bb._gevIconLarge ? TRACKED_ICON_PX : undefined, + aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, ); bb.width = icao24 === flightState._trackedIcao ? 24 : 20; bb.height = icao24 === flightState._trackedIcao ? 24 : 20; @@ -400,7 +401,7 @@ export function createRendering({ const key = _specKeyFor(flightState.records.data.get(icao24)?.klass); const current = flightState._models.get(icao24); if ( - (current && current._gevSpecKey !== key) || + (current && aircraftVisuals.read(current)?.specKey !== key) || (!current && flightState._modelPending.has(icao24)) ) { const bb = flightState._billboards.get(icao24); @@ -410,7 +411,7 @@ export function createRendering({ if ( icao24 === flightState._trackedIcao && flightState._trackedModel && - flightState._trackedModel._gevSpecKey !== key + aircraftVisuals.read(flightState._trackedModel)?.specKey !== key ) { _releaseTrackedModel(); } @@ -433,7 +434,11 @@ export function createRendering({ const batch = flightState._irReloadQueue.splice(0, IR_RELOAD_BATCH); for (const icao of batch) { const model = flightState._models.get(icao); - if (!model || model._gevIrBoost === flightState._irBoost) continue; // already right state + if ( + !model || + aircraftVisuals.read(model)?.irBoost === flightState._irBoost + ) + continue; // already right state const bb = flightState._billboards.get(icao); if (bb && icao !== flightState._trackedIcao) bb.show = true; _releaseModel(icao); @@ -536,8 +541,9 @@ export function createRendering({ // Keep the pick identity explicit on the resolved primitive. This also // protects injected/custom loaders that do not copy the creation option. model.id = icao24; - model._gevSpecKey = specKey; // class-change sync compares against this - model._gevIrBoost = loadIrBoost; // boost-flip reload queue compares against this + const visual = aircraftVisuals.write(model); + visual.specKey = specKey; // class-change sync compares against this + visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this // Admitted, not yet the visual. Cesium's default is show=true, which would let // an unplaced primitive claim ownership from the billboard for the frames // between admission and the next fleet tick (and draw at the identity matrix, @@ -725,7 +731,7 @@ export function createRendering({ // Assign after resolution as well as in the creation options so the // standalone primitive always exposes the tracked aircraft pick id. m.id = flightState._trackedIcao; - m._gevSpecKey = trackedKey; // class-change sync compares against this + aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this m.show = false; // admitted, not yet the visual — the driver shows it once placed // Seed the world transform before the primitive enters the scene. A model // can become ready+shown between render phases; leaving Cesium's identity @@ -1005,9 +1011,10 @@ export function createRendering({ (bb.scale || 1) * distanceScale * (globalThis.devicePixelRatio || 1); - const wantLarge = bb._gevIconLarge ? glyphDevPx > 56 : glyphDevPx > 76; - if (wantLarge !== !!bb._gevIconLarge) { - bb._gevIconLarge = wantLarge; + const visual = aircraftVisuals.write(bb); + const wantLarge = visual.iconLarge ? glyphDevPx > 56 : glyphDevPx > 76; + if (wantLarge !== !!visual.iconLarge) { + visual.iconLarge = wantLarge; bb.image = aircraftIcon( _iconKind(icao24, flightState.records.data.get(icao24)?.klass), wantLarge ? TRACKED_ICON_PX : undefined, From 7ebc73393a31aa9c48abde33614021c89feaa549 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 10:01:12 -0800 Subject: [PATCH 005/470] Keep cable pick info and the prewarm flag off Cesium objects Submarine cables wrote each pick's info both to a per-load WeakMap and to a __gevTeleGeography expando, always together; one cablePicks store replaces both and resolves the same objects. The voice view-target prewarm marks its viewer in a WeakSet instead of a __gevViewTargetPrewarmInstalled property. --- scripts/package-boundaries.json | 4 ++++ src/data/telegeographySubmarineCables.test.mjs | 17 +++++++++-------- src/layers/submarineCables/ingestion.js | 1 - src/layers/submarineCables/interaction.js | 10 ++++------ src/layers/submarineCables/lifecycle.js | 1 - src/layers/submarineCables/pickState.js | 7 +++++++ src/layers/submarineCables/rendering.js | 5 ++--- src/layers/submarineCables/state.js | 2 -- src/voice/gevActions.js | 7 +++++-- 9 files changed, 31 insertions(+), 23 deletions(-) create mode 100644 src/layers/submarineCables/pickState.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 1450306f92..ae9d2e2dd7 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2045,6 +2045,8 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pickState.js", + "src/data/entityRecords.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", @@ -2622,6 +2624,7 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pickState.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", @@ -3529,6 +3532,7 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", + "src/layers/submarineCables/pickState.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", diff --git a/src/data/telegeographySubmarineCables.test.mjs b/src/data/telegeographySubmarineCables.test.mjs index 110f65f18b..d1373be447 100644 --- a/src/data/telegeographySubmarineCables.test.mjs +++ b/src/data/telegeographySubmarineCables.test.mjs @@ -22,6 +22,7 @@ import { selectCableReferenceLabelWinners, updateCableReferenceStem, } from './telegeographySubmarineCables.js'; +import { cablePicks } from '../layers/submarineCables/pickState.js'; test('cable reference winners remain nearest-first and hard-capped', () => { const records = Array.from({ length: 300 }, (_, index) => ({ @@ -1840,7 +1841,7 @@ test('multipart association accepts frozen provider collections without modifyin for (const dataSource of env.dataSources.slice(0, 2)) { assert.deepEqual( dataSource.entities.values.map( - (entity) => entity.__gevTeleGeography?.label, + (entity) => cablePicks.read(entity)?.info.label, ), ['Alpha cable', 'Alpha cable', 'Alpha cable', 'Beta cable'], ); @@ -1866,7 +1867,7 @@ test('multipart cables retain their own styling, picking and culling on every se assert.equal(entities.length, 4); for (const [index, entity] of entities.entries()) { const feature = features[index < 3 ? 0 : 1]; - const info = entity.__gevTeleGeography; + const info = cablePicks.read(entity)?.info; assert.equal(info?.label, feature.properties.name, entity.id); assert.deepEqual(info.reference, { lon: feature.properties.coordinates[0], @@ -1922,7 +1923,7 @@ test('multipart association supports missing and repeated IDs without guessing C ['alpha', 'alpha_2', 'alpha_3', 'alpha_2_2', 'cable-2', 'alpha_4'], ); assert.deepEqual( - entities.map((entity) => entity.__gevTeleGeography?.label), + entities.map((entity) => cablePicks.read(entity)?.info.label), [ 'Alpha cable', 'Alpha cable', @@ -1934,7 +1935,7 @@ test('multipart association supports missing and repeated IDs without guessing C ); assert.deepEqual( env.dataSources[2].entities.values.map( - (entity) => entity.__gevTeleGeography.featureId, + (entity) => cablePicks.read(entity)?.info.featureId, ), ['alpha', 'alpha_2', 'cable-2', 'alpha'], ); @@ -1951,12 +1952,12 @@ test('multipart landing geometry keeps every pick with one reference per feature try { const entities = env.dataSources[1].entities.values; assert.deepEqual( - entities.map((entity) => entity.__gevTeleGeography?.label), + entities.map((entity) => cablePicks.read(entity)?.info.label), ['Alpha cable', 'Alpha cable', 'Alpha cable', 'Beta cable'], ); assert.ok( entities.every( - (entity) => entity.__gevTeleGeography.kind === 'landing-point', + (entity) => cablePicks.read(entity)?.info.kind === 'landing-point', ), ); assert.equal(env.dataSources[2].entities.values.length, 2); @@ -1989,11 +1990,11 @@ test('every bundled cable segment is associated with its source feature', async for (const [index, entity] of entities.entries()) { const feature = expandedFeatures[index]; assert.equal( - entity.__gevTeleGeography?.label, + cablePicks.read(entity)?.info.label, feature.properties.name, entity.id, ); - assert.deepEqual(entity.__gevTeleGeography.reference, { + assert.deepEqual(cablePicks.read(entity)?.info.reference, { lon: feature.properties.coordinates[0], lat: feature.properties.coordinates[1], }); diff --git a/src/layers/submarineCables/ingestion.js b/src/layers/submarineCables/ingestion.js index 714b8753b3..23bc4c7351 100644 --- a/src/layers/submarineCables/ingestion.js +++ b/src/layers/submarineCables/ingestion.js @@ -142,7 +142,6 @@ export function createIngestion({ state, parts, source }) { const cableEntities = state._cableDataSource.entities.values; const landingEntities = state._landingDataSource.entities.values; - state._pickByEntity = new WeakMap(); state._referenceRecords = []; state._surfaceRecords = []; diff --git a/src/layers/submarineCables/interaction.js b/src/layers/submarineCables/interaction.js index aaa4f8aadc..19500db6d2 100644 --- a/src/layers/submarineCables/interaction.js +++ b/src/layers/submarineCables/interaction.js @@ -1,10 +1,10 @@ import * as Cesium from 'cesium'; import { isPointerFree } from '../../data/inputOwnership.js'; +import { cablePicks } from './pickState.js'; export function createInteraction({ state, screenSpaceEventHandlerFactory }) { function registerPickEntity(entity, info) { - entity.__gevTeleGeography = info; - state._pickByEntity.set(entity, info); + cablePicks.write(entity).info = info; } function beginInteraction(viewer) { @@ -25,9 +25,8 @@ export function createInteraction({ state, screenSpaceEventHandlerFactory }) { if (!picked) return null; const primitive = picked.primitive; if (primitive) { - const primitiveInfo = state._pickByEntity.get(primitive); + const primitiveInfo = cablePicks.read(primitive)?.info; if (primitiveInfo) return primitiveInfo; - if (primitive.__gevTeleGeography) return primitive.__gevTeleGeography; if ( primitive.id && typeof primitive.id === 'object' && @@ -39,9 +38,8 @@ export function createInteraction({ state, screenSpaceEventHandlerFactory }) { const entity = picked.id; if (entity) { - const entityInfo = state._pickByEntity.get(entity); + const entityInfo = cablePicks.read(entity)?.info; if (entityInfo) return entityInfo; - if (entity.__gevTeleGeography) return entity.__gevTeleGeography; if (entity.id && typeof entity.id === 'object' && entity.id.reference) { return entity.id; } diff --git a/src/layers/submarineCables/lifecycle.js b/src/layers/submarineCables/lifecycle.js index 39e41f6308..87da52ee7f 100644 --- a/src/layers/submarineCables/lifecycle.js +++ b/src/layers/submarineCables/lifecycle.js @@ -133,7 +133,6 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { state._referenceDataSource = null; state._referenceRecords = []; state._surfaceRecords = []; - state._pickByEntity = new WeakMap(); state._referenceLabelCount = 0; state._publishScratch.length = 0; state._markerBlendDone = false; diff --git a/src/layers/submarineCables/pickState.js b/src/layers/submarineCables/pickState.js new file mode 100644 index 0000000000..c84e592bb9 --- /dev/null +++ b/src/layers/submarineCables/pickState.js @@ -0,0 +1,7 @@ +import { createEntityStore } from '../../data/entityRecords.js'; + +/** + * The reference a picked cable, landing point or reference marker flies to: + * `info` is `{ label, kind, featureId, reference: { lon, lat } }`. + */ +export const cablePicks = createEntityStore(); diff --git a/src/layers/submarineCables/rendering.js b/src/layers/submarineCables/rendering.js index 91936573ff..15f1fd263a 100644 --- a/src/layers/submarineCables/rendering.js +++ b/src/layers/submarineCables/rendering.js @@ -10,6 +10,7 @@ import { selectCableReferenceLabelWinners, cableReferencePriority, } from './overlay.js'; +import { cablePicks } from './pickState.js'; export function createRendering({ state }) { function resetPublishSignature() { @@ -40,7 +41,6 @@ export function createRendering({ state }) { state._referenceDataSource = null; state._referenceRecords = []; state._surfaceRecords = []; - state._pickByEntity = new WeakMap(); state._referenceLabelCount = 0; state._publishScratch.length = 0; // The blend pass targets the collections being dropped; the rebuilt @@ -180,8 +180,7 @@ export function createRendering({ state }) { }, }); - entity.__gevTeleGeography = info; - state._pickByEntity.set(entity, info); + cablePicks.write(entity).info = info; const record = { id: entity.id, entity, diff --git a/src/layers/submarineCables/state.js b/src/layers/submarineCables/state.js index 0761688aa9..885cd722fe 100644 --- a/src/layers/submarineCables/state.js +++ b/src/layers/submarineCables/state.js @@ -69,8 +69,6 @@ export function createState({ sweepClock, overlayHost }) { state._markerBlendInvariantWarned = false; - state._pickByEntity = new WeakMap(); - state._referenceLabelCount = 0; state._referenceSweepGate = createCableReferenceSweepGate({ diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 70636dd4e0..6ab6884566 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -2869,9 +2869,12 @@ async function basemapLabelsAt( }; } +/** Viewers that already prewarm view targets on camera settle. */ +const prewarmedViewers = new WeakSet(); + function installViewTargetPrewarm(viewer) { - if (viewer.__gevViewTargetPrewarmInstalled) return; - viewer.__gevViewTargetPrewarmInstalled = true; + if (prewarmedViewers.has(viewer)) return; + prewarmedViewers.add(viewer); let timer = null; let reportedPrewarmFailure = false; viewer.camera.moveEnd.addEventListener(() => { From bb91688a6290f5b834ff010efad99cd783a68f41 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 10:56:08 -0800 Subject: [PATCH 006/470] Read flight and military billboard state from the app's mirror Flights and military now add their billboards through addBillboard and write show, position, scale, rotation, size and distance scaling through setBillboard, which keeps the app's copy in src/data/billboardMirror.js. Their reads go to billboardState instead of the Cesium billboard, so the layers no longer read back what they pushed to the renderer. A mirrored billboard needs an explicit width and height, because unset Cesium reports the loaded image's size. Colour is not mirrored yet: the cyber-sonar theme writes it too and tells the writers apart by the live value, so it moves with the effects port. --- scripts/package-boundaries.json | 4 + src/data/aircraftRecession.js | 8 +- src/data/aircraftRecession.test.mjs | 9 +- src/data/billboardMirror.js | 106 ++++++++++++++++++++++++ src/data/billboardMirror.test.mjs | 74 +++++++++++++++++ src/data/cockpitModels.test.mjs | 4 +- src/data/routeSegment.test.mjs | 5 +- src/data/tr3bRegistry.test.mjs | 2 +- src/data/trackedModelRegime.test.mjs | 13 +-- src/layers/flights/enrichment.js | 11 ++- src/layers/flights/evidence.js | 21 +++-- src/layers/flights/motion.js | 7 +- src/layers/flights/queries.js | 20 +++-- src/layers/flights/queries.test.mjs | 24 ++++-- src/layers/flights/rendering.js | 85 ++++++++++--------- src/layers/flights/snapshotRenderer.js | 3 +- src/layers/flights/testing.js | 5 +- src/layers/flights/tracking.js | 44 ++++++---- src/layers/military/queries.js | 20 +++-- src/layers/military/rendering.js | 81 +++++++++--------- src/layers/military/snapshotRenderer.js | 5 +- src/layers/military/testing.js | 5 +- src/layers/military/tracking.js | 40 +++++---- 23 files changed, 424 insertions(+), 172 deletions(-) create mode 100644 src/data/billboardMirror.js create mode 100644 src/data/billboardMirror.test.mjs diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ae9d2e2dd7..f469c92da5 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1315,6 +1315,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", @@ -1375,6 +1376,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", "src/layers/military/state.js", "src/layers/military/testing.js", @@ -2320,6 +2322,7 @@ "src/data/aircraftMeta.js", "src/data/aircraftNearbyPolicy.js", "src/data/aircraftRecession.js", + "src/data/billboardMirror.js", "src/data/aisLiveVessels.js", "src/data/alprCameras.js", "src/data/analystEngine.js", @@ -3284,6 +3287,7 @@ "src/data/aircraftMeta.js", "src/data/aircraftNearbyPolicy.js", "src/data/aircraftRecession.js", + "src/data/billboardMirror.js", "src/data/cctvCards.js", "src/data/cctvFootprint.js", "src/data/cctvGizmo.js", diff --git a/src/data/aircraftRecession.js b/src/data/aircraftRecession.js index 04c41e6049..984038d16f 100644 --- a/src/data/aircraftRecession.js +++ b/src/data/aircraftRecession.js @@ -5,6 +5,7 @@ * with the locked NearFarScalar. It never edits that scalar, culls a contact, * or allows alpha to reach zero. */ +import { billboardState, setBillboard } from './billboardMirror.js'; export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({ startLimbRatio: 0.5, @@ -220,11 +221,12 @@ export function applyAircraftBillboardTreatment({ const alpha = baseAlpha * composedTreatment; let scaleWrites = 0; let alphaWrites = 0; + const pushedScale = billboardState(billboard)?.scale; if ( - !Number.isFinite(billboard.scale) || - Math.abs(billboard.scale - scale) > tuning.writeEpsilon + !Number.isFinite(pushedScale) || + Math.abs(pushedScale - scale) > tuning.writeEpsilon ) { - billboard.scale = scale; + setBillboard(billboard, 'scale', scale); scaleWrites = 1; } if ( diff --git a/src/data/aircraftRecession.test.mjs b/src/data/aircraftRecession.test.mjs index 23b8ceffb0..7173a36d20 100644 --- a/src/data/aircraftRecession.test.mjs +++ b/src/data/aircraftRecession.test.mjs @@ -7,6 +7,7 @@ import { applyAircraftModelTreatment, cameraLimbDistanceM, } from './aircraftRecession.js'; +import { mirrorBillboard } from './billboardMirror.js'; const params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS }; const cameraHeightM = 1_000_000; @@ -68,7 +69,7 @@ test('globe-view transition eases to identity without a threshold pop', () => { test('aircraft billboard wire writes scale and alpha only for the far treatment', () => { const color = { withAlpha: (alpha) => ({ alpha }) }; - const near = { scale: 1.2, color: { alpha: 0.8 } }; + const near = mirrorBillboard({ scale: 1.2, color: { alpha: 0.8 } }); const nearResult = applyAircraftBillboardTreatment({ billboard: near, baseScale: 1.2, @@ -82,7 +83,7 @@ test('aircraft billboard wire writes scale and alpha only for the far treatment' assert.equal(nearResult.scaleWrites, 0); assert.equal(nearResult.alphaWrites, 0); - const far = { scale: 1.2, color: { alpha: 0.8 } }; + const far = mirrorBillboard({ scale: 1.2, color: { alpha: 0.8 } }); const farResult = applyAircraftBillboardTreatment({ billboard: far, baseScale: 1.2, @@ -101,7 +102,7 @@ test('aircraft billboard wire writes scale and alpha only for the far treatment' test('combined focus and haze product is clamped at the composed alpha floor', () => { const color = { withAlpha: (alpha) => ({ alpha }) }; - const billboard = { scale: 0.45, color: { alpha: 1 } }; + const billboard = mirrorBillboard({ scale: 0.45, color: { alpha: 1 } }); const result = applyAircraftBillboardTreatment({ billboard, baseScale: 1, @@ -118,7 +119,7 @@ test('combined focus and haze product is clamped at the composed alpha floor', ( test('applyAircraftBillboardTreatment returns its documented module singleton', () => { const color = { withAlpha: (alpha) => ({ alpha }) }; - const billboard = { scale: 1, color: { alpha: 1 } }; + const billboard = mirrorBillboard({ scale: 1, color: { alpha: 1 } }); const input = { billboard, baseAlpha: 1, diff --git a/src/data/billboardMirror.js b/src/data/billboardMirror.js new file mode 100644 index 0000000000..5e2676098f --- /dev/null +++ b/src/data/billboardMirror.js @@ -0,0 +1,106 @@ +/** + * @module billboardMirror + * @description The app's copy of what a layer pushed to its billboards, so the layer + * reads its own state back from the app instead of from the renderer's objects. + * + * A layer adds billboards with {@link addBillboard}, writes the mirrored fields + * with {@link setBillboard}, and reads them with {@link billboardState}. Fields + * outside the mirror (image, colour, eye offset, …) are written to the billboard + * directly. Colour stays out because the cyber-sonar theme writes it too and + * tells the two writers apart by reading the live value. + */ +import * as Cesium from 'cesium'; +import { createEntityStore } from './entityRecords.js'; + +const mirrors = createEntityStore(); + +/** + * Mirrored fields with Cesium's defaults for a billboard added without them. + * Width and height have none: unset, Cesium reports the loaded image's size, + * which the app cannot know, so {@link addBillboard} requires them. + */ +const DEFAULTS = Object.freeze({ + show: true, + scale: 1, + rotation: 0, + width: undefined, + height: undefined, + scaleByDistance: undefined, +}); + +/** Cesium copies positions and scalers on write; the mirror keeps its own copy too. */ +function copyInto(record, field, value) { + if (field === 'position') { + // Cesium keeps its old position when handed none; so does the mirror. + if (!value && record.position) return; + record.position = Cesium.Cartesian3.clone( + value ?? Cesium.Cartesian3.ZERO, + record.position, + ); + } else if (field === 'scaleByDistance') { + record.scaleByDistance = value + ? Cesium.NearFarScalar.clone(value, record.scaleByDistance) + : undefined; + } else { + record[field] = value; + } +} + +function seed(billboard, source) { + const record = mirrors.write(billboard); + copyInto(record, 'position', source.position); + for (const [field, fallback] of Object.entries(DEFAULTS)) + copyInto(record, field, source[field] ?? fallback); + return record; +} + +/** + * Add a billboard and remember what was pushed. + * @param {Cesium.BillboardCollection} collection + * @param {Object} options Billboard options, as for `collection.add`, with an + * explicit `width` and `height`. + * @returns {Cesium.Billboard} + */ +export function addBillboard(collection, options) { + if (!Number.isFinite(options?.width) || !Number.isFinite(options?.height)) + throw new TypeError( + 'A mirrored billboard needs an explicit width and height', + ); + const billboard = collection.add(options); + seed(billboard, options); + return billboard; +} + +/** + * Start mirroring a billboard the app did not add itself (test seams), from its + * current fields. + * @param {Object} billboard + * @returns {Object} The billboard. + */ +export function mirrorBillboard(billboard) { + if (billboard && typeof billboard === 'object') seed(billboard, billboard); + return billboard; +} + +/** + * Write one mirrored field to the billboard and to the app's copy. + * @param {Object} billboard + * @param {'show'|'position'|'scale'|'rotation'|'width'|'height'|'scaleByDistance'} field + * @param {*} value + */ +export function setBillboard(billboard, field, value) { + copyInto(mirrors.write(billboard), field, value); + billboard[field] = value; +} + +/** + * The app's copy of a billboard's mirrored fields, or null when it has none (or + * there is no billboard). + * @param {Object|null|undefined} billboard + * @returns {{ show: boolean, position: Cesium.Cartesian3, scale: number, + * rotation: number, width?: number, height?: number, + * scaleByDistance?: Cesium.NearFarScalar }|null} + */ +export function billboardState(billboard) { + return mirrors.read(billboard); +} diff --git a/src/data/billboardMirror.test.mjs b/src/data/billboardMirror.test.mjs new file mode 100644 index 0000000000..3afb2755c7 --- /dev/null +++ b/src/data/billboardMirror.test.mjs @@ -0,0 +1,74 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + addBillboard, + billboardState, + mirrorBillboard, + setBillboard, +} from './billboardMirror.js'; + +const SIZE = Object.freeze({ width: 20, height: 20 }); + +function fakeCollection() { + return { add: (options) => ({ ...options }) }; +} + +test('an added billboard is mirrored with Cesium defaults for unset fields', () => { + const position = Cesium.Cartesian3.fromDegrees(10, 20, 30); + const bb = addBillboard(fakeCollection(), { position, width: 20, height: 24 }); + const state = billboardState(bb); + assert.equal(state.show, true); + assert.equal(state.scale, 1); + assert.equal(state.rotation, 0); + assert.equal(state.width, 20); + assert.equal(state.height, 24); + assert.ok(Cesium.Cartesian3.equals(state.position, position)); + assert.notEqual(state.position, position, 'the mirror keeps its own copy'); +}); + +test('writes reach both the billboard and the mirror', () => { + const bb = addBillboard(fakeCollection(), SIZE); + setBillboard(bb, 'show', false); + setBillboard(bb, 'scale', 0.5); + assert.equal(bb.show, false); + assert.equal(billboardState(bb).show, false); + assert.equal(billboardState(bb).scale, 0.5); +}); + +test('a reused scratch position does not move the mirror', () => { + const bb = addBillboard(fakeCollection(), SIZE); + const scratch = Cesium.Cartesian3.fromDegrees(1, 2, 3); + setBillboard(bb, 'position', scratch); + const written = Cesium.Cartesian3.clone(scratch); + Cesium.Cartesian3.fromDegrees(50, 50, 50, undefined, scratch); + assert.ok(Cesium.Cartesian3.equals(billboardState(bb).position, written)); +}); + +test('writing no position keeps the last one, as Cesium does', () => { + const position = Cesium.Cartesian3.fromDegrees(1, 2, 3); + const bb = addBillboard(fakeCollection(), { ...SIZE, position }); + setBillboard(bb, 'position', undefined); + assert.ok(Cesium.Cartesian3.equals(billboardState(bb).position, position)); +}); + +test('the mirror answers from the app, not from the billboard', () => { + const bb = addBillboard(fakeCollection(), { ...SIZE, show: true }); + bb.show = false; // a write that bypassed the mirror + assert.equal(billboardState(bb).show, true); +}); + +test('a billboard the app did not add can be mirrored from its fields', () => { + const bb = mirrorBillboard({ show: false, scale: 2 }); + assert.equal(billboardState(bb).show, false); + assert.equal(billboardState(bb).scale, 2); + assert.ok(Cesium.Cartesian3.equals(billboardState(bb).position, Cesium.Cartesian3.ZERO)); + assert.equal(billboardState(null), null); + assert.equal(mirrorBillboard(null), null); +}); + +test('a billboard without explicit dimensions is refused', () => { + // Unset, Cesium reports the image's size, which the mirror cannot know. + assert.throws(() => addBillboard(fakeCollection(), {}), TypeError); + assert.throws(() => addBillboard(fakeCollection(), { width: 20 }), TypeError); +}); diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index fcadcfa51d..2f4930985d 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -90,11 +90,11 @@ for (const layer of LAYERS) { // operator explicitly converted into a TR-3B. assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*aircraftVisuals\.read\(bb\)\?\.iconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); - assert.match(source, /bb\.rotation\s*=\s*0;/, + assert.match(source, /setBillboard\(\s*bb,\s*'rotation',\s*0\s*\);/, 'far dots are reset to a rotation-free presentation'); assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)/, 'near 2D silhouettes continue to receive projected course'); - assert.match(source, /if\s*\(\s*bb\.show,?\s*\)\s*bb\.show\s*=\s*false;\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, + assert.match(source, /if\s*\(\s*billboardState\(bb\)\.show,?\s*\)\s*setBillboard\(\s*bb,\s*'show',\s*false\s*\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, 'the gap-proof billboard-to-model handoff remains intact'); }); diff --git a/src/data/routeSegment.test.mjs b/src/data/routeSegment.test.mjs index caa02c4ea9..e48d4645d7 100644 --- a/src/data/routeSegment.test.mjs +++ b/src/data/routeSegment.test.mjs @@ -3,6 +3,7 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { routePlausible } from './routePlausible.js'; import { createTracking } from '../layers/flights/tracking.js'; +import { addBillboard } from './billboardMirror.js'; const SFO = { lat: 37.6188, lon: -122.3754, code: 'SFO' }; const LAX = { lat: 33.9416, lon: -118.4085, code: 'LAX' }; @@ -156,8 +157,10 @@ test('the actual native tracked label hides the wrong leg and keeps a healthy ro }); flightState._billboards.set( id, - collection.add({ + addBillboard(collection, { id, + width: 20, + height: 20, position: Cesium.Cartesian3.fromDegrees( position.lon, position.lat, diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index 9ba8c25c21..654dce572e 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -245,7 +245,7 @@ test('both flight layers keep a converted contact 2D and visible (render invaria // 2. The billboard is never hidden by that suppression — it must keep // satisfying the getNearby/getDetectableObjects visibility guards, so a // converted contact still works in Contacts and Cockpit. - assert.match(source, /if\s*\(\s*bb\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*bb\.show\s*=\s*true;|if\s*\(\s*modelled\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*modelled\.show\s*=\s*true;/, + assert.match(source, /if\s*\(\s*(bb|modelled)\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*setBillboard\(\s*\1,\s*'show',\s*true,?\s*\);/, `${name}: converting restores the billboard the model handoff had hidden`); // 3. Every aircraftIcon() CALL SITE routes through the kind resolver, so no diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index 17fec219d1..d30adb4e89 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -45,6 +45,7 @@ import militaryFlightsLayer, { } from './militaryFlights.js'; import { clearTr3bRegistry, setTr3b } from './tr3bRegistry.js'; import { reportMeshFloorCell, _clearMeshFloorCellsForTest } from './groundFloor.js'; +import { setBillboard } from './billboardMirror.js'; // Sample altitudes are expressed RELATIVE to the band rather than as absolute // offsets. The thresholds have already been retuned once (1_000_000 → 150_000 @@ -351,7 +352,7 @@ for (const fixture of LAYERS) { onGround: true, models: [[icao24, model]], }); - billboard.show = false; + setBillboard(billboard, 'show', false); let ownsVisual = fixture.driveFleetModel({ icao24, position, course: 92 }); assert.equal(ownsVisual, false, 'cold terrain cannot transfer ownership to 3D'); @@ -487,7 +488,7 @@ for (const fixture of LAYERS) { onGround: true, models: [[icao24, model]], }); - billboard.show = false; + setBillboard(billboard, 'show', false); const atA = Cesium.Cartesian3.fromDegrees(A_LON, LAT, 0); const atB = Cesium.Cartesian3.fromDegrees(B_LON, LAT, 0); @@ -622,7 +623,7 @@ for (const fixture of LAYERS) { 0, 1e-6, ), 'a hidden tracked model cannot steal the detection anchor'); - billboard.show = false; // tracking hides the fleet sprite; the tracked entity remains the 2D owner + setBillboard(billboard, 'show', false); // tracking hides the fleet sprite; the tracked entity remains the 2D owner const loadingNearby = fixture.layer.getNearby(billboard.position, 1_000, 50) .find((object) => object.icao24 === (fixture.name === 'flights' ? 'a0f001' : 'b0f001')); assert.ok(loadingNearby, 'the tracked contact remains in proximity while its model loads'); @@ -661,7 +662,7 @@ for (const fixture of LAYERS) { viewer.tileset.tilesLoaded = false; sampledHeight = undefined; - billboard.position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, -500); + setBillboard(billboard, 'position', Cesium.Cartesian3.fromDegrees(-97.71, 30.21, -500)); fixture.driveTrackedModel(); assert.equal(model.show, true, 'a successful cached snap survives a poll-time vertical datum change'); @@ -671,7 +672,7 @@ for (const fixture of LAYERS) { // Taxi past the resample threshold with the tiles gone: the tracked model // holds its last measured floor rather than handing the operator's own // selection back to a 2D glyph for a retry backoff. - billboard.position = Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500); + setBillboard(billboard, 'position', Cesium.Cartesian3.fromDegrees(-97.709, 30.21, -500)); fixture.driveTrackedModel(); assert.equal(model.show, true, 'a taxi-invalidated tracked snap is HELD through the resample outage'); @@ -680,7 +681,7 @@ for (const fixture of LAYERS) { assert.equal(sampleCalls, 1, 'the hold costs no extra synchronous sample'); // Past the drift bound the memory is released and the gate takes over. - billboard.position = Cesium.Cartesian3.fromDegrees(-97.707, 30.21, -500); + setBillboard(billboard, 'position', Cesium.Cartesian3.fromDegrees(-97.707, 30.21, -500)); fixture.driveTrackedModel(); assert.equal(model.show, false, 'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld'); diff --git a/src/layers/flights/enrichment.js b/src/layers/flights/enrichment.js index aaf8ceb38d..a3b2984a4a 100644 --- a/src/layers/flights/enrichment.js +++ b/src/layers/flights/enrichment.js @@ -9,6 +9,7 @@ import { ENRICH_AMBIENT_REFILL_WINDOW_MS, ENRICH_AMBIENT_PER_SWEEP, } from './policy.js'; +import { billboardState } from '../../data/billboardMirror.js'; export function createEnrichment({ flightState, @@ -199,11 +200,9 @@ export function createEnrichment({ 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 - Cesium.Cartesian3.clone( - bb.position, - flightState._scratchModelBS.center, - ); + const { position } = billboardState(bb); + if (!position || !occluder.isPointVisible(position)) continue; // beyond the limb + Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); if ( cull.computeVisibility(flightState._scratchModelBS) === Cesium.Intersect.OUTSIDE @@ -211,7 +210,7 @@ export function createEnrichment({ continue; // off-screen cand.push([ icao24, - Cesium.Cartesian3.distanceSquared(camPos, bb.position), + Cesium.Cartesian3.distanceSquared(camPos, position), ]); } cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first diff --git a/src/layers/flights/evidence.js b/src/layers/flights/evidence.js index 243fe9b9a3..49407daffc 100644 --- a/src/layers/flights/evidence.js +++ b/src/layers/flights/evidence.js @@ -1,6 +1,11 @@ import * as Cesium from 'cesium'; import { aircraftIcon } from '../../data/aircraftIcons.js'; import { FOCUS_EVIDENCE_DEV } from './policy.js'; +import { + addBillboard, + billboardState, + setBillboard, +} from '../../data/billboardMirror.js'; export function createEvidence({ flightState, @@ -83,7 +88,7 @@ export function createEvidence({ flightState.records.data.set(id, meta); flightState._cullPositions.delete(id); flightState._focusEvidenceIds.add(id); - const bb = flightState._billboardCollection.add({ + const bb = addBillboard(flightState._billboardCollection, { position, image: aircraftIcon(parts.rendering._iconKind(id, klass)), width: 20, @@ -119,7 +124,7 @@ export function createEvidence({ const position = _focusEvidencePosition(record); const bb = flightState._billboards.get(id); if (!position || !bb) continue; - bb.position = position; + setBillboard(bb, 'position', position); const meta = flightState.records.data.get(id); if (meta) { if (Number.isFinite(record.trackDeg)) meta.true_track = record.trackDeg; @@ -139,23 +144,23 @@ export function createEvidence({ if (!FOCUS_EVIDENCE_DEV || !flightState._viewer) return []; return [...flightState._focusEvidenceIds].map((id) => { const bb = flightState._billboards.get(id); - const screen = bb?.position + const screen = billboardState(bb)?.position ? Cesium.SceneTransforms.worldToWindowCoordinates( flightState._viewer.scene, - bb.position, + billboardState(bb).position, ) : null; return { id, - show: bb?.show === true, - scale: bb?.scale ?? null, + show: billboardState(bb)?.show === true, + scale: billboardState(bb)?.scale ?? null, alpha: bb?.color?.alpha ?? null, x: screen?.x ?? null, y: screen?.y ?? null, - cameraDistanceM: bb?.position + cameraDistanceM: billboardState(bb)?.position ? Cesium.Cartesian3.distance( flightState._viewer.camera.positionWC, - bb.position, + billboardState(bb).position, ) : null, }; diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 87a0a402b9..d4ae59845f 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -35,6 +35,7 @@ import { DISPLAY_CORRIDOR_CELL_BUDGET, DISPLAY_CORRIDOR_FAIR_SHARE, } from './policy.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createMotion({ flightState, @@ -109,7 +110,7 @@ export function createMotion({ if (newest) newest.position = Cesium.Cartesian3.clone(position, newest.position); const bb = flightState._billboards.get(icao24); - if (bb) bb.position = position; + if (bb) setBillboard(bb, 'position', position); } } @@ -131,7 +132,9 @@ export function createMotion({ function _deadReckon(icao24, result, sampledRenderTime) { const info = flightState.records.data.get(icao24); if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) { - const position = flightState._billboards.get(icao24)?.position; + const position = billboardState( + flightState._billboards.get(icao24), + )?.position; flightState._drCourseDeg = info?.true_track || 0; flightState._drSpeedMps = info?.velocity || 0; flightState._drCourseHold = diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 89b91f1257..0cfad575ed 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -16,6 +16,7 @@ import { FLEET_DR_INTERVAL_MS, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createQueries({ flightState, @@ -134,7 +135,8 @@ export function createQueries({ const info = flightState.records.data.get(icao24); const bb = flightState._billboards.get(icao24); const basePos = - parts.motion._deadReckon(icao24) || (bb ? bb.position : null); + parts.motion._deadReckon(icao24) || + (bb ? billboardState(bb).position : null); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -336,7 +338,8 @@ export function createQueries({ // here would double-image the tracked plane when 3D is turned off mid-track. if (flightState._billboardCollection) for (const [icao, bb] of flightState._billboards) { - if (icao !== flightState._trackedIcao) bb.show = true; + if (icao !== flightState._trackedIcao) + setBillboard(bb, 'show', true); } } } @@ -454,7 +457,8 @@ export function createQueries({ // doesn't vanish on the 2D→3D handoff; bb.position stays current while hidden. const model = flightState._models.get(icao24) ?? null; const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24, model); - if (!isTracked && !bb.show && !modelOwnsVisual) continue; + if (!isTracked && !billboardState(bb).show && !modelOwnsVisual) + continue; const info = flightState.records.data.get(icao24); let object = flightState._detectionObjects.get(icao24); if (!object) { @@ -476,7 +480,7 @@ export function createQueries({ ? parts.rendering._modelSpec(info?.klass) : null; const pos = isTracked - ? parts.motion._trackedVisualCached() || bb.position + ? parts.motion._trackedVisualCached() || billboardState(bb).position : modelOwnsVisual ? modelVisualAnchor( model.modelMatrix, @@ -486,7 +490,7 @@ export function createQueries({ : spec.scale, object._weldPos || (object._weldPos = new Cesium.Cartesian3()), ) - : bb.position; + : billboardState(bb).position; if (!pos) continue; object.position = pos; object.skipLabel = isTracked; @@ -600,7 +604,7 @@ export function createQueries({ if ( !aircraftIncludedInNearby({ isTracked, - billboardShown: bb.show, + billboardShown: billboardState(bb).show, modelRendering: parts.rendering._modelOwnsVisual(icao24), includeHidden, }) @@ -610,7 +614,7 @@ export function createQueries({ const trackedPos = isTracked ? parts.motion._trackedDisplayCached() : null; // cached, no recompute (anti-jitter) - const pos = trackedPos || bb.position; + const pos = trackedPos || billboardState(bb).position; if (!pos) continue; const distance = Cesium.Cartesian3.distance(center, pos); @@ -692,7 +696,7 @@ export function createQueries({ const result = []; for (const [icao24, bb] of flightState._billboards) { - const pos = bb.position; + const pos = billboardState(bb).position; if (!pos) continue; const carto = Cesium.Cartographic.fromCartesian( pos, diff --git a/src/layers/flights/queries.test.mjs b/src/layers/flights/queries.test.mjs index 13957d6cca..33eec2ed92 100644 --- a/src/layers/flights/queries.test.mjs +++ b/src/layers/flights/queries.test.mjs @@ -3,6 +3,11 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { createQueries } from './queries.js'; import { createRendering } from './rendering.js'; +import { + billboardState, + mirrorBillboard, + setBillboard, +} from '../../data/billboardMirror.js'; function fixture() { const info = { @@ -10,7 +15,10 @@ function fixture() { registration: ' N123 ', altitude: 1000, }; - const bb = { show: true, position: new Cesium.Cartesian3(1, 2, 3) }; + const bb = mirrorBillboard({ + show: true, + position: new Cesium.Cartesian3(1, 2, 3), + }); const flightState = { feed: {}, _billboardCollection: { show: true }, @@ -48,9 +56,10 @@ test('candidate text follows in-place enrichment without freezing identity or po const [first] = f.queries.getDetectableObjects(); assert.equal(first.id, 'TEST123'); assert.equal(first.sourceId, 'abc123'); - f.bb.position = new Cesium.Cartesian3(4, 5, 6); + setBillboard(f.bb, 'position', new Cesium.Cartesian3(4, 5, 6)); assert.equal(f.queries.getDetectableObjects()[0], first); - assert.equal(first.position, f.bb.position); + assert.equal(first.position, billboardState(f.bb).position); + assert.deepEqual(first.position, new Cesium.Cartesian3(4, 5, 6)); assert.equal(f.formats(), 1); f.info.callsign = ' NEW456 '; assert.equal(f.queries.getDetectableObjects()[0].id, 'NEW456'); @@ -97,7 +106,7 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => scale: 1, }); f.flightState._models.set('abc123', model); - f.bb.show = false; + setBillboard(f.bb, 'show', false); assert.deepEqual(f.queries.getDetectableObjects(), []); model.ready = true; assert.equal(f.queries.getDetectableObjects()[0], candidate); @@ -111,8 +120,11 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60)); model.show = false; assert.deepEqual(f.queries.getDetectableObjects(), []); - f.bb.show = true; - assert.equal(f.queries.getDetectableObjects()[0].position, f.bb.position); + setBillboard(f.bb, 'show', true); + assert.equal( + f.queries.getDetectableObjects()[0].position, + billboardState(f.bb).position, + ); assert.equal(get.mock.callCount(), 6); model.show = true; assert.equal(f.parts.rendering._modelOwnsVisual('abc123'), true); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index 147d730ad3..a110600718 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -39,6 +39,7 @@ import { } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createRendering({ flightState, @@ -151,12 +152,12 @@ export function createRendering({ if (isCockpitContact && !isCockpitNear) { const freshnessAlpha = cyberSonarBaseAlpha(bb); bb.image = cockpitContactDotImage(); - bb.width = COCKPIT_CONTACT_SIZE_PX; - bb.height = COCKPIT_CONTACT_SIZE_PX; - bb.scale = limbScale; - bb.scaleByDistance = _cockpitBillboardScaleByDistance(); + setBillboard(bb, 'width', COCKPIT_CONTACT_SIZE_PX); + setBillboard(bb, 'height', COCKPIT_CONTACT_SIZE_PX); + setBillboard(bb, 'scale', limbScale); + setBillboard(bb, 'scaleByDistance', _cockpitBillboardScaleByDistance()); bb.color = _cockpitContactColor(icao24).withAlpha(freshnessAlpha); - bb.rotation = 0; + setBillboard(bb, 'rotation', 0); return; } @@ -165,10 +166,14 @@ export function createRendering({ _iconKind(icao24, meta?.klass), aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, ); - bb.width = icao24 === flightState._trackedIcao ? 24 : 20; - bb.height = icao24 === flightState._trackedIcao ? 24 : 20; - bb.scale = _fleetBillboardScale(icao24, meta?.klass) * limbScale; - bb.scaleByDistance = _normalBillboardScaleByDistance(); + setBillboard(bb, 'width', icao24 === flightState._trackedIcao ? 24 : 20); + setBillboard(bb, 'height', icao24 === flightState._trackedIcao ? 24 : 20); + setBillboard( + bb, + 'scale', + _fleetBillboardScale(icao24, meta?.klass) * limbScale, + ); + setBillboard(bb, 'scaleByDistance', _normalBillboardScaleByDistance()); bb.color = _fleetBillboardColor(icao24).withAlpha(cyberSonarBaseAlpha(bb)); } @@ -324,7 +329,7 @@ export function createRendering({ function _driveFleetModelHandoff(icao24, model, bb, pos, course, beforeShow) { if (!model) { - bb.show = true; + setBillboard(bb, 'show', true); return false; } const displayPos = _modelDisplayPosition( @@ -334,7 +339,7 @@ export function createRendering({ ); if (!displayPos) { model.show = false; // no ground evidence → nothing safe to place a depth-tested model at - bb.show = true; + setBillboard(bb, 'show', true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip @@ -343,12 +348,12 @@ export function createRendering({ _modelMatrix(displayPos, course, model.modelMatrix); if (!model.ready) { model.show = false; // not loaded yet → keep the 2D icon, no half-model flash - bb.show = true; + setBillboard(bb, 'show', true); return false; } beforeShow?.(); if (!model.show) model.show = true; - if (bb.show) bb.show = false; // hand off ONLY once the model renders + if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders return true; } @@ -437,7 +442,8 @@ export function createRendering({ (!current && flightState._modelPending.has(icao24)) ) { const bb = flightState._billboards.get(icao24); - if (bb && icao24 !== flightState._trackedIcao) bb.show = true; + if (bb && icao24 !== flightState._trackedIcao) + setBillboard(bb, 'show', true); _releaseModel(icao24); } if ( @@ -472,7 +478,8 @@ export function createRendering({ ) continue; // already right state const bb = flightState._billboards.get(icao); - if (bb && icao !== flightState._trackedIcao) bb.show = true; + if (bb && icao !== flightState._trackedIcao) + setBillboard(bb, 'show', true); _releaseModel(icao); } if (flightState._irReloadQueue.length === 0) @@ -699,7 +706,8 @@ export function createRendering({ // readout consumers then reuse that exact cached position. const pos = parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState(flightState._billboards.get(flightState._trackedIcao)) + ?.position; if (!pos) { if (flightState._trackedModel) flightState._trackedModel.show = false; return; @@ -777,7 +785,9 @@ export function createRendering({ // default here produces a one-frame jump to the Earth's center. const currentPos = parts.motion._trackedDisplayCached() || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState( + flightState._billboards.get(flightState._trackedIcao), + )?.position; if (currentPos) { const displayPos = _modelDisplayPosition( flightState._trackedIcao, @@ -938,12 +948,10 @@ export function createRendering({ // ground or in the air — no distinction"). The cap + nearest-first ordering // below already bound airport clusters; grounded placement is handled by the // one-shot ground snap in _modelDisplayPosition. - const d2 = Cesium.Cartesian3.distanceSquared(camPos, bb.position); + const { position } = billboardState(bb); + const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible - Cesium.Cartesian3.clone( - bb.position, - flightState._scratchModelBS.center, - ); + Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); cand.push([ icao, d2, @@ -973,6 +981,7 @@ export function createRendering({ for (const [icao24, bb] of flightState._billboards) { if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion + const icon = billboardState(bb); const info = flightState.records.data.get(icao24); @@ -996,9 +1005,9 @@ export function createRendering({ // collection's vertex buffer, so skip sub-meter moves. if ( display && - Cesium.Cartesian3.distanceSquared(display, bb.position) > 1.0 + Cesium.Cartesian3.distanceSquared(display, icon.position) > 1.0 ) { - bb.position = display; + setBillboard(bb, 'position', display); } // Round 6: occlusion-test a LIFTED point for contacts rendering below @@ -1007,15 +1016,15 @@ export function createRendering({ // pass would hide a plane that is really just low over high-N terrain // waiting for its floor to warm (ATL grounded contacts at geoid −31 m). const beyondHorizon = !occluder.isPointVisible( - flightState._cullPositions.get(icao24) || bb.position, + flightState._cullPositions.get(icao24) || icon.position, ); // A billboard flipping INTO view (horizon reveal while the camera idles) // gets its rotation refreshed THIS tick even without a pose change — // otherwise it reappears wearing its stale (often creation-north) nose for // up to ROTATION_REFRESH_MS. (Model-handed-off planes also read show=false // here; harmless — the model branch below `continue`s past the rotation.) - const revealed = !beyondHorizon && !bb.show; - if (bb.show === beyondHorizon) bb.show = !beyondHorizon; + const revealed = !beyondHorizon && !icon.show; + if (icon.show === beyondHorizon) setBillboard(bb, 'show', !beyondHorizon); if (beyondHorizon) { // Also hide any 3D model — otherwise a model that crossed the limb would keep // rendering through the hidden globe at its last matrix. @@ -1031,22 +1040,22 @@ export function createRendering({ // alpha; nearer focus behavior remains tunable rather than universal. const cameraDistanceM = Cesium.Cartesian3.distance( camera.positionWC, - bb.position, + icon.position, ); const distanceScale = nearFarScalarValueAtDistance( - bb.scaleByDistance, + icon.scaleByDistance, cameraDistanceM, ); const focus = advanceProjectedSpriteFocus( bb, - bb.position, + icon.position, scene, camera, nowMs, focusTarget, undefined, - (bb.width || 20) * (bb.scale || 1) * distanceScale * 0.5, - (bb.height || 20) * (bb.scale || 1) * distanceScale * 0.5, + (icon.width || 20) * (icon.scale || 1) * distanceScale * 0.5, + (icon.height || 20) * (icon.scale || 1) * distanceScale * 0.5, ); const isCockpitNear = flightState._cockpitContactMode && @@ -1077,8 +1086,8 @@ export function createRendering({ // hysteresis so zoom oscillation never thrashes the atlas. if (!flightState._cockpitContactMode || isCockpitNear) { const glyphDevPx = - (bb.width || 20) * - (bb.scale || 1) * + (icon.width || 20) * + (icon.scale || 1) * distanceScale * (globalThis.devicePixelRatio || 1); const visual = aircraftVisuals.write(bb); @@ -1160,12 +1169,12 @@ export function createRendering({ ) { const rot = screenProjectedRotation( scene, - bb.position, + icon.position, course, - bb.rotation, + icon.rotation, ); - if (rot !== null && Math.abs(rot - bb.rotation) > 0.002) { - bb.rotation = rot; + if (rot !== null && Math.abs(rot - icon.rotation) > 0.002) { + setBillboard(bb, 'rotation', rot); } } } diff --git a/src/layers/flights/snapshotRenderer.js b/src/layers/flights/snapshotRenderer.js index ec6c2933b3..2fa013a487 100644 --- a/src/layers/flights/snapshotRenderer.js +++ b/src/layers/flights/snapshotRenderer.js @@ -7,6 +7,7 @@ import { } from '../../data/motionModel.js'; import { aircraftIcon } from '../../data/aircraftIcons.js'; import { POSITION_HISTORY_LIMIT } from './recordPolicy.js'; +import { addBillboard } from '../../data/billboardMirror.js'; /** Apply reconciled aircraft records to Cesium resources and follow state. */ export function createFlightSnapshotRenderer({ @@ -195,7 +196,7 @@ export function createFlightSnapshotRenderer({ rendering._modelOwnsVisual(icao24), )) || position; - const bb = flightState._billboardCollection.add({ + const bb = addBillboard(flightState._billboardCollection, { position: displayed, image: aircraftIcon(rendering._iconKind(icao24, meta.klass)), width: isTracked ? 24 : 20, diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index ccb109ae1c..df54b7c9da 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -1,5 +1,6 @@ import * as Cesium from 'cesium'; import { CYAN_TRANSPARENT } from './policy.js'; +import { mirrorBillboard } from '../../data/billboardMirror.js'; export function createTesting({ flightState, @@ -68,7 +69,7 @@ export function createTesting({ flightState._viewer = viewer; flightState._modelCollection = modelCollection; flightState._billboardCollection = billboardCollection; - flightState._billboards = new Map([[icao24, billboard]]); + flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); flightState._cullPositions.clear(); flightState._models.clear(); for (const [key, model] of models) flightState._models.set(key, model); @@ -117,7 +118,7 @@ export function createTesting({ billboard, history = [], }) { - flightState._billboards.set(icao24, billboard); + flightState._billboards.set(icao24, mirrorBillboard(billboard)); flightState.records.data.set(icao24, meta); flightState._positionHistory.set(icao24, history); } diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 064fce011f..9969ad88eb 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -26,6 +26,7 @@ import { } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createTracking({ flightState, @@ -65,7 +66,7 @@ export function createTracking({ function _publishTrackedSelection(icao24, origin = 'programmatic') { const bb = flightState._billboards.get(icao24); const info = flightState.records.data.get(icao24); - if (!bb?.position || !info) return false; + if (!billboardState(bb)?.position || !info) return false; if (flightState._trackedEntity) entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { @@ -76,7 +77,7 @@ export function createTracking({ // a callsign-less contact reached Context as its raw hex even once adsbdb // had supplied a registration. Identity below stays `icao24`. label: parts.queries._contactLabel(icao24, info), - position: Cesium.Cartesian3.clone(bb.position), + position: Cesium.Cartesian3.clone(billboardState(bb).position), origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(icao24)); @@ -162,12 +163,13 @@ export function createTracking({ const previous = flightState._cockpitNearContacts; const distancesSquared = []; for (const [icao24, bb] of flightState._billboards) { - if (icao24 === flightState._trackedIcao || !bb?.position) continue; + const position = billboardState(bb)?.position; + if (icao24 === flightState._trackedIcao || !position) continue; distancesSquared.push([ icao24, Cesium.Cartesian3.distanceSquared( flightState._viewer.camera.positionWC, - bb.position, + position, ), ]); } @@ -316,7 +318,8 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState(flightState._billboards.get(flightState._trackedIcao)) + ?.position; if (!pos) return; const projected = screenProjectedRotation( flightState._viewer.scene, @@ -642,17 +645,21 @@ export function createTracking({ // ROTATION_REFRESH_MS of a wrong (possibly reversed) nose on release. if (flightState._billboards.has(flightState._trackedIcao)) { const bb = flightState._billboards.get(flightState._trackedIcao); - bb.show = true; - bb.width = 20; - bb.height = 20; + setBillboard(bb, 'show', true); + setBillboard(bb, 'width', 20); + setBillboard(bb, 'height', 20); // Ground/military-aware restore (a plane untracked while taxiing must come // back muted-gray at ground scale, not white at full scale). bb.color = parts.rendering._fleetBillboardColor(flightState._trackedIcao); - bb.scale = parts.rendering._fleetBillboardScale( - flightState._trackedIcao, - flightState.records.data.get(flightState._trackedIcao)?.klass, + setBillboard( + bb, + 'scale', + parts.rendering._fleetBillboardScale( + flightState._trackedIcao, + flightState.records.data.get(flightState._trackedIcao)?.klass, + ), ); - bb.rotation = flightState._lastTrackedRotation; + setBillboard(bb, 'rotation', flightState._lastTrackedRotation); } flightState._lastCamPoseSig = ''; // force a fleet rotation pass on the next tick @@ -830,7 +837,7 @@ export function createTracking({ if (flightState._models.has(id) || flightState._modelPending.has(id)) parts.rendering._releaseModel(id); const bb = flightState._billboards.get(id); - if (bb && id !== flightState._trackedIcao) bb.show = true; // horizon cull re-asserts next tick + if (bb && id !== flightState._trackedIcao) setBillboard(bb, 'show', true); // horizon cull re-asserts next tick if (id === flightState._trackedIcao) { parts.rendering._releaseTrackedModel(); _syncTracked2dRotation(); @@ -862,9 +869,9 @@ export function createTracking({ function _routeIsPlausible(icao24, route) { const info = flightState.records.data.get(icao24); const bb = flightState._billboards.get(icao24); - if (!info || !bb || !bb.position) return true; + if (!info || !bb || !billboardState(bb).position) return true; const carto = Cesium.Cartographic.fromCartesian( - bb.position, + billboardState(bb).position, Cesium.Ellipsoid.WGS84, flightState._scratchCarto, ); @@ -906,21 +913,22 @@ export function createTracking({ flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget flightState._cachedDRFrame = -1; - flightState._lastTrackedRotation = bb.rotation || 0; + flightState._lastTrackedRotation = billboardState(bb).rotation || 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. parts.rendering._releaseModel(icao24); // Hide the billboard — the tracked entity replaces it visually - bb.show = false; + setBillboard(bb, 'show', false); // Helper: smoothed, per-frame-cached tracked position (see _trackedDisplayPosition — // one computation shared by the position/alignedAxis/rotation/trail-head callbacks, // with discontinuity reconciliation). Falls back to the last billboard position when // the aircraft has no fix. const getTrackedPosition = () => - parts.motion._trackedDisplayPosition(icao24) || bb.position; + parts.motion._trackedDisplayPosition(icao24) || + billboardState(bb).position; // Dead-reckoning position property — smooth continuous motion between API updates. const positionProperty = new Cesium.CallbackProperty(() => { diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index d23ad621a0..db357a87fc 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -11,6 +11,7 @@ import { } from '../../data/contactMatch.js'; import { LANDED_ALT_MAX_FT, LANDED_SPEED_MAX_MPS } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createQueries({ flightState, @@ -96,7 +97,8 @@ export function createQueries({ const info = flightState.records.data.get(icao24); const bb = flightState._billboards.get(icao24); const basePos = - parts.motion._deadReckon(icao24) || (bb ? bb.position : null); + parts.motion._deadReckon(icao24) || + (bb ? billboardState(bb).position : null); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -272,7 +274,8 @@ export function createQueries({ // plane's own fleet billboard — its tracked entity is the visual (avoids a double-image). if (flightState._billboardCollection) for (const [icao, bb] of flightState._billboards) { - if (icao !== flightState._trackedIcao) bb.show = true; + if (icao !== flightState._trackedIcao) + setBillboard(bb, 'show', true); } } } @@ -375,7 +378,7 @@ export function createQueries({ if ( !aircraftIncludedInNearby({ isTracked, - billboardShown: bb.show, + billboardShown: billboardState(bb).show, modelRendering: parts.rendering._modelOwnsVisual(icao24), includeHidden, }) @@ -385,7 +388,7 @@ export function createQueries({ const trackedPos = isTracked ? parts.motion._trackedDisplayCached() : null; // cached, no recompute (anti-jitter) - const pos = trackedPos || bb.position; + const pos = trackedPos || billboardState(bb).position; if (!pos) continue; const distance = Cesium.Cartesian3.distance(center, pos); @@ -462,7 +465,8 @@ export function createQueries({ // doesn't vanish on the 2D→3D handoff; bb.position stays current while hidden. const model = flightState._models.get(icao24); const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24); - if (!isTracked && !bb.show && !modelOwnsVisual) continue; + if (!isTracked && !billboardState(bb).show && !modelOwnsVisual) + continue; const info = flightState.records.data.get(icao24); const callsign = info?.callsign?.trim(); const registration = info?.registration?.trim(); @@ -484,7 +488,7 @@ export function createQueries({ ? parts.rendering._modelSpec(info?.klass) : null; const pos = isTracked - ? parts.motion._trackedVisualCached() || bb.position + ? parts.motion._trackedVisualCached() || billboardState(bb).position : modelOwnsVisual ? modelVisualAnchor( model.modelMatrix, @@ -494,7 +498,7 @@ export function createQueries({ : spec.scale, object._weldPos || (object._weldPos = new Cesium.Cartesian3()), ) - : bb.position; + : billboardState(bb).position; if (!pos) continue; object.position = pos; object.skipLabel = isTracked; @@ -616,7 +620,7 @@ export function createQueries({ const result = []; for (const [icao24, bb] of flightState._billboards) { - const pos = bb.position; + const pos = billboardState(bb).position; if (!pos) continue; const carto = Cesium.Cartographic.fromCartesian( pos, diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index f65103887e..1287196308 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -55,6 +55,7 @@ import { } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createRendering({ flightState, @@ -159,12 +160,12 @@ export function createRendering({ if (isCockpitContact && !isCockpitNear) { const freshnessAlpha = cyberSonarBaseAlpha(bb); bb.image = cockpitContactDotImage(); - bb.width = COCKPIT_CONTACT_SIZE_PX; - bb.height = COCKPIT_CONTACT_SIZE_PX; - bb.scale = limbScale; - bb.scaleByDistance = _cockpitBillboardScaleByDistance(); + setBillboard(bb, 'width', COCKPIT_CONTACT_SIZE_PX); + setBillboard(bb, 'height', COCKPIT_CONTACT_SIZE_PX); + setBillboard(bb, 'scale', limbScale); + setBillboard(bb, 'scaleByDistance', _cockpitBillboardScaleByDistance()); bb.color = _fleetBillboardColor(icao24).withAlpha(freshnessAlpha); - bb.rotation = 0; + setBillboard(bb, 'rotation', 0); return; } @@ -173,10 +174,10 @@ export function createRendering({ _iconKind(icao24, meta?.klass), aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, ); - bb.width = icao24 === flightState._trackedIcao ? 24 : 20; - bb.height = icao24 === flightState._trackedIcao ? 24 : 20; - bb.scale = _militaryBillboardScale(icao24) * limbScale; - bb.scaleByDistance = _normalBillboardScaleByDistance(); + setBillboard(bb, 'width', icao24 === flightState._trackedIcao ? 24 : 20); + setBillboard(bb, 'height', icao24 === flightState._trackedIcao ? 24 : 20); + setBillboard(bb, 'scale', _militaryBillboardScale(icao24) * limbScale); + setBillboard(bb, 'scaleByDistance', _normalBillboardScaleByDistance()); bb.color = _fleetBillboardColor(icao24, meta).withAlpha( cyberSonarBaseAlpha(bb), ); @@ -330,7 +331,7 @@ export function createRendering({ function _driveFleetModelHandoff(icao24, model, bb, pos, course, beforeShow) { if (!model) { - bb.show = true; + setBillboard(bb, 'show', true); return false; } const displayPos = _modelDisplayPosition( @@ -340,7 +341,7 @@ export function createRendering({ ); if (!displayPos) { model.show = false; // no ground evidence → nothing safe to place a depth-tested model at - bb.show = true; + setBillboard(bb, 'show', true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip @@ -354,12 +355,12 @@ export function createRendering({ ); if (!model.ready) { model.show = false; // not loaded yet → keep the 2D icon, no half-model flash - bb.show = true; + setBillboard(bb, 'show', true); return false; } beforeShow?.(); if (!model.show) model.show = true; - if (bb.show) bb.show = false; // hand off ONLY once the model renders + if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders return true; } @@ -405,7 +406,8 @@ export function createRendering({ (!current && flightState._modelPending.has(icao24)) ) { const bb = flightState._billboards.get(icao24); - if (bb && icao24 !== flightState._trackedIcao) bb.show = true; + if (bb && icao24 !== flightState._trackedIcao) + setBillboard(bb, 'show', true); _releaseModel(icao24); } if ( @@ -440,7 +442,8 @@ export function createRendering({ ) continue; // already right state const bb = flightState._billboards.get(icao); - if (bb && icao !== flightState._trackedIcao) bb.show = true; + if (bb && icao !== flightState._trackedIcao) + setBillboard(bb, 'show', true); _releaseModel(icao); } if (flightState._irReloadQueue.length === 0) @@ -662,7 +665,8 @@ export function createRendering({ // readout consumers then reuse that exact cached position. const pos = parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState(flightState._billboards.get(flightState._trackedIcao)) + ?.position; if (!pos) { if (flightState._trackedModel) flightState._trackedModel.show = false; return; @@ -738,7 +742,9 @@ export function createRendering({ // default here produces a one-frame jump to the Earth's center. const currentPos = parts.motion._trackedDisplayCached() || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState( + flightState._billboards.get(flightState._trackedIcao), + )?.position; if (currentPos) { const displayPos = _modelDisplayPosition( flightState._trackedIcao, @@ -897,12 +903,10 @@ export function createRendering({ // Ground planes compete for model slots like everyone else (owner decision // 2026-07-03, mirror of flights.js — no air/ground distinction; grounded // placement is handled by the one-shot ground snap in _modelDisplayPosition). - const d2 = Cesium.Cartesian3.distanceSquared(camPos, bb.position); + const { position } = billboardState(bb); + const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); if (d2 > keepDistSq) continue; // beyond keep radius → never eligible - Cesium.Cartesian3.clone( - bb.position, - flightState._scratchModelBS.center, - ); + Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); cand.push([ icao, d2, @@ -932,27 +936,28 @@ export function createRendering({ for (const [icao24, bb] of flightState._billboards) { if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion + const icon = billboardState(bb); const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos); // Gate the write — assigning Billboard.position dirties the whole // collection's vertex buffer, so skip sub-meter moves. - if (dr && Cesium.Cartesian3.distanceSquared(dr, bb.position) > 1.0) { - bb.position = dr; + if (dr && Cesium.Cartesian3.distanceSquared(dr, icon.position) > 1.0) { + setBillboard(bb, 'position', dr); } // Round 6: occlusion-test a LIFTED point for contacts at/below the // ellipsoid (mirror of flights.js — sub-ellipsoid points near the limb // read "beyond the horizon" and would hide low contacts awaiting floors). const beyondHorizon = !occluder.isPointVisible( - flightState.records.data.get(icao24)?.cullPosition || bb.position, + flightState.records.data.get(icao24)?.cullPosition || icon.position, ); // A billboard flipping INTO view (horizon reveal while the camera idles) // gets its rotation refreshed THIS tick even without a pose change — // otherwise it reappears wearing its stale (often creation-north) nose for // up to ROTATION_REFRESH_MS. (Model-handed-off planes also read show=false // here; harmless — the model branch below `continue`s past the rotation.) - const revealed = !beyondHorizon && !bb.show; - if (bb.show === beyondHorizon) bb.show = !beyondHorizon; + const revealed = !beyondHorizon && !icon.show; + if (icon.show === beyondHorizon) setBillboard(bb, 'show', !beyondHorizon); if (beyondHorizon) { // Also hide any 3D model — otherwise a model that crossed the limb would keep // rendering through the hidden globe at its last matrix. @@ -968,22 +973,22 @@ export function createRendering({ // untouched and multiplicative; there is no cull or zero-alpha path. const cameraDistanceM = Cesium.Cartesian3.distance( camera.positionWC, - bb.position, + icon.position, ); const distanceScale = nearFarScalarValueAtDistance( - bb.scaleByDistance, + icon.scaleByDistance, cameraDistanceM, ); const focus = advanceProjectedSpriteFocus( bb, - bb.position, + icon.position, scene, camera, nowMs, focusTarget, undefined, - (bb.width || 20) * (bb.scale || 1) * distanceScale * 0.5, - (bb.height || 20) * (bb.scale || 1) * distanceScale * 0.5, + (icon.width || 20) * (icon.scale || 1) * distanceScale * 0.5, + (icon.height || 20) * (icon.scale || 1) * distanceScale * 0.5, ); const isCockpitNear = flightState._cockpitContactMode && @@ -1007,8 +1012,8 @@ export function createRendering({ // focus/limb recession counts) with hysteresis (atlas has no mips). if (!flightState._cockpitContactMode || isCockpitNear) { const glyphDevPx = - (bb.width || 20) * - (bb.scale || 1) * + (icon.width || 20) * + (icon.scale || 1) * distanceScale * (globalThis.devicePixelRatio || 1); const visual = aircraftVisuals.write(bb); @@ -1087,12 +1092,12 @@ export function createRendering({ ) { const rot = screenProjectedRotation( scene, - bb.position, + icon.position, course, - bb.rotation, + icon.rotation, ); - if (rot !== null && Math.abs(rot - bb.rotation) > 0.002) { - bb.rotation = rot; + if (rot !== null && Math.abs(rot - icon.rotation) > 0.002) { + setBillboard(bb, 'rotation', rot); } } } diff --git a/src/layers/military/snapshotRenderer.js b/src/layers/military/snapshotRenderer.js index 7ed2b1c1fe..5473595598 100644 --- a/src/layers/military/snapshotRenderer.js +++ b/src/layers/military/snapshotRenderer.js @@ -9,6 +9,7 @@ import { import { aircraftIcon } from '../../data/aircraftIcons.js'; import { POSITION_HISTORY_LIMIT } from './recordPolicy.js'; import { BILLBOARD_SCALE, GROUND_SCALE, TRACKED_ICON_COLOR } from './policy.js'; +import { addBillboard, setBillboard } from '../../data/billboardMirror.js'; /** Apply military record changes to Cesium resources and existing follow operations. */ export function createMilitarySnapshotRenderer({ @@ -150,7 +151,7 @@ export function createMilitarySnapshotRenderer({ // it ahead until the next fleet tick snapped it back. const displayed = motion._deadReckon(icao24, new Cesium.Cartesian3()) || position; - const bb = flightState._billboardCollection.add({ + const bb = addBillboard(flightState._billboardCollection, { position: displayed, image: aircraftIcon(rendering._iconKind(icao24, meta.klass)), width: isTracked ? 24 : 20, @@ -226,7 +227,7 @@ export function createMilitarySnapshotRenderer({ if (newest) newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position); const bbStale = flightState._billboards.get(icao24); - if (bbStale) bbStale.position = liftedPos; + if (bbStale) setBillboard(bbStale, 'position', liftedPos); } // Round 4: sample the RENDERED mesh for those cells (one-shot per cell, // budget-capped, viewer-proximate, google-3d regime only), excluding diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index 15ab140504..fa43ed0fc4 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -1,4 +1,5 @@ import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js'; +import { mirrorBillboard } from '../../data/billboardMirror.js'; export function createTesting({ flightState, @@ -39,7 +40,7 @@ export function createTesting({ flightState._viewer = viewer; flightState._modelCollection = modelCollection; flightState._billboardCollection = billboardCollection; - flightState._billboards = new Map([[icao24, billboard]]); + flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); flightState._cullPositions.clear(); flightState._models.clear(); for (const [key, model] of models) flightState._models.set(key, model); @@ -86,7 +87,7 @@ export function createTesting({ billboard, history = [], }) { - flightState._billboards.set(icao24, billboard); + flightState._billboards.set(icao24, mirrorBillboard(billboard)); flightState.records.data.set(icao24, meta); flightState._positionHistory.set(icao24, history); } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 16252caca1..7000950adf 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -27,6 +27,7 @@ import { } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createTracking({ flightState, @@ -64,7 +65,7 @@ export function createTracking({ function _publishTrackedSelection(icao24, origin = 'programmatic') { const bb = flightState._billboards.get(icao24); const info = flightState.records.data.get(icao24); - if (!bb?.position || !info) return false; + if (!billboardState(bb)?.position || !info) return false; if (flightState._trackedEntity) entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { @@ -74,7 +75,7 @@ export function createTracking({ parts.queries._toCleanText(info.callsign) || parts.queries._toCleanText(info.registration) || icao24, - position: Cesium.Cartesian3.clone(bb.position), + position: Cesium.Cartesian3.clone(billboardState(bb).position), origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(icao24)); @@ -151,12 +152,13 @@ export function createTracking({ const previous = flightState._cockpitNearContacts; const distancesSquared = []; for (const [icao24, bb] of flightState._billboards) { - if (icao24 === flightState._trackedIcao || !bb?.position) continue; + const position = billboardState(bb)?.position; + if (icao24 === flightState._trackedIcao || !position) continue; distancesSquared.push([ icao24, Cesium.Cartesian3.distanceSquared( flightState._viewer.camera.positionWC, - bb.position, + position, ), ]); } @@ -295,7 +297,8 @@ export function createTracking({ if (flightState._models.has(id) || flightState._modelPending.has(id)) parts.rendering._releaseModel(id); const modelled = flightState._billboards.get(id); - if (modelled && id !== flightState._trackedIcao) modelled.show = true; // horizon cull re-asserts next tick + if (modelled && id !== flightState._trackedIcao) + setBillboard(modelled, 'show', true); // horizon cull re-asserts next tick if (id === flightState._trackedIcao) { parts.rendering._releaseTrackedModel(); _syncTracked2dRotation(); @@ -411,7 +414,8 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - flightState._billboards.get(flightState._trackedIcao)?.position; + billboardState(flightState._billboards.get(flightState._trackedIcao)) + ?.position; if (!pos) return; const projected = screenProjectedRotation( flightState._viewer.scene, @@ -780,21 +784,24 @@ export function createTracking({ if (flightState._billboards.has(flightState._trackedIcao)) { const bb = flightState._billboards.get(flightState._trackedIcao); const meta = flightState.records.data.get(flightState._trackedIcao); - bb.show = true; - bb.width = 20; - bb.height = 20; + setBillboard(bb, 'show', true); + setBillboard(bb, 'width', 20); + setBillboard(bb, 'height', 20); // Ground-aware restore (a plane untracked while taxiing comes back at // ground scale; the fleet tint is amber, or red while broadcasting an // emergency, on the ground and in the air). - bb.scale = + setBillboard( + bb, + 'scale', BILLBOARD_SCALE * - (CLASS_SCALE_2D[meta?.klass] || 1) * - (meta?.onGround ? GROUND_SCALE : 1); + (CLASS_SCALE_2D[meta?.klass] || 1) * + (meta?.onGround ? GROUND_SCALE : 1), + ); bb.color = parts.rendering._fleetBillboardColor( flightState._trackedIcao, meta, ); - bb.rotation = flightState._lastTrackedRotation; + setBillboard(bb, 'rotation', flightState._lastTrackedRotation); } flightState._lastCamPoseSig = ''; // force a fleet rotation pass on the next tick @@ -869,21 +876,22 @@ export function createTracking({ flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget flightState._cachedDRFrame = -1; - flightState._lastTrackedRotation = bb.rotation || 0; + flightState._lastTrackedRotation = billboardState(bb).rotation || 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. parts.rendering._releaseModel(icao24); // Hide the billboard -- the tracked entity replaces it visually - bb.show = false; + setBillboard(bb, 'show', false); // Helper: smoothed, per-frame-cached tracked position (see _trackedDisplayPosition — // one computation shared by the position/rotation/trail-head callbacks, with // discontinuity reconciliation). Falls back to the last billboard position when the // aircraft has no fix. const getTrackedPosition = () => - parts.motion._trackedDisplayPosition(icao24) || bb.position; + parts.motion._trackedDisplayPosition(icao24) || + billboardState(bb).position; // Dead-reckoning position property evaluated every render frame. // isConstant = false so CesiumJS re-evaluates each frame. From 6639c4bb80f7aad87b195eeb3695a10055dc2608 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 11:14:33 -0800 Subject: [PATCH 007/470] Read vessel, CCTV and FIRMS billboard state from the app's mirror The three layers now add their billboards through addBillboard and write the mirrored fields through setBillboard, so selection, cards, queries, focus, view thinning and the FIRMS horizon cull read what was pushed from the app instead of from Cesium. Vessels and FIRMS state their sprites' own sizes (32 px ship artwork, the glow canvas at twice the core size), which the mirror needs. A vessel helper, iconPosition, replaces the repeated mirror-or-visual position lookups, and the vessel visibility pass writes show only when it changes, as CCTV and FIRMS already did. A billboard never given a position now has none in the mirror rather than the origin. --- scripts/package-boundaries.json | 5 +++ src/data/aisLiveVessels.test.mjs | 34 +++++++++++--------- src/data/billboardMirror.js | 12 +++---- src/data/billboardMirror.test.mjs | 2 +- src/data/cctv.test.mjs | 7 ++-- src/data/cctvViewThinning.test.mjs | 9 ++++-- src/data/firmsHorizonCull.test.mjs | 5 +-- src/data/focusResumeGate.test.mjs | 9 +++--- src/layers/cctv/geometry.js | 3 +- src/layers/cctv/ground.js | 4 ++- src/layers/cctv/lifecycle.js | 3 +- src/layers/cctv/rendering.js | 18 +++++++---- src/layers/cctv/rendering.test.mjs | 3 +- src/layers/firms/model.js | 12 ++++--- src/layers/firms/rendering.js | 9 ++++-- src/layers/vessels/cards.js | 8 ++--- src/layers/vessels/evidence.js | 8 +++-- src/layers/vessels/ownership.test.mjs | 4 +-- src/layers/vessels/queries.js | 16 ++++------ src/layers/vessels/rendering.js | 44 ++++++++++++++++++-------- src/layers/vessels/selection.js | 19 +++++++---- src/layers/vessels/snapshotRenderer.js | 11 +++++-- src/layers/vessels/tracking.js | 4 ++- 23 files changed, 152 insertions(+), 97 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index f469c92da5..ee13c0f9d0 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1447,6 +1447,8 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/data/entityRecords.js", + "src/data/billboardMirror.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -1528,6 +1530,8 @@ "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", + "src/data/entityRecords.js", + "src/data/billboardMirror.js", "src/layers/firms/selection.js", "src/layers/firms/source.js", "src/layers/firms/state.js", @@ -1857,6 +1861,7 @@ "src/layers/cctv/projection.js", "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", + "src/data/billboardMirror.js", "src/layers/cctv/selection.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 8e12bff949..210f6aa431 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -39,6 +39,7 @@ import { presentSelectedVessel, subscribeSelectedVessel, } from '../hudReadouts.js'; +import { mirrorBillboard, setBillboard } from './billboardMirror.js'; test('open feed with vessels is healthy (null)', () => { assert.equal(deriveAisFeedError({ status: 'open', lastMessageAt: 1, error: null }, 42), null); @@ -659,12 +660,12 @@ test('vessel focus wire animates alpha with deadband and restores after tracking let writes = 0; const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); let color = makeColor(1); - const billboard = { + const billboard = mirrorBillboard({ position: { x: 1, y: 2, z: 3 }, show: true, get color() { return color; }, set color(next) { writes += 1; color = next; }, - }; + }); const records = [{ position: billboard.position, billboard }]; const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, @@ -713,12 +714,12 @@ test('vessel focus wire animates alpha with deadband and restores after tracking test('vessel focus wire performs no alpha writes when nothing has been tracked', () => { let writes = 0; - const billboard = { + const billboard = mirrorBillboard({ position: { x: 0, y: 0, z: 0 }, show: true, get color() { return { alpha: 1 }; }, set color(_next) { writes += 1; }, - }; + }); const result = applyVesselFocusDeemphasis({ records: [{ position: billboard.position, billboard }], target: null, @@ -737,11 +738,11 @@ test('vessel focus wire performs no alpha writes when nothing has been tracked', test('vessel focus wire restores a hidden sprite before releasing the active pass', () => { const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); - const billboard = { + const billboard = mirrorBillboard({ position: { x: 1, y: 2, z: 3 }, show: true, color: makeColor(1), - }; + }); const records = [{ billboard }]; const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, @@ -771,7 +772,7 @@ test('vessel focus wire restores a hidden sprite before releasing the active pas assert.equal(dimmed.activeCount, 1); assert.equal(billboard.color.alpha, params.dimFloor); - billboard.show = false; + setBillboard(billboard, 'show', false); const releaseStart = pass(params.attackMs, null, dimmed.activeCount); const restored = pass(params.attackMs + params.releaseMs, null, releaseStart.activeCount); assert.equal(restored.ran, true); @@ -1350,9 +1351,11 @@ test('buildVesselCard: unnamed vessels title as MMSI; long names truncate', () = }); test('buildVesselCard: anchors to the billboard position when present', () => { - const rendered = { x: 9, y: 9, z: 9 }; - const card = buildVesselCard(makeRecord({ billboard: { position: rendered } })); - assert.equal(card.position, rendered); + const rendered = new Cesium.Cartesian3(9, 9, 9); + const card = buildVesselCard( + makeRecord({ billboard: mirrorBillboard({ position: rendered }) }), + ); + assert.deepEqual(card.position, rendered); }); test('buildVesselCard: tanker types carry the amber accent', () => { @@ -1742,11 +1745,12 @@ test('vessel selection passes the opaque source reference to optional history', test('vessel focus wire skips hidden sprites at rest while a target is tracked', () => { const makeColor = (alpha) => ({ alpha, withAlpha: (next) => makeColor(next) }); - const sprite = (show) => ({ - position: { x: 1, y: 2, z: 3 }, - show, - color: makeColor(1), - }); + const sprite = (show) => + mirrorBillboard({ + position: { x: 1, y: 2, z: 3 }, + show, + color: makeColor(1), + }); const visible = sprite(true); const hidden = Array.from({ length: 50 }, () => sprite(false)); const records = [visible, ...hidden].map((billboard) => ({ diff --git a/src/data/billboardMirror.js b/src/data/billboardMirror.js index 5e2676098f..8b97b479ff 100644 --- a/src/data/billboardMirror.js +++ b/src/data/billboardMirror.js @@ -31,12 +31,10 @@ const DEFAULTS = Object.freeze({ /** Cesium copies positions and scalers on write; the mirror keeps its own copy too. */ function copyInto(record, field, value) { if (field === 'position') { - // Cesium keeps its old position when handed none; so does the mirror. - if (!value && record.position) return; - record.position = Cesium.Cartesian3.clone( - value ?? Cesium.Cartesian3.ZERO, - record.position, - ); + // Cesium keeps its old position when handed none; so does the mirror. A + // billboard never given one has none here (Cesium would report the origin). + if (!value) return; + record.position = Cesium.Cartesian3.clone(value, record.position); } else if (field === 'scaleByDistance') { record.scaleByDistance = value ? Cesium.NearFarScalar.clone(value, record.scaleByDistance) @@ -97,7 +95,7 @@ export function setBillboard(billboard, field, value) { * The app's copy of a billboard's mirrored fields, or null when it has none (or * there is no billboard). * @param {Object|null|undefined} billboard - * @returns {{ show: boolean, position: Cesium.Cartesian3, scale: number, + * @returns {{ show: boolean, position?: Cesium.Cartesian3, scale: number, * rotation: number, width?: number, height?: number, * scaleByDistance?: Cesium.NearFarScalar }|null} */ diff --git a/src/data/billboardMirror.test.mjs b/src/data/billboardMirror.test.mjs index 3afb2755c7..67363b3684 100644 --- a/src/data/billboardMirror.test.mjs +++ b/src/data/billboardMirror.test.mjs @@ -62,7 +62,7 @@ test('a billboard the app did not add can be mirrored from its fields', () => { const bb = mirrorBillboard({ show: false, scale: 2 }); assert.equal(billboardState(bb).show, false); assert.equal(billboardState(bb).scale, 2); - assert.ok(Cesium.Cartesian3.equals(billboardState(bb).position, Cesium.Cartesian3.ZERO)); + assert.equal(billboardState(bb).position, undefined, 'none was pushed'); assert.equal(billboardState(null), null); assert.equal(mirrorBillboard(null), null); }); diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index f76acdb727..d7cc131b58 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -79,6 +79,7 @@ import { IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; +import { mirrorBillboard } from './billboardMirror.js'; const ASPECT = 16 / 9; const toRad = (deg) => (deg * Math.PI) / 180; @@ -355,7 +356,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { const record = (id, feedType) => ({ camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, - billboard: {}, + billboard: mirrorBillboard({}), coverageEntities: [], projection: null, }); @@ -682,7 +683,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou camera: { id: 'a' }, activationDone: true, probeClampRangeM: 105, - billboard: { color: 'keep-color', scale: 1.25 }, + billboard: mirrorBillboard({ color: 'keep-color', scale: 1.25 }), coverageEntities: [{ show: true }, { show: true }], projection: { planeEntity: { show: true } }, viewshedPrimitive: viewshedA, @@ -691,7 +692,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou camera: { id: 'b' }, activationDone: true, probeClampRangeM: 146, - billboard: { color: 'keep-color', scale: 1 }, + billboard: mirrorBillboard({ color: 'keep-color', scale: 1 }), projection: null, viewshedPrimitive: viewshedB, }, diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 1bc94eed8a..62eacbab6d 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -10,6 +10,7 @@ import cctvLayer, { _viewRecordIdsForTest, refreshHorizonCulling, } from './cctv.js'; +import { mirrorBillboard } from './billboardMirror.js'; const WIDTH = 800; const HEIGHT = 600; @@ -40,7 +41,7 @@ function recordsAt( mountHeightM: 8, }, position, - billboard: { position, show: true }, + billboard: mirrorBillboard({ position, show: true }), coverageEntities: [], projection: null, }; @@ -59,7 +60,11 @@ function viewerAt(heightM, screenByPosition, shiftX = 0) { scene: { canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, cartesianToCanvasCoordinates: (position) => { - const screen = screenByPosition.get(position); + // The mirror holds its own copy of each position, so match by value. + const key = [...screenByPosition.keys()].find((candidate) => + Cesium.Cartesian3.equals(candidate, position), + ); + const screen = screenByPosition.get(key); return screen && { x: screen.x + shiftX, y: screen.y }; }, }, diff --git a/src/data/firmsHorizonCull.test.mjs b/src/data/firmsHorizonCull.test.mjs index 198ffefdc2..277e4f4839 100644 --- a/src/data/firmsHorizonCull.test.mjs +++ b/src/data/firmsHorizonCull.test.mjs @@ -15,6 +15,7 @@ import { } from './groundFloor.js'; import { unregisterSpriteCollection } from './spriteOrder.js'; import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldOverlay.js'; +import { mirrorBillboard } from './billboardMirror.js'; const AUSTIN = { lon: -97.7, lat: 30.2 }; /** Antipode of Austin — as far behind the limb as a point on Earth can be. */ @@ -34,13 +35,13 @@ const LIMB_DLON = 41.87; * the pass does not dirty the collection's vertex buffer needlessly. */ function billboard(position, show = true) { - return { + return mirrorBillboard({ position, _show: show, writes: 0, get show() { return this._show; }, set show(value) { this._show = value; this.writes += 1; }, - }; + }); } /** Cesium BillboardCollection-shaped stub. */ diff --git a/src/data/focusResumeGate.test.mjs b/src/data/focusResumeGate.test.mjs index ecd30e831a..93d4c2ba1e 100644 --- a/src/data/focusResumeGate.test.mjs +++ b/src/data/focusResumeGate.test.mjs @@ -4,6 +4,7 @@ import { applyVesselFocusDeemphasis } from './aisLiveVessels.js'; import { applyCctvFocusDeemphasis } from './cctv.js'; import { applySatellitePointFocusDeemphasis } from './satellites.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; +import { mirrorBillboard } from './billboardMirror.js'; const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 }; const target = { @@ -51,14 +52,14 @@ function assertResumeGate(name, makePass) { } assertResumeGate('vessel', () => { - const billboard = { + const billboard = mirrorBillboard({ position: { x: 1, y: 2, z: 3 }, show: true, width: 32, height: 32, scale: 1, color: color(), - }; + }); return { pass: ({ nowMs, target: focusTarget, previousActiveCount }) => ( applyVesselFocusDeemphasis({ @@ -76,14 +77,14 @@ assertResumeGate('vessel', () => { }); assertResumeGate('CCTV', () => { - const billboard = { + const billboard = mirrorBillboard({ position: { x: 1, y: 2, z: 3 }, show: true, width: 24, height: 24, scale: 1, color: color(), - }; + }); const record = { camera: { id: 'cam-1' }, billboard }; return { pass: ({ nowMs, target: focusTarget, previousActiveCount }) => ( diff --git a/src/layers/cctv/geometry.js b/src/layers/cctv/geometry.js index 808ddda250..7a816374d9 100644 --- a/src/layers/cctv/geometry.js +++ b/src/layers/cctv/geometry.js @@ -16,6 +16,7 @@ import { poseHash, requiredPlaneLift, } from '../../data/cctvFootprint.js'; +import { setBillboard } from '../../data/billboardMirror.js'; export function createGeometry({ state: layerState, services, parts, source }) { const { warmGroundFloor, cachedGroundFloor } = services.ground; @@ -347,7 +348,7 @@ export function createGeometry({ state: layerState, services, parts, source }) { record.position = positions.mount; record.camera.absoluteHeightM = geometry.mount.alt; if (record.billboard) { - record.billboard.position = positions.mount; + setBillboard(record.billboard, 'position', positions.mount); } if (record.coverageEntities?.length >= 5) { record.coverageEntities[0].polyline.positions = [ diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index fdf36db148..a7e610c4df 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -4,6 +4,7 @@ import { planeSupportPoints, poseHash, } from '../../data/cctvFootprint.js'; +import { setBillboard } from '../../data/billboardMirror.js'; /** Cooldown before a provisional (geoid-fallback / partial) footprint is retried. */ const FOOTPRINT_RETRY_MS = 60_000; @@ -238,7 +239,8 @@ export function createGround({ state: layerState, services, parts, source }) { undefined, record.position, ); - if (record.billboard) record.billboard.position = record.position; + if (record.billboard) + setBillboard(record.billboard, 'position', record.position); moved += 1; } continue; diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 4e4443df8f..40ccf84019 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -12,6 +12,7 @@ import { VIEW_MOTION_MIN_TURN_DEG, VIEW_MOTION_COST_FACTOR, } from './policy.js'; +import { addBillboard } from '../../data/billboardMirror.js'; const MIN_TURN_COS = Math.cos((VIEW_MOTION_MIN_TURN_DEG * Math.PI) / 180); @@ -237,7 +238,7 @@ export function createLifecycle({ camera.lat, camera.absoluteHeightM, ); - const billboard = layerState._billboards.add({ + const billboard = addBillboard(layerState._billboards, { id: camera.id, image: CAMERA_ICON, position, diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 4b6f215e47..36ac3d8d43 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -14,6 +14,7 @@ import { VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, } from './policy.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; /** FNV-1a over a camera id: a stable, well-spread order for crowded cells. */ function idHash(id) { @@ -110,19 +111,20 @@ export function createRendering({ for (const record of records || []) { const bb = record.billboard; if (!bb) continue; - const position = bb.position; + const icon = billboardState(bb); + const position = icon.position; // CCTV never publishes a tracked focus target, so every icon is ambient. const focus = advanceSpriteFocus(bb, { // Keep hidden icons in the state/release pass so the active count cannot // drop while a stale dim alpha remains waiting to reappear. screenPosition: - bb.show === false || !position ? null : screenPositionFor(position), + icon.show === false || !position ? null : screenPositionFor(position), cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, target, params, - spriteHalfWidthPx: (bb.width || 24) * (bb.scale || 1) * 0.5, - spriteHalfHeightPx: (bb.height || 24) * (bb.scale || 1) * 0.5, + spriteHalfWidthPx: (icon.width || 24) * (icon.scale || 1) * 0.5, + spriteHalfHeightPx: (icon.height || 24) * (icon.scale || 1) * 0.5, }); transitioning ||= focus.transitioning; if (focus.active) activeCount += 1; @@ -200,7 +202,7 @@ export function createRendering({ const shown = []; const cells = new Map(); for (const record of layerState._records) { - const position = record.billboard?.position; + const position = billboardState(record.billboard)?.position; if (!position) continue; const vx = position.x * inverseRadii.x - cx; const vy = position.y * inverseRadii.y - cy; @@ -245,7 +247,8 @@ export function createRendering({ const bb = record.billboard; if (!bb) continue; const visible = record.viewPass === pass; - if (bb.show !== visible) bb.show = visible; + if (billboardState(bb).show !== visible) + setBillboard(bb, 'show', visible); } const previous = layerState._viewRecords; const changed = @@ -397,7 +400,8 @@ export function createRendering({ if (!Cesium.Color.equals(record.billboard.color, color)) record.billboard.color = color; const scale = isActive ? 1.25 : 1.0; - if (record.billboard.scale !== scale) record.billboard.scale = scale; + if (billboardState(record.billboard).scale !== scale) + setBillboard(record.billboard, 'scale', scale); // disableDepthTestDistance stays POSITIVE_INFINITY for every billboard // (set at creation) — see the field-test far-zoom submerge fix there. } diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index c4b490dd2b..4ba0c2b022 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -11,6 +11,7 @@ import { LIVE_CAMERA_COLOR, } from './policy.js'; import { isVideoFeedType } from '../../sources/cctvTypes.js'; +import { mirrorBillboard } from '../../data/billboardMirror.js'; const FOCUS_FACTOR = 0.5; @@ -29,7 +30,7 @@ test('focus de-emphasis fades each icon from its own color', () => { camera: { id, feedType }, // No position, so the pass skips screen projection; the focus stub below // decides the factor on its own. - billboard: { show: true }, + billboard: mirrorBillboard({ show: true }), }); const idleVideo = record('idle-hls', 'hls'); const idleStill = record('idle-image', 'image'); diff --git a/src/layers/firms/model.js b/src/layers/firms/model.js index 9e3cf7f95c..1c58738122 100644 --- a/src/layers/firms/model.js +++ b/src/layers/firms/model.js @@ -13,6 +13,7 @@ import { CULL_LIFT_M, LABEL_MIN_SEP_PX, } from './policy.js'; +import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createModel({ layerState, @@ -273,9 +274,9 @@ export function createModel({ * the opposite side of the Earth shine through the planet at tilted mid-altitude * views. Same pattern as the flights/CCTV layers' `EllipsoidalOccluder` passes. * - * Pure and allocation-free: reads `billboard.position`, writes `billboard.show` - * only when it actually flips (assigning `show` dirties the collection's vertex - * buffer). Accepts any `{length, get(i)}` shape so it is unit-testable without + * Pure and allocation-free: reads the billboard's mirrored position and show, + * and writes `show` only when it actually flips (assigning `show` dirties the + * collection's vertex buffer). Accepts any `{length, get(i)}` shape so it is unit-testable without * a WebGL scene. * * @param {?{length: number, get: function(number): (Object|undefined)}} billboards @@ -295,9 +296,10 @@ export function createModel({ for (let i = 0; i < total; i += 1) { const billboard = billboards.get(i); if (!billboard) continue; - const point = (cullPositions && cullPositions[i]) || billboard.position; + const pushed = billboardState(billboard); + const point = (cullPositions && cullPositions[i]) || pushed.position; const visible = occluder.isPointVisible(point) === true; - if (billboard.show !== visible) billboard.show = visible; + if (pushed.show !== visible) setBillboard(billboard, 'show', visible); if (visible) visibleCount += 1; } return visibleCount; diff --git a/src/layers/firms/rendering.js b/src/layers/firms/rendering.js index 8ae445f913..2694bfa1da 100644 --- a/src/layers/firms/rendering.js +++ b/src/layers/firms/rendering.js @@ -2,6 +2,7 @@ import * as Cesium from 'cesium'; import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js'; import { horizonOccluder } from '../../data/iconOrientation.js'; import { LOD_LEVELS, CONTEXT_TOP_N } from './policy.js'; +import { addBillboard } from '../../data/billboardMirror.js'; export function createRendering({ layerState, @@ -237,13 +238,17 @@ export function createRendering({ const pickId = `firms-${fire.index}`; layerState._pickIndexById.set(pickId, fire); layerState._cullPositions.push(cullPosition); - layerState._billboards.add({ + const corePx = components.model.sizeBucket(coreSize); + addBillboard(layerState._billboards, { id: pickId, position, image: components.model.glowSprite( components.model.detectionColorStop(fire), - components.model.sizeBucket(coreSize), + corePx, ), + // The glow sprite's own size (see glowSprite), stated for the app's mirror. + width: corePx * 2, + height: corePx * 2, verticalOrigin: Cesium.VerticalOrigin.CENTER, horizontalOrigin: Cesium.HorizontalOrigin.CENTER, disableDepthTestDistance: Number.POSITIVE_INFINITY, diff --git a/src/layers/vessels/cards.js b/src/layers/vessels/cards.js index bcf3459f17..4666228d8c 100644 --- a/src/layers/vessels/cards.js +++ b/src/layers/vessels/cards.js @@ -61,9 +61,7 @@ export function createCards({ return { id: vesselOverlayEntryId(record), actionable: Boolean(record?.mmsi), - position: - components.rendering.getVisual(record).billboard?.position || - components.rendering.getVisual(record).position, + position: components.rendering.iconPosition(record), gapPx: 10, accent: accentForVesselType(record.type), title: trimHudValue(displayVesselName(record), 26), @@ -102,9 +100,7 @@ export function createCards({ return { id: vesselOverlayEntryId(record), actionable: Boolean(record?.mmsi), - position: - components.rendering.getVisual(record).billboard?.position || - components.rendering.getVisual(record).position, + position: components.rendering.iconPosition(record), gapPx: 12, accent: accentForVesselType(record.type), title: trimHudValue(displayVesselName(record), 32), diff --git a/src/layers/vessels/evidence.js b/src/layers/vessels/evidence.js index c5e593e267..9cbf6521ac 100644 --- a/src/layers/vessels/evidence.js +++ b/src/layers/vessels/evidence.js @@ -1,5 +1,6 @@ import * as Cesium from 'cesium'; import { FOCUS_EVIDENCE_DEV } from './policy.js'; +import { billboardState } from '../../data/billboardMirror.js'; export function createEvidence({ vesselState, @@ -40,15 +41,16 @@ export function createEvidence({ if (!FOCUS_EVIDENCE_DEV || !state.viewer) return []; return state.records.all.map((record) => { const bb = components.rendering.getVisual(record).billboard; - const screen = bb?.position + const icon = billboardState(bb); + const screen = icon?.position ? Cesium.SceneTransforms.worldToWindowCoordinates( state.viewer.scene, - bb.position, + icon.position, ) : null; return { id: record.mmsi, - show: bb?.show === true, + show: icon?.show === true, alpha: bb?.color?.alpha ?? null, x: screen?.x ?? null, y: screen?.y ?? null, diff --git a/src/layers/vessels/ownership.test.mjs b/src/layers/vessels/ownership.test.mjs index 4ef9b75253..d5cd274c25 100644 --- a/src/layers/vessels/ownership.test.mjs +++ b/src/layers/vessels/ownership.test.mjs @@ -292,7 +292,7 @@ test('refresh keeps pick identity and renderer geometry separate, and eviction r for (const key of ['position', 'surfacePosition', 'normal', 'billboard']) { assert.equal(Object.hasOwn(record, key), false); } - assert.equal(layer.findByQuery('111').position, primitive.position); + assert.deepEqual(layer.findByQuery('111').position, primitive.position); const oldPosition = primitive.position; current = snapshot([{ ...observation('111'), longitude: 4.06 }]); await layer.update(); @@ -300,7 +300,7 @@ test('refresh keeps pick identity and renderer geometry separate, and eviction r assert.equal([...primitives][0], primitive); assert.equal(primitive.id, record); assert.notDeepEqual(primitive.position, oldPosition); - assert.equal(layer.findByQuery('111').position, primitive.position); + assert.deepEqual(layer.findByQuery('111').position, primitive.position); current = snapshot([observation('222')]); await layer.update(); assert.equal(primitives.has(primitive), false); diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index c848acc2d0..56d86e104e 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -21,6 +21,7 @@ import { REFRESH_MS, FOCUS_EVIDENCE_DEV, } from './policy.js'; +import { billboardState } from '../../data/billboardMirror.js'; export function createQueries({ vesselState, @@ -295,9 +296,7 @@ export function createQueries({ } if (!record) return null; - const position = - components.rendering.getVisual(record).billboard?.position || - components.rendering.getVisual(record).position; + const position = components.rendering.iconPosition(record); if (!position) return null; return { mmsi: record.mmsi, @@ -328,10 +327,9 @@ export function createQueries({ const entries = []; for (const record of records) { - const visual = components.rendering.getVisual(record); if (!Number.isFinite(record.lat) || !Number.isFinite(record.lon)) continue; - const position = visual.billboard?.position || visual.position; + const position = components.rendering.iconPosition(record); if (!position) continue; const distanceM = Cesium.Cartesian3.distance(centerCartesian, position); if (!Number.isFinite(distanceM) || distanceM > range) continue; @@ -381,9 +379,8 @@ export function createQueries({ Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 800; for (const record of records) { - const visual = components.rendering.getVisual(record); if (result.length >= cap) break; - const position = visual.billboard?.position || visual.position; + const position = components.rendering.iconPosition(record); if (!position) continue; result.push({ id: record.mmsi, @@ -495,8 +492,9 @@ export function createQueries({ if ((idx - start) % stride !== 0) continue; const record = records[idx]; const visual = components.rendering.getVisual(record); - if (visual.billboard && !visual.billboard.show) continue; - const position = visual.billboard?.position || visual.position; + const icon = billboardState(visual.billboard); + if (icon && !icon.show) continue; + const position = icon?.position || visual.position; if (!position) continue; result.push({ position, diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index 328dd4aee3..a7fdf726a5 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -20,6 +20,11 @@ import { LABEL_GRID_PX, CARD_MIN_SEP_PX, } from './policy.js'; +import { + addBillboard, + billboardState, + setBillboard, +} from '../../data/billboardMirror.js'; export function createRendering({ vesselState, @@ -36,6 +41,12 @@ export function createRendering({ return visualRecords.get(record) || record; } + /** Where a record's icon was drawn, from the app's mirror, else its visual position. */ + function iconPosition(record) { + const visual = getVisual(record); + return billboardState(visual.billboard)?.position || visual.position; + } + function prepareRecordVisual(record) { let visual = visualRecords.get(record); if (!visual) { @@ -121,10 +132,13 @@ export function createRendering({ const visible = state.feed.enabled && isVisible(getVisual(record).surfacePosition, occluder); - getVisual(record).billboard = state.billboardCollection.add({ + getVisual(record).billboard = addBillboard(state.billboardCollection, { position: getVisual(record).position, show: visible, image: shipIcon(record, false), + // The ship artwork's own size, stated so the app's mirror knows it. + width: 32, + height: 32, scale: shipScale(record), // Screen-projected rotation lands on the next visibility/rotation pass. rotation: 0, @@ -286,19 +300,18 @@ export function createRendering({ const visual = getVisual(record); const visible = isVisible(visual.surfacePosition, occluder); if (visual.billboard) { - visual.billboard.show = visible; + if (billboardState(visual.billboard).show !== visible) + setBillboard(visual.billboard, 'show', visible); if (visible && doRotations && scene) { + const { rotation } = billboardState(visual.billboard); const rot = screenProjectedRotation( scene, visual.position, vesselCourseDeg(record), - visual.billboard.rotation, + rotation, ); - if ( - rot !== null && - Math.abs(rot - visual.billboard.rotation) > 0.002 - ) { - visual.billboard.rotation = rot; + if (rot !== null && Math.abs(rot - rotation) > 0.002) { + setBillboard(visual.billboard, 'rotation', rot); } } } @@ -353,14 +366,15 @@ export function createRendering({ for (const record of records || []) { const visual = getVisual(record); const bb = visual?.billboard; - const position = bb?.position || visual?.position; + const icon = billboardState(bb); + const position = icon?.position || visual?.position; if (!bb || !position) continue; // Most of a worldwide feed sits behind the horizon. A hidden sprite with // no pending focus state and full alpha would advance to exactly what it // already is, so skip it instead of paying its distance and state work // every 80 ms while anything is tracked. if ( - bb.show === false && + icon.show === false && spriteFocusAtRest(bb) && !focusAlphaNeedsWrite(bb.color?.alpha, 1, params) ) @@ -368,15 +382,16 @@ export function createRendering({ const focus = advanceSpriteFocus(bb, { // Hidden/far-side sprites still finish any pending release so the active // count remains truthful and they cannot reappear with stale dim alpha. - screenPosition: bb.show === false ? null : screenPositionFor(position), + screenPosition: + icon.show === false ? null : screenPositionFor(position), cameraDistance: cameraDistanceFor(position), nowMs, target, params, // Vessel artwork is 32 px before billboard scale. Including the // ambient chevron's own rendered extent prevents edge-overlap misses. - spriteHalfWidthPx: (bb.width || 32) * (bb.scale || 1) * 0.5, - spriteHalfHeightPx: (bb.height || 32) * (bb.scale || 1) * 0.5, + spriteHalfWidthPx: (icon.width || 32) * (icon.scale || 1) * 0.5, + spriteHalfHeightPx: (icon.height || 32) * (icon.scale || 1) * 0.5, }); transitioning ||= focus.transitioning; if (focus.active) activeCount += 1; @@ -461,7 +476,7 @@ export function createRendering({ if (selected) { const screen = Cesium.SceneTransforms.worldToWindowCoordinates( scene, - getVisual(selected).billboard?.position || getVisual(selected).position, + iconPosition(selected), ); if (screen) accepted.push({ x: screen.x, y: screen.y }); } @@ -561,6 +576,7 @@ export function createRendering({ } return { getVisual, + iconPosition, prepareRecordVisual, resetRecordVisuals, renderRowLimit, diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index 96c5df6ebd..42e6b7ae5a 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -1,6 +1,7 @@ import * as Cesium from 'cesium'; import { isPointerFree } from '../../data/inputOwnership.js'; import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; +import { setBillboard } from '../../data/billboardMirror.js'; export function createSelection({ vesselState, @@ -131,9 +132,7 @@ export function createSelection({ kind: 'vessel', id: record.mmsi, label: record.name || record.mmsi, - position: - components.rendering.getVisual(record).billboard?.position || - components.rendering.getVisual(record).position, + position: components.rendering.iconPosition(record), }); return true; } @@ -174,8 +173,11 @@ export function createSelection({ if (components.rendering.getVisual(record).billboard) { components.rendering.getVisual(record).billboard.image = components.rendering.shipIcon(record, true); - components.rendering.getVisual(record).billboard.scale = - components.rendering.shipScale(record) * 1.2; + setBillboard( + components.rendering.getVisual(record).billboard, + 'scale', + components.rendering.shipScale(record) * 1.2, + ); } // Rebuild the card set immediately so the full-detail card appears on the // click, not up to VISIBILITY_UPDATE_MS later. @@ -230,8 +232,11 @@ export function createSelection({ if (components.rendering.getVisual(record)?.billboard) { components.rendering.getVisual(record).billboard.image = components.rendering.shipIcon(record, false); - components.rendering.getVisual(record).billboard.scale = - components.rendering.shipScale(record); + setBillboard( + components.rendering.getVisual(record).billboard, + 'scale', + components.rendering.shipScale(record), + ); } state.selectedRecord = null; // Drop the full-detail card right away (no-op when the layer is disabled — diff --git a/src/layers/vessels/snapshotRenderer.js b/src/layers/vessels/snapshotRenderer.js index 03abb81dc3..99c6b47bfe 100644 --- a/src/layers/vessels/snapshotRenderer.js +++ b/src/layers/vessels/snapshotRenderer.js @@ -1,4 +1,6 @@ /** Connect portable vessel reconciliation to scene and selection operations. */ +import { setBillboard } from '../../data/billboardMirror.js'; + export function createVesselSnapshotRenderer({ state, records, @@ -29,9 +31,12 @@ export function createVesselSnapshotRenderer({ const selected = record === state.selectedRecord; const visual = rendering.prepareRecordVisual(record); if (visual.billboard) { - visual.billboard.position = visual.position; - visual.billboard.scale = - rendering.shipScale(record) * (selected ? 1.2 : 1); + setBillboard(visual.billboard, 'position', visual.position); + setBillboard( + visual.billboard, + 'scale', + rendering.shipScale(record) * (selected ? 1.2 : 1), + ); const nextIcon = rendering.shipIcon(record, selected); if (nextIcon !== prevIcon) visual.billboard.image = nextIcon; } diff --git a/src/layers/vessels/tracking.js b/src/layers/vessels/tracking.js index 2c11ff463f..b2faf0cd38 100644 --- a/src/layers/vessels/tracking.js +++ b/src/layers/vessels/tracking.js @@ -6,6 +6,7 @@ import { TRAIL_MAX_POINTS, TRAIL_MIN_MOVE_M, } from './policy.js'; +import { setBillboard } from '../../data/billboardMirror.js'; export function createTracking({ vesselState, @@ -71,7 +72,8 @@ export function createTracking({ record.lat, heightM, ); - if (visual.billboard) visual.billboard.position = visual.position; + if (visual.billboard) + setBillboard(visual.billboard, 'position', visual.position); } } From 05904edfc9120433a642ecc3384e3a08db03f797 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 12:58:50 -0800 Subject: [PATCH 008/470] Read aircraft model placement from the app's mirror Flights, military and local ADS-B now write their models' show and world matrix through setModel in src/data/modelMirror.js, and read them back through modelState: the fleet and tracked handoffs, the tracked visual and trail anchors, detection anchors and modelAnchorWorld. A matrix is copied into the app's record and into the model's own matrix, so the shared scratch can be passed directly and models still never share one matrix object. What Cesium measures (ready, computedScale) is still read from the model, and colour stays live as on billboards, because cyber sonar writes it too. Test seams mirror the models they install, as they do billboards. --- scripts/package-boundaries.json | 6 +++ src/data/modelMirror.js | 74 +++++++++++++++++++++++++++++ src/data/modelMirror.test.mjs | 67 ++++++++++++++++++++++++++ src/data/modelScale.test.mjs | 9 ++-- src/data/modelVisualAnchor.js | 6 ++- src/layers/flights/motion.js | 5 +- src/layers/flights/queries.js | 3 +- src/layers/flights/queries.test.mjs | 27 ++++++----- src/layers/flights/rendering.js | 48 ++++++++++--------- src/layers/flights/testing.js | 4 +- src/layers/localAdsb/models.js | 26 ++++++---- src/layers/military/motion.js | 5 +- src/layers/military/queries.js | 3 +- src/layers/military/rendering.js | 74 ++++++++++++++++++----------- src/layers/military/testing.js | 4 +- 15 files changed, 273 insertions(+), 88 deletions(-) create mode 100644 src/data/modelMirror.js create mode 100644 src/data/modelMirror.test.mjs diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index ee13c0f9d0..e759dd4939 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1315,6 +1315,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelMirror.js", "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", @@ -1376,6 +1377,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/data/modelMirror.js", "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", "src/layers/military/state.js", @@ -1420,6 +1422,8 @@ "src/data/layerStateCoordinator.js", "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", + "src/data/modelMirror.js", + "src/data/entityRecords.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", "src/data/renderAltitude.js", @@ -2543,6 +2547,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelMirror.js", "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", @@ -3453,6 +3458,7 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/data/modelMirror.js", "src/layers/aircraft/visualState.js", "src/layers/flights/state.js", "src/layers/flights/testing.js", diff --git a/src/data/modelMirror.js b/src/data/modelMirror.js new file mode 100644 index 0000000000..5d27be6ef2 --- /dev/null +++ b/src/data/modelMirror.js @@ -0,0 +1,74 @@ +/** + * @module modelMirror + * @description The app's copy of what a layer pushed to its 3D models, so the layer + * reads its own placement back from the app instead of from the renderer's objects. + * + * A layer writes the mirrored fields with {@link setModel} and reads them with + * {@link modelState}. What the renderer measures (`ready`, `computedScale`) is + * still read from the model. Colour stays out for the same reason as on + * billboards: the cyber-sonar theme writes it too and reads the live value. + */ +import * as Cesium from 'cesium'; +import { createEntityStore } from './entityRecords.js'; + +const mirrors = createEntityStore(); + +/** + * The app's record for `model`, made on first write with Cesium's defaults for a + * model loaded without `show` or `modelMatrix` options (shown, at the identity). + */ +function recordFor(model) { + const record = mirrors.write(model); + if (!record.modelMatrix) { + record.show = true; + record.modelMatrix = Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY); + } + return record; +} + +/** + * Start mirroring a model the app did not write itself (test seams), from its + * current fields. + * @param {Object} model + * @returns {Object} The model. + */ +export function mirrorModel(model) { + if (!model || typeof model !== 'object') return model; + const record = recordFor(model); + record.show = model.show ?? true; + if (model.modelMatrix) + Cesium.Matrix4.clone(model.modelMatrix, record.modelMatrix); + return model; +} + +/** + * Write one mirrored field to the model and to the app's copy. A matrix is copied + * into both, so a shared scratch can be passed and reused straight after. + * @param {Object} model + * @param {'show'|'modelMatrix'} field + * @param {*} value + */ +export function setModel(model, field, value) { + if (field !== 'show' && field !== 'modelMatrix') + throw new TypeError(`The model mirror does not hold ${field}`); + const record = recordFor(model); + if (field === 'modelMatrix') { + Cesium.Matrix4.clone(value, record.modelMatrix); + // Cesium clones the model's own matrix each frame, so write into it in place. + if (model.modelMatrix) Cesium.Matrix4.clone(value, model.modelMatrix); + else model.modelMatrix = Cesium.Matrix4.clone(value); + } else { + record[field] = value; + model[field] = value; + } +} + +/** + * The app's copy of a model's mirrored fields, or null when nothing was written to + * it yet (or there is no model). + * @param {Object|null|undefined} model + * @returns {{ show: boolean, modelMatrix: Cesium.Matrix4 }|null} + */ +export function modelState(model) { + return mirrors.read(model); +} diff --git a/src/data/modelMirror.test.mjs b/src/data/modelMirror.test.mjs new file mode 100644 index 0000000000..500ebc6dd4 --- /dev/null +++ b/src/data/modelMirror.test.mjs @@ -0,0 +1,67 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { mirrorModel, modelState, setModel } from './modelMirror.js'; + +function fakeModel() { + return { show: true, modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY) }; +} + +test('a model has no mirror until the app writes to it', () => { + assert.equal(modelState(fakeModel()), null); + assert.equal(modelState(null), null); +}); + +test('the first write starts from Cesium defaults for the other fields', () => { + const model = fakeModel(); + setModel(model, 'show', false); + assert.equal(model.show, false); + assert.equal(modelState(model).show, false); + assert.ok(Cesium.Matrix4.equals(modelState(model).modelMatrix, Cesium.Matrix4.IDENTITY)); +}); + +test('a matrix is copied into both the model and the mirror, never shared', () => { + const model = fakeModel(); + const own = model.modelMatrix; + const scratch = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(1, 2, 3)); + setModel(model, 'modelMatrix', scratch); + assert.equal(model.modelMatrix, own, "written into the model's own matrix"); + assert.ok(Cesium.Matrix4.equals(model.modelMatrix, scratch)); + assert.notEqual(modelState(model).modelMatrix, scratch); + Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(9, 9, 9), scratch); + assert.deepEqual( + Cesium.Matrix4.getTranslation(modelState(model).modelMatrix, new Cesium.Cartesian3()), + new Cesium.Cartesian3(1, 2, 3), + 'reusing the scratch moves neither copy', + ); + assert.ok(!Cesium.Matrix4.equals(model.modelMatrix, scratch)); +}); + +test('the mirror answers from the app, not from the model', () => { + const model = fakeModel(); + setModel(model, 'show', true); + model.show = false; // a write that bypassed the mirror + assert.equal(modelState(model).show, true); +}); + +test("a model without its own matrix yet gets a copy, not the caller's", () => { + const model = { show: true }; + const matrix = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(1, 2, 3)); + setModel(model, 'modelMatrix', matrix); + assert.notEqual(model.modelMatrix, matrix); + assert.ok(Cesium.Matrix4.equals(model.modelMatrix, matrix)); +}); + +test('a model the app did not write can be mirrored from its fields', () => { + const matrix = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(4, 5, 6)); + const model = mirrorModel({ show: false, modelMatrix: matrix }); + assert.equal(modelState(model).show, false); + assert.ok(Cesium.Matrix4.equals(modelState(model).modelMatrix, matrix)); + assert.notEqual(modelState(model).modelMatrix, matrix); + assert.equal(modelState(mirrorModel({})).show, true, 'Cesium shows by default'); + assert.equal(mirrorModel(null), null); +}); + +test('fields outside the mirror are refused', () => { + assert.throws(() => setModel({}, 'scale', 2), TypeError); +}); diff --git a/src/data/modelScale.test.mjs b/src/data/modelScale.test.mjs index d919148052..37cb1ca31a 100644 --- a/src/data/modelScale.test.mjs +++ b/src/data/modelScale.test.mjs @@ -32,6 +32,7 @@ import { trailHeadStart, modelAnchorWorld, } from './modelVisualAnchor.js'; +import { mirrorModel } from './modelMirror.js'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); @@ -797,11 +798,11 @@ test('the trail anchor rides the rendered longitudinal axis at every heading', ( position, hpr, Cesium.Ellipsoid.WGS84, undefined, new Cesium.Matrix4(), ); for (const [url, anchor] of Object.entries(MODEL_TRAIL_ANCHOR_NATIVE)) { - const model = { + const model = mirrorModel({ modelMatrix, computedScale: 1, sceneGraph: { components: { transform: rootTransform } }, - }; + }); const origin = Cesium.Matrix4.getTranslation(modelMatrix, new Cesium.Cartesian3()); const world = modelAnchorWorld(model, anchor, new Cesium.Cartesian3()); // Reference axes derived INDEPENDENTLY, from the ENU frame and the same @@ -860,11 +861,11 @@ test('a hovering rotorcraft anchors aft of its own hull, whatever its heading', const anchor = MODEL_TRAIL_ANCHOR_NATIVE['/models/bell206.glb']; for (const headingDeg of [0, 137.5, 271.9]) { const hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(headingDeg), 0, 0); - const model = { + const model = mirrorModel({ modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame( position, hpr, Cesium.Ellipsoid.WGS84, undefined, new Cesium.Matrix4()), computedScale: 1, - }; + }); const origin = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3()); const world = modelAnchorWorld(model, anchor, new Cesium.Cartesian3()); const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin, Cesium.Ellipsoid.WGS84, new Cesium.Matrix4()); diff --git a/src/data/modelVisualAnchor.js b/src/data/modelVisualAnchor.js index 733cd50496..a3bd92b64a 100644 --- a/src/data/modelVisualAnchor.js +++ b/src/data/modelVisualAnchor.js @@ -1,4 +1,5 @@ import * as Cesium from 'cesium'; +import { modelState } from './modelMirror.js'; /** * Model-space visual centres measured from the shipped GLBs' scene-space AABBs. * @@ -112,7 +113,8 @@ const _chainScratch = new Cesium.Matrix4(); * @returns {{x:number,y:number,z:number}|null} World position of the anchor. */ export function modelAnchorWorld(model, nativeAnchor, result) { - if (!model || !model.modelMatrix || !nativeAnchor || !result) return null; + const modelMatrix = modelState(model)?.modelMatrix; + if (!modelMatrix || !nativeAnchor || !result) return null; const scale = Number.isFinite(model.computedScale) ? model.computedScale : 1; _anchorScratch.x = (nativeAnchor[0] || 0) * scale; _anchorScratch.y = (nativeAnchor[1] || 0) * scale; @@ -122,7 +124,7 @@ export function modelAnchorWorld(model, nativeAnchor, result) { // baked root transform is carried too. const components = model?.sceneGraph?.components?.transform; Cesium.Matrix4.multiplyTransformation( - model.modelMatrix, + modelMatrix, components || Cesium.Matrix4.IDENTITY, _chainScratch, ); diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index d4ae59845f..6fe988f12e 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -36,6 +36,7 @@ import { DISPLAY_CORRIDOR_FAIR_SHARE, } from './policy.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; +import { modelState } from '../../data/modelMirror.js'; export function createMotion({ flightState, @@ -530,7 +531,7 @@ export function createMotion({ flightState.records.data.get(flightState._trackedIcao)?.klass, ); return modelVisualAnchor( - flightState._trackedModel.modelMatrix, + modelState(flightState._trackedModel).modelMatrix, spec.visualCenterNative, Number.isFinite(flightState._trackedModel.computedScale) ? flightState._trackedModel.computedScale @@ -559,7 +560,7 @@ export function createMotion({ ) return null; return Cesium.Matrix4.getTranslation( - flightState._trackedModel.modelMatrix, + modelState(flightState._trackedModel).modelMatrix, flightState._scratchTrailClip, ); } diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 0cfad575ed..e8eb44e8db 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -17,6 +17,7 @@ import { } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; +import { modelState } from '../../data/modelMirror.js'; export function createQueries({ flightState, @@ -483,7 +484,7 @@ export function createQueries({ ? parts.motion._trackedVisualCached() || billboardState(bb).position : modelOwnsVisual ? modelVisualAnchor( - model.modelMatrix, + modelState(model).modelMatrix, spec.visualCenterNative, Number.isFinite(model.computedScale) ? model.computedScale diff --git a/src/layers/flights/queries.test.mjs b/src/layers/flights/queries.test.mjs index 33eec2ed92..106bc0170a 100644 --- a/src/layers/flights/queries.test.mjs +++ b/src/layers/flights/queries.test.mjs @@ -8,6 +8,7 @@ import { mirrorBillboard, setBillboard, } from '../../data/billboardMirror.js'; +import { mirrorModel, setModel } from '../../data/modelMirror.js'; function fixture() { const info = { @@ -94,13 +95,13 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => const get = t.mock.method(f.flightState._models, 'get'); const [candidate] = f.queries.getDetectableObjects(); assert.equal(get.mock.callCount(), 1); - const model = { + const model = mirrorModel({ ready: false, show: true, modelMatrix: Cesium.Matrix4.fromTranslation( new Cesium.Cartesian3(10, 20, 30), ), - }; + }); f.parts.rendering._modelSpec = () => ({ visualCenterNative: Cesium.Cartesian3.ZERO, scale: 1, @@ -111,14 +112,14 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => model.ready = true; assert.equal(f.queries.getDetectableObjects()[0], candidate); assert.deepEqual(candidate.position, new Cesium.Cartesian3(10, 20, 30)); - Cesium.Matrix4.setTranslation( - model.modelMatrix, - new Cesium.Cartesian3(40, 50, 60), - model.modelMatrix, + setModel( + model, + 'modelMatrix', + Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(40, 50, 60)), ); f.queries.getDetectableObjects(); assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60)); - model.show = false; + setModel(model, 'show', false); assert.deepEqual(f.queries.getDetectableObjects(), []); setBillboard(f.bb, 'show', true); assert.equal( @@ -126,7 +127,7 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => billboardState(f.bb).position, ); assert.equal(get.mock.callCount(), 6); - model.show = true; + setModel(model, 'show', true); assert.equal(f.parts.rendering._modelOwnsVisual('abc123'), true); assert.equal(get.mock.callCount(), 7); }); @@ -134,7 +135,7 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => test('tracked ownership and live anchors remain independent of fleet models', () => { const f = fixture(); f.flightState._trackedIcao = 'abc123'; - f.flightState._trackedModel = { ready: true, show: true }; + f.flightState._trackedModel = mirrorModel({ ready: true, show: true }); f.parts.rendering._modelSpec = () => ({}); let anchor = new Cesium.Cartesian3(10, 20, 30); f.parts.motion._trackedVisualCached = () => anchor; @@ -146,16 +147,16 @@ test('tracked ownership and live anchors remain independent of fleet models', () assert.equal(f.queries.getDetectableObjects()[0].position, anchor); for (const tracked of [ null, - { ready: false, show: true }, - { ready: true, show: false }, + mirrorModel({ ready: false, show: true }), + mirrorModel({ ready: true, show: false }), ]) { f.flightState._trackedModel = tracked; assert.equal( - f.parts.rendering._modelOwnsVisual('abc123', { ready: true, show: true }), + f.parts.rendering._modelOwnsVisual('abc123', mirrorModel({ ready: true, show: true })), false, ); } - f.flightState._trackedModel = { ready: true, show: true }; + f.flightState._trackedModel = mirrorModel({ ready: true, show: true }); f.parts.tracking._trackedModelRegimeActive = () => false; assert.equal(f.parts.rendering._modelOwnsVisual('abc123', null), false); }); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index a110600718..ecaa138765 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -40,6 +40,7 @@ import { import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; +import { modelState, setModel } from '../../data/modelMirror.js'; export function createRendering({ flightState, @@ -242,8 +243,9 @@ export function createRendering({ } /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into - * `result` and returns it — pass each model's OWN `.modelMatrix` so models never share one - * mutable matrix object. `Model.modelMatrix` is a plain field (not a cloning setter); Cesium + * `result` (a shared scratch by default) and returns it. Push it with `setModel`, which copies + * it into the app's mirror and the model's own matrix, so models never share one mutable matrix + * object. `Model.modelMatrix` is a plain field (not a cloning setter); Cesium * clones it per frame in updateModelMatrix(). Sharing a single scratch made every model render at * the LAST-written transform — all stacked on one plane — and, once the tracked model wrote the * scratch every frame, the stack point oscillated frame-to-frame: the "flickering like mad" bug. */ @@ -338,21 +340,21 @@ export function createRendering({ flightState._scratchGroundPos, ); if (!displayPos) { - model.show = false; // no ground evidence → nothing safe to place a depth-tested model at + setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at setBillboard(bb, 'show', true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip // `ready` during scene update after this tick, and a first rendered frame on a // stale load-start matrix is the one-frame jump this ordering prevents. - _modelMatrix(displayPos, course, model.modelMatrix); + setModel(model, 'modelMatrix', _modelMatrix(displayPos, course)); if (!model.ready) { - model.show = false; // not loaded yet → keep the 2D icon, no half-model flash + setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash setBillboard(bb, 'show', true); return false; } beforeShow?.(); - if (!model.show) model.show = true; + if (!modelState(model).show) setModel(model, 'show', true); if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders return true; } @@ -415,7 +417,7 @@ export function createRendering({ * limb cull, a regime exit — only ever clears it. */ function _modelIsRendering(model) { - return !!model && model.ready === true && model.show === true; + return !!model && model.ready === true && modelState(model)?.show === true; } /** Spec identity for a LOADED model: URL and scale together (same-URL classes @@ -590,7 +592,7 @@ export function createRendering({ // an unplaced primitive claim ownership from the billboard for the frames // between admission and the next fleet tick (and draw at the identity matrix, // i.e. the Earth's centre). The handoff turns it on once it has a matrix. - model.show = false; + setModel(model, 'show', false); flightState._modelCollection.add(model); flightState._models.set(icao24, model); flightState._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard @@ -697,7 +699,8 @@ export function createRendering({ flightState._modelCollection && !flightState._modelCollection.isDestroyed(); if (!active) { - if (flightState._trackedModel) flightState._trackedModel.show = false; + if (flightState._trackedModel) + setModel(flightState._trackedModel, 'show', false); return; } // Ask the frame-cached source directly. If the entity callback already ran, @@ -709,7 +712,8 @@ export function createRendering({ billboardState(flightState._billboards.get(flightState._trackedIcao)) ?.position; if (!pos) { - if (flightState._trackedModel) flightState._trackedModel.show = false; + if (flightState._trackedModel) + setModel(flightState._trackedModel, 'show', false); return; } if ( @@ -779,7 +783,7 @@ export function createRendering({ // standalone primitive always exposes the tracked aircraft pick id. m.id = flightState._trackedIcao; aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this - m.show = false; // admitted, not yet the visual — the driver shows it once placed + setModel(m, 'show', false); // admitted, not yet the visual — the driver shows it once placed // Seed the world transform before the primitive enters the scene. A model // can become ready+shown between render phases; leaving Cesium's identity // default here produces a one-frame jump to the Earth's center. @@ -795,10 +799,10 @@ export function createRendering({ flightState._scratchGroundPos, ); if (displayPos) - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - m.modelMatrix, + setModel( + m, + 'modelMatrix', + _modelMatrix(displayPos, parts.motion._trackedDisplayCourse()), ); } flightState._trackedModel = m; @@ -828,13 +832,13 @@ export function createRendering({ flightState._scratchGroundPos, ); if (!displayPos) { - flightState._trackedModel.show = false; // no ground evidence → the billboard carries it + setModel(flightState._trackedModel, 'show', false); // no ground evidence → the billboard carries it return; } - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - flightState._trackedModel.modelMatrix, + setModel( + flightState._trackedModel, + 'modelMatrix', + _modelMatrix(displayPos, parts.motion._trackedDisplayCourse()), ); if (!flightState._trackedModel.ready) return; const spec = _modelSpec( @@ -851,7 +855,7 @@ export function createRendering({ fovyRad: flightState._viewer.camera.frustum.fovy, maximumPixelSize: TRACKED_MODEL_MAX_PX, }); - flightState._trackedModel.show = true; + setModel(flightState._trackedModel, 'show', true); } } @@ -1029,7 +1033,7 @@ export function createRendering({ // Also hide any 3D model — otherwise a model that crossed the limb would keep // rendering through the hidden globe at its last matrix. const m = flightState._models.get(icao24); - if (m && m.show) m.show = false; + if (m && modelState(m)?.show) setModel(m, 'show', false); continue; } diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index df54b7c9da..41fd19533c 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -1,6 +1,7 @@ import * as Cesium from 'cesium'; import { CYAN_TRANSPARENT } from './policy.js'; import { mirrorBillboard } from '../../data/billboardMirror.js'; +import { mirrorModel } from '../../data/modelMirror.js'; export function createTesting({ flightState, @@ -72,7 +73,8 @@ export function createTesting({ flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); flightState._cullPositions.clear(); flightState._models.clear(); - for (const [key, model] of models) flightState._models.set(key, model); + for (const [key, model] of models) + flightState._models.set(key, mirrorModel(model)); flightState._detectionObjects = new Map(); flightState.records.data = new Map([[icao24, meta]]); flightState._positionHistory = new Map([[icao24, history]]); diff --git a/src/layers/localAdsb/models.js b/src/layers/localAdsb/models.js index c9b9a03ae8..84ae5677b8 100644 --- a/src/layers/localAdsb/models.js +++ b/src/layers/localAdsb/models.js @@ -16,6 +16,7 @@ import { } from '../flights/policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; +import { setModel } from '../../data/modelMirror.js'; const specKey = (spec) => `${spec.url}@${spec.scale}`; @@ -56,6 +57,7 @@ export function createLocalAdsbModels({ let lastEligibilityAt = 0; let eligible = new Set(); const scratchHpr = new Cesium.HeadingPitchRoll(); + const scratchMatrix = new Cesium.Matrix4(); const scratchSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO, 1); const scratchCarto = new Cesium.Cartographic(); const scratchGround = new Cesium.Cartesian3(); @@ -118,7 +120,7 @@ export function createLocalAdsbModels({ visual.specKey = key; visual.bellyM = spec.bellyM; // Admitted, not yet the visual: placement turns it on. - model.show = false; + setModel(model, 'show', false); collection.add(model); models.set(id, model); } @@ -224,7 +226,7 @@ export function createLocalAdsbModels({ if (!model || !marker.position) continue; const position = placement(id, marker); if (!position || !occluder.isPointVisible(marker.position)) { - model.show = false; + setModel(model, 'show', false); continue; } scratchHpr.heading = Cesium.Math.toRadians( @@ -232,18 +234,22 @@ export function createLocalAdsbModels({ ); scratchHpr.pitch = 0; scratchHpr.roll = 0; - Cesium.Transforms.headingPitchRollToFixedFrame( - position, - scratchHpr, - Cesium.Ellipsoid.WGS84, - undefined, - model.modelMatrix, + setModel( + model, + 'modelMatrix', + Cesium.Transforms.headingPitchRollToFixedFrame( + position, + scratchHpr, + Cesium.Ellipsoid.WGS84, + undefined, + scratchMatrix, + ), ); if (!model.ready) { - model.show = false; + setModel(model, 'show', false); continue; } - model.show = true; + setModel(model, 'show', true); marker.modelOwnsVisual = true; } for (const id of [...models.keys()]) if (!markers.has(id)) release(id); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 06dce15444..eb7ef13b98 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -24,6 +24,7 @@ import { COURSE_SLEW_DT_MAX_SEC, COURSE_MAX_DPS, } from './policy.js'; +import { modelState } from '../../data/modelMirror.js'; export function createMotion({ flightState, @@ -383,7 +384,7 @@ export function createMotion({ flightState.records.data.get(flightState._trackedIcao)?.klass, ); return modelVisualAnchor( - flightState._trackedModel.modelMatrix, + modelState(flightState._trackedModel).modelMatrix, spec.visualCenterNative, Number.isFinite(flightState._trackedModel.computedScale) ? flightState._trackedModel.computedScale @@ -410,7 +411,7 @@ export function createMotion({ ) return null; return Cesium.Matrix4.getTranslation( - flightState._trackedModel.modelMatrix, + modelState(flightState._trackedModel).modelMatrix, flightState._scratchTrailClip, ); } diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index db357a87fc..205284c7e0 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -12,6 +12,7 @@ import { import { LANDED_ALT_MAX_FT, LANDED_SPEED_MAX_MPS } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; +import { modelState } from '../../data/modelMirror.js'; export function createQueries({ flightState, @@ -491,7 +492,7 @@ export function createQueries({ ? parts.motion._trackedVisualCached() || billboardState(bb).position : modelOwnsVisual ? modelVisualAnchor( - model.modelMatrix, + modelState(model).modelMatrix, spec.visualCenterNative, Number.isFinite(model.computedScale) ? model.computedScale diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index 1287196308..8e8423923c 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -56,6 +56,7 @@ import { import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; +import { modelState, setModel } from '../../data/modelMirror.js'; export function createRendering({ flightState, @@ -253,9 +254,9 @@ export function createRendering({ } /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into - * `result` and returns it — pass each model's OWN `.modelMatrix` so models never share one mutable - * matrix object (see flights.js for the full rationale: sharing one scratch stacked every model on - * the last-written transform, and the per-frame tracked write made it flicker). */ + * `result` (a shared scratch by default) and returns it. Push it with `setModel`, which copies + * it into the app's mirror and the model's own matrix, so models never share one mutable matrix + * object (see flights.js for the full rationale). */ function _modelMatrix( pos, @@ -340,26 +341,31 @@ export function createRendering({ flightState._scratchGroundPos, ); if (!displayPos) { - model.show = false; // no ground evidence → nothing safe to place a depth-tested model at + setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at setBillboard(bb, 'show', true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip // `ready` during scene update after this tick, and a first rendered frame on a // stale load-start matrix is the one-frame jump this ordering prevents. - _modelMatrix( - displayPos, - course, - model.modelMatrix, - _modelSpec(flightState.records.data.get(icao24)?.klass).headingOffsetDeg, + setModel( + model, + 'modelMatrix', + _modelMatrix( + displayPos, + course, + undefined, + _modelSpec(flightState.records.data.get(icao24)?.klass) + .headingOffsetDeg, + ), ); if (!model.ready) { - model.show = false; // not loaded yet → keep the 2D icon, no half-model flash + setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash setBillboard(bb, 'show', true); return false; } beforeShow?.(); - if (!model.show) model.show = true; + if (!modelState(model).show) setModel(model, 'show', true); if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders return true; } @@ -383,7 +389,7 @@ export function createRendering({ * a regime exit — only ever clears it. Mirror of flights.js. */ function _modelIsRendering(model) { - return !!model && model.ready === true && model.show === true; + return !!model && model.ready === true && modelState(model)?.show === true; } /** Spec identity for a LOADED model — mirror of flights.js: URL and scale @@ -551,7 +557,7 @@ export function createRendering({ // an unplaced primitive claim ownership from the billboard for the frames // between admission and the next fleet tick (and draw at the identity matrix, // i.e. the Earth's centre). The handoff turns it on once it has a matrix. - model.show = false; + setModel(model, 'show', false); flightState._modelCollection.add(model); flightState._models.set(icao24, model); flightState._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard @@ -656,7 +662,8 @@ export function createRendering({ flightState._modelCollection && !flightState._modelCollection.isDestroyed(); if (!active) { - if (flightState._trackedModel) flightState._trackedModel.show = false; + if (flightState._trackedModel) + setModel(flightState._trackedModel, 'show', false); return; } // Ask the frame-cached source directly. If the entity callback already ran, @@ -668,7 +675,8 @@ export function createRendering({ billboardState(flightState._billboards.get(flightState._trackedIcao)) ?.position; if (!pos) { - if (flightState._trackedModel) flightState._trackedModel.show = false; + if (flightState._trackedModel) + setModel(flightState._trackedModel, 'show', false); return; } if ( @@ -736,7 +744,7 @@ export function createRendering({ // standalone primitive always exposes the tracked aircraft pick id. m.id = flightState._trackedIcao; aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this - m.show = false; // admitted, not yet the visual — the driver shows it once placed + setModel(m, 'show', false); // admitted, not yet the visual — the driver shows it once placed // Seed the world transform before the primitive enters the scene. A model // can become ready+shown between render phases; leaving Cesium's identity // default here produces a one-frame jump to the Earth's center. @@ -752,11 +760,15 @@ export function createRendering({ flightState._scratchGroundPos, ); if (displayPos) { - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - m.modelMatrix, - trackedSpec.headingOffsetDeg, + setModel( + m, + 'modelMatrix', + _modelMatrix( + displayPos, + parts.motion._trackedDisplayCourse(), + undefined, + trackedSpec.headingOffsetDeg, + ), ); } } @@ -787,17 +799,21 @@ export function createRendering({ flightState._scratchGroundPos, ); if (!displayPos) { - flightState._trackedModel.show = false; // no ground evidence → the billboard carries it + setModel(flightState._trackedModel, 'show', false); // no ground evidence → the billboard carries it return; } const spec = _modelSpec( flightState.records.data.get(flightState._trackedIcao)?.klass, ); - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - flightState._trackedModel.modelMatrix, - spec.headingOffsetDeg, + setModel( + flightState._trackedModel, + 'modelMatrix', + _modelMatrix( + displayPos, + parts.motion._trackedDisplayCourse(), + undefined, + spec.headingOffsetDeg, + ), ); if (!flightState._trackedModel.ready) return; flightState._trackedModel.scale = trackedModelScaleForPixelCap({ @@ -811,7 +827,7 @@ export function createRendering({ fovyRad: flightState._viewer.camera.frustum.fovy, maximumPixelSize: TRACKED_MODEL_MAX_PX, }); - flightState._trackedModel.show = true; + setModel(flightState._trackedModel, 'show', true); } } @@ -962,7 +978,7 @@ export function createRendering({ // Also hide any 3D model — otherwise a model that crossed the limb would keep // rendering through the hidden globe at its last matrix. const m = flightState._models.get(icao24); - if (m && m.show) m.show = false; + if (m && modelState(m)?.show) setModel(m, 'show', false); continue; } diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index fa43ed0fc4..5af1140df0 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -1,5 +1,6 @@ import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js'; import { mirrorBillboard } from '../../data/billboardMirror.js'; +import { mirrorModel } from '../../data/modelMirror.js'; export function createTesting({ flightState, @@ -43,7 +44,8 @@ export function createTesting({ flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); flightState._cullPositions.clear(); flightState._models.clear(); - for (const [key, model] of models) flightState._models.set(key, model); + for (const [key, model] of models) + flightState._models.set(key, mirrorModel(model)); flightState._detectionObjects = new Map(); flightState.records.data = new Map([[icao24, meta]]); flightState._positionHistory = new Map([[icao24, history]]); From 0889cd0cb77c065be8d5c24cf2785f9a9f68d507 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 13:32:53 -0800 Subject: [PATCH 009/470] Answer earthquake, CCTV pick and tracked sprite reads from the app Earthquake analyst records come from the events the layer drew, gated on its own enabled flag, instead of reading each entity's position and property bag back; the discs no longer carry the bag. CCTV coverage rays and projection planes record their camera id in a layer pick store instead of a cctvCameraId entity property, with the same ownership checks. The tracked flight, military and local ADS-B billboards record their size and distance scaling as the entity record's sprite, which the close-range camera guard and the screen annotations' tracked footprint now read in place of the billboard's property getters. --- scripts/package-boundaries.json | 3 ++ src/annotations/screenAnnotationRenderer.js | 14 ++--- src/data/cctv.test.mjs | 14 +++-- src/data/cctvGizmo.js | 4 +- src/data/entityRecords.js | 2 + src/layers/cctv/geometry.js | 9 ++-- src/layers/cctv/pickState.js | 7 +++ src/layers/cctv/projection.js | 3 +- src/layers/cctv/selection.js | 15 +++--- src/layers/earthquakes/index.js | 59 ++++++++------------- src/layers/earthquakes/ownership.test.mjs | 35 ++++++++++++ src/layers/flights/motion.js | 13 +++-- src/layers/flights/tracking.js | 24 ++++++--- src/layers/localAdsb/index.js | 15 ++++-- src/layers/military/motion.js | 13 +++-- src/layers/military/tracking.js | 26 ++++++--- 16 files changed, 160 insertions(+), 96 deletions(-) create mode 100644 src/layers/cctv/pickState.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index e759dd4939..a76faec8df 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1867,6 +1867,7 @@ "src/layers/cctv/rendering.js", "src/data/billboardMirror.js", "src/layers/cctv/selection.js", + "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", @@ -2518,6 +2519,7 @@ "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", + "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", @@ -3429,6 +3431,7 @@ "src/layers/cctv/videoPlayback.js", "src/layers/cctv/rendering.js", "src/layers/cctv/selection.js", + "src/layers/cctv/pickState.js", "src/layers/cctv/source.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index 54ca3205fe..27ae2fcb42 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -424,7 +424,6 @@ export function createScreenAnnotationRenderer( let bottom = painted ? painted.y + painted.h : undefined; const ent = viewer.trackedEntity; - const now = Cesium.JulianDate.now(); const displayPosition = readEntityRecord(ent)?.displayPosition; const world = typeof displayPosition === 'function' ? displayPosition() : null; @@ -436,13 +435,14 @@ export function createScreenAnnotationRenderer( ) : null; - // Billboard box — centered on the anchor, magnified by scaleByDistance. - const bb = ent?.billboard; - if (bb && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { - const baseW = bb.width?.getValue?.(now) ?? 28; - const baseH = bb.height?.getValue?.(now) ?? 28; + // Billboard box — centered on the anchor, magnified by scaleByDistance, from + // the size the tracking layer recorded for its sprite. + const sprite = readEntityRecord(ent)?.sprite; + if (sprite && win && Number.isFinite(win.x) && Number.isFinite(win.y)) { + const baseW = sprite.width ?? 28; + const baseH = sprite.height ?? 28; let scale = 1; - const sbd = bb.scaleByDistance?.getValue?.(now); + const sbd = sprite.scaleByDistance; if (sbd) scale = nearFarValue( sbd, diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index d7cc131b58..483dec3994 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -80,6 +80,7 @@ import { LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; import { mirrorBillboard } from './billboardMirror.js'; +import { cctvPicks } from '../layers/cctv/pickState.js'; const ASPECT = 16 / 9; const toRad = (deg) => (deg * Math.PI) / 180; @@ -1130,10 +1131,10 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => { const billboard = { id: 'shared-id' }; - const ownedCoverageEntity = { - id: 'cctv-shared-id-cap', - properties: { cctvCameraId: 'shared-id' }, - }; + const ownedCoverageEntity = { id: 'cctv-shared-id-cap' }; + cctvPicks.write(ownedCoverageEntity).cameraId = 'shared-id'; + const strayEntity = { id: 'cctv-shared-id-stray' }; + cctvPicks.write(strayEntity).cameraId = 'shared-id'; const record = { ...makeDeselectRecord('shared-id'), billboard, @@ -1176,6 +1177,11 @@ test('CCTV camera extraction requires layer ownership, not a colliding sibling I null, 'a sibling cannot impersonate CCTV by copying its property shape', ); + assert.equal( + _extractPickedCameraIdForTest({ id: strayEntity }), + null, + 'a camera id alone is not ownership: the record must hold the entity', + ); } finally { _setCctvCoverageStateForTest({ enabled: false }); } diff --git a/src/data/cctvGizmo.js b/src/data/cctvGizmo.js index fa15c55320..8e3efc8630 100644 --- a/src/data/cctvGizmo.js +++ b/src/data/cctvGizmo.js @@ -118,8 +118,8 @@ export function signedAngleDelta(fromRad, toRad) { // --------------------------------------------------------------------------- /** Entity id prefix for every gizmo part — the layer's pick-owner regex and - * click-to-select guard key off this. Gizmo entities NEVER carry a - * `cctvCameraId` property, so the layer's selection path ignores them. */ + * click-to-select guard key off this. Gizmo entities NEVER get a camera id in + * the layer's pick store, so the layer's selection path ignores them. */ export const GIZMO_ID_PREFIX = 'cctv-gizmo-'; const RING_SEGMENTS = 96; diff --git a/src/data/entityRecords.js b/src/data/entityRecords.js index 6de9c409e4..7c49c7e106 100644 --- a/src/data/entityRecords.js +++ b/src/data/entityRecords.js @@ -12,6 +12,8 @@ * - `visualPosition()`: where a 3D model is actually drawn, for the tracked card. * - `labelModel`: the tracked card's `{ title, details, accent, … }`. * - `selectionOrigin`: what started the selection (`'user'`, …). + * - `sprite`: a tracked billboard's pushed `{ width, height, scale, scaleByDistance }`, for + * the close-range camera guard and the screen annotations' tracked footprint. * * A layer's private per-entity state goes in its own store ({@link createEntityStore}). */ diff --git a/src/layers/cctv/geometry.js b/src/layers/cctv/geometry.js index 7a816374d9..f806508543 100644 --- a/src/layers/cctv/geometry.js +++ b/src/layers/cctv/geometry.js @@ -17,6 +17,7 @@ import { requiredPlaneLift, } from '../../data/cctvFootprint.js'; import { setBillboard } from '../../data/billboardMirror.js'; +import { cctvPicks } from './pickState.js'; export function createGeometry({ state: layerState, services, parts, source }) { const { warmGroundFloor, cachedGroundFloor } = services.ground; @@ -700,16 +701,18 @@ export function createGeometry({ state: layerState, services, parts, source }) { record.position = positions.mount; } - const addPolyline = (role, linePositions) => - layerState._viewer.entities.add({ + const addPolyline = (role, linePositions) => { + const entity = layerState._viewer.entities.add({ id: `cctv-${camera.id}-${role}`, - properties: { cctvCameraId: camera.id }, polyline: { positions: linePositions, width: 1.2, material: IDLE_COVERAGE_COLOR, }, }); + cctvPicks.write(entity).cameraId = camera.id; + return entity; + }; const entities = [ addPolyline('ray-tl', [positions.mount, positions.tl]), diff --git a/src/layers/cctv/pickState.js b/src/layers/cctv/pickState.js new file mode 100644 index 0000000000..e24012d972 --- /dev/null +++ b/src/layers/cctv/pickState.js @@ -0,0 +1,7 @@ +import { createEntityStore } from '../../data/entityRecords.js'; + +/** + * The camera a picked coverage ray or projection plane belongs to: `cameraId` + * is the upstream camera id. Gizmo entities never get one. + */ +export const cctvPicks = createEntityStore(); diff --git a/src/layers/cctv/projection.js b/src/layers/cctv/projection.js index e32db4fd41..64b0441045 100644 --- a/src/layers/cctv/projection.js +++ b/src/layers/cctv/projection.js @@ -7,6 +7,7 @@ import { PROJECTION_CANVAS_WIDTH, PROJECTION_CANVAS_HEIGHT, } from './policy.js'; +import { cctvPicks } from './pickState.js'; export function createProjection({ state: layerState, @@ -134,7 +135,6 @@ export function createProjection({ }); runtime.planeEntity = layerState._viewer.entities.add({ id: `cctv-${record.camera.id}-plane`, - properties: { cctvCameraId: record.camera.id }, show: false, position: positions.capCenter, orientation: parts.model.planeOrientationFor( @@ -152,6 +152,7 @@ export function createProjection({ outlineColor: PLANE_OUTLINE_COLOR, }, }); + cctvPicks.write(runtime.planeEntity).cameraId = record.camera.id; return runtime.planeEntity; } diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index c86425fd0b..23473258c3 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -3,6 +3,7 @@ import { isTrackingClickGesture, } from '../../data/trackingClickGesture.js'; import * as Cesium from 'cesium'; +import { cctvPicks } from './pickState.js'; export function createSelection({ state: layerState, @@ -207,7 +208,7 @@ export function createSelection({ /** * Extracts a camera ID from a Cesium pick result by checking billboard IDs, - * primitive IDs, and entity cctvCameraId properties. + * primitive IDs, and the camera ids the layer keeps for its coverage entities. * @param {Object|null} picked - Result from scene.pick(). * @returns {string|null} Camera ID, or null if the pick is not a CCTV entity. */ @@ -215,17 +216,13 @@ export function createSelection({ function extractPickedCameraId(picked) { if (!picked) return null; - const entity = picked.id?.properties + const entity = cctvPicks.read(picked.id) ? picked.id - : picked.primitive?.id?.properties + : cctvPicks.read(picked.primitive?.id) ? picked.primitive.id : null; - const maybeProp = entity?.properties?.cctvCameraId; - if (maybeProp) { - const value = - typeof maybeProp.getValue === 'function' - ? maybeProp.getValue(Cesium.JulianDate.now()) - : maybeProp; + const value = cctvPicks.read(entity)?.cameraId; + if (value !== undefined) { const record = typeof value === 'string' ? layerState._recordById.get(value) : null; const ownsCoverageEntity = Boolean( diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 0d522fcb90..023c3017b4 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -23,6 +23,8 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { let _viewer = null; let _request = null; let _dataSource = null; + // What the discs were drawn from, so analyst reads come from the app, not the entities. + let _events = []; let _count = 0; let _lastUpdate = null; let _lastError = null; @@ -77,6 +79,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { return false; const nextEntities = []; + const nextEvents = []; let count = 0; const overlayEntries = []; @@ -98,6 +101,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { const outlineAlpha = isSignificant ? 1.0 : 0.8; const position = Cesium.Cartesian3.fromDegrees(lon, lat); + nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat }); nextEntities.push( new Cesium.Entity({ id: `earthquake:${stableId}`, @@ -115,14 +119,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { outlineWidth: isSignificant ? 3 : 2, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, }, - properties: { - // Analyst seam (additive): the USGS event id (e.g. "us7000abcd"). - usgsId, - mag, - place, - time, - depth: depthKm, - }, }), ); overlayEntries.push( @@ -137,6 +133,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _dataSource.entities.removeAll(); for (const entity of nextEntities) _dataSource.entities.add(entity); + _events = nextEvents; if (_enabled) { overlayHost.setEntries( EARTHQUAKE_OVERLAY_SOURCE_ID, @@ -176,6 +173,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { viewer.dataSources.remove(_dataSource, true); _dataSource = null; } + _events = []; _count = 0; _lastUpdate = null; _lastError = null; @@ -190,39 +188,24 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { * @returns {Array} See mapAnalystRecord for the record shape. */ getAnalystRecords(maxCount = 2000) { - if (!_dataSource || !_dataSource.show) return []; - const entities = _dataSource.entities.values; - if (!entities.length) return []; + if (!_dataSource || !_enabled || !_events.length) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) : 2000; - const now = Cesium.JulianDate.now(); - const result = []; - for (const entity of entities) { - if (result.length >= limit) break; - const cartesian = entity.position - ? entity.position.getValue(now) - : null; - const carto = cartesian - ? Cesium.Cartographic.fromCartesian(cartesian) - : null; - const p = entity.properties; - result.push( - mapAnalystRecord( - { - id: p?.usgsId?.getValue(now) ?? null, - mag: p?.mag?.getValue(now), - place: p?.place?.getValue(now), - time: p?.time?.getValue(now), - depth: p?.depth?.getValue(now), - lat: carto ? Cesium.Math.toDegrees(carto.latitude) : null, - lon: carto ? Cesium.Math.toDegrees(carto.longitude) : null, - }, - result.length, - ), - ); - } - return result; + return _events.slice(0, limit).map((event, index) => + mapAnalystRecord( + { + id: event.usgsId ?? null, + mag: event.mag, + place: event.place, + time: event.time, + depth: event.depthKm, + lat: event.lat, + lon: event.lon, + }, + index, + ), + ); }, getStats() { diff --git a/src/layers/earthquakes/ownership.test.mjs b/src/layers/earthquakes/ownership.test.mjs index 9951935de9..b13cc005eb 100644 --- a/src/layers/earthquakes/ownership.test.mjs +++ b/src/layers/earthquakes/ownership.test.mjs @@ -88,3 +88,38 @@ test('USGS body completion honors cancellation even with an uncooperative transp name: 'AbortError', }); }); +test('analyst records come from the events the layer drew, and only while it is on', async () => { + const h = harness({ + getSnapshot: async () => [ + row, + { ...row, stableId: 'event-b', usgsId: 'event-b', mag: 5.5 }, + ], + }); + await h.layer.update(h.viewer); + assert.deepEqual(h.layer.getAnalystRecords(), [ + { + id: 'event-a', + magnitude: 4, + depthKm: 3, + lat: 20, + lon: 30, + timeMs: 1000, + place: 'Fixture', + }, + { + id: 'event-b', + magnitude: 5.5, + depthKm: 3, + lat: 20, + lon: 30, + timeMs: 1000, + place: 'Fixture', + }, + ]); + assert.equal(h.layer.getAnalystRecords(1).length, 1); + const [entity] = h.sources[0].entities.values; + assert.equal(entity.properties, undefined, 'the entity carries drawing only'); + h.layer.disable(h.viewer); + assert.deepEqual(h.layer.getAnalystRecords(), []); + h.layer.destroy(h.viewer); +}); diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 6fe988f12e..309966b9b0 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -37,6 +37,7 @@ import { } from './policy.js'; import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState } from '../../data/modelMirror.js'; +import { readEntityRecord } from '../../data/entityRecords.js'; export function createMotion({ flightState, @@ -372,16 +373,14 @@ export function createMotion({ ); } - const billboard = flightState._trackedEntity?.billboard; - const time = flightState._viewer.clock.currentTime; - const width = billboard?.width?.getValue(time) ?? 28; - const height = billboard?.height?.getValue(time) ?? 28; + const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; + const width = sprite?.width ?? 28; + const height = sprite?.height ?? 28; const scale = - billboard?.scale?.getValue(time) ?? + sprite?.scale ?? (CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1); const scaleByDistance = - billboard?.scaleByDistance?.getValue(time) ?? - TRACKED_BILLBOARD_SCALE_BY_DISTANCE; + sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE; const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM); return Math.max(width, height) * scale * distanceScale; } diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 9969ad88eb..d0d00cba06 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -23,6 +23,7 @@ import { RENDER_DELAY_SEC, TRAIL_COLOR, CYAN_TRANSPARENT, + TRACKED_BILLBOARD_SCALE_BY_DISTANCE, } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; @@ -952,6 +953,17 @@ export function createTracking({ // entity is what makes the follow-camera's bounding sphere always ready (see _trackedModel). // Keep Cesium's generated entity ID: re-init without destroy can temporarily // overlap collections, and an explicit ICAO ID would throw on that duplicate. + // What the tracked billboard is drawn at, kept in its entity record so the + // camera guard and screen annotations size it from the app. + const sprite = { + width: 28, + height: 28, + scale: + CLASS_SCALE_2D[ + flightState.records.data.get(flightState._trackedIcao)?.klass + ] || 1, + scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, + }; flightState._trackedEntity = flightState._viewer.entities.add({ position: positionProperty, // Force Cesium's built-in EntityView and our close-range camera guard to @@ -967,12 +979,9 @@ export function createTracking({ ), TRACKED_ICON_PX, ), - width: 28, - height: 28, - scale: - CLASS_SCALE_2D[ - flightState.records.data.get(flightState._trackedIcao)?.klass - ] || 1, + width: sprite.width, + height: sprite.height, + scale: sprite.scale, // Solid cyan 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( @@ -983,7 +992,7 @@ export function createTracking({ false, ), sizeInMeters: false, - scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5), + 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 cyan icon inside @@ -1016,6 +1025,7 @@ export function createTracking({ }); entityRecord(flightState._trackedEntity).selectionOrigin = origin; entityRecord(flightState._trackedEntity).trackedId = `flights:${icao24}`; + entityRecord(flightState._trackedEntity).sprite = sprite; entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff'); diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index 2eb13b80a4..86aa7283ba 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -45,6 +45,12 @@ const FEET_TO_METERS = 0.3048; const RENDER_HOLD_ID = 'local-adsb'; /** Picks looked through under a click for a local aircraft. */ const CLICK_DRILL_LIMIT = 8; +/** Marker billboard size and distance scaling, as pushed and as recorded. */ +const MARKER_SPRITE = Object.freeze({ + width: 20, + height: 20, + scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8_000_000, 0.5), +}); /** Trail lines pass through their aircraft; a click never stops on one. */ const TRAIL_PICK_PREFIX = 'gev-trail:'; /** The DISPLAY rail's first-run 3D preference, used when no reader is wired. */ @@ -265,6 +271,7 @@ export function createLocalAdsbLayer({ if (marker.iconScale !== scale) { marker.iconScale = scale; billboard.scale = scale; + entityRecord(marker.entity).sprite.scale = scale; } } @@ -437,12 +444,12 @@ export function createLocalAdsbLayer({ position: new Cesium.CallbackProperty(() => marker.position, false), billboard: { image: aircraftIcon('airliner'), - width: 20, - height: 20, + width: MARKER_SPRITE.width, + height: MARKER_SPRITE.height, scale: 1, color, sizeInMeters: false, - scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8_000_000, 0.5), + scaleByDistance: MARKER_SPRITE.scaleByDistance, alignedAxis: Cesium.Cartesian3.ZERO, rotation: new Cesium.CallbackProperty( () => markerRotation(marker), @@ -460,6 +467,8 @@ export function createLocalAdsbLayer({ }, }); entityRecord(marker.entity).trackedId = id; + // Sized from the app when Cesium tracks the marker (screen annotations). + entityRecord(marker.entity).sprite = { ...MARKER_SPRITE, scale: 1 }; entityRecord(marker.entity).displayPosition = () => marker.position; } refreshClass(marker); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index eb7ef13b98..9309d4378f 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -25,6 +25,7 @@ import { COURSE_MAX_DPS, } from './policy.js'; import { modelState } from '../../data/modelMirror.js'; +import { readEntityRecord } from '../../data/entityRecords.js'; export function createMotion({ flightState, @@ -250,17 +251,15 @@ export function createMotion({ ); } - const billboard = flightState._trackedEntity?.billboard; - const time = flightState._viewer.clock.currentTime; - const width = billboard?.width?.getValue(time) ?? 28; - const height = billboard?.height?.getValue(time) ?? 28; + const sprite = readEntityRecord(flightState._trackedEntity)?.sprite; + const width = sprite?.width ?? 28; + const height = sprite?.height ?? 28; const scale = - billboard?.scale?.getValue(time) ?? + sprite?.scale ?? BILLBOARD_SCALE * (CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1); const scaleByDistance = - billboard?.scaleByDistance?.getValue(time) ?? - TRACKED_BILLBOARD_SCALE_BY_DISTANCE; + sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE; const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM); return Math.max(width, height) * scale * distanceScale; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 7000950adf..07538df0e8 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -24,6 +24,7 @@ import { GROUND_SCALE, AMBER_TRANSPARENT, TRACKED_ICON_COLOR, + TRACKED_BILLBOARD_SCALE_BY_DISTANCE, } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; @@ -915,6 +916,18 @@ export function createTracking({ // 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(); keeping it off the entity is // what makes the follow-camera's bounding sphere always ready (see _trackedModel). + // What the tracked billboard is drawn at, kept in its entity record so the + // camera guard and screen annotations size it from the app. + const sprite = { + width: 28, + height: 28, + scale: + BILLBOARD_SCALE * + (CLASS_SCALE_2D[ + flightState.records.data.get(flightState._trackedIcao)?.klass + ] || 1), + scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, + }; flightState._trackedEntity = flightState._viewer.entities.add({ position: positionProperty, // Keep Cesium's EntityView in the same ENU frame as the close-range @@ -928,13 +941,9 @@ export function createTracking({ ), TRACKED_ICON_PX, ), - width: 28, - height: 28, - scale: - BILLBOARD_SCALE * - (CLASS_SCALE_2D[ - flightState.records.data.get(flightState._trackedIcao)?.klass - ] || 1), + 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( @@ -945,7 +954,7 @@ export function createTracking({ false, ), sizeInMeters: false, - scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5), + 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 @@ -978,6 +987,7 @@ export function createTracking({ }); entityRecord(flightState._trackedEntity).selectionOrigin = origin; entityRecord(flightState._trackedEntity).trackedId = `military:${icao24}`; + entityRecord(flightState._trackedEntity).sprite = sprite; entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166'); From 08985d5083d3af94e37d8f5a041e73ded1e89a7f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 14:57:31 -0800 Subject: [PATCH 010/470] Keep installation and local GeoJSON pick state off Cesium entities Installation selection fills and outlines record the installation they belong to in the layer's installationMarkers store instead of an installationId expando, and the click handler resolves them from there. Named-marker points keep their { installationId } pick payload, which is the app's own object, so sibling layers treat a point click as before; the marker remembers its record id for visit() instead of reading the point. The local GeoJSON package tracks the entities each layer loaded in a per-instance set instead of a __localLayerId tag, and passes the stem base to registerEntityContext as targetPosition instead of hanging it on the entity; FIRMS does the same, and voice targeting reads the context record. QA scripts find a layer's features by their context id. --- scripts/qa-draw-tool.mjs | 13 ++++++++++--- scripts/qa-infra-lod.mjs | 4 +++- scripts/qa-installation-polish.mjs | 7 +++++-- scripts/qa-overpass-offload.mjs | 5 +++-- src/data/localGeojson.test.mjs | 12 ++++++++++-- src/data/localGeojsonCore.js | 15 ++++++++------- src/layers/firms/selection.js | 3 +-- src/layers/installations/markerState.js | 2 ++ src/layers/installations/namedMarkers.js | 9 ++++++--- src/layers/installations/rendering.js | 4 ++-- src/layers/installations/selection.js | 7 +++++-- src/layers/installations/selectionFill.test.mjs | 3 ++- src/voice/gevActions.js | 2 +- 13 files changed, 58 insertions(+), 28 deletions(-) diff --git a/scripts/qa-draw-tool.mjs b/scripts/qa-draw-tool.mjs index 5985730ec0..c1b6e7e596 100644 --- a/scripts/qa-draw-tool.mjs +++ b/scripts/qa-draw-tool.mjs @@ -941,6 +941,11 @@ async function findClickableTarget() { const site = await page .evaluate(async () => { const viewer = window.__godsEyeView.viewer; + // The app registers each local feature's context as `:`. + const isDataCentre = (entity) => + window.__godsEyeView.entityRecords + .read(entity) + ?.contextId?.startsWith('local-datacenters:'); await window.__godsEyeView.dataManager.setEnabled( 'local-datacenters', true, @@ -960,7 +965,7 @@ async function findClickableTarget() { for (let attempt = 0; attempt < 40; attempt += 1) { for (let i = 0; i < viewer.dataSources.length; i += 1) { for (const entity of viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId !== 'local-datacenters') continue; + if (!isDataCentre(entity)) continue; const point = centreOf(entity); if (!point) continue; const carto = window.Cesium @@ -993,8 +998,10 @@ async function findClickableTarget() { viewer.scene.requestRender(); }, site); await wait(4000); - const spot = await onScreen( - (entity) => entity.__localLayerId === 'local-datacenters', + const spot = await onScreen((entity) => + window.__godsEyeView.entityRecords + .read(entity) + ?.contextId?.startsWith('local-datacenters:'), ); return spot ? { ...spot, layer: 'data centre' } : null; } diff --git a/scripts/qa-infra-lod.mjs b/scripts/qa-infra-lod.mjs index 5be19fe640..3c4c75c3a3 100644 --- a/scripts/qa-infra-lod.mjs +++ b/scripts/qa-infra-lod.mjs @@ -218,9 +218,11 @@ try { const gev = window.__godsEyeView; const snap = () => infraIds.map((id) => { const visibleIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < gev.viewer.dataSources.length; i++) { for (const entity of gev.viewer.dataSources.get(i).entities.values) { - if (entity.__localLayerId === id && entity.show) visibleIds.push(String(entity.id)); + const contextId = gev.entityRecords.read(entity)?.contextId; + if (contextId?.startsWith(`${id}:`) && entity.show) visibleIds.push(String(entity.id)); } } return visibleIds.sort(); diff --git a/scripts/qa-installation-polish.mjs b/scripts/qa-installation-polish.mjs index bda5f0dfee..df1b8429e4 100644 --- a/scripts/qa-installation-polish.mjs +++ b/scripts/qa-installation-polish.mjs @@ -17,9 +17,11 @@ export async function checkInstallationPan(page, dir) { 'military-installations', ).module; const centerIds = []; + // The app registers each local feature's context as `:`. for (let i = 0; i < g.viewer.dataSources.length; i++) for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.__localLayerId === 'local-datacenters') centerIds.push(e.id); + if (g.entityRecords.read(e)?.contextId?.startsWith('local-datacenters:')) + centerIds.push(e.id); window.__polishPanFrames = []; window.__stopPolishPan = g.viewer.scene.postRender.addEventListener(() => { const sites = [], @@ -333,7 +335,8 @@ export async function checkInstallationSelection( for (let y = 250; y < 650; y += 75) for (let x = 400; x < 850; x += 75) { const pick = g.viewer.scene.pick({ x, y }); - if (!pick?.id?.installationId && !window.__godsEyeView.entityRecords.read(pick?.id)?.trackedId) + // Nothing picked: no installation marker, outline or tracked contact. + if (!pick?.id) return { x, y }; } throw new Error('No empty map point'); diff --git a/scripts/qa-overpass-offload.mjs b/scripts/qa-overpass-offload.mjs index 8f6594011f..4d5c7c3f0e 100644 --- a/scripts/qa-overpass-offload.mjs +++ b/scripts/qa-overpass-offload.mjs @@ -1277,8 +1277,9 @@ try { outlines = 0; for (let i = 0; i < viewer.dataSources.length; i++) for (const entity of viewer.dataSources.get(i).entities.values) { - if (!ids.has(entity.installationId || entity.id) || !entity.show) - continue; + // Outline entities are `:outline:`. + const recordId = String(entity.id).replace(/:outline:\d+$/, ''); + if (!ids.has(recordId) || !entity.show) continue; if (entity.billboard || entity.point) markers++; if (entity.polyline) outlines++; } diff --git a/src/data/localGeojson.test.mjs b/src/data/localGeojson.test.mjs index 13cde65a51..0535fc2e67 100644 --- a/src/data/localGeojson.test.mjs +++ b/src/data/localGeojson.test.mjs @@ -21,6 +21,8 @@ import { getRenderGovernorDiagnostics, _resetRenderGovernorForTest, } from '../renderGovernor.js'; +import { getContextStore } from './contextStore.js'; +import { readEntityRecord } from './entityRecords.js'; /** The catalog's services, with the overlay host each test supplies. */ const createLocalGeoJsonLayer = (options) => @@ -486,7 +488,7 @@ for (const [heightM, minStemM, maxStemM] of [[500, 45, 90], [10000, 1100, 1400]] const env = await createRealLocalLayerHarness(); t.after(() => { env.layer.destroy(env.viewer); env.cleanup(); }); const entity = env.dataSources[0].entities.values[0]; - const carto = entity.__localBaseCarto; + const carto = Cesium.Cartographic.fromCartesian(targetPositionOf(entity)); env.viewer.camera.positionWC = Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, heightM); env.preRender.raise(env.viewer.scene, Cesium.JulianDate.now()); const positions = entity.polyline.positions.getValue(Cesium.JulianDate.now()); @@ -894,10 +896,16 @@ function runArmedRetryChain(env, t, clock, cycles) { } } +/** The stem base an entity registered for voice targeting. */ +function targetPositionOf(entity) { + const contextId = readEntityRecord(entity)?.contextId; + return getContextStore().entities.get(contextId)?.targetPosition; +} + /** Height of the (mutated-in-place) stem base — 0 until a sample lands. */ function baseHeightM(env) { const entity = env.dataSources[0].entities.values[0]; - return Cesium.Cartographic.fromCartesian(entity.__localBaseCartesian).height; + return Cesium.Cartographic.fromCartesian(targetPositionOf(entity)).height; } /** diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js index 1d04fa46c1..90276634a6 100644 --- a/src/data/localGeojsonCore.js +++ b/src/data/localGeojsonCore.js @@ -327,6 +327,8 @@ export function createLocalGeoJsonLayer( }, ) { let _dataSource = null; + // The entities this layer loaded, so its click and teardown recognise them. + const _ownEntities = new WeakSet(); let _enabled = false; let _clickHandler = null; let _count = 0; @@ -464,7 +466,7 @@ export function createLocalGeoJsonLayer( releaseDataSource(viewer); _overlayPublisher.hide(); clearSelectedEntityContextForLayer(id); - if (viewer?.selectedEntity?.__localLayerId === id) { + if (_ownEntities.has(viewer?.selectedEntity)) { viewer.selectedEntity = undefined; } if (_preRenderRemover) { @@ -641,7 +643,7 @@ export function createLocalGeoJsonLayer( for (let i = 0; i < entities.length; i++) { const feature = entities[i]; - feature.__localLayerId = id; // Tag it so our click handler knows it belongs to this layer + _ownEntities.add(feature); let pos = feature.position?.getValue(Cesium.JulianDate.now()); @@ -686,9 +688,6 @@ export function createLocalGeoJsonLayer( const properties = propertyObject(feature); const recordId = String(feature.id ?? i); - // Store references for bounded stem scaling and native picking. - feature.__localBaseCarto = carto; - feature.__localBaseCartesian = base; registerEntityContext(feature, { id: `${id}:${recordId}`, layerId: id, @@ -703,6 +702,9 @@ export function createLocalGeoJsonLayer( longitude: Number( Cesium.Math.toDegrees(carto.longitude).toFixed(6), ), + // The surface base voice targeting projects. Ground sampling + // re-grounds it in place, so this stays current. + targetPosition: base, }); // Constant properties are refreshed on the existing 450 ms source @@ -792,7 +794,7 @@ export function createLocalGeoJsonLayer( if (!_enabled) return; const picked = viewer.scene.pick(click.position); - if (picked && picked.id && picked.id.__localLayerId === id) { + if (picked && _ownEntities.has(picked.id)) { const entity = picked.id; viewer.selectedEntity = entity; selectEntityContext(entity); @@ -1174,7 +1176,6 @@ function setLocalGroundHeight(record, height) { Cesium.Ellipsoid.WGS84, record.base, ); - record.entity.__localBaseCartesian = record.base; } function updateLocalStemGeometry(viewer, record, now, knownDistance = null) { diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index d5cfc4d26b..3ffc333542 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -185,9 +185,8 @@ export function createSelection({ // Refreshed every registration: the anchor re-grounds onto the DEM when // its floor cell warms, and voice targeting must project the same point // the sprite renders at. - fire.contextEntity.__localBaseCartesian = - components.model.firePosition(fire); registerEntityContext(fire.contextEntity, { + targetPosition: components.model.firePosition(fire), id: recordId, layerId: id, layerName: name, diff --git a/src/layers/installations/markerState.js b/src/layers/installations/markerState.js index 7738011acf..295e9a733c 100644 --- a/src/layers/installations/markerState.js +++ b/src/layers/installations/markerState.js @@ -3,5 +3,7 @@ import { createEntityStore } from '../../data/entityRecords.js'; /** * What the installations layer last drew for a retained marker entity, so an * unchanged record leaves it alone: `heightM` (surface height) and `selected`. + * Selection fills and outlines record the installation they belong to as + * `recordId`, which a pick on them resolves through. */ export const installationMarkers = createEntityStore(); diff --git a/src/layers/installations/namedMarkers.js b/src/layers/installations/namedMarkers.js index 48a314ac2d..73177873da 100644 --- a/src/layers/installations/namedMarkers.js +++ b/src/layers/installations/namedMarkers.js @@ -128,6 +128,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { const marker = markers.get(alias); markers.delete(alias); marker.point.id = { installationId: record.id }; + marker.recordId = record.id; marker.entry.id = record.id; markers.set(record.id, marker); } @@ -148,10 +149,12 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { ); let marker = markers.get(record.id); if (!marker) { - const id = { installationId: record.id }; marker = { + recordId: record.id, point: points.add({ - id, + // The app's own pick payload. An object, not the bare record id, so the + // shared pick registry keeps treating a point click as it always has. + id: { installationId: record.id }, position, pixelSize: 7, color: parts.model.colorFor(record), @@ -197,7 +200,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) { visit(visitor) { for (let i = 0; i < ordered.length; i++) { const marker = ordered[i]; - visitor(marker.point.id.installationId, marker.point); + visitor(marker.recordId, marker.point); } }, refresh, diff --git a/src/layers/installations/rendering.js b/src/layers/installations/rendering.js index e1a46f7005..8b76d83d3d 100644 --- a/src/layers/installations/rendering.js +++ b/src/layers/installations/rendering.js @@ -84,7 +84,7 @@ export function createRendering({ classificationType, }, }); - fill.installationId = record.id; + installationMarkers.write(fill).recordId = record.id; selectedFillIds.push(fill.id); } governorRequestRender('installation-selection-fill'); @@ -267,7 +267,7 @@ export function createRendering({ classificationType: Cesium.ClassificationType.BOTH, }, }); - outline.installationId = record.id; + installationMarkers.write(outline).recordId = record.id; entityIds.push(outline.id); } Object.assign(installationMarkers.write(entity), { diff --git a/src/layers/installations/selection.js b/src/layers/installations/selection.js index 26a4980ef4..bcf623b786 100644 --- a/src/layers/installations/selection.js +++ b/src/layers/installations/selection.js @@ -1,6 +1,7 @@ import * as Cesium from 'cesium'; import { isPointerFree } from '../../data/inputOwnership.js'; import { LAYER_ID } from './policy.js'; +import { installationMarkers } from './markerState.js'; export function createSelection({ state: layerState, @@ -58,9 +59,11 @@ export function createSelection({ if (!isPointerFree()) return; if (!layerState.enabled) return; const picked = viewer.scene.pick(click.position); + const target = picked?.id; const id = - picked?.id?.installationId || - (typeof picked?.id?.id === 'string' ? picked.id.id : null); + target?.installationId || + installationMarkers.read(target)?.recordId || + (typeof target?.id === 'string' ? target.id : null); if (id && layerState.recordById.has(id) && id !== layerState.selectedId) { selectRecord(id); } else if (layerState.selectedId) { diff --git a/src/layers/installations/selectionFill.test.mjs b/src/layers/installations/selectionFill.test.mjs index e3a29c3766..5086a4a5af 100644 --- a/src/layers/installations/selectionFill.test.mjs +++ b/src/layers/installations/selectionFill.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import * as C from 'cesium'; import { createRendering } from './rendering.js'; import { createLifecycle } from './lifecycle.js'; +import { installationMarkers } from './markerState.js'; function harness() { const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]]; @@ -23,7 +24,7 @@ test('selected multipart footprints classify Google tiles with one constant tran const fills = h.state.dataSource.entities.values.slice(); assert.equal(fills.length, 2); for (const fill of fills) { - assert.equal(fill.installationId, 'base'); + assert.equal(installationMarkers.read(fill)?.recordId, 'base'); assert.equal(fill.polygon.classificationType.getValue(), C.ClassificationType.CESIUM_3D_TILE); assert.equal(fill.polygon.height, undefined); assert.equal(fill.polygon.extrudedHeight, undefined); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 6ab6884566..24d5f109b7 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -3983,7 +3983,7 @@ function visibleEntityContexts( const candidates = []; for (const { record } of nearbyRecords) { - const position = record.entity?.__localBaseCartesian; + const position = record.targetPosition; if (!position) continue; const screen = Cesium.SceneTransforms.worldToWindowCoordinates( viewer.scene, From 37dd4058c1b7c9b54f49290403d1bb2f3f8c9f05 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 18:35:12 -0800 Subject: [PATCH 011/470] Add columnar icon sets drawn by an instanced Cesium primitive Icon rows live in typed-array columns: one packed motion segment (hold, lerp or arc, with a course glide), style, colour and pick ids per row. The primitive draws every row in one instanced call, dead-reckons in the vertex shader, matches the billboard treatment the fleet layers use, and picks and drill-picks like a billboard. Cyber sonar covers icon sets. --- scripts/package-boundaries.json | 4 + src/cyberSonarGpu.js | 19 +- src/data/iconAtlas.js | 150 ++++++++ src/data/iconSegment.js | 320 +++++++++++++++++ src/data/iconSegment.test.mjs | 215 ++++++++++++ src/data/iconSet.js | 468 +++++++++++++++++++++++++ src/data/iconSet.test.mjs | 227 +++++++++++++ src/data/iconSetPrimitive.js | 584 ++++++++++++++++++++++++++++++++ 8 files changed, 1982 insertions(+), 5 deletions(-) create mode 100644 src/data/iconAtlas.js create mode 100644 src/data/iconSegment.js create mode 100644 src/data/iconSegment.test.mjs create mode 100644 src/data/iconSet.js create mode 100644 src/data/iconSet.test.mjs create mode 100644 src/data/iconSetPrimitive.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a76faec8df..f3467710f3 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2259,6 +2259,10 @@ "src/hudLayoutPolicy.js", "src/ui/radioPanelPlacement.js", "src/cyberSonarGpu.js", + "src/data/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", "src/scenes/nepalEvidencePack.js", "src/data/approxDistance.js", "src/data/bhoteKoshiEvent.js", diff --git a/src/cyberSonarGpu.js b/src/cyberSonarGpu.js index bb4aff4d68..9689d534bd 100644 --- a/src/cyberSonarGpu.js +++ b/src/cyberSonarGpu.js @@ -1,4 +1,5 @@ import * as Cesium from 'cesium'; +import { IconSetPrimitive } from './data/iconSetPrimitive.js'; // Narrow, version-tested engine adapter. Cesium has no public custom shader // option for native point/billboard collections. Do not patch its prototypes or @@ -64,9 +65,15 @@ export function sonarVertexSource(source, kind) { kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale'; const lowAttribute = kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation'; + // Icon sets move rows on the GPU, so their shader publishes the anchor itself. + const anchorSource = + kind === 'icon' + ? 'iconAnchorClip' + : `czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz)`; if ( - !text.includes(attribute) || - !text.includes(lowAttribute) || + (kind === 'icon' + ? !text.includes('iconAnchorClip') + : !text.includes(attribute) || !text.includes(lowAttribute)) || !text.includes('v_color') || !/void\s+main\s*\(\s*\)/.test(text) ) @@ -83,7 +90,7 @@ void main() { gev_sonar_main(); // All corners/glyphs share the contact anchor, before native screen offsets. // Leave gl_Position untouched so appearance never changes geometry or picks. - vec4 anchor = czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz); + vec4 anchor = ${anchorSource}; if (anchor.w <= 0.0) return; vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5; float floorValue = u_gevSonar.z; @@ -108,7 +115,7 @@ void main() { v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72; // Apply before native fragment pass classification, never after main(). v_color.a *= factor; - ${kind === 'point' ? 'v_outlineColor.a *= factor;' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'} + ${kind === 'point' ? 'v_outlineColor.a *= factor;' : kind === 'icon' ? '' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'} } `, ]; @@ -208,7 +215,9 @@ export function createCyberSonarGpu(scene, readFrame) { ? 'point' : native.owner instanceof Cesium.BillboardCollection ? 'billboard' - : null; + : native.owner instanceof IconSetPrimitive + ? 'icon' + : null; if (!kind || !native.shaderProgram || !native.uniformMap) continue; const source = native.shaderProgram; // Label backgrounds are non-SDF billboard batches. The version-tested diff --git a/src/data/iconAtlas.js b/src/data/iconAtlas.js new file mode 100644 index 0000000000..8e08c2532e --- /dev/null +++ b/src/data/iconAtlas.js @@ -0,0 +1,150 @@ +/** + * @module iconAtlas + * @description The images icon sets draw, packed into one canvas. A layer asks for a + * slot by image URL and raster size and gets a number at once; the image loads and is + * packed later, and until then its slot is empty and rows using it draw nothing (as a + * Cesium billboard waits for its image). + * + * The renderer uploads {@link iconAtlas}.canvas whenever `version` changes and reads + * each slot's texture rectangle from `rects`. + */ + +/** Slots a renderer can address (one vec4 uniform each). */ +export const MAX_ICON_SLOTS = 64; + +const PADDING_PX = 2; +const START_SIZE_PX = 1024; +const MAX_SIZE_PX = 4096; + +function createAtlas() { + const slotOfKey = new Map(); + const entries = []; + const atlas = { + /** Bumped whenever the canvas or a slot rectangle changes. */ + version: 0, + canvas: null, + width: 0, + height: 0, + /** Per slot `[u0, v0, u1, v1]`, zero until the image is packed. */ + rects: new Float32Array(MAX_ICON_SLOTS * 4), + get size() { + return entries.length; + }, + + /** + * The slot for `url` rasterised at `sizePx` square. + * @param {string} url + * @param {number} sizePx + * @returns {number} + */ + slot(url, sizePx) { + const key = `${sizePx}|${url}`; + const known = slotOfKey.get(key); + if (known !== undefined) return known; + if (entries.length >= MAX_ICON_SLOTS) + throw new RangeError( + `The icon atlas holds at most ${MAX_ICON_SLOTS} images`, + ); + const slot = entries.length; + const entry = { url, sizePx, image: null, x: 0, y: 0 }; + entries.push(entry); + slotOfKey.set(key, slot); + load(entry); + return slot; + }, + + /** Whether a slot's image is packed and drawable. */ + ready(slot) { + return atlas.rects[slot * 4 + 2] > 0; + }, + }; + + function load(entry) { + if (typeof Image === 'undefined') return; // Node: slots only + const image = new Image(entry.sizePx, entry.sizePx); + image.decoding = 'async'; + // A cross-origin image would taint the canvas and every texture upload. + image.crossOrigin = 'anonymous'; + image.onload = () => { + entry.image = image; + if (!pack()) { + entry.image = null; // does not fit: leave its slot empty, keep the rest + entry.failed = true; + console.warn( + `[iconAtlas] No room for ${entry.sizePx} px icon; slot stays empty`, + ); + pack(); + } + }; + image.onerror = () => { + entry.failed = true; + console.warn( + `[iconAtlas] Icon failed to load: ${entry.url.slice(0, 80)}`, + ); + }; + image.src = entry.url; + } + + // Shelf packing over every loaded image, largest first, growing the canvas + // until they fit. Rebuilt in full: the set is a few dozen images. Returns false, + // changing nothing, when they cannot fit at the largest size. + function pack() { + const loaded = entries.filter((entry) => entry.image); + loaded.sort((a, b) => b.sizePx - a.sizePx); + let size = Math.max(atlas.width, START_SIZE_PX); + while (!place(loaded, size)) { + size *= 2; + if (size > MAX_SIZE_PX) return false; + } + if (!atlas.canvas || atlas.width !== size) { + atlas.canvas = + typeof document !== 'undefined' + ? Object.assign(document.createElement('canvas'), { + width: size, + height: size, + }) + : new OffscreenCanvas(size, size); + atlas.width = size; + atlas.height = size; + } + const g = atlas.canvas.getContext('2d'); + g.clearRect(0, 0, size, size); + atlas.rects.fill(0); + for (const entry of loaded) { + g.drawImage(entry.image, entry.x, entry.y, entry.sizePx, entry.sizePx); + const slot = entries.indexOf(entry); + const o = slot * 4; + atlas.rects[o] = entry.x / size; + atlas.rects[o + 1] = entry.y / size; + atlas.rects[o + 2] = (entry.x + entry.sizePx) / size; + atlas.rects[o + 3] = (entry.y + entry.sizePx) / size; + } + atlas.version++; + return true; + } + + function place(loaded, size) { + let x = 0; + let y = 0; + let shelf = 0; + for (const entry of loaded) { + const cell = entry.sizePx + PADDING_PX * 2; + if (x + cell > size) { + x = 0; + y += shelf; + shelf = 0; + } + if (y + cell > size) return false; + entry.x = x + PADDING_PX; + entry.y = y + PADDING_PX; + x += cell; + shelf = Math.max(shelf, cell); + } + return true; + } + + return atlas; +} + +/** The one atlas every icon set draws from. */ +export const iconAtlas = createAtlas(); diff --git a/src/data/iconSegment.js b/src/data/iconSegment.js new file mode 100644 index 0000000000..c23addfb48 --- /dev/null +++ b/src/data/iconSegment.js @@ -0,0 +1,320 @@ +/** + * @module iconSegment + * @description The motion an icon row follows between CPU updates: one segment, packed + * into a row of floats that the CPU ({@link evaluateSegment}) and the GPU + * ({@link ICON_SEGMENT_GLSL}) evaluate the same way at a render time. + * + * A segment is `position(τ) = base + U·e(τ) + V·n(τ)` plus a course: + * - hold: stays at `base`, course fixed; + * - lerp: straight from `base` to `base + U` between two fix times (the interpolation + * between two known fixes), course affine in the fraction; + * - arc: a constant-rate turn from a fix in its east/north plane (`U`, `V`), with the + * elapsed time clamped (warm-up before the first fix, coast after the last). + * + * The arc uses `cos a − cos(a+b) = 2 sin(b/2) sin(a+b/2)`, so its offset is + * `v·t·sinc(ωt/2)·(sin, cos)(a + ωt/2)`: no cancellation in float32 and no branch + * between straight and turning motion. Turn rates under 1e-4 rad/s fly straight, + * as `arcOffsetEnu` does. + * + * Times are seconds since the owning set's epoch. `base` is stored as high and low + * float32 parts (Cesium's EncodedCartesian3) so the GPU can draw it relative to the eye. + */ +import * as Cesium from 'cesium'; +import { norm180, norm360 } from './motionModel.js'; + +/** Floats per packed segment. */ +export const SEGMENT_STRIDE = 24; + +export const SEGMENT_HOLD = 0; +export const SEGMENT_LERP = 1; +export const SEGMENT_ARC = 2; + +// Offsets inside one packed segment. The GPU reads them as six vec4s in this order. +const BASE_HIGH = 0; +const BASE_LOW = 3; +const AXIS_U = 6; +const AXIS_V = 9; +const KIND = 12; +const T0 = 13; +const P1 = 14; // lerp: span (s); arc: smallest elapsed time (s) +const P2 = 15; // arc: largest elapsed time (s) +const SPEED = 16; // m/s +const TRACK = 17; // rad, clockwise from north +const OMEGA = 18; // rad/s +const COURSE0 = 19; // deg +const COURSE_SLOPE = 20; // lerp: deg per unit fraction +const SLEW_OFFSET = 21; // deg still to glide at SLEW_T0 +const SLEW_T0 = 22; // s +const SLEW_RATE = 23; // deg/s + +const DEG = Math.PI / 180; +const STRAIGHT_BELOW_RAD_PER_SEC = 1e-4; + +const _encoded = new Cesium.EncodedCartesian3(); +const _enu = new Cesium.Matrix4(); + +function writeBase(out, o, position) { + Cesium.EncodedCartesian3.fromCartesian(position, _encoded); + out[o + BASE_HIGH] = _encoded.high.x; + out[o + BASE_HIGH + 1] = _encoded.high.y; + out[o + BASE_HIGH + 2] = _encoded.high.z; + out[o + BASE_LOW] = _encoded.low.x; + out[o + BASE_LOW + 1] = _encoded.low.y; + out[o + BASE_LOW + 2] = _encoded.low.z; +} + +function clearMotion(out, o) { + out.fill(0, o + AXIS_U, o + SEGMENT_STRIDE); +} + +/** + * Stay at `position` facing `courseDeg`. + * @param {Float32Array} out + * @param {number} row + * @param {Cesium.Cartesian3} position + * @param {number} courseDeg + */ +export function writeHoldSegment(out, row, position, courseDeg) { + const o = row * SEGMENT_STRIDE; + writeBase(out, o, position); + clearMotion(out, o); + out[o + KIND] = SEGMENT_HOLD; + out[o + COURSE0] = norm360(courseDeg || 0); +} + +/** + * Move straight from `from` (at `t0`) to `to` (at `t1`), holding at either end. + * The course runs from `course0Deg` by `courseSlopeDeg` over the segment. + * @param {Float32Array} out + * @param {number} row + * @param {{from: Cesium.Cartesian3, to: Cesium.Cartesian3, t0: number, t1: number, + * course0Deg: number, courseSlopeDeg: number}} segment + */ +export function writeLerpSegment(out, row, segment) { + const o = row * SEGMENT_STRIDE; + const { from, to } = segment; + writeBase(out, o, from); + clearMotion(out, o); + out[o + AXIS_U] = to.x - from.x; + out[o + AXIS_U + 1] = to.y - from.y; + out[o + AXIS_U + 2] = to.z - from.z; + out[o + KIND] = SEGMENT_LERP; + out[o + T0] = segment.t0; + out[o + P1] = Math.max(0, segment.t1 - segment.t0); + out[o + COURSE0] = norm360(segment.course0Deg || 0); + out[o + COURSE_SLOPE] = segment.courseSlopeDeg || 0; +} + +/** + * Turn at a constant rate from `fix` (at `t0`) in its east/north plane, with the + * elapsed time clamped to `[minDt, maxDt]`. + * @param {Float32Array} out + * @param {number} row + * @param {{fix: Cesium.Cartesian3, t0: number, minDt: number, maxDt: number, + * speedMps: number, trackDeg: number, turnRateDps: number}} segment + */ +export function writeArcSegment(out, row, segment) { + const o = row * SEGMENT_STRIDE; + const { fix } = segment; + writeBase(out, o, fix); + clearMotion(out, o); + Cesium.Transforms.eastNorthUpToFixedFrame(fix, Cesium.Ellipsoid.WGS84, _enu); + // Column-major: columns 0 and 1 are the east and north unit vectors. + out[o + AXIS_U] = _enu[0]; + out[o + AXIS_U + 1] = _enu[1]; + out[o + AXIS_U + 2] = _enu[2]; + out[o + AXIS_V] = _enu[4]; + out[o + AXIS_V + 1] = _enu[5]; + out[o + AXIS_V + 2] = _enu[6]; + const omega = (segment.turnRateDps || 0) * DEG; + out[o + KIND] = SEGMENT_ARC; + out[o + T0] = segment.t0; + out[o + P1] = segment.minDt; + out[o + P2] = segment.maxDt; + out[o + SPEED] = segment.speedMps || 0; + out[o + TRACK] = (segment.trackDeg || 0) * DEG; + out[o + OMEGA] = Math.abs(omega) < STRAIGHT_BELOW_RAD_PER_SEC ? 0 : omega; + out[o + COURSE0] = norm360(segment.trackDeg || 0); +} + +/** + * Glide the displayed course from `fromCourseDeg` onto the segment's own course, + * at most `rateDps`, starting at `t0` (the rate limit at a segment boundary). + * Call after writing the segment. + * @param {Float32Array} out + * @param {number} row + * @param {number} fromCourseDeg + * @param {number} t0 + * @param {number} rateDps + */ +export function writeCourseGlide(out, row, fromCourseDeg, t0, rateDps) { + const o = row * SEGMENT_STRIDE; + out[o + SLEW_OFFSET] = 0; + const target = targetCourse(out, o, t0); + out[o + SLEW_OFFSET] = norm180(fromCourseDeg - target); + out[o + SLEW_T0] = t0; + out[o + SLEW_RATE] = Math.max(0, rateDps); +} + +/** + * Move a row's stored times by `deltaSec` (the epoch moved by `-deltaSec`). + * @param {Float32Array} out + * @param {number} row + * @param {number} deltaSec + */ +export function shiftSegmentTimes(out, row, deltaSec) { + const o = row * SEGMENT_STRIDE; + out[o + T0] += deltaSec; + out[o + SLEW_T0] += deltaSec; +} + +/** Elapsed fraction (lerp) or clamped elapsed seconds (arc) at `tau`. */ +function segmentParameter(seg, o, tau) { + const kind = seg[o + KIND]; + if (kind === SEGMENT_LERP) { + const span = seg[o + P1]; + return span > 0 ? Math.min(1, Math.max(0, (tau - seg[o + T0]) / span)) : 1; + } + if (kind === SEGMENT_ARC) + return Math.min(seg[o + P2], Math.max(seg[o + P1], tau - seg[o + T0])); + return 0; +} + +function sinc(x) { + return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x; +} + +/** + * The displayed course at `tau`, in degrees clockwise from north. + * @param {Float32Array} seg + * @param {number} row + * @param {number} tau + * @returns {number} + */ +export function segmentCourse(seg, row, tau) { + const o = row * SEGMENT_STRIDE; + const course = targetCourse(seg, o, tau); + const offset = seg[o + SLEW_OFFSET]; + if (offset === 0) return norm360(course); + // limitCourseStep: the displayed course turns at the rate toward the segment's + // own (possibly turning) course until it reaches it, then follows it. The + // segment's course is linear and unwrapped, so the gap needs no modulo. + const t0 = seg[o + SLEW_T0]; + const toward = -Math.sign(offset); + const start = targetCourse(seg, o, t0); + const turned = seg[o + SLEW_RATE] * Math.max(0, tau - t0); + const gap = toward * (course - start - offset); + return norm360(turned < gap ? start + offset + toward * turned : course); +} + +/** The segment's own course at `tau`, before any glide. */ +function targetCourse(seg, o, tau) { + const kind = seg[o + KIND]; + const p = segmentParameter(seg, o, tau); + let course = seg[o + COURSE0]; + if (kind === SEGMENT_LERP) course += seg[o + COURSE_SLOPE] * p; + else if (kind === SEGMENT_ARC) course += (seg[o + OMEGA] / DEG) * p; + return course; +} + +/** + * Where the row is at `tau`, in ECEF. + * @param {Float32Array} seg + * @param {number} row + * @param {number} tau + * @param {Cesium.Cartesian3} [result] + * @returns {Cesium.Cartesian3} + */ +export function segmentPosition( + seg, + row, + tau, + result = new Cesium.Cartesian3(), +) { + const o = row * SEGMENT_STRIDE; + let x = seg[o + BASE_HIGH] + seg[o + BASE_LOW]; + let y = seg[o + BASE_HIGH + 1] + seg[o + BASE_LOW + 1]; + let z = seg[o + BASE_HIGH + 2] + seg[o + BASE_LOW + 2]; + const kind = seg[o + KIND]; + if (kind === SEGMENT_LERP) { + const f = segmentParameter(seg, o, tau); + x += seg[o + AXIS_U] * f; + y += seg[o + AXIS_U + 1] * f; + z += seg[o + AXIS_U + 2] * f; + } else if (kind === SEGMENT_ARC) { + const dt = segmentParameter(seg, o, tau); + const half = seg[o + OMEGA] * dt * 0.5; + const reach = seg[o + SPEED] * dt * sinc(half); + const heading = seg[o + TRACK] + half; + const e = reach * Math.sin(heading); + const n = reach * Math.cos(heading); + x += seg[o + AXIS_U] * e + seg[o + AXIS_V] * n; + y += seg[o + AXIS_U + 1] * e + seg[o + AXIS_V + 1] * n; + z += seg[o + AXIS_U + 2] * e + seg[o + AXIS_V + 2] * n; + } + result.x = x; + result.y = y; + result.z = z; + return result; +} + +/** + * GLSL for the same evaluation. Expects the six segment vec4s as `seg0`…`seg5` + * (floats 0–3, 4–7, … of the packed row) and returns the eye-relative position in + * `positionRte` and the course in degrees. + */ +export const ICON_SEGMENT_GLSL = /* glsl */ ` +float iconSinc(float x) { + return abs(x) < 1e-4 ? 1.0 - x * x / 6.0 : sin(x) / x; +} + +float iconSegmentParameter(vec4 seg3, vec4 seg4, float tau) { + float kind = seg3.x; + if (kind == 1.0) { + float span = seg3.z; + return span > 0.0 ? clamp((tau - seg3.y) / span, 0.0, 1.0) : 1.0; + } + if (kind == 2.0) return clamp(tau - seg3.y, seg3.z, seg3.w); + return 0.0; +} + +vec3 iconSegmentPosition(vec4 seg0, vec4 seg1, vec4 seg2, vec4 seg3, vec4 seg4, float tau) { + vec3 high = seg0.xyz; + vec3 low = vec3(seg0.w, seg1.xy); + vec3 axisU = vec3(seg1.zw, seg2.x); + vec3 axisV = seg2.yzw; + vec4 rte = czm_translateRelativeToEye(high, low); + vec3 p = rte.xyz; + float kind = seg3.x; + float t = iconSegmentParameter(seg3, seg4, tau); + if (kind == 1.0) { + p += axisU * t; + } else if (kind == 2.0) { + float half_ = seg4.z * t * 0.5; + float reach = seg4.x * t * iconSinc(half_); + float heading = seg4.y + half_; + p += axisU * (reach * sin(heading)) + axisV * (reach * cos(heading)); + } + return p; +} + +float iconTargetCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) { + float kind = seg3.x; + float t = iconSegmentParameter(seg3, seg4, tau); + float course = seg4.w; + if (kind == 1.0) course += seg5.x * t; + else if (kind == 2.0) course += degrees(seg4.z) * t; + return course; +} + +float iconSegmentCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) { + float course = iconTargetCourse(seg3, seg4, seg5, tau); + float offset = seg5.y; + if (offset == 0.0) return course; + float toward = -sign(offset); + float start = iconTargetCourse(seg3, seg4, seg5, seg5.z); + float turned = seg5.w * max(0.0, tau - seg5.z); + float gap = toward * (course - start - offset); + return turned < gap ? start + offset + toward * turned : course; +} +`; diff --git a/src/data/iconSegment.test.mjs b/src/data/iconSegment.test.mjs new file mode 100644 index 0000000000..6384d91aa0 --- /dev/null +++ b/src/data/iconSegment.test.mjs @@ -0,0 +1,215 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + SEGMENT_STRIDE, + segmentCourse, + segmentPosition, + writeArcSegment, + writeCourseGlide, + writeHoldSegment, + writeLerpSegment, +} from './iconSegment.js'; +import { + arcOffsetEnu, + lerpAngleDeg, + limitCourseStep, + norm180, +} from './motionModel.js'; + +const fix = Cesium.Cartesian3.fromDegrees(-97.04, 32.9, 10_500); + +/** What the flights layer's _extrapolateFix draws for the same fix and dt. */ +function productionArc(position, speed, trackDeg, turnRateDps, dt) { + const arc = arcOffsetEnu(speed, trackDeg, turnRateDps, dt, {}); + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position); + const offset = new Cesium.Cartesian3(arc.east, arc.north, 0); + return { + position: Cesium.Matrix4.multiplyByPoint( + enu, + offset, + new Cesium.Cartesian3(), + ), + course: arc.endCourseDeg, + }; +} + +function courseGap(a, b) { + return Math.abs(norm180(a - b)); +} + +test('a hold stays put to float32 encoding precision', () => { + const seg = new Float32Array(SEGMENT_STRIDE * 2); + writeHoldSegment(seg, 1, fix, 271); + const at = segmentPosition(seg, 1, 1234); + assert.ok(Cesium.Cartesian3.distance(at, fix) < 0.005); + assert.equal(segmentCourse(seg, 1, 99), 271); +}); + +test('a lerp matches Cesium.Cartesian3.lerp between two fixes and holds at both ends', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + const to = Cesium.Cartesian3.fromDegrees(-97.0, 32.93, 10_650); + writeLerpSegment(seg, 0, { + from: fix, + to, + t0: 100, + t1: 110, + course0Deg: 40, + courseSlopeDeg: 6, + }); + for (const tau of [100, 102.5, 107, 110]) { + const want = Cesium.Cartesian3.lerp( + fix, + to, + (tau - 100) / 10, + new Cesium.Cartesian3(), + ); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, tau), want) < 0.01, + `τ=${tau}`, + ); + } + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 50), fix) < 0.01, + ); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 500), to) < 0.01, + ); + assert.ok(courseGap(segmentCourse(seg, 0, 105), 43) < 1e-4); +}); + +test('a lerp course reproduces the blended track-and-chord course across the segment', () => { + // _deadReckon: lerpAngle(lerpAngle(trackFrom, trackTo, t), chord, w). + const trackFrom = 350; + const trackTo = 20; + const chord = 10; + const w = 0.6; + const at = (t) => lerpAngleDeg(lerpAngleDeg(trackFrom, trackTo, t), chord, w); + const course0 = at(0); + const slope = norm180(trackTo - trackFrom) * (1 - w); + const seg = new Float32Array(SEGMENT_STRIDE); + const to = Cesium.Cartesian3.fromDegrees(-97.0, 32.93, 10_650); + writeLerpSegment(seg, 0, { + from: fix, + to, + t0: 0, + t1: 10, + course0Deg: course0, + courseSlopeDeg: slope, + }); + for (const t of [0, 0.25, 0.5, 0.9, 1]) + assert.ok(courseGap(segmentCourse(seg, 0, t * 10), at(t)) < 1e-3, `t=${t}`); +}); + +test('an arc matches the production turn for straight, slow, standard and tight turns', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + for (const turnRateDps of [0, 0.004, 0.01, 0.5, 3, -3, 12]) { + for (const dt of [0.08, 1, 30, 120, 300]) { + writeArcSegment(seg, 0, { + fix, + t0: 1000, + minDt: -60, + maxDt: 300, + speedMps: 240, + trackDeg: 305, + turnRateDps, + }); + const want = productionArc(fix, 240, 305, turnRateDps, dt); + const got = segmentPosition(seg, 0, 1000 + dt); + assert.ok( + Cesium.Cartesian3.distance(got, want.position) < 0.05, + `ω=${turnRateDps}°/s dt=${dt}s off by ${Cesium.Cartesian3.distance(got, want.position)} m`, + ); + assert.ok( + courseGap(segmentCourse(seg, 0, 1000 + dt), want.course) < 1e-3, + ); + } + } +}); + +test('an arc extrapolates backward for warm-up and clamps both ends', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + writeArcSegment(seg, 0, { + fix, + t0: 500, + minDt: -60, + maxDt: 0, + speedMps: 200, + trackDeg: 90, + turnRateDps: 1.5, + }); + const back = productionArc(fix, 200, 90, 1.5, -20); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 480), back.position) < + 0.05, + ); + const earliest = productionArc(fix, 200, 90, 1.5, -60); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 0), earliest.position) < + 0.05, + ); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 900), fix) < 0.01, + ); +}); + +test('the course glide follows limitCourseStep onto a steady target', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + writeHoldSegment(seg, 0, fix, 10); + writeCourseGlide(seg, 0, 300, 50, 24); + let prev = 300; + for (let tau = 50; tau <= 56; tau += 0.08) { + assert.ok(courseGap(segmentCourse(seg, 0, tau), prev) < 1e-3, `τ=${tau}`); + prev = limitCourseStep(prev, 10, 24, 0.08); + } + assert.equal(segmentCourse(seg, 0, 80), 10); +}); + +test('writing a segment clears the previous one', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + writeArcSegment(seg, 0, { + fix, + t0: 0, + minDt: 0, + maxDt: 300, + speedMps: 250, + trackDeg: 0, + turnRateDps: 3, + }); + writeCourseGlide(seg, 0, 90, 0, 30); + writeHoldSegment(seg, 0, fix, 5); + assert.ok( + Cesium.Cartesian3.distance(segmentPosition(seg, 0, 100), fix) < 0.005, + ); + assert.equal(segmentCourse(seg, 0, 0), 5); +}); + +test('the course glide never outruns the rate while its target turns', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + writeArcSegment(seg, 0, { + fix, + t0: 0, + minDt: 0, + maxDt: 300, + speedMps: 200, + trackDeg: 90, + turnRateDps: 3, + }); + writeCourseGlide(seg, 0, 60, 0, 24); + let prev = 60; + for (let tau = 0; tau <= 4; tau += 0.01) { + assert.ok( + courseGap(segmentCourse(seg, 0, tau), prev) < 0.05, + `τ=${tau.toFixed(2)}`, + ); + prev = limitCourseStep(prev, 90 + 3 * (tau + 0.01), 24, 0.01); + } + assert.ok( + courseGap(segmentCourse(seg, 0, 1), 84) < 0.05, + '24° in the first second, not 27°', + ); + assert.ok( + courseGap(segmentCourse(seg, 0, 10), 120) < 1e-3, + 'then it follows the turn', + ); +}); diff --git a/src/data/iconSet.js b/src/data/iconSet.js new file mode 100644 index 0000000000..c268e6d260 --- /dev/null +++ b/src/data/iconSet.js @@ -0,0 +1,468 @@ +/** + * @module iconSet + * @description A set of icons the app draws, held as typed-array columns: the only copy of + * what was pushed. Each row is one icon, keyed by a string id and carrying an opaque + * `meta` that comes back on picks. A row moves along its segment ({@link module:iconSegment}) + * on the renderer's clock, so the CPU writes a row only when its motion or style changes. + * + * Rows are packed: removing one moves the last row into its place, so the renderer + * draws `count` instances and the CPU walks rows by index. Writes mark rows dirty per + * column ({@link DirtyRows}) for the renderer to upload. + * + * Segment times are float32 seconds since the set's epoch. The renderer calls + * {@link rebase} once a frame so they stay small (sub-millisecond steps) however + * long the session runs. + */ +import * as Cesium from 'cesium'; +import { + SEGMENT_STRIDE, + segmentCourse, + segmentPosition, + shiftSegmentTimes, +} from './iconSegment.js'; + +/** Floats per row of style: size, scale, alpha, atlas slots, flags, focus, near/far scaler. */ +export const STYLE_STRIDE = 12; + +const WIDTH = 0; +const HEIGHT = 1; +const SCALE = 2; +const ALPHA = 3; +const IMAGE_FAR = 4; +const IMAGE_NEAR = 5; +const FLAGS = 6; +const FOCUS = 7; +const NEAR_DISTANCE = 8; +const NEAR_VALUE = 9; +const FAR_DISTANCE = 10; +const FAR_VALUE = 11; + +/** Row flags, combined in the style's flags float. */ +export const ICON_SHOWN = 1; +/** Rotate the icon along its course on screen (otherwise upright). */ +export const ICON_ROTATES = 2; +/** Fade and shrink toward the globe's limb (aircraft recession). */ +export const ICON_RECEDES = 4; +/** Lift the row 12 m along the normal before the horizon test (fixes near the ground). */ +export const ICON_CULL_LIFT = 8; + +/** Move the epoch forward once render times pass this many seconds. */ +const REBASE_AFTER_SEC = 1800; + +/** + * Rows written since the last upload, for one column. Uploads go out as runs of + * nearby rows, so a removal near the top and a write near the bottom send two + * small runs rather than the whole column. + */ +export class DirtyRows { + constructor(capacity) { + this._marked = new Uint8Array(capacity); + this._rows = []; + this._all = false; + } + + mark(row) { + if (this._all || this._marked[row]) return; + this._marked[row] = 1; + this._rows.push(row); + } + + markAll() { + this._all = true; + } + + get empty() { + return !this._all && this._rows.length === 0; + } + + /** + * Coalesced `[from, to]` runs of dirty rows below `count`, merging rows closer + * than `gap`; everything when marked all or when most rows are dirty. + * @param {number} count + * @param {number} [gap] + * @returns {Array<[number, number]>} + */ + runs(count, gap = 32) { + if (count === 0) return []; + if (this._all || this._rows.length * 4 > count) return [[0, count - 1]]; + const rows = this._rows.filter((row) => row < count).sort((a, b) => a - b); + const runs = []; + for (const row of rows) { + const last = runs[runs.length - 1]; + if (last && row - last[1] <= gap) last[1] = row; + else runs.push([row, row]); + } + return runs; + } + + clear() { + for (const row of this._rows) this._marked[row] = 0; + this._rows.length = 0; + this._all = false; + } + + grow(capacity) { + const marked = new Uint8Array(capacity); + marked.set(this._marked); + this._marked = marked; + this.markAll(); + } +} + +/** + * @param {{ capacity?: number, epoch?: Cesium.JulianDate }} [options] + */ +export function createIconSet({ capacity = 1024, epoch } = {}) { + capacity = Math.max(1, capacity); + const rowOfId = new Map(); + let ids = []; + let metas = []; + let handles = []; + let segments = new Float32Array(capacity * SEGMENT_STRIDE); + let style = new Float32Array(capacity * STYLE_STRIDE); + let colors = new Uint8Array(capacity * 4); + // CPU only: until when (seconds since the epoch) the row's segment holds. + let expires = new Float64Array(capacity); + let count = 0; + const epochTime = Cesium.JulianDate.clone(epoch ?? Cesium.JulianDate.now()); + + const set = { + /** Bumped when the columns are reallocated; the renderer rebuilds its buffers. */ + generation: 0, + dirty: { + segments: new DirtyRows(capacity), + style: new DirtyRows(capacity), + colors: new DirtyRows(capacity), + }, + show: true, + /** Called with a row's renderer handle when the row goes away. */ + onRelease: null, + + get count() { + return count; + }, + get capacity() { + return capacity; + }, + get segments() { + return segments; + }, + get style() { + return style; + }, + get colors() { + return colors; + }, + get epoch() { + return epochTime; + }, + + /** Seconds since the set's epoch: the clock segments are written in. */ + seconds(julianDate) { + return Cesium.JulianDate.secondsDifference(julianDate, epochTime); + }, + + /** + * Move the epoch to `julianDate` once it is more than half an hour ahead, + * shifting every stored time. Call between frames, never while a caller holds + * times in the old base. + * @returns {boolean} Whether it moved. + */ + rebase(julianDate) { + const shift = set.seconds(julianDate); + if (shift < REBASE_AFTER_SEC) return false; + for (let row = 0; row < count; row++) { + shiftSegmentTimes(segments, row, -shift); + expires[row] -= shift; + } + Cesium.JulianDate.clone(julianDate, epochTime); + set.dirty.segments.markAll(); + return true; + }, + + has(id) { + return rowOfId.has(id); + }, + row(id) { + return rowOfId.get(id) ?? -1; + }, + idAt(row) { + return ids[row]; + }, + metaAt(row) { + return metas[row]; + }, + handleAt(row) { + return handles[row]; + }, + setHandle(row, handle) { + handles[row] = handle; + }, + + /** + * Add a row (hidden, no image) or return the existing row for `id`. + * @param {string} id + * @param {*} [meta] + * @returns {number} The row. + */ + add(id, meta) { + const existing = rowOfId.get(id); + if (existing !== undefined) { + metas[existing] = meta; + return existing; + } + if (count === capacity) grow(capacity * 2); + const row = count++; + rowOfId.set(id, row); + ids[row] = id; + metas[row] = meta; + handles[row] = undefined; + segments.fill(0, row * SEGMENT_STRIDE, (row + 1) * SEGMENT_STRIDE); + style.fill(0, row * STYLE_STRIDE, (row + 1) * STYLE_STRIDE); + const o = row * STYLE_STRIDE; + style[o + SCALE] = 1; + style[o + ALPHA] = 1; + style[o + FOCUS] = 1; + style[o + IMAGE_FAR] = -1; + style[o + IMAGE_NEAR] = -1; + colors.fill(255, row * 4, row * 4 + 4); + expires[row] = -Infinity; + markRow(row); + return row; + }, + + /** Remove `id`'s row; the last row moves into its place. */ + remove(id) { + const row = rowOfId.get(id); + if (row === undefined) return false; + rowOfId.delete(id); + const handle = handles[row]; + const last = --count; + if (row !== last) { + segments.copyWithin( + row * SEGMENT_STRIDE, + last * SEGMENT_STRIDE, + (last + 1) * SEGMENT_STRIDE, + ); + style.copyWithin( + row * STYLE_STRIDE, + last * STYLE_STRIDE, + (last + 1) * STYLE_STRIDE, + ); + colors.copyWithin(row * 4, last * 4, last * 4 + 4); + expires[row] = expires[last]; + ids[row] = ids[last]; + metas[row] = metas[last]; + handles[row] = handles[last]; + rowOfId.set(ids[row], row); + markRow(row); + } + ids[last] = undefined; + metas[last] = undefined; + handles[last] = undefined; + if (handle !== undefined) set.onRelease?.(handle); + return true; + }, + + clear() { + for (let row = 0; row < count; row++) + if (handles[row] !== undefined) set.onRelease?.(handles[row]); + rowOfId.clear(); + ids = []; + metas = []; + handles = []; + count = 0; + }, + + /** Mark a row's segment written (after a write*Segment call on `segments`). */ + segmentWritten(row, expiresAt = Infinity) { + expires[row] = expiresAt; + set.dirty.segments.mark(row); + }, + /** Until when (seconds since the epoch) the row's segment holds. */ + expires(row) { + return expires[row]; + }, + + setShown(row, shown) { + setFlag(row, ICON_SHOWN, shown); + }, + shown(row) { + return (style[row * STYLE_STRIDE + FLAGS] & ICON_SHOWN) !== 0; + }, + setFlag(row, flag, on) { + setFlag(row, flag, on); + }, + flags(row) { + return style[row * STYLE_STRIDE + FLAGS]; + }, + + setSize(row, width, height) { + const o = row * STYLE_STRIDE; + if ( + style[o + WIDTH] === Math.fround(width) && + style[o + HEIGHT] === Math.fround(height) + ) + return; + style[o + WIDTH] = width; + style[o + HEIGHT] = height; + set.dirty.style.mark(row); + }, + width(row) { + return style[row * STYLE_STRIDE + WIDTH]; + }, + height(row) { + return style[row * STYLE_STRIDE + HEIGHT]; + }, + + setScale(row, scale) { + writeStyle(row, SCALE, scale); + }, + scale(row) { + return style[row * STYLE_STRIDE + SCALE]; + }, + + /** The row's own alpha; the renderer multiplies in recession and focus. */ + setAlpha(row, alpha) { + writeStyle(row, ALPHA, alpha); + }, + alpha(row) { + return style[row * STYLE_STRIDE + ALPHA]; + }, + + /** Focus de-emphasis factor, 1 when not de-emphasised. */ + setFocus(row, factor) { + writeStyle(row, FOCUS, factor); + }, + focus(row) { + return style[row * STYLE_STRIDE + FOCUS]; + }, + + /** Atlas slots: `far` for small on-screen sizes, `near` once the icon is large. */ + setImage(row, far, near = far) { + const o = row * STYLE_STRIDE; + if (style[o + IMAGE_FAR] === far && style[o + IMAGE_NEAR] === near) + return; + style[o + IMAGE_FAR] = far; + style[o + IMAGE_NEAR] = near; + set.dirty.style.mark(row); + }, + imageFar(row) { + return style[row * STYLE_STRIDE + IMAGE_FAR]; + }, + imageNear(row) { + return style[row * STYLE_STRIDE + IMAGE_NEAR]; + }, + + /** Size by camera distance, as Cesium's NearFarScalar (unset: 1 everywhere). */ + setScaleByDistance(row, scalar) { + const o = row * STYLE_STRIDE; + const near = scalar?.near ?? 0; + const nearValue = scalar?.nearValue ?? 1; + const far = scalar?.far ?? 0; + const farValue = scalar?.farValue ?? 1; + if ( + style[o + NEAR_DISTANCE] === Math.fround(near) && + style[o + NEAR_VALUE] === Math.fround(nearValue) && + style[o + FAR_DISTANCE] === Math.fround(far) && + style[o + FAR_VALUE] === Math.fround(farValue) + ) + return; + style[o + NEAR_DISTANCE] = near; + style[o + NEAR_VALUE] = nearValue; + style[o + FAR_DISTANCE] = far; + style[o + FAR_VALUE] = farValue; + set.dirty.style.mark(row); + }, + scaleByDistance(row, result = new Cesium.NearFarScalar()) { + const o = row * STYLE_STRIDE; + result.near = style[o + NEAR_DISTANCE]; + result.nearValue = style[o + NEAR_VALUE]; + result.far = style[o + FAR_DISTANCE]; + result.farValue = style[o + FAR_VALUE]; + return result; + }, + + /** Tint as a Cesium.Color; its alpha multiplies the row's own alpha. */ + setColor(row, color) { + const o = row * 4; + const r = Cesium.Color.floatToByte(color.red); + const g = Cesium.Color.floatToByte(color.green); + const b = Cesium.Color.floatToByte(color.blue); + const a = Cesium.Color.floatToByte(color.alpha); + if ( + colors[o] === r && + colors[o + 1] === g && + colors[o + 2] === b && + colors[o + 3] === a + ) + return; + colors[o] = r; + colors[o + 1] = g; + colors[o + 2] = b; + colors[o + 3] = a; + set.dirty.colors.mark(row); + }, + color(row, result = new Cesium.Color()) { + const o = row * 4; + return Cesium.Color.fromBytes( + colors[o], + colors[o + 1], + colors[o + 2], + colors[o + 3], + result, + ); + }, + + /** Where the row is at `tau` (seconds since the epoch). */ + position(row, tau, result) { + return segmentPosition(segments, row, tau, result); + }, + /** The row's displayed course at `tau`, degrees clockwise from north. */ + course(row, tau) { + return segmentCourse(segments, row, tau); + }, + }; + + function markRow(row) { + set.dirty.segments.mark(row); + set.dirty.style.mark(row); + set.dirty.colors.mark(row); + } + + function writeStyle(row, field, value) { + const o = row * STYLE_STRIDE + field; + if (style[o] === Math.fround(value)) return; + style[o] = value; + set.dirty.style.mark(row); + } + + function setFlag(row, flag, on) { + const o = row * STYLE_STRIDE + FLAGS; + const flags = style[o]; + const next = on ? flags | flag : flags & ~flag; + if (next === flags) return; + style[o] = next; + set.dirty.style.mark(row); + } + + function grow(next) { + const s = new Float32Array(next * SEGMENT_STRIDE); + s.set(segments); + const st = new Float32Array(next * STYLE_STRIDE); + st.set(style); + const c = new Uint8Array(next * 4); + c.set(colors); + const e = new Float64Array(next); + e.set(expires); + segments = s; + style = st; + colors = c; + expires = e; + capacity = next; + set.generation++; + for (const rows of Object.values(set.dirty)) rows.grow(next); + } + + return set; +} diff --git a/src/data/iconSet.test.mjs b/src/data/iconSet.test.mjs new file mode 100644 index 0000000000..934b83e535 --- /dev/null +++ b/src/data/iconSet.test.mjs @@ -0,0 +1,227 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + createIconSet, + DirtyRows, + ICON_ROTATES, + ICON_SHOWN, +} from './iconSet.js'; +import { + writeArcSegment, + writeCourseGlide, + writeHoldSegment, +} from './iconSegment.js'; + +function place(set, id, lon, course = 0) { + const row = set.add(id, { id }); + writeHoldSegment( + set.segments, + row, + Cesium.Cartesian3.fromDegrees(lon, 10, 1000), + course, + ); + set.segmentWritten(row); + return row; +} + +function settle(set) { + for (const rows of Object.values(set.dirty)) rows.clear(); +} + +test('rows are added once per id and carry their meta', () => { + const set = createIconSet({ capacity: 4 }); + assert.equal(set.add('a', 1), 0); + assert.equal(set.add('b', 2), 1); + assert.equal(set.add('a', 3), 0, 'same id, same row'); + assert.equal(set.metaAt(0), 3); + assert.equal(set.count, 2); + assert.equal(set.row('missing'), -1); +}); + +test('a new row starts hidden, unscaled, opaque white and unfocused', () => { + const set = createIconSet(); + const row = set.add('a'); + assert.equal(set.shown(row), false); + assert.equal(set.scale(row), 1); + assert.equal(set.alpha(row), 1); + assert.equal(set.focus(row), 1); + assert.ok(Cesium.Color.equals(set.color(row), Cesium.Color.WHITE)); +}); + +test('removing a row moves the last row into its place with all its columns', () => { + const set = createIconSet({ capacity: 4 }); + place(set, 'a', 1); + place(set, 'b', 2); + const c = place(set, 'c', 3, 120); + set.setShown(c, true); + set.setFlag(c, ICON_ROTATES, true); + set.setSize(c, 20, 24); + set.setScale(c, 1.3); + set.setColor(c, Cesium.Color.fromCssColorString('#FFB800')); + set.setHandle(c, 'handle-c'); + settle(set); + + assert.ok(set.remove('a')); + assert.equal(set.count, 2); + assert.equal(set.row('c'), 0); + assert.equal(set.idAt(0), 'c'); + assert.deepEqual(set.metaAt(0), { id: 'c' }); + assert.equal(set.handleAt(0), 'handle-c'); + assert.equal(set.flags(0), ICON_SHOWN | ICON_ROTATES); + assert.equal(set.width(0), 20); + assert.equal(set.height(0), 24); + assert.ok(Math.abs(set.scale(0) - 1.3) < 1e-6); + assert.deepEqual([...set.colors.subarray(0, 4)], [255, 184, 0, 255]); + const at = set.position(0, 0); + assert.ok( + Cesium.Cartesian3.distance(at, Cesium.Cartesian3.fromDegrees(3, 10, 1000)) < + 0.01, + ); + assert.equal(set.course(0, 0), 120); + assert.equal( + set.dirty.segments.runs(set.count)[0][0], + 0, + 'the moved row uploads', + ); + assert.equal(set.remove('a'), false); +}); + +test('removing the last row moves nothing', () => { + const set = createIconSet(); + place(set, 'a', 1); + place(set, 'b', 2); + settle(set); + set.remove('b'); + assert.equal(set.count, 1); + assert.ok(set.dirty.segments.empty); +}); + +test('a released row hands its renderer handle back', () => { + const set = createIconSet(); + const released = []; + set.onRelease = (handle) => released.push(handle); + set.setHandle(set.add('a'), 'ha'); + set.setHandle(set.add('b'), 'hb'); + set.remove('a'); + set.clear(); + assert.deepEqual(released, ['ha', 'hb']); + assert.equal(set.count, 0); + assert.equal(set.has('b'), false); +}); + +test('unchanged writes leave the columns clean', () => { + const set = createIconSet(); + const row = set.add('a'); + set.setSize(row, 20, 20); + set.setScale(row, 0.8); + set.setShown(row, true); + set.setColor(row, Cesium.Color.CYAN); + set.setScaleByDistance(row, new Cesium.NearFarScalar(1000, 3, 8e6, 0.5)); + settle(set); + set.setSize(row, 20, 20); + set.setScale(row, 0.8); + set.setShown(row, true); + set.setColor(row, Cesium.Color.CYAN); + set.setScaleByDistance(row, new Cesium.NearFarScalar(1000, 3, 8e6, 0.5)); + assert.ok(set.dirty.style.empty); + assert.ok(set.dirty.colors.empty); + set.setScale(row, 0.9); + assert.deepEqual(set.dirty.style.runs(set.count), [[0, 0]]); +}); + +test('the set grows past its capacity and keeps every row', () => { + const set = createIconSet({ capacity: 2 }); + for (let i = 0; i < 5; i++) place(set, `r${i}`, i, i * 10); + assert.equal(set.count, 5); + assert.ok(set.capacity >= 5); + assert.equal(set.generation, 2); + for (let i = 0; i < 5; i++) + assert.equal(set.course(set.row(`r${i}`), 0), i * 10); +}); + +test('times are seconds since the epoch', () => { + const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z'); + const set = createIconSet({ epoch }); + assert.equal( + set.seconds( + Cesium.JulianDate.addSeconds(epoch, 42.5, new Cesium.JulianDate()), + ), + 42.5, + ); +}); + +test('dirty rows go out as coalesced runs, or whole when most rows changed', () => { + const rows = new DirtyRows(1000); + for (const row of [900, 3, 5, 40, 901, 3]) rows.mark(row); + assert.deepEqual(rows.runs(1000), [ + [3, 5], + [40, 40], + [900, 901], + ]); + assert.deepEqual(rows.runs(1000, 64), [ + [3, 40], + [900, 901], + ]); + assert.deepEqual( + rows.runs(500), + [ + [3, 5], + [40, 40], + ], + 'rows past the count are dropped', + ); + rows.clear(); + assert.ok(rows.empty); + for (let row = 0; row < 300; row++) rows.mark(row * 3); + assert.deepEqual(rows.runs(1000), [[0, 999]]); +}); + +test('a new row has no image until one is set', () => { + const set = createIconSet(); + const row = set.add('a'); + assert.equal(set.imageFar(row), -1); + assert.equal(set.imageNear(row), -1); + set.setImage(row, 3, 4); + assert.equal(set.imageNear(row), 4); +}); + +test('a set of capacity zero still grows', () => { + const set = createIconSet({ capacity: 0 }); + set.add('a'); + set.add('b'); + assert.equal(set.count, 2); +}); + +test('rebasing moves the epoch without moving any row', () => { + const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z'); + const set = createIconSet({ epoch }); + const fix = Cesium.Cartesian3.fromDegrees(-97, 33, 10_000); + const row = set.add('a'); + writeArcSegment(set.segments, row, { + fix, + t0: 5000, + minDt: 0, + maxDt: 300, + speedMps: 240, + trackDeg: 80, + turnRateDps: 2, + }); + writeCourseGlide(set.segments, row, 30, 5000, 20); + set.segmentWritten(row, 5100); + const tau = 5060; + const before = set.position(row, tau); + const courseBefore = set.course(row, tau); + settle(set); + + const later = (s) => + Cesium.JulianDate.addSeconds(epoch, s, new Cesium.JulianDate()); + assert.equal(set.rebase(later(1000)), false, 'under half an hour: stays'); + assert.equal(set.rebase(later(4000)), true); + assert.equal(set.seconds(later(4000)), 0); + const after = set.position(row, tau - 4000); + assert.ok(Cesium.Cartesian3.distance(before, after) < 0.01); + assert.ok(Math.abs(set.course(row, tau - 4000) - courseBefore) < 1e-3); + assert.equal(set.expires(row), 1100); + assert.deepEqual(set.dirty.segments.runs(set.count), [[0, 0]]); +}); diff --git a/src/data/iconSetPrimitive.js b/src/data/iconSetPrimitive.js new file mode 100644 index 0000000000..f832cfdf7c --- /dev/null +++ b/src/data/iconSetPrimitive.js @@ -0,0 +1,584 @@ +/** + * @module iconSetPrimitive + * @description Draws an {@link module:iconSet} in a Cesium scene: one instanced quad per + * row, moved along its segment on the GPU at the set's render time. This replaces a + * BillboardCollection for large moving fleets, so the CPU writes rows only when their + * motion or style changes and uploads just the rows it wrote. + * + * It reproduces the billboard behaviour the aircraft layers used: pixel size by + * `width × scale × NearFarScalar(distance)`, screen rotation along the course + * (`alignedAxis` zero), depth test disabled at any distance (drawn on the near plane), + * opaque and translucent passes, horizon culling, and per-row picks whose object is + * `{ id, meta, primitive }` (`primitive.show` hides that one row, as drillPick expects). + * Rows flagged to recede also take the aircraft limb recession, composed with focus. + * + * This module is the one place the icon sets touch Cesium's renderer internals. + */ +import * as Cesium from 'cesium'; +import { ICON_SEGMENT_GLSL, SEGMENT_STRIDE } from './iconSegment.js'; +import { ICON_CULL_LIFT, STYLE_STRIDE } from './iconSet.js'; +import { iconAtlas, MAX_ICON_SLOTS } from './iconAtlas.js'; +import { + cameraLimbDistanceM, + getAircraftRecessionParams, +} from './aircraftRecession.js'; + +/** On-screen device pixels above which a row draws its near (large) image. */ +const NEAR_IMAGE_PX = 76; +/** Rows lifted this far before the horizon test when flagged (low fixes). */ +const CULL_LIFT_M = 12; + +const ATTRIBUTE_LOCATIONS = Object.freeze({ + corner: 0, + seg0: 1, + seg1: 2, + seg2: 3, + seg3: 4, + seg4: 5, + seg5: 6, + style0: 7, + style1: 8, + style2: 9, + color: 10, + pickColor: 11, +}); + +const VERTEX_SHADER = /* glsl */ ` +in vec2 corner; +in vec4 seg0; +in vec4 seg1; +in vec4 seg2; +in vec4 seg3; +in vec4 seg4; +in vec4 seg5; +in vec4 style0; // width, height, scale, alpha +in vec4 style1; // far image, near image, flags, focus +in vec4 style2; // scale by distance (near, near value, far, far value) +in vec4 color; +in vec4 pickColor; + +uniform float u_tau; +uniform vec3 u_cameraPosition; +uniform vec4 u_horizon; // camera in ellipsoid-scaled space, squared scaled limb distance +uniform vec3 u_cameraRight; +uniform vec3 u_cameraUp; +uniform vec4 u_recession; // limb distance, start ratio, strength, enabled +uniform vec3 u_recessionFloors; // scale, alpha, combined alpha +uniform vec4 u_slots[${MAX_ICON_SLOTS}]; + +out vec2 v_uv; +out vec4 v_color; +out vec4 v_pickColor; + +// The row's anchor in clip space before screen offsets, for effects that wrap +// main() (cyber sonar) and must not change geometry or picks. +vec4 iconAnchorClip = vec4(0.0, 0.0, 0.0, -1.0); + +${ICON_SEGMENT_GLSL} + +bool iconFlag(float flags, float bit) { + return mod(floor(flags / bit), 2.0) == 1.0; +} + +bool occludedByEllipsoid(vec3 world) { + vec3 cv = u_horizon.xyz; + float vh2 = u_horizon.w; + vec3 vt = world * czm_ellipsoidInverseRadii - cv; + float vtDotVc = -dot(vt, cv); + return vh2 < 0.0 + ? vtDotVc > 0.0 + : vtDotVc > vh2 && vtDotVc * vtDotVc / dot(vt, vt) > vh2; +} + +void main() { + v_pickColor = pickColor; + v_uv = vec2(0.0); + v_color = vec4(0.0); + gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn + + float flags = style1.z; + if (!iconFlag(flags, 1.0)) return; + + vec3 rte = iconSegmentPosition(seg0, seg1, seg2, seg3, seg4, u_tau); + vec3 world = u_cameraPosition + rte; + vec3 cullPoint = iconFlag(flags, ${ICON_CULL_LIFT.toFixed(1)}) ? world + normalize(world) * ${CULL_LIFT_M.toFixed(1)} : world; + if (occludedByEllipsoid(cullPoint)) return; + + vec4 positionEC = czm_modelViewRelativeToEye * vec4(rte, 1.0); + if (positionEC.z >= 0.0) return; // behind the camera + iconAnchorClip = czm_projection * positionEC; + + float distanceSq = dot(positionEC.xyz, positionEC.xyz); + float distanceScale = style2.z > 0.0 ? czm_nearFarScalar(style2, distanceSq) : 1.0; + float scale = style0.z; + float alpha = style0.w; + float focus = clamp(style1.w, 0.0, 1.0); + if (iconFlag(flags, 4.0) && u_recession.w > 0.0) { + float ratio = sqrt(distanceSq) / u_recession.x; + float t = clamp((ratio - u_recession.y) / (1.0 - u_recession.y), 0.0, 1.0); + float ease = t * t * (3.0 - 2.0 * t) * u_recession.z; + scale *= 1.0 + (u_recessionFloors.x - 1.0) * ease; + alpha *= max(u_recessionFloors.z, focus * (1.0 + (u_recessionFloors.y - 1.0) * ease)); + } else if (iconFlag(flags, 4.0)) { + alpha *= max(u_recessionFloors.z, focus); // recession off: the floor still holds + } else { + alpha *= focus; + } + + float glyphPx = style0.x * scale * distanceScale * czm_pixelRatio; + float slot = glyphPx > ${NEAR_IMAGE_PX.toFixed(1)} ? style1.y : style1.x; + if (slot < 0.0) return; // no image set + vec4 rect = u_slots[int(slot)]; + if (rect.z <= 0.0) return; // image not loaded yet + + vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner; + if (iconFlag(flags, 2.0)) { + float course = radians(iconSegmentCourse(seg3, seg4, seg5, u_tau)); + vec3 up = czm_geodeticSurfaceNormal(world, vec3(0.0), czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii); + // East as Cesium's ENU frame builds it; at the poles it uses +y. + vec2 horizontal = vec2(-world.y, world.x); + vec3 east = dot(horizontal, horizontal) > 1.0 ? normalize(vec3(horizontal, 0.0)) : vec3(0.0, 1.0, 0.0); + vec3 north = cross(up, east); + vec3 forward = east * sin(course) + north * cos(course); + float dx = dot(forward, u_cameraRight); + float dy = -dot(forward, u_cameraUp); + // Heading into or out of the screen: no stable direction, stay upright + // (screenProjectedRotation's 0.5 m of a 2 km probe). + if (dx * dx + dy * dy >= 6.25e-8) { + float rotation = atan(-dx, -dy); + float c = cos(rotation); + float s = sin(rotation); + halfSize = mat2(c, s, -s, c) * halfSize; + } + } + positionEC.xy += halfSize * czm_metersPerPixel(positionEC); + gl_Position = czm_projection * positionEC; + +#ifdef LOG_DEPTH + czm_vertexLogDepth(); +#endif + // Depth test disabled at any distance: draw on the near plane, as a billboard + // with disableDepthTestDistance = Infinity. + float zclip = gl_Position.z / gl_Position.w; + if (zclip >= -1.0 && zclip <= 1.0) { + gl_Position.z = -gl_Position.w; +#ifdef LOG_DEPTH + v_depthFromNearPlusOne = 1.0; +#endif + } + + v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5)); + v_color = vec4(color.rgb, color.a * alpha); +} +`; + +const FRAGMENT_SHADER = /* glsl */ ` +uniform sampler2D u_atlas; + +in vec2 v_uv; +in vec4 v_color; +in vec4 v_pickColor; + +void main() { + vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv)); + color *= czm_gammaCorrect(v_color); + if (color.a < 0.005) discard; +#ifdef OPAQUE + if (color.a < 0.995) discard; +#else + if (color.a >= 0.995) discard; +#endif + out_FragColor = color; +#ifdef LOG_DEPTH + czm_writeLogDepth(v_depthFromNearPlusOne); +#endif +} +`; + +const SEGMENT_BYTES = SEGMENT_STRIDE * 4; +const STYLE_BYTES = STYLE_STRIDE * 4; +const EARTH_BOUNDS = new Cesium.BoundingSphere( + Cesium.Cartesian3.ZERO, + 6_500_000, +); + +/** + * @param {{ set: object, renderTime: () => Cesium.JulianDate }} options `renderTime` + * gives the instant to draw at (the layer's delayed clock). + */ +export class IconSetPrimitive { + constructor({ set, renderTime }) { + this.set = set; + this.renderTime = renderTime; + this.show = true; + this._tau = 0; + this._generation = -1; + this._buffers = null; + this._vertexArray = null; + this._pickColors = null; + this._programs = null; + this._commands = null; + this._texture = null; + this._atlasVersion = -1; + this._slots = Array.from( + { length: MAX_ICON_SLOTS }, + () => new Cesium.Cartesian4(), + ); + this._horizon = new Cesium.Cartesian4(); + this._cameraPosition = new Cesium.Cartesian3(); + this._cameraRight = new Cesium.Cartesian3(); + this._cameraUp = new Cesium.Cartesian3(); + this._recession = new Cesium.Cartesian4(); + this._recessionFloors = new Cesium.Cartesian3(); + this._destroyed = false; + set.onRelease = (handle) => handle.pickId.destroy(); + const primitive = this; + this._uniforms = { + u_tau: () => primitive._tau, + u_cameraPosition: () => primitive._cameraPosition, + u_horizon: () => primitive._horizon, + u_cameraRight: () => primitive._cameraRight, + u_cameraUp: () => primitive._cameraUp, + u_recession: () => primitive._recession, + u_recessionFloors: () => primitive._recessionFloors, + u_slots: () => primitive._slots, + u_atlas: () => primitive._texture, + }; + } + + update(frameState) { + const set = this.set; + if ( + !this.show || + !set.show || + (!frameState.passes.render && !frameState.passes.pick) + ) + return; + const context = frameState.context; + this._syncAtlas(context); + if (!this._texture) return; + const renderTime = this.renderTime(); + set.rebase(renderTime); + if (this._generation !== set.generation) this._allocate(context); + this._upload(context); + if (set.count === 0) return; + + this._tau = set.seconds(renderTime); + this._syncCamera(frameState); + if (!this._programs) this._createCommands(context); + for (const command of this._commands) { + command.instanceCount = set.count; + frameState.commandList.push(command); + } + } + + _syncAtlas(context) { + if (iconAtlas.version === this._atlasVersion || !iconAtlas.canvas) return; + this._atlasVersion = iconAtlas.version; + this._texture?.destroy(); + this._texture = new Cesium.Texture({ + context, + source: iconAtlas.canvas, + flipY: false, + sampler: new Cesium.Sampler({ + wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE, + wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE, + minificationFilter: Cesium.TextureMinificationFilter.LINEAR, + magnificationFilter: Cesium.TextureMagnificationFilter.LINEAR, + }), + }); + for (let slot = 0; slot < MAX_ICON_SLOTS; slot++) + Cesium.Cartesian4.unpack(iconAtlas.rects, slot * 4, this._slots[slot]); + } + + _allocate(context) { + const set = this.set; + this._destroyBuffers(); + const capacity = set.capacity; + const usage = Cesium.BufferUsage.DYNAMIC_DRAW; + const buffers = { + corner: Cesium.Buffer.createVertexBuffer({ + context, + typedArray: new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), + usage: Cesium.BufferUsage.STATIC_DRAW, + }), + index: Cesium.Buffer.createIndexBuffer({ + context, + typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]), + usage: Cesium.BufferUsage.STATIC_DRAW, + indexDatatype: Cesium.IndexDatatype.UNSIGNED_SHORT, + }), + segments: Cesium.Buffer.createVertexBuffer({ + context, + sizeInBytes: capacity * SEGMENT_BYTES, + usage, + }), + style: Cesium.Buffer.createVertexBuffer({ + context, + sizeInBytes: capacity * STYLE_BYTES, + usage, + }), + colors: Cesium.Buffer.createVertexBuffer({ + context, + sizeInBytes: capacity * 4, + usage, + }), + picks: Cesium.Buffer.createVertexBuffer({ + context, + sizeInBytes: capacity * 4, + usage, + }), + }; + const float = Cesium.ComponentDatatype.FLOAT; + const byte = Cesium.ComponentDatatype.UNSIGNED_BYTE; + const attributes = [ + { + index: ATTRIBUTE_LOCATIONS.corner, + vertexBuffer: buffers.corner, + componentsPerAttribute: 2, + componentDatatype: float, + }, + ]; + for (let i = 0; i < 6; i++) + attributes.push({ + index: ATTRIBUTE_LOCATIONS[`seg${i}`], + vertexBuffer: buffers.segments, + componentsPerAttribute: 4, + componentDatatype: float, + offsetInBytes: i * 16, + strideInBytes: SEGMENT_BYTES, + instanceDivisor: 1, + }); + for (let i = 0; i < 3; i++) + attributes.push({ + index: ATTRIBUTE_LOCATIONS[`style${i}`], + vertexBuffer: buffers.style, + componentsPerAttribute: 4, + componentDatatype: float, + offsetInBytes: i * 16, + strideInBytes: STYLE_BYTES, + instanceDivisor: 1, + }); + for (const [name, buffer] of [ + ['color', buffers.colors], + ['pickColor', buffers.picks], + ]) + attributes.push({ + index: ATTRIBUTE_LOCATIONS[name], + vertexBuffer: buffer, + componentsPerAttribute: 4, + componentDatatype: byte, + normalize: true, + instanceDivisor: 1, + }); + this._buffers = buffers; + this._vertexArray = new Cesium.VertexArray({ + context, + attributes, + indexBuffer: buffers.index, + }); + this._pickColors = new Uint8Array(capacity * 4); + this._generation = set.generation; + for (const rows of Object.values(set.dirty)) rows.markAll(); + if (this._commands) + for (const command of this._commands) + command.vertexArray = this._vertexArray; + } + + _upload(context) { + const set = this.set; + const { segments, style, colors } = set.dirty; + const count = set.count; + for (const [from, to] of segments.runs(count)) + this._buffers.segments.copyFromArrayView( + set.segments.subarray(from * SEGMENT_STRIDE, (to + 1) * SEGMENT_STRIDE), + from * SEGMENT_BYTES, + ); + for (const [from, to] of style.runs(count)) { + this._buffers.style.copyFromArrayView( + set.style.subarray(from * STYLE_STRIDE, (to + 1) * STYLE_STRIDE), + from * STYLE_BYTES, + ); + // Rows that are new or moved by a removal: (re)write their pick colours. + for (let row = from; row <= to; row++) this._writePick(context, row); + this._buffers.picks.copyFromArrayView( + this._pickColors.subarray(from * 4, (to + 1) * 4), + from * 4, + ); + } + for (const [from, to] of colors.runs(count)) + this._buffers.colors.copyFromArrayView( + set.colors.subarray(from * 4, (to + 1) * 4), + from * 4, + ); + segments.clear(); + style.clear(); + colors.clear(); + } + + _writePick(context, row) { + const set = this.set; + let handle = set.handleAt(row); + if (!handle) { + const id = set.idAt(row); + const facade = { + id, + get show() { + const at = set.row(id); + return at >= 0 && set.shown(at); + }, + set show(value) { + const at = set.row(id); + if (at >= 0) set.setShown(at, value); + }, + }; + handle = { + pickId: context.createPickId({ + id, + get meta() { + const at = set.row(id); + return at >= 0 ? set.metaAt(at) : undefined; + }, + primitive: facade, + }), + }; + set.setHandle(row, handle); + } + const color = handle.pickId.color; + const o = row * 4; + this._pickColors[o] = Cesium.Color.floatToByte(color.red); + this._pickColors[o + 1] = Cesium.Color.floatToByte(color.green); + this._pickColors[o + 2] = Cesium.Color.floatToByte(color.blue); + this._pickColors[o + 3] = Cesium.Color.floatToByte(color.alpha); + } + + _syncCamera(frameState) { + const camera = frameState.camera; + const radii = Cesium.Ellipsoid.WGS84.oneOverRadii; + const position = camera.positionWC; + Cesium.Cartesian3.clone(position, this._cameraPosition); + Cesium.Cartesian3.clone(camera.rightWC, this._cameraRight); + Cesium.Cartesian3.clone(camera.upWC, this._cameraUp); + const cx = position.x * radii.x; + const cy = position.y * radii.y; + const cz = position.z * radii.z; + Cesium.Cartesian4.fromElements( + cx, + cy, + cz, + cx * cx + cy * cy + cz * cz - 1, + this._horizon, + ); + + const tuning = getAircraftRecessionParams(); + const height = camera.positionCartographic?.height; + const limb = cameraLimbDistanceM(height, tuning.earthRadiusM); + const active = + Number.isFinite(height) && + height > 0 && + height < tuning.globeViewBlendEndM && + limb > 0; + let strength = 0; + if (active) { + const g = Math.min( + 1, + Math.max( + 0, + (height - tuning.globeViewBlendStartM) / + (tuning.globeViewBlendEndM - tuning.globeViewBlendStartM), + ), + ); + strength = 1 - g * g * (3 - 2 * g); + } + Cesium.Cartesian4.fromElements( + active ? limb : 1, + tuning.startLimbRatio, + strength, + active ? 1 : 0, + this._recession, + ); + Cesium.Cartesian3.fromElements( + tuning.scaleFloor, + tuning.alphaFloor, + tuning.combinedAlphaFloor, + this._recessionFloors, + ); + } + + _createCommands(context) { + const programFor = (pass) => + Cesium.ShaderProgram.fromCache({ + context, + vertexShaderSource: new Cesium.ShaderSource({ + sources: [VERTEX_SHADER], + }), + fragmentShaderSource: new Cesium.ShaderSource({ + defines: pass === 'opaque' ? ['OPAQUE'] : ['TRANSLUCENT'], + sources: [FRAGMENT_SHADER], + }), + attributeLocations: ATTRIBUTE_LOCATIONS, + }); + this._programs = { + opaque: programFor('opaque'), + translucent: programFor('translucent'), + }; + const depthTest = { enabled: true, func: Cesium.DepthFunction.LESS }; + const command = (pass, program, renderState) => + new Cesium.DrawCommand({ + owner: this, + pass, + primitiveType: Cesium.PrimitiveType.TRIANGLES, + vertexArray: this._vertexArray, + count: 6, + instanceCount: 0, + shaderProgram: program, + uniformMap: this._uniforms, + renderState, + boundingVolume: EARTH_BOUNDS, + pickId: 'v_pickColor', + }); + this._commands = [ + command( + Cesium.Pass.OPAQUE, + this._programs.opaque, + Cesium.RenderState.fromCache({ depthTest, depthMask: true }), + ), + command( + Cesium.Pass.TRANSLUCENT, + this._programs.translucent, + Cesium.RenderState.fromCache({ + depthTest, + depthMask: false, + blending: Cesium.BlendingState.ALPHA_BLEND, + }), + ), + ]; + } + + _destroyBuffers() { + this._vertexArray?.destroy(); // destroys its buffers too + this._vertexArray = null; + this._buffers = null; + } + + isDestroyed() { + return this._destroyed; + } + + destroy() { + this._destroyBuffers(); + this._programs?.opaque.destroy(); + this._programs?.translucent.destroy(); + this._texture?.destroy(); + // The set outlives its renderer: release only the pick ids this one made. + const set = this.set; + for (let row = 0; row < set.count; row++) { + set.handleAt(row)?.pickId.destroy(); + set.setHandle(row, undefined); + } + set.onRelease = null; + for (const rows of Object.values(set.dirty)) rows.markAll(); + this._destroyed = true; + return Cesium.destroyObject(this); + } +} From fa3a3a3bca1b0884767dd163379e8835cd4b9fd8 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 19:40:39 -0800 Subject: [PATCH 012/470] Draw civil flights from an icon set moved on the GPU Every flight is now a row in the layer's icon set. Its motion segment follows the same regime `_deadReckon` picks (interpolate between fixes, warm up backward from the oldest, coast forward from the newest), and one shared `_motionRegime` makes that choice for both. The shader moves every untracked contact between polls, so the 12 Hz fleet tick no longer touches each billboard. It now only re-plans expired rows, floors grounded contacts, advances focus while needed, and runs the 3D model regime. Grounded contacts the floor lifts are pinned to a hold at the floored position. Their nose glides on the GPU. Contacts within 50 km re-floor every tick, and farther ones take turns about once a second. Low contacts are judged for the horizon at no lower than 12 m above the ellipsoid, as before. Below hover speed a contact's nose holds. A row whose fleet model is drawn keeps its focus updated, because the model reads it. Untracking re-plans and re-floors the icon from the tracked course. On the same views with about 6,700 OpenSky flights, frame gaps at p95 drop from 28-40 ms to 17 ms, and the fleet tick from 16-37 ms to about 2 ms at most. --- scripts/package-boundaries.json | 12 + src/data/aircraftIcons.js | 2 + src/data/aircraftRecession.js | 34 ++ src/data/cockpitModels.test.mjs | 12 +- src/data/flights.js | 4 + src/data/flights.test.mjs | 129 ++++-- src/data/iconSegment.js | 20 +- src/data/iconSegment.test.mjs | 32 ++ src/data/iconSet.js | 26 +- src/data/iconSet.test.mjs | 24 ++ src/data/iconSetPrimitive.js | 13 +- src/data/militaryAwareness.test.mjs | 2 +- src/data/nearbyModelHandoff.test.mjs | 14 +- src/data/routeSegment.test.mjs | 26 +- src/data/tr3bRegistry.test.mjs | 6 +- src/data/trackedModelRegime.test.mjs | 23 +- src/layers/flights/enrichment.js | 22 +- src/layers/flights/evidence.js | 105 ++--- src/layers/flights/icons.js | 471 +++++++++++++++++++++ src/layers/flights/icons.test.mjs | 120 ++++++ src/layers/flights/index.js | 3 + src/layers/flights/lifecycle.js | 56 ++- src/layers/flights/motion.js | 242 ++++++----- src/layers/flights/ownership.test.mjs | 3 +- src/layers/flights/policy.js | 8 + src/layers/flights/queries.js | 159 ++++---- src/layers/flights/queries.test.mjs | 51 ++- src/layers/flights/rendering.js | 539 +++++++------------------ src/layers/flights/snapshotRenderer.js | 127 ++---- src/layers/flights/state.js | 42 +- src/layers/flights/testing.js | 79 +++- src/layers/flights/tracking.js | 176 ++++---- src/ui/cyberTheme.test.mjs | 2 +- 33 files changed, 1598 insertions(+), 986 deletions(-) create mode 100644 src/layers/flights/icons.js create mode 100644 src/layers/flights/icons.test.mjs diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index f3467710f3..731b9da199 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1315,6 +1315,12 @@ "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", + "src/layers/flights/icons.js", + "src/data/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", "src/data/modelMirror.js", "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", @@ -2249,6 +2255,7 @@ "./standalone/catalog" ], "modules": [ + "src/layers/flights/icons.js", "src/sources/adsbFields.js", "src/data/headingDegrees.js", "src/data/distanceFormat.js", @@ -3248,6 +3255,11 @@ "application-layer-construction": { "exports": ["./application/layers"], "modules": [ + "src/layers/flights/icons.js", + "src/data/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", "src/sources/adsbFields.js", "src/data/headingDegrees.js", "src/data/distanceFormat.js", diff --git a/src/data/aircraftIcons.js b/src/data/aircraftIcons.js index bca4ca6553..cbcff065b2 100644 --- a/src/data/aircraftIcons.js +++ b/src/data/aircraftIcons.js @@ -252,6 +252,8 @@ const _b64 = (s) => * NEAR the display size lets the browser's SVG AA do the work: crisp AND * smooth. 64 covers the 40–58 px fleet band with ≤1.6× minification. */ const FLEET_RASTER_PX = 64; +/** Raster size of the default fleet glyph. */ +export const FLEET_ICON_PX = FLEET_RASTER_PX; /** Tracked raster: the tracked billboard is the one SUSTAINED large 2D glyph * (close-zoom fleet flybys hand off to 3D models). Keep the 192 px texture so * it stays crisp at its biggest on-screen sizes. */ diff --git a/src/data/aircraftRecession.js b/src/data/aircraftRecession.js index 984038d16f..77c7b160e7 100644 --- a/src/data/aircraftRecession.js +++ b/src/data/aircraftRecession.js @@ -243,6 +243,40 @@ export function applyAircraftBillboardTreatment({ return _treatmentResult; } +/** + * The alpha an aircraft draws with: base × max(combined floor, focus × limb + * haze). Icon sets compose the same thing in their shader; models need it here. + * @param {object} input + * @param {number} input.baseAlpha + * @param {number} input.focusFactor + * @param {number} input.cameraDistanceM + * @param {number} input.cameraHeightM + * @param {Partial} [input.params] + * @returns {number} + */ +export function aircraftTreatmentAlpha({ + baseAlpha, + focusFactor, + cameraDistanceM, + cameraHeightM, + params, +}) { + const tuning = resolvedParams(params); + const factors = aircraftRecessionFactorsResolved( + cameraDistanceM, + cameraHeightM, + tuning, + _scratchFactors, + ); + return ( + baseAlpha * + Math.max( + tuning.combinedAlphaFloor, + clamp(focusFactor, 0, 1) * factors.alpha, + ) + ); +} + /** * Apply layer-owned hue and composed aircraft alpha to an ambient glTF model without * disturbing Cesium's existing MIX/colorBlendAmount presentation semantics. diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 2f4930985d..2c8bc5f28b 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -83,24 +83,24 @@ for (const layer of LAYERS) { test(`${layer.name}: near AIR state is independent from model admission`, () => { assert.match(source, /nextCockpitNearContacts\(/, 'Cockpit derives a separate near-contact hysteresis set'); - assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)/, + assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)|!flightState\._cockpitNearContacts\.has\(icao24\);\s*if \(cockpitDot\) \{\s*const dot = iconAtlas\.slot\(cockpitContactDotImage\(\)/, 'only out-of-range Cockpit contacts become dots'); // `_iconKind` is identity for every unconverted contact (see // tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the // operator explicitly converted into a TR-3B. - assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*aircraftVisuals\.read\(bb\)\?\.iconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/, + assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*aircraftVisuals\.read\(bb\)\?\.iconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)|aircraftIcon\(\s*parts\.rendering\._iconKind\(icao24, info\?\.klass\),?\s*\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); - assert.match(source, /setBillboard\(\s*bb,\s*'rotation',\s*0\s*\);/, + assert.match(source, /setBillboard\(\s*bb,\s*'rotation',\s*0\s*\);|set\.setFlag\(row, ICON_ROTATES, false\);/, 'far dots are reset to a rotation-free presentation'); - assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)/, + assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)|set\.setFlag\(row, ICON_ROTATES, true\);/, 'near 2D silhouettes continue to receive projected course'); - assert.match(source, /if\s*\(\s*billboardState\(bb\)\.show,?\s*\)\s*setBillboard\(\s*bb,\s*'show',\s*false\s*\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, + assert.match(source, /if\s*\(\s*billboardState\(bb\)\.show,?\s*\)\s*setBillboard\(\s*bb,\s*'show',\s*false\s*\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders|icons\.setShown\(row, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, 'the gap-proof billboard-to-model handoff remains intact'); }); test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => { const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); - assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);/); + assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);|for \(let row = 0; row < \(icons\?\.count \?\? 0\); row\+\+\)\s*parts\.icons\._applyIconPresentation\(icons\.idAt\(row\)\);/); }); } diff --git a/src/data/flights.js b/src/data/flights.js index 6e2d35dbc5..8c56fb38e7 100644 --- a/src/data/flights.js +++ b/src/data/flights.js @@ -40,5 +40,9 @@ export const _driveFleetModelHandoffForTest = flightsLayer.testing._driveFleetModelHandoffForTest; export const _ensureFleetModelForTest = flightsLayer.testing._ensureFleetModelForTest; +export const _iconForTest = flightsLayer.testing._iconForTest; +export const _setIconForTest = flightsLayer.testing._setIconForTest; +export const _floorGroundedIconsForTest = + flightsLayer.testing._floorGroundedIconsForTest; export const mapAnalystRecord = flightsLayer.mapAnalystRecord; export default flightsLayer; diff --git a/src/data/flights.test.mjs b/src/data/flights.test.mjs index d6a06e5b9a..487a9d5385 100644 --- a/src/data/flights.test.mjs +++ b/src/data/flights.test.mjs @@ -14,6 +14,8 @@ import flightsLayer, { _setTrackedFlightRefreshStateForTest, _floorGroundedDisplayPositionForTest, _clearDisplayFloorStateForTest, + _iconForTest, + _floorGroundedIconsForTest, mapAnalystRecord, } from './flights.js'; import { setMilitaryLayerActive } from './militaryRegistry.js'; @@ -225,18 +227,9 @@ test('nonempty OpenSky payload with zero usable rows cannot prove share target a test('a newly seen aircraft appears at its delayed position, not ahead of it', async () => { // The fleet renders RENDER_DELAY_SEC behind real time, so a fresh contact's // first displayed position is its fix projected back to that delayed time. - // Creating the billboard at the raw fix drew it ahead until the next fleet + // Creating the icon at the raw fix drew it ahead until the next fleet // tick, which then jumped it back about one delay of travel. - const added = []; - const billboardCollection = { - show: false, - add(options) { - const billboard = { ...options }; - added.push(billboard); - return billboard; - }, - remove() {}, - }; + const billboardCollection = { show: false }; const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedFlightRefreshStateForTest({ icao24: 'seed00', @@ -293,9 +286,9 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a }; try { await flightsLayer.update(viewer); - const billboard = added.find((entry) => entry.id === icao24); - assert.ok(billboard, 'the new contact gets a billboard'); - const shown = Cesium.Cartographic.fromCartesian(billboard.position); + const icon = _iconForTest(icao24); + assert.ok(icon, 'the new contact gets an icon'); + const shown = Cesium.Cartographic.fromCartesian(icon.position); const fix = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_700); const behindM = Cesium.Cartesian3.distance( Cesium.Cartesian3.fromRadians(shown.longitude, shown.latitude, 10_700), @@ -1066,21 +1059,12 @@ const _floorCarto = (pos) => test('a newly seen taxiing aircraft starts on the floor under its delayed position', async () => { // A grounded contact is drawn at its delayed position lifted onto the floor - // under it. Creating the billboard without that lift started it on the + // under it. Creating the icon without that lift started it on the // floor of its reported fix, then the next fleet tick raised it. _clearDisplayFloorStateForTest(); _clearMeshFloorCellsForTest(); setMeshFloorPreferred(true); - const added = []; - const billboardCollection = { - show: false, - add(options) { - const billboard = { ...options }; - added.push(billboard); - return billboard; - }, - remove() {}, - }; + const billboardCollection = { show: false }; const viewer = { camera: { positionCartographic: null }, scene: {} }; _setTrackedFlightRefreshStateForTest({ icao24: 'seed00', @@ -1142,9 +1126,9 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi }; try { await flightsLayer.update(viewer); - const billboard = added.find((entry) => entry.id === icao24); - assert.ok(billboard, 'the new contact gets a billboard'); - const shown = _floorCarto(billboard.position); + const icon = _iconForTest(icao24); + assert.ok(icon, 'the new contact gets an icon'); + const shown = _floorCarto(icon.position); assert.ok( Cesium.Math.toDegrees(shown.longitude) < fixLon, 'drawn behind the fix', @@ -1160,6 +1144,95 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi } }); +test('far grounded contacts take turns on the floor; near ones refloor every tick', async () => { + // The floor pass is the fleet tick's only per-contact CPU work. Past + // FLOOR_NEAR_M a contact is refloored once per FLOOR_FAR_EVERY_TICKS. + _clearDisplayFloorStateForTest(); + _clearMeshFloorCellsForTest(); + setMeshFloorPreferred(true); + const viewer = { camera: { positionCartographic: null }, scene: {} }; + _setTrackedFlightRefreshStateForTest({ + icao24: 'seed00', + entity: null, + billboard: { + show: false, + position: Cesium.Cartesian3.fromDegrees(0, 0, 0), + }, + billboardCollection: { show: false }, + viewer, + meta: { rawLat: 0, rawLon: 0, onGround: false }, + tracked: false, + }); + const icao24 = 'taxi02'; + const fixLon = -97.66; + const fixLat = 30.2; + for (let k = -40; k <= 40; k += 1) { + reportMeshFloorCell(fixLat, fixLon + k * 0.0001, 131.5); + } + const nowSec = Math.floor(Date.now() / 1000); + const realFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + if (!String(url).startsWith('/api/flights')) { + return { ok: true, status: 200, json: async () => ({ ac: [] }) }; + } + return { + ok: true, + status: 200, + headers: { get: () => null }, + json: async () => ({ + time: nowSec, + states: [ + [ + icao24, + 'TAXI02 ', + 'United States', + nowSec - 2, + nowSec - 2, + fixLon, + fixLat, + null, + true, + 10, + 90, + 0, + null, + null, + null, + null, + null, + 5, + ], + ], + }), + }; + }; + try { + await flightsLayer.update(viewer); + const start = Cesium.JulianDate.now(); + const at = (s) => + Cesium.JulianDate.addSeconds(start, s, new Cesium.JulianDate()); + const far = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 3_000_000); + const near = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_000); + let last = _iconForTest(icao24).position; + const moves = (camera, from, to) => { + let count = 0; + for (let tick = from; tick <= to; tick += 1) { + _floorGroundedIconsForTest(at(tick), camera); + const now = _iconForTest(icao24).position; + if (Cesium.Cartesian3.distance(now, last) > 1) count += 1; + last = now; + } + return count; + }; + assert.equal(moves(far, 1, 24), 2, 'far: once per 12 ticks'); + assert.equal(moves(near, 25, 30), 6, 'near: every tick'); + } finally { + globalThis.fetch = realFetch; + _clearMeshFloorCellsForTest(); + _clearDisplayFloorStateForTest(); + } +}); + test('display floor: a grounded contact that drifted onto a higher cell is lifted', () => { _clearDisplayFloorStateForTest(); _clearMeshFloorCellsForTest(); diff --git a/src/data/iconSegment.js b/src/data/iconSegment.js index c23addfb48..421311059b 100644 --- a/src/data/iconSegment.js +++ b/src/data/iconSegment.js @@ -45,7 +45,7 @@ const COURSE0 = 19; // deg const COURSE_SLOPE = 20; // lerp: deg per unit fraction const SLEW_OFFSET = 21; // deg still to glide at SLEW_T0 const SLEW_T0 = 22; // s -const SLEW_RATE = 23; // deg/s +const SLEW_RATE = 23; // deg/s; negative holds the course at the glide's start const DEG = Math.PI / 180; const STRAIGHT_BELOW_RAD_PER_SEC = 1e-4; @@ -140,6 +140,8 @@ export function writeArcSegment(out, row, segment) { /** * Glide the displayed course from `fromCourseDeg` onto the segment's own course, * at most `rateDps`, starting at `t0` (the rate limit at a segment boundary). + * A rate of zero or less holds `fromCourseDeg` for the whole segment instead + * (a hover: the nose keeps its heading however the track moves). * Call after writing the segment. * @param {Float32Array} out * @param {number} row @@ -153,7 +155,7 @@ export function writeCourseGlide(out, row, fromCourseDeg, t0, rateDps) { const target = targetCourse(out, o, t0); out[o + SLEW_OFFSET] = norm180(fromCourseDeg - target); out[o + SLEW_T0] = t0; - out[o + SLEW_RATE] = Math.max(0, rateDps); + out[o + SLEW_RATE] = rateDps > 0 ? rateDps : -1; } /** @@ -195,6 +197,8 @@ export function segmentCourse(seg, row, tau) { const o = row * SEGMENT_STRIDE; const course = targetCourse(seg, o, tau); const offset = seg[o + SLEW_OFFSET]; + if (seg[o + SLEW_RATE] < 0) + return norm360(targetCourse(seg, o, seg[o + SLEW_T0]) + offset); if (offset === 0) return norm360(course); // limitCourseStep: the displayed course turns at the rate toward the segment's // own (possibly turning) course until it reaches it, then follows it. The @@ -207,6 +211,17 @@ export function segmentCourse(seg, row, tau) { return norm360(turned < gap ? start + offset + toward * turned : course); } +/** + * The course the row glides toward at `tau` (its segment's own course). + * @param {Float32Array} seg + * @param {number} row + * @param {number} tau + * @returns {number} + */ +export function segmentTargetCourse(seg, row, tau) { + return norm360(targetCourse(seg, row * SEGMENT_STRIDE, tau)); +} + /** The segment's own course at `tau`, before any glide. */ function targetCourse(seg, o, tau) { const kind = seg[o + KIND]; @@ -310,6 +325,7 @@ float iconTargetCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) { float iconSegmentCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) { float course = iconTargetCourse(seg3, seg4, seg5, tau); float offset = seg5.y; + if (seg5.w < 0.0) return iconTargetCourse(seg3, seg4, seg5, seg5.z) + offset; if (offset == 0.0) return course; float toward = -sign(offset); float start = iconTargetCourse(seg3, seg4, seg5, seg5.z); diff --git a/src/data/iconSegment.test.mjs b/src/data/iconSegment.test.mjs index 6384d91aa0..0beec4b6e2 100644 --- a/src/data/iconSegment.test.mjs +++ b/src/data/iconSegment.test.mjs @@ -213,3 +213,35 @@ test('the course glide never outruns the rate while its target turns', () => { 'then it follows the turn', ); }); + +test('a zero-rate glide holds the course however the segment turns', () => { + const seg = new Float32Array(SEGMENT_STRIDE); + const to = Cesium.Cartesian3.fromDegrees(-97.04, 32.90001, 10_500); + for (const from of [0, 30]) { + writeLerpSegment(seg, 0, { + from: fix, + to, + t0: 0, + t1: 30, + course0Deg: 0, + courseSlopeDeg: 90, + }); + writeCourseGlide(seg, 0, from, 0, 0); + for (const tau of [0, 10, 20, 30, 60]) + assert.ok( + courseGap(segmentCourse(seg, 0, tau), from) < 1e-4, + `from ${from}° at τ=${tau}`, + ); + } + writeArcSegment(seg, 0, { + fix, + t0: 0, + minDt: 0, + maxDt: 300, + speedMps: 1, + trackDeg: 90, + turnRateDps: 3, + }); + writeCourseGlide(seg, 0, 90, 0, 0); + assert.ok(courseGap(segmentCourse(seg, 0, 20), 90) < 1e-4, 'arc turn held'); +}); diff --git a/src/data/iconSet.js b/src/data/iconSet.js index c268e6d260..1ac8b8c3c3 100644 --- a/src/data/iconSet.js +++ b/src/data/iconSet.js @@ -43,8 +43,14 @@ export const ICON_SHOWN = 1; export const ICON_ROTATES = 2; /** Fade and shrink toward the globe's limb (aircraft recession). */ export const ICON_RECEDES = 4; -/** Lift the row 12 m along the normal before the horizon test (fixes near the ground). */ +/** + * Judge the row at no lower than ICON_CULL_HEIGHT_M above the ellipsoid in the + * horizon test. A fix near or below the ellipsoid (a grounded contact at geoid + * −31 m before its floor warms) otherwise reads as beyond the limb. + */ export const ICON_CULL_LIFT = 8; +/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */ +export const ICON_CULL_HEIGHT_M = 12; /** Move the epoch forward once render times pass this many seconds. */ const REBASE_AFTER_SEC = 1800; @@ -422,6 +428,24 @@ export function createIconSet({ capacity = 1024, epoch } = {}) { course(row, tau) { return segmentCourse(segments, row, tau); }, + /** The point the horizon test judges for a row drawn at `position`. */ + cullPoint(row, position, result = new Cesium.Cartesian3()) { + if (!(style[row * STYLE_STRIDE + FLAGS] & ICON_CULL_LIFT)) + return Cesium.Cartesian3.clone(position, result); + // Height above the ellipsoid along the geocentric ray, as the shader + // computes it: exact to millimetres this close to the surface. + const radius = Cesium.Cartesian3.magnitude(position); + Cesium.Cartesian3.multiplyComponents( + position, + Cesium.Ellipsoid.WGS84.oneOverRadii, + result, + ); + const height = radius * (1 - 1 / Cesium.Cartesian3.magnitude(result)); + const lift = Math.max(0, ICON_CULL_HEIGHT_M - height); + Cesium.Cartesian3.normalize(position, result); + Cesium.Cartesian3.multiplyByScalar(result, lift, result); + return Cesium.Cartesian3.add(position, result, result); + }, }; function markRow(row) { diff --git a/src/data/iconSet.test.mjs b/src/data/iconSet.test.mjs index 934b83e535..84e11c48b7 100644 --- a/src/data/iconSet.test.mjs +++ b/src/data/iconSet.test.mjs @@ -4,6 +4,8 @@ import * as Cesium from 'cesium'; import { createIconSet, DirtyRows, + ICON_CULL_HEIGHT_M, + ICON_CULL_LIFT, ICON_ROTATES, ICON_SHOWN, } from './iconSet.js'; @@ -225,3 +227,25 @@ test('rebasing moves the epoch without moving any row', () => { assert.equal(set.expires(row), 1100); assert.deepEqual(set.dirty.segments.runs(set.count), [[0, 0]]); }); + +test('a cull-lift row is judged at no lower than the cull height above the ellipsoid', () => { + const set = createIconSet(); + const row = set.add('a'); + const height = (p) => Cesium.Cartographic.fromCartesian(p).height; + const at = (h) => Cesium.Cartesian3.fromDegrees(-84.43, 33.64, h); + assert.ok( + Math.abs(height(set.cullPoint(row, at(-31))) - -31) < 1e-6, + 'unflagged: as drawn', + ); + set.setFlag(row, ICON_CULL_LIFT, true); + for (const h of [-31, 0, 5]) { + assert.ok( + Math.abs(height(set.cullPoint(row, at(h))) - ICON_CULL_HEIGHT_M) < 0.01, + `${h} m is judged at ${ICON_CULL_HEIGHT_M} m`, + ); + } + assert.ok( + Math.abs(height(set.cullPoint(row, at(131))) - 131) < 1e-6, + 'a contact floored higher keeps its own height', + ); +}); diff --git a/src/data/iconSetPrimitive.js b/src/data/iconSetPrimitive.js index f832cfdf7c..6aaf9907e3 100644 --- a/src/data/iconSetPrimitive.js +++ b/src/data/iconSetPrimitive.js @@ -16,7 +16,7 @@ */ import * as Cesium from 'cesium'; import { ICON_SEGMENT_GLSL, SEGMENT_STRIDE } from './iconSegment.js'; -import { ICON_CULL_LIFT, STYLE_STRIDE } from './iconSet.js'; +import { ICON_CULL_HEIGHT_M, ICON_CULL_LIFT, STYLE_STRIDE } from './iconSet.js'; import { iconAtlas, MAX_ICON_SLOTS } from './iconAtlas.js'; import { cameraLimbDistanceM, @@ -25,8 +25,6 @@ import { /** On-screen device pixels above which a row draws its near (large) image. */ const NEAR_IMAGE_PX = 76; -/** Rows lifted this far before the horizon test when flagged (low fixes). */ -const CULL_LIFT_M = 12; const ATTRIBUTE_LOCATIONS = Object.freeze({ corner: 0, @@ -80,6 +78,13 @@ bool iconFlag(float flags, float bit) { return mod(floor(flags / bit), 2.0) == 1.0; } +// Raise a near-ground point to at least the cull height (iconSet.cullPoint). +vec3 iconCullPoint(vec3 world) { + float radius = length(world); + float height = radius * (1.0 - 1.0 / length(world * czm_ellipsoidInverseRadii)); + return world + world / radius * max(0.0, ${ICON_CULL_HEIGHT_M.toFixed(1)} - height); +} + bool occludedByEllipsoid(vec3 world) { vec3 cv = u_horizon.xyz; float vh2 = u_horizon.w; @@ -101,7 +106,7 @@ void main() { vec3 rte = iconSegmentPosition(seg0, seg1, seg2, seg3, seg4, u_tau); vec3 world = u_cameraPosition + rte; - vec3 cullPoint = iconFlag(flags, ${ICON_CULL_LIFT.toFixed(1)}) ? world + normalize(world) * ${CULL_LIFT_M.toFixed(1)} : world; + vec3 cullPoint = iconFlag(flags, ${ICON_CULL_LIFT.toFixed(1)}) ? iconCullPoint(world) : world; if (occludedByEllipsoid(cullPoint)) return; vec4 positionEC = czm_modelViewRelativeToEye * vec4(rte, 1.0); diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index 5a17be256c..529544d2d9 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -1660,7 +1660,7 @@ test('hasContact declines while a layer is disabled, whatever its maps still hol [ 'flights', readLayerSource(new URL('./flights.js', import.meta.url)), - /hasContact\(\s*icao24,?\s*\)\s*\{\s*\n\s*if\s*\(\s*!(?:flightState\.)?_billboardCollection\s*\|\|\s*!(?:flightState\.)?_billboardCollection\.show\s*\|\|\s*(?:flightState\.)?_billboards\.size\s*===\s*0,?\s*\)\s*return\s*null;/, + /hasContact\(\s*icao24,?\s*\)\s*\{\s*\n\s*const icons = flightState\._icons;\s*\n\s*if\s*\(\s*!icons\s*\|\|\s*!icons\.show\s*\|\|\s*icons\.count\s*===\s*0,?\s*\)\s*return\s*null;/, ], [ 'militaryFlights', diff --git a/src/data/nearbyModelHandoff.test.mjs b/src/data/nearbyModelHandoff.test.mjs index 665ef72b58..449ec6a805 100644 --- a/src/data/nearbyModelHandoff.test.mjs +++ b/src/data/nearbyModelHandoff.test.mjs @@ -10,7 +10,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import flightsLayer, { _setTrackedFlightRefreshStateForTest } from './flights.js'; +import flightsLayer, { + _iconForTest, + _setTrackedFlightRefreshStateForTest, +} from './flights.js'; import militaryFlightsLayer, { _setTrackedMilitaryRefreshStateForTest } from './militaryFlights.js'; const ICAO = 'abc123'; @@ -39,6 +42,8 @@ const LAYERS = [ name: 'commercial', layer: flightsLayer, visualCenterM: Cesium.Cartesian3.ZERO, + // Where the icon is drawn: the seeded position as the GPU encodes it. + spritePosition: () => _iconForTest(ICAO).position, seed({ billboardShow, models = [] }) { _setTrackedFlightRefreshStateForTest({ icao24: ICAO, @@ -61,6 +66,7 @@ const LAYERS = [ name: 'military', layer: militaryFlightsLayer, visualCenterM: Cesium.Cartesian3.ZERO, + spritePosition: () => contactBillboard(true).position, seed({ billboardShow, models = [] }) { _setTrackedMilitaryRefreshStateForTest({ icao24: ICAO, @@ -149,8 +155,8 @@ for (const fixture of LAYERS) { const spritePosition = detectionPosition(fixture.layer); assert.ok(spritePosition, 'the 2D sprite publishes a detection candidate'); assert.ok( - Cesium.Cartesian3.equalsEpsilon(spritePosition, contactBillboard(true).position, 0, 1e-6), - 'the 2D bracket stays welded to the billboard position', + Cesium.Cartesian3.equalsEpsilon(spritePosition, fixture.spritePosition(), 0, 1e-6), + 'the 2D bracket stays welded to the drawn sprite position', ); const modelMatrix = Cesium.Matrix4.fromRotationTranslation(MODEL_ROTATION, MODEL_POSITION); @@ -195,7 +201,7 @@ for (const fixture of LAYERS) { const loadingPosition = detectionPosition(fixture.layer); assert.ok(loadingPosition, 'the billboard remains detectable while its model loads'); assert.ok( - Cesium.Cartesian3.equalsEpsilon(loadingPosition, contactBillboard(true).position, 0, 1e-6), + Cesium.Cartesian3.equalsEpsilon(loadingPosition, fixture.spritePosition(), 0, 1e-6), 'a shown-but-unready zero-scale model cannot steal the detection anchor', ); }); diff --git a/src/data/routeSegment.test.mjs b/src/data/routeSegment.test.mjs index e48d4645d7..9eee62c563 100644 --- a/src/data/routeSegment.test.mjs +++ b/src/data/routeSegment.test.mjs @@ -3,7 +3,6 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { routePlausible } from './routePlausible.js'; import { createTracking } from '../layers/flights/tracking.js'; -import { addBillboard } from './billboardMirror.js'; const SFO = { lat: 37.6188, lon: -122.3754, code: 'SFO' }; const LAX = { lat: 33.9416, lon: -118.4085, code: 'LAX' }; @@ -116,15 +115,14 @@ test('unjudgeable endpoint geometry and missing coordinates keep the loose contr assert.equal(plausible(beyond, null, null), true); }); -test('the actual native tracked label hides the wrong leg and keeps a healthy route', (t) => { - const collection = new Cesium.BillboardCollection(); - t.after(() => collection.destroy()); +test('the actual native tracked label hides the wrong leg and keeps a healthy route', () => { const flightState = { records: { data: new Map(), missingPolls: new Map() }, feed: { _backoff: false }, - _billboards: new Map(), _scratchCarto: new Cesium.Cartographic(), }; + // Where each contact's icon is drawn. + const drawn = new Map(); // Only application host services are supplied. Route admission, WGS84 // billboard conversion and tracked-label formatting are the actual owners. const services = Object.fromEntries( @@ -141,7 +139,10 @@ test('the actual native tracked label hides the wrong leg and keeps a healthy ro ].map((name) => [name, {}]), ); services.aircraftPresentation = { isTr3b: () => false }; - const parts = { queries: { _contactLabel: (_, info) => info.callsign } }; + const parts = { + queries: { _contactLabel: (_, info) => info.callsign }, + icons: { _iconPosition: (id) => drawn.get(id) ?? null }, + }; const tracking = createTracking({ flightState, services, parts }); for (const [position, expected] of [ [beyond, false], @@ -155,18 +156,9 @@ test('the actual native tracked label hides the wrong leg and keeps a healthy ro verticalRate: 0, route, }); - flightState._billboards.set( + drawn.set( id, - addBillboard(collection, { - id, - width: 20, - height: 20, - position: Cesium.Cartesian3.fromDegrees( - position.lon, - position.lat, - 10000, - ), - }), + Cesium.Cartesian3.fromDegrees(position.lon, position.lat, 10000), ); assert.equal( tracking._trackedLabelText(id).includes('SFO → LAX'), diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index 654dce572e..d2053832ae 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -233,7 +233,7 @@ test('both flight layers keep a converted contact 2D and visible (render invaria // 1. The 3D model handoff is SUPPRESSED for a converted contact — there is // no TR-3B GLB, so the triangle billboard stays the visual. - assert.match(source, /modelEligible\.has\(icao24\) && !isTr3b\(icao24\)/, + assert.match(source, /modelEligible\.has\(icao24\) && !isTr3b\(icao24\)|for \(const icao24 of modelEligible\) \{\s*if \(isTr3b\(icao24\)\) continue;/, `${name}: fleet model handoff skips converted contacts`); // The tracked regime became default-on and camera-distance driven // (2026-08-19), so the suppression moved from a conjunct on @@ -245,7 +245,7 @@ test('both flight layers keep a converted contact 2D and visible (render invaria // 2. The billboard is never hidden by that suppression — it must keep // satisfying the getNearby/getDetectableObjects visibility guards, so a // converted contact still works in Contacts and Cockpit. - assert.match(source, /if\s*\(\s*(bb|modelled)\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*setBillboard\(\s*\1,\s*'show',\s*true,?\s*\);/, + assert.match(source, /if\s*\(\s*(bb|modelled)\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*setBillboard\(\s*\1,\s*'show',\s*true,?\s*\);|if\s*\(\s*row >= 0\s*&&\s*id\s*!==\s*flightState\._trackedIcao\s*\)\s*flightState\._icons\.setShown\(row, true\);/, `${name}: converting restores the billboard the model handoff had hidden`); // 3. Every aircraftIcon() CALL SITE routes through the kind resolver, so no @@ -411,7 +411,7 @@ test('a converted contact never consumes a 3D model CAP SLOT', async () => { const source = readLayerSource(new URL(`./${name}`, import.meta.url)); // Anchor on the MODEL-eligibility loop (keepDistSq), not the unrelated // ambient-enrichment candidate loop that also builds a `cand`. - const loop = /const\s*cand\s*=\s*\[\];\s*\n\s*for\s*\(\s*const\s*\[icao,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)[\s\S]*?cand\.push\(\s*/.exec(source)?.[0]; + const loop = /const\s*cand\s*=\s*\[\];\s*\n\s*for\s*\((?:\s*const\s*\[icao,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*|let row = 0; row < icons\.count; row\+\+)\)[\s\S]*?cand\.push\(\s*/.exec(source)?.[0]; assert.ok(loop, `${name}: the model-eligibility candidate loop is present`); assert.match(loop, /keepDistSq/, `${name}: matched the model-eligibility loop`); assert.match(loop, /if \(isTr3b\(icao\)\) continue;/, diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index d30adb4e89..072aab15f6 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -34,6 +34,8 @@ import flightsLayer, { _trackedBillboardColorForTest as flightsTrackedBillboardColor, _driveFleetModelHandoffForTest as flightsDriveFleetModel, _ensureFleetModelForTest as flightsEnsureFleetModel, + _iconForTest as flightsIcon, + _setIconForTest as flightsSetIcon, } from './flights.js'; import militaryFlightsLayer, { _setTrackedMilitaryRefreshStateForTest, @@ -186,6 +188,25 @@ function contactBillboard() { }; } +/** A flights contact's icon row, read and written the way these tests read a + * billboard: where it is drawn and whether the layer shows it. */ +function flightIconView(icao24) { + return { + get position() { + return flightsIcon(icao24)?.position; + }, + set position(position) { + flightsSetIcon(icao24, { position }); + }, + get show() { + return flightsIcon(icao24)?.shown === true; + }, + set show(shown) { + flightsSetIcon(icao24, { shown }); + }, + }; +} + /** Records what the driver hands to the scene, so a test can assert that a * failing loader never put a model up. */ function recordingModelCollection() { @@ -216,7 +237,7 @@ const LAYERS = [ modelCollection, meta: { callsign: 'TEST123 ', altitude: 10_668, klass: 'airliner', onGround }, }); - return billboard; + return flightIconView(icao24); }, }, { diff --git a/src/layers/flights/enrichment.js b/src/layers/flights/enrichment.js index a3b2984a4a..b174591a07 100644 --- a/src/layers/flights/enrichment.js +++ b/src/layers/flights/enrichment.js @@ -9,7 +9,6 @@ import { ENRICH_AMBIENT_REFILL_WINDOW_MS, ENRICH_AMBIENT_PER_SWEEP, } from './policy.js'; -import { billboardState } from '../../data/billboardMirror.js'; export function createEnrichment({ flightState, @@ -94,9 +93,7 @@ export function createEnrichment({ }); if (klass !== meta.klass) { meta.klass = klass; - const bb = flightState._billboards.get(icao24); - if (bb) - parts.rendering._applyFleetBillboardPresentation(icao24, bb); + parts.icons._applyIconPresentation(icao24); // 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); @@ -182,8 +179,7 @@ export function createEnrichment({ if ( flightState._enrichAmbientBudget <= 0 || !flightState._viewer || - !flightState._billboardCollection || - !flightState._billboardCollection.show + !flightState._icons?.show ) return; try { @@ -196,13 +192,19 @@ export function createEnrichment({ camera.upWC, ); const cand = []; - for (const [icao24, bb] of flightState._billboards) { + const icons = flightState._icons; + const tau = parts.icons._displayTau(); + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); 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) - const { position } = billboardState(bb); - if (!position || !occluder.isPointVisible(position)) continue; // beyond the limb - Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); + const position = icons.position( + row, + tau, + flightState._scratchModelBS.center, + ); + if (!occluder.isPointVisible(position)) continue; // beyond the limb if ( cull.computeVisibility(flightState._scratchModelBS) === Cesium.Intersect.OUTSIDE diff --git a/src/layers/flights/evidence.js b/src/layers/flights/evidence.js index 49407daffc..0e02411f13 100644 --- a/src/layers/flights/evidence.js +++ b/src/layers/flights/evidence.js @@ -1,11 +1,11 @@ import * as Cesium from 'cesium'; -import { aircraftIcon } from '../../data/aircraftIcons.js'; import { FOCUS_EVIDENCE_DEV } from './policy.js'; +import { writeHoldSegment } from '../../data/iconSegment.js'; import { - addBillboard, - billboardState, - setBillboard, -} from '../../data/billboardMirror.js'; + aircraftRecessionFactors, + aircraftTreatmentAlpha, +} from '../../data/aircraftRecession.js'; +import { horizonOccluder } from '../../data/iconOrientation.js'; export function createEvidence({ flightState, @@ -44,17 +44,14 @@ export function createEvidence({ /** Replace the real fleet with deterministic explicit-position contacts. */ function _setFocusEvidenceAircraft(records = []) { - if ( - !FOCUS_EVIDENCE_DEV || - !flightState._billboardCollection || - !flightState._viewer - ) + if (!FOCUS_EVIDENCE_DEV || !flightState._icons || !flightState._viewer) return { ok: false, count: 0 }; if (flightState._trackedIcao) parts.tracking._clearTracking(); parts.rendering._releaseModels(); - for (const bb of flightState._billboards.values()) - flightState._billboardCollection.remove(bb); - flightState._billboards.clear(); + const icons = flightState._icons; + icons.clear(); + flightState._grounded.clear(); + flightState._floorPinned.clear(); flightState.records.data.clear(); flightState._positionHistory.clear(); flightState._displayCourse.clear(); @@ -86,32 +83,19 @@ export function createEvidence({ rawLon: record.longitude ?? null, }; flightState.records.data.set(id, meta); - flightState._cullPositions.delete(id); flightState._focusEvidenceIds.add(id); - const bb = addBillboard(flightState._billboardCollection, { - position, - image: aircraftIcon(parts.rendering._iconKind(id, klass)), - width: 20, - height: 20, - scale: parts.rendering._fleetBillboardScale(id, klass), - rotation: 0, - alignedAxis: Cesium.Cartesian3.ZERO, - color: parts.rendering._fleetBillboardColor(id), - sizeInMeters: false, - scaleByDistance: parts.rendering._normalBillboardScaleByDistance(), - disableDepthTestDistance: parts.rendering._groundDepthDistance(), - id, - show: true, - }); - flightState._billboards.set(id, bb); + parts.icons._addIcon(id); + const row = icons.row(id); + writeHoldSegment(icons.segments, row, position, meta.true_track); + icons.segmentWritten(row); } - flightState.feed._count = flightState._billboards.size; + flightState.feed._count = icons.count; flightState._lastFleetTickMs = 0; flightState._viewer.scene.requestRender?.(); return { ok: true, count: flightState.feed._count }; } - /** Update explicit evidence positions without rebuilding billboards. */ + /** Update explicit evidence positions without rebuilding rows. */ function _moveFocusEvidenceAircraft(records = []) { if (!FOCUS_EVIDENCE_DEV) return { ok: false, moved: 0 }; @@ -122,15 +106,21 @@ export function createEvidence({ .toLowerCase(); if (!flightState._focusEvidenceIds.has(id)) continue; const position = _focusEvidencePosition(record); - const bb = flightState._billboards.get(id); - if (!position || !bb) continue; - setBillboard(bb, 'position', position); + const row = flightState._icons?.row(id) ?? -1; + if (!position || row < 0) continue; const meta = flightState.records.data.get(id); if (meta) { if (Number.isFinite(record.trackDeg)) meta.true_track = record.trackDeg; if (Number.isFinite(record.velocityMps)) meta.velocity = record.velocityMps; } + writeHoldSegment( + flightState._icons.segments, + row, + position, + meta?.true_track ?? 0, + ); + flightState._icons.segmentWritten(row); moved += 1; } flightState._lastFleetTickMs = 0; @@ -142,27 +132,42 @@ export function createEvidence({ function _focusEvidenceSnapshot() { if (!FOCUS_EVIDENCE_DEV || !flightState._viewer) return []; + const icons = flightState._icons; + const { scene, camera } = flightState._viewer; + const occluder = horizonOccluder(camera); + const cameraHeightM = camera.positionCartographic?.height; return [...flightState._focusEvidenceIds].map((id) => { - const bb = flightState._billboards.get(id); - const screen = billboardState(bb)?.position - ? Cesium.SceneTransforms.worldToWindowCoordinates( - flightState._viewer.scene, - billboardState(bb).position, - ) + const row = icons?.row(id) ?? -1; + const position = row < 0 ? null : parts.icons._iconPosition(id); + const cameraDistanceM = position + ? Cesium.Cartesian3.distance(camera.positionWC, position) + : null; + const screen = position + ? Cesium.SceneTransforms.worldToWindowCoordinates(scene, position) + : null; + // What the icon shader composes: base scale × limb taper, and base + // alpha × max(floor, focus × limb haze). + const factors = position + ? aircraftRecessionFactors({ cameraDistanceM, cameraHeightM }) : null; return { id, - show: billboardState(bb)?.show === true, - scale: billboardState(bb)?.scale ?? null, - alpha: bb?.color?.alpha ?? null, + show: + !!position && + icons.shown(row) && + parts.icons._aboveHorizon(row, position, occluder), + scale: factors ? icons.scale(row) * factors.scale : null, + alpha: position + ? aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(row), + focusFactor: icons.focus(row), + cameraDistanceM, + cameraHeightM, + }) + : null, x: screen?.x ?? null, y: screen?.y ?? null, - cameraDistanceM: billboardState(bb)?.position - ? Cesium.Cartesian3.distance( - flightState._viewer.camera.positionWC, - billboardState(bb).position, - ) - : null, + cameraDistanceM, }; }); } diff --git a/src/layers/flights/icons.js b/src/layers/flights/icons.js new file mode 100644 index 0000000000..8bf4df65f5 --- /dev/null +++ b/src/layers/flights/icons.js @@ -0,0 +1,471 @@ +import * as Cesium from 'cesium'; +import { + COURSE_HOLD_SPEED_MPS, + courseBetweenCartesians, + courseSlewCapDps, + norm180, + speedRamp, + staleCoastLimitSeconds, +} from '../../data/motionModel.js'; +import { + createIconSet, + ICON_CULL_LIFT, + ICON_RECEDES, + ICON_ROTATES, +} from '../../data/iconSet.js'; +import { + segmentCourse, + segmentTargetCourse, + writeArcSegment, + writeCourseGlide, + writeHoldSegment, + writeLerpSegment, +} from '../../data/iconSegment.js'; +import { IconSetPrimitive } from '../../data/iconSetPrimitive.js'; +import { iconAtlas } from '../../data/iconAtlas.js'; +import { + aircraftIcon, + FLEET_ICON_PX, + TRACKED_ICON_PX, +} from '../../data/aircraftIcons.js'; +import { cockpitContactDotImage } from '../../data/cockpitContactDot.js'; +import { horizonOccluder } from '../../data/iconOrientation.js'; +import { + COCKPIT_CONTACT_SIZE_PX, + COURSE_MAX_DPS, + FLOOR_FAR_EVERY_TICKS, + FLOOR_NEAR_M, + RENDER_DELAY_SEC, +} from './policy.js'; + +/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ +const COCKPIT_DOT_PX = 16; +/** Pinned grounded rows rewrite only past this displayed move (m²) or turn (°). */ +const PIN_MOVE_SQ_M = 1; +const PIN_TURN_DEG = 0.1; + +/** + * The flights layer's contacts as one icon set: each row's motion segment + * mirrors `_deadReckon`'s regime for the delayed display time, so the GPU + * moves every untracked contact between polls with no per-frame CPU pass. + */ +export function createIcons({ flightState, services, parts }) { + const { focusPassIsNeeded } = services.focus; + const scratchTime = new Cesium.JulianDate(); + const scratchPosition = new Cesium.Cartesian3(); + const scratchCull = new Cesium.Cartesian3(); + const scratchScaleByDistance = new Cesium.NearFarScalar(); + let normalScaleByDistance = null; + let cockpitScaleByDistance = null; + + /** The delayed instant every untracked contact is drawn at. */ + function _displayTime(result = scratchTime) { + return Cesium.JulianDate.addSeconds( + Cesium.JulianDate.now(result), + -RENDER_DELAY_SEC, + result, + ); + } + + function _displayTau() { + return flightState._icons.seconds(_displayTime()); + } + + /** Create the set and its primitive for one layer lifetime. */ + function _createIcons(viewer) { + flightState._icons = createIconSet({ epoch: _displayTime() }); + flightState._iconPrimitive = new IconSetPrimitive({ + set: flightState._icons, + renderTime: () => _displayTime(flightState._scratchIconRenderTime), + }); + viewer.scene.primitives.add(flightState._iconPrimitive); + return flightState._iconPrimitive; + } + + /** Where a contact is drawn right now, or null when it has no row. */ + function _iconPosition(icao24, result = new Cesium.Cartesian3()) { + const set = flightState._icons; + const row = set.row(icao24); + return row < 0 ? null : set.position(row, _displayTau(), result); + } + + /** The nose direction a contact is drawn with right now. */ + function _iconCourse(icao24) { + const set = flightState._icons; + const row = set.row(icao24); + return row < 0 ? null : set.course(row, _displayTau()); + } + + /** Whether the layer draws this contact's icon (not tracked, not model-owned). */ + function _iconShown(icao24) { + const set = flightState._icons; + const row = set.row(icao24); + return row >= 0 && set.shown(row); + } + + /** The camera's horizon test, or null when there is no placed camera. */ + function _occluder() { + const camera = flightState._viewer?.camera; + return camera?.positionWC ? horizonOccluder(camera) : null; + } + + /** Whether a drawn row at `position` clears the camera's horizon, judged + * exactly as the icon shader judges it. No camera, no horizon. */ + function _aboveHorizon(row, position, occluder) { + return ( + !occluder || + occluder.isPointVisible( + flightState._icons.cullPoint(row, position, scratchCull), + ) + ); + } + + /** + * Write the segment `_deadReckon` would follow from now on: interpolation + * between the bracketing fixes, the warm-up arc back from the oldest fix, or + * the coast arc past the newest. The displayed nose glides from where it is + * onto the new course at the fleet's slew cap; a hovering contact keeps its + * nose. The row expires when the regime would change. + * @param {string} icao24 + * @param {{fromCourseDeg?: number|null}} [options] Nose to glide from when + * the row's own segment is not what was on screen (tracking handoff). + */ + function _planIcon(icao24, { fromCourseDeg } = {}) { + const set = flightState._icons; + const row = set.row(icao24); + if (row < 0) return; + if (flightState._focusEvidenceIds.has(icao24)) return; + if (flightState._floorPinned.has(icao24)) return; + const history = flightState._positionHistory.get(icao24); + if (!history?.length) return; + const info = flightState.records.data.get(icao24); + const renderTime = _displayTime(); + const tau = set.seconds(renderTime); + const seg = set.segments; + const shownCourse = + fromCourseDeg ?? + (set.expires(row) === -Infinity ? null : set.course(row, tau)); + + const regime = parts.motion._motionRegime(history, info, renderTime); + let speed; + let expiresAt = Infinity; + if (regime.kind === 'between') { + const { a, b, span, trackFrom, trackTo, chordCourse } = regime; + speed = regime.speed; + const blend = chordCourse == null ? 0 : regime.blend; + const t0 = set.seconds(a.time); + if (span > 0) { + writeLerpSegment(seg, row, { + from: a.position, + to: b.position, + t0, + t1: set.seconds(b.time), + course0Deg: + trackFrom + blend * norm180((chordCourse ?? 0) - trackFrom), + courseSlopeDeg: norm180(trackTo - trackFrom) * (1 - blend), + }); + } else { + writeHoldSegment( + seg, + row, + b.position, + trackTo + blend * norm180((chordCourse ?? 0) - trackTo), + ); + } + expiresAt = set.seconds(b.time); + } else { + const { fix, heading } = regime; + speed = regime.speed; + const t0 = set.seconds(fix.time); + if (speed === 0) { + writeHoldSegment(seg, row, fix.position, heading); + } else { + writeArcSegment(seg, row, { + fix: fix.position, + t0, + minDt: regime.minDt, + maxDt: regime.maxDt, + speedMps: speed, + trackDeg: heading, + turnRateDps: regime.turnRateDps, + }); + } + // A warm-up's arc ends at its fix; a coast's runs to its limit. + if (regime.maxDt === 0) expiresAt = t0; + } + // Below hover speed the nose holds what is on screen (or, for a new row, + // where this segment starts); above it, it glides on at the slew cap. + const hold = speed < COURSE_HOLD_SPEED_MPS; + if (hold || shownCourse != null) { + writeCourseGlide( + seg, + row, + shownCourse ?? segmentCourse(seg, row, tau), + tau, + hold ? 0 : courseSlewCapDps(speed, COURSE_MAX_DPS), + ); + } + set.segmentWritten(row, expiresAt); + } + + /** Re-plan every row whose regime ended before `tau`. */ + function _replanExpired(tau) { + const set = flightState._icons; + const due = []; + for (let row = 0; row < set.count; row++) + if (set.expires(row) <= tau) due.push(set.idAt(row)); + for (const icao24 of due) _planIcon(icao24); + } + + /** + * Grounded contacts stand on the floor under where they are DRAWN, which the + * GPU cannot sample. While the floor lifts one, the CPU pins its row to a + * hold at the floored dead-reckoned position each tick (rewritten only when + * it moved); once nothing lifts it the row goes back to its planned segment. + */ + function _floorGroundedIcons(renderTime, tau, nowMs, cameraPosition) { + const set = flightState._icons; + // Past FLOOR_NEAR_M a taxiing contact moves well under a pixel per tick, + // so far rows take turns: each refreshes every FLOOR_FAR_EVERY_TICKS. Their + // eases onto a lower floor advance per call, so they run that much slower + // out there too — sub-pixel at that range, and full rate once near. + const turn = flightState._floorTick++ % FLOOR_FAR_EVERY_TICKS; + const nearSq = FLOOR_NEAR_M * FLOOR_NEAR_M; + for (const icao24 of flightState._grounded) { + if (icao24 === flightState._trackedIcao) continue; + const row = set.row(icao24); + if (row < 0) continue; + if ( + row % FLOOR_FAR_EVERY_TICKS !== turn && + cameraPosition && + Cesium.Cartesian3.distanceSquared( + cameraPosition, + set.position(row, tau, scratchPosition), + ) > nearSq + ) + continue; + _floorIcon(icao24, renderTime, tau, nowMs); + } + } + + /** One grounded contact's floor pass (see `_floorGroundedIcons`). */ + function _floorIcon(icao24, renderTime, tau, nowMs) { + const set = flightState._icons; + const row = set.row(icao24); + if (row < 0) return; + const info = flightState.records.data.get(icao24); + const raw = parts.motion._deadReckon( + icao24, + flightState._scratchFleetPos, + renderTime, + ); + const rawCourse = + flightState._drCourseDeg ?? (info && info.true_track) ?? 0; + const hold = flightState._drCourseHold; + const speed = flightState._drSpeedMps ?? info?.velocity ?? NaN; + const display = parts.motion._floorGroundedDisplayPosition( + icao24, + info, + raw, + parts.rendering._modelOwnsVisual(icao24), + nowMs, + ); + if (!display || display === raw) { + if (flightState._floorPinned.delete(icao24)) + _planIcon(icao24, { fromCourseDeg: set.course(row, tau) }); + return; + } + const planned = set.expires(row) !== -Infinity; + const prev = planned ? set.course(row, tau) : null; + // The pin holds the position; the GPU glides the course onto the target, + // so the rate stays exact however seldom the pin is rewritten. + const target = hold && prev != null ? prev : rawCourse; + if ( + flightState._floorPinned.has(icao24) && + Cesium.Cartesian3.distanceSquared( + display, + set.position(row, tau, scratchPosition), + ) <= PIN_MOVE_SQ_M && + Math.abs(norm180(target - segmentTargetCourse(set.segments, row, tau))) <= + PIN_TURN_DEG + ) + return; + flightState._floorPinned.add(icao24); + writeHoldSegment(set.segments, row, display, target); + if (prev != null) + writeCourseGlide( + set.segments, + row, + prev, + tau, + courseSlewCapDps(speed, COURSE_MAX_DPS), + ); + set.segmentWritten(row); + } + + /** + * Advance focus de-emphasis for every drawn row (and every row a fleet model + * draws for, whose alpha reads it), only while a focus target exists or some + * row is still relaxing back to full emphasis. + */ + function _focusIcons(tau, scene, camera, nowMs, target) { + if (!focusPassIsNeeded(target, flightState._iconFocusActive)) return; + const { advanceProjectedSpriteFocus, nearFarScalarValueAtDistance } = + services.focus; + const set = flightState._icons; + let active = 0; + for (let row = 0; row < set.count; row++) { + if (!set.shown(row) && !flightState._models.has(set.idAt(row))) continue; + const position = set.position(row, tau, scratchPosition); + const distanceScale = nearFarScalarValueAtDistance( + set.scaleByDistance(row, scratchScaleByDistance), + Cesium.Cartesian3.distance(camera.positionWC, position), + ); + const half = set.scale(row) * distanceScale * 0.5; + const focus = advanceProjectedSpriteFocus( + set.metaAt(row), + position, + scene, + camera, + nowMs, + target, + undefined, + set.width(row) * half, + set.height(row) * half, + ); + set.setFocus(row, focus.factor); + if (focus.active || focus.transitioning) active++; + } + flightState._iconFocusActive = active; + } + + /** Image, size, scale, tint and freshness for one row under the current + * normal/cockpit contract. Motion and rotation stay with the segment. */ + function _applyIconPresentation(icao24) { + const set = flightState._icons; + const row = set.row(icao24); + if (row < 0) return; + const info = flightState.records.data.get(icao24); + const tracked = icao24 === flightState._trackedIcao; + const cockpitDot = + flightState._cockpitContactMode && + !tracked && + !flightState._cockpitNearContacts.has(icao24); + if (cockpitDot) { + const dot = iconAtlas.slot(cockpitContactDotImage(), COCKPIT_DOT_PX); + set.setImage(row, dot, dot); + set.setSize(row, COCKPIT_CONTACT_SIZE_PX, COCKPIT_CONTACT_SIZE_PX); + set.setScale(row, 1); + cockpitScaleByDistance ??= + parts.rendering._cockpitBillboardScaleByDistance(); + set.setScaleByDistance(row, cockpitScaleByDistance); + set.setColor(row, parts.rendering._cockpitContactColor(icao24, info)); + set.setFlag(row, ICON_ROTATES, false); + } else { + set.setImage( + row, + iconAtlas.slot( + aircraftIcon(parts.rendering._iconKind(icao24, info?.klass)), + FLEET_ICON_PX, + ), + iconAtlas.slot( + aircraftIcon( + parts.rendering._iconKind(icao24, info?.klass), + TRACKED_ICON_PX, + ), + TRACKED_ICON_PX, + ), + ); + const size = tracked ? 24 : 20; + set.setSize(row, size, size); + set.setScale( + row, + parts.rendering._fleetBillboardScale(icao24, info?.klass), + ); + normalScaleByDistance ??= + parts.rendering._normalBillboardScaleByDistance(); + set.setScaleByDistance(row, normalScaleByDistance); + set.setColor(row, parts.rendering._fleetBillboardColor(icao24, info)); + set.setFlag(row, ICON_ROTATES, true); + } + set.setFlag(row, ICON_RECEDES, true); + set.setFlag( + row, + ICON_CULL_LIFT, + Number.isFinite(info?.renderAltitudeM) && info.renderAltitudeM < 10, + ); + set.setAlpha(row, flightState.records.missingPolls.get(icao24) ? 0.45 : 1); + } + + /** Add a row for a new contact, hidden while it is the tracked one. */ + function _addIcon(icao24) { + const set = flightState._icons; + const row = set.add(icao24, { layer: 'flights', id: icao24 }); + _applyIconPresentation(icao24); + _settleIcon(icao24); + set.setShown(row, icao24 !== flightState._trackedIcao); + return row; + } + + /** + * Plan a row afresh, dropping any floor pin (a pin stops at the last floor + * pass, which skips a tracked contact), and let a dimmed row relax. A grounded contact goes straight onto + * the floor under where it is drawn, not its fix's floor until the next fleet + * tick raises it. + * @param {string} icao24 + * @param {{fromCourseDeg?: number}} [options] The course on screen to glide from. + */ + function _settleIcon(icao24, options) { + const set = flightState._icons; + flightState._floorPinned.delete(icao24); + // A row that sat out the focus pass (tracked) may come back dimmed after + // the pass went idle; count it so the pass runs and relaxes it. + if (set.focus(set.row(icao24)) < 1) flightState._iconFocusActive += 1; + _planIcon(icao24, options); + if (flightState._grounded.has(icao24)) { + const renderTime = _displayTime(); + _floorIcon(icao24, renderTime, set.seconds(renderTime), Date.now()); + } + } + + /** Drop a contact and everything the layer keeps for it. */ + function _forgetContact(icao24) { + flightState._icons?.remove(icao24); + parts.rendering._releaseModel(icao24); + flightState.records.forget(icao24); + flightState._positionHistory.delete(icao24); + flightState._displayCourse.delete(icao24); + flightState._groundSnap.forget(icao24); + flightState._displayFloorState.delete(icao24); + flightState._grounded.delete(icao24); + flightState._floorPinned.delete(icao24); + } + + /** Icon ids, so ray samples never land on an aircraft instead of the ground. */ + function _iconIds() { + const set = flightState._icons; + const ids = new Array(set?.count ?? 0); + for (let row = 0; row < ids.length; row++) ids[row] = set.idAt(row); + return ids; + } + + return { + _displayTime, + _displayTau, + _createIcons, + _iconPosition, + _iconCourse, + _iconShown, + _occluder, + _aboveHorizon, + _planIcon, + _settleIcon, + _replanExpired, + _floorGroundedIcons, + _focusIcons, + _applyIconPresentation, + _addIcon, + _forgetContact, + _iconIds, + }; +} diff --git a/src/layers/flights/icons.test.mjs b/src/layers/flights/icons.test.mjs new file mode 100644 index 0000000000..1357e93acf --- /dev/null +++ b/src/layers/flights/icons.test.mjs @@ -0,0 +1,120 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { createFlightState } from './state.js'; +import { createIcons } from './icons.js'; +import { createIconSet } from '../../data/iconSet.js'; +import { writeHoldSegment } from '../../data/iconSegment.js'; + +function services(focus = {}) { + return { + focus: { focusPassIsNeeded: () => true, ...focus }, + groundSnap: { createGroundSnap: () => ({ clear() {}, forget() {} }) }, + }; +} + +function setup({ focus, motion = {}, rendering = {} } = {}) { + const svc = services(focus); + const flightState = createFlightState({ services: svc }); + flightState._icons = createIconSet(); + const parts = { + motion, + rendering: { _modelOwnsVisual: () => false, ...rendering }, + }; + const icons = createIcons({ flightState, services: svc, parts }); + return { flightState, icons, set: flightState._icons }; +} + +function hold(set, id, position, course = 0) { + const row = set.add(id, { layer: 'flights', id }); + writeHoldSegment(set.segments, row, position, course); + set.segmentWritten(row); + return row; +} + +const at = (lon, h = 1000) => Cesium.Cartesian3.fromDegrees(lon, 30, h); + +test('focus advances for drawn rows and for rows a fleet model draws for', () => { + const advanced = []; + const { flightState, icons, set } = setup({ + focus: { + nearFarScalarValueAtDistance: () => 1, + advanceProjectedSpriteFocus(meta) { + advanced.push(meta.id); + return { factor: 0.4, active: true }; + }, + }, + }); + set.setShown(hold(set, 'drawn', at(0)), true); + const modeled = hold(set, 'modeled', at(0.1)); + hold(set, 'hidden', at(0.2)); + flightState._models.set('modeled', {}); + + icons._focusIcons(0, {}, { positionWC: at(0, 50_000) }, 0, {}); + assert.deepEqual(advanced, ['drawn', 'modeled']); + assert.ok( + Math.abs(set.focus(modeled) - 0.4) < 1e-6, + "the model's alpha reads it", + ); + assert.equal(flightState._iconFocusActive, 2); +}); + +test('settling a pinned grounded contact re-floors it where it is now, nose kept', () => { + const taxied = at(0.01, 100); + const floored = at(0.01, 131.5); + const { flightState, icons, set } = setup({ + motion: { + _motionRegime: () => ({ + kind: 'fix', + fix: { position: taxied, time: Cesium.JulianDate.now() }, + speed: 0, + heading: 200, + turnRateDps: 0, + minDt: -60, + maxDt: 60, + }), + _deadReckon(icao24, result) { + flightState._drCourseDeg = 200; + flightState._drSpeedMps = 0; + flightState._drCourseHold = true; + return Cesium.Cartesian3.clone(taxied, result); + }, + _floorGroundedDisplayPosition: () => floored, + }, + }); + // Pinned before it was tracked, 1 km back, facing 10°. + const row = hold(set, 'g', at(0, 131.5), 10); + flightState._floorPinned.add('g'); + flightState._grounded.add('g'); + flightState.records.data.set('g', { onGround: true }); + flightState._positionHistory.set('g', [{}]); + + icons._settleIcon('g', { fromCourseDeg: 123 }); + const tau = icons._displayTau(); + assert.ok(Cesium.Cartesian3.distance(set.position(row, tau), floored) < 0.01); + assert.ok(Math.abs(set.course(row, tau) - 123) < 1e-3, 'tracked nose kept'); + assert.ok(flightState._floorPinned.has('g'), 'pinned on the new floor'); +}); + +test('a contact that comes back dimmed re-arms the idle focus pass', () => { + const advanced = []; + const { flightState, icons, set } = setup({ + focus: { + focusPassIsNeeded: (target, active) => target != null || active > 0, + nearFarScalarValueAtDistance: () => 1, + advanceProjectedSpriteFocus(meta) { + advanced.push(meta.id); + return { factor: 1, active: false, transitioning: false }; + }, + }, + motion: { _motionRegime: () => null }, + }); + const row = hold(set, 'was-tracked', at(0)); + set.setFocus(row, 0.2); + flightState._iconFocusActive = 0; + icons._settleIcon('was-tracked'); + set.setShown(row, true); + icons._focusIcons(0, {}, { positionWC: at(0, 50_000) }, 0, null); + assert.deepEqual(advanced, ['was-tracked']); + assert.equal(set.focus(row), 1); +}); diff --git a/src/layers/flights/index.js b/src/layers/flights/index.js index f778c98b15..c42a0f9fba 100644 --- a/src/layers/flights/index.js +++ b/src/layers/flights/index.js @@ -1,6 +1,7 @@ import { createFlightSnapshotRenderer } from './snapshotRenderer.js'; import { createFlightState } from './state.js'; import { createRendering } from './rendering.js'; +import { createIcons } from './icons.js'; import { createMotion } from './motion.js'; import { createTracking } from './tracking.js'; import { createController } from './controller.js'; @@ -21,6 +22,7 @@ export function createCivilFlightLayer({ const layer = {}; const context = { flightState, services, parts, layer, resolveAsset }; parts.rendering = createRendering(context); + parts.icons = createIcons(context); parts.motion = createMotion(context); parts.tracking = createTracking(context); parts.controller = createController(context); @@ -38,6 +40,7 @@ export function createCivilFlightLayer({ rendering: parts.rendering, tracking: parts.tracking, motion: parts.motion, + icons: parts.icons, enrichment: parts.enrichment, queries: parts.queries, }); diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index 0ca9446472..225e8bf82c 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -34,7 +34,7 @@ export function createLifecycle({ /** * Initialize the flights layer. - * Creates the BillboardCollection, resets all state, and installs the + * Creates the icon set and its primitive, resets all state, and installs the * click-to-track handler on the scene canvas. * @param {Cesium.Viewer} viewer - The CesiumJS viewer instance. */ @@ -48,9 +48,7 @@ export function createLifecycle({ clearFocusTarget('flights'); flightState._focusEvidenceIds.clear(); flightState._viewer = viewer; - flightState._billboardCollection = new Cesium.BillboardCollection(); - viewer.scene.primitives.add(flightState._billboardCollection); - registerSpriteCollection('flights', flightState._billboardCollection); + registerSpriteCollection('flights', parts.icons._createIcons(viewer)); flightState._modelCollection = new Cesium.PrimitiveCollection(); viewer.scene.primitives.add(flightState._modelCollection); // Warm the glTF cache so the tracked plane's model instantiates instantly when first needed @@ -78,8 +76,9 @@ export function createLifecycle({ /* tracked plane just stays a billboard a beat longer */ }); } - flightState._billboards = new Map(); - flightState._cullPositions.clear(); + flightState._grounded.clear(); + flightState._floorPinned.clear(); + flightState._iconFocusActive = 0; flightState._detectionObjects = new Map(); flightState.records.data = new Map(); flightState._positionHistory = new Map(); @@ -126,16 +125,15 @@ export function createLifecycle({ restoreSpriteOrder(viewer); - console.log('[Data:Flights] Initialized with billboard icons'); + console.log('[Data:Flights] Initialized with GPU icons'); }, /** - * Show the billboard collection and re-install the click handler. + * Show the icons and re-install the click handler. * @param {Cesium.Viewer} viewer */ enable(viewer) { - if (flightState._billboardCollection) - flightState._billboardCollection.show = true; + if (flightState._icons) flightState._icons.show = true; holdContinuousRender('flights'); // per-frame animator (perf wave 2) if (flightState._modelCollection) flightState._modelCollection.show = true; @@ -156,11 +154,10 @@ export function createLifecycle({ }); } parts.tracking._installClickHandler(viewer); - registerPickOwner('flights', (pickedId) => - flightState._billboards.has(pickedId), + registerPickOwner( + 'flights', + (pickedId) => flightState._icons?.has(pickedId) === true, ); - // Force a fresh rotation pass on the first tick after re-enable - flightState._lastCamPoseSig = ''; if (!flightState._preRenderRemove && viewer?.scene) { flightState._preRenderRemove = viewer.scene.preRender.addEventListener( parts.rendering._fleetTick, @@ -173,18 +170,11 @@ export function createLifecycle({ ); } if (!flightState._moveEndRemove && viewer?.camera) { - // Arrival polish (field test 2026-07-03: "planes look weird when you first - // come to them"): when a camera move SETTLES (voice fly-to, fast pan - // release), force a full rotation pass on the very next frame. The - // pose-signature gate alone can eat the settle — the final easing frames - // of a flight land inside one quantization bucket (10 m / 0.06°), leaving - // every icon wearing its last mid-flight rotation for up to - // ROTATION_REFRESH_MS. Zeroing the tick throttle too means the pass runs - // on the next preRender, not up to FLEET_DR_INTERVAL_MS later. Cost: one - // extra rotation pass per completed camera gesture — nothing per-frame. + // A settled camera move (voice fly-to, fast pan release) runs the fleet + // pass on the very next preRender rather than up to FLEET_DR_INTERVAL_MS + // later, so the model handoff and focus land with the camera. flightState._moveEndRemove = viewer.camera.moveEnd.addEventListener( () => { - flightState._lastCamPoseSig = ''; flightState._lastFleetTickMs = 0; }, ); @@ -193,15 +183,14 @@ export function createLifecycle({ }, /** - * Hide all flight billboards and tear down click/keyboard handlers. + * Hide all flight icons and tear down click/keyboard handlers. * Also clears any active flight tracking so the camera is released. * @param {Cesium.Viewer} viewer */ disable(viewer) { parts.controller._abortActiveUpdates(); parts.tracking._cancelPendingTrackingRestore(); - if (flightState._billboardCollection) - flightState._billboardCollection.show = false; + if (flightState._icons) flightState._icons.show = false; releaseContinuousRender('flights'); parts.rendering._releaseModels(); if (flightState._modelCollection) @@ -282,10 +271,12 @@ export function createLifecycle({ flightState._moveEndRemove = null; } parts.rendering._releaseModels(); - if (flightState._billboardCollection) { - viewer.scene.primitives.remove(flightState._billboardCollection); - flightState._billboardCollection = null; + if (flightState._iconPrimitive) { + viewer.scene.primitives.remove(flightState._iconPrimitive); // removing destroys it + flightState._iconPrimitive = null; } + flightState._icons?.clear(); + flightState._icons = null; if (flightState._modelCollection) { viewer.scene.primitives.remove(flightState._modelCollection); // removing destroys it + its models flightState._modelCollection = null; @@ -302,8 +293,9 @@ export function createLifecycle({ flightState._preloadModel = null; } flightState._planeModelLoaded = false; - flightState._billboards.clear(); - flightState._cullPositions.clear(); + flightState._grounded.clear(); + flightState._floorPinned.clear(); + flightState._iconFocusActive = 0; flightState._detectionObjects.clear(); flightState.records.data.clear(); flightState._positionHistory.clear(); diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 309966b9b0..37f2febc94 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -35,10 +35,23 @@ import { DISPLAY_CORRIDOR_CELL_BUDGET, DISPLAY_CORRIDOR_FAIR_SHARE, } from './policy.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState } from '../../data/modelMirror.js'; import { readEntityRecord } from '../../data/entityRecords.js'; +/** A fix's own ground speed, else the record's. */ +function fixSpeedMps(fix, info) { + return Number.isFinite(fix.velocity) + ? fix.velocity + : (info && info.velocity) || 0; +} + +/** A fix's own track, else the record's. */ +function fixTrackDeg(fix, info) { + return Number.isFinite(fix.track) + ? fix.track + : (info && info.true_track) || 0; +} + export function createMotion({ flightState, services, @@ -66,6 +79,23 @@ export function createMotion({ // Fixes leave the cache with their history; corrected positions invalidate // the local frame even when the existing Cartesian is mutated in place. const fixFrames = new WeakMap(); + /** `_motionRegime`'s reused result. */ + const regime = { + kind: 'fix', + a: null, + b: null, + span: 0, + speed: 0, + trackFrom: 0, + trackTo: 0, + chordCourse: null, + blend: 0, + fix: null, + heading: 0, + turnRateDps: 0, + minDt: 0, + maxDt: 0, + }; // Round 5: the old `_warmGroundedAircraftSurfaceCache` (global exact-5-decimal // warm for every grounded contact on Earth) is GONE. Parked-aircraft GPS @@ -81,7 +111,7 @@ export function createMotion({ * coasting on its final meta — if that fix predated the floor warm, it sat * frozen underground forever. Runs once per poll over the (bounded) flight * map; touches only grounded, feed-absent, demonstrably-below-floor - * contacts, and patches the stored fix + billboard in place (zero-velocity + * contacts, and patches the stored fix + icon in place (zero-velocity * DR renders the patched fix verbatim). * @param {Set} currentIcaos - Contacts present in THIS poll (already * floored by the live path — skipped here). @@ -101,7 +131,6 @@ export function createMotion({ ) continue; info.renderAltitudeM = lifted; - flightState._cullPositions.delete(icao24); // above the ellipsoid now (or floors say otherwise next poll) const position = Cesium.Cartesian3.fromDegrees( info.rawLon, info.rawLat, @@ -111,8 +140,9 @@ export function createMotion({ const newest = history?.[history.length - 1]; if (newest) newest.position = Cesium.Cartesian3.clone(position, newest.position); - const bb = flightState._billboards.get(icao24); - if (bb) setBillboard(bb, 'position', position); + // Above the ellipsoid now (or floors say otherwise next poll). + parts.icons._applyIconPresentation(icao24); + parts.icons._planIcon(icao24); } } @@ -134,9 +164,7 @@ export function createMotion({ function _deadReckon(icao24, result, sampledRenderTime) { const info = flightState.records.data.get(icao24); if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) { - const position = billboardState( - flightState._billboards.get(icao24), - )?.position; + const position = parts.icons._iconPosition(icao24); flightState._drCourseDeg = info?.true_track || 0; flightState._drSpeedMps = info?.velocity || 0; flightState._drCourseHold = @@ -166,100 +194,113 @@ export function createMotion({ flightState._scratchRenderTime, ); - // Bracketing pair: interpolate — no extrapolation error, no snap-back. + const regime = _motionRegime(history, info, renderTime); + if (regime.kind === 'between') { + const { a, b, span } = regime; + const t = + span > 0 + ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span + : 1.0; + const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t); + flightState._drCourseDeg = + regime.chordCourse != null + ? lerpAngleDeg(trackCourse, regime.chordCourse, regime.blend) + : trackCourse; + flightState._drSpeedMps = regime.speed; + flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS; + flightState._drExtrapolating = false; + return Cesium.Cartesian3.lerp(a.position, b.position, t, out); + } + const dt = Cesium.Math.clamp( + Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time), + regime.minDt, + regime.maxDt, + ); + return _extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps); + } + + /** + * Which motion a contact's history gives at `renderTime` — the one choice + * `_deadReckon` (CPU) and the icon planner (GPU segment) both draw from. + * + * - `between`: interpolate the bracketing pair `a`→`b`, no extrapolation + * error and no snap-back. The course of the DISPLAYED motion blends the + * time-interpolated reported track toward the chord by `blend`: the chord + * is only trustworthy when the segment covers real ground (at hover its + * direction is GPS jitter; on a slow tight turn it STEPS the whole + * per-segment turn at each boundary), and helicopters never use it + * (rotorcraft chords are noise-dominated at their typical speeds). + * - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt]. + * Warm-up (renderTime predates ALL history: freshly seen or just tracked, + * before RENDER_DELAY_SEC of history exists) runs the OLDEST fix BACKWARD, + * preserving the 30s-behind invariant, so as history fills the icon glides + * FORWARD into interpolation with no freeze and no backward snap (holding + * the oldest fix froze the icon; extrapolating the newest to wall-clock + * made it jump back a poll interval when interpolation took over). + * Otherwise the newest fix coasts. OpenSky can still be receiving fresh + * contact messages for that aircraft; freezing 60 s after the position + * produced a stop → catch-up → stop cadence, so it coasts through the latest + * real contact plus a bounded grace, with an absolute cap so a stale cached + * feed cannot drift forever. + * + * The returned object is a reused scratch: read it before the next call. + * @param {Array} history Non-empty, oldest first. + * @param {object|undefined} info The contact's record. + * @param {Cesium.JulianDate} renderTime + */ + function _motionRegime(history, info, renderTime) { for (let i = history.length - 1; i >= 1; i--) { const a = history[i - 1]; const b = history[i]; if ( - Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) && - Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) - ) { - const span = Cesium.JulianDate.secondsDifference(b.time, a.time); - const t = - span > 0 - ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span - : 1.0; - // Course of the DISPLAYED motion. The chord is only trustworthy when the - // segment covers real ground (at hover its direction is GPS jitter; on a - // slow tight turn it STEPS the whole per-segment turn at each boundary), - // so it is blended against the reported per-fix track by displayed - // ground speed — and the track is TIME-INTERPOLATED between the fixes so - // a slow turner's nose advances continuously through the segment instead - // of snapping once per poll. Helicopters always use the reported track - // (rotorcraft chords are noise-dominated at their typical speeds). - const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); - const segSpeed = - span > 0 ? chordLenM / span : (info && info.velocity) || 0; - const fallbackTrack = (info && info.true_track) || 0; - const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; - const trackTo = Number.isFinite(b.track) ? b.track : trackFrom; - const trackCourse = lerpAngleDeg(trackFrom, trackTo, t); - const w = info && info.klass === 'helicopter' ? 0 : speedRamp(segSpeed); - const chordCourse = - w > 0 ? courseBetweenCartesians(a.position, b.position) : null; - flightState._drCourseDeg = - chordCourse != null - ? lerpAngleDeg(trackCourse, chordCourse, w) - : trackCourse; - flightState._drSpeedMps = segSpeed; - flightState._drCourseHold = segSpeed < COURSE_HOLD_SPEED_MPS; - flightState._drExtrapolating = false; - return Cesium.Cartesian3.lerp(a.position, b.position, t, out); - } + !Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) || + !Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) + ) + continue; + const span = Cesium.JulianDate.secondsDifference(b.time, a.time); + const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); + const speed = span > 0 ? chordLenM / span : (info && info.velocity) || 0; + const fallbackTrack = (info && info.true_track) || 0; + const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; + const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed); + regime.kind = 'between'; + regime.a = a; + regime.b = b; + regime.span = span; + regime.speed = speed; + regime.trackFrom = trackFrom; + regime.trackTo = Number.isFinite(b.track) ? b.track : trackFrom; + regime.chordCourse = + blend > 0 ? courseBetweenCartesians(a.position, b.position) : null; + regime.blend = blend; + return regime; } - const newest = history[history.length - 1]; - const elapsedSec = Cesium.JulianDate.secondsDifference( - renderTime, - newest.time, - ); - if (elapsedSec <= 0) { - // Warm-up: renderTime predates ALL history (freshly seen / just-started-tracking - // aircraft, before RENDER_DELAY_SEC of history has accumulated, so no bracketing - // pair exists yet). Render at the DELAYED renderTime — preserving the 30s-behind - // invariant — by extrapolating the OLDEST fix BACKWARD to renderTime. As history - // fills, renderTime advances toward the first fix and the icon glides FORWARD into - // the bracketing interpolation above with NO freeze and NO backward snap. (Holding - // the oldest fix froze the icon; extrapolating the NEWEST fix to wall-clock now made - // the icon jump back ~one poll interval the instant interpolation took over.) - const oldest = history[0]; - const lookbackSec = Cesium.JulianDate.secondsDifference( - oldest.time, - renderTime, - ); // ≥ 0 - return _extrapolateFix( - oldest, - info, - -Math.min(lookbackSec, 60), - out, - (info && info.turnRateDps) || 0, - ); - } - - // Newest POSITION is older than renderTime. OpenSky can still be receiving - // fresh contact/kinematic messages for that aircraft; freezing at a hard - // 60 s-after-position boundary produced the visible stop → catch-up → stop - // cadence. Coast through the latest real contact plus a bounded grace - // window, with an absolute cap so a stale cached feed cannot drift forever. - const coastLimitSec = staleCoastLimitSeconds({ - // `epochMs` is captured once when the poll is normalized. Avoid allocating - // a Date per aircraft on every 12 Hz fleet tick. - fixEpochMs: Number.isFinite(newest.epochMs) - ? newest.epochMs - : Cesium.JulianDate.toDate(newest.time).getTime(), - lastContactEpochMs: info?.lastContactEpochMs, - // Permit one minute of contact grace but cap any cached-feed drift at - // five minutes. Source backoff is exposed separately as a STALE cue. - minimumSec: 60, - maximumSec: 300, - }); - return _extrapolateFix( - newest, - info, - Math.min(elapsedSec, coastLimitSec), - out, - (info && info.turnRateDps) || 0, - ); + const warming = Cesium.JulianDate.lessThan(renderTime, history[0].time); + regime.kind = 'fix'; + regime.fix = warming ? history[0] : newest; + regime.speed = fixSpeedMps(regime.fix, info); + regime.heading = fixTrackDeg(regime.fix, info); + regime.turnRateDps = (info && info.turnRateDps) || 0; + regime.minDt = -60; + // A warm-up ends when real time reaches the oldest fix; a single fix keeps + // coasting forward on the same arc. + regime.maxDt = + warming && history.length > 1 + ? 0 + : staleCoastLimitSeconds({ + // `epochMs` is captured once when the poll is normalized. Avoid + // allocating a Date per aircraft on every 12 Hz fleet tick. + fixEpochMs: Number.isFinite(newest.epochMs) + ? newest.epochMs + : Cesium.JulianDate.toDate(newest.time).getTime(), + lastContactEpochMs: info?.lastContactEpochMs, + // Permit one minute of contact grace but cap any cached-feed drift + // at five minutes. Source backoff is exposed separately as a STALE cue. + minimumSec: 60, + maximumSec: 300, + }); + return regime; } /** @@ -274,12 +315,8 @@ export function createMotion({ */ function _extrapolateFix(fix, info, dt, out, turnRateDps = 0) { - const speed = Number.isFinite(fix.velocity) - ? fix.velocity - : (info && info.velocity) || 0; - const heading = Number.isFinite(fix.track) - ? fix.track - : (info && info.true_track) || 0; + const speed = fixSpeedMps(fix, info); + const heading = fixTrackDeg(fix, info); flightState._drSpeedMps = speed; flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS; flightState._drExtrapolating = true; @@ -1114,6 +1151,7 @@ export function createMotion({ return { _refloorStaleGroundedContacts, _deadReckon, + _motionRegime, _extrapolateFix, _isTrackWarmingUp, _trackedFocusSizePx, diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs index 16c1a9cc6f..7b175bc413 100644 --- a/src/layers/flights/ownership.test.mjs +++ b/src/layers/flights/ownership.test.mjs @@ -59,7 +59,8 @@ test('flight state owns distinct mutable records, scratch objects and floor samp for (const key of [ 'records', 'feed', - '_billboards', + '_grounded', + '_floorPinned', '_positionHistory', '_displayFloorState', '_groundSnap', diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index 2ecb0a8a49..e951d6cf54 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -207,6 +207,14 @@ export const COURSE_MAX_DPS = 60; export const COURSE_SLEW_DT_MAX_SEC = 0.25; +/** Grounded contacts this close to the camera are floored every fleet tick. */ + +export const FLOOR_NEAR_M = 50_000; + +/** Farther grounded contacts are floored once per this many fleet ticks (~1 s). */ + +export const FLOOR_FAR_EVERY_TICKS = 12; + // --------------------------------------------------------------------------- // adsbdb enrichment (best-effort, fail-silent). Bounded fan-out: max 4 // concurrent requests, dispatches dripped ≥ENRICH_DISPATCH_GAP_MS apart diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index e8eb44e8db..23f64b0c15 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -16,7 +16,6 @@ import { FLEET_DR_INTERVAL_MS, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState } from '../../data/modelMirror.js'; export function createQueries({ @@ -99,7 +98,7 @@ export function createQueries({ * airframe itself and cannot go stale the way a leg can. * * This is a DISPLAY string only. Identity everywhere in this layer is `icao24` - * (the `_billboards`/`_flightData` key, the `sourceId` detection declutter hashes, + * (the `_icons`/`_flightData` key, the `sourceId` detection declutter hashes, * the `id` that trackById/Context cohorts resolve) — never the label. * @param {string} icao24 - ICAO 24-bit transponder address (the identity key). * @param {Object|null|undefined} info - `_flightData` record for this aircraft. @@ -134,10 +133,8 @@ export function createQueries({ // every visual consumer reads the floored per-frame cache instead (see // `_trackedDisplayPosition`). If that ever changes, floor this path too. const info = flightState.records.data.get(icao24); - const bb = flightState._billboards.get(icao24); const basePos = - parts.motion._deadReckon(icao24) || - (bb ? billboardState(bb).position : null); + parts.motion._deadReckon(icao24) || parts.icons._iconPosition(icao24); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -334,14 +331,8 @@ export function createQueries({ if (!flightState._models3dEnabled) { parts.rendering._releaseModels(); parts.tracking._syncTracked2dRotation(); - // Restore fleet billboards (the horizon-cull pass re-asserts next tick), but NEVER the - // tracked plane's own fleet billboard — its tracked entity is the visual, so re-showing it - // here would double-image the tracked plane when 3D is turned off mid-track. - if (flightState._billboardCollection) - for (const [icao, bb] of flightState._billboards) { - if (icao !== flightState._trackedIcao) - setBillboard(bb, 'show', true); - } + // (Releasing the models handed each fleet contact back to its icon, never + // the tracked plane's own — its tracked entity is the visual.) } } if ( @@ -424,42 +415,34 @@ export function createQueries({ * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>} */ getDetectableObjects(options = {}) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return []; - // Compute a stride that evenly samples the billboard map. + const icons = flightState._icons; + if (!icons || !icons.show) return []; + // Compute a stride that evenly samples the icon rows. // seed shifts the starting offset so successive calls can sample - // different aircraft without shuffling the underlying Map order. + // different aircraft without reordering the rows. const maxCount = Number.isFinite(options.maxCount) ? Math.max(1, Math.floor(options.maxCount)) - : flightState._billboards.size; + : icons.count; const seed = Number.isFinite(options.seed) ? Math.floor(options.seed) : 0; - const stride = Math.max( - 1, - Math.ceil(flightState._billboards.size / maxCount), - ); + const stride = Math.max(1, Math.ceil(icons.count / maxCount)); const start = seed % stride; + const occluder = parts.icons._occluder(); + const tau = parts.icons._displayTau(); const result = []; - let idx = 0; - for (const [icao24, bb] of flightState._billboards) { - const shouldTake = (idx - start) % stride === 0; - idx++; - if (!shouldTake) continue; + for (let row = start; row < icons.count; row += stride) { + const icao24 = icons.idAt(row); if ( flightState._cockpitContactMode && icao24.toLowerCase() === flightState._cockpitSubjectId ) continue; const isTracked = icao24 === flightState._trackedIcao; - // Keep planes rendered as a 3D model (billboard hidden) so the detection box - // doesn't vanish on the 2D→3D handoff; bb.position stays current while hidden. + // Keep planes rendered as a 3D model (icon hidden) so the detection box + // doesn't vanish on the 2D→3D handoff. const model = flightState._models.get(icao24) ?? null; const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24, model); - if (!isTracked && !billboardState(bb).show && !modelOwnsVisual) - continue; + if (!isTracked && !icons.shown(row) && !modelOwnsVisual) continue; const info = flightState.records.data.get(icao24); let object = flightState._detectionObjects.get(icao24); if (!object) { @@ -467,21 +450,24 @@ export function createQueries({ sourceId: icao24, type: 'AIR', _weldPos: new Cesium.Cartesian3(), + _iconPos: new Cesium.Cartesian3(), }; flightState._detectionObjects.set(icao24, object); } + // WELD: anchor to whatever actually owns the visual. A model-owned contact is // read straight off the translation the fleet tick already wrote into its // modelMatrix, so bracket and label sit on the aircraft you can see instead of - // on the buried billboard position, which for a grounded plane is ~100 m below + // on the buried icon position, which for a grounded plane is ~100 m below // and rises only as the coarse ground-floor cell warms. Zero extra sampling and - // no `_modelDisplayPosition` call from postRender. Sprite-owned contacts keep - // `bb.position` — sprite and bracket are co-located there, so association holds. + // no `_modelDisplayPosition` call from postRender. Icon-owned contacts keep + // the drawn icon position — icon and bracket are co-located there. const spec = modelOwnsVisual ? parts.rendering._modelSpec(info?.klass) : null; const pos = isTracked - ? parts.motion._trackedVisualCached() || billboardState(bb).position + ? parts.motion._trackedVisualCached() || + icons.position(row, tau, object._iconPos) : modelOwnsVisual ? modelVisualAnchor( modelState(model).modelMatrix, @@ -491,8 +477,15 @@ export function createQueries({ : spec.scale, object._weldPos || (object._weldPos = new Cesium.Cartesian3()), ) - : billboardState(bb).position; - if (!pos) continue; + : icons.position(row, tau, object._iconPos); + // An icon past the horizon is not drawn, so it is not detectable. + if ( + !pos || + (!isTracked && + !modelOwnsVisual && + !parts.icons._aboveHorizon(row, pos, occluder)) + ) + continue; object.position = pos; object.skipLabel = isTracked; // Card text only — declutter/cohort identity is `object.sourceId` (icao24). @@ -517,13 +510,9 @@ export function createQueries({ result.push(object); if (result.length >= maxCount) break; } - if ( - flightState._detectionObjects.size > - flightState._billboards.size + 512 - ) { + if (flightState._detectionObjects.size > icons.count + 512) { for (const icao24 of flightState._detectionObjects.keys()) { - if (!flightState._billboards.has(icao24)) - flightState._detectionObjects.delete(icao24); + if (!icons.has(icao24)) flightState._detectionObjects.delete(icao24); } } return result; @@ -583,12 +572,11 @@ export function createQueries({ * @returns {Array<{id: string, icao24: string, callsign: string|null, position: Cesium.Cartesian3, distance: number, aircraftClass: string|null, altitudeM: number|null, velocityMps: number|null, track: number|null}>} */ getNearby(center, range, maxCount = 50, { includeHidden = false } = {}) { - if ( - !center || - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return []; + const icons = flightState._icons; + if (!center || !icons || !icons.show) return []; + const occluder = parts.icons._occluder(); + const tau = parts.icons._displayTau(); + const scratch = flightState._scratchNearbyPos; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) @@ -598,28 +586,30 @@ export function createQueries({ const nearby = []; - for (const [icao24, bb] of flightState._billboards) { + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); const isTracked = icao24 === flightState._trackedIcao; - // Keep planes rendered as a 3D model (billboard hidden) so proximity counts - // don't drop to zero on the 2D→3D handoff; bb.position stays current while hidden. + const trackedPos = isTracked + ? parts.motion._trackedDisplayCached() + : null; // cached, no recompute (anti-jitter) + const drawn = trackedPos || icons.position(row, tau, 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: billboardState(bb).show, + billboardShown: + icons.shown(row) && + parts.icons._aboveHorizon(row, drawn, occluder), modelRendering: parts.rendering._modelOwnsVisual(icao24), includeHidden, }) ) continue; - const trackedPos = isTracked - ? parts.motion._trackedDisplayCached() - : null; // cached, no recompute (anti-jitter) - const pos = trackedPos || billboardState(bb).position; - if (!pos) continue; - - const distance = Cesium.Cartesian3.distance(center, pos); + const distance = Cesium.Cartesian3.distance(center, drawn); if (distance > maxRange) continue; + const pos = trackedPos || Cesium.Cartesian3.clone(drawn); const info = flightState.records.data.get(icao24); const callsign = info?.callsign?.trim() || null; @@ -651,8 +641,8 @@ export function createQueries({ /** * Return id/label/position for up to maxCount currently rendered aircraft. - * Cheap snapshot for voice-tool framing — billboard positions only, no - * dead reckoning and no cloning. + * 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: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>} */ @@ -671,34 +661,25 @@ export function createQueries({ * holds no data and therefore cannot answer. */ hasContact(icao24) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show || - flightState._billboards.size === 0 - ) - return null; + const icons = flightState._icons; + if (!icons || !icons.show || icons.count === 0) return null; if (!icao24) return false; const id = String(icao24).trim(); - return ( - flightState._billboards.has(id) || - flightState._billboards.has(id.toLowerCase()) - ); + return icons.has(id) || icons.has(id.toLowerCase()); }, getAllPositions(maxCount = 500) { - if ( - !flightState._billboardCollection || - flightState._billboards.size === 0 - ) - return []; + const icons = flightState._icons; + if (!icons || icons.count === 0) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) : 500; + const tau = parts.icons._displayTau(); const result = []; - for (const [icao24, bb] of flightState._billboards) { - const pos = billboardState(bb).position; - if (!pos) continue; + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); + const pos = icons.position(row, tau); const carto = Cesium.Cartographic.fromCartesian( pos, Cesium.Ellipsoid.WGS84, @@ -741,11 +722,7 @@ export function createQueries({ * @returns {Array} See mapAnalystRecord for the record shape. */ getAnalystRecords(maxCount = 2000) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show || - flightState.records.data.size === 0 - ) + if (!flightState._icons?.show || flightState.records.data.size === 0) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) @@ -773,8 +750,8 @@ export function createQueries({ trackById(icao24, { origin = 'programmatic' } = {}) { if (!icao24) return false; let id = String(icao24).trim(); - if (!flightState._billboards.has(id)) id = id.toLowerCase(); - if (!flightState._billboards.has(id)) return false; + 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) @@ -844,7 +821,7 @@ export function createQueries({ ) return false; let id = String(icao24).trim(); - if (!flightState._billboards.has(id)) id = id.toLowerCase(); + if (!flightState._icons?.has(id)) id = id.toLowerCase(); if ( id !== flightState._trackedIcao || !flightState._viewer.entities?.contains?.(flightState._trackedEntity) || diff --git a/src/layers/flights/queries.test.mjs b/src/layers/flights/queries.test.mjs index 106bc0170a..a2d1fff19d 100644 --- a/src/layers/flights/queries.test.mjs +++ b/src/layers/flights/queries.test.mjs @@ -3,11 +3,9 @@ import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { createQueries } from './queries.js'; import { createRendering } from './rendering.js'; -import { - billboardState, - mirrorBillboard, - setBillboard, -} from '../../data/billboardMirror.js'; +import { createIcons } from './icons.js'; +import { createIconSet } from '../../data/iconSet.js'; +import { writeHoldSegment } from '../../data/iconSegment.js'; import { mirrorModel, setModel } from '../../data/modelMirror.js'; function fixture() { @@ -16,14 +14,11 @@ function fixture() { registration: ' N123 ', altitude: 1000, }; - const bb = mirrorBillboard({ - show: true, - position: new Cesium.Cartesian3(1, 2, 3), - }); + const icons = createIconSet(); const flightState = { feed: {}, - _billboardCollection: { show: true }, - _billboards: new Map([['abc123', bb]]), + _icons: icons, + _scratchIconRenderTime: new Cesium.JulianDate(), _models: new Map(), _detectionObjects: new Map(), records: { data: new Map([['abc123', info]]) }, @@ -48,8 +43,27 @@ function fixture() { motion: { _trackedVisualCached: () => null }, }; parts.rendering = createRendering({ flightState, services, parts }); + parts.icons = createIcons({ flightState, services, parts }); const queries = createQueries({ flightState, services, parts }).methods; - return { flightState, info, bb, parts, queries, formats: () => formats }; + const row = () => icons.row('abc123'); + /** Hold the contact's icon at `position`. */ + const place = (position) => { + writeHoldSegment(icons.segments, row(), position, 0); + icons.segmentWritten(row()); + }; + icons.add('abc123', { id: 'abc123' }); + place(new Cesium.Cartesian3(1, 2, 3)); + icons.setShown(row(), true); + return { + flightState, + info, + parts, + queries, + formats: () => formats, + place, + show: (shown) => icons.setShown(row(), shown), + drawn: () => parts.icons._iconPosition('abc123'), + }; } test('candidate text follows in-place enrichment without freezing identity or positions', () => { @@ -57,9 +71,9 @@ test('candidate text follows in-place enrichment without freezing identity or po const [first] = f.queries.getDetectableObjects(); assert.equal(first.id, 'TEST123'); assert.equal(first.sourceId, 'abc123'); - setBillboard(f.bb, 'position', new Cesium.Cartesian3(4, 5, 6)); + f.place(new Cesium.Cartesian3(4, 5, 6)); assert.equal(f.queries.getDetectableObjects()[0], first); - assert.equal(first.position, billboardState(f.bb).position); + assert.deepEqual(first.position, f.drawn()); assert.deepEqual(first.position, new Cesium.Cartesian3(4, 5, 6)); assert.equal(f.formats(), 1); f.info.callsign = ' NEW456 '; @@ -107,7 +121,7 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => scale: 1, }); f.flightState._models.set('abc123', model); - setBillboard(f.bb, 'show', false); + f.show(false); assert.deepEqual(f.queries.getDetectableObjects(), []); model.ready = true; assert.equal(f.queries.getDetectableObjects()[0], candidate); @@ -121,11 +135,8 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60)); setModel(model, 'show', false); assert.deepEqual(f.queries.getDetectableObjects(), []); - setBillboard(f.bb, 'show', true); - assert.equal( - f.queries.getDetectableObjects()[0].position, - billboardState(f.bb).position, - ); + f.show(true); + assert.deepEqual(f.queries.getDetectableObjects()[0].position, f.drawn()); assert.equal(get.mock.callCount(), 6); setModel(model, 'show', true); assert.equal(f.parts.rendering._modelOwnsVisual('abc123'), true); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index ecaa138765..c6adae37dd 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -1,22 +1,14 @@ import * as Cesium from 'cesium'; -import { cyberSonarBaseAlpha } from '../../cyberSonar.js'; import { selectModelEligible } from '../../data/modelEligibility.js'; import { civilAircraftModelSpec } from './modelSpec.js'; import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { isEmergency } from '../../data/aircraftEmergency.js'; -import { cockpitContactDotImage } from '../../data/cockpitContactDot.js'; -import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js'; -import { - cameraPoseSignature, - horizonOccluder, - screenProjectedRotation, -} from '../../data/iconOrientation.js'; -import { limitCourseStep, courseSlewCapDps } from '../../data/motionModel.js'; +import { horizonOccluder } from '../../data/iconOrientation.js'; +import { aircraftTreatmentAlpha } from '../../data/aircraftRecession.js'; import { MIL_TINT, EMERGENCY_TINT, GROUND_SCALE, - COCKPIT_CONTACT_SIZE_PX, COCKPIT_CIVILIAN_COLOR, MODEL_ALT_CEIL_M, MODEL_MAX_ALL, @@ -32,14 +24,9 @@ import { TRACKED_MODEL_MIN_PX, TRACKED_MODEL_MAX_PX, FLEET_DR_INTERVAL_MS, - RENDER_DELAY_SEC, - COURSE_SLEW_DT_MAX_SEC, - ROTATION_REFRESH_MS, - COURSE_MAX_DPS, } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState, setModel } from '../../data/modelMirror.js'; export function createRendering({ @@ -52,14 +39,8 @@ export function createRendering({ const { isMilitaryIcao } = services.militaryRegistry; const { tr3bIconKind, isTr3b } = services.aircraftPresentation; const { trackedModelScaleForPixelCap } = services.camera; - const { - focusNowMs, - getFocusTarget, - nearFarScalarValueAtDistance, - advanceProjectedSpriteFocus, - } = services.focus; - const { applyAircraftBillboardTreatment, applyAircraftModelTreatment } = - services.recession; + const { focusNowMs, getFocusTarget } = services.focus; + const { applyAircraftModelTreatment } = services.recession; /** True while this contact's latest poll broadcast an emergency code. */ @@ -98,22 +79,6 @@ export function createRendering({ ); } - /** Depth-test policy for aircraft billboards. Round 5 (owner directive - * 2026-07-06: "I just want the planes and their lines to ALWAYS be - * visible... evenly applied"): EVERY contact renders depth-test-free at - * every distance — grounded, low, and airborne alike. The photoreal mesh - * writes depth and residual baro/floor error will always leave some sprite - * geometry at or below it; a uniform rule beats the grounded-only / - * low-AGL-only conditions that kept leaving classes of contacts buried - * (2026-07-03 Van Nuys grounded case; 2026-07-06 Austin QNH-below-field - * case). Far-side planes are still removed by the fleet tick's horizon - * occluder, which never depended on depth. Kept as a function so the - * callers' restyle sites stay diff-stable. */ - - function _groundDepthDistance() { - return Number.POSITIVE_INFINITY; - } - function _modelSpec(klass) { const cached = flightState._specCache.get(klass); if (cached) return cached; @@ -141,53 +106,6 @@ export function createRendering({ const _iconKind = (icao24, klass) => tr3bIconKind(icao24, klass, { hot: flightState._irBoost }); - /** Apply the current normal/cockpit visual contract to one owned fleet billboard. */ - - function _applyFleetBillboardPresentation(icao24, bb) { - if (!bb) return; - const limbScale = flightState._billboardLimbScale.get(bb) ?? 1; - const isCockpitContact = - flightState._cockpitContactMode && icao24 !== flightState._trackedIcao; - const isCockpitNear = - isCockpitContact && flightState._cockpitNearContacts.has(icao24); - if (isCockpitContact && !isCockpitNear) { - const freshnessAlpha = cyberSonarBaseAlpha(bb); - bb.image = cockpitContactDotImage(); - setBillboard(bb, 'width', COCKPIT_CONTACT_SIZE_PX); - setBillboard(bb, 'height', COCKPIT_CONTACT_SIZE_PX); - setBillboard(bb, 'scale', limbScale); - setBillboard(bb, 'scaleByDistance', _cockpitBillboardScaleByDistance()); - bb.color = _cockpitContactColor(icao24).withAlpha(freshnessAlpha); - setBillboard(bb, 'rotation', 0); - return; - } - - const meta = flightState.records.data.get(icao24); - bb.image = aircraftIcon( - _iconKind(icao24, meta?.klass), - aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, - ); - setBillboard(bb, 'width', icao24 === flightState._trackedIcao ? 24 : 20); - setBillboard(bb, 'height', icao24 === flightState._trackedIcao ? 24 : 20); - setBillboard( - bb, - 'scale', - _fleetBillboardScale(icao24, meta?.klass) * limbScale, - ); - setBillboard(bb, 'scaleByDistance', _normalBillboardScaleByDistance()); - bb.color = _fleetBillboardColor(icao24).withAlpha(cyberSonarBaseAlpha(bb)); - } - - /** - * Per-preRender fleet pass at ~12Hz: dead-reckons every untracked billboard, - * horizon-culls billboards beyond the limb (no far-side depth with the globe - * hidden), and refreshes screen-projected icon rotations whenever the camera - * pose changed (plus a 1s drift catch-up while idle). Driven by - * scene.preRender — NOT camera.changed, whose granularity is globally - * degraded by other layers mutating camera.percentageChanged. - * @returns {void} - */ - /** Model tint, mirroring the billboard color rules. */ function _modelColor(icao24) { @@ -272,12 +190,12 @@ export function createRendering({ /** Everything scene.sampleHeight must NOT hit when snapping a grounded model: the * vertical pick ray at a plane's own lat/lon otherwise lands on its (or a parked * neighbor's) billboard/model instead of the tile skin. Cesium's ray-pick exclusion - * matches picked-object IDs, and every billboard AND model in this layer carries its + * matches picked-object IDs, and every icon AND model in this layer carries its * icao as `id`, so the icao strings cover both; the tracked entity is excluded as the * object itself. Built lazily — only when a sample actually fires (one-shot). */ function _groundSampleExclusions() { - const out = [...flightState._billboards.keys()]; + const out = parts.icons._iconIds(); if (flightState._trackedEntity) out.push(flightState._trackedEntity); return out; } @@ -323,15 +241,23 @@ export function createRendering({ ); } - /** Atomically hand one fleet contact from its billboard to a safely placed, + /** Atomically hand one fleet contact from its icon to a safely placed, * ready 3D model. Missing/loading models and unresolved terrain always leave - * the billboard owning the visual, so no render frame can hide both. + * the icon owning the visual, so no render frame can hide both. * `beforeShow` runs only on the committing path — the per-tick model treatment * belongs to a model that is about to draw, not to one still waiting. */ - function _driveFleetModelHandoff(icao24, model, bb, pos, course, beforeShow) { + function _driveFleetModelHandoff( + icao24, + model, + row, + pos, + course, + beforeShow, + ) { + const icons = flightState._icons; if (!model) { - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } const displayPos = _modelDisplayPosition( @@ -341,7 +267,7 @@ export function createRendering({ ); if (!displayPos) { setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip @@ -350,12 +276,12 @@ export function createRendering({ setModel(model, 'modelMatrix', _modelMatrix(displayPos, course)); if (!model.ready) { setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } beforeShow?.(); if (!modelState(model).show) setModel(model, 'show', true); - if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders + icons.setShown(row, false); // hand off ONLY once the model renders return true; } @@ -443,9 +369,6 @@ export function createRendering({ (current && aircraftVisuals.read(current)?.specKey !== key) || (!current && flightState._modelPending.has(icao24)) ) { - const bb = flightState._billboards.get(icao24); - if (bb && icao24 !== flightState._trackedIcao) - setBillboard(bb, 'show', true); _releaseModel(icao24); } if ( @@ -479,9 +402,6 @@ export function createRendering({ aircraftVisuals.read(model)?.irBoost === flightState._irBoost ) continue; // already right state - const bb = flightState._billboards.get(icao); - if (bb && icao !== flightState._trackedIcao) - setBillboard(bb, 'show', true); _releaseModel(icao); } if (flightState._irReloadQueue.length === 0) @@ -624,6 +544,7 @@ export function createRendering({ } } flightState._models.delete(icao24); + _showReleasedIcon(icao24); } // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so @@ -664,9 +585,20 @@ export function createRendering({ } } } + for (const icao24 of flightState._models.keys()) _showReleasedIcon(icao24); flightState._models.clear(); } + /** A released fleet model hands the visual straight back to its icon (the + * tracked contact's entity keeps its own). */ + + function _showReleasedIcon(icao24) { + const icons = flightState._icons; + const row = icons?.row(icao24) ?? -1; + if (row >= 0 && icao24 !== flightState._trackedIcao) + icons.setShown(row, true); + } + /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ function _releaseTrackedModel() { @@ -709,8 +641,7 @@ export function createRendering({ // readout consumers then reuse that exact cached position. const pos = parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - billboardState(flightState._billboards.get(flightState._trackedIcao)) - ?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (!pos) { if (flightState._trackedModel) setModel(flightState._trackedModel, 'show', false); @@ -789,9 +720,7 @@ export function createRendering({ // default here produces a one-frame jump to the Earth's center. const currentPos = parts.motion._trackedDisplayCached() || - billboardState( - flightState._billboards.get(flightState._trackedIcao), - )?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (currentPos) { const displayPos = _modelDisplayPosition( flightState._trackedIcao, @@ -859,54 +788,40 @@ export function createRendering({ } } + /** + * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and + * the two-tier glyph swap all run on the GPU from each row's segment, so this + * only re-plans rows whose regime ended, pins grounded contacts to the floor + * under them, advances focus de-emphasis while a target exists, and drives + * the 3D-model handoff inside the model regime. Driven by scene.preRender. + * @returns {void} + */ + function _fleetTick() { - if ( - !flightState._viewer || - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return; + const icons = flightState._icons; + if (!flightState._viewer || !icons || !icons.show) return; const scene = flightState._viewer.scene; const camera = flightState._viewer.camera; const nowMs = focusNowMs(Date.now()); - // (The tracked trail head is now the per-frame _trailHeadEntity segment — no 1 Hz - // primitive rebuild needed here anymore.) - if (nowMs - flightState._lastFleetTickMs < FLEET_DR_INTERVAL_MS) return; - const tickDtSec = flightState._lastFleetTickMs - ? Math.min( - COURSE_SLEW_DT_MAX_SEC, - (nowMs - flightState._lastFleetTickMs) / 1000, - ) - : 0.08; flightState._lastFleetTickMs = nowMs; // Every contact in this pass shares the same delayed display instant. - const renderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(flightState._scratchFleetRenderTime), - -RENDER_DELAY_SEC, + const renderTime = parts.icons._displayTime( flightState._scratchFleetRenderTime, ); + const tau = icons.seconds(renderTime); _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload if (flightState._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); - const poseSig = cameraPoseSignature(camera); - // Only the nearby Cockpit silhouettes need projected course; far dots are - // rotation-free. The per-contact gate below keeps the pip path cheap. - const doRotations = - poseSig !== flightState._lastCamPoseSig || - nowMs - flightState._lastRotPassMs >= ROTATION_REFRESH_MS; - if (doRotations) { - flightState._lastCamPoseSig = poseSig; - flightState._lastRotPassMs = nowMs; - } - - const occluder = horizonOccluder(camera); + parts.icons._replanExpired(tau); + parts.icons._floorGroundedIcons(renderTime, tau, nowMs, camera.positionWC); const focusTarget = getFocusTarget(); + parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget); // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. - // Drop all models the moment we leave it (toggled off / zoomed out) so billboards resume. + // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. const useModels = _modelRegimeActive(); // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that // resolves after zoom-out could briefly add a model outside the 3D-model regime). @@ -915,6 +830,7 @@ export function createRendering({ (flightState._models.size || flightState._modelPending.size) ) _releaseModels(); + if (!useModels) return; // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen @@ -925,273 +841,124 @@ export function createRendering({ // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum // filtering dropped near off-screen planes entirely. This does both right. - let modelEligible = null; - if (useModels) { - const cap = _modelCap(); - const camPos = camera.positionWC; - const addM = _modelAddDistM(); - const addDistSq = addM * addM; - const keepM = _modelKeepDistM(); - const keepDistSq = keepM * keepM; - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, + const cap = _modelCap(); + const camPos = camera.positionWC; + const addM = _modelAddDistM(); + const addDistSq = addM * addM; + const keepM = _modelKeepDistM(); + const keepDistSq = keepM * keepM; + const cull = camera.frustum.computeCullingVolume( + camPos, + camera.directionWC, + camera.upWC, + ); + // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. + const cand = []; + for (let row = 0; row < icons.count; row++) { + const icao = icons.idAt(row); + if (icao === flightState._trackedIcao) continue; + // A converted TR-3B renders as an icon and can never take a model, so + // it must not occupy a CAP SLOT either — excluded here at selection time, + // not just at the handoff below, or accumulated conversions would starve + // ordinary contacts of 3D models. (The handoff guard stays as defence.) + if (isTr3b(icao)) continue; + // Ground planes compete for model slots like everyone else (owner decision + // 2026-07-03: "3D mode is respected regardless of whether a plane is on the + // ground or in the air — no distinction"). The cap + nearest-first ordering + // below already bound airport clusters; grounded placement is handled by the + // one-shot ground snap in _modelDisplayPosition. + const position = icons.position( + row, + tau, + flightState._scratchModelBS.center, ); - // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. - const cand = []; - for (const [icao, bb] of flightState._billboards) { - if (icao === flightState._trackedIcao) continue; - // A converted TR-3B renders as a billboard and can never take a model, so - // it must not occupy a CAP SLOT either — excluded here at selection time, - // not just at the handoff below, or accumulated conversions would starve - // ordinary contacts of 3D models. (The handoff guard stays as defence.) - if (isTr3b(icao)) continue; - // Ground planes compete for model slots like everyone else (owner decision - // 2026-07-03: "3D mode is respected regardless of whether a plane is on the - // ground or in the air — no distinction"). The cap + nearest-first ordering - // below already bound airport clusters; grounded placement is handled by the - // one-shot ground snap in _modelDisplayPosition. - const { position } = billboardState(bb); - const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); - if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible - Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); - cand.push([ - icao, - d2, - cull.computeVisibility(flightState._scratchModelBS) !== - Cesium.Intersect.OUTSIDE, - ]); - } - cand.sort((a, b) => a[1] - b[1]); // nearest first - if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { - console.warn( - `[Data:Flights] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`, - ); - flightState._lastModelCapWarnMs = nowMs; - } - modelEligible = selectModelEligible(cand, { - cap, - addDistSq, - isModeled: (icao) => flightState._models.has(icao), - }); - const toRelease = []; - for (const icao of flightState._models.keys()) { - if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) - toRelease.push(icao); - } - for (const icao of toRelease) _releaseModel(icao); + const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); + if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible + cand.push([ + icao, + d2, + cull.computeVisibility(flightState._scratchModelBS) !== + Cesium.Intersect.OUTSIDE, + ]); } - - for (const [icao24, bb] of flightState._billboards) { - if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion - const icon = billboardState(bb); - - const info = flightState.records.data.get(icao24); - - const dr = parts.motion._deadReckon( - icao24, - flightState._scratchFleetPos, - renderTime, + cand.sort((a, b) => a[1] - b[1]); // nearest first + if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { + console.warn( + `[Data:Flights] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`, ); - // The dead-reckoned point drifts away from the fix whose cell supplied the - // height, so a grounded contact's sprite ends up under the mesh it taxied - // (or coasted) over. Re-floor at the DISPLAYED coordinate — read-only, and - // never while a 3D model owns the visual (T7). - const display = parts.motion._floorGroundedDisplayPosition( - icao24, - info, - dr, - _modelOwnsVisual(icao24), - nowMs, - ); - // Gate the write — assigning Billboard.position dirties the whole - // collection's vertex buffer, so skip sub-meter moves. - if ( - display && - Cesium.Cartesian3.distanceSquared(display, icon.position) > 1.0 - ) { - setBillboard(bb, 'position', display); - } + flightState._lastModelCapWarnMs = nowMs; + } + const modelEligible = selectModelEligible(cand, { + cap, + addDistSq, + isModeled: (icao) => flightState._models.has(icao), + }); + const toRelease = []; + for (const icao of flightState._models.keys()) { + if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) + toRelease.push(icao); + } + for (const icao of toRelease) _releaseModel(icao); - // Round 6: occlusion-test a LIFTED point for contacts rendering below - // (or within a wingspan of) the ellipsoid — EllipsoidalOccluder judges a - // sub-ellipsoid point near the limb "beyond the horizon" and the fleet - // pass would hide a plane that is really just low over high-N terrain - // waiting for its floor to warm (ATL grounded contacts at geoid −31 m). - const beyondHorizon = !occluder.isPointVisible( - flightState._cullPositions.get(icao24) || icon.position, - ); - // A billboard flipping INTO view (horizon reveal while the camera idles) - // gets its rotation refreshed THIS tick even without a pose change — - // otherwise it reappears wearing its stale (often creation-north) nose for - // up to ROTATION_REFRESH_MS. (Model-handed-off planes also read show=false - // here; harmless — the model branch below `continue`s past the rotation.) - const revealed = !beyondHorizon && !icon.show; - if (icon.show === beyondHorizon) setBillboard(bb, 'show', !beyondHorizon); - if (beyondHorizon) { - // Also hide any 3D model — otherwise a model that crossed the limb would keep - // rendering through the hidden globe at its last matrix. + // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown + // until the model is actually READY to render, so a plane is never both iconless AND + // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick + // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on + // purpose: the Easter egg IS the triangle, and there is no GLB for it. + const occluder = horizonOccluder(camera); + for (const icao24 of modelEligible) { + if (isTr3b(icao24)) continue; + const row = icons.row(icao24); + if (row < 0) continue; + const position = icons.position(row, tau, flightState._scratchFleetPos); + if (!parts.icons._aboveHorizon(row, position, occluder)) { + // A model that crossed the limb would keep rendering through the + // hidden globe at its last matrix; the icon's own cull is on the GPU. const m = flightState._models.get(icao24); if (m && modelState(m)?.show) setModel(m, 'show', false); continue; } - - // One order-independent write site composes freshness × focus × limb haze - // for alpha, and base class/ground scale × limb taper for scale. Cesium's - // locked NearFarScalar remains a separate multiplicative stage. This - // narrowly amends always-visible rendering without count culling or zero - // alpha; nearer focus behavior remains tunable rather than universal. - const cameraDistanceM = Cesium.Cartesian3.distance( - camera.positionWC, - icon.position, + _ensureModel(icao24); + const model = flightState._models.get(icao24); + const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); + _driveFleetModelHandoff( + icao24, + model, + row, + position, + icons.course(row, tau), + () => { + applyAircraftModelTreatment({ + model, + // IR boost must survive the per-tick treatment write — otherwise + // any alpha change would repaint the ordinary tint over the hot + // white. Boosted models also skip the recession fade: hot targets + // stay full-strength at any range (icons keep their normal + // fade — full-opacity glyph walls read as overwhelming). + baseColor: flightState._irBoost + ? Cesium.Color.WHITE + : _modelColor(icao24), + alpha: flightState._irBoost + ? 1 + : aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(row), + focusFactor: icons.focus(row), + cameraDistanceM, + cameraHeightM: camera.positionCartographic?.height, + }), + }); + }, ); - const distanceScale = nearFarScalarValueAtDistance( - icon.scaleByDistance, - cameraDistanceM, - ); - const focus = advanceProjectedSpriteFocus( - bb, - icon.position, - scene, - camera, - nowMs, - focusTarget, - undefined, - (icon.width || 20) * (icon.scale || 1) * distanceScale * 0.5, - (icon.height || 20) * (icon.scale || 1) * distanceScale * 0.5, - ); - const isCockpitNear = - flightState._cockpitContactMode && - flightState._cockpitNearContacts.has(icao24); - const layerBaseColor = - flightState._cockpitContactMode && !isCockpitNear - ? _cockpitContactColor(icao24, info) - : _fleetBillboardColor(icao24, info); - const baseColor = layerBaseColor; - const treatment = applyAircraftBillboardTreatment({ - billboard: bb, - baseScale: - flightState._cockpitContactMode && !isCockpitNear - ? 1 - : _fleetBillboardScale(icao24, info?.klass), - baseAlpha: flightState.records.missingPolls.get(icao24) ? 0.45 : 1, - baseColor, - focusFactor: focus.factor, - cameraDistanceM, - cameraHeightM: camera.positionCartographic?.height, - }); - flightState._billboardLimbScale.set(bb, treatment.factors.scale); - // Two-tier glyph raster (owner playtest 2026-08-16): the billboard atlas - // has no mipmaps, so no single texture stays crisp across the ~25–150 - // device-px range scaleByDistance produces. Swap between the 64 px fleet - // raster and the 192 px close raster on the billboard's ACTUAL on-screen - // size — post-treatment bb.scale, so focus/limb recession counts — with - // hysteresis so zoom oscillation never thrashes the atlas. - if (!flightState._cockpitContactMode || isCockpitNear) { - const glyphDevPx = - (icon.width || 20) * - (icon.scale || 1) * - distanceScale * - (globalThis.devicePixelRatio || 1); - const visual = aircraftVisuals.write(bb); - const wantLarge = visual.iconLarge ? glyphDevPx > 56 : glyphDevPx > 76; - if (wantLarge !== !!visual.iconLarge) { - visual.iconLarge = wantLarge; - bb.image = aircraftIcon( - _iconKind(icao24, info?.klass), - wantLarge ? TRACKED_ICON_PX : undefined, - ); - } - } - - // Smoothed display course: the path direction _deadReckon just reported - // for THIS aircraft (nothing else calls _deadReckon in between), rate- - // limited so segment-boundary course steps glide instead of snapping. - // The slew cap eases toward COURSE_MIN_DPS at low speed, and a hovering - // aircraft (hold flag) keeps its previous nose direction outright. - const rawCourse = - flightState._drCourseDeg != null - ? flightState._drCourseDeg - : (info && info.true_track) || 0; - const prevCourse = flightState._displayCourse.get(icao24); - const course = - flightState._drCourseHold && prevCourse != null - ? prevCourse - : limitCourseStep( - prevCourse, - rawCourse, - courseSlewCapDps( - flightState._drSpeedMps != null - ? flightState._drSpeedMps - : ((info && info.velocity) ?? NaN), - COURSE_MAX_DPS, - ), - tickDtSec, - ); - flightState._displayCourse.set(icao24, course); - - // 3D model takes over from the billboard for in-view planes (modelEligible). GAP-PROOF: the - // billboard stays shown until the model is actually READY to render, so a plane is never both - // iconless AND modelless (the "planes vanish when 3D turns on" bug). Position the model every - // tick regardless so it's framed the instant it becomes ready. - // Converted TR-3Bs stay 2D on purpose: the Easter egg IS the triangle, and - // there is no GLB for it, so the model handoff is suppressed rather than - // fed a stand-in mesh. The billboard keeps rendering (and keeps satisfying - // the getNearby/getDetectableObjects `bb.show` visibility guards), so a - // converted contact still works in Contacts and Cockpit. - if (useModels && dr && modelEligible.has(icao24) && !isTr3b(icao24)) { - _ensureModel(icao24); - const model = flightState._models.get(icao24); - const ownsVisual = _driveFleetModelHandoff( - icao24, - model, - bb, - dr, - course, - () => { - applyAircraftModelTreatment({ - model, - // IR boost must survive the per-tick treatment write — otherwise - // any alpha change would repaint the ordinary tint over the hot - // white. Boosted models also skip the recession fade: hot targets - // stay full-strength at any range (billboards keep their normal - // fade — full-opacity glyph walls read as overwhelming). - baseColor: flightState._irBoost - ? Cesium.Color.WHITE - : _modelColor(icao24), - alpha: flightState._irBoost ? 1 : treatment.alpha, - }); - }, - ); - if (ownsVisual) continue; // skip billboard rotation - } - - if ( - (!flightState._cockpitContactMode || isCockpitNear) && - (doRotations || revealed) - ) { - const rot = screenProjectedRotation( - scene, - icon.position, - course, - icon.rotation, - ); - if (rot !== null && Math.abs(rot - icon.rotation) > 0.002) { - setBillboard(bb, 'rotation', rot); - } - } } } return { _fleetBillboardColor, _fleetBillboardScale, - _groundDepthDistance, + _cockpitContactColor, _modelSpec, _normalBillboardScaleByDistance, _cockpitBillboardScaleByDistance, _iconKind, - _applyFleetBillboardPresentation, _modelColor, _modelRegimeActive, _modelCap, diff --git a/src/layers/flights/snapshotRenderer.js b/src/layers/flights/snapshotRenderer.js index 2fa013a487..ddc8c864a8 100644 --- a/src/layers/flights/snapshotRenderer.js +++ b/src/layers/flights/snapshotRenderer.js @@ -1,13 +1,10 @@ import * as Cesium from 'cesium'; -import { cyberSonarBaseAlpha } from '../../cyberSonar.js'; import { turnRateFromFixHistory, liftRepeatedGroundFix, synthesizeForwardKinematicsFix, } from '../../data/motionModel.js'; -import { aircraftIcon } from '../../data/aircraftIcons.js'; import { POSITION_HISTORY_LIMIT } from './recordPolicy.js'; -import { addBillboard } from '../../data/billboardMirror.js'; /** Apply reconciled aircraft records to Cesium resources and follow state. */ export function createFlightSnapshotRenderer({ @@ -19,6 +16,7 @@ export function createFlightSnapshotRenderer({ rendering, tracking, motion, + icons, enrichment, queries, }) { @@ -53,17 +51,8 @@ export function createFlightSnapshotRenderer({ // which hands off on untrack). const isMil = isMilitaryIcao(icao24); if (isMil && tracking._militaryLayerSuppresses(icao24)) { - const dupe = flightState._billboards.get(icao24); - if (dupe) { - flightState._billboardCollection.remove(dupe); - flightState._billboards.delete(icao24); - rendering._releaseModel(icao24); // military-suppression: drop any 3D model too - records.forget(icao24); - flightState._cullPositions.delete(icao24); - flightState._positionHistory.delete(icao24); - flightState._displayCourse.delete(icao24); - flightState._groundSnap.forget(icao24); - } + // Military-suppression: drop the duplicate with any 3D model too. + if (flightState._icons.has(icao24)) icons._forgetContact(icao24); continue; } @@ -84,12 +73,12 @@ export function createFlightSnapshotRenderer({ ); // Either flip retires the previous one-shot ground sample. if (groundFlipped) flightState._groundSnap.forget(icao24); - flightState._cullPositions.set( - icao24, - meta.renderAltitudeM < 10 - ? Cesium.Cartesian3.fromDegrees(meta.rawLon, meta.rawLat, 12) - : null, - ); + if (meta.onGround) { + flightState._grounded.add(icao24); + } else if (flightState._grounded.delete(icao24)) { + flightState._floorPinned.delete(icao24); + motion._retireDisplayFloorState(icao24, Date.now()); + } const isTracked = icao24 === flightState._trackedIcao; // Append to position history stamped with the FEED's fix epoch @@ -153,72 +142,18 @@ export function createFlightSnapshotRenderer({ } } - if (flightState._billboards.has(icao24)) { - const bb = flightState._billboards.get(icao24); - // Reclassify if the category resolved/changed (first extended poll); - // a ground flip (landing/takeoff) re-scales the SAME billboard in - // place — the transition is a restyle, never a removal. - // Round 5: depth policy is uniform (always depth-test-free, see - // _groundDepthDistance) — nothing to flip on landing/takeoff. - // Position AND rotation are owned by the fleet pass (_fleetTick); - // course changes land on the next rotation pass (forced below). - if (!isTracked) { - // Refresh affiliation hue without clobbering the tick-owned - // freshness × focus × horizon alpha composition. - bb.color = rendering - ._fleetBillboardColor(icao24) - .withAlpha(cyberSonarBaseAlpha(bb)); - } - if ( - prevMeta?.klass !== meta.klass || - groundFlipped || - flightState._cockpitContactMode - ) { - rendering._applyFleetBillboardPresentation(icao24, bb); - } + if (flightState._icons.has(icao24)) { + // Reclassification, a ground flip (a restyle, never a removal), a + // freshness change and the cockpit contract all land on the row's + // style; motion re-plans from the updated history. + icons._applyIconPresentation(icao24); + icons._planIcon(icao24); // Poll-path class change (category updates): same model resync rule // as the enrichment path — the class's GLB/scale may have changed. if (prevMeta?.klass !== meta.klass) rendering._syncModelToClass(icao24); } else { - // Start where the fleet pass will draw it: the fleet renders behind - // real time, so a fresh contact's displayed position is its fix - // projected back to that delayed time, and a grounded contact is then - // lifted onto the floor under that delayed position. Creating it at - // the raw fix drew it ahead until the next fleet tick snapped it back; - // skipping the floor started a taxiing contact low and then raised it. - const delayed = motion._deadReckon(icao24, new Cesium.Cartesian3()); - const displayed = - (delayed && - motion._floorGroundedDisplayPosition( - icao24, - flightState.records.data.get(icao24) || meta, - delayed, - rendering._modelOwnsVisual(icao24), - )) || - position; - const bb = addBillboard(flightState._billboardCollection, { - position: displayed, - image: aircraftIcon(rendering._iconKind(icao24, meta.klass)), - width: isTracked ? 24 : 20, - height: isTracked ? 24 : 20, - scale: rendering._fleetBillboardScale(icao24, meta.klass), - // Screen-projected rotation lands on the next fleet tick. - rotation: 0, - alignedAxis: Cesium.Cartesian3.ZERO, - color: isTracked - ? Cesium.Color.CYAN - : rendering._fleetBillboardColor(icao24), - sizeInMeters: false, - scaleByDistance: rendering._normalBillboardScaleByDistance(), - // Grounded/near-surface planes sit at/below the photoreal tile - // surface — render them depth-test-free so they never vanish up - // close (_groundDepthDistance). - disableDepthTestDistance: rendering._groundDepthDistance(), - id: icao24, - show: !isTracked, // hidden if currently tracked (entity replaces it) - }); - flightState._billboards.set(icao24, bb); - rendering._applyFleetBillboardPresentation(icao24, bb); + // Hidden while tracked: the tracked entity replaces it. + icons._addIcon(icao24); } // Takeoff while TRACKED: ground traffic drew no trail, so start one @@ -240,8 +175,12 @@ export function createFlightSnapshotRenderer({ // EXCEPTION: likely-landed planes (last fix low + slow) get only // LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a // feed gap, and the full grace left phantom planes parked at airports. - for (const [icao24, bb] of flightState._billboards) { - if (currentIcaos.has(icao24)) continue; + const absentIds = []; + for (let row = 0; row < flightState._icons.count; row++) { + const icao24 = flightState._icons.idAt(row); + if (!currentIcaos.has(icao24)) absentIds.push(icao24); + } + for (const icao24 of absentIds) { const absence = records.absence(icao24, { complete: snapshot.complete, retainIds: snapshot.retainIds, @@ -249,8 +188,9 @@ export function createFlightSnapshotRenderer({ }); if (absence === 'retain') continue; if (absence === 'stale') { + icons._applyIconPresentation(icao24); // the faded freshness alpha if (icao24 === flightState._trackedIcao && flightState._trackedEntity) { - // Honest readout: the tracked plane has no faded billboard (its + // Honest readout: the tracked plane has no faded icon (its // entity owns the visual), so refresh the label — with icao24 now // in _missingPolls, _trackedLabelText appends the STALE cue so // last-known velocity/altitude aren't presented as live. @@ -269,20 +209,9 @@ export function createFlightSnapshotRenderer({ tracking._clearTracking(false, { evicted: true }); } - flightState._billboardCollection.remove(bb); - flightState._billboards.delete(icao24); - rendering._releaseModel(icao24); // aged-out aircraft: drop its 3D model (no orphan / cap leak) - records.forget(icao24); - flightState._cullPositions.delete(icao24); - flightState._positionHistory.delete(icao24); - flightState._displayCourse.delete(icao24); - flightState._groundSnap.forget(icao24); - flightState._displayFloorState.delete(icao24); + icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak) } - // Fresh courses arrived — force a rotation pass on the next fleet tick - flightState._lastCamPoseSig = ''; - // Ambient type enrichment: give ON-SCREEN planes real types (bounded // sweep — see _sweepAmbientEnrichment; internally fail-silent). enrichment._sweepAmbientEnrichment(); @@ -307,7 +236,7 @@ export function createFlightSnapshotRenderer({ // aircraft instead of the pavement. sampleMeshFloorCells(flightState._viewer?.scene, floorWarmPoints, { excludeObjects: [ - ...flightState._billboards.values(), + ...icons._iconIds(), ...flightState._models.values(), flightState._trackedModel, ].filter(Boolean), @@ -327,6 +256,6 @@ export function createFlightSnapshotRenderer({ // in place is safe (the DR extrapolates a zero-velocity fix). motion._refloorStaleGroundedContacts(currentIcaos); - return { count: flightState._billboards.size, ids: acceptedSnapshotIcaos }; + return { count: flightState._icons.count, ids: acceptedSnapshotIcaos }; }; } diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index b297d5a9d5..b3ac6ab0d6 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -11,7 +11,6 @@ export function createFlightState({ source, services }) { ...services.geoid, ...services.groundFloor, }); - flightState._cullPositions = new Map(); /** Per-class model spec. Hangar-fleet classes (CLASS_MODEL_REAL) ship GLBs * vertex-baked to real-world METERS in the airplane.glb axis convention, so @@ -91,22 +90,37 @@ export function createFlightState({ source, services }) { 1.0, ); // frustum-visibility test - /** Last limb taper per billboard, retained across class/ground/cockpit repaints. */ - - flightState._billboardLimbScale = new WeakMap(); // keep last N positions per aircraft // --------------------------------------------------------------------------- // Module-level state: billboard collection and per-aircraft lookup maps // --------------------------------------------------------------------------- - /** @type {Cesium.BillboardCollection|null} */ + /** Every contact's icon row (see icons.js); null outside a layer lifetime. */ - flightState._billboardCollection = null; + flightState._icons = null; - /** @type {Map} icao24 -> billboard primitive */ + /** The primitive drawing `_icons`. */ - flightState._billboards = new Map(); + flightState._iconPrimitive = null; + + flightState._scratchIconRenderTime = new Cesium.JulianDate(); + + /** Contacts whose latest poll put them on the ground. */ + + flightState._grounded = new Set(); + + /** Grounded contacts the floor currently lifts; their rows hold CPU positions. */ + + flightState._floorPinned = new Set(); + + /** Fleet ticks since start; far grounded rows take their floor turn by it. */ + + flightState._floorTick = 0; + + /** Rows still away from full focus emphasis after the last focus pass. */ + + flightState._iconFocusActive = 0; /** Stable lightweight records reused by the detection overlay between polls. */ @@ -204,14 +218,6 @@ export function createFlightState({ source, services }) { flightState._lastFleetTickMs = 0; - /** @type {string} Camera pose signature at the last rotation pass */ - - flightState._lastCamPoseSig = ''; - - /** @type {number} Epoch ms of the last full rotation pass */ - - flightState._lastRotPassMs = 0; - /** @type {number} Last computed rotation for the tracked entity (radians) */ flightState._lastTrackedRotation = 0; @@ -250,6 +256,10 @@ export function createFlightState({ source, services }) { flightState._scratchFleetPos = new Cesium.Cartesian3(); + flightState._scratchCockpitPos = new Cesium.Cartesian3(); + + flightState._scratchNearbyPos = new Cesium.Cartesian3(); + flightState._scratchSonarScreen = new Cesium.Cartesian2(); flightState._scratchDrRaw = new Cesium.Cartesian3(); diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index 41fd19533c..b5df7a0764 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -1,7 +1,8 @@ import * as Cesium from 'cesium'; import { CYAN_TRANSPARENT } from './policy.js'; -import { mirrorBillboard } from '../../data/billboardMirror.js'; import { mirrorModel } from '../../data/modelMirror.js'; +import { createIconSet } from '../../data/iconSet.js'; +import { writeHoldSegment } from '../../data/iconSegment.js'; export function createTesting({ flightState, @@ -38,6 +39,19 @@ export function createTesting({ flightState._displayFloorState.clear(); } + /** Give a test contact an icon row held at `billboard.position`, shown as + * `billboard.show` says (hidden by default while tracked). */ + + function _seedIconForTest(icao24, billboard, tracked) { + const icons = flightState._icons; + const row = icons.add(icao24, { layer: 'flights', id: icao24 }); + if (billboard?.position) + writeHoldSegment(icons.segments, row, billboard.position, 0); + icons.segmentWritten(row); + icons.setShown(row, billboard?.show ?? !tracked); + return row; + } + /** * Seed only the mutable state needed to exercise tracked-card refreshes through * the production poll reconciler. Tests still call `flightsLayer.update()`; @@ -46,13 +60,14 @@ export function createTesting({ * @param {string} state.icao24 * @param {object} state.entity * @param {object} state.meta - * @param {object} state.billboard - * @param {object} state.billboardCollection + * @param {{position?: Cesium.Cartesian3, show?: boolean}} [state.billboard] + * Where the contact's icon is held, and whether it is shown. + * @param {{show?: boolean}} [state.billboardCollection] Layer visibility. * @param {object} state.viewer * @param {Array} [state.history=[]] * @param {boolean} [state.tracked=true] * @param {Iterable<[string, object]>} [state.models=[]] - Fleet 3D models keyed - * by icao24, for the billboard-hidden/model-shown handoff state. + * by icao24, for the icon-hidden/model-shown handoff state. */ function _setTrackedFlightRefreshStateForTest({ @@ -69,9 +84,13 @@ export function createTesting({ }) { flightState._viewer = viewer; flightState._modelCollection = modelCollection; - flightState._billboardCollection = billboardCollection; - flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); - flightState._cullPositions.clear(); + flightState._icons = createIconSet({ + epoch: parts.icons._displayTime(new Cesium.JulianDate()), + }); + flightState._icons.show = billboardCollection?.show ?? true; + flightState._grounded.clear(); + flightState._floorPinned.clear(); + _seedIconForTest(icao24, billboard, tracked); flightState._models.clear(); for (const [key, model] of models) flightState._models.set(key, mirrorModel(model)); @@ -120,7 +139,7 @@ export function createTesting({ billboard, history = [], }) { - flightState._billboards.set(icao24, mirrorBillboard(billboard)); + _seedIconForTest(icao24, billboard, false); flightState.records.data.set(icao24, meta); flightState._positionHistory.set(icao24, history); } @@ -181,25 +200,64 @@ export function createTesting({ : Cesium.Color.CYAN; } - /** Drive the exact fleet billboard-to-model handoff used by `_fleetTick`. */ + /** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */ function _driveFleetModelHandoffForTest({ icao24, position, course = 0 }) { return parts.rendering._driveFleetModelHandoff( icao24, flightState._models.get(icao24), - flightState._billboards.get(icao24), + flightState._icons.row(icao24), position, course, ); } + /** Where a contact's icon is drawn now and whether the layer shows it. */ + + function _iconForTest(icao24) { + const position = parts.icons._iconPosition(icao24); + return position + ? { + position, + shown: parts.icons._iconShown(icao24), + course: parts.icons._iconCourse(icao24), + } + : null; + } + /** Exercise the exact asynchronous fleet loader and return its admitted model. */ async function _ensureFleetModelForTest(icao24) { await parts.rendering._ensureModel(icao24); return flightState._models.get(icao24) || null; } + /** Show or hide a contact's icon as a handoff would, or hold it somewhere. */ + + function _setIconForTest(icao24, { shown, position } = {}) { + const icons = flightState._icons; + const row = icons?.row(icao24) ?? -1; + if (row < 0) return; + if (shown !== undefined) icons.setShown(row, shown); + if (position) { + writeHoldSegment(icons.segments, row, position, 0); + icons.segmentWritten(row); + } + } + + /** Run the fleet tick's grounded floor pass once, at `renderTime`. */ + + function _floorGroundedIconsForTest(renderTime, cameraPosition) { + const icons = flightState._icons; + parts.icons._floorGroundedIcons( + renderTime, + icons.seconds(renderTime), + Date.now(), + cameraPosition, + ); + } return { + _floorGroundedIconsForTest, + _setIconForTest, _floorGroundedDisplayPositionForTest, _clearDisplayFloorStateForTest, _setTrackedFlightRefreshStateForTest, @@ -214,6 +272,7 @@ export function createTesting({ _updateTrackedModelForTest, _trackedBillboardColorForTest, _driveFleetModelHandoffForTest, + _iconForTest, _ensureFleetModelForTest, }; } diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index d0d00cba06..60159be88b 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -27,7 +27,6 @@ import { } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createTracking({ flightState, @@ -65,9 +64,9 @@ export function createTracking({ } function _publishTrackedSelection(icao24, origin = 'programmatic') { - const bb = flightState._billboards.get(icao24); + const position = parts.icons._iconPosition(icao24); const info = flightState.records.data.get(icao24); - if (!billboardState(bb)?.position || !info) return false; + if (!position || !info) return false; if (flightState._trackedEntity) entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { @@ -78,7 +77,7 @@ export function createTracking({ // a callsign-less contact reached Context as its raw hex even once adsbdb // had supplied a registration. Identity below stays `icao24`. label: parts.queries._contactLabel(icao24, info), - position: Cesium.Cartesian3.clone(billboardState(bb).position), + position, origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(icao24)); @@ -163,9 +162,12 @@ export function createTracking({ } const previous = flightState._cockpitNearContacts; const distancesSquared = []; - for (const [icao24, bb] of flightState._billboards) { - const position = billboardState(bb)?.position; - if (icao24 === flightState._trackedIcao || !position) continue; + const icons = flightState._icons; + const tau = parts.icons._displayTau(); + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); + if (icao24 === flightState._trackedIcao) continue; + const position = icons.position(row, tau, flightState._scratchCockpitPos); distancesSquared.push([ icao24, Cesium.Cartesian3.distanceSquared( @@ -181,13 +183,10 @@ export function createTracking({ parts.rendering._modelKeepDistM(), ); flightState._cockpitNearContacts = next; - let presentationChanged = false; - for (const [icao24, bb] of flightState._billboards) { - if (previous.has(icao24) === next.has(icao24)) continue; - parts.rendering._applyFleetBillboardPresentation(icao24, bb); - presentationChanged = true; - } - if (presentationChanged) flightState._lastCamPoseSig = ''; + for (const icao24 of previous) + if (!next.has(icao24)) parts.icons._applyIconPresentation(icao24); + for (const icao24 of next) + if (!previous.has(icao24)) parts.icons._applyIconPresentation(icao24); } /** Switch all current and future ambient contacts between silhouettes and cockpit pips. */ @@ -205,9 +204,9 @@ export function createTracking({ if (flightState._modelCollection) flightState._modelCollection.show = true; flightState._trail?.setVisible(!next); if (flightState._trailHeadEntity) flightState._trailHeadEntity.show = !next; - for (const [icao24, bb] of flightState._billboards) - parts.rendering._applyFleetBillboardPresentation(icao24, bb); - flightState._lastCamPoseSig = ''; + const icons = flightState._icons; + for (let row = 0; row < (icons?.count ?? 0); row++) + parts.icons._applyIconPresentation(icons.idAt(row)); flightState._lastFleetTickMs = 0; } @@ -319,8 +318,7 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - billboardState(flightState._billboards.get(flightState._trackedIcao)) - ?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (!pos) return; const projected = screenProjectedRotation( flightState._viewer.scene, @@ -639,30 +637,9 @@ export function createTracking({ const clearedIcao = flightState._trackedIcao; clearFocusTarget('flights', clearedIcao); - // Restore the original billboard appearance. The rotation is re-seeded from - // the tracked entity's last rendered rotation and a rotation pass is forced - // (_lastCamPoseSig below): the fleet billboard otherwise reappears with the - // STALE screen rotation it had when tracking began — up to a full - // ROTATION_REFRESH_MS of a wrong (possibly reversed) nose on release. - if (flightState._billboards.has(flightState._trackedIcao)) { - const bb = flightState._billboards.get(flightState._trackedIcao); - setBillboard(bb, 'show', true); - setBillboard(bb, 'width', 20); - setBillboard(bb, 'height', 20); - // Ground/military-aware restore (a plane untracked while taxiing must come - // back muted-gray at ground scale, not white at full scale). - bb.color = parts.rendering._fleetBillboardColor(flightState._trackedIcao); - setBillboard( - bb, - 'scale', - parts.rendering._fleetBillboardScale( - flightState._trackedIcao, - flightState.records.data.get(flightState._trackedIcao)?.klass, - ), - ); - setBillboard(bb, 'rotation', flightState._lastTrackedRotation); - } - flightState._lastCamPoseSig = ''; // force a fleet rotation pass on the next tick + // The nose the icon continues from (the shared _displayCourse entry), so + // release never flips it. + const trackedCourseDeg = flightState._displayCourse.get(clearedIcao); // Stop tracking and remove the entity. skipViewerUntrack: when ANOTHER layer just grabbed the // follow-camera, we tear down our own state but must NOT clear viewer.trackedEntity (the new owner @@ -679,10 +656,14 @@ export function createTracking({ parts.rendering._releaseTrackedModel(); _resetTrackedSelectionState(); // the zoom band + load-failure budget belong to the selection we just dropped flightState._trackedIcao = null; - parts.rendering._applyFleetBillboardPresentation( - clearedIcao, - flightState._billboards.get(clearedIcao), - ); + // Hand the contact back to its icon only now: settling floors a grounded + // contact, and while it still read as tracked its tracked model owned the + // visual, so the floor would have stepped aside. + if (flightState._icons?.has(clearedIcao)) { + flightState._icons.setShown(flightState._icons.row(clearedIcao), true); + parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg }); + } + parts.icons._applyIconPresentation(clearedIcao); clearTrackedSubjectContext('flights'); _emitAwarenessEvent('gev:awareness-subject-cleared', { layerId: 'flights', @@ -730,10 +711,7 @@ export function createTracking({ pending.generation !== flightState._trackingIntentGeneration ) return false; - if ( - !flightState._billboardCollection?.show || - !flightState._billboards.has(pending.id) - ) + if (!flightState._icons?.show || !flightState._icons.has(pending.id)) return false; flightState._pendingTrackingRestore = null; _trackFlight(pending.id, { origin: pending.origin }); @@ -837,42 +815,42 @@ export function createTracking({ // an already-loaded model would otherwise linger with the billboard hidden. if (flightState._models.has(id) || flightState._modelPending.has(id)) parts.rendering._releaseModel(id); - const bb = flightState._billboards.get(id); - if (bb && id !== flightState._trackedIcao) setBillboard(bb, 'show', true); // horizon cull re-asserts next tick + const row = flightState._icons?.row(id) ?? -1; + if (row >= 0 && id !== flightState._trackedIcao) + flightState._icons.setShown(row, true); if (id === flightState._trackedIcao) { parts.rendering._releaseTrackedModel(); _syncTracked2dRotation(); } } - const bb = flightState._billboards.get(id); - if (bb) parts.rendering._applyFleetBillboardPresentation(id, bb); + parts.icons._applyIconPresentation(id); if (id === flightState._trackedIcao) { _syncTrackedBillboardImage(); _updateTrackedLabelModel(id); } flightState._viewer?.scene?.requestRender?.(); - return flightState._billboards.has(id) || id === flightState._trackedIcao; + return flightState._icons?.has(id) || id === flightState._trackedIcao; } /** Re-image every converted contact this layer owns (IR style flip). */ function _refreshTr3bForStyle() { for (const id of tr3bConvertedIds()) { - if (flightState._billboards.has(id) || id === flightState._trackedIcao) + if (flightState._icons?.has(id) || id === flightState._trackedIcao) _refreshTr3bContact(id); } } - /** Plausibility check anchored to the plane's billboard position (coarse is + /** Plausibility check anchored to the plane's icon position (coarse is * fine here — this gates a LABEL, and it must not touch the tracked frame * cache). Missing data → true (never hide what we can't judge). */ function _routeIsPlausible(icao24, route) { const info = flightState.records.data.get(icao24); - const bb = flightState._billboards.get(icao24); - if (!info || !bb || !billboardState(bb).position) return true; + const position = parts.icons._iconPosition(icao24); + if (!info || !position) return true; const carto = Cesium.Cartographic.fromCartesian( - billboardState(bb).position, + position, Cesium.Ellipsoid.WGS84, flightState._scratchCarto, ); @@ -907,29 +885,42 @@ export function createTracking({ function _trackFlight(icao24, { origin = 'programmatic' } = {}) { _clearTracking(false, { origin }); // switching planes — the new follow-camera takes over - const bb = flightState._billboards.get(icao24); + const icons = flightState._icons; + const row = icons?.row(icao24) ?? -1; const info = flightState.records.data.get(icao24); - if (!bb || !info) return; + if (row < 0 || !info) return; + // 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 tau = parts.icons._displayTau(); + const iconPosition = icons.position(row, tau); + flightState._displayCourse.set(icao24, icons.course(row, tau)); flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget flightState._cachedDRFrame = -1; - flightState._lastTrackedRotation = billboardState(bb).rotation || 0; + flightState._lastTrackedRotation = + screenProjectedRotation( + flightState._viewer.scene, + iconPosition, + icons.course(row, tau), + 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. parts.rendering._releaseModel(icao24); - // Hide the billboard — the tracked entity replaces it visually - setBillboard(bb, 'show', false); + // Hide the icon — the tracked entity replaces it visually + icons.setShown(row, false); // Helper: smoothed, per-frame-cached tracked position (see _trackedDisplayPosition — // one computation shared by the position/alignedAxis/rotation/trail-head callbacks, - // with discontinuity reconciliation). Falls back to the last billboard position when + // with discontinuity reconciliation). Falls back to the icon's position when // the aircraft has no fix. const getTrackedPosition = () => parts.motion._trackedDisplayPosition(icao24) || - billboardState(bb).position; + parts.icons._iconPosition(icao24) || + iconPosition; // Dead-reckoning position property — smooth continuous motion between API updates. const positionProperty = new Cesium.CallbackProperty(() => { @@ -1106,23 +1097,19 @@ export function createTracking({ */ function _onMilitaryActiveChange(active) { - if (!flightState._viewer || !flightState._billboardCollection) return; + const icons = flightState._icons; + if (!flightState._viewer || !icons) return; if (active) { - for (const [icao24, bb] of flightState._billboards) { - if (!isMilitaryIcao(icao24) || icao24 === flightState._trackedIcao) - continue; - flightState._billboardCollection.remove(bb); - flightState._billboards.delete(icao24); - parts.rendering._releaseModel(icao24); // military-suppression: drop any 3D model too - flightState.records.data.delete(icao24); - flightState._cullPositions.delete(icao24); - flightState._positionHistory.delete(icao24); - flightState._displayCourse.delete(icao24); - flightState._groundSnap.forget(icao24); - flightState.records.missingPolls.delete(icao24); + const suppressed = []; + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); + if (isMilitaryIcao(icao24) && icao24 !== flightState._trackedIcao) + suppressed.push(icao24); } - flightState.feed._count = flightState._billboards.size; - } else if (flightState._billboardCollection.show) { + // Military-suppression: drop each duplicate with any 3D model too. + for (const icao24 of suppressed) parts.icons._forgetContact(icao24); + flightState.feed._count = icons.count; + } else if (icons.show) { // Fire-and-forget refresh; only while the layer is actually enabled. void flightsLayer.update(flightState._viewer); } @@ -1212,25 +1199,12 @@ export function createTracking({ return; } - // For BillboardCollection picks, the billboard may be at picked.primitive or picked.id - const billboard = picked.primitive; - if ( - billboard && - billboard.id && - flightState._billboards.has(billboard.id) - ) { + // Icon picks carry the icao on picked.id; models carry it on the primitive. + const pickedIcao = + typeof picked.id === 'string' ? picked.id : picked.primitive?.id; + if (pickedIcao && flightState._icons?.has(pickedIcao)) { _cancelPendingTrackingRestore(); - _trackFlight(billboard.id, { origin: 'user' }); - return; - } - // Some CesiumJS versions surface the id as a string on picked.id instead - if ( - picked.id && - typeof picked.id === 'string' && - flightState._billboards.has(picked.id) - ) { - _cancelPendingTrackingRestore(); - _trackFlight(picked.id, { origin: 'user' }); + _trackFlight(pickedIcao, { origin: 'user' }); return; } } diff --git a/src/ui/cyberTheme.test.mjs b/src/ui/cyberTheme.test.mjs index 75746b6e32..605876f738 100644 --- a/src/ui/cyberTheme.test.mjs +++ b/src/ui/cyberTheme.test.mjs @@ -702,7 +702,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', () assert.doesNotMatch(detection, /sonarActive \? 1 : 0/); assert.match( civilRendering, - /alpha: flightState\._irBoost \? 1 : treatment\.alpha/, + /alpha: flightState\._irBoost\s*\?\s*1\s*:\s*aircraftTreatmentAlpha\(/, ); assert.match( militaryRendering, From b027bde6adccd8d2c42b6eaa9a569aa2c9ceaa03 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 20:30:43 -0800 Subject: [PATCH 013/470] Draw military flights from the shared GPU icon set The flights icon planning and presentation move into `createAircraftIcons` (src/data/aircraftIconLayer.js), and the motion regime both layers dead-reckon from into src/data/aircraftMotionRegime.js. Flights keeps only its grounded-floor pass on top. Military now draws every contact as a row of that icon set, like flights: the billboards, the cull positions and the rotation-pass signature go. Tracking hides the row and untracking re-plans it from the tracked course. Queries read the drawn row position and judge the horizon as the shader does. Snapshots that arrive before init or after destroy are ignored, and per-contact lookups find no contact then instead of throwing. With about 120 live military contacts, preRender p95 drops from 0.7-0.8 ms to 0.2 ms on the same views. Render time and frame gaps are unchanged or slightly lower. --- scripts/package-boundaries.json | 16 + src/data/aircraftEmergencyAnalyst.test.mjs | 56 ++- src/data/aircraftIconLayer.js | 443 +++++++++++++++++ src/data/aircraftMotionRegime.js | 138 ++++++ src/data/cockpitModels.test.mjs | 14 +- src/data/militaryAwareness.test.mjs | 2 +- src/data/militaryFlights.js | 2 + src/data/nearbyModelHandoff.test.mjs | 7 +- src/data/tr3bRegistry.test.mjs | 12 +- src/data/trackedModelRegime.test.mjs | 18 +- src/layers/flights/icons.js | 398 ++-------------- src/layers/flights/motion.js | 135 +----- src/layers/flights/ownership.test.mjs | 14 + src/layers/flights/policy.js | 16 +- src/layers/flights/rendering.js | 4 +- src/layers/flights/snapshotRenderer.js | 2 + src/layers/flights/testing.js | 43 +- src/layers/flights/tracking.js | 4 +- src/layers/military/icons.js | 19 + src/layers/military/index.js | 4 +- src/layers/military/lifecycle.js | 50 +- src/layers/military/motion.js | 138 ++---- src/layers/military/ownership.test.mjs | 35 +- src/layers/military/policy.js | 32 +- src/layers/military/queries.js | 153 +++--- src/layers/military/records.js | 10 +- src/layers/military/rendering.js | 525 +++++++-------------- src/layers/military/snapshotRenderer.js | 115 ++--- src/layers/military/state.js | 33 +- src/layers/military/testing.js | 30 +- src/layers/military/tracking.js | 154 +++--- src/testSupport/readLayerSource.mjs | 8 +- src/ui/cyberTheme.test.mjs | 2 +- 33 files changed, 1256 insertions(+), 1376 deletions(-) create mode 100644 src/data/aircraftIconLayer.js create mode 100644 src/data/aircraftMotionRegime.js create mode 100644 src/layers/military/icons.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 731b9da199..631fb2f6d4 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1316,6 +1316,8 @@ "src/layers/flights/queries.js", "src/layers/flights/rendering.js", "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", "src/data/iconSegment.js", @@ -1383,6 +1385,14 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/aircraftMotionRegime.js", + "src/data/iconSetPrimitive.js", + "src/data/iconSet.js", + "src/data/iconSegment.js", + "src/data/iconAtlas.js", + "src/data/aircraftRecession.js", "src/data/modelMirror.js", "src/data/billboardMirror.js", "src/layers/aircraft/visualState.js", @@ -2256,6 +2266,8 @@ ], "modules": [ "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/aircraftMotionRegime.js", "src/sources/adsbFields.js", "src/data/headingDegrees.js", "src/data/distanceFormat.js", @@ -2604,6 +2616,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", @@ -3256,6 +3269,8 @@ "exports": ["./application/layers"], "modules": [ "src/layers/flights/icons.js", + "src/data/aircraftIconLayer.js", + "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", "src/data/iconSegment.js", @@ -3521,6 +3536,7 @@ "src/layers/military/policy.js", "src/layers/military/queries.js", "src/layers/military/rendering.js", + "src/layers/military/icons.js", "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", diff --git a/src/data/aircraftEmergencyAnalyst.test.mjs b/src/data/aircraftEmergencyAnalyst.test.mjs index 27deb2b467..59516787aa 100644 --- a/src/data/aircraftEmergencyAnalyst.test.mjs +++ b/src/data/aircraftEmergencyAnalyst.test.mjs @@ -3,6 +3,12 @@ import { TRACKED_ICON_COLOR } from '../layers/military/policy.js'; import { createRendering as civilRendering } from '../layers/flights/rendering.js'; import { createRendering as militaryRendering } from '../layers/military/rendering.js'; import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js'; +import { createIcons as createMilitaryIcons } from '../layers/military/icons.js'; +import { createIconSet } from './iconSet.js'; +import { + aircraftMotionRegime, + createMotionRegime, +} from './aircraftMotionRegime.js'; import { aircraftEmergency } from './aircraftEmergency.js'; // Source-to-voice provenance, status retention/clearing, contact-time contracts, // and civil/military billboard, Cockpit and model tint regressions. @@ -462,18 +468,16 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do } }); -test('GERMAN: an existing untracked military billboard repaints each poll without alpha loss', () => { +test('GERMAN: an existing untracked military icon repaints each poll without losing its fade', () => { const { flightState, rendering } = renderHarness(militaryRendering); - const bb = { - color: rendering._fleetBillboardColor('abc123').withAlpha(0.65), - }; Object.assign(flightState, { - _billboards: new Map([['abc123', bb]]), + _icons: createIconSet(), _models: new Map(), _positionHistory: new Map(), - _cullPositions: new Map(), + _displayCourse: new Map(), _groundSnap: { forget() {} }, _cockpitContactMode: false, + _cockpitNearContacts: new Set(), }); const records = new MilitaryFlightRecords({ geoidHeight: () => 0, @@ -481,18 +485,42 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou floorAltitudeM: (value) => value, }); flightState.records = records; + const parts = { + rendering: { + ...rendering, + _iconKind: () => 'jet', + _syncModelToClass() {}, + }, + motion: { + _motionRegime: (history, info, renderTime) => + aircraftMotionRegime( + history, + info, + renderTime, + { speed: 'speedMps', track: 'track' }, + createMotionRegime(), + ), + }, + }; + const icons = createMilitaryIcons({ + flightState, + services: { focus: { focusPassIsNeeded: () => false } }, + parts, + }); + const row = flightState._icons.add('abc123', { + layer: 'military', + id: 'abc123', + }); + // The focus fade the fleet tick composes lives in its own column. + flightState._icons.setFocus(row, 0.65); const apply = createMilitarySnapshotRenderer({ flightState, records, groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null }, meshFloor: { sampleMeshFloorCells() {} }, militaryRegistry: { registerMilitaryIcaos() {} }, - rendering: { - ...rendering, - _syncModelToClass() {}, - _applyFleetBillboardPresentation() {}, - }, - motion: {}, + rendering: parts.rendering, + icons, tracking: {}, queries: {}, }); @@ -518,7 +546,7 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou { observedAtMs: NOW_MS }, ); apply(snapshot, {}); - assert.equal(bb.color.green < 0.5, red); - assert.equal(bb.color.alpha, 0.65); + assert.equal(flightState._icons.color(row).green < 0.5, red); + assert.ok(Math.abs(flightState._icons.focus(row) - 0.65) < 1e-6); } }); diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js new file mode 100644 index 0000000000..e7ea0db824 --- /dev/null +++ b/src/data/aircraftIconLayer.js @@ -0,0 +1,443 @@ +import * as Cesium from 'cesium'; +import { + COURSE_HOLD_SPEED_MPS, + courseSlewCapDps, + norm180, +} from './motionModel.js'; +import { + createIconSet, + ICON_CULL_LIFT, + ICON_RECEDES, + ICON_ROTATES, +} from './iconSet.js'; +import { + segmentCourse, + writeArcSegment, + writeCourseGlide, + writeHoldSegment, + writeLerpSegment, +} from './iconSegment.js'; +import { IconSetPrimitive } from './iconSetPrimitive.js'; +import { iconAtlas } from './iconAtlas.js'; +import { + aircraftIcon, + FLEET_ICON_PX, + TRACKED_ICON_PX, +} from './aircraftIcons.js'; +import { cockpitContactDotImage } from './cockpitContactDot.js'; +import { horizonOccluder } from './iconOrientation.js'; + +/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ +const COCKPIT_DOT_PX = 16; +/** Contacts drawn below this height (m) are judged for the horizon a little + * above the ellipsoid (ICON_CULL_LIFT). */ +const CULL_LIFT_BELOW_M = 10; + +/** + * An aircraft layer's contacts as one icon set: each row's motion segment + * mirrors the layer's dead reckoning for the delayed display time, so the GPU + * moves every untracked contact between polls with no per-frame CPU pass. + * + * The layer's state supplies `_icons`, `_iconPrimitive`, `_scratchIconRenderTime`, + * `_iconFocusActive`, `_positionHistory`, `_displayCourse`, `_groundSnap`, + * `_models`, `_trackedIcao`, `_viewer`, `_cockpitContactMode`, + * `_cockpitNearContacts` and `records` (`data`, `missingPolls`, `forget`). + * `parts.motion._motionRegime` picks the motion; `parts.rendering` supplies + * the icon kind, scale, colours and distance scalars, and `_releaseModel`. + * + * @param {object} options + * @param {object} options.state The layer's mutable state. + * @param {object} options.services The layer's services (`focus`). + * @param {object} options.parts The layer's parts (`motion`, `rendering`). + * @param {string} options.layerId Pick and focus owner id. + * @param {number} options.renderDelaySec How far behind real time contacts draw. + * @param {number} options.courseMaxDps The fleet's course slew cap. + * @param {number} options.cockpitContactSizePx Cockpit far-contact pip size. + * @param {(icao24: string) => boolean} [options.holdsPlan] True while something + * else writes this row's segment (it is not planned). + * @param {(icao24: string) => void} [options.beforeSettle] Runs before a row is + * planned afresh. + * @param {(icao24: string) => void} [options.afterSettle] Runs after it. + * @param {(icao24: string) => void} [options.onForget] Drops the layer's own + * per-contact state when a contact goes. + */ +export function createAircraftIcons({ + state, + services, + parts, + layerId, + renderDelaySec, + courseMaxDps, + cockpitContactSizePx, + holdsPlan = () => false, + beforeSettle = () => {}, + afterSettle = () => {}, + onForget = () => {}, +}) { + const { focusPassIsNeeded } = services.focus; + const scratchTime = new Cesium.JulianDate(); + const scratchPosition = new Cesium.Cartesian3(); + const scratchCull = new Cesium.Cartesian3(); + const scratchScaleByDistance = new Cesium.NearFarScalar(); + let normalScaleByDistance = null; + let cockpitScaleByDistance = null; + + /** The delayed instant every untracked contact is drawn at. */ + function _displayTime(result = scratchTime) { + return Cesium.JulianDate.addSeconds( + Cesium.JulianDate.now(result), + -renderDelaySec, + result, + ); + } + + function _displayTau() { + return state._icons.seconds(_displayTime()); + } + + /** Create the set and its primitive for one layer lifetime. */ + function _createIcons(viewer) { + state._icons = createIconSet({ epoch: _displayTime() }); + state._iconPrimitive = new IconSetPrimitive({ + set: state._icons, + renderTime: () => _displayTime(state._scratchIconRenderTime), + }); + viewer.scene.primitives.add(state._iconPrimitive); + return state._iconPrimitive; + } + + /** Where a contact is drawn right now, or null when it has no row. */ + function _iconPosition(icao24, result = new Cesium.Cartesian3()) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + return row < 0 ? null : set.position(row, _displayTau(), result); + } + + /** The nose direction a contact is drawn with right now. */ + function _iconCourse(icao24) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + return row < 0 ? null : set.course(row, _displayTau()); + } + + /** Whether the layer draws this contact's icon (not tracked, not model-owned). */ + function _iconShown(icao24) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + return row >= 0 && set.shown(row); + } + + /** The camera's horizon test, or null when there is no placed camera. */ + function _occluder() { + const camera = state._viewer?.camera; + return camera?.positionWC ? horizonOccluder(camera) : null; + } + + /** Whether a drawn row at `position` clears the camera's horizon, judged + * exactly as the icon shader judges it. No camera, no horizon. */ + function _aboveHorizon(row, position, occluder) { + return ( + !occluder || + occluder.isPointVisible( + state._icons.cullPoint(row, position, scratchCull), + ) + ); + } + + /** + * Write the segment the layer's dead reckoning would follow from now on: + * interpolation between the bracketing fixes, the warm-up arc back from the + * oldest fix, or the coast arc past the newest. The displayed nose glides + * from where it is onto the new course at the fleet's slew cap; a hovering + * contact keeps its nose. The row expires when the regime would change. + * @param {string} icao24 + * @param {{fromCourseDeg?: number|null}} [options] Nose to glide from when + * the row's own segment is not what was on screen (tracking handoff). + */ + function _planIcon(icao24, { fromCourseDeg } = {}) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + if (row < 0 || holdsPlan(icao24)) return; + const history = state._positionHistory.get(icao24); + if (!history?.length) return; + const info = state.records.data.get(icao24); + const renderTime = _displayTime(); + const tau = set.seconds(renderTime); + const seg = set.segments; + const shownCourse = + fromCourseDeg ?? + (set.expires(row) === -Infinity ? null : set.course(row, tau)); + + const regime = parts.motion._motionRegime(history, info, renderTime); + let speed; + let expiresAt = Infinity; + if (regime.kind === 'between') { + const { a, b, span, trackFrom, trackTo, chordCourse } = regime; + speed = regime.speed; + const blend = chordCourse == null ? 0 : regime.blend; + if (span > 0) { + writeLerpSegment(seg, row, { + from: a.position, + to: b.position, + t0: set.seconds(a.time), + t1: set.seconds(b.time), + course0Deg: + trackFrom + blend * norm180((chordCourse ?? 0) - trackFrom), + courseSlopeDeg: norm180(trackTo - trackFrom) * (1 - blend), + }); + } else { + writeHoldSegment( + seg, + row, + b.position, + trackTo + blend * norm180((chordCourse ?? 0) - trackTo), + ); + } + expiresAt = set.seconds(b.time); + } else { + const { fix, heading } = regime; + speed = regime.speed; + const t0 = set.seconds(fix.time); + if (speed === 0) { + writeHoldSegment(seg, row, fix.position, heading); + } else { + writeArcSegment(seg, row, { + fix: fix.position, + t0, + minDt: regime.minDt, + maxDt: regime.maxDt, + speedMps: speed, + trackDeg: heading, + turnRateDps: regime.turnRateDps, + }); + } + // A warm-up's arc ends at its fix; a coast's runs to its limit. + if (regime.maxDt === 0) expiresAt = t0; + } + // Below hover speed the nose holds what is on screen (or, for a new row, + // where this segment starts); above it, it glides on at the slew cap. + const hold = speed < COURSE_HOLD_SPEED_MPS; + if (hold || shownCourse != null) { + writeCourseGlide( + seg, + row, + shownCourse ?? segmentCourse(seg, row, tau), + tau, + hold ? 0 : courseSlewCapDps(speed, courseMaxDps), + ); + } + set.segmentWritten(row, expiresAt); + } + + /** Re-plan every row whose regime ended before `tau`. */ + function _replanExpired(tau) { + const set = state._icons; + const due = []; + for (let row = 0; row < set.count; row++) + if (set.expires(row) <= tau) due.push(set.idAt(row)); + for (const icao24 of due) _planIcon(icao24); + } + + /** + * Advance focus de-emphasis for every drawn row (and every row a fleet model + * draws for, whose alpha reads it), only while a focus target exists or some + * row is still relaxing back to full emphasis. + */ + function _focusIcons(tau, scene, camera, nowMs, target) { + if (!focusPassIsNeeded(target, state._iconFocusActive)) return; + const { advanceProjectedSpriteFocus, nearFarScalarValueAtDistance } = + services.focus; + const set = state._icons; + let active = 0; + for (let row = 0; row < set.count; row++) { + if (!set.shown(row) && !state._models.has(set.idAt(row))) continue; + const position = set.position(row, tau, scratchPosition); + const distanceScale = nearFarScalarValueAtDistance( + set.scaleByDistance(row, scratchScaleByDistance), + Cesium.Cartesian3.distance(camera.positionWC, position), + ); + const half = set.scale(row) * distanceScale * 0.5; + const focus = advanceProjectedSpriteFocus( + set.metaAt(row), + position, + scene, + camera, + nowMs, + target, + undefined, + set.width(row) * half, + set.height(row) * half, + ); + set.setFocus(row, focus.factor); + if (focus.active || focus.transitioning) active++; + } + state._iconFocusActive = active; + } + + /** Image, size, scale, tint and freshness for one row under the current + * normal/cockpit contract. Motion and rotation stay with the segment. */ + function _applyIconPresentation(icao24) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + if (row < 0) return; + const rendering = parts.rendering; + const info = state.records.data.get(icao24); + const tracked = icao24 === state._trackedIcao; + const cockpitDot = + state._cockpitContactMode && + !tracked && + !state._cockpitNearContacts.has(icao24); + if (cockpitDot) { + const dot = iconAtlas.slot(cockpitContactDotImage(), COCKPIT_DOT_PX); + set.setImage(row, dot, dot); + set.setSize(row, cockpitContactSizePx, cockpitContactSizePx); + set.setScale(row, 1); + cockpitScaleByDistance ??= rendering._cockpitBillboardScaleByDistance(); + set.setScaleByDistance(row, cockpitScaleByDistance); + set.setColor(row, rendering._cockpitContactColor(icao24, info)); + set.setFlag(row, ICON_ROTATES, false); + } else { + set.setImage( + row, + iconAtlas.slot( + aircraftIcon(rendering._iconKind(icao24, info?.klass)), + FLEET_ICON_PX, + ), + iconAtlas.slot( + aircraftIcon( + rendering._iconKind(icao24, info?.klass), + TRACKED_ICON_PX, + ), + TRACKED_ICON_PX, + ), + ); + const size = tracked ? 24 : 20; + set.setSize(row, size, size); + set.setScale(row, rendering._fleetBillboardScale(icao24, info?.klass)); + normalScaleByDistance ??= rendering._normalBillboardScaleByDistance(); + set.setScaleByDistance(row, normalScaleByDistance); + set.setColor(row, rendering._fleetBillboardColor(icao24, info)); + set.setFlag(row, ICON_ROTATES, true); + } + set.setFlag(row, ICON_RECEDES, true); + set.setFlag( + row, + ICON_CULL_LIFT, + Number.isFinite(info?.renderAltitudeM) && + info.renderAltitudeM < CULL_LIFT_BELOW_M, + ); + set.setAlpha(row, state.records.missingPolls.get(icao24) ? 0.45 : 1); + } + + /** Add a row for a new contact, hidden while it is the tracked one. */ + function _addIcon(icao24) { + const set = state._icons; + const row = set.add(icao24, { layer: layerId, id: icao24 }); + _applyIconPresentation(icao24); + _settleIcon(icao24); + set.setShown(row, icao24 !== state._trackedIcao); + return row; + } + + /** + * Plan a row afresh, with the layer's own settle work on either side, and + * let a dimmed row relax: one that sat out the focus pass (tracked) may come + * back dimmed after the pass went idle, so it is counted to run the pass. + * @param {string} icao24 + * @param {{fromCourseDeg?: number}} [options] The course on screen to glide from. + */ + function _settleIcon(icao24, options) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + if (row < 0) return; + beforeSettle(icao24); + if (set.focus(row) < 1) state._iconFocusActive += 1; + _planIcon(icao24, options); + afterSettle(icao24); + } + + /** Drop a contact and everything the layer keeps for it. */ + function _forgetContact(icao24) { + state._icons?.remove(icao24); + parts.rendering._releaseModel(icao24); + state.records.forget(icao24); + state._positionHistory.delete(icao24); + state._displayCourse.delete(icao24); + state._groundSnap.forget(icao24); + onForget(icao24); + } + + /** Icon ids, so ray samples never land on an aircraft instead of the ground. */ + function _iconIds() { + const set = state._icons; + const ids = new Array(set?.count ?? 0); + for (let row = 0; row < ids.length; row++) ids[row] = set.idAt(row); + return ids; + } + + return { + _displayTime, + _displayTau, + _createIcons, + _iconPosition, + _iconCourse, + _iconShown, + _occluder, + _aboveHorizon, + _planIcon, + _settleIcon, + _replanExpired, + _focusIcons, + _applyIconPresentation, + _addIcon, + _forgetContact, + _iconIds, + }; +} + +/** + * Test seams over an aircraft layer's icon rows, shared by the flights and + * military `testing` parts. + * @param {object} state The layer state holding `_icons`. + * @param {{icons: ReturnType}} parts Read at call time. + * @param {string} layerId + */ +export function aircraftIconTestSeams(state, parts, layerId) { + /** Give a test contact an icon row held at `billboard.position`, shown as + * `billboard.show` says (hidden by default while tracked). */ + function _seedIconForTest(icao24, billboard, tracked) { + const set = state._icons; + const row = set.add(icao24, { layer: layerId, id: icao24 }); + if (billboard?.position) + writeHoldSegment(set.segments, row, billboard.position, 0); + set.segmentWritten(row); + set.setShown(row, billboard?.show ?? !tracked); + return row; + } + + /** Where a contact's icon is drawn now and whether the layer shows it. */ + function _iconForTest(icao24) { + const position = parts.icons._iconPosition(icao24); + return position + ? { + position, + shown: parts.icons._iconShown(icao24), + course: parts.icons._iconCourse(icao24), + } + : null; + } + + /** Show or hide a contact's icon as a handoff would, or hold it somewhere. */ + function _setIconForTest(icao24, { shown, position } = {}) { + const set = state._icons; + const row = set?.row(icao24) ?? -1; + if (row < 0) return; + if (shown !== undefined) set.setShown(row, shown); + if (position) { + writeHoldSegment(set.segments, row, position, 0); + set.segmentWritten(row); + } + } + + return { _seedIconForTest, _iconForTest, _setIconForTest }; +} diff --git a/src/data/aircraftMotionRegime.js b/src/data/aircraftMotionRegime.js new file mode 100644 index 0000000000..dcbe36e26c --- /dev/null +++ b/src/data/aircraftMotionRegime.js @@ -0,0 +1,138 @@ +import * as Cesium from 'cesium'; +import { + courseBetweenCartesians, + speedRamp, + staleCoastLimitSeconds, +} from './motionModel.js'; + +/** + * Which record fields carry an aircraft layer's reported ground speed (m/s) + * and track (degrees clockwise from north). + * @typedef {{speed: string, track: string}} AircraftRecordFields + */ + +/** A fix's own ground speed, else the record's. */ +export function fixSpeedMps(fix, info, fields) { + return Number.isFinite(fix.velocity) + ? fix.velocity + : (info && info[fields.speed]) || 0; +} + +/** A fix's own track, else the record's. */ +export function fixTrackDeg(fix, info, fields) { + return Number.isFinite(fix.track) + ? fix.track + : (info && info[fields.track]) || 0; +} + +/** A reusable result for `aircraftMotionRegime`. */ +export function createMotionRegime() { + return { + kind: 'fix', + a: null, + b: null, + span: 0, + speed: 0, + trackFrom: 0, + trackTo: 0, + chordCourse: null, + blend: 0, + fix: null, + heading: 0, + turnRateDps: 0, + minDt: 0, + maxDt: 0, + }; +} + +/** + * Which motion an aircraft's history gives at `renderTime` — the one choice + * the CPU dead reckoning and the icon planner (GPU segment) both draw from. + * + * - `between`: interpolate the bracketing pair `a`→`b`, no extrapolation + * error and no snap-back. The course of the DISPLAYED motion blends the + * time-interpolated reported track toward the chord by `blend`: the chord + * is only trustworthy when the segment covers real ground (at hover its + * direction is GPS jitter; on a slow tight turn it STEPS the whole + * per-segment turn at each boundary), and helicopters never use it + * (rotorcraft chords are noise-dominated at their typical speeds). + * - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt]. + * Warm-up (renderTime predates ALL history: freshly seen or just tracked, + * before a poll interval of history exists) runs the OLDEST fix BACKWARD, + * preserving the behind-real-time invariant, so as history fills the icon + * glides FORWARD into interpolation with no freeze and no backward snap + * (holding the oldest fix froze the icon; extrapolating the newest to + * wall-clock made it jump back a poll interval when interpolation took + * over). Otherwise the newest fix coasts. A feed can still be receiving + * fresh contact messages for that aircraft; freezing 60 s after the + * position produced a stop → catch-up → stop cadence, so it coasts through + * the latest real contact plus a bounded grace, with an absolute cap so a + * stale cached feed cannot drift forever. + * + * @param {Array} history Non-empty, oldest first. + * @param {object|undefined} info The contact's record. + * @param {Cesium.JulianDate} renderTime + * @param {AircraftRecordFields} fields + * @param {object} result From `createMotionRegime`; returned filled in. + */ +export function aircraftMotionRegime( + history, + info, + renderTime, + fields, + result, +) { + for (let i = history.length - 1; i >= 1; i--) { + const a = history[i - 1]; + const b = history[i]; + if ( + !Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) || + !Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) + ) + continue; + const span = Cesium.JulianDate.secondsDifference(b.time, a.time); + const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); + const speed = + span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0; + const fallbackTrack = (info && info[fields.track]) || 0; + const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; + const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed); + result.kind = 'between'; + result.a = a; + result.b = b; + result.span = span; + result.speed = speed; + result.trackFrom = trackFrom; + result.trackTo = Number.isFinite(b.track) ? b.track : trackFrom; + result.chordCourse = + blend > 0 ? courseBetweenCartesians(a.position, b.position) : null; + result.blend = blend; + return result; + } + const newest = history[history.length - 1]; + const warming = Cesium.JulianDate.lessThan(renderTime, history[0].time); + result.kind = 'fix'; + result.fix = warming ? history[0] : newest; + result.speed = fixSpeedMps(result.fix, info, fields); + result.heading = fixTrackDeg(result.fix, info, fields); + result.turnRateDps = (info && info.turnRateDps) || 0; + result.minDt = -60; + // A warm-up ends when real time reaches the oldest fix; a single fix keeps + // coasting forward on the same arc. + result.maxDt = + warming && history.length > 1 + ? 0 + : staleCoastLimitSeconds({ + // `epochMs` is captured once when the poll is normalized. Avoid + // allocating a Date per aircraft on every 12 Hz fleet tick. + fixEpochMs: Number.isFinite(newest.epochMs) + ? newest.epochMs + : Cesium.JulianDate.toDate(newest.time).getTime(), + lastContactEpochMs: info?.lastContactEpochMs, + // Permit one minute of contact grace but cap any cached-feed drift + // at five minutes. Source backoff is exposed separately as a STALE cue. + minimumSec: 60, + maximumSec: 300, + }); + return result; +} diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 2c8bc5f28b..0afc0fb96f 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -83,24 +83,24 @@ for (const layer of LAYERS) { test(`${layer.name}: near AIR state is independent from model admission`, () => { assert.match(source, /nextCockpitNearContacts\(/, 'Cockpit derives a separate near-contact hysteresis set'); - assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)|!flightState\._cockpitNearContacts\.has\(icao24\);\s*if \(cockpitDot\) \{\s*const dot = iconAtlas\.slot\(cockpitContactDotImage\(\)/, + assert.match(source, /!state\._cockpitNearContacts\.has\(icao24\);\s*if \(cockpitDot\) \{\s*const dot = iconAtlas\.slot\(cockpitContactDotImage\(\)/, 'only out-of-range Cockpit contacts become dots'); // `_iconKind` is identity for every unconverted contact (see // tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the // operator explicitly converted into a TR-3B. - assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*aircraftVisuals\.read\(bb\)\?\.iconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)|aircraftIcon\(\s*parts\.rendering\._iconKind\(icao24, info\?\.klass\),?\s*\)/, + assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*\)/, 'near contacts and model fallbacks retain the class-derived aircraft silhouette'); - assert.match(source, /setBillboard\(\s*bb,\s*'rotation',\s*0\s*\);|set\.setFlag\(row, ICON_ROTATES, false\);/, + assert.match(source, /set\.setFlag\(row, ICON_ROTATES, false\);/, 'far dots are reset to a rotation-free presentation'); - assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)|set\.setFlag\(row, ICON_ROTATES, true\);/, + assert.match(source, /set\.setFlag\(row, ICON_ROTATES, true\);/, 'near 2D silhouettes continue to receive projected course'); - assert.match(source, /if\s*\(\s*billboardState\(bb\)\.show,?\s*\)\s*setBillboard\(\s*bb,\s*'show',\s*false\s*\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders|icons\.setShown\(row, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, - 'the gap-proof billboard-to-model handoff remains intact'); + assert.match(source, /icons\.setShown\(row, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/, + 'the gap-proof icon-to-model handoff remains intact'); }); test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => { const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); - assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);|for \(let row = 0; row < \(icons\?\.count \?\? 0\); row\+\+\)\s*parts\.icons\._applyIconPresentation\(icons\.idAt\(row\)\);/); + assert.match(setMode, /for \(let row = 0; row < \(icons\?\.count \?\? 0\); row\+\+\)\s*parts\.icons\._applyIconPresentation\(icons\.idAt\(row\)\);/); }); } diff --git a/src/data/militaryAwareness.test.mjs b/src/data/militaryAwareness.test.mjs index 529544d2d9..606dc8440d 100644 --- a/src/data/militaryAwareness.test.mjs +++ b/src/data/militaryAwareness.test.mjs @@ -1665,7 +1665,7 @@ test('hasContact declines while a layer is disabled, whatever its maps still hol [ 'militaryFlights', readLayerSource(new URL('./militaryFlights.js', import.meta.url)), - /hasContact\(\s*icao24,?\s*\)\s*\{\s*\n\s*if\s*\(\s*!(?:flightState\.)?_billboardCollection\s*\|\|\s*!(?:flightState\.)?_billboardCollection\.show\s*\|\|\s*(?:flightState\.)?_billboards\.size\s*===\s*0,?\s*\)\s*return\s*null;/, + /hasContact\(\s*icao24,?\s*\)\s*\{\s*\n\s*const icons = flightState\._icons;\s*\n\s*if\s*\(\s*!icons\s*\|\|\s*!icons\.show\s*\|\|\s*icons\.count\s*===\s*0,?\s*\)\s*return\s*null;/, ], [ 'aisLiveVessels', diff --git a/src/data/militaryFlights.js b/src/data/militaryFlights.js index db8276b02b..dd7d8c9025 100644 --- a/src/data/militaryFlights.js +++ b/src/data/militaryFlights.js @@ -32,5 +32,7 @@ export const _driveFleetModelHandoffForTest = militaryFlightsLayer.testing._driveFleetModelHandoffForTest; export const _ensureFleetModelForTest = militaryFlightsLayer.testing._ensureFleetModelForTest; +export const _iconForTest = militaryFlightsLayer.testing._iconForTest; +export const _setIconForTest = militaryFlightsLayer.testing._setIconForTest; export const mapAnalystRecord = militaryFlightsLayer.mapAnalystRecord; export default militaryFlightsLayer; diff --git a/src/data/nearbyModelHandoff.test.mjs b/src/data/nearbyModelHandoff.test.mjs index 449ec6a805..e540be6181 100644 --- a/src/data/nearbyModelHandoff.test.mjs +++ b/src/data/nearbyModelHandoff.test.mjs @@ -14,7 +14,10 @@ import flightsLayer, { _iconForTest, _setTrackedFlightRefreshStateForTest, } from './flights.js'; -import militaryFlightsLayer, { _setTrackedMilitaryRefreshStateForTest } from './militaryFlights.js'; +import militaryFlightsLayer, { + _iconForTest as _militaryIconForTest, + _setTrackedMilitaryRefreshStateForTest, +} from './militaryFlights.js'; const ICAO = 'abc123'; const OTHER = 'def456'; @@ -66,7 +69,7 @@ const LAYERS = [ name: 'military', layer: militaryFlightsLayer, visualCenterM: Cesium.Cartesian3.ZERO, - spritePosition: () => contactBillboard(true).position, + spritePosition: () => _militaryIconForTest(ICAO).position, seed({ billboardShow, models = [] }) { _setTrackedMilitaryRefreshStateForTest({ icao24: ICAO, diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index d2053832ae..89b64c733c 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -232,8 +232,8 @@ test('both flight layers keep a converted contact 2D and visible (render invaria const source = readLayerSource(new URL(`./${name}`, import.meta.url)); // 1. The 3D model handoff is SUPPRESSED for a converted contact — there is - // no TR-3B GLB, so the triangle billboard stays the visual. - assert.match(source, /modelEligible\.has\(icao24\) && !isTr3b\(icao24\)|for \(const icao24 of modelEligible\) \{\s*if \(isTr3b\(icao24\)\) continue;/, + // no TR-3B GLB, so the triangle icon stays the visual. + assert.match(source, /for \(const icao24 of modelEligible\) \{\s*if \(isTr3b\(icao24\)\) continue;/, `${name}: fleet model handoff skips converted contacts`); // The tracked regime became default-on and camera-distance driven // (2026-08-19), so the suppression moved from a conjunct on @@ -242,11 +242,11 @@ test('both flight layers keep a converted contact 2D and visible (render invaria assert.match(source, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isTr3b\(\s*(?:flightState\.)?_trackedIcao,?\s*\),?\s*\)\s*\{/, `${name}: the standalone tracked model is suppressed for a converted contact`); - // 2. The billboard is never hidden by that suppression — it must keep + // 2. The icon is never hidden by that suppression — it must keep // satisfying the getNearby/getDetectableObjects visibility guards, so a // converted contact still works in Contacts and Cockpit. - assert.match(source, /if\s*\(\s*(bb|modelled)\s*&&\s*id\s*!==\s*(?:flightState\.)?_trackedIcao,?\s*\)\s*setBillboard\(\s*\1,\s*'show',\s*true,?\s*\);|if\s*\(\s*row >= 0\s*&&\s*id\s*!==\s*flightState\._trackedIcao\s*\)\s*flightState\._icons\.setShown\(row, true\);/, - `${name}: converting restores the billboard the model handoff had hidden`); + assert.match(source, /if\s*\(\s*row >= 0\s*&&\s*id\s*!==\s*flightState\._trackedIcao\s*\)\s*flightState\._icons\.setShown\(row, true\);/, + `${name}: converting restores the icon the model handoff had hidden`); // 3. Every aircraftIcon() CALL SITE routes through the kind resolver, so no // refresh path (poll reconciler, raster swap, presentation, tracked @@ -411,7 +411,7 @@ test('a converted contact never consumes a 3D model CAP SLOT', async () => { const source = readLayerSource(new URL(`./${name}`, import.meta.url)); // Anchor on the MODEL-eligibility loop (keepDistSq), not the unrelated // ambient-enrichment candidate loop that also builds a `cand`. - const loop = /const\s*cand\s*=\s*\[\];\s*\n\s*for\s*\((?:\s*const\s*\[icao,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*|let row = 0; row < icons\.count; row\+\+)\)[\s\S]*?cand\.push\(\s*/.exec(source)?.[0]; + const loop = /const\s*cand\s*=\s*\[\];\s*\n\s*for\s*\(let row = 0; row < icons\.count; row\+\+\)[\s\S]*?cand\.push\(\s*/.exec(source)?.[0]; assert.ok(loop, `${name}: the model-eligibility candidate loop is present`); assert.match(loop, /keepDistSq/, `${name}: matched the model-eligibility loop`); assert.match(loop, /if \(isTr3b\(icao\)\) continue;/, diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index 072aab15f6..fa0e705b21 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -44,6 +44,8 @@ import militaryFlightsLayer, { _trackedBillboardColorForTest as militaryTrackedBillboardColor, _driveFleetModelHandoffForTest as militaryDriveFleetModel, _ensureFleetModelForTest as militaryEnsureFleetModel, + _iconForTest as militaryIcon, + _setIconForTest as militarySetIcon, } from './militaryFlights.js'; import { clearTr3bRegistry, setTr3b } from './tr3bRegistry.js'; import { reportMeshFloorCell, _clearMeshFloorCellsForTest } from './groundFloor.js'; @@ -188,21 +190,21 @@ function contactBillboard() { }; } -/** A flights contact's icon row, read and written the way these tests read a +/** A contact's icon row, read and written the way these tests read a * billboard: where it is drawn and whether the layer shows it. */ -function flightIconView(icao24) { +function iconView(icao24, readIcon, setIcon) { return { get position() { - return flightsIcon(icao24)?.position; + return readIcon(icao24)?.position; }, set position(position) { - flightsSetIcon(icao24, { position }); + setIcon(icao24, { position }); }, get show() { - return flightsIcon(icao24)?.shown === true; + return readIcon(icao24)?.shown === true; }, set show(shown) { - flightsSetIcon(icao24, { shown }); + setIcon(icao24, { shown }); }, }; } @@ -237,7 +239,7 @@ const LAYERS = [ modelCollection, meta: { callsign: 'TEST123 ', altitude: 10_668, klass: 'airliner', onGround }, }); - return flightIconView(icao24); + return iconView(icao24, flightsIcon, flightsSetIcon); }, }, { @@ -262,7 +264,7 @@ const LAYERS = [ modelCollection, meta: { callsign: 'TEST123 ', altitudeFt: 35_000, klass: 'fastjet', onGround }, }); - return billboard; + return iconView(icao24, militaryIcon, militarySetIcon); }, }, ]; diff --git a/src/layers/flights/icons.js b/src/layers/flights/icons.js index 8bf4df65f5..10967dc73e 100644 --- a/src/layers/flights/icons.js +++ b/src/layers/flights/icons.js @@ -1,35 +1,11 @@ import * as Cesium from 'cesium'; +import { courseSlewCapDps, norm180 } from '../../data/motionModel.js'; import { - COURSE_HOLD_SPEED_MPS, - courseBetweenCartesians, - courseSlewCapDps, - norm180, - speedRamp, - staleCoastLimitSeconds, -} from '../../data/motionModel.js'; -import { - createIconSet, - ICON_CULL_LIFT, - ICON_RECEDES, - ICON_ROTATES, -} from '../../data/iconSet.js'; -import { - segmentCourse, segmentTargetCourse, - writeArcSegment, writeCourseGlide, writeHoldSegment, - writeLerpSegment, } from '../../data/iconSegment.js'; -import { IconSetPrimitive } from '../../data/iconSetPrimitive.js'; -import { iconAtlas } from '../../data/iconAtlas.js'; -import { - aircraftIcon, - FLEET_ICON_PX, - TRACKED_ICON_PX, -} from '../../data/aircraftIcons.js'; -import { cockpitContactDotImage } from '../../data/cockpitContactDot.js'; -import { horizonOccluder } from '../../data/iconOrientation.js'; +import { createAircraftIcons } from '../../data/aircraftIconLayer.js'; import { COCKPIT_CONTACT_SIZE_PX, COURSE_MAX_DPS, @@ -38,184 +14,48 @@ import { RENDER_DELAY_SEC, } from './policy.js'; -/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ -const COCKPIT_DOT_PX = 16; /** Pinned grounded rows rewrite only past this displayed move (m²) or turn (°). */ const PIN_MOVE_SQ_M = 1; const PIN_TURN_DEG = 0.1; /** - * The flights layer's contacts as one icon set: each row's motion segment - * mirrors `_deadReckon`'s regime for the delayed display time, so the GPU - * moves every untracked contact between polls with no per-frame CPU pass. + * The flights layer's contacts as one icon set (`createAircraftIcons`), plus + * the grounded floor: a floor-pinned row holds a CPU position, so it is not + * planned, and settling a grounded contact puts it straight onto the floor. */ export function createIcons({ flightState, services, parts }) { - const { focusPassIsNeeded } = services.focus; - const scratchTime = new Cesium.JulianDate(); const scratchPosition = new Cesium.Cartesian3(); - const scratchCull = new Cesium.Cartesian3(); - const scratchScaleByDistance = new Cesium.NearFarScalar(); - let normalScaleByDistance = null; - let cockpitScaleByDistance = null; - - /** The delayed instant every untracked contact is drawn at. */ - function _displayTime(result = scratchTime) { - return Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(result), - -RENDER_DELAY_SEC, - result, - ); - } - - function _displayTau() { - return flightState._icons.seconds(_displayTime()); - } - - /** Create the set and its primitive for one layer lifetime. */ - function _createIcons(viewer) { - flightState._icons = createIconSet({ epoch: _displayTime() }); - flightState._iconPrimitive = new IconSetPrimitive({ - set: flightState._icons, - renderTime: () => _displayTime(flightState._scratchIconRenderTime), - }); - viewer.scene.primitives.add(flightState._iconPrimitive); - return flightState._iconPrimitive; - } - - /** Where a contact is drawn right now, or null when it has no row. */ - function _iconPosition(icao24, result = new Cesium.Cartesian3()) { - const set = flightState._icons; - const row = set.row(icao24); - return row < 0 ? null : set.position(row, _displayTau(), result); - } - - /** The nose direction a contact is drawn with right now. */ - function _iconCourse(icao24) { - const set = flightState._icons; - const row = set.row(icao24); - return row < 0 ? null : set.course(row, _displayTau()); - } - - /** Whether the layer draws this contact's icon (not tracked, not model-owned). */ - function _iconShown(icao24) { - const set = flightState._icons; - const row = set.row(icao24); - return row >= 0 && set.shown(row); - } - - /** The camera's horizon test, or null when there is no placed camera. */ - function _occluder() { - const camera = flightState._viewer?.camera; - return camera?.positionWC ? horizonOccluder(camera) : null; - } - - /** Whether a drawn row at `position` clears the camera's horizon, judged - * exactly as the icon shader judges it. No camera, no horizon. */ - function _aboveHorizon(row, position, occluder) { - return ( - !occluder || - occluder.isPointVisible( - flightState._icons.cullPoint(row, position, scratchCull), - ) - ); - } - - /** - * Write the segment `_deadReckon` would follow from now on: interpolation - * between the bracketing fixes, the warm-up arc back from the oldest fix, or - * the coast arc past the newest. The displayed nose glides from where it is - * onto the new course at the fleet's slew cap; a hovering contact keeps its - * nose. The row expires when the regime would change. - * @param {string} icao24 - * @param {{fromCourseDeg?: number|null}} [options] Nose to glide from when - * the row's own segment is not what was on screen (tracking handoff). - */ - function _planIcon(icao24, { fromCourseDeg } = {}) { - const set = flightState._icons; - const row = set.row(icao24); - if (row < 0) return; - if (flightState._focusEvidenceIds.has(icao24)) return; - if (flightState._floorPinned.has(icao24)) return; - const history = flightState._positionHistory.get(icao24); - if (!history?.length) return; - const info = flightState.records.data.get(icao24); - const renderTime = _displayTime(); - const tau = set.seconds(renderTime); - const seg = set.segments; - const shownCourse = - fromCourseDeg ?? - (set.expires(row) === -Infinity ? null : set.course(row, tau)); - - const regime = parts.motion._motionRegime(history, info, renderTime); - let speed; - let expiresAt = Infinity; - if (regime.kind === 'between') { - const { a, b, span, trackFrom, trackTo, chordCourse } = regime; - speed = regime.speed; - const blend = chordCourse == null ? 0 : regime.blend; - const t0 = set.seconds(a.time); - if (span > 0) { - writeLerpSegment(seg, row, { - from: a.position, - to: b.position, - t0, - t1: set.seconds(b.time), - course0Deg: - trackFrom + blend * norm180((chordCourse ?? 0) - trackFrom), - courseSlopeDeg: norm180(trackTo - trackFrom) * (1 - blend), - }); - } else { - writeHoldSegment( - seg, - row, - b.position, - trackTo + blend * norm180((chordCourse ?? 0) - trackTo), - ); - } - expiresAt = set.seconds(b.time); - } else { - const { fix, heading } = regime; - speed = regime.speed; - const t0 = set.seconds(fix.time); - if (speed === 0) { - writeHoldSegment(seg, row, fix.position, heading); - } else { - writeArcSegment(seg, row, { - fix: fix.position, - t0, - minDt: regime.minDt, - maxDt: regime.maxDt, - speedMps: speed, - trackDeg: heading, - turnRateDps: regime.turnRateDps, - }); - } - // A warm-up's arc ends at its fix; a coast's runs to its limit. - if (regime.maxDt === 0) expiresAt = t0; - } - // Below hover speed the nose holds what is on screen (or, for a new row, - // where this segment starts); above it, it glides on at the slew cap. - const hold = speed < COURSE_HOLD_SPEED_MPS; - if (hold || shownCourse != null) { - writeCourseGlide( - seg, - row, - shownCourse ?? segmentCourse(seg, row, tau), - tau, - hold ? 0 : courseSlewCapDps(speed, COURSE_MAX_DPS), + const icons = createAircraftIcons({ + state: flightState, + services, + parts, + layerId: 'flights', + renderDelaySec: RENDER_DELAY_SEC, + courseMaxDps: COURSE_MAX_DPS, + cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX, + holdsPlan: (icao24) => + flightState._focusEvidenceIds.has(icao24) || + flightState._floorPinned.has(icao24), + // A pin stops at the last floor pass, which skips a tracked contact. + beforeSettle: (icao24) => flightState._floorPinned.delete(icao24), + // Straight onto the floor under where it is drawn, not its fix's floor + // until the next fleet tick raises it. + afterSettle(icao24) { + if (!flightState._grounded.has(icao24)) return; + const renderTime = icons._displayTime(); + _floorIcon( + icao24, + renderTime, + flightState._icons.seconds(renderTime), + Date.now(), ); - } - set.segmentWritten(row, expiresAt); - } - - /** Re-plan every row whose regime ended before `tau`. */ - function _replanExpired(tau) { - const set = flightState._icons; - const due = []; - for (let row = 0; row < set.count; row++) - if (set.expires(row) <= tau) due.push(set.idAt(row)); - for (const icao24 of due) _planIcon(icao24); - } + }, + onForget(icao24) { + flightState._displayFloorState.delete(icao24); + flightState._grounded.delete(icao24); + flightState._floorPinned.delete(icao24); + }, + }); /** * Grounded contacts stand on the floor under where they are DRAWN, which the @@ -272,7 +112,7 @@ export function createIcons({ flightState, services, parts }) { ); if (!display || display === raw) { if (flightState._floorPinned.delete(icao24)) - _planIcon(icao24, { fromCourseDeg: set.course(row, tau) }); + icons._planIcon(icao24, { fromCourseDeg: set.course(row, tau) }); return; } const planned = set.expires(row) !== -Infinity; @@ -303,169 +143,5 @@ export function createIcons({ flightState, services, parts }) { set.segmentWritten(row); } - /** - * Advance focus de-emphasis for every drawn row (and every row a fleet model - * draws for, whose alpha reads it), only while a focus target exists or some - * row is still relaxing back to full emphasis. - */ - function _focusIcons(tau, scene, camera, nowMs, target) { - if (!focusPassIsNeeded(target, flightState._iconFocusActive)) return; - const { advanceProjectedSpriteFocus, nearFarScalarValueAtDistance } = - services.focus; - const set = flightState._icons; - let active = 0; - for (let row = 0; row < set.count; row++) { - if (!set.shown(row) && !flightState._models.has(set.idAt(row))) continue; - const position = set.position(row, tau, scratchPosition); - const distanceScale = nearFarScalarValueAtDistance( - set.scaleByDistance(row, scratchScaleByDistance), - Cesium.Cartesian3.distance(camera.positionWC, position), - ); - const half = set.scale(row) * distanceScale * 0.5; - const focus = advanceProjectedSpriteFocus( - set.metaAt(row), - position, - scene, - camera, - nowMs, - target, - undefined, - set.width(row) * half, - set.height(row) * half, - ); - set.setFocus(row, focus.factor); - if (focus.active || focus.transitioning) active++; - } - flightState._iconFocusActive = active; - } - - /** Image, size, scale, tint and freshness for one row under the current - * normal/cockpit contract. Motion and rotation stay with the segment. */ - function _applyIconPresentation(icao24) { - const set = flightState._icons; - const row = set.row(icao24); - if (row < 0) return; - const info = flightState.records.data.get(icao24); - const tracked = icao24 === flightState._trackedIcao; - const cockpitDot = - flightState._cockpitContactMode && - !tracked && - !flightState._cockpitNearContacts.has(icao24); - if (cockpitDot) { - const dot = iconAtlas.slot(cockpitContactDotImage(), COCKPIT_DOT_PX); - set.setImage(row, dot, dot); - set.setSize(row, COCKPIT_CONTACT_SIZE_PX, COCKPIT_CONTACT_SIZE_PX); - set.setScale(row, 1); - cockpitScaleByDistance ??= - parts.rendering._cockpitBillboardScaleByDistance(); - set.setScaleByDistance(row, cockpitScaleByDistance); - set.setColor(row, parts.rendering._cockpitContactColor(icao24, info)); - set.setFlag(row, ICON_ROTATES, false); - } else { - set.setImage( - row, - iconAtlas.slot( - aircraftIcon(parts.rendering._iconKind(icao24, info?.klass)), - FLEET_ICON_PX, - ), - iconAtlas.slot( - aircraftIcon( - parts.rendering._iconKind(icao24, info?.klass), - TRACKED_ICON_PX, - ), - TRACKED_ICON_PX, - ), - ); - const size = tracked ? 24 : 20; - set.setSize(row, size, size); - set.setScale( - row, - parts.rendering._fleetBillboardScale(icao24, info?.klass), - ); - normalScaleByDistance ??= - parts.rendering._normalBillboardScaleByDistance(); - set.setScaleByDistance(row, normalScaleByDistance); - set.setColor(row, parts.rendering._fleetBillboardColor(icao24, info)); - set.setFlag(row, ICON_ROTATES, true); - } - set.setFlag(row, ICON_RECEDES, true); - set.setFlag( - row, - ICON_CULL_LIFT, - Number.isFinite(info?.renderAltitudeM) && info.renderAltitudeM < 10, - ); - set.setAlpha(row, flightState.records.missingPolls.get(icao24) ? 0.45 : 1); - } - - /** Add a row for a new contact, hidden while it is the tracked one. */ - function _addIcon(icao24) { - const set = flightState._icons; - const row = set.add(icao24, { layer: 'flights', id: icao24 }); - _applyIconPresentation(icao24); - _settleIcon(icao24); - set.setShown(row, icao24 !== flightState._trackedIcao); - return row; - } - - /** - * Plan a row afresh, dropping any floor pin (a pin stops at the last floor - * pass, which skips a tracked contact), and let a dimmed row relax. A grounded contact goes straight onto - * the floor under where it is drawn, not its fix's floor until the next fleet - * tick raises it. - * @param {string} icao24 - * @param {{fromCourseDeg?: number}} [options] The course on screen to glide from. - */ - function _settleIcon(icao24, options) { - const set = flightState._icons; - flightState._floorPinned.delete(icao24); - // A row that sat out the focus pass (tracked) may come back dimmed after - // the pass went idle; count it so the pass runs and relaxes it. - if (set.focus(set.row(icao24)) < 1) flightState._iconFocusActive += 1; - _planIcon(icao24, options); - if (flightState._grounded.has(icao24)) { - const renderTime = _displayTime(); - _floorIcon(icao24, renderTime, set.seconds(renderTime), Date.now()); - } - } - - /** Drop a contact and everything the layer keeps for it. */ - function _forgetContact(icao24) { - flightState._icons?.remove(icao24); - parts.rendering._releaseModel(icao24); - flightState.records.forget(icao24); - flightState._positionHistory.delete(icao24); - flightState._displayCourse.delete(icao24); - flightState._groundSnap.forget(icao24); - flightState._displayFloorState.delete(icao24); - flightState._grounded.delete(icao24); - flightState._floorPinned.delete(icao24); - } - - /** Icon ids, so ray samples never land on an aircraft instead of the ground. */ - function _iconIds() { - const set = flightState._icons; - const ids = new Array(set?.count ?? 0); - for (let row = 0; row < ids.length; row++) ids[row] = set.idAt(row); - return ids; - } - - return { - _displayTime, - _displayTau, - _createIcons, - _iconPosition, - _iconCourse, - _iconShown, - _occluder, - _aboveHorizon, - _planIcon, - _settleIcon, - _replanExpired, - _floorGroundedIcons, - _focusIcons, - _applyIconPresentation, - _addIcon, - _forgetContact, - _iconIds, - }; + return { ...icons, _floorGroundedIcons }; } diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 37f2febc94..f8d76eb6c6 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -2,9 +2,6 @@ import * as Cesium from 'cesium'; import { COURSE_HOLD_SPEED_MPS, lerpAngleDeg, - speedRamp, - courseBetweenCartesians, - staleCoastLimitSeconds, arcOffsetEnu, courseSlewCapDps, limitCourseStep, @@ -37,20 +34,15 @@ import { } from './policy.js'; import { modelState } from '../../data/modelMirror.js'; import { readEntityRecord } from '../../data/entityRecords.js'; +import { + aircraftMotionRegime, + createMotionRegime, + fixSpeedMps, + fixTrackDeg, +} from '../../data/aircraftMotionRegime.js'; -/** A fix's own ground speed, else the record's. */ -function fixSpeedMps(fix, info) { - return Number.isFinite(fix.velocity) - ? fix.velocity - : (info && info.velocity) || 0; -} - -/** A fix's own track, else the record's. */ -function fixTrackDeg(fix, info) { - return Number.isFinite(fix.track) - ? fix.track - : (info && info.true_track) || 0; -} +/** Where a flights record carries its reported speed and track. */ +const RECORD_FIELDS = { speed: 'velocity', track: 'true_track' }; export function createMotion({ flightState, @@ -80,22 +72,7 @@ export function createMotion({ // the local frame even when the existing Cartesian is mutated in place. const fixFrames = new WeakMap(); /** `_motionRegime`'s reused result. */ - const regime = { - kind: 'fix', - a: null, - b: null, - span: 0, - speed: 0, - trackFrom: 0, - trackTo: 0, - chordCourse: null, - blend: 0, - fix: null, - heading: 0, - turnRateDps: 0, - minDt: 0, - maxDt: 0, - }; + const regime = createMotionRegime(); // Round 5: the old `_warmGroundedAircraftSurfaceCache` (global exact-5-decimal // warm for every grounded contact on Earth) is GONE. Parked-aircraft GPS @@ -221,86 +198,18 @@ export function createMotion({ /** * Which motion a contact's history gives at `renderTime` — the one choice - * `_deadReckon` (CPU) and the icon planner (GPU segment) both draw from. - * - * - `between`: interpolate the bracketing pair `a`→`b`, no extrapolation - * error and no snap-back. The course of the DISPLAYED motion blends the - * time-interpolated reported track toward the chord by `blend`: the chord - * is only trustworthy when the segment covers real ground (at hover its - * direction is GPS jitter; on a slow tight turn it STEPS the whole - * per-segment turn at each boundary), and helicopters never use it - * (rotorcraft chords are noise-dominated at their typical speeds). - * - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt]. - * Warm-up (renderTime predates ALL history: freshly seen or just tracked, - * before RENDER_DELAY_SEC of history exists) runs the OLDEST fix BACKWARD, - * preserving the 30s-behind invariant, so as history fills the icon glides - * FORWARD into interpolation with no freeze and no backward snap (holding - * the oldest fix froze the icon; extrapolating the newest to wall-clock - * made it jump back a poll interval when interpolation took over). - * Otherwise the newest fix coasts. OpenSky can still be receiving fresh - * contact messages for that aircraft; freezing 60 s after the position - * produced a stop → catch-up → stop cadence, so it coasts through the latest - * real contact plus a bounded grace, with an absolute cap so a stale cached - * feed cannot drift forever. - * - * The returned object is a reused scratch: read it before the next call. - * @param {Array} history Non-empty, oldest first. - * @param {object|undefined} info The contact's record. - * @param {Cesium.JulianDate} renderTime + * `_deadReckon` (CPU) and the icon planner (GPU segment) both draw from + * (`aircraftMotionRegime`). The result is a reused scratch: read it before + * the next call. */ function _motionRegime(history, info, renderTime) { - for (let i = history.length - 1; i >= 1; i--) { - const a = history[i - 1]; - const b = history[i]; - if ( - !Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) || - !Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) - ) - continue; - const span = Cesium.JulianDate.secondsDifference(b.time, a.time); - const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); - const speed = span > 0 ? chordLenM / span : (info && info.velocity) || 0; - const fallbackTrack = (info && info.true_track) || 0; - const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; - const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed); - regime.kind = 'between'; - regime.a = a; - regime.b = b; - regime.span = span; - regime.speed = speed; - regime.trackFrom = trackFrom; - regime.trackTo = Number.isFinite(b.track) ? b.track : trackFrom; - regime.chordCourse = - blend > 0 ? courseBetweenCartesians(a.position, b.position) : null; - regime.blend = blend; - return regime; - } - const newest = history[history.length - 1]; - const warming = Cesium.JulianDate.lessThan(renderTime, history[0].time); - regime.kind = 'fix'; - regime.fix = warming ? history[0] : newest; - regime.speed = fixSpeedMps(regime.fix, info); - regime.heading = fixTrackDeg(regime.fix, info); - regime.turnRateDps = (info && info.turnRateDps) || 0; - regime.minDt = -60; - // A warm-up ends when real time reaches the oldest fix; a single fix keeps - // coasting forward on the same arc. - regime.maxDt = - warming && history.length > 1 - ? 0 - : staleCoastLimitSeconds({ - // `epochMs` is captured once when the poll is normalized. Avoid - // allocating a Date per aircraft on every 12 Hz fleet tick. - fixEpochMs: Number.isFinite(newest.epochMs) - ? newest.epochMs - : Cesium.JulianDate.toDate(newest.time).getTime(), - lastContactEpochMs: info?.lastContactEpochMs, - // Permit one minute of contact grace but cap any cached-feed drift - // at five minutes. Source backoff is exposed separately as a STALE cue. - minimumSec: 60, - maximumSec: 300, - }); - return regime; + return aircraftMotionRegime( + history, + info, + renderTime, + RECORD_FIELDS, + regime, + ); } /** @@ -315,8 +224,8 @@ export function createMotion({ */ function _extrapolateFix(fix, info, dt, out, turnRateDps = 0) { - const speed = fixSpeedMps(fix, info); - const heading = fixTrackDeg(fix, info); + const speed = fixSpeedMps(fix, info, RECORD_FIELDS); + const heading = fixTrackDeg(fix, info, RECORD_FIELDS); flightState._drSpeedMps = speed; flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS; flightState._drExtrapolating = true; @@ -533,7 +442,7 @@ export function createMotion({ * readout run in postRender at a LATER frameNumber, so calling _trackedDisplayPosition there would * re-run the dead-reckon on a fresh sample and double-advance the reconciliation → the label jitters * against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when - * there's no valid fix for the tracked aircraft, so callers fall back to the billboard position. */ + * there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */ function _trackedDisplayCached() { return flightState._drReconcileValid && diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs index 7b175bc413..1a6bf7b666 100644 --- a/src/layers/flights/ownership.test.mjs +++ b/src/layers/flights/ownership.test.mjs @@ -147,3 +147,17 @@ test('voice context reads a track that rounds to north as 0°, not 360°', () => '0°', ); }); + +test('a flight layer without an icon set declines contact refreshes', () => { + // Before init and after destroy there are no icon rows: a TR-3B refresh + // reports that the layer owns no such contact instead of throwing. + const layer = createCivilFlightLayer({ + source: { label: 'Fixture aircraft', getSnapshot() {} }, + services: { + ...services(), + aircraftPresentation: { isTr3b: () => true, tr3bConvertedIds: () => [] }, + }, + }); + assert.equal(layer.refreshTr3b('abc123'), false); + assert.equal(layer.trackById('abc123'), false); +}); diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index e951d6cf54..dbe001624e 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -181,23 +181,17 @@ export const LANDED_SPEED_MAX_MPS = 23; /** @constant {number} Max viewer distance (km) for the fleet ground-floor clamp. */ // --------------------------------------------------------------------------- -// Icon orientation (2026-06-10 playtest fix): rotation is computed by -// projecting each aircraft's course vector into WINDOW coordinates -// (iconOrientation.js) with alignedAxis always ZERO — exact at every camera -// pitch/heading, including tracked-entity orbit mode. Rotation passes run on -// the fleet tick only when the camera pose changed (or 1s drift catch-up). -// The same tick horizon-culls billboards: with the Cesium globe hidden there -// is no far-side depth, so planes otherwise show through the planet. +// Fleet icons are one GPU icon set (iconSet.js): the shader dead-reckons each +// row's motion segment, projects its course into window coordinates and +// horizon-culls it (with the Cesium globe hidden there is no far-side depth, +// so planes otherwise show through the planet). The fleet tick only re-plans +// expired rows and drives the model handoff. // --------------------------------------------------------------------------- /** @constant {number} Fleet dead-reckoning tick interval (ms) — ~12Hz, not per-frame. */ export const FLEET_DR_INTERVAL_MS = 80; -/** @constant {number} Max ms between rotation passes while the camera is idle. */ - -export const ROTATION_REFRESH_MS = 1000; - /** Max course slew (deg/s) — well above real turns (≤4°/s), hides fix-boundary * steps. Scaled down toward COURSE_MIN_DPS at low speed (courseSlewCapDps). */ diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index c6adae37dd..c2a15bd7d3 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -456,7 +456,7 @@ export function createRendering({ id: icao24, // so scene.pick returns the icao for click-to-track }); } catch { - // asset/decode fail — stay billboard. Only touch this lifecycle's state if still current + // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current // (a destroy/re-init may have swapped the globals while this load was in flight). if (epoch === flightState._modelEpoch) { flightState._modelPending.delete(icao24); @@ -509,7 +509,7 @@ export function createRendering({ visual.specKey = specKey; // class-change sync compares against this visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this // Admitted, not yet the visual. Cesium's default is show=true, which would let - // an unplaced primitive claim ownership from the billboard for the frames + // an unplaced primitive claim ownership from the icon for the frames // between admission and the next fleet tick (and draw at the identity matrix, // i.e. the Earth's centre). The handoff turns it on once it has a matrix. setModel(model, 'show', false); diff --git a/src/layers/flights/snapshotRenderer.js b/src/layers/flights/snapshotRenderer.js index ddc8c864a8..17260ec939 100644 --- a/src/layers/flights/snapshotRenderer.js +++ b/src/layers/flights/snapshotRenderer.js @@ -24,6 +24,8 @@ export function createFlightSnapshotRenderer({ const { warmGroundFloor } = groundFloor; const { sampleMeshFloorCells } = meshFloor; return function applySnapshot(snapshot, viewer) { + // Before init (or after destroy) there is no icon set to draw into. + if (!flightState._icons) return { count: 0, ids: new Set() }; const currentIcaos = new Set(); const acceptedSnapshotIcaos = new Set(); // Field-test round 3 (2026-07-06, Austin fleet-underground): viewer diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index b5df7a0764..06a1b9061c 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -2,7 +2,7 @@ import * as Cesium from 'cesium'; import { CYAN_TRANSPARENT } from './policy.js'; import { mirrorModel } from '../../data/modelMirror.js'; import { createIconSet } from '../../data/iconSet.js'; -import { writeHoldSegment } from '../../data/iconSegment.js'; +import { aircraftIconTestSeams } from '../../data/aircraftIconLayer.js'; export function createTesting({ flightState, @@ -11,6 +11,8 @@ export function createTesting({ layer, resolveAsset, }) { + const { _seedIconForTest, _iconForTest, _setIconForTest } = + aircraftIconTestSeams(flightState, parts, 'flights'); /** Test seam for the display-floor clamp (unit-tested against real Cesium math * with seeded mesh cells — the drift mechanism is otherwise only reachable * through a live poll + render loop). */ @@ -39,19 +41,6 @@ export function createTesting({ flightState._displayFloorState.clear(); } - /** Give a test contact an icon row held at `billboard.position`, shown as - * `billboard.show` says (hidden by default while tracked). */ - - function _seedIconForTest(icao24, billboard, tracked) { - const icons = flightState._icons; - const row = icons.add(icao24, { layer: 'flights', id: icao24 }); - if (billboard?.position) - writeHoldSegment(icons.segments, row, billboard.position, 0); - icons.segmentWritten(row); - icons.setShown(row, billboard?.show ?? !tracked); - return row; - } - /** * Seed only the mutable state needed to exercise tracked-card refreshes through * the production poll reconciler. Tests still call `flightsLayer.update()`; @@ -212,38 +201,12 @@ export function createTesting({ ); } - /** Where a contact's icon is drawn now and whether the layer shows it. */ - - function _iconForTest(icao24) { - const position = parts.icons._iconPosition(icao24); - return position - ? { - position, - shown: parts.icons._iconShown(icao24), - course: parts.icons._iconCourse(icao24), - } - : null; - } - /** Exercise the exact asynchronous fleet loader and return its admitted model. */ async function _ensureFleetModelForTest(icao24) { await parts.rendering._ensureModel(icao24); return flightState._models.get(icao24) || null; } - /** Show or hide a contact's icon as a handoff would, or hold it somewhere. */ - - function _setIconForTest(icao24, { shown, position } = {}) { - const icons = flightState._icons; - const row = icons?.row(icao24) ?? -1; - if (row < 0) return; - if (shown !== undefined) icons.setShown(row, shown); - if (position) { - writeHoldSegment(icons.segments, row, position, 0); - icons.segmentWritten(row); - } - } - /** Run the fleet tick's grounded floor pass once, at `renderTime`. */ function _floorGroundedIconsForTest(renderTime, cameraPosition) { diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 60159be88b..0adb932359 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -164,7 +164,7 @@ export function createTracking({ const distancesSquared = []; const icons = flightState._icons; const tau = parts.icons._displayTau(); - for (let row = 0; row < icons.count; row++) { + for (let row = 0; row < (icons?.count ?? 0); row++) { const icao24 = icons.idAt(row); if (icao24 === flightState._trackedIcao) continue; const position = icons.position(row, tau, flightState._scratchCockpitPos); @@ -987,7 +987,7 @@ export function createTracking({ alignedAxis: Cesium.Cartesian3.ZERO, // The tracked target must never vanish into tile geometry — tracking a // taxiing plane at street level would otherwise bury the cyan icon inside - // the runway skin exactly like the fleet ground icons (_groundDepthDistance); + // 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 diff --git a/src/layers/military/icons.js b/src/layers/military/icons.js new file mode 100644 index 0000000000..4d9a942eed --- /dev/null +++ b/src/layers/military/icons.js @@ -0,0 +1,19 @@ +import { createAircraftIcons } from '../../data/aircraftIconLayer.js'; +import { + COCKPIT_CONTACT_SIZE_PX, + COURSE_MAX_DPS, + RENDER_DELAY_SEC, +} from './policy.js'; + +/** The military layer's contacts as one icon set (`createAircraftIcons`). */ +export function createIcons({ flightState, services, parts }) { + return createAircraftIcons({ + state: flightState, + services, + parts, + layerId: 'military', + renderDelaySec: RENDER_DELAY_SEC, + courseMaxDps: COURSE_MAX_DPS, + cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX, + }); +} diff --git a/src/layers/military/index.js b/src/layers/military/index.js index 53a1a25b46..f5c9a6ac77 100644 --- a/src/layers/military/index.js +++ b/src/layers/military/index.js @@ -1,6 +1,7 @@ import { createMilitarySnapshotRenderer } from './snapshotRenderer.js'; import { createFlightState } from './state.js'; import { createRendering } from './rendering.js'; +import { createIcons } from './icons.js'; import { createMotion } from './motion.js'; import { createTracking } from './tracking.js'; import { createController } from './controller.js'; @@ -19,6 +20,7 @@ export function createMilitaryFlightLayer({ const layer = {}; const context = { flightState, services, parts, layer, resolveAsset }; parts.rendering = createRendering(context); + parts.icons = createIcons(context); parts.motion = createMotion(context); parts.tracking = createTracking(context); parts.controller = createController(context); @@ -33,7 +35,7 @@ export function createMilitaryFlightLayer({ militaryRegistry: services.militaryRegistry, rendering: parts.rendering, tracking: parts.tracking, - motion: parts.motion, + icons: parts.icons, queries: parts.queries, }); parts.ingestion = createIngestion({ diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index c9e658e989..31eabd2e44 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -29,7 +29,7 @@ export function createLifecycle({ }, /** - * Initialize the layer: create the billboard collection, reset all state, + * Initialize the layer: create the icon set and its primitive, reset all state, * and install the click-to-track handler. * @param {Cesium.Viewer} viewer - The Cesium viewer instance */ @@ -42,9 +42,7 @@ export function createLifecycle({ flightState.lifetime = new AbortController(); clearFocusTarget('militaryFlights'); flightState._viewer = viewer; - flightState._billboardCollection = new Cesium.BillboardCollection(); - viewer.scene.primitives.add(flightState._billboardCollection); - registerSpriteCollection('military', flightState._billboardCollection); + registerSpriteCollection('military', parts.icons._createIcons(viewer)); flightState._modelCollection = new Cesium.PrimitiveCollection(); viewer.scene.primitives.add(flightState._modelCollection); // Warm the glTF cache so the tracked plane's model instantiates instantly when first needed @@ -69,11 +67,10 @@ export function createLifecycle({ } }) .catch(() => { - /* tracked plane just stays a billboard a beat longer */ + /* tracked plane just stays an icon a beat longer */ }); } - flightState._billboards = new Map(); - flightState._cullPositions.clear(); + flightState._iconFocusActive = 0; flightState._detectionObjects = new Map(); flightState.records.data = new Map(); flightState._positionHistory = new Map(); @@ -105,7 +102,7 @@ export function createLifecycle({ restoreSpriteOrder(viewer); - console.log('[Data:Military] Initialized with billboard icons'); + console.log('[Data:Military] Initialized with GPU icons'); }, /** @@ -113,8 +110,7 @@ export function createLifecycle({ * @param {Cesium.Viewer} viewer - The Cesium viewer instance */ enable(viewer) { - if (flightState._billboardCollection) - flightState._billboardCollection.show = true; + if (flightState._icons) flightState._icons.show = true; holdContinuousRender('military'); // per-frame animator (perf wave 2) if (flightState._modelCollection) flightState._modelCollection.show = true; @@ -135,13 +131,12 @@ export function createLifecycle({ }); } parts.tracking._installClickHandler(viewer); - registerPickOwner('military', (pickedId) => - flightState._billboards.has(pickedId), + registerPickOwner( + 'military', + (pickedId) => flightState._icons?.has(pickedId) === true, ); // 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 && viewer?.scene) { flightState._preRenderRemove = viewer.scene.preRender.addEventListener( parts.rendering._fleetTick, @@ -154,14 +149,11 @@ export function createLifecycle({ ); } if (!flightState._moveEndRemove && viewer?.camera) { - // 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. + // A settled camera move (voice fly-to, fast pan release) runs the fleet + // pass on the very next preRender rather than up to FLEET_DR_INTERVAL_MS + // later, so the model handoff and focus land with the camera. flightState._moveEndRemove = viewer.camera.moveEnd.addEventListener( () => { - flightState._lastCamPoseSig = ''; flightState._lastFleetTickMs = 0; }, ); @@ -177,8 +169,7 @@ export function createLifecycle({ disable(viewer) { parts.controller._abortActiveUpdates(); parts.tracking._cancelPendingTrackingRestore(); - if (flightState._billboardCollection) - flightState._billboardCollection.show = false; + if (flightState._icons) flightState._icons.show = false; releaseContinuousRender('military'); parts.rendering._releaseModels(); if (flightState._modelCollection) @@ -214,8 +205,8 @@ export function createLifecycle({ }, /** - * Tear down the layer: clear tracking, remove handlers, remove the billboard - * collection from the scene, and release all state. + * Tear down the layer: clear tracking, remove handlers, remove the icon + * primitive from the scene, and release all state. * @param {Cesium.Viewer} viewer - The Cesium viewer instance */ destroy(viewer) { @@ -255,10 +246,12 @@ export function createLifecycle({ flightState._moveEndRemove = null; } parts.rendering._releaseModels(); - if (flightState._billboardCollection) { - viewer.scene.primitives.remove(flightState._billboardCollection); - flightState._billboardCollection = null; + if (flightState._iconPrimitive) { + viewer.scene.primitives.remove(flightState._iconPrimitive); // removing destroys it + flightState._iconPrimitive = null; } + flightState._icons?.clear(); + flightState._icons = null; if (flightState._modelCollection) { viewer.scene.primitives.remove(flightState._modelCollection); // removing destroys it + its models flightState._modelCollection = null; @@ -275,8 +268,7 @@ export function createLifecycle({ flightState._preloadModel = null; } flightState._planeModelLoaded = false; - flightState._billboards.clear(); - flightState._cullPositions.clear(); + flightState._iconFocusActive = 0; flightState._detectionObjects.clear(); flightState.records.data.clear(); flightState._positionHistory.clear(); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 9309d4378f..36c068531c 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -1,10 +1,7 @@ import * as Cesium from 'cesium'; import { lerpAngleDeg, - speedRamp, - courseBetweenCartesians, COURSE_HOLD_SPEED_MPS, - staleCoastLimitSeconds, arcOffsetEnu, courseSlewCapDps, limitCourseStep, @@ -26,6 +23,15 @@ import { } from './policy.js'; import { modelState } from '../../data/modelMirror.js'; import { readEntityRecord } from '../../data/entityRecords.js'; +import { + aircraftMotionRegime, + createMotionRegime, + fixSpeedMps, + fixTrackDeg, +} from '../../data/aircraftMotionRegime.js'; + +/** Where a military record carries its reported speed and track. */ +const RECORD_FIELDS = { speed: 'speedMps', track: 'track' }; export function createMotion({ flightState, @@ -40,6 +46,8 @@ export function createMotion({ clearFocusTarget, publishFocusTargetFromCachedPosition, } = services.focus; + /** `_motionRegime`'s reused result. */ + const regime = createMotionRegime(); /** * Dead-reckon an aircraft's current position using ENU (East-North-Up) frame math. @@ -74,90 +82,43 @@ export function createMotion({ flightState._scratchRenderTime, ); - // Bracketing pair: interpolate — no extrapolation error, no snap-back. - for (let i = history.length - 1; i >= 1; i--) { - const a = history[i - 1]; - const b = history[i]; - if ( - Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) && - Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) - ) { - const span = Cesium.JulianDate.secondsDifference(b.time, a.time); - const t = - span > 0 - ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span - : 1.0; - // Course of the DISPLAYED motion. The chord is only trustworthy when the - // segment covers real ground (at hover its direction is GPS jitter; on a - // slow tight turn it STEPS the whole per-segment turn at each boundary), - // so it is blended against the reported per-fix track by displayed - // ground speed — and the track is TIME-INTERPOLATED between the fixes so - // a slow turner's nose advances continuously through the segment instead - // of snapping once per poll. Helicopters always use the reported track - // (rotorcraft chords are noise-dominated at their typical speeds). - const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); - const segSpeed = - span > 0 ? chordLenM / span : (info && info.speedMps) || 0; - const fallbackTrack = (info && info.track) || 0; - const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack; - const trackTo = Number.isFinite(b.track) ? b.track : trackFrom; - const trackCourse = lerpAngleDeg(trackFrom, trackTo, t); - const w = info && info.klass === 'helicopter' ? 0 : speedRamp(segSpeed); - const chordCourse = - w > 0 ? courseBetweenCartesians(a.position, b.position) : null; - flightState._drCourseDeg = - chordCourse != null - ? lerpAngleDeg(trackCourse, chordCourse, w) - : trackCourse; - flightState._drSpeedMps = segSpeed; - flightState._drCourseHold = segSpeed < COURSE_HOLD_SPEED_MPS; - return Cesium.Cartesian3.lerp(a.position, b.position, t, out); - } + const regime = _motionRegime(history, info, renderTime); + if (regime.kind === 'between') { + const { a, b, span } = regime; + const t = + span > 0 + ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span + : 1.0; + const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t); + flightState._drCourseDeg = + regime.chordCourse != null + ? lerpAngleDeg(trackCourse, regime.chordCourse, regime.blend) + : trackCourse; + flightState._drSpeedMps = regime.speed; + flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS; + return Cesium.Cartesian3.lerp(a.position, b.position, t, out); } - - const newest = history[history.length - 1]; - const elapsedSec = Cesium.JulianDate.secondsDifference( - renderTime, - newest.time, + const dt = Cesium.Math.clamp( + Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time), + regime.minDt, + regime.maxDt, ); - if (elapsedSec <= 0) { - // Warm-up: renderTime predates ALL history (freshly seen / just-started-tracking - // aircraft, before RENDER_DELAY_SEC of history has accumulated, so no bracketing - // pair exists yet). Render at the DELAYED renderTime — preserving the behind-real-time - // invariant — by extrapolating the OLDEST fix BACKWARD to renderTime. As history - // fills, renderTime advances toward the first fix and the icon glides FORWARD into - // the bracketing interpolation above with NO freeze and NO backward snap. (Holding - // the oldest fix froze the icon until enough history accrued, then jumped.) - const oldest = history[0]; - const lookbackSec = Cesium.JulianDate.secondsDifference( - oldest.time, - renderTime, - ); // ≥ 0 - return _extrapolateFix( - oldest, - info, - -Math.min(lookbackSec, 60), - out, - (info && info.turnRateDps) || 0, - ); - } + return _extrapolateFix(regime.fix, info, dt, out, regime.turnRateDps); + } - // Continue through fresh adsb.lol contacts even when the position epoch has - // not advanced, but keep an absolute stale-feed drift ceiling. - const coastLimitSec = staleCoastLimitSeconds({ - // Captured at poll normalization so the fleet tick does not allocate a - // Date for every aircraft twelve times per second. - fixEpochMs: Number.isFinite(newest.epochMs) - ? newest.epochMs - : Cesium.JulianDate.toDate(newest.time).getTime(), - lastContactEpochMs: info?.lastContactEpochMs, - }); - return _extrapolateFix( - newest, + /** + * Which motion a contact's history gives at `renderTime` — the one choice + * `_deadReckon` (CPU) and the icon planner (GPU segment) both draw from + * (`aircraftMotionRegime`). The result is a reused scratch: read it before + * the next call. + */ + function _motionRegime(history, info, renderTime) { + return aircraftMotionRegime( + history, info, - Math.min(elapsedSec, coastLimitSec), - out, - (info && info.turnRateDps) || 0, + renderTime, + RECORD_FIELDS, + regime, ); } @@ -173,12 +134,8 @@ export function createMotion({ */ function _extrapolateFix(fix, info, dt, out, turnRateDps = 0) { - const speed = Number.isFinite(fix.velocity) - ? fix.velocity - : (info && info.speedMps) || 0; - const heading = Number.isFinite(fix.track) - ? fix.track - : (info && info.track) || 0; + const speed = fixSpeedMps(fix, info, RECORD_FIELDS); + const heading = fixTrackDeg(fix, info, RECORD_FIELDS); flightState._drSpeedMps = speed; flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS; if (speed === 0 || dt === 0) { @@ -356,7 +313,7 @@ export function createMotion({ /** The tracked plane's display position WITHOUT recomputing — the value the follow-camera already * settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender at * a later frameNumber, so recomputing _trackedDisplayPosition there jitters the label against the - * now-stable plane. Null when no valid fix (callers fall back to the billboard position). */ + * now-stable plane. Null when no valid fix (callers fall back to the icon position). */ function _trackedDisplayCached() { return flightState._drReconcileValid && @@ -513,6 +470,7 @@ export function createMotion({ } return { _deadReckon, + _motionRegime, _extrapolateFix, _isTrackWarmingUp, _trackedFocusSizePx, diff --git a/src/layers/military/ownership.test.mjs b/src/layers/military/ownership.test.mjs index 3b77643d6e..2741ea83dd 100644 --- a/src/layers/military/ownership.test.mjs +++ b/src/layers/military/ownership.test.mjs @@ -87,7 +87,7 @@ test('military state owns separate contact maps, motion scratch and ground sampl for (const key of [ 'records', 'feed', - '_billboards', + '_displayCourse', '_positionHistory', '_groundSnap', '_scratchCarto', @@ -141,7 +141,7 @@ test('a normalized source can retain its stale reason without changing standalon test('a newly seen military contact appears at its delayed position, not ahead of it', async () => { // The military fleet renders RENDER_DELAY_SEC behind real time, so a fresh // contact's first displayed position is its fix projected back to that - // delayed time. Creating the billboard at the raw fix drew it ahead until + // delayed time. Creating the icon at the raw fix drew it ahead until // the next fleet tick jumped it back. const Cesium = await import('cesium'); const { RENDER_DELAY_SEC } = await import('./policy.js'); @@ -177,7 +177,6 @@ test('a newly seen military contact appears at its delayed position, not ahead o }, }, }); - const added = []; layer.testing._setTrackedMilitaryRefreshStateForTest({ icao24: 'seed00', entity: null, @@ -186,22 +185,14 @@ test('a newly seen military contact appears at its delayed position, not ahead o show: false, position: Cesium.Cartesian3.fromDegrees(0, 0, 0), }, - billboardCollection: { - show: false, - add(options) { - const billboard = { ...options }; - added.push(billboard); - return billboard; - }, - remove() {}, - }, + billboardCollection: { show: false }, viewer: { camera: { positionCartographic: null }, scene: {} }, tracked: false, }); await layer.update({ camera: { positionCartographic: null }, scene: {} }); - const billboard = added.find((entry) => entry.id === 'ae0001'); - assert.ok(billboard, 'the new contact gets a billboard'); - const shown = Cesium.Cartographic.fromCartesian(billboard.position); + const icon = layer.testing._iconForTest('ae0001'); + assert.ok(icon, 'the new contact gets an icon'); + const shown = Cesium.Cartographic.fromCartesian(icon.position); const behindM = Cesium.Cartesian3.distance( Cesium.Cartesian3.fromRadians(shown.longitude, shown.latitude, 0), Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 0), @@ -289,3 +280,17 @@ test('voice context reads a track that rounds to north as 0°, not 360°', () => '0°', ); }); + +test('a military layer without an icon set declines contact refreshes', () => { + // Before init and after destroy there are no icon rows: a TR-3B refresh + // reports that the layer owns no such contact instead of throwing. + const layer = createMilitaryFlightLayer({ + source: { label: 'Fixture aircraft', getSnapshot() {} }, + services: { + ...services(), + aircraftPresentation: { isTr3b: () => true, tr3bConvertedIds: () => [] }, + }, + }); + assert.equal(layer.refreshTr3b('abc123'), false); + assert.equal(layer.trackById('abc123'), false); +}); diff --git a/src/layers/military/policy.js b/src/layers/military/policy.js index bb1d89127c..3dba916a39 100644 --- a/src/layers/military/policy.js +++ b/src/layers/military/policy.js @@ -5,28 +5,23 @@ import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js'; * @module militaryFlights * @description Real-time military flight tracking layer powered by the adsb.lol API. * - * Renders aircraft as amber chevron billboards in a single BillboardCollection - * for GPU-efficient batch drawing. Supports click-to-track: selecting an aircraft + * Renders aircraft as amber chevrons in one GPU icon set (iconSet.js), whose + * shader dead-reckons and orients every row. Supports click-to-track: selecting an aircraft * spawns an Entity the camera follows, whose position is driven by a * dead-reckoning CallbackProperty. The whole fleet renders at * now - RENDER_DELAY_SEC so positions interpolate BETWEEN two known fixes * instead of extrapolating ahead and snapping back when the next poll lands. - * - * Billboard orientation uses alignedAxis set to the WGS84 surface normal at each - * position so that the rotation angle (heading/track) operates in the local tangent - * plane where 0 deg = north; near nadir the icons switch to screen-aligned - * rotation (camera.heading - track) with hysteresis. */ /** @constant {number} Milliseconds to wait before retrying after a transient error */ /** @constant {number} Max position samples retained per aircraft for dead reckoning */ -/** @constant {number} Base billboard display scale */ +/** @constant {number} Base icon display scale */ export const BILLBOARD_SCALE = 0.7; -/** @constant {Cesium.Color} Default amber tint for untracked military billboards */ +/** @constant {Cesium.Color} Default amber tint for untracked military icons */ export const MIL_ICON_COLOR = Cesium.Color.fromCssColorString('#FFB800'); @@ -44,7 +39,7 @@ export const EMERGENCY_ICON_COLOR = // boolean). Such aircraft are RENDERED instead of floating at the 3 km altitude // fallback: same silhouette + rotation pipeline, clickable/trackable/detectable, // sticky metadata updating normally. The on-ground flip restyles the existing -// billboard IN PLACE (landing/takeoff transition, never a removal); ground planes +// icon IN PLACE (landing/takeoff transition, never a removal); ground planes // draw no trails. In 3D mode they take model slots like airborne planes (owner // decision 2026-07-03 — no air/ground distinction), placed by the one-shot // ground snap (see _modelDisplayPosition). @@ -53,7 +48,7 @@ export const EMERGENCY_ICON_COLOR = // test: the day-1 slate-gray 50%-alpha muted tint was unreadable — "in NYC I can // barely see them"). "On the ground" reads from the ×0.8 scale + missing trail; // "feed-dropped, coasting" stays the 45%-alpha stale fade. -/** Ground billboards render slightly smaller so airport clutter stays visually minor. */ +/** Ground icons render slightly smaller so airport clutter stays visually minor. */ export const GROUND_SCALE = 0.8; @@ -215,25 +210,10 @@ export const LANDED_SPEED_MAX_MPS = 23; // gets the floor. /** @constant {number} Max render altitude (m, ellipsoidal) eligible for the ground-floor clamp. */ -// --------------------------------------------------------------------------- -// Nadir-stable icon orientation (mirrors flights.js): surface-normal alignment -// degenerates when the camera looks straight down (the normal is parallel to -// the view direction and the shader's screen-projected angle is 0/0). Near -// nadir we switch to screen-aligned billboards with -// rotation = camera.heading - track (screen-up points at azimuth -// camera.heading; a CW track t appears t-h from screen-up; billboard rotation -// is CCW-positive => r = h - t). Discrete switch with hysteresis; rotations -// are continuous at the boundary with this formula. -// --------------------------------------------------------------------------- - /** @constant {number} Fleet dead-reckoning tick interval (ms) — ~12Hz, not per-frame. */ export const FLEET_DR_INTERVAL_MS = 80; -/** @constant {number} Max ms between rotation passes while the camera is idle. */ - -export const ROTATION_REFRESH_MS = 1000; - /** Max course slew (deg/s) — well above real turns (≤4°/s), hides fix-boundary * steps. Scaled down toward COURSE_MIN_DPS at low speed (courseSlewCapDps). */ diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 205284c7e0..e2908fbb9c 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -11,7 +11,6 @@ import { } from '../../data/contactMatch.js'; import { LANDED_ALT_MAX_FT, LANDED_SPEED_MAX_MPS } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState } from '../../data/modelMirror.js'; export function createQueries({ @@ -88,7 +87,7 @@ export function createQueries({ /** * Build a public descriptor for one aircraft using its best current position - * (dead-reckoned when history exists, billboard position otherwise). + * (dead-reckoned when history exists, icon position otherwise). * @param {string} icao24 - ICAO hex identifier of the aircraft. * @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, 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. @@ -96,10 +95,8 @@ export function createQueries({ function _describeFlight(icao24) { const info = flightState.records.data.get(icao24); - const bb = flightState._billboards.get(icao24); const basePos = - parts.motion._deadReckon(icao24) || - (bb ? billboardState(bb).position : null); + parts.motion._deadReckon(icao24) || parts.icons._iconPosition(icao24); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -271,13 +268,8 @@ export function createQueries({ if (!flightState._models3dEnabled) { parts.rendering._releaseModels(); parts.tracking._syncTracked2dRotation(); - // Restore fleet billboards (horizon-cull re-asserts next tick), but NEVER the tracked - // plane's own fleet billboard — its tracked entity is the visual (avoids a double-image). - if (flightState._billboardCollection) - for (const [icao, bb] of flightState._billboards) { - if (icao !== flightState._trackedIcao) - setBillboard(bb, 'show', true); - } + // (Releasing the models handed each fleet contact back to its icon, never + // the tracked plane's own — its tracked entity is the visual.) } } if ( @@ -357,12 +349,11 @@ export function createQueries({ * @returns {Array} Sorted array of nearby aircraft descriptors */ getNearby(center, range, maxCount = 50, { includeHidden = false } = {}) { - if ( - !center || - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return []; + const icons = flightState._icons; + if (!center || !icons || !icons.show) return []; + const occluder = parts.icons._occluder(); + const tau = parts.icons._displayTau(); + const scratch = flightState._scratchNearbyPos; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) @@ -372,28 +363,30 @@ export function createQueries({ const nearby = []; - for (const [icao24, bb] of flightState._billboards) { + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); const isTracked = icao24 === flightState._trackedIcao; - // Keep planes rendered as a 3D model (billboard hidden) so proximity counts - // don't drop to zero on the 2D→3D handoff; bb.position stays current while hidden. + const trackedPos = isTracked + ? parts.motion._trackedDisplayCached() + : null; // cached, no recompute (anti-jitter) + const drawn = trackedPos || icons.position(row, tau, 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: billboardState(bb).show, + billboardShown: + icons.shown(row) && + parts.icons._aboveHorizon(row, drawn, occluder), modelRendering: parts.rendering._modelOwnsVisual(icao24), includeHidden, }) ) continue; - const trackedPos = isTracked - ? parts.motion._trackedDisplayCached() - : null; // cached, no recompute (anti-jitter) - const pos = trackedPos || billboardState(bb).position; - if (!pos) continue; - - const distance = Cesium.Cartesian3.distance(center, pos); + const distance = Cesium.Cartesian3.distance(center, drawn); if (distance > maxRange) continue; + const pos = trackedPos || Cesium.Cartesian3.clone(drawn); const info = flightState.records.data.get(icao24); nearby.push({ @@ -434,40 +427,32 @@ export function createQueries({ * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>} */ getDetectableObjects(options = {}) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return []; + const icons = flightState._icons; + if (!icons || !icons.show) return []; const maxCount = Number.isFinite(options.maxCount) ? Math.max(1, Math.floor(options.maxCount)) - : flightState._billboards.size; + : icons.count; const seed = Number.isFinite(options.seed) ? Math.floor(options.seed) : 0; - // Deterministic stride: evenly space selections across the billboard map - const stride = Math.max( - 1, - Math.ceil(flightState._billboards.size / maxCount), - ); + // 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 tau = parts.icons._displayTau(); const result = []; - let idx = 0; - for (const [icao24, bb] of flightState._billboards) { - const shouldTake = (idx - start) % stride === 0; - idx++; - if (!shouldTake) continue; + for (let row = start; row < icons.count; row += stride) { + const icao24 = icons.idAt(row); if ( flightState._cockpitContactMode && icao24.toLowerCase() === flightState._cockpitSubjectId ) continue; const isTracked = icao24 === flightState._trackedIcao; - // Keep planes rendered as a 3D model (billboard hidden) so the detection box - // doesn't vanish on the 2D→3D handoff; bb.position stays current while hidden. + // Keep planes rendered as a 3D model (icon hidden) so the detection box + // doesn't vanish on the 2D→3D handoff. const model = flightState._models.get(icao24); const modelOwnsVisual = parts.rendering._modelOwnsVisual(icao24); - if (!isTracked && !billboardState(bb).show && !modelOwnsVisual) - continue; + if (!isTracked && !icons.shown(row) && !modelOwnsVisual) continue; const info = flightState.records.data.get(icao24); const callsign = info?.callsign?.trim(); const registration = info?.registration?.trim(); @@ -478,18 +463,20 @@ export function createQueries({ type: 'AIR', tier: 'military', _weldPos: new Cesium.Cartesian3(), + _iconPos: new Cesium.Cartesian3(), }; 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; sprite-owned contacts keep `bb.position`, where sprite and bracket - // are co-located anyway. + // modelMatrix; icon-owned contacts keep the drawn icon position, where icon and + // bracket are co-located anyway. const spec = modelOwnsVisual ? parts.rendering._modelSpec(info?.klass) : null; const pos = isTracked - ? parts.motion._trackedVisualCached() || billboardState(bb).position + ? parts.motion._trackedVisualCached() || + icons.position(row, tau, object._iconPos) : modelOwnsVisual ? modelVisualAnchor( modelState(model).modelMatrix, @@ -499,8 +486,15 @@ export function createQueries({ : spec.scale, object._weldPos || (object._weldPos = new Cesium.Cartesian3()), ) - : billboardState(bb).position; - if (!pos) continue; + : icons.position(row, tau, object._iconPos); + // An icon past the horizon is not drawn, so it is not detectable. + if ( + !pos || + (!isTracked && + !modelOwnsVisual && + !parts.icons._aboveHorizon(row, pos, occluder)) + ) + continue; object.position = pos; object.skipLabel = isTracked; const id = callsign || registration || icao24; @@ -519,13 +513,9 @@ export function createQueries({ result.push(object); if (result.length >= maxCount) break; } - if ( - flightState._detectionObjects.size > - flightState._billboards.size + 512 - ) { + if (flightState._detectionObjects.size > icons.count + 512) { for (const icao24 of flightState._detectionObjects.keys()) { - if (!flightState._billboards.has(icao24)) - flightState._detectionObjects.delete(icao24); + if (!icons.has(icao24)) flightState._detectionObjects.delete(icao24); } } return result; @@ -577,8 +567,8 @@ export function createQueries({ /** * Return id/label/position for up to maxCount currently rendered aircraft. - * Cheap snapshot for voice-tool framing — billboard positions only, no - * dead reckoning and no cloning. + * 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: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>} */ @@ -595,34 +585,25 @@ export function createQueries({ * holds no data and therefore cannot answer. */ hasContact(icao24) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show || - flightState._billboards.size === 0 - ) - return null; + const icons = flightState._icons; + if (!icons || !icons.show || icons.count === 0) return null; if (!icao24) return false; const id = String(icao24).trim(); - return ( - flightState._billboards.has(id) || - flightState._billboards.has(id.toLowerCase()) - ); + return icons.has(id) || icons.has(id.toLowerCase()); }, getAllPositions(maxCount = 500) { - if ( - !flightState._billboardCollection || - flightState._billboards.size === 0 - ) - return []; + const icons = flightState._icons; + if (!icons || icons.count === 0) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) : 500; + const tau = parts.icons._displayTau(); const result = []; - for (const [icao24, bb] of flightState._billboards) { - const pos = billboardState(bb).position; - if (!pos) continue; + for (let row = 0; row < icons.count; row++) { + const icao24 = icons.idAt(row); + const pos = icons.position(row, tau); const carto = Cesium.Cartographic.fromCartesian( pos, Cesium.Ellipsoid.WGS84, @@ -657,11 +638,7 @@ export function createQueries({ * @returns {Array} See mapAnalystRecord for the record shape. */ getAnalystRecords(maxCount = 2000) { - if ( - !flightState._billboardCollection || - !flightState._billboardCollection.show || - flightState.records.data.size === 0 - ) + if (!flightState._icons?.show || flightState.records.data.size === 0) return []; const limit = Number.isFinite(maxCount) ? Math.max(1, Math.floor(maxCount)) @@ -682,8 +659,8 @@ export function createQueries({ trackById(icao24, { origin = 'programmatic' } = {}) { if (!icao24) return false; let id = String(icao24).trim(); - if (!flightState._billboards.has(id)) id = id.toLowerCase(); - if (!flightState._billboards.has(id)) return false; + 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) @@ -752,7 +729,7 @@ export function createQueries({ ) return false; let id = String(icao24).trim(); - if (!flightState._billboards.has(id)) id = id.toLowerCase(); + if (!flightState._icons?.has(id)) id = id.toLowerCase(); if ( id !== flightState._trackedIcao || !flightState._viewer.entities?.contains?.(flightState._trackedEntity) || diff --git a/src/layers/military/records.js b/src/layers/military/records.js index 7198d62da1..b92542f5d1 100644 --- a/src/layers/military/records.js +++ b/src/layers/military/records.js @@ -59,14 +59,14 @@ export class MilitaryFlightRecords { // GROUND-SNAP INTERPLAY (brief item 3 — "don't double-correct"): a // grounded plane's MODEL already rides groundSnap.js's one-shot tileset // sample (_modelDisplayPosition), which is the visual on the ground, and - // its billboard is depth-test-free (_groundDepthDistance) so its exact + // its icon is depth-test-free (the icon set draws on the near plane) so its exact // height is cosmetic. Deliberately pass surfaceM=null so // pickRenderAltitudeM's on-ground surface branch never fires here: // 1. It would be the SECOND correction of the same grounded plane // (model tileset-snap is the first) — the exact double-correct the // brief forbids. // 2. Military ground rows carry NO baro ("alt_baro":"ground"), so the - // grounded billboard sits at 0 m until a surface value warms; letting + // grounded icon sits at 0 m until a surface value warms; letting // surfaceM then jump it 0 -> ~surface (often ~100 m) BETWEEN polls // drags the model's ground-snap input past groundSnap's 50 m // move-invalidation threshold and forces a re-sample every time the @@ -95,7 +95,7 @@ export class MilitaryFlightRecords { // ellipsoidal ground (warm-cache read only — the batch warm below // fills cells for later polls). Grounded contacts are deliberately // NOT touched: their model rides groundSnap's tileset sample and - // their billboard is depth-test-free (see the surfaceM:null block + // their icon is depth-test-free (see the surfaceM:null block // above — same one-shot-invariant reasoning). if (!onGround && renderAltitudeM < GROUND_FLOOR_WARM_MAX_ALT_M) { renderAltitudeM = floorAltitudeM( @@ -105,10 +105,10 @@ export class MilitaryFlightRecords { _floorWarmPoints.push({ lat, lon }); } else if (onGround) { // Grounded contacts: warm the floor cell, and — round 4 — when NO - // 3D model owns this contact's visual, lift the billboard itself + // 3D model owns this contact's visual, lift the icon itself // onto the floor (mesh-first): the R20053 heli sat "straight up in // the ground" because grounded rows render at the legacy ~0 m. - // With a model present the billboard stays put (it hides behind + // With a model present the icon stays put (it hides behind // the tileset-snapped model, and moving it would drag groundSnap's // input past its move-invalidation threshold — the T7 one-shot // invariant the track regression locks). diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index 8e8423923c..1d747e6eae 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -9,15 +9,8 @@ import { } from '../../data/modelVisualAnchor.js'; import * as Cesium from 'cesium'; import { selectModelEligible } from '../../data/modelEligibility.js'; -import { cyberSonarBaseAlpha } from '../../cyberSonar.js'; -import { cockpitContactDotImage } from '../../data/cockpitContactDot.js'; -import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js'; -import { - cameraPoseSignature, - horizonOccluder, - screenProjectedRotation, -} from '../../data/iconOrientation.js'; -import { limitCourseStep, courseSlewCapDps } from '../../data/motionModel.js'; +import { horizonOccluder } from '../../data/iconOrientation.js'; +import { aircraftTreatmentAlpha } from '../../data/aircraftRecession.js'; import { isEmergency } from '../../data/aircraftEmergency.js'; import { PLANE_MODEL_SCALE, @@ -31,7 +24,6 @@ import { MODEL_HEADING_OFFSET_DEG, BILLBOARD_SCALE, GROUND_SCALE, - COCKPIT_CONTACT_SIZE_PX, MIL_ICON_COLOR, TRACKED_ICON_COLOR, EMERGENCY_ICON_COLOR, @@ -49,13 +41,9 @@ import { TRACKED_MODEL_MIN_PX, TRACKED_MODEL_MAX_PX, FLEET_DR_INTERVAL_MS, - COURSE_SLEW_DT_MAX_SEC, - ROTATION_REFRESH_MS, - COURSE_MAX_DPS, } from './policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { aircraftVisuals } from '../aircraft/visualState.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; import { modelState, setModel } from '../../data/modelMirror.js'; export function createRendering({ @@ -67,23 +55,8 @@ export function createRendering({ }) { const { tr3bIconKind, isTr3b } = services.aircraftPresentation; const { trackedModelScaleForPixelCap } = services.camera; - const { - focusNowMs, - getFocusTarget, - nearFarScalarValueAtDistance, - advanceProjectedSpriteFocus, - } = services.focus; - const { applyAircraftBillboardTreatment, applyAircraftModelTreatment } = - services.recession; - - /** Depth-test policy for aircraft billboards (mirror of flights.js — see the - * full rationale there). Round 5 (owner directive 2026-07-06): EVERY contact - * renders depth-test-free at every distance — a uniform always-visible rule; - * the fleet tick's horizon occluder still removes far-side contacts. */ - - function _groundDepthDistance() { - return Number.POSITIVE_INFINITY; - } + const { focusNowMs, getFocusTarget } = services.focus; + const { applyAircraftModelTreatment } = services.recession; function _modelSpec(klass) { let spec = flightState._specCache.get(klass); @@ -140,7 +113,9 @@ export function createRendering({ return new Cesium.NearFarScalar(1000, 1.15, 8000000, 0.65); } - function _militaryBillboardScale(icao24) { + /** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */ + + function _fleetBillboardScale(icao24) { const meta = flightState.records.data.get(icao24); return ( BILLBOARD_SCALE * @@ -149,42 +124,7 @@ export function createRendering({ ); } - /** Apply the current normal/cockpit visual contract to one owned fleet billboard. */ - - function _applyFleetBillboardPresentation(icao24, bb) { - if (!bb) return; - const limbScale = flightState._billboardLimbScale.get(bb) ?? 1; - const isCockpitContact = - flightState._cockpitContactMode && icao24 !== flightState._trackedIcao; - const isCockpitNear = - isCockpitContact && flightState._cockpitNearContacts.has(icao24); - if (isCockpitContact && !isCockpitNear) { - const freshnessAlpha = cyberSonarBaseAlpha(bb); - bb.image = cockpitContactDotImage(); - setBillboard(bb, 'width', COCKPIT_CONTACT_SIZE_PX); - setBillboard(bb, 'height', COCKPIT_CONTACT_SIZE_PX); - setBillboard(bb, 'scale', limbScale); - setBillboard(bb, 'scaleByDistance', _cockpitBillboardScaleByDistance()); - bb.color = _fleetBillboardColor(icao24).withAlpha(freshnessAlpha); - setBillboard(bb, 'rotation', 0); - return; - } - - const meta = flightState.records.data.get(icao24); - bb.image = aircraftIcon( - _iconKind(icao24, meta?.klass), - aircraftVisuals.read(bb)?.iconLarge ? TRACKED_ICON_PX : undefined, - ); - setBillboard(bb, 'width', icao24 === flightState._trackedIcao ? 24 : 20); - setBillboard(bb, 'height', icao24 === flightState._trackedIcao ? 24 : 20); - setBillboard(bb, 'scale', _militaryBillboardScale(icao24) * limbScale); - setBillboard(bb, 'scaleByDistance', _normalBillboardScaleByDistance()); - bb.color = _fleetBillboardColor(icao24, meta).withAlpha( - cyberSonarBaseAlpha(bb), - ); - } - - /** Sprite kind for one contact's billboard. Identity for every aircraft except + /** Sprite kind for one contact's icon. Identity for every aircraft except * the ones the operator converted into a TR-3B (Easter egg), which draw the * black-triangle glyph — its thermal-reactive variant while an IR style owns * the scene. Routing EVERY `aircraftIcon()` call through this is what makes a @@ -210,6 +150,10 @@ export function createRendering({ return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MIL_ICON_COLOR; } + /** Cockpit far-contact pips wear the fleet tint. */ + + const _cockpitContactColor = _fleetBillboardColor; + /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in @@ -280,12 +224,12 @@ export function createRendering({ /** Everything scene.sampleHeight must NOT hit when snapping a grounded model (mirror of * flights.js): the vertical pick ray at a plane's own lat/lon otherwise lands on its - * (or a parked neighbor's) billboard/model instead of the tile skin. Exclusion matches - * picked-object IDs — every billboard AND model here carries its icao as `id` — plus + * (or a parked neighbor's) icon/model instead of the tile skin. Exclusion matches + * picked-object IDs — every icon AND model here carries its icao as `id` — plus * the tracked entity object itself. Built lazily, only when a sample actually fires. */ function _groundSampleExclusions() { - const out = [...flightState._billboards.keys()]; + const out = parts.icons._iconIds(); if (flightState._trackedEntity) out.push(flightState._trackedEntity); return out; } @@ -295,7 +239,7 @@ export function createRendering({ * (groundSnap.js; taxiing >50 m retires it to a bounded last-known) plus the belly * offset so they sit on their * gear; airborne planes pass through. Until the FIRST sample lands, callers keep the - * depth-test-free billboard visible and the model hidden while this returns null; a + * icon visible and the model hidden while this returns null; a * contact that has already resolved once holds that measurement through a later * outage inside groundSnap's drift bound, so taxiing does not pop it back to 2D. */ @@ -324,15 +268,23 @@ export function createRendering({ ); } - /** Atomically hand one fleet contact from its billboard to a safely placed, + /** Atomically hand one fleet contact from its icon to a safely placed, * ready 3D model. Missing/loading models and unresolved terrain always leave - * the billboard owning the visual, so no render frame can hide both. + * the icon owning the visual, so no render frame can hide both. * `beforeShow` runs only on the committing path — the per-tick model treatment * belongs to a model that is about to draw, not to one still waiting. */ - function _driveFleetModelHandoff(icao24, model, bb, pos, course, beforeShow) { + function _driveFleetModelHandoff( + icao24, + model, + row, + pos, + course, + beforeShow, + ) { + const icons = flightState._icons; if (!model) { - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } const displayPos = _modelDisplayPosition( @@ -342,7 +294,7 @@ export function createRendering({ ); if (!displayPos) { setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } // The matrix is written BEFORE the readiness test on purpose: a model can flip @@ -361,12 +313,12 @@ export function createRendering({ ); if (!model.ready) { setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash - setBillboard(bb, 'show', true); + icons.setShown(row, true); return false; } beforeShow?.(); if (!modelState(model).show) setModel(model, 'show', true); - if (billboardState(bb).show) setBillboard(bb, 'show', false); // hand off ONLY once the model renders + icons.setShown(row, false); // hand off ONLY once the model renders return true; } @@ -402,7 +354,7 @@ export function createRendering({ /** Class-change model sync — mirror of flights.js: drop a live model or * in-flight load whose spec no longer matches the class, re-showing the - * fleet billboard FIRST (gap-proof) and covering the tracked standalone. */ + * fleet icon (on release, gap-proof) and covering the tracked standalone. */ function _syncModelToClass(icao24) { const key = _specKeyFor(flightState.records.data.get(icao24)?.klass); @@ -411,9 +363,6 @@ export function createRendering({ (current && aircraftVisuals.read(current)?.specKey !== key) || (!current && flightState._modelPending.has(icao24)) ) { - const bb = flightState._billboards.get(icao24); - if (bb && icao24 !== flightState._trackedIcao) - setBillboard(bb, 'show', true); _releaseModel(icao24); } if ( @@ -447,16 +396,13 @@ export function createRendering({ aircraftVisuals.read(model)?.irBoost === flightState._irBoost ) continue; // already right state - const bb = flightState._billboards.get(icao); - if (bb && icao !== flightState._trackedIcao) - setBillboard(bb, 'show', true); _releaseModel(icao); } if (flightState._irReloadQueue.length === 0) flightState._irReloadQueue = null; } - /** Lazily create the glTF model for an aircraft (fire-and-forget; billboard shows until ready). */ + /** Lazily create the glTF model for an aircraft (fire-and-forget; its icon shows until ready). */ async function _ensureModel(icao24) { // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet @@ -501,7 +447,7 @@ export function createRendering({ id: icao24, // so scene.pick returns the icao for click-to-track }); } catch { - // asset/decode fail — stay billboard. Only touch this lifecycle's state if still current + // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current // (a destroy/re-init may have swapped the globals while this load was in flight). if (epoch === flightState._modelEpoch) { flightState._modelPending.delete(icao24); @@ -554,7 +500,7 @@ export function createRendering({ visual.specKey = specKey; // class-change sync compares against this visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this // Admitted, not yet the visual. Cesium's default is show=true, which would let - // an unplaced primitive claim ownership from the billboard for the frames + // an unplaced primitive claim ownership from the icon for the frames // between admission and the next fleet tick (and draw at the identity matrix, // i.e. the Earth's centre). The handoff turns it on once it has a matrix. setModel(model, 'show', false); @@ -589,6 +535,7 @@ export function createRendering({ } } flightState._models.delete(icao24); + _showReleasedIcon(icao24); } // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so @@ -607,7 +554,7 @@ export function createRendering({ flightState._modelGen.delete(icao24); } - /** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */ + /** Remove all live models (toggle-off / zoom-out); icons take back over at once. */ function _releaseModels() { flightState._irReloadQueue = null; // a full release supersedes any pending boost-flip drain @@ -629,9 +576,20 @@ export function createRendering({ } } } + for (const icao24 of flightState._models.keys()) _showReleasedIcon(icao24); flightState._models.clear(); } + /** A released fleet model hands the visual straight back to its icon (the + * tracked contact's entity keeps its own). */ + + function _showReleasedIcon(icao24) { + const icons = flightState._icons; + const row = icons?.row(icao24) ?? -1; + if (row >= 0 && icao24 !== flightState._trackedIcao) + icons.setShown(row, true); + } + /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ function _releaseTrackedModel() { @@ -672,8 +630,7 @@ export function createRendering({ // readout consumers then reuse that exact cached position. const pos = parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - billboardState(flightState._billboards.get(flightState._trackedIcao)) - ?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (!pos) { if (flightState._trackedModel) setModel(flightState._trackedModel, 'show', false); @@ -750,9 +707,7 @@ export function createRendering({ // default here produces a one-frame jump to the Earth's center. const currentPos = parts.motion._trackedDisplayCached() || - billboardState( - flightState._billboards.get(flightState._trackedIcao), - )?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (currentPos) { const displayPos = _modelDisplayPosition( flightState._trackedIcao, @@ -832,57 +787,38 @@ export function createRendering({ } /** - * Per-preRender fleet pass at ~12Hz: dead-reckons every untracked billboard, - * horizon-culls billboards beyond the limb (no far-side depth with the globe - * hidden), and refreshes screen-projected icon rotations whenever the camera - * pose changed (plus a 1s drift catch-up while idle). Driven by - * scene.preRender — NOT camera.changed, whose granularity is globally - * degraded by other layers mutating camera.percentageChanged. + * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and + * the two-tier glyph swap all run on the GPU from each row's segment, so this + * only re-plans rows whose regime ended, advances focus de-emphasis while a + * target exists, and drives the 3D-model handoff inside the model regime. + * Driven by scene.preRender. * @returns {void} */ function _fleetTick() { - if ( - !flightState._viewer || - !flightState._billboardCollection || - !flightState._billboardCollection.show - ) - return; + const icons = flightState._icons; + if (!flightState._viewer || !icons || !icons.show) return; const scene = flightState._viewer.scene; const camera = flightState._viewer.camera; const nowMs = focusNowMs(Date.now()); - // (The tracked trail head is now the per-frame _trailHeadEntity segment — no 1 Hz - // primitive rebuild here. The body rebuilds only when a real fix arrives.) - if (nowMs - flightState._lastFleetTickMs < FLEET_DR_INTERVAL_MS) return; - const tickDtSec = flightState._lastFleetTickMs - ? Math.min( - COURSE_SLEW_DT_MAX_SEC, - (nowMs - flightState._lastFleetTickMs) / 1000, - ) - : 0.08; flightState._lastFleetTickMs = nowMs; + // Every contact in this pass shares the same delayed display instant. + const renderTime = parts.icons._displayTime( + flightState._scratchFleetRenderTime, + ); + const tau = icons.seconds(renderTime); _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload if (flightState._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); - const poseSig = cameraPoseSignature(camera); - // Only nearby Cockpit silhouettes need projected course; far dots remain - // rotation-free through the per-contact gate below. - const doRotations = - poseSig !== flightState._lastCamPoseSig || - nowMs - flightState._lastRotPassMs >= ROTATION_REFRESH_MS; - if (doRotations) { - flightState._lastCamPoseSig = poseSig; - flightState._lastRotPassMs = nowMs; - } - - const occluder = horizonOccluder(camera); + parts.icons._replanExpired(tau); const focusTarget = getFocusTarget(); + parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget); // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. - // Drop all models the moment we leave it (toggled off / zoomed out) so billboards resume. + // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. const useModels = _modelRegimeActive(); // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that // resolves after zoom-out could briefly add a model outside the 3D-model regime). @@ -891,240 +827,133 @@ export function createRendering({ (flightState._models.size || flightState._modelPending.size) ) _releaseModels(); + if (!useModels) return; - // 3D-model eligibility: by DISTANCE (mode's add/keep band) with ON-SCREEN PRIORITY under the cap — - // mirror of flights.js. FOUR visible-first passes: (1) KEEP on-screen modeled; (2) ADD on-screen - // new in add radius; (3) KEEP off-screen modeled; (4) ADD off-screen new with leftover slots. KEEP - // is split by frustum so an off-screen retained model can't starve an on-screen plane (review finding). - let modelEligible = null; - if (useModels) { - const cap = _modelCap(); - const camPos = camera.positionWC; - const addM = _modelAddDistM(); - const addDistSq = addM * addM; - const keepM = _modelKeepDistM(); - const keepDistSq = keepM * keepM; - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, + // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the + // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen + // already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius, + // nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots + // (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint). + // Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an + // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap + // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum + // filtering dropped near off-screen planes entirely. This does both right. + const cap = _modelCap(); + const camPos = camera.positionWC; + const addM = _modelAddDistM(); + const addDistSq = addM * addM; + const keepM = _modelKeepDistM(); + const keepDistSq = keepM * keepM; + const cull = camera.frustum.computeCullingVolume( + camPos, + camera.directionWC, + camera.upWC, + ); + // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. + const cand = []; + for (let row = 0; row < icons.count; row++) { + const icao = icons.idAt(row); + if (icao === flightState._trackedIcao) continue; + // A converted TR-3B renders as an icon and can never take a model, so + // it must not occupy a CAP SLOT either — excluded here at selection time, + // not just at the handoff below, or accumulated conversions would starve + // ordinary contacts of 3D models. (The handoff guard stays as defence.) + if (isTr3b(icao)) continue; + // Ground planes compete for model slots like everyone else (owner decision + // 2026-07-03: "3D mode is respected regardless of whether a plane is on the + // ground or in the air — no distinction"). The cap + nearest-first ordering + // below already bound airport clusters; grounded placement is handled by the + // one-shot ground snap in _modelDisplayPosition. + const position = icons.position( + row, + tau, + flightState._scratchModelBS.center, ); - const cand = []; - for (const [icao, bb] of flightState._billboards) { - if (icao === flightState._trackedIcao) continue; - // A converted TR-3B renders as a billboard and can never take a model, so - // it must not occupy a CAP SLOT either (mirror of flights.js) — excluded - // at selection time, not just at the handoff below. - if (isTr3b(icao)) continue; - // Ground planes compete for model slots like everyone else (owner decision - // 2026-07-03, mirror of flights.js — no air/ground distinction; grounded - // placement is handled by the one-shot ground snap in _modelDisplayPosition). - const { position } = billboardState(bb); - const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); - if (d2 > keepDistSq) continue; // beyond keep radius → never eligible - Cesium.Cartesian3.clone(position, flightState._scratchModelBS.center); - cand.push([ - icao, - d2, - cull.computeVisibility(flightState._scratchModelBS) !== - Cesium.Intersect.OUTSIDE, - ]); - } - cand.sort((a, b) => a[1] - b[1]); - if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { - console.warn( - `[Data:Military] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen prioritized.`, - ); - flightState._lastModelCapWarnMs = nowMs; - } - modelEligible = selectModelEligible(cand, { - cap, - addDistSq, - isModeled: (icao) => flightState._models.has(icao), - }); - const toRelease = []; - for (const icao of flightState._models.keys()) { - if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) - toRelease.push(icao); - } - for (const icao of toRelease) _releaseModel(icao); + const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); + if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible + cand.push([ + icao, + d2, + cull.computeVisibility(flightState._scratchModelBS) !== + Cesium.Intersect.OUTSIDE, + ]); } - - for (const [icao24, bb] of flightState._billboards) { - if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion - const icon = billboardState(bb); - - const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos); - // Gate the write — assigning Billboard.position dirties the whole - // collection's vertex buffer, so skip sub-meter moves. - if (dr && Cesium.Cartesian3.distanceSquared(dr, icon.position) > 1.0) { - setBillboard(bb, 'position', dr); - } - - // Round 6: occlusion-test a LIFTED point for contacts at/below the - // ellipsoid (mirror of flights.js — sub-ellipsoid points near the limb - // read "beyond the horizon" and would hide low contacts awaiting floors). - const beyondHorizon = !occluder.isPointVisible( - flightState.records.data.get(icao24)?.cullPosition || icon.position, + cand.sort((a, b) => a[1] - b[1]); // nearest first + if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { + console.warn( + `[Data:Military] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`, ); - // A billboard flipping INTO view (horizon reveal while the camera idles) - // gets its rotation refreshed THIS tick even without a pose change — - // otherwise it reappears wearing its stale (often creation-north) nose for - // up to ROTATION_REFRESH_MS. (Model-handed-off planes also read show=false - // here; harmless — the model branch below `continue`s past the rotation.) - const revealed = !beyondHorizon && !icon.show; - if (icon.show === beyondHorizon) setBillboard(bb, 'show', !beyondHorizon); - if (beyondHorizon) { - // Also hide any 3D model — otherwise a model that crossed the limb would keep - // rendering through the hidden globe at its last matrix. + flightState._lastModelCapWarnMs = nowMs; + } + const modelEligible = selectModelEligible(cand, { + cap, + addDistSq, + isModeled: (icao) => flightState._models.has(icao), + }); + const toRelease = []; + for (const icao of flightState._models.keys()) { + if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) + toRelease.push(icao); + } + for (const icao of toRelease) _releaseModel(icao); + + // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown + // until the model is actually READY to render, so a plane is never both iconless AND + // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick + // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on + // purpose: the Easter egg IS the triangle, and there is no GLB for it. + const occluder = horizonOccluder(camera); + for (const icao24 of modelEligible) { + if (isTr3b(icao24)) continue; + const row = icons.row(icao24); + if (row < 0) continue; + const position = icons.position(row, tau, flightState._scratchFleetPos); + if (!parts.icons._aboveHorizon(row, position, occluder)) { + // A model that crossed the limb would keep rendering through the + // hidden globe at its last matrix; the icon's own cull is on the GPU. const m = flightState._models.get(icao24); if (m && modelState(m)?.show) setModel(m, 'show', false); continue; } - - const info = flightState.records.data.get(icao24); - - // One sprite-owned write site composes freshness × focus × limb haze and - // base class/ground scale × limb taper. The locked NearFarScalar remains - // untouched and multiplicative; there is no cull or zero-alpha path. - const cameraDistanceM = Cesium.Cartesian3.distance( - camera.positionWC, - icon.position, + _ensureModel(icao24); + const model = flightState._models.get(icao24); + const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); + _driveFleetModelHandoff( + icao24, + model, + row, + position, + icons.course(row, tau), + () => { + applyAircraftModelTreatment({ + model, + // IR boost must survive the per-tick treatment write — otherwise + // any alpha change would repaint the ordinary tint over the hot + // white. Boosted models also skip the recession fade: hot targets + // stay full-strength at any range (icons keep their normal + // fade — full-opacity glyph walls read as overwhelming). + baseColor: flightState._irBoost + ? Cesium.Color.WHITE + : _modelColor(icao24), + alpha: flightState._irBoost + ? 1 + : aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(row), + focusFactor: icons.focus(row), + cameraDistanceM, + cameraHeightM: camera.positionCartographic?.height, + }), + }); + }, ); - const distanceScale = nearFarScalarValueAtDistance( - icon.scaleByDistance, - cameraDistanceM, - ); - const focus = advanceProjectedSpriteFocus( - bb, - icon.position, - scene, - camera, - nowMs, - focusTarget, - undefined, - (icon.width || 20) * (icon.scale || 1) * distanceScale * 0.5, - (icon.height || 20) * (icon.scale || 1) * distanceScale * 0.5, - ); - const isCockpitNear = - flightState._cockpitContactMode && - flightState._cockpitNearContacts.has(icao24); - const baseColor = _fleetBillboardColor(icao24, info); - const treatment = applyAircraftBillboardTreatment({ - billboard: bb, - baseScale: - flightState._cockpitContactMode && !isCockpitNear - ? 1 - : _militaryBillboardScale(icao24), - baseAlpha: flightState.records.missingPolls.get(icao24) ? 0.45 : 1, - baseColor, - focusFactor: focus.factor, - cameraDistanceM, - cameraHeightM: camera.positionCartographic?.height, - }); - flightState._billboardLimbScale.set(bb, treatment.factors.scale); - // Two-tier glyph raster — mirror of flights.js: swap 64/192 px rasters on - // the billboard's ACTUAL on-screen size (post-treatment bb.scale, so - // focus/limb recession counts) with hysteresis (atlas has no mips). - if (!flightState._cockpitContactMode || isCockpitNear) { - const glyphDevPx = - (icon.width || 20) * - (icon.scale || 1) * - distanceScale * - (globalThis.devicePixelRatio || 1); - const visual = aircraftVisuals.write(bb); - const wantLarge = visual.iconLarge ? glyphDevPx > 56 : glyphDevPx > 76; - if (wantLarge !== !!visual.iconLarge) { - visual.iconLarge = wantLarge; - bb.image = aircraftIcon( - _iconKind(icao24, flightState.records.data.get(icao24)?.klass), - wantLarge ? TRACKED_ICON_PX : undefined, - ); - } - } - - // Smoothed display course: the path direction _deadReckon just reported - // for THIS aircraft (nothing else calls _deadReckon in between), rate- - // limited so segment-boundary course steps glide instead of snapping. - // The slew cap eases toward COURSE_MIN_DPS at low speed, and a hovering - // aircraft (hold flag) keeps its previous nose direction outright. - const rawCourse = - flightState._drCourseDeg != null - ? flightState._drCourseDeg - : (info && info.track) || 0; - const prevCourse = flightState._displayCourse.get(icao24); - const course = - flightState._drCourseHold && prevCourse != null - ? prevCourse - : limitCourseStep( - prevCourse, - rawCourse, - courseSlewCapDps( - flightState._drSpeedMps != null - ? flightState._drSpeedMps - : ((info && info.speedMps) ?? NaN), - COURSE_MAX_DPS, - ), - tickDtSec, - ); - flightState._displayCourse.set(icao24, course); - - // 3D model takes over from the billboard for in-view planes (modelEligible). GAP-PROOF: the - // billboard stays shown until the model is actually READY to render, so a plane is never both - // iconless AND modelless (the "planes vanish when 3D turns on" bug). Position the model every - // tick regardless so it's framed the instant it becomes ready. - // Converted TR-3Bs stay 2D on purpose (mirror of flights.js): the Easter - // egg IS the triangle and there is no GLB for it, so the model handoff is - // suppressed. The billboard keeps rendering, so the contact still satisfies - // the getNearby/getDetectableObjects visibility guards. - if (useModels && dr && modelEligible.has(icao24) && !isTr3b(icao24)) { - _ensureModel(icao24); - const model = flightState._models.get(icao24); - const ownsVisual = _driveFleetModelHandoff( - icao24, - model, - bb, - dr, - course, - () => { - applyAircraftModelTreatment({ - model, - // IR boost must survive the per-tick treatment write; boosted - // models also skip the recession fade (mirror of flights.js — - // billboards keep their normal fade, hot MODELS stay full-strength). - baseColor: flightState._irBoost - ? Cesium.Color.WHITE - : _modelColor(icao24), - alpha: flightState._irBoost ? 1 : treatment.alpha, - }); - }, - ); - if (ownsVisual) continue; // skip billboard rotation - } - - if ( - (!flightState._cockpitContactMode || isCockpitNear) && - (doRotations || revealed) - ) { - const rot = screenProjectedRotation( - scene, - icon.position, - course, - icon.rotation, - ); - if (rot !== null && Math.abs(rot - icon.rotation) > 0.002) { - setBillboard(bb, 'rotation', rot); - } - } } } return { - _groundDepthDistance, _modelSpec, _normalBillboardScaleByDistance, _cockpitBillboardScaleByDistance, - _militaryBillboardScale, - _applyFleetBillboardPresentation, + _fleetBillboardScale, + _cockpitContactColor, _iconKind, _modelColor, _fleetBillboardColor, diff --git a/src/layers/military/snapshotRenderer.js b/src/layers/military/snapshotRenderer.js index 5473595598..f1ad8f1829 100644 --- a/src/layers/military/snapshotRenderer.js +++ b/src/layers/military/snapshotRenderer.js @@ -1,15 +1,10 @@ import * as Cesium from 'cesium'; -import { cyberSonarBaseAlpha } from '../../cyberSonar.js'; -import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { turnRateFromFixHistory, liftRepeatedGroundFix, synthesizeForwardKinematicsFix, } from '../../data/motionModel.js'; -import { aircraftIcon } from '../../data/aircraftIcons.js'; import { POSITION_HISTORY_LIMIT } from './recordPolicy.js'; -import { BILLBOARD_SCALE, GROUND_SCALE, TRACKED_ICON_COLOR } from './policy.js'; -import { addBillboard, setBillboard } from '../../data/billboardMirror.js'; /** Apply military record changes to Cesium resources and existing follow operations. */ export function createMilitarySnapshotRenderer({ @@ -20,7 +15,7 @@ export function createMilitarySnapshotRenderer({ militaryRegistry, rendering, tracking, - motion, + icons, queries, }) { const { warmGroundFloor, cachedGroundFloor, GROUND_FLOOR_LIFT_M } = @@ -28,6 +23,8 @@ export function createMilitarySnapshotRenderer({ const { sampleMeshFloorCells } = meshFloor; const { registerMilitaryIcaos } = militaryRegistry; return function applySnapshot(snapshot, viewer) { + // Before init (or after destroy) there is no icon set to draw into. + if (!flightState._icons) return { count: 0, ids: new Set() }; const currentIcaos = new Set(); const receiptNowMs = snapshot.observedAtMs; // Field-test fix (RS46): coarse floor cells to warm for the below-ground @@ -55,12 +52,6 @@ export function createMilitarySnapshotRenderer({ meta.renderAltitudeM, ); if (groundFlipped) flightState._groundSnap.forget(icao24); - flightState._cullPositions.set( - icao24, - meta.renderAltitudeM < 10 - ? Cesium.Cartesian3.fromDegrees(meta.rawLon, meta.rawLat, 12) - : null, - ); const isTracked = icao24 === flightState._trackedIcao; // Append to position history stamped with the FEED's fix epoch. @@ -120,63 +111,19 @@ export function createMilitarySnapshotRenderer({ } } - if (flightState._billboards.has(icao24)) { - const bb = flightState._billboards.get(icao24); - if (!isTracked) { - bb.color = rendering - ._fleetBillboardColor(icao24, meta) - .withAlpha(cyberSonarBaseAlpha(bb)); - } - // Position AND rotation are owned by the fleet pass (_fleetTick); - // course changes land on the next rotation pass (forced below). - // Ground flips (landing/takeoff) restyle this SAME billboard in - // place — the transition is never a removal. - if ( - prevMeta?.klass !== meta.klass || - groundFlipped || - flightState._cockpitContactMode - ) { - rendering._applyFleetBillboardPresentation(icao24, bb); - } + if (flightState._icons.has(icao24)) { + // Reclassification, a ground flip (a restyle, never a removal), a + // freshness change and the cockpit contract all land on the row's + // style; motion re-plans from the updated history. + icons._applyIconPresentation(icao24); + icons._planIcon(icao24); // Per-class GLBs: a class change can mean a different asset OR scale — // resync the live model, any in-flight load, and the tracked // standalone (mirror of flights.js). if (prevMeta?.klass !== meta.klass) rendering._syncModelToClass(icao24); - // Round 5: depth policy is uniform (always depth-test-free, see - // _groundDepthDistance) — nothing to flip on landing/takeoff. } else { - // Start where the fleet pass will draw it: the fleet renders behind - // real time, so a fresh contact's displayed position is its fix - // projected back to that delayed time. Creating it at the raw fix drew - // it ahead until the next fleet tick snapped it back. - const displayed = - motion._deadReckon(icao24, new Cesium.Cartesian3()) || position; - const bb = addBillboard(flightState._billboardCollection, { - position: displayed, - image: aircraftIcon(rendering._iconKind(icao24, meta.klass)), - width: isTracked ? 24 : 20, - height: isTracked ? 24 : 20, - scale: - BILLBOARD_SCALE * - (CLASS_SCALE_2D[meta.klass] || 1) * - (meta.onGround ? GROUND_SCALE : 1), - // Screen-projected rotation lands on the next fleet tick. - rotation: 0, - alignedAxis: Cesium.Cartesian3.ZERO, - color: isTracked - ? TRACKED_ICON_COLOR - : rendering._fleetBillboardColor(icao24, meta), - sizeInMeters: false, - scaleByDistance: rendering._normalBillboardScaleByDistance(), - // Grounded/near-surface planes sit at/below the photoreal tile - // surface — render them depth-test-free so they never vanish up - // close (_groundDepthDistance). - disableDepthTestDistance: rendering._groundDepthDistance(), - id: icao24, - show: !isTracked, // hidden if currently tracked (entity replaces it) - }); - flightState._billboards.set(icao24, bb); - rendering._applyFleetBillboardPresentation(icao24, bb); + // Hidden while tracked: the tracked entity replaces it. + icons._addIcon(icao24); } // Takeoff while TRACKED: ground traffic drew no trail, so start one @@ -200,7 +147,7 @@ export function createMilitarySnapshotRenderer({ // 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 billboard would + // 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; @@ -216,7 +163,6 @@ export function createMilitarySnapshotRenderer({ ) continue; info.renderAltitudeM = lifted; - flightState._cullPositions.delete(icao24); const liftedPos = Cesium.Cartesian3.fromDegrees( info.rawLon, info.rawLat, @@ -226,18 +172,20 @@ export function createMilitarySnapshotRenderer({ const newest = hist?.[hist.length - 1]; if (newest) newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position); - const bbStale = flightState._billboards.get(icao24); - if (bbStale) setBillboard(bbStale, 'position', liftedPos); + if (flightState._icons.has(icao24)) { + icons._applyIconPresentation(icao24); + icons._planIcon(icao24); + } } // 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 billboards/models from the probe. + // this layer's own icons/models from the probe. { const viewerCarto = flightState._viewer?.camera?.positionCartographic || null; sampleMeshFloorCells(flightState._viewer?.scene, _floorWarmPoints, { excludeObjects: [ - ...flightState._billboards.values(), + ...icons._iconIds(), ...flightState._models.values(), flightState._trackedModel, ].filter(Boolean), @@ -256,8 +204,12 @@ export function createMilitarySnapshotRenderer({ // EXCEPTION: likely-landed planes (last fix low + slow) get only // LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a // feed gap, and the full grace left phantom planes parked at airports. - for (const [icao24, bb] of flightState._billboards) { - if (currentIcaos.has(icao24)) continue; + const absentIds = []; + for (let row = 0; row < flightState._icons.count; row++) { + const icao24 = flightState._icons.idAt(row); + if (!currentIcaos.has(icao24)) absentIds.push(icao24); + } + for (const icao24 of absentIds) { const absence = records.absence(icao24, { complete: snapshot.complete, retainIds: snapshot.retainIds, @@ -265,8 +217,9 @@ export function createMilitarySnapshotRenderer({ }); if (absence === 'retain') continue; if (absence === 'stale') { + icons._applyIconPresentation(icao24); // the faded freshness alpha if (icao24 === flightState._trackedIcao && flightState._trackedEntity) { - // Honest readout: the tracked plane has no faded billboard (its + // Honest readout: the tracked plane has no faded icon (its // entity owns the visual), so refresh the label — with icao24 now // in _missingPolls, _buildTrackedLabel appends the STALE cue so // last-known altitude/speed aren't presented as live. @@ -277,7 +230,7 @@ export function createMilitarySnapshotRenderer({ // If the tracked flight is truly gone, clear tracking BEFORE deleting // its state (M3 ordering, keep it): teardown reads the maps this loop - // is about to delete (billboard restore, DR cache reset), and we must + // is about to delete (icon restore, DR cache reset), and we must // never leave the camera mid-follow with stale tracking state. The // camera is then RELEASED IN PLACE — it stays where the follow left // it, fully free (owner decision 2026-07-02: no overview flyTo). @@ -285,22 +238,12 @@ export function createMilitarySnapshotRenderer({ tracking._clearTracking(false, { evicted: true }); } - flightState._billboardCollection.remove(bb); - flightState._billboards.delete(icao24); - rendering._releaseModel(icao24); // aged-out aircraft: drop its 3D model (no orphan / cap leak) - records.forget(icao24); - flightState._cullPositions.delete(icao24); - flightState._positionHistory.delete(icao24); - flightState._displayCourse.delete(icao24); - flightState._groundSnap.forget(icao24); + icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak) } - // Fresh courses arrived — force a rotation pass on the next fleet tick - flightState._lastCamPoseSig = ''; - // Feed the shared registry so the flights layer can classify/suppress registerMilitaryIcaos(currentIcaos); - return { count: flightState._billboards.size, ids: currentIcaos }; + return { count: flightState._icons.count, ids: currentIcaos }; }; } diff --git a/src/layers/military/state.js b/src/layers/military/state.js index f1a2d691f5..8b71c22994 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -10,7 +10,6 @@ export function createFlightState({ source, services }) { ...services.geoid, ...services.groundFloor, }); - flightState._cullPositions = new Map(); /** Per-class model spec for THIS layer (2026-08-16, owner playtest ask: * military contacts should read as their WEIGHT CLASS, always in this layer's @@ -87,22 +86,24 @@ export function createFlightState({ source, services }) { new Cesium.Cartesian3(), 1.0, ); - // frustum-visibility test - /** Last limb taper per billboard, retained across class/ground/cockpit repaints. */ - - flightState._billboardLimbScale = new WeakMap(); // --------------------------------------------------------------------------- // Module-level state // --------------------------------------------------------------------------- - /** @type {Cesium.BillboardCollection|null} Single GPU-batched collection for all aircraft */ + /** Every contact's icon row (see icons.js); null outside a layer lifetime. */ - flightState._billboardCollection = null; + flightState._icons = null; - /** @type {Map} ICAO hex -> billboard primitive */ + /** The primitive drawing `_icons`. */ - flightState._billboards = new Map(); + flightState._iconPrimitive = null; + + flightState._scratchIconRenderTime = new Cesium.JulianDate(); + + /** Rows still away from full focus emphasis after the last focus pass. */ + + flightState._iconFocusActive = 0; /** Stable lightweight records reused by the detection overlay between polls. */ @@ -187,14 +188,6 @@ export function createFlightState({ source, services }) { flightState._lastFleetTickMs = 0; - /** @type {string} Camera pose signature at the last rotation pass */ - - flightState._lastCamPoseSig = ''; - - /** @type {number} Epoch ms of the last full rotation pass */ - - flightState._lastRotPassMs = 0; - /** @type {number} Last computed rotation for the tracked entity (radians) */ flightState._lastTrackedRotation = 0; @@ -225,8 +218,14 @@ export function createFlightState({ source, services }) { flightState._scratchRenderTime = new Cesium.JulianDate(); + flightState._scratchFleetRenderTime = new Cesium.JulianDate(); + flightState._scratchFleetPos = new Cesium.Cartesian3(); + flightState._scratchCockpitPos = new Cesium.Cartesian3(); + + flightState._scratchNearbyPos = new Cesium.Cartesian3(); + flightState._scratchSonarScreen = new Cesium.Cartesian2(); flightState._scratchDrRaw = new Cesium.Cartesian3(); diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index 5af1140df0..b67ab72992 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -1,6 +1,8 @@ +import * as Cesium from 'cesium'; import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js'; -import { mirrorBillboard } from '../../data/billboardMirror.js'; import { mirrorModel } from '../../data/modelMirror.js'; +import { createIconSet } from '../../data/iconSet.js'; +import { aircraftIconTestSeams } from '../../data/aircraftIconLayer.js'; export function createTesting({ flightState, @@ -9,6 +11,8 @@ export function createTesting({ layer, resolveAsset, }) { + const { _seedIconForTest, _iconForTest, _setIconForTest } = + aircraftIconTestSeams(flightState, parts, 'military'); /** * Seed only the mutable state needed to exercise tracked-card refreshes through * the production military poll reconciler. Tests still call @@ -17,13 +21,14 @@ export function createTesting({ * @param {string} state.icao24 * @param {object} state.entity * @param {object} state.meta - * @param {object} state.billboard - * @param {object} state.billboardCollection + * @param {{position?: Cesium.Cartesian3, show?: boolean}} [state.billboard] + * Where the contact's icon is held, and whether it is shown. + * @param {{show?: boolean}} [state.billboardCollection] Layer visibility. * @param {object} state.viewer * @param {Array} [state.history=[]] * @param {boolean} [state.tracked=true] * @param {Iterable<[string, object]>} [state.models=[]] - Fleet 3D models keyed - * by icao24, for the billboard-hidden/model-shown handoff state. + * by icao24, for the icon-hidden/model-shown handoff state. */ function _setTrackedMilitaryRefreshStateForTest({ @@ -40,9 +45,11 @@ export function createTesting({ }) { flightState._viewer = viewer; flightState._modelCollection = modelCollection; - flightState._billboardCollection = billboardCollection; - flightState._billboards = new Map([[icao24, mirrorBillboard(billboard)]]); - flightState._cullPositions.clear(); + flightState._icons = createIconSet({ + epoch: parts.icons._displayTime(new Cesium.JulianDate()), + }); + flightState._icons.show = billboardCollection?.show ?? true; + _seedIconForTest(icao24, billboard, tracked); flightState._models.clear(); for (const [key, model] of models) flightState._models.set(key, mirrorModel(model)); @@ -89,7 +96,7 @@ export function createTesting({ billboard, history = [], }) { - flightState._billboards.set(icao24, mirrorBillboard(billboard)); + _seedIconForTest(icao24, billboard, false); flightState.records.data.set(icao24, meta); flightState._positionHistory.set(icao24, history); } @@ -135,13 +142,13 @@ export function createTesting({ : TRACKED_ICON_COLOR; } - /** Drive the exact fleet billboard-to-model handoff used by `_fleetTick`. */ + /** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */ function _driveFleetModelHandoffForTest({ icao24, position, course = 0 }) { return parts.rendering._driveFleetModelHandoff( icao24, flightState._models.get(icao24), - flightState._billboards.get(icao24), + flightState._icons.row(icao24), position, course, ); @@ -153,6 +160,7 @@ export function createTesting({ await parts.rendering._ensureModel(icao24); return flightState._models.get(icao24) || null; } + return { _setTrackedMilitaryRefreshStateForTest, _setMilitaryTrackingRefreshOutcomeForTest, @@ -164,6 +172,8 @@ export function createTesting({ _updateTrackedModelForTest, _trackedBillboardColorForTest, _driveFleetModelHandoffForTest, + _iconForTest, + _setIconForTest, _ensureFleetModelForTest, }; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 07538df0e8..d967799b49 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -21,14 +21,12 @@ import { RENDER_DELAY_SEC, TRAIL_COLOR, BILLBOARD_SCALE, - GROUND_SCALE, AMBER_TRANSPARENT, TRACKED_ICON_COLOR, TRACKED_BILLBOARD_SCALE_BY_DISTANCE, } from './policy.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; -import { billboardState, setBillboard } from '../../data/billboardMirror.js'; export function createTracking({ flightState, @@ -64,9 +62,9 @@ export function createTracking({ } function _publishTrackedSelection(icao24, origin = 'programmatic') { - const bb = flightState._billboards.get(icao24); + const position = parts.icons._iconPosition(icao24); const info = flightState.records.data.get(icao24); - if (!billboardState(bb)?.position || !info) return false; + if (!position || !info) return false; if (flightState._trackedEntity) entityRecord(flightState._trackedEntity).selectionOrigin = origin; _emitAwarenessEvent('gev:awareness-subject-selected', { @@ -76,7 +74,7 @@ export function createTracking({ parts.queries._toCleanText(info.callsign) || parts.queries._toCleanText(info.registration) || icao24, - position: Cesium.Cartesian3.clone(billboardState(bb).position), + position, origin, }); selectTrackedSubjectContext(_contextSubjectMetadata(icao24)); @@ -152,9 +150,12 @@ export function createTracking({ } const previous = flightState._cockpitNearContacts; const distancesSquared = []; - for (const [icao24, bb] of flightState._billboards) { - const position = billboardState(bb)?.position; - if (icao24 === flightState._trackedIcao || !position) continue; + const icons = flightState._icons; + const tau = parts.icons._displayTau(); + for (let row = 0; row < (icons?.count ?? 0); row++) { + const icao24 = icons.idAt(row); + if (icao24 === flightState._trackedIcao) continue; + const position = icons.position(row, tau, flightState._scratchCockpitPos); distancesSquared.push([ icao24, Cesium.Cartesian3.distanceSquared( @@ -170,13 +171,10 @@ export function createTracking({ parts.rendering._modelKeepDistM(), ); flightState._cockpitNearContacts = next; - let presentationChanged = false; - for (const [icao24, bb] of flightState._billboards) { - if (previous.has(icao24) === next.has(icao24)) continue; - parts.rendering._applyFleetBillboardPresentation(icao24, bb); - presentationChanged = true; - } - if (presentationChanged) flightState._lastCamPoseSig = ''; + for (const icao24 of previous) + if (!next.has(icao24)) parts.icons._applyIconPresentation(icao24); + for (const icao24 of next) + if (!previous.has(icao24)) parts.icons._applyIconPresentation(icao24); } /** Switch all current and future ambient contacts between silhouettes and cockpit pips. */ @@ -193,9 +191,9 @@ export function createTracking({ if (flightState._modelCollection) flightState._modelCollection.show = true; flightState._trail?.setVisible(!next); if (flightState._trailHeadEntity) flightState._trailHeadEntity.show = !next; - for (const [icao24, bb] of flightState._billboards) - parts.rendering._applyFleetBillboardPresentation(icao24, bb); - flightState._lastCamPoseSig = ''; + const icons = flightState._icons; + for (let row = 0; row < (icons?.count ?? 0); row++) + parts.icons._applyIconPresentation(icons.idAt(row)); flightState._lastFleetTickMs = 0; } @@ -297,29 +295,28 @@ export function createTracking({ if (isTr3b(id)) { if (flightState._models.has(id) || flightState._modelPending.has(id)) parts.rendering._releaseModel(id); - const modelled = flightState._billboards.get(id); - if (modelled && id !== flightState._trackedIcao) - setBillboard(modelled, 'show', true); // horizon cull re-asserts next tick + const row = flightState._icons?.row(id) ?? -1; + if (row >= 0 && id !== flightState._trackedIcao) + flightState._icons.setShown(row, true); if (id === flightState._trackedIcao) { parts.rendering._releaseTrackedModel(); _syncTracked2dRotation(); } } - const bb = flightState._billboards.get(id); - if (bb) parts.rendering._applyFleetBillboardPresentation(id, bb); + parts.icons._applyIconPresentation(id); if (id === flightState._trackedIcao) { _syncTrackedBillboardImage(); _updateTrackedLabelModel(id); } flightState._viewer?.scene?.requestRender?.(); - return flightState._billboards.has(id) || id === flightState._trackedIcao; + return flightState._icons?.has(id) || id === flightState._trackedIcao; } /** Re-image every converted contact this layer owns (IR style flip). */ function _refreshTr3bForStyle() { for (const id of tr3bConvertedIds()) { - if (flightState._billboards.has(id) || id === flightState._trackedIcao) + if (flightState._icons?.has(id) || id === flightState._trackedIcao) _refreshTr3bContact(id); } } @@ -415,8 +412,7 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - billboardState(flightState._billboards.get(flightState._trackedIcao)) - ?.position; + parts.icons._iconPosition(flightState._trackedIcao); if (!pos) return; const projected = screenProjectedRotation( flightState._viewer.scene, @@ -745,7 +741,7 @@ export function createTracking({ /** * Stop tracking the current aircraft and clean up all tracking state. - * Restores the original billboard, removes the tracked Entity, invalidates + * Hands the contact back to its icon, removes the tracked Entity, invalidates * the per-frame DR cache, and RELEASES the camera IN PLACE — no flyTo * (mirror of flights.js). Deselect used to fly an ~80 km pulled-back * overview; the owner field-ruled that wrong (2026-07-02: "it randomly zooms @@ -777,34 +773,9 @@ export function createTracking({ const clearedIcao = flightState._trackedIcao; clearFocusTarget('militaryFlights', clearedIcao); - // Restore the original billboard appearance. The rotation is re-seeded from - // the tracked entity's last rendered rotation and a rotation pass is forced - // (_lastCamPoseSig below): the fleet billboard otherwise reappears with the - // STALE screen rotation it had when tracking began — up to a full - // ROTATION_REFRESH_MS of a wrong (possibly reversed) nose on release. - if (flightState._billboards.has(flightState._trackedIcao)) { - const bb = flightState._billboards.get(flightState._trackedIcao); - const meta = flightState.records.data.get(flightState._trackedIcao); - setBillboard(bb, 'show', true); - setBillboard(bb, 'width', 20); - setBillboard(bb, 'height', 20); - // Ground-aware restore (a plane untracked while taxiing comes back at - // ground scale; the fleet tint is amber, or red while broadcasting an - // emergency, on the ground and in the air). - setBillboard( - bb, - 'scale', - BILLBOARD_SCALE * - (CLASS_SCALE_2D[meta?.klass] || 1) * - (meta?.onGround ? GROUND_SCALE : 1), - ); - bb.color = parts.rendering._fleetBillboardColor( - flightState._trackedIcao, - meta, - ); - setBillboard(bb, 'rotation', flightState._lastTrackedRotation); - } - flightState._lastCamPoseSig = ''; // force a fleet rotation pass on the next tick + // The nose the icon continues from (the shared _displayCourse entry), so + // 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 viewer.trackedEntity (they own it now). @@ -820,10 +791,13 @@ export function createTracking({ parts.rendering._releaseTrackedModel(); _resetTrackedSelectionState(); // the zoom band + load-failure budget belong to the selection we just dropped flightState._trackedIcao = null; - parts.rendering._applyFleetBillboardPresentation( - clearedIcao, - flightState._billboards.get(clearedIcao), - ); + // Hand the contact back to its icon only now, once it no longer reads as + // tracked (the settle plans it as a fleet contact). + if (flightState._icons?.has(clearedIcao)) { + flightState._icons.setShown(flightState._icons.row(clearedIcao), true); + parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg }); + } + parts.icons._applyIconPresentation(clearedIcao); clearTrackedSubjectContext('military'); _emitAwarenessEvent('gev:awareness-subject-cleared', { layerId: 'military', @@ -844,10 +818,7 @@ export function createTracking({ pending.generation !== flightState._trackingIntentGeneration ) return false; - if ( - !flightState._billboardCollection?.show || - !flightState._billboards.has(pending.id) - ) + if (!flightState._icons?.show || !flightState._icons.has(pending.id)) return false; flightState._pendingTrackingRestore = null; _trackFlight(pending.id, { origin: pending.origin }); @@ -861,7 +832,7 @@ export function createTracking({ /** * Begin tracking a specific aircraft. Clears any previous tracking, hides the - * billboard, creates a new Entity with dead-reckoning CallbackProperties for + * icon, creates a new Entity with dead-reckoning CallbackProperties for * smooth continuous motion, and sets the viewer's trackedEntity so the camera * follows. * @param {string} icao24 - ICAO hex identifier of the aircraft to track @@ -870,29 +841,42 @@ export function createTracking({ function _trackFlight(icao24, { origin = 'programmatic' } = {}) { _clearTracking(false, { origin }); // switching planes — the new follow-camera takes over - const bb = flightState._billboards.get(icao24); + const icons = flightState._icons; + const row = icons?.row(icao24) ?? -1; const info = flightState.records.data.get(icao24); - if (!bb || !info) return; + if (row < 0 || !info) return; + // 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 tau = parts.icons._displayTau(); + const iconPosition = icons.position(row, tau); + flightState._displayCourse.set(icao24, icons.course(row, tau)); flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget flightState._cachedDRFrame = -1; - flightState._lastTrackedRotation = billboardState(bb).rotation || 0; + flightState._lastTrackedRotation = + screenProjectedRotation( + flightState._viewer.scene, + iconPosition, + icons.course(row, tau), + 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. parts.rendering._releaseModel(icao24); - // Hide the billboard -- the tracked entity replaces it visually - setBillboard(bb, 'show', false); + // Hide the icon -- the tracked entity replaces it visually + icons.setShown(row, false); // Helper: smoothed, per-frame-cached tracked position (see _trackedDisplayPosition — // one computation shared by the position/rotation/trail-head callbacks, with - // discontinuity reconciliation). Falls back to the last billboard position when the + // discontinuity reconciliation). Falls back to the icon's position when the // aircraft has no fix. const getTrackedPosition = () => parts.motion._trackedDisplayPosition(icao24) || - billboardState(bb).position; + parts.icons._iconPosition(icao24) || + iconPosition; // Dead-reckoning position property evaluated every render frame. // isConstant = false so CesiumJS re-evaluates each frame. @@ -958,7 +942,7 @@ export function createTracking({ 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 exactly like the fleet ground icons (_groundDepthDistance); + // 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 @@ -1120,26 +1104,12 @@ export function createTracking({ return; } - // BillboardCollection picks: CesiumJS may expose the billboard as - // picked.primitive (with .id = icao24) or directly as picked.id - const billboard = picked.primitive; - if ( - billboard && - billboard.id && - flightState._billboards.has(billboard.id) - ) { + // Icon picks carry the icao on picked.id; models carry it on the primitive. + const pickedIcao = + typeof picked.id === 'string' ? picked.id : picked.primitive?.id; + if (pickedIcao && flightState._icons?.has(pickedIcao)) { _cancelPendingTrackingRestore(); - _trackFlight(billboard.id, { origin: 'user' }); - return; - } - // Fallback: some CesiumJS versions surface the id string at picked.id - if ( - picked.id && - typeof picked.id === 'string' && - flightState._billboards.has(picked.id) - ) { - _cancelPendingTrackingRestore(); - _trackFlight(picked.id, { origin: 'user' }); + _trackFlight(pickedIcao, { origin: 'user' }); return; } } diff --git a/src/testSupport/readLayerSource.mjs b/src/testSupport/readLayerSource.mjs index 4d07e04079..07a8712418 100644 --- a/src/testSupport/readLayerSource.mjs +++ b/src/testSupport/readLayerSource.mjs @@ -45,9 +45,15 @@ export function readLayerSource(file) { ? '../layers/cctv' : '../layers/vessels', ); + // The aircraft layers draw through one shared icon layer; it is their code too. + const shared = ['flights.js', 'militaryFlights.js'].includes(basename(path)) + ? [join(dirname(path), 'aircraftIconLayer.js')] + : []; return readdirSync(directory) .filter((name) => name.endsWith('.js')) .sort() - .map((name) => readFileSync(join(directory, name), 'utf8')) + .map((name) => join(directory, name)) + .concat(shared) + .map((file) => readFileSync(file, 'utf8')) .join('\n'); } diff --git a/src/ui/cyberTheme.test.mjs b/src/ui/cyberTheme.test.mjs index 605876f738..da84f29d57 100644 --- a/src/ui/cyberTheme.test.mjs +++ b/src/ui/cyberTheme.test.mjs @@ -706,7 +706,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', () ); assert.match( militaryRendering, - /baseAlpha:[\s\S]*?alpha: flightState\._irBoost \? 1 : treatment\.alpha/, + /alpha: flightState\._irBoost\s*\?\s*1\s*:\s*aircraftTreatmentAlpha\(/, ); assert.match( cyberStyles, From 816002e3b94c950bf9e87e49f09d0cb5fa63d695 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Tue, 3 Nov 2026 20:55:09 -0800 Subject: [PATCH 014/470] Share the aircraft 3D-model regime between flights and military --- scripts/package-boundaries.json | 4 + src/data/aircraftIconLayer.js | 21 +- src/data/aircraftModelLayer.js | 888 ++++++++++++++++++++++++++ src/data/cockpitModels.test.mjs | 37 +- src/data/modelScale.test.mjs | 6 +- src/data/trackedModelRegime.test.mjs | 8 +- src/layers/flights/rendering.js | 916 +-------------------------- src/layers/military/rendering.js | 867 +------------------------ src/testSupport/readLayerSource.mjs | 7 +- src/ui/cyberTheme.test.mjs | 11 +- 10 files changed, 992 insertions(+), 1773 deletions(-) create mode 100644 src/data/aircraftModelLayer.js diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 631fb2f6d4..c94739cedf 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1317,6 +1317,7 @@ "src/layers/flights/rendering.js", "src/layers/flights/icons.js", "src/data/aircraftIconLayer.js", + "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", @@ -1387,6 +1388,7 @@ "src/layers/military/rendering.js", "src/layers/military/icons.js", "src/data/aircraftIconLayer.js", + "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", @@ -2267,6 +2269,7 @@ "modules": [ "src/layers/flights/icons.js", "src/data/aircraftIconLayer.js", + "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", "src/sources/adsbFields.js", "src/data/headingDegrees.js", @@ -3270,6 +3273,7 @@ "modules": [ "src/layers/flights/icons.js", "src/data/aircraftIconLayer.js", + "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", diff --git a/src/data/aircraftIconLayer.js b/src/data/aircraftIconLayer.js index e7ea0db824..94040f0c2f 100644 --- a/src/data/aircraftIconLayer.js +++ b/src/data/aircraftIconLayer.js @@ -29,6 +29,19 @@ import { horizonOccluder } from './iconOrientation.js'; /** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */ const COCKPIT_DOT_PX = 16; +/** Fleet glyphs keep the established close-range 3× scale. */ +const NORMAL_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( + 1000, + 3.0, + 8000000, + 0.5, +); +const COCKPIT_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( + 1000, + 1.15, + 8000000, + 0.65, +); /** Contacts drawn below this height (m) are judged for the horizon a little * above the ellipsoid (ICON_CULL_LIFT). */ const CULL_LIFT_BELOW_M = 10; @@ -79,8 +92,6 @@ export function createAircraftIcons({ const scratchPosition = new Cesium.Cartesian3(); const scratchCull = new Cesium.Cartesian3(); const scratchScaleByDistance = new Cesium.NearFarScalar(); - let normalScaleByDistance = null; - let cockpitScaleByDistance = null; /** The delayed instant every untracked contact is drawn at. */ function _displayTime(result = scratchTime) { @@ -292,8 +303,7 @@ export function createAircraftIcons({ set.setImage(row, dot, dot); set.setSize(row, cockpitContactSizePx, cockpitContactSizePx); set.setScale(row, 1); - cockpitScaleByDistance ??= rendering._cockpitBillboardScaleByDistance(); - set.setScaleByDistance(row, cockpitScaleByDistance); + set.setScaleByDistance(row, COCKPIT_SCALE_BY_DISTANCE); set.setColor(row, rendering._cockpitContactColor(icao24, info)); set.setFlag(row, ICON_ROTATES, false); } else { @@ -314,8 +324,7 @@ export function createAircraftIcons({ const size = tracked ? 24 : 20; set.setSize(row, size, size); set.setScale(row, rendering._fleetBillboardScale(icao24, info?.klass)); - normalScaleByDistance ??= rendering._normalBillboardScaleByDistance(); - set.setScaleByDistance(row, normalScaleByDistance); + set.setScaleByDistance(row, NORMAL_SCALE_BY_DISTANCE); set.setColor(row, rendering._fleetBillboardColor(icao24, info)); set.setFlag(row, ICON_ROTATES, true); } diff --git a/src/data/aircraftModelLayer.js b/src/data/aircraftModelLayer.js new file mode 100644 index 0000000000..8ac3306891 --- /dev/null +++ b/src/data/aircraftModelLayer.js @@ -0,0 +1,888 @@ +import * as Cesium from 'cesium'; +import { selectModelEligible } from './modelEligibility.js'; +import { horizonOccluder } from './iconOrientation.js'; +import { aircraftTreatmentAlpha } from './aircraftRecession.js'; +import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; +import { aircraftVisuals } from '../layers/aircraft/visualState.js'; +import { modelState, setModel } from './modelMirror.js'; + +/** + * An aircraft layer's 3D models: the fleet regime and its gap-proof handoff + * from the icon set (`createAircraftIcons`), the standalone tracked model, and + * the ~12 Hz fleet tick that drives both. Shared by the flights and military + * layers, which differ only in the options below. + * @param {object} options + * @param {object} options.state The layer state. + * @param {object} options.services + * @param {object} options.parts The layer's parts; `icons`, `motion` and + * `tracking` are read at call time. + * @param {(url: string) => string} options.resolveAsset + * @param {string} options.logLabel Console prefix, e.g. `Data:Flights`. + * @param {object} options.policy The layer's model budgets, radii, pixel + * bounds, heading offset, IR reload batch and fleet tick interval. + * @param {(klass: string) => object} options.modelSpec The class's GLB, scale, + * geometry and tint blend; `headingOffsetDeg` overrides the policy's. + * @param {(icao24: string) => Cesium.Color} options.modelColor Model tint, + * including the tracked contact's. + * @param {(icao24: string) => void} [options.onModelEligible] Runs when a + * contact is about to render in 3D. + * @param {(renderTime: Cesium.JulianDate, tau: number, nowMs: number, + * camera: Cesium.Camera) => void} [options.afterReplan] The layer's own pass + * in the fleet tick, after expired rows are re-planned. + */ +export function createAircraftModels({ + state, + services, + parts, + resolveAsset, + logLabel, + policy, + modelSpec: _modelSpec, + modelColor: _modelColor, + onModelEligible = () => {}, + afterReplan = () => {}, +}) { + const { isTr3b } = services.aircraftPresentation; + const { trackedModelScaleForPixelCap } = services.camera; + const { focusNowMs, getFocusTarget } = services.focus; + const { applyAircraftModelTreatment } = services.recession; + + /** The model heading offset a class's GLB needs. */ + const _headingOffsetDeg = (klass) => + _modelSpec(klass).headingOffsetDeg ?? policy.MODEL_HEADING_OFFSET_DEG; + + /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude + * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the + * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in + * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms + * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED + * contact does not route through here: it is one model, it is what the camera is aimed at, + * and it takes its own default-on, hysteretic zoom regime + * (`_trackedModelRegimeActive`). */ + + function _modelRegimeActive() { + if (!state._models3dEnabled) return false; + const h = state._viewer?.camera?.positionCartographic?.height ?? Infinity; + return h < policy.MODEL_ALT_CEIL_M; + } + + /** Active model cap — the eligibility pre-pass AND _ensureModel's admission checks must use the + * SAME value, else 'all' (MODEL_MAX_ALL) would mark planes eligible that _ensureModel then refuses + * at the lower MODEL_MAX, silently degrading 'all' to 'proximity'. */ + + function _modelCap() { + const mapCap = + state._models3dMode === 'all' ? policy.MODEL_MAX_ALL : policy.MODEL_MAX; + // `Math.min` on purpose: cockpit may only ever LOWER the GLB budget. Cockpit is + // already the heaviest mode (20 Hz camera setView ahead of scene update, photoreal + // retraversal, the cloud pass) and every model is its own draw call. + return state._cockpitContactMode + ? Math.min(policy.COCKPIT_MODEL_MAX, mapCap) + : mapCap; + } + + /** Active ADD radius (m) — new planes inside this range get a model. Mode-aware: 'all' reaches far. */ + + function _modelAddDistM() { + return state._models3dMode === 'all' + ? policy.MODEL_ALL_ADD_M + : policy.MODEL_PROX_ADD_M; + } + + /** Active KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */ + + function _modelKeepDistM() { + return state._models3dMode === 'all' + ? policy.MODEL_ALL_KEEP_M + : policy.MODEL_PROX_KEEP_M; + } + + /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into + * `result` (a shared scratch by default) and returns it. Push it with `setModel`, which copies + * it into the app's mirror and the model's own matrix, so models never share one mutable matrix + * object. `Model.modelMatrix` is a plain field (not a cloning setter); Cesium + * clones it per frame in updateModelMatrix(). Sharing a single scratch made every model render at + * the LAST-written transform — all stacked on one plane — and, once the tracked model wrote the + * scratch every frame, the stack point oscillated frame-to-frame: the "flickering like mad" bug. */ + + function _modelMatrix( + pos, + headingDeg, + result = state._scratchModelMtx, + offsetDeg = policy.MODEL_HEADING_OFFSET_DEG, + ) { + state._scratchModelHpr.heading = Cesium.Math.toRadians( + (headingDeg || 0) + offsetDeg, + ); + state._scratchModelHpr.pitch = 0; + state._scratchModelHpr.roll = 0; + return Cesium.Transforms.headingPitchRollToFixedFrame( + pos, + state._scratchModelHpr, + Cesium.Ellipsoid.WGS84, + undefined, + result, + ); + } + + /** Everything scene.sampleHeight must NOT hit when snapping a grounded model: the + * vertical pick ray at a plane's own lat/lon otherwise lands on its (or a parked + * neighbor's) billboard/model instead of the tile skin. Cesium's ray-pick exclusion + * matches picked-object IDs, and every icon AND model in this layer carries its + * icao as `id`, so the icao strings cover both; the tracked entity is excluded as the + * object itself. Built lazily — only when a sample actually fires (one-shot). */ + + function _groundSampleExclusions() { + const out = parts.icons._iconIds(); + if (state._trackedEntity) out.push(state._trackedEntity); + return out; + } + + /** Position a 3D MODEL renders at. Airborne planes use their dead-reckoned position + * verbatim. GROUNDED planes' meta altitude is last-known baro or 0 m — nowhere near + * the photoreal tile skin in ellipsoid heights (buried ~100+ m at inland airports, + * hovering ~30 m at sea-level ones), and unlike the ground billboards a depth-tested + * model can't hide behind disableDepthTestDistance. So a modeled grounded plane rides + * a ONE-SHOT cached scene.sampleHeight of the skin at its lat/lon (groundSnap.js, + * CCTV-B9b discipline: never per-frame; taxiing >50 m retires the cached value to a + * bounded last-known and resamples), plus + * the belly offset so it sits on its gear rather than sinking to the model-origin + * fuselage centerline. Until the FIRST sample lands (tiles streaming / sample miss) + * there is no safe depth-tested placement at all: this returns null, the caller + * keeps the 2D billboard visible and the model hidden, and it retries later. Once + * a contact has resolved once, a later outage holds that measurement inside + * groundSnap's drift bound instead — a taxiing aircraft does not pop back to 2D + * because a resample is mid-backoff. */ + + function _modelDisplayPosition(icao24, pos, result) { + const meta = state.records.data.get(icao24); + if (!meta || !meta.onGround) return pos; + const h = state._groundSnap.heightFor( + state._viewer, + icao24, + pos, + _groundSampleExclusions, + ); + if (h == null) return null; + const carto = Cesium.Cartographic.fromCartesian( + pos, + Cesium.Ellipsoid.WGS84, + state._scratchGroundCarto, + ); + carto.height = h + _modelSpec(meta.klass).bellyM; + return Cesium.Cartesian3.fromRadians( + carto.longitude, + carto.latitude, + carto.height, + Cesium.Ellipsoid.WGS84, + result, + ); + } + + /** Atomically hand one fleet contact from its icon to a safely placed, + * ready 3D model. Missing/loading models and unresolved terrain always leave + * the icon owning the visual, so no render frame can hide both. + * `beforeShow` runs only on the committing path — the per-tick model treatment + * belongs to a model that is about to draw, not to one still waiting. */ + + function _driveFleetModelHandoff( + icao24, + model, + row, + pos, + course, + beforeShow, + ) { + const icons = state._icons; + if (!model) { + icons.setShown(row, true); + return false; + } + const displayPos = _modelDisplayPosition( + icao24, + pos, + state._scratchGroundPos, + ); + if (!displayPos) { + setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at + icons.setShown(row, true); + return false; + } + // The matrix is written BEFORE the readiness test on purpose: a model can flip + // `ready` during scene update after this tick, and a first rendered frame on a + // stale load-start matrix is the one-frame jump this ordering prevents. + setModel( + model, + 'modelMatrix', + _modelMatrix( + displayPos, + course, + undefined, + _headingOffsetDeg(state.records.data.get(icao24)?.klass), + ), + ); + if (!model.ready) { + setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash + icons.setShown(row, true); + return false; + } + beforeShow?.(); + if (!modelState(model).show) setModel(model, 'show', true); + icons.setShown(row, false); // hand off ONLY once the model renders + return true; + } + + /** + * Whether a 3D model — not the billboard — is what the user actually SEES for + * this contact, and therefore whether the display floor should stand aside. + * + * Model EXISTENCE is not ownership. A fleet model that is still loading, or has + * no resolved ground to stand on, stays hidden while `bb.show` stays true (the + * gap-proof handoff: "hand off ONLY once the model renders"), and a tracked model + * is retained but hidden whenever the model regime is off — 3D disabled, camera + * zoomed past the ceiling, or cockpit mode. Gating on `has()`/existence therefore + * suppressed the clamp in exactly the states where the BILLBOARD is the visual, + * putting the burial straight back. + * + * Cesium's own default `show === true` is the reason admission clears it + * explicitly: a fleet model registered in `_models` the instant its glTF resolves + * would otherwise claim ownership — at the identity matrix — for the frames + * between admission and the next fleet tick, while the BILLBOARD was still the + * visual. Ownership means actually rendering, and every site that sets `show` + * true does so only after committing a matrix. + * + * The two halves: + * - Fleet: the rendering test alone. Safe for the ground snap either way, + * because a fleet model is positioned from the RAW dead-reckon, not from + * the billboard. + * - Tracked: the rendering test AND `_trackedModelRegimeActive()`. The tracked + * model is fed from `_trackedDisplayPosition`, so once it is live the clamp + * must stand aside: two different chains would otherwise be deciding one + * contact's ground, and the billboard's is the one the operator is not + * looking at (T7). The regime check is what makes a regime + * flip take effect on the same frame rather than waiting for + * `_updateTrackedModel` to clear `show`; the rendering test is what keeps a + * null or still-loading tracked model from claiming a visual it is not + * drawing yet. + * @param {string} icao24 + * @param {Cesium.Model|null} [model] Resolved fleet model; null means absent. + * @returns {boolean} + */ + + function _modelOwnsVisual(icao24, model) { + if (icao24 === state._trackedIcao) { + return ( + parts.tracking._trackedModelRegimeActive() && + _modelIsRendering(state._trackedModel) + ); + } + return _modelIsRendering( + model === undefined ? state._models.get(icao24) : model, + ); + } + + /** A model is the visual only once it actually draws — loaded AND shown. + * + * `show` is sufficient evidence of a safe placement because only ONE site ever + * sets it true for a fleet model (`_driveFleetModelHandoff`, after the matrix is + * committed) and one for the tracked model (`_updateTrackedModel`, likewise); + * everything else — admission, an unresolved ground, a not-yet-ready glTF, the + * limb cull, a regime exit — only ever clears it. */ + + function _modelIsRendering(model) { + return !!model && model.ready === true && modelState(model)?.show === true; + } + + /** Spec identity for a LOADED model: URL and scale together (same-URL classes + * differ by scale — airliner vs quadjet both ship airplane.glb). */ + + const _specKeyFor = (klass) => { + const spec = _modelSpec(klass); + return `${spec.url}@${spec.scale}`; + }; + + /** Class-change model sync (enrichment AND poll-path klass updates): when the + * aircraft's live model or in-flight load no longer matches its class's spec, + * drop it so the eligibility pass reloads the right asset at the right scale. + * Gap-proof: the fleet billboard is re-shown BEFORE the release so the + * contact never goes invisible for the tick gap; _releaseModel's generation + * bump also invalidates any pending load. The tracked standalone model gets + * the same rule (its billboard entity is always the fallback visual). */ + + function _syncModelToClass(icao24) { + const key = _specKeyFor(state.records.data.get(icao24)?.klass); + const current = state._models.get(icao24); + if ( + (current && aircraftVisuals.read(current)?.specKey !== key) || + (!current && state._modelPending.has(icao24)) + ) { + _releaseModel(icao24); + } + if ( + icao24 === state._trackedIcao && + state._trackedModel && + aircraftVisuals.read(state._trackedModel)?.specKey !== key + ) { + _releaseTrackedModel(); + } + } + + function _reloadModelsForIrBoost() { + state._irReloadQueue = [...state._models.keys()]; + for (const icao of state._modelPending) { + if (!state._models.has(icao)) + state._modelGen.set(icao, (state._modelGen.get(icao) || 0) + 1); + } + _releaseTrackedModel(); + } + + function _drainIrReloadQueue() { + if (!state._irReloadQueue) return; + const batch = state._irReloadQueue.splice(0, policy.IR_RELOAD_BATCH); + for (const icao of batch) { + const model = state._models.get(icao); + if (!model || aircraftVisuals.read(model)?.irBoost === state._irBoost) + continue; // already right state + _releaseModel(icao); + } + if (state._irReloadQueue.length === 0) state._irReloadQueue = null; + } + + /** Lazily create the glTF model for an aircraft (fire-and-forget; billboard shows until ready). */ + + async function _ensureModel(icao24) { + // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet + // tick skips it, so a model here would be orphaned + double-rendered. + if (icao24 === state._trackedIcao) return; + onModelEligible(icao24); + if (state._models.has(icao24) || state._modelPending.has(icao24)) return; + // Count PENDING loads in the cap so a zoomed-in tick can't fire 100s of concurrent loads + // (the cap is rechecked post-await too, before the add). Mode-aware so 'all' can reach MAX_ALL. + if (state._models.size + state._modelPending.size >= _modelCap()) return; + const epoch = state._modelEpoch; // lifecycle token: if destroy() bumps it, this load is dead + const gen = state._modelGen.get(icao24) || 0; // capture; if it changes during the load, we're stale + state._modelPending.add(icao24); + let model = null; + // Spec identity captured at load START — if enrichment reclassifies the + // aircraft mid-load, the post-await admission below rejects the stale asset. + // Boost state likewise: the creation options bake it in, so a mid-load + // toggle must reject too (the reload queue only covers ADMITTED models). + const specKey = _specKeyFor(state.records.data.get(icao24)?.klass); + const loadIrBoost = state._irBoost; + try { + const spec = _modelSpec(state.records.data.get(icao24)?.klass); + model = await Cesium.Model.fromGltfAsync({ + url: resolveAsset(spec.url), + asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, + minimumPixelSize: policy.MODEL_MIN_PX, + scale: spec.scale, + color: state._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), + colorBlendMode: Cesium.ColorBlendMode.MIX, + // Launch presentation keeps the code-side tint dominant for every approved + // model; IR boost removes the remaining diffuse hint with flat UNLIT white. + colorBlendAmount: state._irBoost ? 1.0 : spec.blendAmount, + customShader: state._irBoost ? state._IR_UNLIT_SHADER : undefined, + id: icao24, // so scene.pick returns the icao for click-to-track + }); + } catch { + // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current + // (a destroy/re-init may have swapped the globals while this load was in flight). + if (epoch === state._modelEpoch) { + state._modelPending.delete(icao24); + _cleanupModelGen(icao24); + } + return; + } + // A load from a PREVIOUS lifecycle (destroy→init happened mid-load) must NOT mutate the new + // epoch's _modelPending/_modelGen or add to the new collection — just drop its model. + if (epoch !== state._modelEpoch) { + try { + model.destroy(); + } catch { + /* gone */ + } + return; + } + state._modelPending.delete(icao24); + // Post-await admission: reject (and DESTROY the loaded model) if anything changed during the + // load — a release bumped the generation (track/untrack/remove), the layer toggled off / was + // torn down, the aircraft is gone or now tracked, a model already exists, or the cap filled. + // Recheck the shared Display 3D toggle and altitude ceiling after the async + // load. Cockpit uses the same OFF / Proximity / All contract as map Display. + const stale = + (state._modelGen.get(icao24) || 0) !== gen || + !_modelRegimeActive() || + !state._modelCollection || + state._modelCollection.isDestroyed() || + !state.records.data.has(icao24) || + icao24 === state._trackedIcao || + state._models.has(icao24) || + state._models.size >= _modelCap() || + // Class reclassified mid-load → this GLB/scale is for the OLD class. + _specKeyFor(state.records.data.get(icao24)?.klass) !== specKey || + // IR boost flipped mid-load → this model baked the wrong shader/tint. + state._irBoost !== loadIrBoost; + if (stale) { + try { + model.destroy(); + } catch { + /* already gone */ + } + _cleanupModelGen(icao24); // bound the map + return; + } + // Keep the pick identity explicit on the resolved primitive. This also + // protects injected/custom loaders that do not copy the creation option. + model.id = icao24; + const visual = aircraftVisuals.write(model); + visual.specKey = specKey; // class-change sync compares against this + visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this + // Admitted, not yet the visual. Cesium's default is show=true, which would let + // an unplaced primitive claim ownership from the icon for the frames + // between admission and the next fleet tick (and draw at the identity matrix, + // i.e. the Earth's centre). The handoff turns it on once it has a matrix. + setModel(model, 'show', false); + state._modelCollection.add(model); + state._models.set(icao24, model); + state._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard + } + + /** Remove the 3D model for ONE aircraft (removal / military-suppression / track handoff). + * Bumps the load generation so any in-flight load for this icao is rejected on completion. */ + + function _releaseModel(icao24) { + const m = state._models.get(icao24); + const pending = state._modelPending.has(icao24); + // Only bump the generation when there's something to invalidate (an in-flight load or a + // live model) — so removing never-modeled aircraft doesn't grow _modelGen. + if (m || pending) { + state._modelGen.set(icao24, (state._modelGen.get(icao24) || 0) + 1); + } + if (m) { + if (state._modelCollection && !state._modelCollection.isDestroyed()) { + try { + state._modelCollection.remove(m); + } catch { + /* gone */ + } + } + state._models.delete(icao24); + _showReleasedIcon(icao24); + } + // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping + // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so + // the resolving load's gen-check still rejects it. + _cleanupModelGen(icao24); + } + + /** Drop an icao's generation entry once nothing references it (no live model, no in-flight + * load) — keeps _modelGen bounded. Shared by _releaseModel + both _ensureModel exit paths. */ + + function _cleanupModelGen(icao24) { + if (!state._modelPending.has(icao24) && !state._models.has(icao24)) + state._modelGen.delete(icao24); + } + + /** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */ + + function _releaseModels() { + state._irReloadQueue = null; // a full release supersedes any pending boost-flip drain + // Invalidate in-flight loads so a completion after this bulk release can't add a model. + for (const icao of state._modelPending) + state._modelGen.set(icao, (state._modelGen.get(icao) || 0) + 1); + if (state._modelCollection && !state._modelCollection.isDestroyed()) { + for (const m of state._models.values()) { + try { + state._modelCollection.remove(m); + } catch { + /* gone */ + } + } + } + for (const icao24 of state._models.keys()) _showReleasedIcon(icao24); + state._models.clear(); + } + + /** A released fleet model hands the visual straight back to its icon (the + * tracked contact's entity keeps its own). */ + + function _showReleasedIcon(icao24) { + const icons = state._icons; + const row = icons?.row(icao24) ?? -1; + if (row >= 0 && icao24 !== state._trackedIcao) icons.setShown(row, true); + } + + /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ + + function _releaseTrackedModel() { + state._trackedModelGen++; + state._trackedModelLoading = false; + if (state._trackedModel) { + if (state._modelCollection && !state._modelCollection.isDestroyed()) { + try { + state._modelCollection.remove(state._trackedModel); + } catch { + /* gone */ + } + } + state._trackedModel = null; + } + } + + /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet + * cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the + * follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed + * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). */ + + function _updateTrackedModel() { + const active = + state._trackedIcao && + parts.tracking._trackedModelRegimeActive() && + state._modelCollection && + !state._modelCollection.isDestroyed(); + if (!active) { + if (state._trackedModel) setModel(state._trackedModel, 'show', false); + return; + } + // Ask the frame-cached source directly. If the entity callback already ran, + // this is a no-op; if model loading completed between phases, it establishes + // this frame's single sample before the model renders. Camera, detection, and + // readout consumers then reuse that exact cached position. + const pos = + parts.motion._trackedDisplayPosition(state._trackedIcao) || + parts.icons._iconPosition(state._trackedIcao); + if (!pos) { + if (state._trackedModel) setModel(state._trackedModel, 'show', false); + return; + } + if ( + !state._trackedModel && + !state._trackedModelLoading && + parts.tracking._trackedModelLoadAllowed() + ) { + state._trackedModelLoading = true; + const gen = state._trackedModelGen; + const trackedSpec = _modelSpec( + state.records.data.get(state._trackedIcao)?.klass, + ); + const trackedKey = _specKeyFor( + state.records.data.get(state._trackedIcao)?.klass, + ); + const trackedIrBoost = state._irBoost; + Cesium.Model.fromGltfAsync({ + url: resolveAsset(trackedSpec.url), + asynchronous: false, + environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, + minimumPixelSize: policy.TRACKED_MODEL_MIN_PX, + scale: trackedSpec.scale, + color: state._irBoost + ? Cesium.Color.WHITE + : _modelColor(state._trackedIcao), + colorBlendMode: Cesium.ColorBlendMode.MIX, + // The tracked aircraft uses the same dominant light tint as the fleet; + // IR boost removes the remaining diffuse hint with flat UNLIT white. + colorBlendAmount: state._irBoost ? 1.0 : trackedSpec.blendAmount, + customShader: state._irBoost ? state._IR_UNLIT_SHADER : undefined, + // Pick id (H1): without it, clicking the very plane being tracked read as + // EMPTY SPACE (scene.pick → primitive with no id) → an unintended + // deselect. With the icao, the click handler recognizes it as ours. + id: state._trackedIcao, + }) + .then((m) => { + // Untracked / re-tracked / torn down during the load → drop it. + if ( + gen !== state._trackedModelGen || + !state._modelCollection || + state._modelCollection.isDestroyed() + ) { + try { + m.destroy(); + } catch { + /* gone */ + } + return; + } + // Class reclassified OR boost flipped mid-load (no release ran — + // _trackedModel was still null): drop the stale asset; driver reloads. + if ( + _specKeyFor(state.records.data.get(state._trackedIcao)?.klass) !== + trackedKey || + state._irBoost !== trackedIrBoost + ) { + try { + m.destroy(); + } catch { + /* gone */ + } + state._trackedModelLoading = false; + return; + } + // Assign after resolution as well as in the creation options so the + // standalone primitive always exposes the tracked aircraft pick id. + m.id = state._trackedIcao; + aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this + setModel(m, 'show', false); // admitted, not yet the visual — the driver shows it once placed + // Seed the world transform before the primitive enters the scene. A model + // can become ready+shown between render phases; leaving Cesium's identity + // default here produces a one-frame jump to the Earth's center. + const currentPos = + parts.motion._trackedDisplayCached() || + parts.icons._iconPosition(state._trackedIcao); + if (currentPos) { + const displayPos = _modelDisplayPosition( + state._trackedIcao, + currentPos, + state._scratchGroundPos, + ); + if (displayPos) + setModel( + m, + 'modelMatrix', + _modelMatrix( + displayPos, + parts.motion._trackedDisplayCourse(), + undefined, + trackedSpec.headingOffsetDeg ?? + policy.MODEL_HEADING_OFFSET_DEG, + ), + ); + } + state._trackedModel = m; + state._trackedModelLoading = false; + // A good load retires this selection's failure budget — a contact that + // recovers after a transient blip is not one attempt from giving up. + state._trackedModelFailIcao = null; + state._trackedModelFailCount = 0; + state._trackedModelRetryAtMs = 0; + state._modelCollection.add(m); + state._planeModelLoaded = true; // GLB cached — the tracked billboard can fade out once the model is up + }) + .catch((err) => { + if (gen !== state._trackedModelGen) return; // superseded load — not this selection's failure + state._trackedModelLoading = false; + parts.tracking._noteTrackedModelLoadFailure(trackedSpec.url, err); + }); + return; // billboard carries the visual until the model is ready + } + if (state._trackedModel) { + // Keep the transform current while GPU resources are still loading. Cesium + // can flip ready during scene update after this callback; waiting for ready + // here would let that first rendered frame use a stale load-start matrix. + const displayPos = _modelDisplayPosition( + state._trackedIcao, + pos, + state._scratchGroundPos, + ); + if (!displayPos) { + setModel(state._trackedModel, 'show', false); // no ground evidence → the billboard carries it + return; + } + const spec = _modelSpec( + state.records.data.get(state._trackedIcao)?.klass, + ); + setModel( + state._trackedModel, + 'modelMatrix', + _modelMatrix( + displayPos, + parts.motion._trackedDisplayCourse(), + undefined, + spec.headingOffsetDeg ?? policy.MODEL_HEADING_OFFSET_DEG, + ), + ); + if (!state._trackedModel.ready) return; + state._trackedModel.scale = trackedModelScaleForPixelCap({ + baseScale: spec.scale, + nativeRadiusM: spec.nativeRadiusM, + rangeM: Cesium.Cartesian3.distance( + state._viewer.camera.positionWC, + displayPos, + ), + viewportHeightPx: state._viewer.scene.canvas.clientHeight, + fovyRad: state._viewer.camera.frustum.fovy, + maximumPixelSize: policy.TRACKED_MODEL_MAX_PX, + }); + setModel(state._trackedModel, 'show', true); + } + } + + /** + * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and + * the two-tier glyph swap all run on the GPU from each row's segment, so this + * only re-plans rows whose regime ended, runs the layer's own pass after + * that (flights floors grounded contacts), advances focus de-emphasis while + * a target exists, and drives the 3D-model handoff inside the model regime. + * Driven by scene.preRender. + * @returns {void} + */ + + function _fleetTick() { + const icons = state._icons; + if (!state._viewer || !icons || !icons.show) return; + const scene = state._viewer.scene; + const camera = state._viewer.camera; + const nowMs = focusNowMs(Date.now()); + + if (nowMs - state._lastFleetTickMs < policy.FLEET_DR_INTERVAL_MS) return; + state._lastFleetTickMs = nowMs; + // Every contact in this pass shares the same delayed display instant. + const renderTime = parts.icons._displayTime(state._scratchFleetRenderTime); + const tau = icons.seconds(renderTime); + + _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload + if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); + parts.icons._replanExpired(tau); + afterReplan(renderTime, tau, nowMs, camera); + const focusTarget = getFocusTarget(); + parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget); + + // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. + // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. + const useModels = _modelRegimeActive(); + // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that + // resolves after zoom-out could briefly add a model outside the 3D-model regime). + if (!useModels && (state._models.size || state._modelPending.size)) + _releaseModels(); + if (!useModels) return; + + // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the + // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen + // already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius, + // nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots + // (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint). + // Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an + // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap + // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum + // filtering dropped near off-screen planes entirely. This does both right. + const cap = _modelCap(); + const camPos = camera.positionWC; + const addM = _modelAddDistM(); + const addDistSq = addM * addM; + const keepM = _modelKeepDistM(); + const keepDistSq = keepM * keepM; + const cull = camera.frustum.computeCullingVolume( + camPos, + camera.directionWC, + camera.upWC, + ); + // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. + const cand = []; + for (let row = 0; row < icons.count; row++) { + const icao = icons.idAt(row); + if (icao === state._trackedIcao) continue; + // A converted TR-3B renders as an icon and can never take a model, so + // it must not occupy a CAP SLOT either — excluded here at selection time, + // not just at the handoff below, or accumulated conversions would starve + // ordinary contacts of 3D models. (The handoff guard stays as defence.) + if (isTr3b(icao)) continue; + // Ground planes compete for model slots like everyone else (owner decision + // 2026-07-03: "3D mode is respected regardless of whether a plane is on the + // ground or in the air — no distinction"). The cap + nearest-first ordering + // below already bound airport clusters; grounded placement is handled by the + // one-shot ground snap in _modelDisplayPosition. + const position = icons.position(row, tau, state._scratchModelBS.center); + const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); + if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible + cand.push([ + icao, + d2, + cull.computeVisibility(state._scratchModelBS) !== + Cesium.Intersect.OUTSIDE, + ]); + } + cand.sort((a, b) => a[1] - b[1]); // nearest first + if (cand.length > cap && nowMs - state._lastModelCapWarnMs > 5000) { + console.warn( + `[${logLabel}] ${cand.length} planes in 3D range; capped at ${cap} (${state._models3dMode}). On-screen planes are prioritized.`, + ); + state._lastModelCapWarnMs = nowMs; + } + const modelEligible = selectModelEligible(cand, { + cap, + addDistSq, + isModeled: (icao) => state._models.has(icao), + }); + const toRelease = []; + for (const icao of state._models.keys()) { + if (icao !== state._trackedIcao && !modelEligible.has(icao)) + toRelease.push(icao); + } + for (const icao of toRelease) _releaseModel(icao); + + // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown + // until the model is actually READY to render, so a plane is never both iconless AND + // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick + // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on + // purpose: the Easter egg IS the triangle, and there is no GLB for it. + const occluder = horizonOccluder(camera); + for (const icao24 of modelEligible) { + if (isTr3b(icao24)) continue; + const row = icons.row(icao24); + if (row < 0) continue; + const position = icons.position(row, tau, state._scratchFleetPos); + if (!parts.icons._aboveHorizon(row, position, occluder)) { + // A model that crossed the limb would keep rendering through the + // hidden globe at its last matrix; the icon's own cull is on the GPU. + const m = state._models.get(icao24); + if (m && modelState(m)?.show) setModel(m, 'show', false); + continue; + } + _ensureModel(icao24); + const model = state._models.get(icao24); + const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); + _driveFleetModelHandoff( + icao24, + model, + row, + position, + icons.course(row, tau), + () => { + applyAircraftModelTreatment({ + model, + // IR boost must survive the per-tick treatment write — otherwise + // any alpha change would repaint the ordinary tint over the hot + // white. Boosted models also skip the recession fade: hot targets + // stay full-strength at any range (icons keep their normal + // fade — full-opacity glyph walls read as overwhelming). + baseColor: state._irBoost + ? Cesium.Color.WHITE + : _modelColor(icao24), + alpha: state._irBoost + ? 1 + : aircraftTreatmentAlpha({ + baseAlpha: icons.alpha(row), + focusFactor: icons.focus(row), + cameraDistanceM, + cameraHeightM: camera.positionCartographic?.height, + }), + }); + }, + ); + } + } + return { + _modelRegimeActive, + _modelCap, + _modelAddDistM, + _modelKeepDistM, + _modelMatrix, + _groundSampleExclusions, + _modelDisplayPosition, + _driveFleetModelHandoff, + _modelOwnsVisual, + _modelIsRendering, + _specKeyFor, + _syncModelToClass, + _reloadModelsForIrBoost, + _drainIrReloadQueue, + _ensureModel, + _releaseModel, + _cleanupModelGen, + _releaseModels, + _showReleasedIcon, + _releaseTrackedModel, + _updateTrackedModel, + _fleetTick, + }; +} diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 0afc0fb96f..a39ae29542 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -1,4 +1,5 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs'; +import { readFileSync } from 'node:fs'; import test from 'node:test'; import assert from 'node:assert/strict'; @@ -39,9 +40,9 @@ for (const layer of LAYERS) { test(`${layer.name}: Cockpit 3D obeys the shared Display toggle`, () => { const regime = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(regime, '_modelRegimeActive is defined'); - assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, + assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, 'OFF must keep Cockpit AIR contacts in 2D'); - assert.doesNotMatch(regime, /!(?:flightState\.)?_models3dEnabled\s*&&\s*!(?:flightState\.)?_cockpitContactMode/, + assert.doesNotMatch(regime, /!(?:(?:flightState|state)\.)?_models3dEnabled\s*&&\s*!(?:(?:flightState|state)\.)?_cockpitContactMode/, 'Cockpit must not bypass the owner-visible Display toggle'); }); @@ -53,7 +54,7 @@ for (const layer of LAYERS) { // suppression is now an explicit early return. const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(regime, '_trackedModelRegimeActive is defined'); - assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/, + assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_trackedIcao\s*\|\|\s*(?:(?:flightState|state)\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/, '_trackedModelRegimeActive excludes cockpit'); const tracked = /^([ \t]*)function _updateTrackedModel\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(tracked, '_updateTrackedModel is defined'); @@ -70,13 +71,13 @@ for (const layer of LAYERS) { const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(add, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_ADD_M\s*:\s*MODEL_PROX_ADD_M/); - assert.match(keep, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_KEEP_M\s*:\s*MODEL_PROX_KEEP_M/); + assert.match(add, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_ADD_M\s*:\s*(?:policy\.)?MODEL_PROX_ADD_M/); + assert.match(keep, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_KEEP_M\s*:\s*(?:policy\.)?MODEL_PROX_KEEP_M/); assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/); assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/); const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(cap, /Math\.min\(\s*COCKPIT_MODEL_MAX/, + assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/, 'Cockpit keeps its 60-model performance ceiling'); }); @@ -100,7 +101,29 @@ for (const layer of LAYERS) { test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => { const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); + assert.match(setMode, /else\s*(?:(?:flightState|state)\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/); assert.match(setMode, /for \(let row = 0; row < \(icons\?\.count \?\? 0\); row\+\+\)\s*parts\.icons\._applyIconPresentation\(icons\.idAt\(row\)\);/); }); } + +// The source reads above include the shared model module, so they pass from it +// alone. These pin that each layer actually builds its models from it, and that +// flights keeps its own hooks. +const RENDERING = { + flights: new URL('../layers/flights/rendering.js', import.meta.url), + militaryFlights: new URL('../layers/military/rendering.js', import.meta.url), +}; + +for (const [name, url] of Object.entries(RENDERING)) { + test(`${name}: 3D models come from the shared aircraft model module`, () => { + const source = readFileSync(url, 'utf8'); + assert.match(source, /createAircraftModels\(\{/); + assert.match(source, /\.\.\.models\b/); + }); +} + +test('flights: model eligibility nudges enrichment and the tick floors grounded icons', () => { + const source = readFileSync(RENDERING.flights, 'utf8'); + assert.match(source, /onModelEligible:[\s\S]*?_requestTypeEnrichment\(icao24, true\)/); + assert.match(source, /afterReplan:[\s\S]*?_floorGroundedIcons\(/); +}); diff --git a/src/data/modelScale.test.mjs b/src/data/modelScale.test.mjs index 37cb1ca31a..e4f404ca8a 100644 --- a/src/data/modelScale.test.mjs +++ b/src/data/modelScale.test.mjs @@ -370,9 +370,9 @@ function layerConstants(sourceFile) { function normalBillboardScaleByDistance(sourceFile) { const src = readLayerSource(path.join(ROOT, sourceFile)); - const fn = src.match(/function (?:parts\.\w+\.)?_normalBillboardScaleByDistance\(\) \{([\s\S]*?)\n\}/); - assert.ok(fn, `${sourceFile}: _normalBillboardScaleByDistance not found`); - const scalar = fn[1].match(/NearFarScalar\((\d+), ([\d.]+), (\d+), ([\d.]+)\)/); + const fn = src.match(/const NORMAL_SCALE_BY_DISTANCE = ([\s\S]*?\);)/); + assert.ok(fn, `${sourceFile}: NORMAL_SCALE_BY_DISTANCE not found`); + const scalar = fn[1].match(/NearFarScalar\(\s*(\d+),\s*([\d.]+),\s*(\d+),\s*([\d.]+),?\s*\)/); assert.ok(scalar, `${sourceFile}: billboard NearFarScalar not found`); return scalar.slice(1).map(Number); } diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index fa0e705b21..09fd23e362 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -956,14 +956,14 @@ for (const fixture of LAYERS) { test('both layers gate the tracked-model load and record its failures', async () => { for (const name of ['flights.js', 'militaryFlights.js']) { const source = readLayerSource(new URL(`./${name}`, import.meta.url)); - assert.match(source, /!(?:flightState\.)?_trackedModel\s*&&\s*!(?:flightState\.)?_trackedModelLoading\s*&&\s*(?:parts\.\w+\.)?_trackedModelLoadAllowed\(\s*,?\s*\)/, + assert.match(source, /!(?:(?:flightState|state)\.)?_trackedModel\s*&&\s*!(?:(?:flightState|state)\.)?_trackedModelLoading\s*&&\s*(?:parts\.\w+\.)?_trackedModelLoadAllowed\(\s*,?\s*\)/, `${name}: the driver asks permission before starting another tracked-model load`); assert.match(source, /(?:parts\.\w+\.)?_noteTrackedModelLoadFailure\(\s*trackedSpec\.url,\s*err,?\s*\)/, `${name}: a rejected load is recorded against this selection, not silently retried`); // The reset must be reachable from the real teardown, not only a test seam. assert.match(source, /(?:parts\.\w+\.)?_releaseTrackedModel\(\s*,?\s*\);\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, `${name}: deselect clears the per-selection latches in the production path`); - assert.match(source, /(?:flightState\.)?_trackedIcao\s*=\s*icao24;\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, + assert.match(source, /(?:(?:flightState|state)\.)?_trackedIcao\s*=\s*icao24;\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/, `${name}: selecting a contact starts from a clean per-selection state`); } }); @@ -973,13 +973,13 @@ test('the tracked regime never consults the fleet models3d toggle', async () => const source = readLayerSource(new URL(`./${name}`, import.meta.url)); const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; assert.ok(regime, `${name}: _trackedModelRegimeActive is defined`); - assert.doesNotMatch(regime, /(?:flightState\.)?_models3dEnabled|(?:parts\.\w+\.)?_modelRegimeActive\(\s*,?\s*\)/, + assert.doesNotMatch(regime, /(?:(?:flightState|state)\.)?_models3dEnabled|(?:parts\.\w+\.)?_modelRegimeActive\(\s*,?\s*\)/, `${name}: the tracked contact's handoff is default-on, not gated on the fleet toggle`); assert.match(regime, /trackedModelZoomActive\(/, `${name}: the tracked contact uses the shared hysteretic zoom policy`); // The FLEET must still obey the toggle — the budget decision stays the operator's. const fleet = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0]; - assert.match(fleet, /if\s*\(\s*!(?:flightState\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, + assert.match(fleet, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/, `${name}: the fleet regime still obeys the DISPLAY-rail 3D toggle`); } }); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index c2a15bd7d3..397f554c31 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -1,33 +1,15 @@ import * as Cesium from 'cesium'; -import { selectModelEligible } from '../../data/modelEligibility.js'; import { civilAircraftModelSpec } from './modelSpec.js'; import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { isEmergency } from '../../data/aircraftEmergency.js'; -import { horizonOccluder } from '../../data/iconOrientation.js'; -import { aircraftTreatmentAlpha } from '../../data/aircraftRecession.js'; import { MIL_TINT, EMERGENCY_TINT, GROUND_SCALE, COCKPIT_CIVILIAN_COLOR, - MODEL_ALT_CEIL_M, - MODEL_MAX_ALL, - MODEL_MAX, - COCKPIT_MODEL_MAX, - MODEL_ALL_ADD_M, - MODEL_PROX_ADD_M, - MODEL_ALL_KEEP_M, - MODEL_PROX_KEEP_M, - MODEL_HEADING_OFFSET_DEG, - IR_RELOAD_BATCH, - MODEL_MIN_PX, - TRACKED_MODEL_MIN_PX, - TRACKED_MODEL_MAX_PX, - FLEET_DR_INTERVAL_MS, } from './policy.js'; -import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; -import { aircraftVisuals } from '../aircraft/visualState.js'; -import { modelState, setModel } from '../../data/modelMirror.js'; +import * as policy from './policy.js'; +import { createAircraftModels } from '../../data/aircraftModelLayer.js'; export function createRendering({ flightState, @@ -37,10 +19,7 @@ export function createRendering({ resolveAsset, }) { const { isMilitaryIcao } = services.militaryRegistry; - const { tr3bIconKind, isTr3b } = services.aircraftPresentation; - const { trackedModelScaleForPixelCap } = services.camera; - const { focusNowMs, getFocusTarget } = services.focus; - const { applyAircraftModelTreatment } = services.recession; + const { tr3bIconKind } = services.aircraftPresentation; /** True while this contact's latest poll broadcast an emergency code. */ @@ -87,16 +66,6 @@ export function createRendering({ return spec; } - function _normalBillboardScaleByDistance() { - // Preserve the established close-range 3× scale. Any smaller owner-visible - // default belongs in a separate evidence-backed proposal. - return new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5); - } - - function _cockpitBillboardScaleByDistance() { - return new Cesium.NearFarScalar(1000, 1.15, 8000000, 0.65); - } - /** Sprite kind for one contact's billboard. Identity for every aircraft except * the ones the operator converted into a TR-3B (Easter egg), which draw the * black-triangle glyph — its thermal-reactive variant while an IR style owns @@ -113,873 +82,34 @@ export function createRendering({ return _fleetBillboardColor(icao24); } - /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude - * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the - * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in - * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms - * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED - * contact does not route through here: it is one model, it is what the camera is aimed at, - * and it takes its own default-on, hysteretic zoom regime - * (`_trackedModelRegimeActive`). */ - - function _modelRegimeActive() { - if (!flightState._models3dEnabled) return false; - const h = - flightState._viewer?.camera?.positionCartographic?.height ?? Infinity; - return h < MODEL_ALT_CEIL_M; - } - - /** Active model cap — the eligibility pre-pass AND _ensureModel's admission checks must use the - * SAME value, else 'all' (MODEL_MAX_ALL) would mark planes eligible that _ensureModel then refuses - * at the lower MODEL_MAX, silently degrading 'all' to 'proximity'. */ - - function _modelCap() { - const mapCap = - flightState._models3dMode === 'all' ? MODEL_MAX_ALL : MODEL_MAX; - // `Math.min` on purpose: cockpit may only ever LOWER the GLB budget. Cockpit is - // already the heaviest mode (20 Hz camera setView ahead of scene update, photoreal - // retraversal, the cloud pass) and every model is its own draw call. - return flightState._cockpitContactMode - ? Math.min(COCKPIT_MODEL_MAX, mapCap) - : mapCap; - } - - /** Active ADD radius (m) — new planes inside this range get a model. Mode-aware: 'all' reaches far. */ - - function _modelAddDistM() { - return flightState._models3dMode === 'all' - ? MODEL_ALL_ADD_M - : MODEL_PROX_ADD_M; - } - - /** Active KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */ - - function _modelKeepDistM() { - return flightState._models3dMode === 'all' - ? MODEL_ALL_KEEP_M - : MODEL_PROX_KEEP_M; - } - - /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into - * `result` (a shared scratch by default) and returns it. Push it with `setModel`, which copies - * it into the app's mirror and the model's own matrix, so models never share one mutable matrix - * object. `Model.modelMatrix` is a plain field (not a cloning setter); Cesium - * clones it per frame in updateModelMatrix(). Sharing a single scratch made every model render at - * the LAST-written transform — all stacked on one plane — and, once the tracked model wrote the - * scratch every frame, the stack point oscillated frame-to-frame: the "flickering like mad" bug. */ - - function _modelMatrix( - pos, - headingDeg, - result = flightState._scratchModelMtx, - ) { - flightState._scratchModelHpr.heading = Cesium.Math.toRadians( - (headingDeg || 0) + MODEL_HEADING_OFFSET_DEG, - ); - flightState._scratchModelHpr.pitch = 0; - flightState._scratchModelHpr.roll = 0; - return Cesium.Transforms.headingPitchRollToFixedFrame( - pos, - flightState._scratchModelHpr, - Cesium.Ellipsoid.WGS84, - undefined, - result, - ); - } - - /** Everything scene.sampleHeight must NOT hit when snapping a grounded model: the - * vertical pick ray at a plane's own lat/lon otherwise lands on its (or a parked - * neighbor's) billboard/model instead of the tile skin. Cesium's ray-pick exclusion - * matches picked-object IDs, and every icon AND model in this layer carries its - * icao as `id`, so the icao strings cover both; the tracked entity is excluded as the - * object itself. Built lazily — only when a sample actually fires (one-shot). */ - - function _groundSampleExclusions() { - const out = parts.icons._iconIds(); - if (flightState._trackedEntity) out.push(flightState._trackedEntity); - return out; - } - - /** Position a 3D MODEL renders at. Airborne planes use their dead-reckoned position - * verbatim. GROUNDED planes' meta altitude is last-known baro or 0 m — nowhere near - * the photoreal tile skin in ellipsoid heights (buried ~100+ m at inland airports, - * hovering ~30 m at sea-level ones), and unlike the ground billboards a depth-tested - * model can't hide behind disableDepthTestDistance. So a modeled grounded plane rides - * a ONE-SHOT cached scene.sampleHeight of the skin at its lat/lon (groundSnap.js, - * CCTV-B9b discipline: never per-frame; taxiing >50 m retires the cached value to a - * bounded last-known and resamples), plus - * the belly offset so it sits on its gear rather than sinking to the model-origin - * fuselage centerline. Until the FIRST sample lands (tiles streaming / sample miss) - * there is no safe depth-tested placement at all: this returns null, the caller - * keeps the 2D billboard visible and the model hidden, and it retries later. Once - * a contact has resolved once, a later outage holds that measurement inside - * groundSnap's drift bound instead — a taxiing aircraft does not pop back to 2D - * because a resample is mid-backoff. */ - - function _modelDisplayPosition(icao24, pos, result) { - const meta = flightState.records.data.get(icao24); - if (!meta || !meta.onGround) return pos; - const h = flightState._groundSnap.heightFor( - flightState._viewer, - icao24, - pos, - _groundSampleExclusions, - ); - if (h == null) return null; - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - flightState._scratchGroundCarto, - ); - carto.height = h + _modelSpec(meta.klass).bellyM; - return Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height, - Cesium.Ellipsoid.WGS84, - result, - ); - } - - /** Atomically hand one fleet contact from its icon to a safely placed, - * ready 3D model. Missing/loading models and unresolved terrain always leave - * the icon owning the visual, so no render frame can hide both. - * `beforeShow` runs only on the committing path — the per-tick model treatment - * belongs to a model that is about to draw, not to one still waiting. */ - - function _driveFleetModelHandoff( - icao24, - model, - row, - pos, - course, - beforeShow, - ) { - const icons = flightState._icons; - if (!model) { - icons.setShown(row, true); - return false; - } - const displayPos = _modelDisplayPosition( - icao24, - pos, - flightState._scratchGroundPos, - ); - if (!displayPos) { - setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at - icons.setShown(row, true); - return false; - } - // The matrix is written BEFORE the readiness test on purpose: a model can flip - // `ready` during scene update after this tick, and a first rendered frame on a - // stale load-start matrix is the one-frame jump this ordering prevents. - setModel(model, 'modelMatrix', _modelMatrix(displayPos, course)); - if (!model.ready) { - setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash - icons.setShown(row, true); - return false; - } - beforeShow?.(); - if (!modelState(model).show) setModel(model, 'show', true); - icons.setShown(row, false); // hand off ONLY once the model renders - return true; - } - - /** - * Whether a 3D model — not the billboard — is what the user actually SEES for - * this contact, and therefore whether the display floor should stand aside. - * - * Model EXISTENCE is not ownership. A fleet model that is still loading, or has - * no resolved ground to stand on, stays hidden while `bb.show` stays true (the - * gap-proof handoff: "hand off ONLY once the model renders"), and a tracked model - * is retained but hidden whenever the model regime is off — 3D disabled, camera - * zoomed past the ceiling, or cockpit mode. Gating on `has()`/existence therefore - * suppressed the clamp in exactly the states where the BILLBOARD is the visual, - * putting the burial straight back. - * - * Cesium's own default `show === true` is the reason admission clears it - * explicitly: a fleet model registered in `_models` the instant its glTF resolves - * would otherwise claim ownership — at the identity matrix — for the frames - * between admission and the next fleet tick, while the BILLBOARD was still the - * visual. Ownership means actually rendering, and every site that sets `show` - * true does so only after committing a matrix. - * - * The two halves: - * - Fleet: the rendering test alone. Safe for the ground snap either way, - * because a fleet model is positioned from the RAW dead-reckon, not from - * the billboard. - * - Tracked: the rendering test AND `_trackedModelRegimeActive()`. The tracked - * model is fed from `_trackedDisplayPosition`, so once it is live the clamp - * must stand aside: two different chains would otherwise be deciding one - * contact's ground, and the billboard's is the one the operator is not - * looking at (T7). The regime check is what makes a regime - * flip take effect on the same frame rather than waiting for - * `_updateTrackedModel` to clear `show`; the rendering test is what keeps a - * null or still-loading tracked model from claiming a visual it is not - * drawing yet. - * @param {string} icao24 - * @param {Cesium.Model|null} [model] Resolved fleet model; null means absent. - * @returns {boolean} - */ - - function _modelOwnsVisual(icao24, model) { - if (icao24 === flightState._trackedIcao) { - return ( - parts.tracking._trackedModelRegimeActive() && - _modelIsRendering(flightState._trackedModel) - ); - } - return _modelIsRendering( - model === undefined ? flightState._models.get(icao24) : model, - ); - } - - /** A model is the visual only once it actually draws — loaded AND shown. - * - * `show` is sufficient evidence of a safe placement because only ONE site ever - * sets it true for a fleet model (`_driveFleetModelHandoff`, after the matrix is - * committed) and one for the tracked model (`_updateTrackedModel`, likewise); - * everything else — admission, an unresolved ground, a not-yet-ready glTF, the - * limb cull, a regime exit — only ever clears it. */ - - function _modelIsRendering(model) { - return !!model && model.ready === true && modelState(model)?.show === true; - } - - /** Spec identity for a LOADED model: URL and scale together (same-URL classes - * differ by scale — airliner vs quadjet both ship airplane.glb). */ - - const _specKeyFor = (klass) => { - const spec = _modelSpec(klass); - return `${spec.url}@${spec.scale}`; - }; - - /** Class-change model sync (enrichment AND poll-path klass updates): when the - * aircraft's live model or in-flight load no longer matches its class's spec, - * drop it so the eligibility pass reloads the right asset at the right scale. - * Gap-proof: the fleet billboard is re-shown BEFORE the release so the - * contact never goes invisible for the tick gap; _releaseModel's generation - * bump also invalidates any pending load. The tracked standalone model gets - * the same rule (its billboard entity is always the fallback visual). */ - - function _syncModelToClass(icao24) { - const key = _specKeyFor(flightState.records.data.get(icao24)?.klass); - const current = flightState._models.get(icao24); - if ( - (current && aircraftVisuals.read(current)?.specKey !== key) || - (!current && flightState._modelPending.has(icao24)) - ) { - _releaseModel(icao24); - } - if ( - icao24 === flightState._trackedIcao && - flightState._trackedModel && - aircraftVisuals.read(flightState._trackedModel)?.specKey !== key - ) { - _releaseTrackedModel(); - } - } - - function _reloadModelsForIrBoost() { - flightState._irReloadQueue = [...flightState._models.keys()]; - for (const icao of flightState._modelPending) { - if (!flightState._models.has(icao)) - flightState._modelGen.set( - icao, - (flightState._modelGen.get(icao) || 0) + 1, - ); - } - _releaseTrackedModel(); - } - - function _drainIrReloadQueue() { - if (!flightState._irReloadQueue) return; - const batch = flightState._irReloadQueue.splice(0, IR_RELOAD_BATCH); - for (const icao of batch) { - const model = flightState._models.get(icao); - if ( - !model || - aircraftVisuals.read(model)?.irBoost === flightState._irBoost - ) - continue; // already right state - _releaseModel(icao); - } - if (flightState._irReloadQueue.length === 0) - flightState._irReloadQueue = null; - } - - /** Lazily create the glTF model for an aircraft (fire-and-forget; billboard shows until ready). */ - - async function _ensureModel(icao24) { - // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet - // tick skips it, so a model here would be orphaned + double-rendered. - if (icao24 === flightState._trackedIcao) return; - parts.enrichment._requestTypeEnrichment(icao24, true); // model-eligible: about to render in 3D — jump the ambient backlog - if ( - flightState._models.has(icao24) || - flightState._modelPending.has(icao24) - ) - return; - // Count PENDING loads in the cap so a zoomed-in tick can't fire 100s of concurrent loads - // (the cap is rechecked post-await too, before the add). Mode-aware so 'all' can reach MAX_ALL. - if ( - flightState._models.size + flightState._modelPending.size >= - _modelCap() - ) - return; - const epoch = flightState._modelEpoch; // lifecycle token: if destroy() bumps it, this load is dead - const gen = flightState._modelGen.get(icao24) || 0; // capture; if it changes during the load, we're stale - flightState._modelPending.add(icao24); - let model = null; - // Spec identity captured at load START — if enrichment reclassifies the - // aircraft mid-load, the post-await admission below rejects the stale asset. - // Boost state likewise: the creation options bake it in, so a mid-load - // toggle must reject too (the reload queue only covers ADMITTED models). - const specKey = _specKeyFor(flightState.records.data.get(icao24)?.klass); - const loadIrBoost = flightState._irBoost; - try { - const spec = _modelSpec(flightState.records.data.get(icao24)?.klass); - model = await Cesium.Model.fromGltfAsync({ - url: resolveAsset(spec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: MODEL_MIN_PX, - scale: spec.scale, - color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), - colorBlendMode: Cesium.ColorBlendMode.MIX, - // Launch presentation keeps the code-side tint dominant for every approved - // model; IR boost removes the remaining diffuse hint with flat UNLIT white. - colorBlendAmount: flightState._irBoost ? 1.0 : spec.blendAmount, - customShader: flightState._irBoost - ? flightState._IR_UNLIT_SHADER - : undefined, - id: icao24, // so scene.pick returns the icao for click-to-track - }); - } catch { - // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current - // (a destroy/re-init may have swapped the globals while this load was in flight). - if (epoch === flightState._modelEpoch) { - flightState._modelPending.delete(icao24); - _cleanupModelGen(icao24); - } - return; - } - // A load from a PREVIOUS lifecycle (destroy→init happened mid-load) must NOT mutate the new - // epoch's _modelPending/_modelGen or add to the new collection — just drop its model. - if (epoch !== flightState._modelEpoch) { - try { - model.destroy(); - } catch { - /* gone */ - } - return; - } - flightState._modelPending.delete(icao24); - // Post-await admission: reject (and DESTROY the loaded model) if anything changed during the - // load — a release bumped the generation (track/untrack/remove), the layer toggled off / was - // torn down, the aircraft is gone or now tracked, a model already exists, or the cap filled. - // Recheck the shared Display 3D toggle and altitude ceiling after the async - // load. Cockpit uses the same OFF / Proximity / All contract as map Display. - const stale = - (flightState._modelGen.get(icao24) || 0) !== gen || - !_modelRegimeActive() || - !flightState._modelCollection || - flightState._modelCollection.isDestroyed() || - !flightState.records.data.has(icao24) || - icao24 === flightState._trackedIcao || - flightState._models.has(icao24) || - flightState._models.size >= _modelCap() || - // Class reclassified mid-load → this GLB/scale is for the OLD class. - _specKeyFor(flightState.records.data.get(icao24)?.klass) !== specKey || - // IR boost flipped mid-load → this model baked the wrong shader/tint. - flightState._irBoost !== loadIrBoost; - if (stale) { - try { - model.destroy(); - } catch { - /* already gone */ - } - _cleanupModelGen(icao24); // bound the map - return; - } - // Keep the pick identity explicit on the resolved primitive. This also - // protects injected/custom loaders that do not copy the creation option. - model.id = icao24; - const visual = aircraftVisuals.write(model); - visual.specKey = specKey; // class-change sync compares against this - visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this - // Admitted, not yet the visual. Cesium's default is show=true, which would let - // an unplaced primitive claim ownership from the icon for the frames - // between admission and the next fleet tick (and draw at the identity matrix, - // i.e. the Earth's centre). The handoff turns it on once it has a matrix. - setModel(model, 'show', false); - flightState._modelCollection.add(model); - flightState._models.set(icao24, model); - flightState._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard - } - - /** Remove the 3D model for ONE aircraft (removal / military-suppression / track handoff). - * Bumps the load generation so any in-flight load for this icao is rejected on completion. */ - - function _releaseModel(icao24) { - const m = flightState._models.get(icao24); - const pending = flightState._modelPending.has(icao24); - // Only bump the generation when there's something to invalidate (an in-flight load or a - // live model) — so removing never-modeled aircraft doesn't grow _modelGen. - if (m || pending) { - flightState._modelGen.set( - icao24, - (flightState._modelGen.get(icao24) || 0) + 1, - ); - } - if (m) { - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - try { - flightState._modelCollection.remove(m); - } catch { - /* gone */ - } - } - flightState._models.delete(icao24); - _showReleasedIcon(icao24); - } - // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping - // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so - // the resolving load's gen-check still rejects it. - _cleanupModelGen(icao24); - } - - /** Drop an icao's generation entry once nothing references it (no live model, no in-flight - * load) — keeps _modelGen bounded. Shared by _releaseModel + both _ensureModel exit paths. */ - - function _cleanupModelGen(icao24) { - if ( - !flightState._modelPending.has(icao24) && - !flightState._models.has(icao24) - ) - flightState._modelGen.delete(icao24); - } - - /** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */ - - function _releaseModels() { - flightState._irReloadQueue = null; // a full release supersedes any pending boost-flip drain - // Invalidate in-flight loads so a completion after this bulk release can't add a model. - for (const icao of flightState._modelPending) - flightState._modelGen.set( - icao, - (flightState._modelGen.get(icao) || 0) + 1, - ); - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - for (const m of flightState._models.values()) { - try { - flightState._modelCollection.remove(m); - } catch { - /* gone */ - } - } - } - for (const icao24 of flightState._models.keys()) _showReleasedIcon(icao24); - flightState._models.clear(); - } - - /** A released fleet model hands the visual straight back to its icon (the - * tracked contact's entity keeps its own). */ - - function _showReleasedIcon(icao24) { - const icons = flightState._icons; - const row = icons?.row(icao24) ?? -1; - if (row >= 0 && icao24 !== flightState._trackedIcao) - icons.setShown(row, true); - } - - /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ - - function _releaseTrackedModel() { - flightState._trackedModelGen++; - flightState._trackedModelLoading = false; - if (flightState._trackedModel) { - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - try { - flightState._modelCollection.remove(flightState._trackedModel); - } catch { - /* gone */ - } - } - flightState._trackedModel = null; - } - } - - /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet - * cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the - * follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed - * in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). */ - - function _updateTrackedModel() { - const active = - flightState._trackedIcao && - parts.tracking._trackedModelRegimeActive() && - flightState._modelCollection && - !flightState._modelCollection.isDestroyed(); - if (!active) { - if (flightState._trackedModel) - setModel(flightState._trackedModel, 'show', false); - return; - } - // Ask the frame-cached source directly. If the entity callback already ran, - // this is a no-op; if model loading completed between phases, it establishes - // this frame's single sample before the model renders. Camera, detection, and - // readout consumers then reuse that exact cached position. - const pos = - parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - parts.icons._iconPosition(flightState._trackedIcao); - if (!pos) { - if (flightState._trackedModel) - setModel(flightState._trackedModel, 'show', false); - return; - } - if ( - !flightState._trackedModel && - !flightState._trackedModelLoading && - parts.tracking._trackedModelLoadAllowed() - ) { - flightState._trackedModelLoading = true; - const gen = flightState._trackedModelGen; - const trackedSpec = _modelSpec( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - const trackedKey = _specKeyFor( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - const trackedIrBoost = flightState._irBoost; - Cesium.Model.fromGltfAsync({ - url: resolveAsset(trackedSpec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: TRACKED_MODEL_MIN_PX, - scale: trackedSpec.scale, - color: flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN, - colorBlendMode: Cesium.ColorBlendMode.MIX, - // The tracked aircraft uses the same dominant light tint as the fleet; - // IR boost removes the remaining diffuse hint with flat UNLIT white. - colorBlendAmount: flightState._irBoost ? 1.0 : trackedSpec.blendAmount, - customShader: flightState._irBoost - ? flightState._IR_UNLIT_SHADER - : undefined, - // Pick id (H1): without it, clicking the very plane being tracked read as - // EMPTY SPACE (scene.pick → primitive with no id) → an unintended - // deselect. With the icao, the click handler recognizes it as ours. - id: flightState._trackedIcao, - }) - .then((m) => { - // Untracked / re-tracked / torn down during the load → drop it. - if ( - gen !== flightState._trackedModelGen || - !flightState._modelCollection || - flightState._modelCollection.isDestroyed() - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - return; - } - // Class reclassified OR boost flipped mid-load (no release ran — - // _trackedModel was still null): drop the stale asset; driver reloads. - if ( - _specKeyFor( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ) !== trackedKey || - flightState._irBoost !== trackedIrBoost - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - flightState._trackedModelLoading = false; - return; - } - // Assign after resolution as well as in the creation options so the - // standalone primitive always exposes the tracked aircraft pick id. - m.id = flightState._trackedIcao; - aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this - setModel(m, 'show', false); // admitted, not yet the visual — the driver shows it once placed - // Seed the world transform before the primitive enters the scene. A model - // can become ready+shown between render phases; leaving Cesium's identity - // default here produces a one-frame jump to the Earth's center. - const currentPos = - parts.motion._trackedDisplayCached() || - parts.icons._iconPosition(flightState._trackedIcao); - if (currentPos) { - const displayPos = _modelDisplayPosition( - flightState._trackedIcao, - currentPos, - flightState._scratchGroundPos, - ); - if (displayPos) - setModel( - m, - 'modelMatrix', - _modelMatrix(displayPos, parts.motion._trackedDisplayCourse()), - ); - } - flightState._trackedModel = m; - flightState._trackedModelLoading = false; - // A good load retires this selection's failure budget — a contact that - // recovers after a transient blip is not one attempt from giving up. - flightState._trackedModelFailIcao = null; - flightState._trackedModelFailCount = 0; - flightState._trackedModelRetryAtMs = 0; - flightState._modelCollection.add(m); - flightState._planeModelLoaded = true; // GLB cached — the tracked billboard can fade out once the model is up - }) - .catch((err) => { - if (gen !== flightState._trackedModelGen) return; // superseded load — not this selection's failure - flightState._trackedModelLoading = false; - parts.tracking._noteTrackedModelLoadFailure(trackedSpec.url, err); - }); - return; // billboard carries the visual until the model is ready - } - if (flightState._trackedModel) { - // Keep the transform current while GPU resources are still loading. Cesium - // can flip ready during scene update after this callback; waiting for ready - // here would let that first rendered frame use a stale load-start matrix. - const displayPos = _modelDisplayPosition( - flightState._trackedIcao, - pos, - flightState._scratchGroundPos, - ); - if (!displayPos) { - setModel(flightState._trackedModel, 'show', false); // no ground evidence → the billboard carries it - return; - } - setModel( - flightState._trackedModel, - 'modelMatrix', - _modelMatrix(displayPos, parts.motion._trackedDisplayCourse()), - ); - if (!flightState._trackedModel.ready) return; - const spec = _modelSpec( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - flightState._trackedModel.scale = trackedModelScaleForPixelCap({ - baseScale: spec.scale, - nativeRadiusM: spec.nativeRadiusM, - rangeM: Cesium.Cartesian3.distance( - flightState._viewer.camera.positionWC, - displayPos, - ), - viewportHeightPx: flightState._viewer.scene.canvas.clientHeight, - fovyRad: flightState._viewer.camera.frustum.fovy, - maximumPixelSize: TRACKED_MODEL_MAX_PX, - }); - setModel(flightState._trackedModel, 'show', true); - } - } - - /** - * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and - * the two-tier glyph swap all run on the GPU from each row's segment, so this - * only re-plans rows whose regime ended, pins grounded contacts to the floor - * under them, advances focus de-emphasis while a target exists, and drives - * the 3D-model handoff inside the model regime. Driven by scene.preRender. - * @returns {void} - */ - - function _fleetTick() { - const icons = flightState._icons; - if (!flightState._viewer || !icons || !icons.show) return; - const scene = flightState._viewer.scene; - const camera = flightState._viewer.camera; - const nowMs = focusNowMs(Date.now()); - - if (nowMs - flightState._lastFleetTickMs < FLEET_DR_INTERVAL_MS) return; - flightState._lastFleetTickMs = nowMs; - // Every contact in this pass shares the same delayed display instant. - const renderTime = parts.icons._displayTime( - flightState._scratchFleetRenderTime, - ); - const tau = icons.seconds(renderTime); - - _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload - if (flightState._cockpitContactMode) - parts.tracking._refreshCockpitNearContacts(); - parts.icons._replanExpired(tau); - parts.icons._floorGroundedIcons(renderTime, tau, nowMs, camera.positionWC); - const focusTarget = getFocusTarget(); - parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget); - - // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. - // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. - const useModels = _modelRegimeActive(); - // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that - // resolves after zoom-out could briefly add a model outside the 3D-model regime). - if ( - !useModels && - (flightState._models.size || flightState._modelPending.size) - ) - _releaseModels(); - if (!useModels) return; - - // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the - // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen - // already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius, - // nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots - // (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint). - // Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an - // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap - // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum - // filtering dropped near off-screen planes entirely. This does both right. - const cap = _modelCap(); - const camPos = camera.positionWC; - const addM = _modelAddDistM(); - const addDistSq = addM * addM; - const keepM = _modelKeepDistM(); - const keepDistSq = keepM * keepM; - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, - ); - // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. - const cand = []; - for (let row = 0; row < icons.count; row++) { - const icao = icons.idAt(row); - if (icao === flightState._trackedIcao) continue; - // A converted TR-3B renders as an icon and can never take a model, so - // it must not occupy a CAP SLOT either — excluded here at selection time, - // not just at the handoff below, or accumulated conversions would starve - // ordinary contacts of 3D models. (The handoff guard stays as defence.) - if (isTr3b(icao)) continue; - // Ground planes compete for model slots like everyone else (owner decision - // 2026-07-03: "3D mode is respected regardless of whether a plane is on the - // ground or in the air — no distinction"). The cap + nearest-first ordering - // below already bound airport clusters; grounded placement is handled by the - // one-shot ground snap in _modelDisplayPosition. - const position = icons.position( - row, + const models = createAircraftModels({ + state: flightState, + services, + parts, + resolveAsset, + logLabel: 'Data:Flights', + policy, + modelSpec: _modelSpec, + modelColor: _modelColor, + // About to render in 3D: jump the ambient type-enrichment backlog. + onModelEligible: (icao24) => + parts.enrichment._requestTypeEnrichment(icao24, true), + afterReplan: (renderTime, tau, nowMs, camera) => + parts.icons._floorGroundedIcons( + renderTime, tau, - flightState._scratchModelBS.center, - ); - const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); - if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible - cand.push([ - icao, - d2, - cull.computeVisibility(flightState._scratchModelBS) !== - Cesium.Intersect.OUTSIDE, - ]); - } - cand.sort((a, b) => a[1] - b[1]); // nearest first - if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { - console.warn( - `[Data:Flights] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`, - ); - flightState._lastModelCapWarnMs = nowMs; - } - const modelEligible = selectModelEligible(cand, { - cap, - addDistSq, - isModeled: (icao) => flightState._models.has(icao), - }); - const toRelease = []; - for (const icao of flightState._models.keys()) { - if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) - toRelease.push(icao); - } - for (const icao of toRelease) _releaseModel(icao); + nowMs, + camera.positionWC, + ), + }); - // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown - // until the model is actually READY to render, so a plane is never both iconless AND - // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick - // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on - // purpose: the Easter egg IS the triangle, and there is no GLB for it. - const occluder = horizonOccluder(camera); - for (const icao24 of modelEligible) { - if (isTr3b(icao24)) continue; - const row = icons.row(icao24); - if (row < 0) continue; - const position = icons.position(row, tau, flightState._scratchFleetPos); - if (!parts.icons._aboveHorizon(row, position, occluder)) { - // A model that crossed the limb would keep rendering through the - // hidden globe at its last matrix; the icon's own cull is on the GPU. - const m = flightState._models.get(icao24); - if (m && modelState(m)?.show) setModel(m, 'show', false); - continue; - } - _ensureModel(icao24); - const model = flightState._models.get(icao24); - const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); - _driveFleetModelHandoff( - icao24, - model, - row, - position, - icons.course(row, tau), - () => { - applyAircraftModelTreatment({ - model, - // IR boost must survive the per-tick treatment write — otherwise - // any alpha change would repaint the ordinary tint over the hot - // white. Boosted models also skip the recession fade: hot targets - // stay full-strength at any range (icons keep their normal - // fade — full-opacity glyph walls read as overwhelming). - baseColor: flightState._irBoost - ? Cesium.Color.WHITE - : _modelColor(icao24), - alpha: flightState._irBoost - ? 1 - : aircraftTreatmentAlpha({ - baseAlpha: icons.alpha(row), - focusFactor: icons.focus(row), - cameraDistanceM, - cameraHeightM: camera.positionCartographic?.height, - }), - }); - }, - ); - } - } return { _fleetBillboardColor, _fleetBillboardScale, _cockpitContactColor, _modelSpec, - _normalBillboardScaleByDistance, - _cockpitBillboardScaleByDistance, _iconKind, _modelColor, - _modelRegimeActive, - _modelCap, - _modelAddDistM, - _modelKeepDistM, - _modelMatrix, - _groundSampleExclusions, - _modelDisplayPosition, - _driveFleetModelHandoff, - _modelOwnsVisual, - _modelIsRendering, - _specKeyFor, - _syncModelToClass, - _reloadModelsForIrBoost, - _drainIrReloadQueue, - _ensureModel, - _releaseModel, - _cleanupModelGen, - _releaseModels, - _releaseTrackedModel, - _updateTrackedModel, - _fleetTick, + ...models, }; } diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index 1d747e6eae..bc98a2c918 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -7,10 +7,6 @@ import { visualCenterForModel, trailAnchorForModel, } from '../../data/modelVisualAnchor.js'; -import * as Cesium from 'cesium'; -import { selectModelEligible } from '../../data/modelEligibility.js'; -import { horizonOccluder } from '../../data/iconOrientation.js'; -import { aircraftTreatmentAlpha } from '../../data/aircraftRecession.js'; import { isEmergency } from '../../data/aircraftEmergency.js'; import { PLANE_MODEL_SCALE, @@ -27,24 +23,10 @@ import { MIL_ICON_COLOR, TRACKED_ICON_COLOR, EMERGENCY_ICON_COLOR, - MODEL_ALT_CEIL_M, - MODEL_MAX_ALL, - MODEL_MAX, - COCKPIT_MODEL_MAX, - MODEL_ALL_ADD_M, - MODEL_PROX_ADD_M, - MODEL_ALL_KEEP_M, - MODEL_PROX_KEEP_M, - IR_RELOAD_BATCH, - MODEL_MIN_PX, MODEL_COLOR_BLEND_AMOUNT, - TRACKED_MODEL_MIN_PX, - TRACKED_MODEL_MAX_PX, - FLEET_DR_INTERVAL_MS, } from './policy.js'; -import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; -import { aircraftVisuals } from '../aircraft/visualState.js'; -import { modelState, setModel } from '../../data/modelMirror.js'; +import * as policy from './policy.js'; +import { createAircraftModels } from '../../data/aircraftModelLayer.js'; export function createRendering({ flightState, @@ -53,10 +35,7 @@ export function createRendering({ layer, resolveAsset, }) { - const { tr3bIconKind, isTr3b } = services.aircraftPresentation; - const { trackedModelScaleForPixelCap } = services.camera; - const { focusNowMs, getFocusTarget } = services.focus; - const { applyAircraftModelTreatment } = services.recession; + const { tr3bIconKind } = services.aircraftPresentation; function _modelSpec(klass) { let spec = flightState._specCache.get(klass); @@ -69,6 +48,7 @@ export function createRendering({ nativeRadiusM: real.radiusM, bellyM: real.bellyM, headingOffsetDeg: 180, + blendAmount: MODEL_COLOR_BLEND_AMOUNT, visualCenterNative: visualCenterForModel(real.url), trailAnchorNative: trailAnchorForModel(real.url), }; @@ -84,6 +64,7 @@ export function createRendering({ nativeRadiusM: PLANE_NATIVE_RADIUS_M, bellyM: PLANE_BELLY_OFFSET_NATIVE * scale, headingOffsetDeg: 180, + blendAmount: MODEL_COLOR_BLEND_AMOUNT, visualCenterNative: visualCenterForModel(PLANE_MODEL_URL), trailAnchorNative: trailAnchorForModel(PLANE_MODEL_URL), }; @@ -95,6 +76,7 @@ export function createRendering({ nativeRadiusM: MODEL_NATIVE_RADIUS_M, bellyM: MODEL_BELLY_OFFSET_NATIVE * scale, headingOffsetDeg: MODEL_HEADING_OFFSET_DEG, + blendAmount: MODEL_COLOR_BLEND_AMOUNT, visualCenterNative: visualCenterForModel(JET_MODEL_URL), trailAnchorNative: trailAnchorForModel(JET_MODEL_URL), }; @@ -103,16 +85,6 @@ export function createRendering({ return spec; } - function _normalBillboardScaleByDistance() { - // Match commercial flights and preserve the established close-range 3× - // default. Smaller owner-visible scaling must be proposed separately. - return new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5); - } - - function _cockpitBillboardScaleByDistance() { - return new Cesium.NearFarScalar(1000, 1.15, 8000000, 0.65); - } - /** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */ function _fleetBillboardScale(icao24) { @@ -154,829 +126,24 @@ export function createRendering({ const _cockpitContactColor = _fleetBillboardColor; - /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude - * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the - * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in - * view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms - * `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED - * contact does not route through here: it is one model, it is what the camera is aimed at, - * and it takes its own default-on, hysteretic zoom regime - * (`_trackedModelRegimeActive`). Mirror of flights.js. */ + const models = createAircraftModels({ + state: flightState, + services, + parts, + resolveAsset, + logLabel: 'Data:Military', + policy, + modelSpec: _modelSpec, + modelColor: _modelColor, + }); - function _modelRegimeActive() { - if (!flightState._models3dEnabled) return false; - const h = - flightState._viewer?.camera?.positionCartographic?.height ?? Infinity; - return h < MODEL_ALT_CEIL_M; - } - - /** Active model cap — the eligibility pre-pass AND _ensureModel's admission checks must use the - * SAME value, else 'all' (MODEL_MAX_ALL) marks planes eligible that _ensureModel refuses at the - * lower MODEL_MAX, silently degrading 'all' to 'proximity'. */ - - function _modelCap() { - const mapCap = - flightState._models3dMode === 'all' ? MODEL_MAX_ALL : MODEL_MAX; - // `Math.min` on purpose: cockpit may only ever LOWER the GLB budget. - return flightState._cockpitContactMode - ? Math.min(COCKPIT_MODEL_MAX, mapCap) - : mapCap; - } - - /** Active ADD/KEEP radii (m) — mode-aware ('all' reaches ~to the horizon). Mirror of flights.js. */ - - function _modelAddDistM() { - return flightState._models3dMode === 'all' - ? MODEL_ALL_ADD_M - : MODEL_PROX_ADD_M; - } - - function _modelKeepDistM() { - return flightState._models3dMode === 'all' - ? MODEL_ALL_KEEP_M - : MODEL_PROX_KEEP_M; - } - - /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into - * `result` (a shared scratch by default) and returns it. Push it with `setModel`, which copies - * it into the app's mirror and the model's own matrix, so models never share one mutable matrix - * object (see flights.js for the full rationale). */ - - function _modelMatrix( - pos, - headingDeg, - result = flightState._scratchModelMtx, - offsetDeg = MODEL_HEADING_OFFSET_DEG, - ) { - flightState._scratchModelHpr.heading = Cesium.Math.toRadians( - (headingDeg || 0) + offsetDeg, - ); - flightState._scratchModelHpr.pitch = 0; - flightState._scratchModelHpr.roll = 0; - return Cesium.Transforms.headingPitchRollToFixedFrame( - pos, - flightState._scratchModelHpr, - Cesium.Ellipsoid.WGS84, - undefined, - result, - ); - } - - /** Everything scene.sampleHeight must NOT hit when snapping a grounded model (mirror of - * flights.js): the vertical pick ray at a plane's own lat/lon otherwise lands on its - * (or a parked neighbor's) icon/model instead of the tile skin. Exclusion matches - * picked-object IDs — every icon AND model here carries its icao as `id` — plus - * the tracked entity object itself. Built lazily, only when a sample actually fires. */ - - function _groundSampleExclusions() { - const out = parts.icons._iconIds(); - if (flightState._trackedEntity) out.push(flightState._trackedEntity); - return out; - } - - /** Position a 3D MODEL renders at (mirror of flights.js — see the full rationale there). - * Grounded planes ride a ONE-SHOT cached scene.sampleHeight of the photoreal tile skin - * (groundSnap.js; taxiing >50 m retires it to a bounded last-known) plus the belly - * offset so they sit on their - * gear; airborne planes pass through. Until the FIRST sample lands, callers keep the - * icon visible and the model hidden while this returns null; a - * contact that has already resolved once holds that measurement through a later - * outage inside groundSnap's drift bound, so taxiing does not pop it back to 2D. */ - - function _modelDisplayPosition(icao24, pos, result) { - const meta = flightState.records.data.get(icao24); - if (!meta || !meta.onGround) return pos; - const h = flightState._groundSnap.heightFor( - flightState._viewer, - icao24, - pos, - _groundSampleExclusions, - ); - if (h == null) return null; - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - flightState._scratchGroundCarto, - ); - carto.height = h + _modelSpec(meta.klass).bellyM; - return Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height, - Cesium.Ellipsoid.WGS84, - result, - ); - } - - /** Atomically hand one fleet contact from its icon to a safely placed, - * ready 3D model. Missing/loading models and unresolved terrain always leave - * the icon owning the visual, so no render frame can hide both. - * `beforeShow` runs only on the committing path — the per-tick model treatment - * belongs to a model that is about to draw, not to one still waiting. */ - - function _driveFleetModelHandoff( - icao24, - model, - row, - pos, - course, - beforeShow, - ) { - const icons = flightState._icons; - if (!model) { - icons.setShown(row, true); - return false; - } - const displayPos = _modelDisplayPosition( - icao24, - pos, - flightState._scratchGroundPos, - ); - if (!displayPos) { - setModel(model, 'show', false); // no ground evidence → nothing safe to place a depth-tested model at - icons.setShown(row, true); - return false; - } - // The matrix is written BEFORE the readiness test on purpose: a model can flip - // `ready` during scene update after this tick, and a first rendered frame on a - // stale load-start matrix is the one-frame jump this ordering prevents. - setModel( - model, - 'modelMatrix', - _modelMatrix( - displayPos, - course, - undefined, - _modelSpec(flightState.records.data.get(icao24)?.klass) - .headingOffsetDeg, - ), - ); - if (!model.ready) { - setModel(model, 'show', false); // not loaded yet → keep the 2D icon, no half-model flash - icons.setShown(row, true); - return false; - } - beforeShow?.(); - if (!modelState(model).show) setModel(model, 'show', true); - icons.setShown(row, false); // hand off ONLY once the model renders - return true; - } - - /** A model owns the visual only while it is ready, shown, and (for the tracked - * primitive) inside the tracked-model regime. Mere existence/loading is not ownership. */ - - function _modelOwnsVisual(icao24) { - if (icao24 === flightState._trackedIcao) { - return ( - parts.tracking._trackedModelRegimeActive() && - _modelIsRendering(flightState._trackedModel) - ); - } - return _modelIsRendering(flightState._models.get(icao24)); - } - - /** `show` is sufficient evidence of a safe placement because only the handoff and - * the tracked driver ever set it true, and both do so after committing a matrix; - * everything else — admission, unresolved ground, an unready glTF, the limb cull, - * a regime exit — only ever clears it. Mirror of flights.js. */ - - function _modelIsRendering(model) { - return !!model && model.ready === true && modelState(model)?.show === true; - } - - /** Spec identity for a LOADED model — mirror of flights.js: URL and scale - * together (same-URL classes differ by scale). */ - - const _specKeyFor = (klass) => { - const spec = _modelSpec(klass); - return `${spec.url}@${spec.scale}`; - }; - - /** Class-change model sync — mirror of flights.js: drop a live model or - * in-flight load whose spec no longer matches the class, re-showing the - * fleet icon (on release, gap-proof) and covering the tracked standalone. */ - - function _syncModelToClass(icao24) { - const key = _specKeyFor(flightState.records.data.get(icao24)?.klass); - const current = flightState._models.get(icao24); - if ( - (current && aircraftVisuals.read(current)?.specKey !== key) || - (!current && flightState._modelPending.has(icao24)) - ) { - _releaseModel(icao24); - } - if ( - icao24 === flightState._trackedIcao && - flightState._trackedModel && - aircraftVisuals.read(flightState._trackedModel)?.specKey !== key - ) { - _releaseTrackedModel(); - } - } - - function _reloadModelsForIrBoost() { - flightState._irReloadQueue = [...flightState._models.keys()]; - for (const icao of flightState._modelPending) { - if (!flightState._models.has(icao)) - flightState._modelGen.set( - icao, - (flightState._modelGen.get(icao) || 0) + 1, - ); - } - _releaseTrackedModel(); - } - - function _drainIrReloadQueue() { - if (!flightState._irReloadQueue) return; - const batch = flightState._irReloadQueue.splice(0, IR_RELOAD_BATCH); - for (const icao of batch) { - const model = flightState._models.get(icao); - if ( - !model || - aircraftVisuals.read(model)?.irBoost === flightState._irBoost - ) - continue; // already right state - _releaseModel(icao); - } - if (flightState._irReloadQueue.length === 0) - flightState._irReloadQueue = null; - } - - /** Lazily create the glTF model for an aircraft (fire-and-forget; its icon shows until ready). */ - - async function _ensureModel(icao24) { - // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet - // tick skips it, so a model here would be orphaned + double-rendered. - if (icao24 === flightState._trackedIcao) return; - if ( - flightState._models.has(icao24) || - flightState._modelPending.has(icao24) - ) - return; - // Count PENDING loads in the cap so a zoomed-in tick can't fire 100s of concurrent loads - // (the cap is rechecked post-await too, before the add). - if ( - flightState._models.size + flightState._modelPending.size >= - _modelCap() - ) - return; - const epoch = flightState._modelEpoch; // lifecycle token: if destroy() bumps it, this load is dead - const gen = flightState._modelGen.get(icao24) || 0; // capture; if it changes during the load, we're stale - flightState._modelPending.add(icao24); - let model = null; - // Spec identity captured at load START (mirror of flights.js): a mid-load - // reclassification makes the post-await admission reject the stale asset. - // Boost state likewise — creation options bake it in. - const specKey = _specKeyFor(flightState.records.data.get(icao24)?.klass); - const loadIrBoost = flightState._irBoost; - try { - const spec = _modelSpec(flightState.records.data.get(icao24)?.klass); - model = await Cesium.Model.fromGltfAsync({ - url: resolveAsset(spec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: MODEL_MIN_PX, - scale: spec.scale, - color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), - colorBlendMode: Cesium.ColorBlendMode.MIX, - // near self-illuminated tint so planes read uniform near AND far; IR boost → flat UNLIT white (hot) - colorBlendAmount: flightState._irBoost ? 1.0 : MODEL_COLOR_BLEND_AMOUNT, - customShader: flightState._irBoost - ? flightState._IR_UNLIT_SHADER - : undefined, - id: icao24, // so scene.pick returns the icao for click-to-track - }); - } catch { - // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current - // (a destroy/re-init may have swapped the globals while this load was in flight). - if (epoch === flightState._modelEpoch) { - flightState._modelPending.delete(icao24); - _cleanupModelGen(icao24); - } - return; - } - // A load from a PREVIOUS lifecycle (destroy→init happened mid-load) must NOT mutate the new - // epoch's _modelPending/_modelGen or add to the new collection — just drop its model. - if (epoch !== flightState._modelEpoch) { - try { - model.destroy(); - } catch { - /* gone */ - } - return; - } - flightState._modelPending.delete(icao24); - // Post-await admission: reject (and DESTROY the loaded model) if anything changed during the - // load — a release bumped the generation (track/untrack/remove), the layer toggled off / was - // torn down, the aircraft is gone or now tracked, a model already exists, or the cap filled. - // Recheck the shared Display 3D toggle and altitude ceiling after the async - // load. Cockpit uses the same OFF / Proximity / All contract as map Display. - const stale = - (flightState._modelGen.get(icao24) || 0) !== gen || - !_modelRegimeActive() || - !flightState._modelCollection || - flightState._modelCollection.isDestroyed() || - !flightState.records.data.has(icao24) || - icao24 === flightState._trackedIcao || - flightState._models.has(icao24) || - flightState._models.size >= _modelCap() || - // Class reclassified mid-load → this GLB/scale is for the OLD class. - _specKeyFor(flightState.records.data.get(icao24)?.klass) !== specKey || - // IR boost flipped mid-load → this model baked the wrong shader/tint. - flightState._irBoost !== loadIrBoost; - if (stale) { - try { - model.destroy(); - } catch { - /* already gone */ - } - _cleanupModelGen(icao24); // bound the map - return; - } - // Keep the pick identity explicit on the resolved primitive. This also - // protects injected/custom loaders that do not copy the creation option. - model.id = icao24; - const visual = aircraftVisuals.write(model); - visual.specKey = specKey; // class-change sync compares against this - visual.irBoost = loadIrBoost; // boost-flip reload queue compares against this - // Admitted, not yet the visual. Cesium's default is show=true, which would let - // an unplaced primitive claim ownership from the icon for the frames - // between admission and the next fleet tick (and draw at the identity matrix, - // i.e. the Earth's centre). The handoff turns it on once it has a matrix. - setModel(model, 'show', false); - flightState._modelCollection.add(model); - flightState._models.set(icao24, model); - flightState._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard - } - - /** Remove the 3D model for ONE aircraft (removal / track handoff). - * Bumps the load generation so any in-flight load for this icao is rejected on completion. */ - - function _releaseModel(icao24) { - const m = flightState._models.get(icao24); - const pending = flightState._modelPending.has(icao24); - // Only bump the generation when there's something to invalidate (an in-flight load or a - // live model) — so removing never-modeled aircraft doesn't grow _modelGen. - if (m || pending) { - flightState._modelGen.set( - icao24, - (flightState._modelGen.get(icao24) || 0) + 1, - ); - } - if (m) { - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - try { - flightState._modelCollection.remove(m); - } catch { - /* gone */ - } - } - flightState._models.delete(icao24); - _showReleasedIcon(icao24); - } - // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping - // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so - // the resolving load's gen-check still rejects it. - _cleanupModelGen(icao24); - } - - /** Drop an icao's generation entry once nothing references it (no live model, no in-flight - * load) — keeps _modelGen bounded. Shared by _releaseModel + both _ensureModel exit paths. */ - - function _cleanupModelGen(icao24) { - if ( - !flightState._modelPending.has(icao24) && - !flightState._models.has(icao24) - ) - flightState._modelGen.delete(icao24); - } - - /** Remove all live models (toggle-off / zoom-out); icons take back over at once. */ - - function _releaseModels() { - flightState._irReloadQueue = null; // a full release supersedes any pending boost-flip drain - // Invalidate in-flight loads so a completion after this bulk release can't add a model. - for (const icao of flightState._modelPending) - flightState._modelGen.set( - icao, - (flightState._modelGen.get(icao) || 0) + 1, - ); - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - for (const m of flightState._models.values()) { - try { - flightState._modelCollection.remove(m); - } catch { - /* gone */ - } - } - } - for (const icao24 of flightState._models.keys()) _showReleasedIcon(icao24); - flightState._models.clear(); - } - - /** A released fleet model hands the visual straight back to its icon (the - * tracked contact's entity keeps its own). */ - - function _showReleasedIcon(icao24) { - const icons = flightState._icons; - const row = icons?.row(icao24) ?? -1; - if (row >= 0 && icao24 !== flightState._trackedIcao) - icons.setShown(row, true); - } - - /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ - - function _releaseTrackedModel() { - flightState._trackedModelGen++; - flightState._trackedModelLoading = false; - if (flightState._trackedModel) { - if ( - flightState._modelCollection && - !flightState._modelCollection.isDestroyed() - ) { - try { - flightState._modelCollection.remove(flightState._trackedModel); - } catch { - /* gone */ - } - } - flightState._trackedModel = null; - } - } - - /** Per-frame driver for the standalone tracked model (see flights.js for the rationale). The - * tracked entity stays a pure billboard, so the follow-camera never stalls/freezes on 3D-toggle. */ - - function _updateTrackedModel() { - const active = - flightState._trackedIcao && - parts.tracking._trackedModelRegimeActive() && - flightState._modelCollection && - !flightState._modelCollection.isDestroyed(); - if (!active) { - if (flightState._trackedModel) - setModel(flightState._trackedModel, 'show', false); - return; - } - // Ask the frame-cached source directly. If the entity callback already ran, - // this is a no-op; if model loading completed between phases, it establishes - // this frame's single sample before the model renders. Camera, detection, and - // readout consumers then reuse that exact cached position. - const pos = - parts.motion._trackedDisplayPosition(flightState._trackedIcao) || - parts.icons._iconPosition(flightState._trackedIcao); - if (!pos) { - if (flightState._trackedModel) - setModel(flightState._trackedModel, 'show', false); - return; - } - if ( - !flightState._trackedModel && - !flightState._trackedModelLoading && - parts.tracking._trackedModelLoadAllowed() - ) { - flightState._trackedModelLoading = true; - const gen = flightState._trackedModelGen; - const trackedSpec = _modelSpec( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - const trackedKey = _specKeyFor( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - const trackedIrBoost = flightState._irBoost; - Cesium.Model.fromGltfAsync({ - url: resolveAsset(trackedSpec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: TRACKED_MODEL_MIN_PX, - scale: trackedSpec.scale, - color: flightState._irBoost ? Cesium.Color.WHITE : TRACKED_ICON_COLOR, - colorBlendMode: Cesium.ColorBlendMode.MIX, - // near self-illuminated tint so planes read uniform near AND far; IR boost → flat UNLIT white (hot) - colorBlendAmount: flightState._irBoost ? 1.0 : MODEL_COLOR_BLEND_AMOUNT, - customShader: flightState._irBoost - ? flightState._IR_UNLIT_SHADER - : undefined, - // Pick id (H1): without it, clicking the very plane being tracked read as - // EMPTY SPACE (scene.pick → primitive with no id) → an unintended - // deselect. With the icao, the click handler recognizes it as ours. - id: flightState._trackedIcao, - }) - .then((m) => { - if ( - gen !== flightState._trackedModelGen || - !flightState._modelCollection || - flightState._modelCollection.isDestroyed() - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - return; - } - // Class reclassified OR boost flipped mid-load (no release ran — - // _trackedModel was still null): drop the stale asset; driver reloads. - if ( - _specKeyFor( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ) !== trackedKey || - flightState._irBoost !== trackedIrBoost - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - flightState._trackedModelLoading = false; - return; - } - // Assign after resolution as well as in the creation options so the - // standalone primitive always exposes the tracked aircraft pick id. - m.id = flightState._trackedIcao; - aircraftVisuals.write(m).specKey = trackedKey; // class-change sync compares against this - setModel(m, 'show', false); // admitted, not yet the visual — the driver shows it once placed - // Seed the world transform before the primitive enters the scene. A model - // can become ready+shown between render phases; leaving Cesium's identity - // default here produces a one-frame jump to the Earth's center. - const currentPos = - parts.motion._trackedDisplayCached() || - parts.icons._iconPosition(flightState._trackedIcao); - if (currentPos) { - const displayPos = _modelDisplayPosition( - flightState._trackedIcao, - currentPos, - flightState._scratchGroundPos, - ); - if (displayPos) { - setModel( - m, - 'modelMatrix', - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - undefined, - trackedSpec.headingOffsetDeg, - ), - ); - } - } - flightState._trackedModel = m; - flightState._trackedModelLoading = false; - // A good load retires this selection's failure budget — a contact that - // recovers after a transient blip is not one attempt from giving up. - flightState._trackedModelFailIcao = null; - flightState._trackedModelFailCount = 0; - flightState._trackedModelRetryAtMs = 0; - flightState._modelCollection.add(m); - flightState._planeModelLoaded = true; - }) - .catch((err) => { - if (gen !== flightState._trackedModelGen) return; // superseded load — not this selection's failure - flightState._trackedModelLoading = false; - parts.tracking._noteTrackedModelLoadFailure(trackedSpec.url, err); - }); - return; - } - if (flightState._trackedModel) { - // Keep the transform current while GPU resources are still loading. Cesium - // can flip ready during scene update after this callback; waiting for ready - // here would let that first rendered frame use a stale load-start matrix. - const displayPos = _modelDisplayPosition( - flightState._trackedIcao, - pos, - flightState._scratchGroundPos, - ); - if (!displayPos) { - setModel(flightState._trackedModel, 'show', false); // no ground evidence → the billboard carries it - return; - } - const spec = _modelSpec( - flightState.records.data.get(flightState._trackedIcao)?.klass, - ); - setModel( - flightState._trackedModel, - 'modelMatrix', - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - undefined, - spec.headingOffsetDeg, - ), - ); - if (!flightState._trackedModel.ready) return; - flightState._trackedModel.scale = trackedModelScaleForPixelCap({ - baseScale: spec.scale, - nativeRadiusM: spec.nativeRadiusM, - rangeM: Cesium.Cartesian3.distance( - flightState._viewer.camera.positionWC, - displayPos, - ), - viewportHeightPx: flightState._viewer.scene.canvas.clientHeight, - fovyRad: flightState._viewer.camera.frustum.fovy, - maximumPixelSize: TRACKED_MODEL_MAX_PX, - }); - setModel(flightState._trackedModel, 'show', true); - } - } - - /** - * ~12 Hz fleet pass. Motion, rotation, the horizon cull, limb recession and - * the two-tier glyph swap all run on the GPU from each row's segment, so this - * only re-plans rows whose regime ended, advances focus de-emphasis while a - * target exists, and drives the 3D-model handoff inside the model regime. - * Driven by scene.preRender. - * @returns {void} - */ - - function _fleetTick() { - const icons = flightState._icons; - if (!flightState._viewer || !icons || !icons.show) return; - const scene = flightState._viewer.scene; - const camera = flightState._viewer.camera; - const nowMs = focusNowMs(Date.now()); - - if (nowMs - flightState._lastFleetTickMs < FLEET_DR_INTERVAL_MS) return; - flightState._lastFleetTickMs = nowMs; - // Every contact in this pass shares the same delayed display instant. - const renderTime = parts.icons._displayTime( - flightState._scratchFleetRenderTime, - ); - const tau = icons.seconds(renderTime); - - _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload - if (flightState._cockpitContactMode) - parts.tracking._refreshCockpitNearContacts(); - parts.icons._replanExpired(tau); - const focusTarget = getFocusTarget(); - parts.icons._focusIcons(tau, scene, camera, nowMs, focusTarget); - - // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. - // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. - const useModels = _modelRegimeActive(); - // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that - // resolves after zoom-out could briefly add a model outside the 3D-model regime). - if ( - !useModels && - (flightState._models.size || flightState._modelPending.size) - ) - _releaseModels(); - if (!useModels) return; - - // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the - // cap. FOUR passes, visible-first, so the slots are spent on what you can see: (1) KEEP on-screen - // already-modeled (hysteresis for visible planes); (2) ADD on-screen new inside the add radius, - // nearest first; (3) KEEP off-screen already-modeled; (4) ADD off-screen new with leftover slots - // (so a plane just off the cone still models — the "planes right next to me aren't 3D" complaint). - // Crucially KEEP is SPLIT by frustum: an off-screen retained model (pass 3) can never starve an - // on-screen plane that wants one (passes 1–2) — a single KEEP-everything pass could fill the cap - // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum - // filtering dropped near off-screen planes entirely. This does both right. - const cap = _modelCap(); - const camPos = camera.positionWC; - const addM = _modelAddDistM(); - const addDistSq = addM * addM; - const keepM = _modelKeepDistM(); - const keepDistSq = keepM * keepM; - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, - ); - // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. - const cand = []; - for (let row = 0; row < icons.count; row++) { - const icao = icons.idAt(row); - if (icao === flightState._trackedIcao) continue; - // A converted TR-3B renders as an icon and can never take a model, so - // it must not occupy a CAP SLOT either — excluded here at selection time, - // not just at the handoff below, or accumulated conversions would starve - // ordinary contacts of 3D models. (The handoff guard stays as defence.) - if (isTr3b(icao)) continue; - // Ground planes compete for model slots like everyone else (owner decision - // 2026-07-03: "3D mode is respected regardless of whether a plane is on the - // ground or in the air — no distinction"). The cap + nearest-first ordering - // below already bound airport clusters; grounded placement is handled by the - // one-shot ground snap in _modelDisplayPosition. - const position = icons.position( - row, - tau, - flightState._scratchModelBS.center, - ); - const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); - if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible - cand.push([ - icao, - d2, - cull.computeVisibility(flightState._scratchModelBS) !== - Cesium.Intersect.OUTSIDE, - ]); - } - cand.sort((a, b) => a[1] - b[1]); // nearest first - if (cand.length > cap && nowMs - flightState._lastModelCapWarnMs > 5000) { - console.warn( - `[Data:Military] ${cand.length} planes in 3D range; capped at ${cap} (${flightState._models3dMode}). On-screen planes are prioritized.`, - ); - flightState._lastModelCapWarnMs = nowMs; - } - const modelEligible = selectModelEligible(cand, { - cap, - addDistSq, - isModeled: (icao) => flightState._models.has(icao), - }); - const toRelease = []; - for (const icao of flightState._models.keys()) { - if (icao !== flightState._trackedIcao && !modelEligible.has(icao)) - toRelease.push(icao); - } - for (const icao of toRelease) _releaseModel(icao); - - // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown - // until the model is actually READY to render, so a plane is never both iconless AND - // modelless (the "planes vanish when 3D turns on" bug). Position the model every tick - // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on - // purpose: the Easter egg IS the triangle, and there is no GLB for it. - const occluder = horizonOccluder(camera); - for (const icao24 of modelEligible) { - if (isTr3b(icao24)) continue; - const row = icons.row(icao24); - if (row < 0) continue; - const position = icons.position(row, tau, flightState._scratchFleetPos); - if (!parts.icons._aboveHorizon(row, position, occluder)) { - // A model that crossed the limb would keep rendering through the - // hidden globe at its last matrix; the icon's own cull is on the GPU. - const m = flightState._models.get(icao24); - if (m && modelState(m)?.show) setModel(m, 'show', false); - continue; - } - _ensureModel(icao24); - const model = flightState._models.get(icao24); - const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); - _driveFleetModelHandoff( - icao24, - model, - row, - position, - icons.course(row, tau), - () => { - applyAircraftModelTreatment({ - model, - // IR boost must survive the per-tick treatment write — otherwise - // any alpha change would repaint the ordinary tint over the hot - // white. Boosted models also skip the recession fade: hot targets - // stay full-strength at any range (icons keep their normal - // fade — full-opacity glyph walls read as overwhelming). - baseColor: flightState._irBoost - ? Cesium.Color.WHITE - : _modelColor(icao24), - alpha: flightState._irBoost - ? 1 - : aircraftTreatmentAlpha({ - baseAlpha: icons.alpha(row), - focusFactor: icons.focus(row), - cameraDistanceM, - cameraHeightM: camera.positionCartographic?.height, - }), - }); - }, - ); - } - } return { _modelSpec, - _normalBillboardScaleByDistance, - _cockpitBillboardScaleByDistance, _fleetBillboardScale, _cockpitContactColor, _iconKind, _modelColor, _fleetBillboardColor, - _modelRegimeActive, - _modelCap, - _modelAddDistM, - _modelKeepDistM, - _modelMatrix, - _groundSampleExclusions, - _modelDisplayPosition, - _driveFleetModelHandoff, - _modelOwnsVisual, - _modelIsRendering, - _specKeyFor, - _syncModelToClass, - _reloadModelsForIrBoost, - _drainIrReloadQueue, - _ensureModel, - _releaseModel, - _cleanupModelGen, - _releaseModels, - _releaseTrackedModel, - _updateTrackedModel, - _fleetTick, + ...models, }; } diff --git a/src/testSupport/readLayerSource.mjs b/src/testSupport/readLayerSource.mjs index 07a8712418..47d92031f8 100644 --- a/src/testSupport/readLayerSource.mjs +++ b/src/testSupport/readLayerSource.mjs @@ -45,9 +45,12 @@ export function readLayerSource(file) { ? '../layers/cctv' : '../layers/vessels', ); - // The aircraft layers draw through one shared icon layer; it is their code too. + // The aircraft layers draw through shared icon and model layers; they are + // their code too. const shared = ['flights.js', 'militaryFlights.js'].includes(basename(path)) - ? [join(dirname(path), 'aircraftIconLayer.js')] + ? ['aircraftIconLayer.js', 'aircraftModelLayer.js'].map((name) => + join(dirname(path), name), + ) : []; return readdirSync(directory) .filter((name) => name.endsWith('.js')) diff --git a/src/ui/cyberTheme.test.mjs b/src/ui/cyberTheme.test.mjs index da84f29d57..d001a77c4d 100644 --- a/src/ui/cyberTheme.test.mjs +++ b/src/ui/cyberTheme.test.mjs @@ -650,8 +650,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', () const hud = read('../hud.js'); const hudView = read('./views/IntelHudView.vue'); const detection = read('../data/detection.js'); - const civilRendering = read('../layers/flights/rendering.js'); - const militaryRendering = read('../layers/military/rendering.js'); + const aircraftModels = read('../data/aircraftModelLayer.js'); const setHud = GEV_ACTION_SCHEMAS.find((schema) => schema.name === 'set_hud'); assert.match(display, /