diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8b01b335ad..ed3531e5cb 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -10,6 +10,20 @@ or an older position from another feed) and one reported slower than 2 m/s give no course and keep the last; an aircraft with no course at all faces north. +A selected vessel, aircraft or military aircraft can be found again from its +Context card. While it is off screen, behind the globe or out of its layer's +feed (the clock jumped to a time the feed lacks it, or the view moved away +from it), the card's header shows Find it (`store.locate()`, +`src/ui/stores/entityCard.js`). One still in its feed is flown to (an +aircraft followed). One out of its feed is looked up at the layer's time on +its own track (`locate` on the vessels, flights and military layers, through +`locateOnTrack` in `src/data/locate.js`): the newest point at or before the +world clock's time while the layer follows the clock, else the newest. The card +moves to it and says how old that reading is, and the camera flies there. Once +the feed has it again, its layer selects it again (an aircraft is followed). +With no point at or before the time, the card says there is no reading then and +the camera stays. A followed item is never counted as off screen. + While anything moves (a layer in motion, the camera, a followed contact), the globe draws at the display's own refresh rate; there is no fixed 60 FPS cap. The render governor (`src/renderGovernor.js`) caps a parked scene at diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index cea396ce3a..babd7e52b0 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1690,6 +1690,7 @@ "src/data/aircraftEmergency.js", "src/ui/stores/entityCard.js", "src/ui/entityContextBridge.js", + "src/data/locate.js", "src/data/trackingClickGesture.js", "src/ui/stores/sceneSharing.js", "src/maps/attribution.js", @@ -1966,6 +1967,7 @@ "src/layers/flights/policy.js", "src/render/color.js", "src/layers/flights/queries.js", + "src/data/locate.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -2117,6 +2119,7 @@ "src/layers/military/policy.js", "src/render/color.js", "src/layers/military/queries.js", + "src/data/locate.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -2284,6 +2287,7 @@ "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/data/locate.js", "src/geo/vector.js", "src/layers/vessels/rendering.js", "src/render/camera/poseSignature.js", @@ -5533,6 +5537,7 @@ "src/data/entityContext.js", "src/ui/stores/entityCard.js", "src/ui/entityContextBridge.js", + "src/data/locate.js", "src/render/cesium/cardPreviews.js" ], "external": [ @@ -5974,6 +5979,7 @@ "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/data/locate.js", "src/layers/vessels/rendering.js", "src/render/motion/iconBook.js", "src/layers/vessels/iconBook.js", diff --git a/src/data/locate.js b/src/data/locate.js new file mode 100644 index 0000000000..7845820f6b --- /dev/null +++ b/src/data/locate.js @@ -0,0 +1,102 @@ +import { fromDegreesInto } from '../geo/ellipsoid.js'; + +/** + * Finding a selected vessel or aircraft again once it has left the screen or + * its layer's feed: where its own track has it at a time, and whether a point + * is on screen at all. + */ + +/** + * The newest point of a track at or before `atMs` (any time when `atMs` is + * not given), from a live source's `getTrack` records + * (`{observedAtMs, latitude, longitude, baroAltitudeM?}`). + * @param {Array} points + * @param {number} [atMs] + * @returns {{lat: number, lon: number, altitudeM: ?number, observedAtMs: number}|null} + */ +export function readingAt(points, atMs) { + let best = null; + for (const point of points ?? []) { + const lat = Number(point?.latitude); + const lon = Number(point?.longitude); + const observedAtMs = point?.observedAtMs; + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + if (!Number.isFinite(observedAtMs)) continue; + if (Number.isFinite(atMs) && observedAtMs > atMs) continue; + if (best && best.observedAtMs >= observedAtMs) continue; + const altitude = Number(point.baroAltitudeM ?? point.altitudeM); + best = { + lat, + lon, + altitudeM: Number.isFinite(altitude) ? altitude : null, + observedAtMs, + }; + } + return best; +} + +/** + * Where a source's track has a vessel or aircraft at `atMs` (now, when not + * given): `{status: 'found', lat, lon, altitudeM, observedAtMs, atMs}`, or + * `{status: 'none'}` when the track has no point at or before the time, the + * source keeps no tracks or the lookup fails. + * @param {{getTrack?: Function}|null} source + * @param {string} reference The track reference the layer's records carry. + * @param {{atMs?: number, signal?: AbortSignal}} [options] + */ +export async function locateOnTrack(source, reference, { atMs, signal } = {}) { + if (typeof source?.getTrack !== 'function' || !reference) + return { status: 'none' }; + try { + const track = await source.getTrack( + reference, + Number.isFinite(atMs) ? { signal, atMs } : { signal }, + ); + const reading = readingAt(track?.records, atMs); + // The time it was looked up for, so its reading's age can be told. + const at = Number.isFinite(atMs) ? atMs : Date.now(); + return reading + ? { status: 'found', ...reading, atMs: at } + : { status: 'none' }; + } catch (error) { + if (signal?.aborted) throw error; + return { status: 'none' }; + } +} + +/** Mean Earth radius (m), for the horizon test. */ +const EARTH_RADIUS_M = 6_371_000; + +/** + * Whether a point is in the camera's view: in front of it, inside its field + * of view and on the near side of the globe. + * @param {{position: {x, y, z}, direction: {x, y, z}, up: {x, y, z}, + * right: {x, y, z}, fovy: number, aspectRatio: number}} pose + * @param {number} lat + * @param {number} lon + * @param {number} [heightM] + * @returns {boolean} + */ +export function onScreen(pose, lat, lon, heightM = 0) { + if (!pose?.position || !Number.isFinite(lat) || !Number.isFinite(lon)) + return false; + const p = fromDegreesInto(lon, lat, Math.max(0, heightM || 0), { + x: 0, + y: 0, + z: 0, + }); + const c = pose.position; + const v = { x: p.x - c.x, y: p.y - c.y, z: p.z - c.z }; + const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z; + const ahead = dot(v, pose.direction); + if (!(ahead > 0)) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * (pose.aspectRatio || 1); + if (Math.abs(dot(v, pose.right) / ahead) > tanX) return false; + if (Math.abs(dot(v, pose.up) / ahead) > tanY) return false; + // Behind the globe: the camera is below the point's horizon plane. Judged + // on a sphere through the point, which is close enough for a button. + const length = Math.hypot(p.x, p.y, p.z) || EARTH_RADIUS_M; + const normal = { x: p.x / length, y: p.y / length, z: p.z / length }; + return dot({ x: c.x - p.x, y: c.y - p.y, z: c.z - p.z }, normal) > 0; +} diff --git a/src/data/locate.test.mjs b/src/data/locate.test.mjs new file mode 100644 index 0000000000..f0fde4ed2c --- /dev/null +++ b/src/data/locate.test.mjs @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { locateOnTrack, onScreen, readingAt } from './locate.js'; +import { fromDegreesInto } from '../geo/ellipsoid.js'; + +const point = (observedAtMs, latitude, longitude, extra = {}) => ({ + observedAtMs, + latitude, + longitude, + ...extra, +}); + +test('the reading at a time is the newest point at or before it', () => { + const track = [ + point(3_000, 3, 30), + point(1_000, 1, 10, { baroAltitudeM: 900 }), + point(2_000, 2, 20), + point(Number.NaN, 9, 90), + point(4_000, Number.NaN, 40), + ]; + assert.deepEqual(readingAt(track, 2_500), { + lat: 2, + lon: 20, + altitudeM: null, + observedAtMs: 2_000, + }); + assert.equal(readingAt(track, 1_000).altitudeM, 900, 'at its own time'); + assert.equal(readingAt(track).observedAtMs, 3_000, 'no time: the newest'); + assert.equal(readingAt(track, 500), null, 'before its first point'); + assert.equal(readingAt([], 500), null); +}); + +test('a track lookup asks for the time and reads the point at it', async () => { + const asked = []; + const source = { + async getTrack(reference, options) { + asked.push([reference, options.atMs]); + return { records: [point(1_000, 1, 10), point(5_000, 5, 50)] }; + }, + }; + assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 2_000 }), { + status: 'found', + lat: 1, + lon: 10, + altitudeM: null, + observedAtMs: 1_000, + atMs: 2_000, + }); + assert.deepEqual(asked, [['vessel:a', 2_000]]); + assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 500 }), { + status: 'none', + }); + const live = await locateOnTrack(source, 'vessel:a'); + assert.equal(live.observedAtMs, 5_000, 'live: its newest point'); + assert.equal(asked.at(-1)[1], undefined, 'live asks for no time'); +}); + +test('a source without tracks, or one that fails, finds nothing', async () => { + assert.deepEqual(await locateOnTrack({}, 'a'), { status: 'none' }); + assert.deepEqual(await locateOnTrack(null, 'a'), { status: 'none' }); + const failing = { + getTrack: async () => { + throw new Error('down'); + }, + }; + assert.deepEqual(await locateOnTrack(failing, 'a'), { status: 'none' }); + assert.deepEqual( + await locateOnTrack({ getTrack: async () => ({ records: [] }) }, ''), + { status: 'none' }, + 'no reference', + ); +}); + +/** A camera 1000 km above a point, looking straight down. */ +function poseAbove(lat, lon) { + const at = fromDegreesInto(lon, lat, 0, { x: 0, y: 0, z: 0 }); + const length = Math.hypot(at.x, at.y, at.z); + const up = { x: at.x / length, y: at.y / length, z: at.z / length }; + const position = { + x: at.x + up.x * 1e6, + y: at.y + up.y * 1e6, + z: at.z + up.z * 1e6, + }; + const direction = { x: -up.x, y: -up.y, z: -up.z }; + // North-ish screen up, east right: any pair at right angles will do. + const east = { + x: -Math.sin((lon * Math.PI) / 180), + y: Math.cos((lon * Math.PI) / 180), + z: 0, + }; + const north = { + x: up.y * east.z - up.z * east.y, + y: up.z * east.x - up.x * east.z, + z: up.x * east.y - up.y * east.x, + }; + return { + position, + direction, + up: north, + right: east, + fovy: Math.PI / 3, + aspectRatio: 1.5, + }; +} + +test('a point is on screen in view, and not out of view or behind the globe', () => { + const pose = poseAbove(10, 20); + assert.equal(onScreen(pose, 10, 20), true, 'under the camera'); + assert.equal(onScreen(pose, 11, 21), true, 'near it'); + assert.equal(onScreen(pose, 30, 20), false, 'outside the view'); + assert.equal(onScreen(pose, -10, -160), false, 'the far side of the globe'); + assert.equal(onScreen(pose, Number.NaN, 20), false, 'no position'); + assert.equal(onScreen(null, 10, 20), false, 'no camera'); +}); diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index fd73175edf..a21ba50c5f 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -4739,5 +4739,9 @@ "Select a map item to see its details.": "اختر عنصرًا على الخريطة لرؤية تفاصيله.", "Bilawal on {site}": "بلال على {site}", "Bilawal's website": "موقع بلال الإلكتروني", - "BACK": "رجوع" + "BACK": "رجوع", + "Finding it…": "جارٍ البحث عنه…", + "No reading at this time": "لا توجد قراءة في هذا الوقت", + "Last reading · {age}": "آخر قراءة · {age}", + "Find it": "اعثر عليه" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 9f18360ee8..19e2c44d82 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -4315,5 +4315,9 @@ "Select a map item to see its details.": "Wähle ein Kartenelement aus, um seine Details zu sehen.", "Bilawal on {site}": "Bilawal auf {site}", "Bilawal's website": "Bilawals Website", - "BACK": "ZURÜCK" + "BACK": "ZURÜCK", + "Finding it…": "Wird gesucht…", + "No reading at this time": "Zu dieser Zeit kein Messwert", + "Last reading · {age}": "Letzter Stand · {age}", + "Find it": "Finden" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 8bb3db1509..f7af0945a9 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Selecciona un elemento del mapa para ver sus detalles.", "Bilawal on {site}": "Bilawal en {site}", "Bilawal's website": "Sitio web de Bilawal", - "BACK": "ATRÁS" + "BACK": "ATRÁS", + "Finding it…": "Buscando…", + "No reading at this time": "Sin lectura a esta hora", + "Last reading · {age}": "Última lectura · {age}", + "Find it": "Encontrar" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 26447fb193..83371618bd 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Sélectionnez un élément de la carte pour voir ses détails.", "Bilawal on {site}": "Bilawal sur {site}", "Bilawal's website": "Site web de Bilawal", - "BACK": "RETOUR" + "BACK": "RETOUR", + "Finding it…": "Recherche…", + "No reading at this time": "Aucune donnée à cette heure", + "Last reading · {age}": "Dernière donnée · {age}", + "Find it": "Retrouver" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 0221989c99..8fffebdc2d 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -4421,5 +4421,9 @@ "Bilawal on YouTube": "בילוואל ב־YouTube", "The studio behind GEV": "הסטודיו שמאחורי GEV", "Open source. Self-host, fork, add a layer.": "קוד פתוח. אירוח עצמאי, יצירת עותק והוספת שכבה.", - "ENTER GOD MODE": "כניסה למצב אלוהים" + "ENTER GOD MODE": "כניסה למצב אלוהים", + "Finding it…": "מחפש…", + "No reading at this time": "אין קריאה בזמן הזה", + "Last reading · {age}": "קריאה אחרונה · {age}", + "Find it": "מצא" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index a6d1bb283d..0894a26b95 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Seleziona un elemento della mappa per vederne i dettagli.", "Bilawal on {site}": "Bilawal su {site}", "Bilawal's website": "Sito web di Bilawal", - "BACK": "INDIETRO" + "BACK": "INDIETRO", + "Finding it…": "Ricerca in corso…", + "No reading at this time": "Nessun dato a quest'ora", + "Last reading · {age}": "Ultimo dato · {age}", + "Find it": "Trova" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 882a005589..2912466cc6 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "地図上の項目を選択すると詳細が表示されます。", "Bilawal on {site}": "{site}のBilawal", "Bilawal's website": "Bilawalのウェブサイト", - "BACK": "戻る" + "BACK": "戻る", + "Finding it…": "検索中…", + "No reading at this time": "この時刻のデータなし", + "Last reading · {age}": "最終データ・{age}", + "Find it": "探す" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index e2a6dc60ed..c67e58da14 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Selecione um item do mapa para ver seus detalhes.", "Bilawal on {site}": "Bilawal no {site}", "Bilawal's website": "Site de Bilawal", - "BACK": "VOLTAR" + "BACK": "VOLTAR", + "Finding it…": "A procurar…", + "No reading at this time": "Sem leitura nesta hora", + "Last reading · {age}": "Última leitura · {age}", + "Find it": "Encontrar" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b323df4d5d..a5fff95f77 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -4527,5 +4527,9 @@ "Select a map item to see its details.": "Выберите объект на карте, чтобы увидеть подробности.", "Bilawal on {site}": "Билал на {site}", "Bilawal's website": "Сайт Билала", - "BACK": "НАЗАД" + "BACK": "НАЗАД", + "Finding it…": "Поиск…", + "No reading at this time": "Нет данных на это время", + "Last reading · {age}": "Последние данные · {age}", + "Find it": "Найти" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index b457512d26..317f70d61d 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -4315,5 +4315,9 @@ "Bilawal on YouTube": "Bilawal på YouTube", "The studio behind GEV": "Studion bakom GEV", "Open source. Self-host, fork, add a layer.": "Öppen källkod. Kör själv, skapa en egen variant, lägg till ett lager.", - "ENTER GOD MODE": "STARTA GUDLÄGE" + "ENTER GOD MODE": "STARTA GUDLÄGE", + "Finding it…": "Söker…", + "No reading at this time": "Ingen avläsning vid den här tiden", + "Last reading · {age}": "Senaste avläsning · {age}", + "Find it": "Hitta" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index edcce4e88d..e57e61af76 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -4527,5 +4527,9 @@ "Select a map item to see its details.": "Виберіть об’єкт на карті, щоб побачити подробиці.", "Bilawal on {site}": "Білал на {site}", "Bilawal's website": "Сайт Білала", - "BACK": "НАЗАД" + "BACK": "НАЗАД", + "Finding it…": "Пошук…", + "No reading at this time": "Немає даних на цей час", + "Last reading · {age}": "Останні дані · {age}", + "Find it": "Знайти" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 05ddb36bc4..f72c5e0b08 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "选择地图上的项目以查看详情。", "Bilawal on {site}": "Bilawal 的 {site} 主页", "Bilawal's website": "Bilawal 的网站", - "BACK": "返回" + "BACK": "返回", + "Finding it…": "正在查找…", + "No reading at this time": "此时无数据", + "Last reading · {age}": "最后数据 · {age}", + "Find it": "查找" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index a84085e7e4..0e481762ed 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "選擇地圖上的項目以查看詳情。", "Bilawal on {site}": "Bilawal 的 {site} 主頁", "Bilawal's website": "Bilawal 的網站", - "BACK": "返回" + "BACK": "返回", + "Finding it…": "正在查找…", + "No reading at this time": "此時無數據", + "Last reading · {age}": "最後數據 · {age}", + "Find it": "查找" } diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index a696165b9a..7ebb9feb12 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -21,6 +21,7 @@ import { followsClock, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { locateOnTrack } from '../../data/locate.js'; export function createQueries({ flightState, @@ -778,6 +779,46 @@ export function createQueries({ return result; }, + /** + * The track reference of a loaded aircraft, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} icao24 + * @returns {string|null} + */ + referenceOf(icao24) { + const id = String(icao24 ?? '') + .trim() + .toLowerCase(); + if (!id) return null; + return flightState.records.data.get(id)?.sourceReference ?? id; + }, + + /** + * Where an aircraft is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for an aircraft that + * has left the feed, so it can be found again. + * @param {string} icao24 + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(icao24, { reference, signal } = {}) { + const atMs = followsClock(flightState) ? flightState.now() : undefined; + return locateOnTrack( + flightState.feed._source, + reference ?? + flightState.records.data.get( + String(icao24 ?? '') + .trim() + .toLowerCase(), + )?.sourceReference ?? + String(icao24 ?? '') + .trim() + .toLowerCase(), + { atMs, signal }, + ); + }, + /** * Ask for an aircraft's scheduled route (origin and destination airports), * as tracking does; it lands on the record when the lookup answers. diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 52221f6d6e..8b14315781 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -19,6 +19,7 @@ import { followsClock, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { locateOnTrack } from '../../data/locate.js'; export function createQueries({ flightState, @@ -651,6 +652,46 @@ export function createQueries({ return result; }, + /** + * The track reference of a loaded aircraft, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} icao24 + * @returns {string|null} + */ + referenceOf(icao24) { + const id = String(icao24 ?? '') + .trim() + .toLowerCase(); + if (!id) return null; + return flightState.records.data.get(id)?.sourceReference ?? id; + }, + + /** + * Where an aircraft is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for an aircraft that + * has left the feed, so it can be found again. + * @param {string} icao24 + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(icao24, { reference, signal } = {}) { + const atMs = followsClock(flightState) ? flightState.now() : undefined; + return locateOnTrack( + flightState.feed._source, + reference ?? + flightState.records.data.get( + String(icao24 ?? '') + .trim() + .toLowerCase(), + )?.sourceReference ?? + String(icao24 ?? '') + .trim() + .toLowerCase(), + { atMs, signal }, + ); + }, + /** * Start camera-tracking an aircraft by ICAO hex identifier. * @param {string} icao24 - ICAO hex identifier of the aircraft. diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index d5fa214f0b..e9dbb296bd 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -27,6 +27,7 @@ import { followsClock, } from './policy.js'; import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; +import { locateOnTrack } from '../../data/locate.js'; const UUID_KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -628,6 +629,39 @@ export function createQueries({ return components.selection.selectAndFocusVessel(record); }, + /** + * The track reference of a loaded vessel, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} id + * @returns {string|null} + */ + referenceOf(id) { + if (id === null || id === undefined) return null; + return recordFor(String(id).trim())?.reference ?? null; + }, + + /** + * Where a vessel is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for a vessel that has + * left the feed, so it can be found again. + * @param {string} id + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(id, { reference, signal } = {}) { + const atMs = followsClock(vesselState) + ? vesselState.worldNow() + : undefined; + return locateOnTrack( + vesselState._source, + reference ?? + recordFor(String(id ?? '').trim())?.reference ?? + String(id ?? ''), + { atMs, signal }, + ); + }, + /** * Return a subset of vessels for the universal detection overlay. * Deterministic stride sampling distributes selections evenly across the diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js index d431d25225..2090ee4d77 100644 --- a/src/ui/entityContextBridge.js +++ b/src/ui/entityContextBridge.js @@ -1,4 +1,5 @@ import { resolvePickedContext } from '../data/pickedContext.js'; +import { onScreen } from '../data/locate.js'; import { clickCard } from '../data/pickRegistry.js'; import { followedOf, onFollowChanged } from '../data/followed.js'; import { fromDegreesInto } from '../geo/ellipsoid.js'; @@ -136,6 +137,21 @@ export function installEntityContext({ } } + // An item back in its feed after it left it is selected again in its layer, + // as the click that picked it: a vessel is highlighted with its trail, and + // an aircraft found again (`follow`) is followed. + function reselect(card, { follow: andFollow = false } = {}) { + const layer = getDataManager()?.layers?.get?.(card?.layerId)?.module; + const id = card?.identity?.id; + if (!layer || !id) return; + try { + if (card.layerId === 'ais-live-vessels') layer.selectById?.(id); + else if (andFollow && FOLLOWABLE.has(card.layerId)) follow(card); + } catch { + // A layer going away meanwhile has nothing to select. + } + } + // Aircraft can be flown from, and a satellite ridden in the orbital view: // track the craft, then enter Cockpit on it. Only layers the tracking // action can follow are offered (local ADS-B cannot be tracked). @@ -197,6 +213,14 @@ export function installEntityContext({ flyTo, follow, letGo, + reselect, + // Whether the camera shows the card's item; null when it cannot tell. + onScreen: (card) => { + const pose = camera()?.pose(); + if (!pose || !Number.isFinite(card?.lat) || !Number.isFinite(card?.lon)) + return null; + return onScreen(pose, card.lat, card.lon, card.altitudeM ?? 0); + }, isOpen, regionalBrief, // The renderer's card previews, when it has them. @@ -343,7 +367,12 @@ export function installEntityContext({ if (!record?.layerId || inCockpit()) return; store.select({ layerId: record.layerId, - id: record.id, + // A vessel goes by its own id, as a click on it names it, not by the + // context store's (src/data/pickedContext.js). + id: + record.layerId === 'ais-live-vessels' && record.properties?.vesselId + ? String(record.properties.vesselId) + : record.id, label: record.label || record.properties?.name, lat: record.latitude, lon: record.longitude, diff --git a/src/ui/entityContextBridge.test.mjs b/src/ui/entityContextBridge.test.mjs index 025b23df57..c83cdb6e14 100644 --- a/src/ui/entityContextBridge.test.mjs +++ b/src/ui/entityContextBridge.test.mjs @@ -83,3 +83,60 @@ test('Context names nothing under a card painted on top, and keeps its card', (t tap(null, null); assert.equal(clears, cleared, 'a card over open map is not open map'); }); + +// A vessel's layer announces its selection with the context store's id; the +// card names it by the vessel's own id, as a click on it does. +test('a vessel announced by its layer is named by its own id', (t) => { + // The page's events, which Node lacks. + const events = new EventTarget(); + for (const name of [ + 'addEventListener', + 'removeEventListener', + 'dispatchEvent', + ]) + globalThis[name] = events[name].bind(events); + t.after(() => { + for (const name of [ + 'addEventListener', + 'removeEventListener', + 'dispatchEvent', + ]) + delete globalThis[name]; + }); + const pinia = createPinia(); + const viewer = { scene: { pick: () => null, drillPick: () => [] } }; + const input = fakeInput(viewer); + const disconnect = installEntityContext({ + viewer, + getDataManager: () => ({ + isEnabled: () => true, + layers: new Map(), + getAll: () => [], + }), + pinia, + }); + t.after(() => { + disconnect(); + input.destroy(); + }); + const store = useEntityCardStore(pinia); + const named = []; + store.select = (identity) => named.push(identity.id); + globalThis.dispatchEvent( + new CustomEvent('gev:entity-selected', { + detail: { + layerId: 'ais-live-vessels', + id: 'ais-5fdca702', + properties: { vesselId: '5fdca702' }, + latitude: 1, + longitude: 2, + }, + }), + ); + globalThis.dispatchEvent( + new CustomEvent('gev:entity-selected', { + detail: { layerId: 'fires', id: 'fire:1', latitude: 1, longitude: 2 }, + }), + ); + assert.deepEqual(named, ['5fdca702', 'fire:1']); +}); diff --git a/src/ui/kit/entityCardControls.test.mjs b/src/ui/kit/entityCardControls.test.mjs index 5dd3f24587..39406f5709 100644 --- a/src/ui/kit/entityCardControls.test.mjs +++ b/src/ui/kit/entityCardControls.test.mjs @@ -31,9 +31,9 @@ const heroViews = [ test('the entity card hand-writes no button; each is a UiButton', () => { for (const markup of [card, camera, nearby, ...heroViews]) assert.deepEqual(markup.match(/ { for (const markup of [card, camera, nearby, ...heroViews]) assert.deepEqual(markup.match(/material-symbols-outlined/g) ?? [], []); const counts = [ - // The preview switch's three, the hero glyph, the header icon, the - // warning, the route's plane, the route note and the three actions. - [card, 11], + // The preview switch's three, the hero glyph, the header icon, Find + // it, the warning, the route's plane, the route note and the three + // actions. + [card, 12], // Bigger view, the popup's camera and More info. [camera, 3], // The two weather glyphs, five headings and three row glyphs. diff --git a/src/ui/stores/entityCard.js b/src/ui/stores/entityCard.js index a0186fea2c..9fd63cdb3e 100644 --- a/src/ui/stores/entityCard.js +++ b/src/ui/stores/entityCard.js @@ -93,6 +93,26 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { const lost = ref(false); /** Bumped on each refresh, so ages shown on the card tick. */ const tick = ref(0); + /** + * True while the item is not to be seen: out of its feed, off screen or + * behind the globe. The card then offers to find it. + */ + const away = ref(false); + /** + * Finding the item again (see locate): `'idle'`, `'finding'` while its + * layer looks it up, or `'none'` when it has no reading at the time. + */ + const finding = ref('idle'); + /** + * Where an item out of its feed was found (see locate): + * `{lat, lon, altitudeM, observedAtMs, atMs}`, or null. + */ + const located = shallowRef(null); + /** The track reference of the card's item, kept for when it leaves its feed. */ + let reference = null; + let locating = null; + /** An aircraft found again is followed once it is back in its feed. */ + let followWhenBack = false; /** * What the camera shows, for the panel to describe when nothing is picked: * `{center: {lat, lon}, rect: {west, south, east, north}, heightM}`. @@ -229,12 +249,105 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { // Keep showing the last reading when the item drops out of its feed. if (!next || next.key !== current.key || next.basis !== 'record') { lost.value = current.basis === 'record'; + away.value = lost.value || !shown(current); tick.value++; return; } + const wasLost = lost.value; card.value = markRaw(next); lost.value = false; + // The camera follows it where it is drawn, which can be ahead of its last + // reading; one being followed is always in view. + away.value = !isFollowing() && !shown(next); tick.value++; + if (wasLost) back(next); + } + + /** Whether the camera shows the item; true when the shell cannot tell. */ + function shown(current) { + const test = shell.value?.onScreen; + return typeof test === 'function' ? test(current) !== false : true; + } + + /** + * The item is back in its feed: its layer selects it again, as the click + * that picked it did, and an aircraft just found is followed. + */ + function back(current) { + const follows = followWhenBack; + // A lookup still running is no longer needed: the feed has it. + stopLocating(); + reference = + layerOf(current.layerId)?.referenceOf?.(current.identity?.id) ?? + reference; + shell.value?.reselect?.(current, { follow: follows }); + } + + const layerOf = (layerId) => + shell.value?.dataManager?.()?.layers?.get?.(layerId)?.module ?? null; + + /** + * Take the camera back to the item. One the camera can see or one still in + * its feed is flown to (an aircraft followed); one out of its feed is + * looked up at the layer's time (the world clock's while it follows the + * clock) on its own track, shown there and flown to, and its layer picks + * it up again once its feed has it. + * @returns {Promise} + */ + async function locate() { + const current = card.value; + if (!current) return; + if (!lost.value) { + if (canFollow()) follow(); + else flyTo(); + return; + } + const layer = layerOf(current.layerId); + if (typeof layer?.locate !== 'function') { + flyTo(); + return; + } + locating?.abort(); + const controller = new AbortController(); + locating = controller; + finding.value = 'finding'; + let result; + try { + result = await layer.locate(current.identity?.id, { + reference, + signal: controller.signal, + }); + } catch { + result = { status: 'none' }; + } + if (locating !== controller) return; + locating = null; + const now = card.value; + if (!now || now.key !== current.key) return; + if (result?.status !== 'found') { + finding.value = 'none'; + return; + } + finding.value = 'idle'; + located.value = markRaw({ ...result }); + card.value = markRaw({ + ...now, + lat: result.lat, + lon: result.lon, + altitudeM: Number.isFinite(result.altitudeM) + ? result.altitudeM + : now.altitudeM, + }); + followWhenBack = canFollow(); + shell.value?.flyTo?.(card.value); + } + + function stopLocating() { + locating?.abort(); + locating = null; + finding.value = 'idle'; + located.value = null; + followWhenBack = false; } /** @@ -261,6 +374,11 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { */ function select(identity, { fly = false, follow: autoFollow = true } = {}) { if (!read(identity)) return false; + stopLocating(); + away.value = false; + reference = + layerOf(identity.layerId)?.referenceOf?.(card.value?.identity?.id) ?? + null; clearInterval(timer); timer = setInterval(refresh, REFRESH_MS); shell.value?.openPanel?.(); @@ -292,6 +410,9 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { timer = null; card.value = null; lost.value = false; + away.value = false; + reference = null; + stopLocating(); } const flyTo = () => card.value && shell.value?.flyTo?.(card.value); @@ -324,6 +445,10 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { card, lost, tick, + away, + finding, + located, + locate, connect, select, clear, diff --git a/src/ui/stores/entityCardLocate.test.mjs b/src/ui/stores/entityCardLocate.test.mjs new file mode 100644 index 0000000000..3200bb316e --- /dev/null +++ b/src/ui/stores/entityCardLocate.test.mjs @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPinia } from 'pinia'; +import { useEntityCardStore } from './entityCard.js'; + +/** + * A vessels layer whose one vessel can leave its feed, and a shell that + * records what the card asks of it. + */ +function setup({ found = true } = {}) { + const vessel = { + id: 'v1', + name: 'ARCADIA', + lat: 1, + lon: 10, + reference: 'vessel:v1', + }; + let inFeed = true; + const asked = []; + const module = { + getAnalystRecords: () => (inFeed ? [{ ...vessel }] : []), + referenceOf: (id) => (id === 'v1' && inFeed ? vessel.reference : null), + async locate(id, { reference }) { + asked.push({ id, reference }); + return found + ? { + status: 'found', + lat: 5, + lon: 50, + altitudeM: null, + observedAtMs: 1_000, + atMs: 61_000, + } + : { status: 'none' }; + }, + }; + const dataManager = { + isEnabled: () => true, + layers: new Map([['ais-live-vessels', { module }]]), + getAll: () => [], + }; + const shell = { + flown: [], + followed: [], + reselected: [], + visible: true, + dataManager: () => dataManager, + openPanel() {}, + flyTo(card) { + shell.flown.push([card.lat, card.lon]); + }, + follow(card) { + shell.followed.push(card.key); + }, + reselect(card, options) { + shell.reselected.push([card.identity.id, options.follow]); + }, + onScreen: () => shell.visible, + canFollow: () => false, + }; + const store = useEntityCardStore(createPinia()); + store.connect(shell); + return { + store, + shell, + asked, + leave: () => (inFeed = false), + come: () => (inFeed = true), + }; +} + +test('a vessel out of its feed is looked up, shown where it was and flown to', async (t) => { + const { store, shell, asked, leave, come } = setup(); + t.after(() => store.clear()); + assert.equal(store.select({ layerId: 'ais-live-vessels', id: 'v1' }), true); + assert.equal(store.away, false, 'on screen and in its feed'); + + leave(); + store.refresh(); + assert.equal(store.lost, true); + assert.equal(store.away, true, 'out of its feed: the card offers to find it'); + + await store.locate(); + assert.deepEqual( + asked, + [{ id: 'v1', reference: 'vessel:v1' }], + 'by the reference it had', + ); + assert.equal(store.card.lat, 5); + assert.equal(store.card.lon, 50); + assert.deepEqual(shell.flown, [[5, 50]]); + assert.equal(store.located.observedAtMs, 1_000); + assert.equal(store.finding, 'idle'); + + come(); + store.refresh(); + assert.equal(store.lost, false, 'back in its feed'); + assert.equal(store.located, null); + assert.deepEqual( + shell.reselected, + [['v1', false]], + 'its layer selects it again', + ); +}); + +test('a vessel with no reading at the time says so and stays put', async (t) => { + const { store, shell, leave } = setup({ found: false }); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + leave(); + store.refresh(); + await store.locate(); + assert.equal(store.finding, 'none'); + assert.deepEqual(shell.flown, [], 'the camera stays'); + assert.equal(store.card.lat, 1, 'the card keeps its last reading'); +}); + +test('an item in its feed but off screen is flown to without a lookup', async (t) => { + const { store, shell, asked } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + shell.visible = false; + store.refresh(); + assert.equal(store.away, true, 'off screen'); + await store.locate(); + assert.deepEqual(asked, []); + assert.deepEqual(shell.flown, [[1, 10]]); +}); + +test('an item the camera follows is never away, wherever its last reading is', (t) => { + const { store, shell } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + shell.visible = false; + store.following = store.card.key; + store.refresh(); + assert.equal(store.away, false); +}); + +test('a lookup still running when the item comes back is dropped', async (t) => { + const { store, shell, leave, come } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + leave(); + store.refresh(); + const pending = store.locate(); + come(); + store.refresh(); + await pending; + assert.equal(store.lost, false); + assert.equal(store.located, null, 'no old reading on a live card'); + assert.equal(store.card.lat, 1, 'the card keeps its live position'); + assert.deepEqual(shell.flown, [], 'the camera stays'); +}); diff --git a/src/ui/styles/entity-card.css b/src/ui/styles/entity-card.css index 223acca6e2..4d4a9d01c9 100644 --- a/src/ui/styles/entity-card.css +++ b/src/ui/styles/entity-card.css @@ -104,6 +104,33 @@ font-size: 1rem; } +/* Find it: shown while the selected item is off screen or out of its feed. */ +.entity-card__find { + display: grid; + flex: none; + place-items: center; + width: 1.9rem; + height: 1.9rem; + color: #36dcff; + background: rgba(29, 69, 81, 0.35); + border: 1px solid rgba(48, 194, 224, 0.55); + border-radius: 7px; +} + +.entity-card__find:hover, +.entity-card__find:focus-visible { + color: #fff; + background: rgba(48, 194, 224, 0.3); +} + +.entity-card__find:disabled { + opacity: 0.55; +} + +.entity-card__find .material-symbols-outlined { + font-size: 1.1rem; +} + .entity-card__title { margin: 0.55rem 0 0.1rem; overflow-wrap: anywhere; @@ -2180,7 +2207,11 @@ border-radius: 3px; } -.entity-hero:is([data-hero='flight'], [data-hero='satellite'], [data-hero='photo']) { +.entity-hero:is( + [data-hero='flight'], + [data-hero='satellite'], + [data-hero='photo'] +) { height: 168px; background: radial-gradient( ellipse 55% 60% at 50% 55%, diff --git a/src/ui/views/panels/EntityCard.vue b/src/ui/views/panels/EntityCard.vue index fd787d97fc..f76d28c926 100644 --- a/src/ui/views/panels/EntityCard.vue +++ b/src/ui/views/panels/EntityCard.vue @@ -26,7 +26,7 @@ const props = defineProps({ withContacts: Boolean, }); const store = useEntityCardStore(); -const { card, lost, tick } = storeToRefs(store); +const { card, lost, tick, away, finding, located } = storeToRefs(store); // Cameras carry only an id; the CCTV panel's store knows the picked one's name. const { frame: cctvFrame } = storeToRefs(useCctvStore()); const shownTitle = computed(() => { @@ -56,6 +56,15 @@ const status = computed(() => { void tick.value; const current = card.value; if (!current) return null; + if (finding.value === 'finding') return { tone: 'aged', text: t('Finding it…') }; + if (finding.value === 'none') return { tone: 'lost', text: t('No reading at this time') }; + if (lost.value && located.value) + return { + tone: 'aged', + text: t('Last reading · {age}', { + age: ago(Math.max(0, located.value.atMs - located.value.observedAtMs)), + }), + }; if (lost.value) return { tone: 'lost', text: t('Out of feed · last reading') }; if (current.observedAgeMs !== null) return { @@ -399,6 +408,7 @@ watch(

{{ shownTitle }}

{{ subtitle }} +