mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main through #1637 into the renderer seam
Ports the cockpit bridge view, the orbital view riding a satellite with ground-site focus, satellite classes and draw-mark row actions onto the renderer contract. The orbital view's imagery look-ahead pre-load is dropped (no contract member); tiles load as they come on screen.
This commit is contained in:
commit
e48ed3eb9e
169 files changed
+22415
-681
No files matched your search
Vendored
+38
@@ -159,6 +159,44 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* A loaded mapped installation by id, as `getNearby` returns it (with its
|
||||
* drawn `position`), or null while the layer is off or the id is not
|
||||
* loaded. Read-only: nothing is selected.
|
||||
* @param {string} id Source-backed installation id.
|
||||
* @returns {object|null}
|
||||
*/
|
||||
getById(id) {
|
||||
if (!layerState.enabled || id === null || id === undefined) return null;
|
||||
const record = layerState.recordById.get(String(id));
|
||||
if (!record || record.kind !== 'installation') return null;
|
||||
return {
|
||||
...record,
|
||||
position: fromDegrees(
|
||||
record.longitude,
|
||||
record.latitude,
|
||||
parts.rendering.installationSurfaceHeightM(record),
|
||||
),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* The mapped installation a query port's pick landed on: a site's dot,
|
||||
* outline or fill, or a named marker, each naming its installation in
|
||||
* its `meta`, as this layer's own click selection reads them. Null for
|
||||
* anything else.
|
||||
* @param {object|null|undefined} hit A query port `Hit`.
|
||||
* @returns {object|null} As {@link getById}.
|
||||
*/
|
||||
findByPick(hit) {
|
||||
const id =
|
||||
hit?.set === parts.namedMarkers?.setId ||
|
||||
parts.rendering.ownsSet(hit?.set)
|
||||
? hit.meta?.installationId
|
||||
: null;
|
||||
return id ? methods.getById(id) : null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Select and frame a mapped installation from another contextual UI.
|
||||
* @param {string} id Source-backed installation id.
|
||||
|
||||
@@ -124,6 +124,13 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
satrec,
|
||||
group: 'dense',
|
||||
launchYear: tleLineLaunchYear(entry.line1),
|
||||
line1: entry.line1,
|
||||
line2: entry.line2,
|
||||
// The dense feed is CelesTrak's Starlink group.
|
||||
satelliteClass: 'starlink',
|
||||
ucs: null,
|
||||
satcat: null,
|
||||
sensor: null,
|
||||
});
|
||||
parts.rendering._addPoint(
|
||||
noradId,
|
||||
@@ -195,6 +202,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
if (token !== layerState._denseLoadToken) return;
|
||||
layerState._params.catalog = 'core';
|
||||
_removeDenseCatalog();
|
||||
// Back on core, Starlink is off: hide the core catalog's own Starlink
|
||||
// points again, and say so in the class choice.
|
||||
if (layerState._params.classes)
|
||||
layerState._params.classes = {
|
||||
...layerState._params.classes,
|
||||
starlink: false,
|
||||
};
|
||||
parts.controls._applyClassVisibility?.();
|
||||
layerState._denseStatus = 'failed';
|
||||
layerState._denseError = reason;
|
||||
parts.controls._notifyRowControls();
|
||||
|
||||
@@ -0,0 +1,765 @@
|
||||
/**
|
||||
* @file Satellite classes: which of six KSP-style classes an object in orbit
|
||||
* belongs to, who owns it and who operates it.
|
||||
*
|
||||
* Classes, in legend order:
|
||||
* - stations: crewed stations and the craft that visit them (ISS, Tiangong,
|
||||
* Soyuz, Shenzhou, Dragon, Progress, Cygnus…), by name. The CubeSats
|
||||
* CelesTrak's stations group also carries after their deployment from the
|
||||
* ISS are classed like any other satellite. Retired stations and the
|
||||
* shuttles have re-entered, so they have no orbit to show.
|
||||
* - imaging: Earth observation of every kind (optical, radar, multispectral,
|
||||
* hyperspectral, weather, Earth science, surveillance).
|
||||
* - telecom: communications and navigation (GEO comsats, Iridium, OneWeb,
|
||||
* GPS, GLONASS, Galileo, BeiDou…), Starlink excepted.
|
||||
* - starlink: the Starlink constellation.
|
||||
* - probes: other working payloads (space science, technology development and
|
||||
* demonstration, education, unknown purpose).
|
||||
* - debris: rocket bodies, fragments, unknown objects and payloads that no
|
||||
* longer work. Shown and tracked on request, never ridden in the Cockpit.
|
||||
*
|
||||
* The evidence, strongest first: CelesTrak SATCAT's object type and
|
||||
* operational status (current, so it overrules UCS on a satellite that has
|
||||
* died since), the UCS Satellite Database's purpose (May 2023), name patterns
|
||||
* for satellites launched after it, and the CelesTrak group the TLE came in.
|
||||
* Pure: no Cesium, no fetches, so the tables are unit-tested directly.
|
||||
*
|
||||
* @module satelliteClasses
|
||||
*/
|
||||
|
||||
import { msg } from '../../i18n/index.js';
|
||||
|
||||
/** Class ids in legend order. */
|
||||
export const SATELLITE_CLASS_IDS = Object.freeze([
|
||||
'stations',
|
||||
'imaging',
|
||||
'telecom',
|
||||
'starlink',
|
||||
'probes',
|
||||
'debris',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Which classes show when nobody has chosen: everything the layer showed
|
||||
* before classes existed. Starlink stays off, as the DENSE switch was.
|
||||
*/
|
||||
export const DEFAULT_SATELLITE_CLASSES = Object.freeze({
|
||||
stations: true,
|
||||
imaging: true,
|
||||
telecom: true,
|
||||
starlink: false,
|
||||
probes: true,
|
||||
debris: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Point colour and the legend and chip text for each class. Colours reuse the
|
||||
* layer's established palette (src/data/satelliteClass.js); debris recedes.
|
||||
*/
|
||||
export const SATELLITE_CLASS_DISPLAY = Object.freeze({
|
||||
stations: Object.freeze({
|
||||
color: '#fff6e5',
|
||||
label: msg('STATIONS'),
|
||||
blurb: msg('Crewed stations and the craft that visit them'),
|
||||
}),
|
||||
imaging: Object.freeze({
|
||||
color: '#4fd8ff',
|
||||
label: msg('IMAGING'),
|
||||
blurb: msg('Earth observation: optical, radar, weather and science'),
|
||||
}),
|
||||
telecom: Object.freeze({
|
||||
color: '#c89bff',
|
||||
label: msg('TELECOM'),
|
||||
blurb: msg('Communications and navigation satellites, Starlink excepted'),
|
||||
}),
|
||||
starlink: Object.freeze({
|
||||
color: '#54697f',
|
||||
label: msg('STARLINK'),
|
||||
blurb: msg('The Starlink constellation (thousands of extra points)'),
|
||||
}),
|
||||
probes: Object.freeze({
|
||||
color: '#9fb3c4',
|
||||
label: msg('PROBES'),
|
||||
blurb: msg('Space science, technology demonstration and other payloads'),
|
||||
}),
|
||||
debris: Object.freeze({
|
||||
color: '#7d7468',
|
||||
label: msg('DEBRIS'),
|
||||
blurb: msg('Rocket bodies, fragments and dead satellites'),
|
||||
}),
|
||||
});
|
||||
|
||||
/** The ISS, a station whatever else says. */
|
||||
const ISS_NORAD = 25544;
|
||||
|
||||
/** SATCAT object types that are never a working payload. */
|
||||
const DEBRIS_OBJECT_TYPES = new Set(['R/B', 'DEB']);
|
||||
/**
|
||||
* SATCAT files a new launch's objects as UNK until it identifies them, so an
|
||||
* unknown object launched within this many calendar years (2: this year or
|
||||
* last) is not presumed debris. Years, not dates: the TLE designator, the
|
||||
* fallback when SATCAT has no launch date, carries only the year.
|
||||
*/
|
||||
export const UNIDENTIFIED_GRACE_YEARS = 2;
|
||||
/** SATCAT operational status: nonoperational, decayed. */
|
||||
const DEAD_STATUSES = new Set(['-', 'D']);
|
||||
/** SATCAT operational status left blank or unknown. */
|
||||
const UNKNOWN_STATUSES = new Set(['', '?']);
|
||||
/**
|
||||
* A payload whose SATCAT record gives no status, with no UCS record and no
|
||||
* recognisable name, that launched this many years ago is presumed dead (old
|
||||
* weather and science satellites the "visual" group keeps for their
|
||||
* brightness). Without a SATCAT record (a failed read) nothing is presumed.
|
||||
*/
|
||||
export const PRESUMED_DEAD_AFTER_YEARS = 20;
|
||||
|
||||
const DEBRIS_NAME = /\bR\/B\b|\bDEB\b|\bAKM\b|ROCKET BODY/i;
|
||||
const STATION_NAME =
|
||||
/^(ISS\b|TIANGONG|TIANHE|WENTIAN|MENGTIAN|CSS\b|SHENZHOU|TIANZHOU|SOYUZ|PROGRESS|CREW DRAGON|DRAGON|CYGNUS|STARLINER|HTV\b|AXIOM)/i;
|
||||
const STARLINK_NAME = /^STARLINK/i;
|
||||
const IMAGING_NAME =
|
||||
/^(SENTINEL|LANDSAT|WORLDVIEW|GEOEYE|PLEIADES|SPOT[ -]\d|ICEYE|CAPELLA|UMBRA|FLOCK|SKYSAT|PELICAN|SUPERDOVE|DOVE\b|NOAA[ -]?\d|GOES|METEOSAT|METOP|HIMAWARI|FENGYUN|FY-?\d|GAOFEN|JILIN|SUPERVIEW|KOMPSAT|RADARSAT|RCM-|TERRA\b|AQUA\b|SUOMI NPP|JPSS|CARTOSAT|RESOURCESAT|RISAT|EOS-\d|ALOS|COSMO-SKYMED|CSG-|TERRASAR|TANDEM-X|PAZ\b|SAOCOM|KANOPUS|RESURS|METEOR-M|ELEKTRO-L|ARKTIKA-M|YAOGAN|NUSAT|NEWSAT|BLACKSKY|GLOBAL-\d|GHGSAT|LEMUR|HAIYANG|HY-\d|ZIYUAN|ZY-\d|TIANHUI|SWOT|ICESAT|GRACE|CRYOSAT|SMAP|SMOS|PROBA-V|DEIMOS|THEOS|GOKTURK|EROS|OFEQ|OPTSAT|PRISMA|ENMAP|NISAR|BIOMASS|EARTHCARE|FORMOSAT|CBERS|AMAZONIA|SICH|DMSP|ELECTRO)/i;
|
||||
const TELECOM_NAME =
|
||||
/^(ONEWEB|IRIDIUM|GLOBALSTAR|ORBCOMM|INTELSAT|IS-\d|SES[ -]?\d|ASTRA|EUTELSAT|INMARSAT|VIASAT|ECHOSTAR|DIRECTV|SIRIUS|XM-|TDRS|NAVSTAR|GPS\b|GLONASS|GSAT0|GALILEO|BEIDOU|QZS|IRNSS|NVS-|KUIPER|LYNK|BLUEBIRD|O3B|TELESAT|ANIK|NIMIQ|AMAZONAS|HISPASAT|ARABSAT|NILESAT|TURKSAT|YAMAL|EXPRESS-|CHINASAT|ZHONGXING|APSTAR|ASIASAT|THAICOM|MEASAT|JCSAT|SUPERBIRD|OPTUS|SKYNET|WGS|MUOS|AEHF|MILSTAR|QIANFAN|GUOWANG|SPACEMOBILE|GONETS|MERIDIAN|LUCH|RADUGA|SKYTERRA|TERRESTAR|SPACEWAY|HYLAS|ARSAT|AMOS|BADR|KA-SAT|YAHSAT|THURAYA)/i;
|
||||
|
||||
const IMAGING_PURPOSE =
|
||||
/earth observation|earth\/space observation|earth science|meteorolog|surveillance/i;
|
||||
const TELECOM_PURPOSE = /communications|navigation|positioning/i;
|
||||
|
||||
/**
|
||||
* CelesTrak groups whose members are, by default, of one class. Not
|
||||
* stations: it also carries CubeSats deployed from the ISS.
|
||||
*/
|
||||
const GROUP_CLASS = Object.freeze({
|
||||
dense: 'starlink',
|
||||
starlink: 'starlink',
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
'gps-ops': 'telecom',
|
||||
glonass: 'telecom',
|
||||
'glo-ops': 'telecom',
|
||||
galileo: 'telecom',
|
||||
geo: 'telecom',
|
||||
science: 'probes',
|
||||
});
|
||||
|
||||
/** CelesTrak groups named for an orbit, not a mission: the last resort. */
|
||||
const ORBIT_GROUPS = new Set(['geo']);
|
||||
|
||||
/** The year of a SATCAT launch date (`2024-03-15`), or null. */
|
||||
function launchYearOf(launchDate) {
|
||||
const match = /^(\d{4})-/.exec(String(launchDate || ''));
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The class a satellite belongs to.
|
||||
* @param {{noradId?: number, name?: string, group?: string|null,
|
||||
* groups?: string[]|null,
|
||||
* ucs?: {purpose?: string|null}|null,
|
||||
* satcat?: {objectType?: string, opsStatus?: string,
|
||||
* launchDate?: string|null}|null,
|
||||
* launchYear?: number|null, nowYear?: number}} subject `groups` is every
|
||||
* CelesTrak group the TLE came in (`group` is the one it is shown under):
|
||||
* the first of them that names a class gives the last-resort class, so a
|
||||
* satellite in both `visual` and `resource` is still imaging. `launchYear` is
|
||||
* the TLE designator's; SATCAT's launch date wins where it has one (an
|
||||
* object deployed from the ISS carries the station's 1998 designator).
|
||||
* @returns {'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris'}
|
||||
*/
|
||||
export function classifySatellite({
|
||||
noradId,
|
||||
name = '',
|
||||
group = null,
|
||||
ucs = null,
|
||||
satcat = null,
|
||||
groups = null,
|
||||
launchYear = null,
|
||||
nowYear = new Date().getUTCFullYear(),
|
||||
} = {}) {
|
||||
if (noradId === ISS_NORAD) return 'stations';
|
||||
const label = String(name || '').trim();
|
||||
const objectType = satcat?.objectType || null;
|
||||
const status = satcat?.opsStatus ?? null;
|
||||
const launched = launchYearOf(satcat?.launchDate) ?? launchYear;
|
||||
const recent =
|
||||
Number.isFinite(launched) && nowYear - launched < UNIDENTIFIED_GRACE_YEARS;
|
||||
if (objectType && DEBRIS_OBJECT_TYPES.has(objectType)) return 'debris';
|
||||
if (objectType === 'UNK' && !recent) return 'debris';
|
||||
if (!objectType && DEBRIS_NAME.test(label)) return 'debris';
|
||||
if (status !== null && DEAD_STATUSES.has(status)) return 'debris';
|
||||
|
||||
// CelesTrak's stations group also carries the CubeSats deployed from the
|
||||
// ISS (they share its 1998-067 designator): only a station or a visiting
|
||||
// craft, by name, is a station.
|
||||
if (STATION_NAME.test(label)) return 'stations';
|
||||
if (group === 'dense' || STARLINK_NAME.test(label)) return 'starlink';
|
||||
|
||||
// UCS writes "Unknown" for a purpose it does not know: no evidence.
|
||||
const purpose = /^unknown$/i.test(ucs?.purpose || '')
|
||||
? ''
|
||||
: ucs?.purpose || '';
|
||||
if (IMAGING_PURPOSE.test(purpose)) return 'imaging';
|
||||
if (TELECOM_PURPOSE.test(purpose)) return 'telecom';
|
||||
if (purpose) return 'probes';
|
||||
|
||||
if (IMAGING_NAME.test(label)) return 'imaging';
|
||||
if (TELECOM_NAME.test(label)) return 'telecom';
|
||||
|
||||
// UCS lists working satellites only: a payload it never knew, whose SATCAT
|
||||
// record gives no status and whose launch is decades old, is presumed
|
||||
// dead. Without a SATCAT record (its read failed or has not landed) there
|
||||
// is no evidence either way, so nothing is presumed.
|
||||
if (
|
||||
satcat &&
|
||||
UNKNOWN_STATUSES.has(status ?? '') &&
|
||||
Number.isFinite(launched) &&
|
||||
nowYear - launched >= PRESUMED_DEAD_AFTER_YEARS
|
||||
)
|
||||
return 'debris';
|
||||
|
||||
// A mission group (weather, resource, science…) says more than an orbit
|
||||
// group: a weather satellite in geostationary orbit is in both.
|
||||
const memberships = groups?.length ? groups : [group];
|
||||
for (const membership of [
|
||||
...memberships.filter((m) => !ORBIT_GROUPS.has(m)),
|
||||
...memberships.filter((m) => ORBIT_GROUPS.has(m)),
|
||||
])
|
||||
if (GROUP_CLASS[membership]) return GROUP_CLASS[membership];
|
||||
return 'probes';
|
||||
}
|
||||
|
||||
/** Whether a class may be ridden in the Cockpit's orbital view. */
|
||||
export function satelliteClassEnterable(satelliteClass) {
|
||||
return (
|
||||
SATELLITE_CLASS_IDS.includes(satelliteClass) && satelliteClass !== 'debris'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a partial class-visibility request into the current choice.
|
||||
* Unknown keys and non-boolean values are ignored.
|
||||
* @param {Record<string, unknown>|null|undefined} request
|
||||
* @param {Record<string, boolean>} [current]
|
||||
* @returns {Record<string, boolean>}
|
||||
*/
|
||||
export function mergeClassVisibility(
|
||||
request,
|
||||
current = DEFAULT_SATELLITE_CLASSES,
|
||||
) {
|
||||
const next = {};
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const value = request?.[id];
|
||||
next[id] = typeof value === 'boolean' ? value : current[id] === true;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
// ISO 3166-1 alpha-2 code → short English name, for every owner below.
|
||||
const COUNTRY_NAMES = Object.freeze({
|
||||
AE: 'United Arab Emirates',
|
||||
AM: 'Armenia',
|
||||
AO: 'Angola',
|
||||
AR: 'Argentina',
|
||||
AT: 'Austria',
|
||||
AU: 'Australia',
|
||||
AZ: 'Azerbaijan',
|
||||
BD: 'Bangladesh',
|
||||
BE: 'Belgium',
|
||||
BG: 'Bulgaria',
|
||||
BH: 'Bahrain',
|
||||
BM: 'Bermuda',
|
||||
BO: 'Bolivia',
|
||||
BR: 'Brazil',
|
||||
BT: 'Bhutan',
|
||||
BW: 'Botswana',
|
||||
BY: 'Belarus',
|
||||
CA: 'Canada',
|
||||
CH: 'Switzerland',
|
||||
CL: 'Chile',
|
||||
CN: 'China',
|
||||
CO: 'Colombia',
|
||||
CR: 'Costa Rica',
|
||||
CZ: 'Czechia',
|
||||
DE: 'Germany',
|
||||
DJ: 'Djibouti',
|
||||
DK: 'Denmark',
|
||||
DZ: 'Algeria',
|
||||
EC: 'Ecuador',
|
||||
EE: 'Estonia',
|
||||
EG: 'Egypt',
|
||||
ES: 'Spain',
|
||||
ET: 'Ethiopia',
|
||||
FI: 'Finland',
|
||||
FR: 'France',
|
||||
GB: 'United Kingdom',
|
||||
GH: 'Ghana',
|
||||
GR: 'Greece',
|
||||
GT: 'Guatemala',
|
||||
HR: 'Croatia',
|
||||
HU: 'Hungary',
|
||||
ID: 'Indonesia',
|
||||
IE: 'Ireland',
|
||||
IL: 'Israel',
|
||||
IN: 'India',
|
||||
IQ: 'Iraq',
|
||||
IR: 'Iran',
|
||||
IT: 'Italy',
|
||||
JO: 'Jordan',
|
||||
JP: 'Japan',
|
||||
KE: 'Kenya',
|
||||
KP: 'North Korea',
|
||||
KR: 'South Korea',
|
||||
KW: 'Kuwait',
|
||||
KZ: 'Kazakhstan',
|
||||
LA: 'Laos',
|
||||
LK: 'Sri Lanka',
|
||||
LT: 'Lithuania',
|
||||
LU: 'Luxembourg',
|
||||
MA: 'Morocco',
|
||||
MC: 'Monaco',
|
||||
MD: 'Moldova',
|
||||
ME: 'Montenegro',
|
||||
MM: 'Myanmar',
|
||||
MN: 'Mongolia',
|
||||
MU: 'Mauritius',
|
||||
MX: 'Mexico',
|
||||
MY: 'Malaysia',
|
||||
NG: 'Nigeria',
|
||||
NL: 'Netherlands',
|
||||
NO: 'Norway',
|
||||
NP: 'Nepal',
|
||||
NZ: 'New Zealand',
|
||||
PE: 'Peru',
|
||||
PH: 'Philippines',
|
||||
PK: 'Pakistan',
|
||||
PL: 'Poland',
|
||||
PT: 'Portugal',
|
||||
PY: 'Paraguay',
|
||||
QA: 'Qatar',
|
||||
RO: 'Romania',
|
||||
RU: 'Russia',
|
||||
RW: 'Rwanda',
|
||||
SA: 'Saudi Arabia',
|
||||
SB: 'Solomon Islands',
|
||||
SD: 'Sudan',
|
||||
SE: 'Sweden',
|
||||
SG: 'Singapore',
|
||||
SI: 'Slovenia',
|
||||
SN: 'Senegal',
|
||||
TH: 'Thailand',
|
||||
TM: 'Turkmenistan',
|
||||
TN: 'Tunisia',
|
||||
TR: 'Türkiye',
|
||||
TW: 'Taiwan',
|
||||
UA: 'Ukraine',
|
||||
US: 'United States',
|
||||
UY: 'Uruguay',
|
||||
VA: 'Vatican City',
|
||||
VE: 'Venezuela',
|
||||
VN: 'Vietnam',
|
||||
ZA: 'South Africa',
|
||||
ZW: 'Zimbabwe',
|
||||
});
|
||||
|
||||
/**
|
||||
* Every owner country a satellite can be marked with, sorted: the flags
|
||||
* `scripts/build-owner-flags.mjs` draws into the owner flag sheet.
|
||||
*/
|
||||
export const OWNER_COUNTRY_CODES = Object.freeze(
|
||||
Object.keys(COUNTRY_NAMES).sort(),
|
||||
);
|
||||
|
||||
// UCS "Country of Operator/Owner" → ISO code. Joint owners ("USA/Japan") and
|
||||
// organisations are not countries and resolve through ORGANISATIONS or as a
|
||||
// joint label.
|
||||
const UCS_COUNTRIES = Object.freeze({
|
||||
Algeria: 'DZ',
|
||||
Angola: 'AO',
|
||||
Argentina: 'AR',
|
||||
Australia: 'AU',
|
||||
Austria: 'AT',
|
||||
Azerbaijan: 'AZ',
|
||||
Bangladesh: 'BD',
|
||||
Belarus: 'BY',
|
||||
Belgium: 'BE',
|
||||
Bolivia: 'BO',
|
||||
Brazil: 'BR',
|
||||
Bulgaria: 'BG',
|
||||
Canada: 'CA',
|
||||
Chile: 'CL',
|
||||
China: 'CN',
|
||||
Colombia: 'CO',
|
||||
'Czech Republic': 'CZ',
|
||||
Denmark: 'DK',
|
||||
Ecuador: 'EC',
|
||||
Egypt: 'EG',
|
||||
Estonia: 'EE',
|
||||
Ethiopia: 'ET',
|
||||
Finland: 'FI',
|
||||
France: 'FR',
|
||||
Germany: 'DE',
|
||||
Greece: 'GR',
|
||||
Hungary: 'HU',
|
||||
India: 'IN',
|
||||
Indonesia: 'ID',
|
||||
Iran: 'IR',
|
||||
Iraq: 'IQ',
|
||||
Israel: 'IL',
|
||||
Italy: 'IT',
|
||||
Japan: 'JP',
|
||||
Jordan: 'JO',
|
||||
Kazakhstan: 'KZ',
|
||||
Kenya: 'KE',
|
||||
Kuwait: 'KW',
|
||||
Laos: 'LA',
|
||||
Lithuania: 'LT',
|
||||
Luxembourg: 'LU',
|
||||
Malaysia: 'MY',
|
||||
Mexico: 'MX',
|
||||
Monaco: 'MC',
|
||||
Morocco: 'MA',
|
||||
Nepal: 'NP',
|
||||
Netherlands: 'NL',
|
||||
'New Zealand': 'NZ',
|
||||
Nigeria: 'NG',
|
||||
Norway: 'NO',
|
||||
Pakistan: 'PK',
|
||||
Peru: 'PE',
|
||||
Poland: 'PL',
|
||||
Russia: 'RU',
|
||||
'Saudi Arabia': 'SA',
|
||||
Sinapore: 'SG',
|
||||
Singapore: 'SG',
|
||||
Slovenia: 'SI',
|
||||
'South Africa': 'ZA',
|
||||
'South Korea': 'KR',
|
||||
Spain: 'ES',
|
||||
Sudan: 'SD',
|
||||
Sweden: 'SE',
|
||||
Switzerland: 'CH',
|
||||
Taiwan: 'TW',
|
||||
Thailand: 'TH',
|
||||
Tunisia: 'TN',
|
||||
Turkey: 'TR',
|
||||
UK: 'GB',
|
||||
USA: 'US',
|
||||
Ukraine: 'UA',
|
||||
'United Arab Emirates': 'AE',
|
||||
'United Kingdom': 'GB',
|
||||
Venezuela: 'VE',
|
||||
Vietnam: 'VN',
|
||||
});
|
||||
|
||||
// CelesTrak SATCAT OWNER code → ISO code (https://celestrak.org/satcat/sources.php).
|
||||
// CIS (former USSR) is filed under Russia, its continuing state.
|
||||
const SATCAT_COUNTRIES = Object.freeze({
|
||||
ALG: 'DZ',
|
||||
ANG: 'AO',
|
||||
ARGN: 'AR',
|
||||
ARM: 'AM',
|
||||
ASRA: 'AT',
|
||||
AUS: 'AU',
|
||||
AZER: 'AZ',
|
||||
BEL: 'BE',
|
||||
BELA: 'BY',
|
||||
BERM: 'BM',
|
||||
BGD: 'BD',
|
||||
BHR: 'BH',
|
||||
BHUT: 'BT',
|
||||
BOL: 'BO',
|
||||
BRAZ: 'BR',
|
||||
BUL: 'BG',
|
||||
BWA: 'BW',
|
||||
CA: 'CA',
|
||||
CHLE: 'CL',
|
||||
CIS: 'RU',
|
||||
COL: 'CO',
|
||||
CRI: 'CR',
|
||||
CZCH: 'CZ',
|
||||
DEN: 'DK',
|
||||
DJI: 'DJ',
|
||||
ECU: 'EC',
|
||||
EGYP: 'EG',
|
||||
EST: 'EE',
|
||||
ETH: 'ET',
|
||||
FIN: 'FI',
|
||||
FR: 'FR',
|
||||
GER: 'DE',
|
||||
GHA: 'GH',
|
||||
GREC: 'GR',
|
||||
GUAT: 'GT',
|
||||
HRV: 'HR',
|
||||
HUN: 'HU',
|
||||
IND: 'IN',
|
||||
INDO: 'ID',
|
||||
IRAN: 'IR',
|
||||
IRAQ: 'IQ',
|
||||
IRL: 'IE',
|
||||
ISRA: 'IL',
|
||||
ISRO: 'IN',
|
||||
IT: 'IT',
|
||||
JPN: 'JP',
|
||||
KAZ: 'KZ',
|
||||
KEN: 'KE',
|
||||
LAOS: 'LA',
|
||||
LKA: 'LK',
|
||||
LTU: 'LT',
|
||||
LUXE: 'LU',
|
||||
MA: 'MA',
|
||||
MALA: 'MY',
|
||||
MCO: 'MC',
|
||||
MDA: 'MD',
|
||||
MEX: 'MX',
|
||||
MMR: 'MM',
|
||||
MNE: 'ME',
|
||||
MNG: 'MN',
|
||||
MUS: 'MU',
|
||||
NETH: 'NL',
|
||||
NIG: 'NG',
|
||||
NKOR: 'KP',
|
||||
NOR: 'NO',
|
||||
NPL: 'NP',
|
||||
NZ: 'NZ',
|
||||
PAKI: 'PK',
|
||||
PERU: 'PE',
|
||||
POL: 'PL',
|
||||
POR: 'PT',
|
||||
PRC: 'CN',
|
||||
PRY: 'PY',
|
||||
QAT: 'QA',
|
||||
ROC: 'TW',
|
||||
ROM: 'RO',
|
||||
RP: 'PH',
|
||||
RWA: 'RW',
|
||||
SAFR: 'ZA',
|
||||
SAUD: 'SA',
|
||||
SDN: 'SD',
|
||||
SEN: 'SN',
|
||||
SING: 'SG',
|
||||
SKOR: 'KR',
|
||||
SLB: 'SB',
|
||||
SPN: 'ES',
|
||||
SVN: 'SI',
|
||||
SWED: 'SE',
|
||||
SWTZ: 'CH',
|
||||
THAI: 'TH',
|
||||
TUN: 'TN',
|
||||
TURK: 'TR',
|
||||
UAE: 'AE',
|
||||
UK: 'GB',
|
||||
UKR: 'UA',
|
||||
URY: 'UY',
|
||||
US: 'US',
|
||||
VAT: 'VA',
|
||||
VENZ: 'VE',
|
||||
VTNM: 'VN',
|
||||
ZWE: 'ZW',
|
||||
});
|
||||
|
||||
// Organisations, by SATCAT code and by UCS name: no flag, a short label.
|
||||
const ORGANISATIONS = Object.freeze({
|
||||
AB: 'Arabsat',
|
||||
ABS: 'ABS',
|
||||
AC: 'AsiaSat',
|
||||
ESA: 'ESA',
|
||||
ESRO: 'ESRO',
|
||||
EUME: 'EUMETSAT',
|
||||
EUTE: 'Eutelsat',
|
||||
GLOB: 'Globalstar',
|
||||
IM: 'Inmarsat',
|
||||
IRID: 'Iridium',
|
||||
ISS: 'ISS partners',
|
||||
ITSO: 'Intelsat',
|
||||
NATO: 'NATO',
|
||||
NICO: 'New ICO',
|
||||
O3B: 'O3b',
|
||||
ORB: 'ORBCOMM',
|
||||
RASC: 'RascomStar-QAF',
|
||||
SEAL: 'Sea Launch',
|
||||
SES: 'SES',
|
||||
Multinational: 'Multinational',
|
||||
});
|
||||
|
||||
// SATCAT codes for joint ownership, as their parts.
|
||||
const SATCAT_JOINT = Object.freeze({
|
||||
CHBZ: ['CN', 'BR'],
|
||||
CHTU: ['CN', 'TR'],
|
||||
FGER: ['FR', 'DE'],
|
||||
FRIT: ['FR', 'IT'],
|
||||
GRSA: ['GR', 'SA'],
|
||||
PRES: ['CN', 'ESA'],
|
||||
SGJP: ['SG', 'JP'],
|
||||
STCT: ['SG', 'TW'],
|
||||
TMMC: ['TM', 'MC'],
|
||||
USBZ: ['US', 'BR'],
|
||||
});
|
||||
|
||||
function country(code) {
|
||||
return COUNTRY_NAMES[code]
|
||||
? { countryCode: code, label: COUNTRY_NAMES[code] }
|
||||
: null;
|
||||
}
|
||||
|
||||
function joint(parts) {
|
||||
const labels = parts.map(
|
||||
(part) => COUNTRY_NAMES[part] || ORGANISATIONS[part] || part,
|
||||
);
|
||||
return { countryCode: null, label: labels.join(' / ') };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a UCS owner country ("USA", "China/France", "ESA",
|
||||
* "Multinational") to `{ countryCode, label }`.
|
||||
* @param {string|null|undefined} text
|
||||
* @returns {{countryCode: string|null, label: string}|null}
|
||||
*/
|
||||
export function ownerFromUcs(text) {
|
||||
const value = String(text || '').trim();
|
||||
if (!value) return null;
|
||||
if (UCS_COUNTRIES[value]) return country(UCS_COUNTRIES[value]);
|
||||
if (ORGANISATIONS[value])
|
||||
return { countryCode: null, label: ORGANISATIONS[value] };
|
||||
if (value.includes('/'))
|
||||
return joint(
|
||||
value
|
||||
.split('/')
|
||||
.map((part) => part.trim())
|
||||
.map((part) => UCS_COUNTRIES[part] || part),
|
||||
);
|
||||
return { countryCode: null, label: value };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a CelesTrak SATCAT OWNER code ("US", "PRC", "CIS", "ITSO") to
|
||||
* `{ countryCode, label }`; null for TBD, UNK and blanks.
|
||||
* @param {string|null|undefined} code
|
||||
* @returns {{countryCode: string|null, label: string}|null}
|
||||
*/
|
||||
export function ownerFromSatcat(code) {
|
||||
const value = String(code || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (!value || value === 'TBD' || value === 'UNK') return null;
|
||||
if (SATCAT_COUNTRIES[value]) return country(SATCAT_COUNTRIES[value]);
|
||||
if (ORGANISATIONS[value])
|
||||
return { countryCode: null, label: ORGANISATIONS[value] };
|
||||
if (SATCAT_JOINT[value]) return joint(SATCAT_JOINT[value]);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who owns a satellite: UCS names the operator's country, SATCAT the
|
||||
* registering owner; UCS wins where both exist. Starlink without either is
|
||||
* SpaceX's, so United States.
|
||||
* @returns {{countryCode: string|null, label: string}|null}
|
||||
*/
|
||||
export function satelliteOwner({
|
||||
ucs = null,
|
||||
satcat = null,
|
||||
satelliteClass,
|
||||
} = {}) {
|
||||
return (
|
||||
ownerFromUcs(ucs?.operatorCountry) ||
|
||||
ownerFromSatcat(satcat?.owner) ||
|
||||
(satelliteClass === 'starlink' ? country('US') : null)
|
||||
);
|
||||
}
|
||||
|
||||
/** Who operates a satellite: UCS's operator, or SpaceX for Starlink. */
|
||||
export function satelliteOperator({ ucs = null, satelliteClass } = {}) {
|
||||
if (ucs?.operator) return ucs.operator;
|
||||
return satelliteClass === 'starlink' ? 'SpaceX' : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The international designator (COSPAR id) from TLE line 1, columns 10–17:
|
||||
* `98067A` → `1998-067A`. Two-digit years below 57 are 20xx.
|
||||
* @param {string|null|undefined} line1
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function cosparIdFromTleLine1(line1) {
|
||||
const field = String(line1 || '')
|
||||
.slice(9, 17)
|
||||
.trim();
|
||||
const match = /^(\d{2})(\d{3})([A-Z]{1,3})$/.exec(field);
|
||||
if (!match) return null;
|
||||
const yy = Number(match[1]);
|
||||
return `${yy < 57 ? 2000 + yy : 1900 + yy}-${match[2]}${match[3]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The TLE's epoch as epoch milliseconds, from satellite.js's Julian date.
|
||||
* @param {{jdsatepoch?: number, jdsatepochF?: number}|null|undefined} satrec
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function tleEpochMs(satrec) {
|
||||
const jd = Number(satrec?.jdsatepoch) + (Number(satrec?.jdsatepochF) || 0);
|
||||
return Number.isFinite(jd) && jd > 0
|
||||
? Math.round((jd - 2440587.5) * 86_400_000)
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Split one RFC 4180 CSV line (quoted fields may hold commas). */
|
||||
function csvFields(line) {
|
||||
const fields = [];
|
||||
let field = '';
|
||||
let quoted = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i];
|
||||
if (quoted) {
|
||||
if (ch === '"' && line[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else if (ch === '"') quoted = false;
|
||||
else field += ch;
|
||||
} else if (ch === '"') quoted = true;
|
||||
else if (ch === ',') {
|
||||
fields.push(field);
|
||||
field = '';
|
||||
} else field += ch;
|
||||
}
|
||||
fields.push(field);
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse CelesTrak SATCAT CSV into records keyed by NORAD number.
|
||||
* @param {string} text `records.php?…&FORMAT=CSV` body.
|
||||
* @returns {Map<number, {objectType: string, opsStatus: string,
|
||||
* owner: string, cosparId: string|null, launchDate: string|null}>}
|
||||
*/
|
||||
export function parseSatcatCsv(text) {
|
||||
const records = new Map();
|
||||
const lines = String(text || '')
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.trim());
|
||||
if (!lines.length) return records;
|
||||
const header = csvFields(lines[0]).map((name) => name.trim());
|
||||
const at = (name) => header.indexOf(name);
|
||||
const col = {
|
||||
norad: at('NORAD_CAT_ID'),
|
||||
type: at('OBJECT_TYPE'),
|
||||
status: at('OPS_STATUS_CODE'),
|
||||
owner: at('OWNER'),
|
||||
id: at('OBJECT_ID'),
|
||||
launch: at('LAUNCH_DATE'),
|
||||
};
|
||||
if (col.norad < 0 || col.type < 0) return records;
|
||||
for (const line of lines.slice(1)) {
|
||||
const fields = csvFields(line);
|
||||
const noradId = Number(fields[col.norad]);
|
||||
if (!Number.isInteger(noradId) || noradId <= 0) continue;
|
||||
const text = (index) => (index < 0 ? '' : (fields[index] ?? '').trim());
|
||||
records.set(noradId, {
|
||||
objectType: text(col.type).toUpperCase(),
|
||||
opsStatus: text(col.status),
|
||||
owner: text(col.owner),
|
||||
cosparId: text(col.id) || null,
|
||||
launchDate: text(col.launch) || null,
|
||||
});
|
||||
}
|
||||
return records;
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { twoline2satrec } from 'satellite.js';
|
||||
import {
|
||||
DEFAULT_SATELLITE_CLASSES,
|
||||
PRESUMED_DEAD_AFTER_YEARS,
|
||||
SATELLITE_CLASS_DISPLAY,
|
||||
SATELLITE_CLASS_IDS,
|
||||
classifySatellite,
|
||||
cosparIdFromTleLine1,
|
||||
mergeClassVisibility,
|
||||
ownerFromSatcat,
|
||||
ownerFromUcs,
|
||||
parseSatcatCsv,
|
||||
satelliteClassEnterable,
|
||||
satelliteOperator,
|
||||
satelliteOwner,
|
||||
tleEpochMs,
|
||||
} from './classes.js';
|
||||
import { CATALOG_GROUPS } from './policy.js';
|
||||
|
||||
const NOW = 2026;
|
||||
const classify = (subject) => classifySatellite({ nowYear: NOW, ...subject });
|
||||
|
||||
test('six classes, with stations and imaging on by default and the rest off', () => {
|
||||
assert.deepEqual(SATELLITE_CLASS_IDS, [
|
||||
'stations',
|
||||
'imaging',
|
||||
'telecom',
|
||||
'starlink',
|
||||
'probes',
|
||||
'debris',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
SATELLITE_CLASS_IDS.filter((id) => DEFAULT_SATELLITE_CLASSES[id]),
|
||||
['stations', 'imaging', 'telecom', 'probes', 'debris'],
|
||||
);
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const display = SATELLITE_CLASS_DISPLAY[id];
|
||||
assert.match(display.color, /^#[0-9a-f]{6}$/, id);
|
||||
assert.ok(display.label && display.blurb, id);
|
||||
}
|
||||
});
|
||||
|
||||
test('SATCAT object type and status file debris first, overruling UCS', () => {
|
||||
const imaging = { purpose: 'Earth Observation' };
|
||||
for (const objectType of ['R/B', 'DEB', 'UNK'])
|
||||
assert.equal(classify({ name: 'X', satcat: { objectType, opsStatus: '' } }), 'debris', objectType);
|
||||
// A satellite UCS listed in 2023 that SATCAT now calls dead or decayed.
|
||||
for (const opsStatus of ['-', 'D'])
|
||||
assert.equal(
|
||||
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus } }),
|
||||
'debris',
|
||||
opsStatus,
|
||||
);
|
||||
assert.equal(
|
||||
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus: '+' } }),
|
||||
'imaging',
|
||||
);
|
||||
// SATCAT calls a new launch's objects UNK until it names them: only an
|
||||
// old unknown object, or one with no launch date, is debris.
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'OBJECT C',
|
||||
group: 'resource',
|
||||
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2025-11-02' },
|
||||
}),
|
||||
'imaging',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'OBJECT C',
|
||||
group: 'resource',
|
||||
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2019-04-01' },
|
||||
}),
|
||||
'debris',
|
||||
);
|
||||
// Debris riding in the stations group (CelesTrak lists FREGAT DEB there).
|
||||
assert.equal(classify({ name: 'FREGAT DEB', group: 'stations' }), 'debris');
|
||||
assert.equal(classify({ name: 'SL-16 R/B', group: 'visual' }), 'debris');
|
||||
});
|
||||
|
||||
test('the ISS is a station whatever else says', () => {
|
||||
assert.equal(
|
||||
classify({ noradId: 25544, name: 'ISS (ZARYA)', group: 'visual', satcat: { objectType: 'DEB' } }),
|
||||
'stations',
|
||||
);
|
||||
});
|
||||
|
||||
test('stations: crewed stations and visiting vehicles by name', () => {
|
||||
assert.equal(classify({ name: 'CSS (TIANHE)', group: 'stations' }), 'stations');
|
||||
assert.equal(classify({ name: 'ISS (NAUKA)', group: 'stations' }), 'stations');
|
||||
for (const name of ['SHENZHOU-21', 'TIANZHOU-9', 'SOYUZ-MS 28', 'PROGRESS-MS 31', 'CREW DRAGON 11', 'CYGNUS NG-23'])
|
||||
assert.equal(classify({ name, group: 'visual' }), 'stations', name);
|
||||
});
|
||||
|
||||
test('UCS purpose decides imaging, telecom and probes', () => {
|
||||
const table = [
|
||||
['Earth Observation', 'imaging'],
|
||||
['Earth Science', 'imaging'],
|
||||
['Meteorological', 'imaging'],
|
||||
['Surveillance', 'imaging'],
|
||||
['Earth Observation/Navigation', 'imaging'],
|
||||
['Earth/Space Observation', 'imaging'],
|
||||
['Communications', 'telecom'],
|
||||
['Navigation/Global Positioning', 'telecom'],
|
||||
['Navigation/Regional Positioning', 'telecom'],
|
||||
['Technology Development', 'probes'],
|
||||
['Technology Demonstration', 'probes'],
|
||||
['Space Science', 'probes'],
|
||||
['Unknown', 'probes'],
|
||||
];
|
||||
for (const [purpose, expected] of table)
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', ucs: { purpose } }), expected, purpose);
|
||||
});
|
||||
|
||||
test('satellites launched after the UCS snapshot are classed by name', () => {
|
||||
const table = [
|
||||
['ICEYE-X50', 'imaging'],
|
||||
['CAPELLA-17', 'imaging'],
|
||||
['FLOCK 4Y-12', 'imaging'],
|
||||
['PELICAN-3', 'imaging'],
|
||||
['SENTINEL-1C', 'imaging'],
|
||||
['LANDSAT 9', 'imaging'],
|
||||
['GOES 19', 'imaging'],
|
||||
['ONEWEB-0712', 'telecom'],
|
||||
['IRIDIUM 180', 'telecom'],
|
||||
['GPS BIII-8 (PRN 14)', 'telecom'],
|
||||
['KUIPER-00042', 'telecom'],
|
||||
['STARLINK-34012', 'starlink'],
|
||||
];
|
||||
for (const [name, expected] of table)
|
||||
assert.equal(classify({ name, group: 'visual', launchYear: 2025 }), expected, name);
|
||||
});
|
||||
|
||||
test('the group the TLE came in is the last resort', () => {
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'resource', launchYear: 2024 }), 'imaging');
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'geo', launchYear: 2024 }), 'telecom');
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'science', launchYear: 2024 }), 'probes');
|
||||
assert.equal(classify({ name: 'STARLINK-1', group: 'dense' }), 'starlink');
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 2024 }), 'probes');
|
||||
});
|
||||
|
||||
test('CubeSats deployed from the ISS are not stations', () => {
|
||||
// They ride in CelesTrak's stations group under the ISS's 1998 designator.
|
||||
for (const name of ['DUPLEX', 'KNACKSAT-2', 'GXIBA-1', 'LEOPARD', 'HMU-SAT2']) {
|
||||
assert.equal(
|
||||
classify({ name, group: 'stations', launchYear: 1998 }),
|
||||
'probes',
|
||||
`${name} without SATCAT`,
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name,
|
||||
group: 'stations',
|
||||
launchYear: 1998,
|
||||
satcat: { objectType: 'PAY', opsStatus: '', launchDate: '2025-04-21' },
|
||||
}),
|
||||
'probes',
|
||||
`${name}: SATCAT's 2025 launch, not the designator's 1998`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
classify({ name: 'UNNAMED-1', group: 'stations', ucs: { purpose: 'Earth Observation' } }),
|
||||
'imaging',
|
||||
);
|
||||
});
|
||||
|
||||
test('an unknown old payload is presumed dead; a recognisable one is not', () => {
|
||||
const old = NOW - PRESUMED_DEAD_AFTER_YEARS;
|
||||
assert.equal(
|
||||
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963 }),
|
||||
'probes',
|
||||
'without a SATCAT record (a failed read) nothing is presumed',
|
||||
);
|
||||
assert.equal(
|
||||
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963, satcat: { objectType: 'PAY', opsStatus: '' } }),
|
||||
'debris',
|
||||
'a blank SATCAT status is no evidence of life',
|
||||
);
|
||||
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: old + 1 }), 'probes');
|
||||
assert.equal(classify({ name: 'NOAA 15', group: 'weather', launchYear: 1998 }), 'imaging');
|
||||
assert.equal(
|
||||
classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 1990, satcat: { objectType: 'PAY', opsStatus: '+' } }),
|
||||
'probes',
|
||||
'SATCAT says it works',
|
||||
);
|
||||
});
|
||||
|
||||
test('only debris is refused the Cockpit', () => {
|
||||
for (const id of SATELLITE_CLASS_IDS)
|
||||
assert.equal(satelliteClassEnterable(id), id !== 'debris', id);
|
||||
assert.equal(satelliteClassEnterable('nonsense'), false);
|
||||
});
|
||||
|
||||
test('class visibility merges booleans and ignores everything else', () => {
|
||||
const next = mergeClassVisibility({ telecom: true, imaging: false, debris: 'yes', bogus: true });
|
||||
assert.deepEqual(next, { ...DEFAULT_SATELLITE_CLASSES, telecom: true, imaging: false });
|
||||
assert.deepEqual(mergeClassVisibility(null), { ...DEFAULT_SATELLITE_CLASSES });
|
||||
assert.equal(Object.hasOwn(next, 'bogus'), false);
|
||||
});
|
||||
|
||||
test('UCS owner countries normalise to ISO codes, organisations and joint owners', () => {
|
||||
assert.deepEqual(ownerFromUcs('USA'), { countryCode: 'US', label: 'United States' });
|
||||
assert.deepEqual(ownerFromUcs('United Kingdom'), { countryCode: 'GB', label: 'United Kingdom' });
|
||||
assert.deepEqual(ownerFromUcs('Sinapore'), { countryCode: 'SG', label: 'Singapore' }, 'UCS typo');
|
||||
assert.deepEqual(ownerFromUcs('Turkey'), { countryCode: 'TR', label: 'Türkiye' });
|
||||
assert.deepEqual(ownerFromUcs('ESA'), { countryCode: null, label: 'ESA' });
|
||||
assert.deepEqual(ownerFromUcs('Multinational'), { countryCode: null, label: 'Multinational' });
|
||||
assert.deepEqual(ownerFromUcs('China/France'), { countryCode: null, label: 'China / France' });
|
||||
assert.deepEqual(ownerFromUcs('United Kingdom/ESA'), { countryCode: null, label: 'United Kingdom / ESA' });
|
||||
assert.equal(ownerFromUcs(''), null);
|
||||
assert.equal(ownerFromUcs(null), null);
|
||||
});
|
||||
|
||||
test('SATCAT owner codes normalise the same way', () => {
|
||||
assert.deepEqual(ownerFromSatcat('US'), { countryCode: 'US', label: 'United States' });
|
||||
assert.deepEqual(ownerFromSatcat('PRC'), { countryCode: 'CN', label: 'China' });
|
||||
assert.deepEqual(ownerFromSatcat('CIS'), { countryCode: 'RU', label: 'Russia' }, 'former USSR');
|
||||
assert.deepEqual(ownerFromSatcat('ISRO'), { countryCode: 'IN', label: 'India' });
|
||||
assert.deepEqual(ownerFromSatcat('itso'), { countryCode: null, label: 'Intelsat' });
|
||||
assert.deepEqual(ownerFromSatcat('EUME'), { countryCode: null, label: 'EUMETSAT' });
|
||||
assert.deepEqual(ownerFromSatcat('PRES'), { countryCode: null, label: 'China / ESA' });
|
||||
assert.deepEqual(ownerFromSatcat('TMMC'), { countryCode: null, label: 'Turkmenistan / Monaco' });
|
||||
for (const code of ['TBD', 'UNK', '', null, 'ZZZZ']) assert.equal(ownerFromSatcat(code), null, String(code));
|
||||
});
|
||||
|
||||
test('owner prefers UCS, falls back to SATCAT, and Starlink is American', () => {
|
||||
assert.deepEqual(
|
||||
satelliteOwner({ ucs: { operatorCountry: 'ESA' }, satcat: { owner: 'FR' } }),
|
||||
{ countryCode: null, label: 'ESA' },
|
||||
);
|
||||
assert.deepEqual(satelliteOwner({ satcat: { owner: 'FR' } }), { countryCode: 'FR', label: 'France' });
|
||||
assert.deepEqual(satelliteOwner({ satelliteClass: 'starlink' }), { countryCode: 'US', label: 'United States' });
|
||||
assert.equal(satelliteOwner({}), null);
|
||||
assert.equal(satelliteOperator({ ucs: { operator: 'Planet Labs, Inc.' } }), 'Planet Labs, Inc.');
|
||||
assert.equal(satelliteOperator({ satelliteClass: 'starlink' }), 'SpaceX');
|
||||
assert.equal(satelliteOperator({ satelliteClass: 'imaging' }), null);
|
||||
});
|
||||
|
||||
const ISS_LINE1 = '1 25544U 98067A 24001.50000000 .00016717 00000-0 30370-3 0 9993';
|
||||
const ISS_LINE2 = '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579432323';
|
||||
|
||||
test('COSPAR ids come from TLE line 1, across the 1957 century pivot', () => {
|
||||
assert.equal(cosparIdFromTleLine1(ISS_LINE1), '1998-067A');
|
||||
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '24123BC ')), '2024-123BC');
|
||||
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '57001A ')), '1957-001A');
|
||||
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', ' ')), null);
|
||||
assert.equal(cosparIdFromTleLine1(null), null);
|
||||
});
|
||||
|
||||
test('the TLE epoch is read as epoch milliseconds', () => {
|
||||
const satrec = twoline2satrec(ISS_LINE1, ISS_LINE2);
|
||||
// Day 001.5 of 2024: 1 January 2024, 12:00 UTC.
|
||||
assert.ok(Math.abs(tleEpochMs(satrec) - Date.UTC(2024, 0, 1, 12)) < 1000);
|
||||
assert.equal(tleEpochMs(null), null);
|
||||
assert.equal(tleEpochMs({}), null);
|
||||
});
|
||||
|
||||
test('SATCAT CSV parses, quoted commas included, keyed by NORAD id', () => {
|
||||
const csv = [
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER,LAUNCH_DATE',
|
||||
'ISS (ZARYA),1998-067A,25544,PAY,+,ISS,1998-11-20',
|
||||
'"THOR AGENA, D R/B",1964-002A,733,r/b,,US,1964-01-19',
|
||||
'BROKEN,,notanumber,PAY,+,US,',
|
||||
'',
|
||||
].join('\r\n');
|
||||
const records = parseSatcatCsv(csv);
|
||||
assert.deepEqual([...records.keys()], [25544, 733]);
|
||||
assert.deepEqual(records.get(25544), {
|
||||
objectType: 'PAY',
|
||||
opsStatus: '+',
|
||||
owner: 'ISS',
|
||||
cosparId: '1998-067A',
|
||||
launchDate: '1998-11-20',
|
||||
});
|
||||
assert.equal(records.get(733).objectType, 'R/B');
|
||||
assert.equal(parseSatcatCsv('<html>busy</html>').size, 0);
|
||||
assert.equal(parseSatcatCsv('').size, 0);
|
||||
});
|
||||
|
||||
/**
|
||||
* A rendering part that keeps what it is told to show: the dots and rings
|
||||
* by NORAD id, as the layer's own rendering part holds them.
|
||||
*/
|
||||
function recordingRendering(state) {
|
||||
const rings = new Map();
|
||||
return {
|
||||
rings,
|
||||
_setPointShown(noradId, show) {
|
||||
const point = state._points.get(noradId);
|
||||
if (point) point.show = show;
|
||||
},
|
||||
_setPointsShown() {},
|
||||
_setOrbitPathShown(noradId, show) {
|
||||
if (state._orbitPaths.has(noradId)) rings.set(noradId, show);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('turning Stations off takes the ISS ring and label with its point', async () => {
|
||||
const { createControls } = await import('./controls.js');
|
||||
let overlaySyncs = 0;
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_params: {
|
||||
catalog: 'core',
|
||||
showOrbits: true,
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, {}]]),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
};
|
||||
const rendering = recordingRendering(state);
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {
|
||||
labels: { _syncIssOverlay: () => (overlaySyncs += 1) },
|
||||
rendering,
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
controls._applyClassVisibility();
|
||||
assert.equal(state._points.get(25544).show, false);
|
||||
assert.equal(rendering.rings.get(25544), false, 'the ring goes with the class');
|
||||
assert.ok(overlaySyncs >= 1, 'the label is re-synced');
|
||||
state._params.classes = { ...DEFAULT_SATELLITE_CLASSES };
|
||||
controls._applyClassVisibility();
|
||||
assert.equal(rendering.rings.get(25544), true, 'and comes back with it');
|
||||
});
|
||||
|
||||
test('a failed Starlink load hides the core catalog Starlink points again', async () => {
|
||||
const { createCatalog } = await import('./catalog.js');
|
||||
let applied = 0;
|
||||
const state = {
|
||||
_params: {
|
||||
catalog: 'dense',
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, starlink: true },
|
||||
},
|
||||
_denseLoadToken: 3,
|
||||
_denseIds: [],
|
||||
_catalog: new Map(),
|
||||
_points: new Map(),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
_activeUpdateControllers: new Set(),
|
||||
coverageChanged() {},
|
||||
};
|
||||
const catalog = createCatalog({
|
||||
state,
|
||||
services: {},
|
||||
parts: {
|
||||
controls: {
|
||||
_applyClassVisibility: () => (applied += 1),
|
||||
_notifyRowControls() {},
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
catalog._denseLoadFailed(state._denseLoadToken, 'feed unreachable');
|
||||
assert.equal(state._params.catalog, 'core');
|
||||
assert.equal(state._params.classes.starlink, false, 'the choice says so');
|
||||
assert.ok(applied >= 1, 'class visibility is applied again');
|
||||
});
|
||||
|
||||
test('every ingested group names the class its unnamed members fall back to', () => {
|
||||
// A group added to CATALOG_GROUPS without a class would file its members
|
||||
// under PROBES, the catch-all.
|
||||
const expected = {
|
||||
stations: 'probes',
|
||||
visual: 'probes',
|
||||
'gps-ops': 'telecom',
|
||||
glonass: 'telecom',
|
||||
galileo: 'telecom',
|
||||
geo: 'telecom',
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
science: 'probes',
|
||||
};
|
||||
assert.deepEqual(
|
||||
Object.fromEntries(
|
||||
CATALOG_GROUPS.map(({ tag }) => [
|
||||
tag,
|
||||
classify({ noradId: 99999, name: 'UNNAMED-1', group: tag }),
|
||||
]),
|
||||
),
|
||||
expected,
|
||||
);
|
||||
});
|
||||
|
||||
test('enabling the layer leaves a hidden Stations class without its ISS ring', async () => {
|
||||
const { createLifecycle } = await import('./lifecycle.js');
|
||||
let issVisible = false;
|
||||
const state = {
|
||||
_params: { showPoints: true, showOrbits: true },
|
||||
_orbitPaths: new Map([
|
||||
[25544, {}],
|
||||
[90001, {}],
|
||||
]),
|
||||
_points: new Map(),
|
||||
coverageChanged() {},
|
||||
};
|
||||
const rendering = recordingRendering(state);
|
||||
const { methods } = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
focus: { clearFocusTarget() {} },
|
||||
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
|
||||
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
|
||||
},
|
||||
parts: {
|
||||
controls: {
|
||||
satelliteVisualsVisible: (enabled, on) => enabled && on !== false,
|
||||
_issOrbitVisible: () => issVisible,
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
interaction: { _installClickHandler() {} },
|
||||
tracking: { _applyPendingTrackingRestore() {} },
|
||||
rendering,
|
||||
},
|
||||
});
|
||||
methods.enable(null);
|
||||
assert.equal(rendering.rings.get(25544), false, 'the ISS ring follows its class');
|
||||
assert.equal(rendering.rings.get(90001), true, 'other rings follow showOrbits');
|
||||
issVisible = true;
|
||||
methods.enable(null);
|
||||
assert.equal(rendering.rings.get(25544), true);
|
||||
});
|
||||
|
||||
test('a mission group outranks an orbit group, and an Unknown UCS purpose is no evidence', () => {
|
||||
assert.equal(
|
||||
classify({ name: 'MTG-X1', group: 'geo', groups: ['geo', 'weather'] }),
|
||||
'imaging',
|
||||
);
|
||||
assert.equal(
|
||||
classify({ name: 'UNNAMED-1', group: 'geo', groups: ['geo'] }),
|
||||
'telecom',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'GPS BIII-9',
|
||||
group: 'visual',
|
||||
ucs: { purpose: 'Unknown' },
|
||||
}),
|
||||
'telecom',
|
||||
);
|
||||
assert.equal(
|
||||
classify({
|
||||
name: 'UNNAMED-1',
|
||||
group: 'resource',
|
||||
ucs: { purpose: 'Unknown' },
|
||||
}),
|
||||
'imaging',
|
||||
);
|
||||
});
|
||||
|
||||
test('a tracked ISS keeps its ring while Stations is hidden', async () => {
|
||||
const { createControls } = await import('./controls.js');
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_params: {
|
||||
catalog: 'core',
|
||||
showOrbits: true,
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, {}]]),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
};
|
||||
const rendering = recordingRendering(state);
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: { labels: { _syncIssOverlay() {} }, rendering },
|
||||
source: {},
|
||||
});
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(rendering.rings.get(25544), false);
|
||||
state._trackedNorad = 25544;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(rendering.rings.get(25544), true, 'tracked, it keeps its ring');
|
||||
state._params.showOrbits = false;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(rendering.rings.get(25544), false, 'orbits off still hides it');
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import {
|
||||
classifySatellite,
|
||||
cosparIdFromTleLine1,
|
||||
satelliteClassEnterable,
|
||||
satelliteOperator,
|
||||
satelliteOwner,
|
||||
tleEpochMs,
|
||||
} from './classes.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
/** The layer id a satellite subject carries through Cockpit events and state. */
|
||||
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
|
||||
|
||||
/**
|
||||
* While the Cockpit rides a satellite, every other orbit ring (the ISS ring
|
||||
* included) draws at this fraction of its normal alpha, so the rings stay
|
||||
* legible without competing with the nadir picture.
|
||||
*/
|
||||
export const COCKPIT_ORBIT_DIM_FACTOR = 0.3;
|
||||
|
||||
/**
|
||||
* Who and what a catalog entry is: class, COSPAR id, TLE, owner, operator.
|
||||
* Fixed for the entry's life, so it is worked out once and kept on it.
|
||||
* @param {number} noradId
|
||||
* @param {object} sat Catalog entry.
|
||||
*/
|
||||
function satelliteIdentity(noradId, sat) {
|
||||
if (sat.cockpitIdentity) return sat.cockpitIdentity;
|
||||
const satelliteClass =
|
||||
sat.satelliteClass ||
|
||||
classifySatellite({ noradId, name: sat.name, group: sat.group });
|
||||
const epochMs = tleEpochMs(sat.satrec);
|
||||
const identity = Object.freeze({
|
||||
satelliteClass,
|
||||
cosparId: sat.satcat?.cosparId || cosparIdFromTleLine1(sat.line1),
|
||||
tle:
|
||||
sat.line1 && sat.line2 && epochMs !== null
|
||||
? Object.freeze({ line1: sat.line1, line2: sat.line2, epochMs })
|
||||
: null,
|
||||
owner: freezeOwner(
|
||||
satelliteOwner({ ucs: sat.ucs, satcat: sat.satcat, satelliteClass }),
|
||||
),
|
||||
operator: satelliteOperator({ ucs: sat.ucs, satelliteClass }),
|
||||
// src/layers/satellites/sensors.js entry, or null: the orbital view's sensor swath.
|
||||
sensor: sat.sensor ?? null,
|
||||
});
|
||||
sat.cockpitIdentity = identity;
|
||||
return identity;
|
||||
}
|
||||
|
||||
function freezeOwner(owner) {
|
||||
return owner
|
||||
? Object.freeze({
|
||||
countryCode: owner.countryCode ?? null,
|
||||
label: owner.label ?? null,
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the tracked satellite and its per-frame fix into Cockpit subject
|
||||
* info, in the shape every Cockpit subject kind shares.
|
||||
* @param {number} noradId NORAD catalog number.
|
||||
* @param {{name?: string, group?: string}|null} sat Catalog entry.
|
||||
* @param {{latitude: number, longitude: number, altitude: number,
|
||||
* speedMps?: number|null, groundTrackDeg?: number|null, atMs?: number}|null}
|
||||
* fix Per-frame SGP4 sample (orbits.js propagatePosition), at `atMs`.
|
||||
* @returns {object|null} Subject info, or null without a usable fix.
|
||||
*/
|
||||
export function satelliteCockpitInfo(noradId, sat, fix) {
|
||||
if (!sat || !fix) return null;
|
||||
const { latitude, longitude, altitude } = fix;
|
||||
if (![latitude, longitude, altitude].every(Number.isFinite)) return null;
|
||||
const isIss = noradId === ISS_NORAD;
|
||||
const identity = satelliteIdentity(noradId, sat);
|
||||
return {
|
||||
kind: 'satellite',
|
||||
layerId: SATELLITE_COCKPIT_LAYER_ID,
|
||||
id: String(noradId),
|
||||
noradId,
|
||||
name: sat.name?.trim() || `SAT-${noradId}`,
|
||||
// Localized at read time, as the vessel layer's type label is.
|
||||
classLabel: satelliteClassText(identity.satelliteClass, sat.group, {
|
||||
isIss,
|
||||
}),
|
||||
latitude,
|
||||
longitude,
|
||||
altitudeM: altitude,
|
||||
// SGP4's TEME velocity: the inertial orbital speed, not ground speed.
|
||||
velocityMps: Number.isFinite(fix.speedMps) ? fix.speedMps : null,
|
||||
// The time the position is at (epoch ms), the satellites' world-clock
|
||||
// time; null when the sample does not say.
|
||||
atMs: Number.isFinite(fix.atMs) ? fix.atMs : null,
|
||||
// Degrees clockwise from north; null for a geostationary satellite.
|
||||
groundTrackDeg: Number.isFinite(fix.groundTrackDeg)
|
||||
? fix.groundTrackDeg
|
||||
: null,
|
||||
stale: false,
|
||||
// src/layers/satellites/classes.js: 'stations'|'imaging'|'telecom'|'starlink'|
|
||||
// 'probes'|'debris'.
|
||||
satelliteClass: identity.satelliteClass,
|
||||
// Whether its class may be ridden in the orbital view (debris may not);
|
||||
// the Cockpit's entry gate reads it (orbitEntryAllowed).
|
||||
enterable: satelliteClassEnterable(identity.satelliteClass),
|
||||
// International designator, e.g. '1998-067A'.
|
||||
cosparId: identity.cosparId,
|
||||
tle: identity.tle,
|
||||
// { countryCode: ISO 3166-1 alpha-2 or null (organisations, joint
|
||||
// owners), label: English name } or null.
|
||||
owner: identity.owner,
|
||||
operator: identity.operator,
|
||||
sensor: identity.sensor,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The tracked satellite as a Cockpit orbital-view subject, and the hold that
|
||||
* hides its own marks while the Cockpit camera rides it.
|
||||
*
|
||||
* While held, the tracked dot is hidden (it would sit on the lens), as are
|
||||
* the point primitives of docked companions (they share the position within
|
||||
* 2 km) and the subject's orbit ring: a nadir camera on the ring sees its far
|
||||
* side, dimmed by the ring's depth-fail appearance, drawn straight across the
|
||||
* Earth's disk. The detection overlay skips the subject too. The tracked
|
||||
* card needs nothing here: its overlay source already hides in Cockpit mode.
|
||||
* Every other orbit ring is dimmed to COCKPIT_ORBIT_DIM_FACTOR of its alpha
|
||||
* while a subject is set; other satellites' points and labels stay as they
|
||||
* are. Scene clicks and the layer's Escape are ignored while held, so the
|
||||
* picture cannot untrack its own subject. Release restores exactly what the
|
||||
* hold hid or dimmed.
|
||||
*/
|
||||
export function createCockpitSubject({ state: layerState, parts }) {
|
||||
/** The subject is held only while it is the tracked satellite. */
|
||||
function _cockpitHeld() {
|
||||
return (
|
||||
layerState._cockpitSubjectNorad !== null &&
|
||||
layerState._cockpitSubjectNorad === layerState._trackedNorad
|
||||
);
|
||||
}
|
||||
|
||||
function _setPointShown(noradId, show) {
|
||||
// Released points go back to their class's visibility.
|
||||
parts.rendering._setPointShown(
|
||||
noradId,
|
||||
show && parts.controls._classVisible(noradId),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply or release the hold. Idempotent, and cheap enough for the preRender
|
||||
* tick, which re-applies it while held so catalog rebuilds, enable and the
|
||||
* orbit toggle cannot re-show what the hold hides.
|
||||
* @returns {void}
|
||||
*/
|
||||
function _syncCockpitSubjectVisuals() {
|
||||
const held = _cockpitHeld();
|
||||
const tracked = layerState._trackedNorad;
|
||||
|
||||
if (held) {
|
||||
parts.rendering._setTrackedDotShown(false);
|
||||
layerState._cockpitHiddenDot = true;
|
||||
} else if (layerState._cockpitHiddenDot) {
|
||||
parts.rendering._setTrackedDotShown(true);
|
||||
layerState._cockpitHiddenDot = false;
|
||||
}
|
||||
|
||||
const hiddenPoints = layerState._cockpitHiddenPoints;
|
||||
const companions = held ? layerState._dockedCompanions : new Set();
|
||||
for (const noradId of [...hiddenPoints]) {
|
||||
if (companions.has(noradId)) continue;
|
||||
hiddenPoints.delete(noradId);
|
||||
// The tracked point stays hidden: the tracked dot draws it.
|
||||
if (noradId !== tracked) _setPointShown(noradId, true);
|
||||
}
|
||||
// Re-applied every sync: a catalog rebuild replaces the points, and the
|
||||
// new ones arrive shown.
|
||||
for (const noradId of companions) {
|
||||
if (noradId === tracked) continue;
|
||||
hiddenPoints.add(noradId);
|
||||
_setPointShown(noradId, false);
|
||||
}
|
||||
if (held) parts.rendering._setPointShown(tracked, false);
|
||||
|
||||
const hiddenPath = layerState._cockpitHiddenPath;
|
||||
if (hiddenPath !== null && (!held || hiddenPath !== tracked)) {
|
||||
const hasPath = layerState._orbitPaths.has(hiddenPath);
|
||||
// The ISS's ring also follows its class (and its tracking).
|
||||
if (hasPath && hiddenPath === ISS_NORAD) parts.controls._syncIssOrbit();
|
||||
else if (hasPath)
|
||||
parts.rendering._setOrbitPathShown(
|
||||
hiddenPath,
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
),
|
||||
);
|
||||
layerState._cockpitHiddenPath = null;
|
||||
}
|
||||
if (held && layerState._orbitPaths.has(tracked)) {
|
||||
parts.rendering._setOrbitPathShown(tracked, false);
|
||||
layerState._cockpitHiddenPath = tracked;
|
||||
}
|
||||
|
||||
// Every other ring is dimmed for the whole session and restored on
|
||||
// release; rebuilt rings arrive at full alpha and are dimmed again here.
|
||||
const subject = layerState._cockpitSubjectNorad;
|
||||
for (const noradId of layerState._orbitPaths.keys()) {
|
||||
const dim = subject !== null && noradId !== subject;
|
||||
parts.rendering._setOrbitPathAlpha(
|
||||
noradId,
|
||||
dim ? COCKPIT_ORBIT_DIM_FACTOR : 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const methods = {
|
||||
/**
|
||||
* The tracked satellite as Cockpit subject info, from the same per-frame
|
||||
* SGP4 sample the dot and the follow camera use.
|
||||
* @returns {{kind: 'satellite', layerId: 'satellites', id: string,
|
||||
* noradId: number, name: string, classLabel: string,
|
||||
* latitude: number, longitude: number, altitudeM: number,
|
||||
* velocityMps: number|null, stale: false,
|
||||
* satelliteClass: 'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris',
|
||||
* cosparId: string|null,
|
||||
* tle: {line1: string, line2: string, epochMs: number}|null,
|
||||
* owner: {countryCode: string|null, label: string|null}|null,
|
||||
* operator: string|null}|null} Null while the layer is off or nothing
|
||||
* is tracked.
|
||||
*/
|
||||
getCockpitSubject() {
|
||||
if (!layerState._enabled || layerState._trackedNorad === null)
|
||||
return null;
|
||||
const noradId = layerState._trackedNorad;
|
||||
return satelliteCockpitInfo(
|
||||
noradId,
|
||||
layerState._catalog.get(noradId),
|
||||
parts.tracking._getTrackedFramePosition(),
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* The tracked satellite's Earth-fixed position this frame: the per-frame
|
||||
* cache the dot and follow camera read, never a separate propagation.
|
||||
* @param {{x: number, y: number, z: number}} [result] Receives the
|
||||
* position.
|
||||
* @returns {{x: number, y: number, z: number}|null} Null while the layer is off, nothing
|
||||
* is tracked or no sample has propagated.
|
||||
*/
|
||||
getCockpitPosition(result) {
|
||||
if (!layerState._enabled || layerState._trackedNorad === null)
|
||||
return null;
|
||||
if (!parts.tracking._getTrackedFramePosition()) return null;
|
||||
const { x, y, z } = layerState._trackedFrameCartesian;
|
||||
const out = result ?? {};
|
||||
out.x = x;
|
||||
out.y = y;
|
||||
out.z = z;
|
||||
return out;
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark the satellite whose position the Cockpit camera occupies, or
|
||||
* release it. The hold applies while that satellite is tracked.
|
||||
* @param {string|number|null} noradId Subject NORAD id, or null to release.
|
||||
* @returns {boolean} Always true.
|
||||
*/
|
||||
setCockpitSubject(noradId) {
|
||||
const next =
|
||||
noradId === null || noradId === undefined
|
||||
? null
|
||||
: parts.tracking._normalizeTrackedNorad(noradId);
|
||||
if (layerState._cockpitSubjectNorad === next) return true;
|
||||
layerState._cockpitSubjectNorad = next;
|
||||
_syncCockpitSubjectVisuals();
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Put the follow camera back on the tracked satellite after the Cockpit
|
||||
* released it, without re-tracking (no new selection or context events).
|
||||
* @param {string|number} noradId The satellite the Cockpit rode.
|
||||
* @returns {boolean} True when that satellite is still tracked and the
|
||||
* follow camera was restored.
|
||||
*/
|
||||
refocusTrackedById(noradId) {
|
||||
const id = parts.tracking._normalizeTrackedNorad(noradId);
|
||||
const viewer = layerState._viewer;
|
||||
if (
|
||||
id === null ||
|
||||
id !== layerState._trackedNorad ||
|
||||
!viewer ||
|
||||
!layerState._followTarget
|
||||
)
|
||||
return false;
|
||||
const camera = cameraOf(viewer);
|
||||
camera.cancelFlight();
|
||||
camera.follow(layerState._followTarget);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
return { _cockpitHeld, _syncCockpitSubjectVisuals, methods };
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createState } from './state.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { createLabels } from './labels.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createCatalog } from './catalog.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createInteraction } from './interaction.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import {
|
||||
COCKPIT_ORBIT_DIM_FACTOR,
|
||||
createCockpitSubject,
|
||||
satelliteCockpitInfo,
|
||||
} from './cockpitSubject.js';
|
||||
import { groundTrackBearingDeg } from './orbits.js';
|
||||
import { indexImagingSensors } from './sensors.js';
|
||||
import { ISS_NORAD, TRACKED_ORBIT_COLOR } from './policy.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
|
||||
const COMPANION = 25545;
|
||||
const GPS = 32711;
|
||||
|
||||
function tle(name, id, motion = '15.48899044', inclination = ' 51.6326') {
|
||||
// Owned synthetic element sets; never live requests. The station pair
|
||||
// share elements, so the companion is docked to the ISS.
|
||||
return `${name}\n1 ${id}U 98067A 26289.78971908 .00007803 00000+0 15012-3 0 9995\n2 ${id} ${inclination} 58.3278 0006748 271.9059 88.1156 ${motion}590607`;
|
||||
}
|
||||
|
||||
const GROUP_TEXT = {
|
||||
stations: [
|
||||
tle('ISS (ZARYA)', ISS_NORAD),
|
||||
tle('PROGRESS-MS 31', COMPANION),
|
||||
].join('\n'),
|
||||
'gps-ops': tle('GPS FIXTURE', GPS, ' 2.00563000', ' 55.0000'),
|
||||
};
|
||||
|
||||
/** The layer's live draw set whose id ends with `suffix`. */
|
||||
function drawnSet(f, suffix) {
|
||||
return [...f.draw.sets.values()].find(
|
||||
(set) => !set.disposed && set.spec.id.endsWith(suffix),
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the tracked dot is drawn shown. */
|
||||
function dotShown(f) {
|
||||
const set = drawnSet(f, ':tracked');
|
||||
const dot = set.items.get(String(f.state._trackedNorad));
|
||||
return dot?.show !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A camera port that keeps what it follows: enough for the layer's follow,
|
||||
* its follow-change listener and the Cockpit's refocus.
|
||||
*/
|
||||
function fakeFollowCamera() {
|
||||
const listeners = new Set();
|
||||
const camera = {
|
||||
followed: null,
|
||||
flightsCancelled: 0,
|
||||
follow(target) {
|
||||
camera.followed = target ?? null;
|
||||
for (const cb of [...listeners]) cb(camera.followed);
|
||||
},
|
||||
cancelFlight() {
|
||||
camera.flightsCancelled += 1;
|
||||
},
|
||||
flyTo() {},
|
||||
pose: () => ({ lon: 0, lat: 0, height: 2e7, heading: 0, pitch: -1.57 }),
|
||||
on(event, cb) {
|
||||
if (event !== 'followChanged') return () => {};
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
};
|
||||
return camera;
|
||||
}
|
||||
|
||||
/** A frame port whose preRender the test steps by hand. */
|
||||
function fakeFrame() {
|
||||
const listeners = new Set();
|
||||
return {
|
||||
on(phase, cb) {
|
||||
if (phase !== 'preRender') return () => {};
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
requestRender() {},
|
||||
holdContinuous: () => () => {},
|
||||
time: () => Date.now(),
|
||||
step(t) {
|
||||
for (const cb of [...listeners]) cb(t);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const SATCAT_HEADER =
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER';
|
||||
const SATCAT_TEXT = {
|
||||
stations: [
|
||||
SATCAT_HEADER,
|
||||
`ISS (ZARYA),1998-067A,${ISS_NORAD},PAY,+,ISS`,
|
||||
`PROGRESS-MS 31,2026-001A,${COMPANION},PAY,+,CIS`,
|
||||
].join('\n'),
|
||||
// No designator: the TLE's is used.
|
||||
'gps-ops': [SATCAT_HEADER, `GPS FIXTURE,,${GPS},PAY,+,US`].join('\n'),
|
||||
};
|
||||
const UCS = new Map([
|
||||
[
|
||||
ISS_NORAD,
|
||||
{
|
||||
noradId: ISS_NORAD,
|
||||
operator: 'NASA/Multinational',
|
||||
operatorCountry: 'Multinational',
|
||||
purpose: 'Space Science',
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
// One sensor entry, matched by NORAD number, for the orbital zoom cap.
|
||||
const SENSORS = indexImagingSensors({
|
||||
entries: [
|
||||
{
|
||||
id: 'fixture-imager',
|
||||
label: 'Fixture imager',
|
||||
match: { norad: [GPS] },
|
||||
narrowestSwathKm: 50,
|
||||
swathConfirmed: true,
|
||||
sources: ['https://example.test/spec'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
async function fixture(t) {
|
||||
const source = {
|
||||
async readGroup(group) {
|
||||
const text = GROUP_TEXT[group] || '';
|
||||
return { ok: true, status: 200, text, stale: false };
|
||||
},
|
||||
async readSatcat(group) {
|
||||
return { ok: true, status: 200, text: SATCAT_TEXT[group] || '' };
|
||||
},
|
||||
readUcs: async () => UCS,
|
||||
readSensors: async () => SENSORS,
|
||||
};
|
||||
const noop = () => {};
|
||||
const services = {
|
||||
overlays: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
layerState: { isExplicitLayerStateOrigin: () => false },
|
||||
focus: {
|
||||
clearFocusTarget: noop,
|
||||
publishFocusTargetFromCachedPosition: noop,
|
||||
publishFocusTargetAt: noop,
|
||||
nearFarScalarValueAtDistance: () => 1,
|
||||
advanceSpriteFocus: () => false,
|
||||
focusAlphaNeedsWrite: () => false,
|
||||
getFocusTarget: () => null,
|
||||
focusNowMs: (now) => now,
|
||||
focusPassIsNeeded: () => false,
|
||||
},
|
||||
context: {
|
||||
clearTrackedSubjectContext: noop,
|
||||
getContextStore: () => ({ entities: new Map() }),
|
||||
refreshTrackedSubjectContext: noop,
|
||||
selectTrackedSubjectContext: noop,
|
||||
},
|
||||
readout: { refreshTrackedReadout: noop },
|
||||
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
|
||||
picking: {
|
||||
registerPickOwner: noop,
|
||||
unregisterPickOwner: noop,
|
||||
resolvePickId: () => null,
|
||||
isOwnedByOtherLayer: () => false,
|
||||
},
|
||||
};
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
const state = createState({ services });
|
||||
const parts = {};
|
||||
const context = { state, services, parts, source };
|
||||
for (const [name, factory] of Object.entries({
|
||||
controls: createControls,
|
||||
orbits: createOrbits,
|
||||
labels: createLabels,
|
||||
tracking: createTracking,
|
||||
rendering: createRendering,
|
||||
catalog: createCatalog,
|
||||
interaction: createInteraction,
|
||||
lifecycle: createLifecycle,
|
||||
ingestion: createIngestion,
|
||||
cockpit: createCockpitSubject,
|
||||
})) {
|
||||
parts[name] = factory(context);
|
||||
}
|
||||
const viewer = { canvas: new EventTarget(), scene: {} };
|
||||
const camera = fakeFollowCamera();
|
||||
const frame = fakeFrame();
|
||||
const { draw, unbind } = bindFakeDraw(viewer, { camera, frame });
|
||||
const input = fakeInput(viewer);
|
||||
let frameNumber = 1;
|
||||
const { log, warn } = console;
|
||||
console.log = noop;
|
||||
console.warn = noop;
|
||||
await parts.lifecycle.methods.init(viewer);
|
||||
await parts.ingestion.methods.update(viewer);
|
||||
parts.lifecycle.methods.enable(viewer);
|
||||
// GPS is TELECOM; these tests need its point on screen whatever the default.
|
||||
parts.controls.methods.setParams({ classes: { telecom: true } });
|
||||
Object.assign(console, { log, warn });
|
||||
t.after(() => {
|
||||
console.log = noop;
|
||||
parts.lifecycle.methods.destroy(viewer);
|
||||
console.log = log;
|
||||
input.destroy();
|
||||
unbind();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
const methods = { ...parts.controls.methods, ...parts.cockpit.methods };
|
||||
return {
|
||||
state,
|
||||
parts,
|
||||
viewer,
|
||||
camera,
|
||||
draw,
|
||||
methods,
|
||||
track(id) {
|
||||
const log = console.log;
|
||||
console.log = noop;
|
||||
try {
|
||||
return methods.trackById(id);
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
},
|
||||
nextFrame() {
|
||||
frameNumber += 1;
|
||||
frame.step({ frame: frameNumber, time: Date.now() });
|
||||
},
|
||||
ring: (id) => state._orbitPaths.get(id)?.item,
|
||||
detected: () =>
|
||||
methods.getDetectableObjects().map((object) => object.sourceId),
|
||||
};
|
||||
}
|
||||
|
||||
test('no subject while the layer is off or nothing is tracked', async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal(f.methods.getCockpitSubject(), null);
|
||||
assert.equal(f.methods.getCockpitPosition(), null);
|
||||
assert.equal(f.track(ISS_NORAD), true);
|
||||
f.state._enabled = false;
|
||||
assert.equal(f.methods.getCockpitSubject(), null);
|
||||
assert.equal(f.methods.getCockpitPosition(), null);
|
||||
});
|
||||
|
||||
test('the tracked satellite is a subject read from the per-frame sample', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
const propagate = f.parts.orbits.propagatePosition;
|
||||
let propagations = 0;
|
||||
f.parts.orbits.propagatePosition = (...args) => {
|
||||
propagations += 1;
|
||||
return propagate(...args);
|
||||
};
|
||||
// The frame's tick takes its sample; every reader shares it.
|
||||
f.nextFrame();
|
||||
const subject = f.methods.getCockpitSubject();
|
||||
const position = f.methods.getCockpitPosition();
|
||||
f.methods.getCockpitSubject();
|
||||
assert.equal(propagations, 1, 'one SGP4 sample per frame for every reader');
|
||||
|
||||
assert.equal(subject.kind, 'satellite');
|
||||
assert.equal(subject.layerId, 'satellites');
|
||||
assert.equal(subject.id, String(ISS_NORAD));
|
||||
assert.equal(subject.noradId, ISS_NORAD);
|
||||
assert.equal(subject.name, 'ISS (ZARYA)');
|
||||
assert.equal(subject.classLabel, 'STATIONS · ISS');
|
||||
assert.equal(subject.stale, false);
|
||||
assert.ok(subject.altitudeM > 150e3 && subject.altitudeM < 1000e3);
|
||||
assert.ok(subject.velocityMps > 7000 && subject.velocityMps < 8000);
|
||||
|
||||
// The same point the tracked dot and follow camera use, as a copy.
|
||||
const cached = f.state._trackedFrameCartesian;
|
||||
assert.deepEqual({ ...position }, { x: cached.x, y: cached.y, z: cached.z });
|
||||
assert.notEqual(position, cached);
|
||||
const target = { x: 0, y: 0, z: 0 };
|
||||
assert.equal(f.methods.getCockpitPosition(target), target);
|
||||
assert.ok(Math.abs(toLonLatH(position).lat - subject.latitude) < 1e-6);
|
||||
f.parts.orbits.propagatePosition = propagate;
|
||||
});
|
||||
|
||||
test('the subject says what it is, which TLE it flies, and who owns and runs it', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
const iss = f.methods.getCockpitSubject();
|
||||
assert.equal(iss.satelliteClass, 'stations');
|
||||
assert.equal(iss.cosparId, '1998-067A');
|
||||
assert.match(iss.tle.line1, /^1 25544U/);
|
||||
assert.match(iss.tle.line2, /^2 25544 /);
|
||||
// Day 289.789… of 2026.
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
iss.tle.epochMs - (Date.UTC(2026, 0, 1) + 288.78971908 * 86_400_000),
|
||||
) < 1000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
iss.owner,
|
||||
{ countryCode: null, label: 'Multinational' },
|
||||
'UCS before SATCAT',
|
||||
);
|
||||
assert.equal(iss.operator, 'NASA/Multinational');
|
||||
assert.equal(
|
||||
f.methods.getCockpitSubject().owner,
|
||||
iss.owner,
|
||||
'worked out once',
|
||||
);
|
||||
|
||||
f.track(GPS);
|
||||
const gps = f.methods.getCockpitSubject();
|
||||
assert.equal(gps.satelliteClass, 'telecom');
|
||||
assert.equal(
|
||||
gps.cosparId,
|
||||
'1998-067A',
|
||||
'from TLE line 1 when SATCAT has none',
|
||||
);
|
||||
assert.deepEqual(gps.owner, { countryCode: 'US', label: 'United States' });
|
||||
assert.equal(gps.operator, null);
|
||||
// The sensor pack is matched once, at ingestion.
|
||||
assert.equal(gps.sensor?.id, 'fixture-imager');
|
||||
assert.equal(gps.sensor.narrowestSwathKm, 50);
|
||||
assert.equal(iss.sensor, null, 'no sensor entry, no extra zoom');
|
||||
|
||||
// A bare catalog entry still answers every field.
|
||||
const bare = satelliteCockpitInfo(
|
||||
GPS,
|
||||
{ name: 'X', group: 'gps-ops' },
|
||||
{ latitude: 1, longitude: 2, altitude: 3 },
|
||||
);
|
||||
assert.equal(bare.satelliteClass, 'telecom');
|
||||
// An imaging satellite CelesTrak lists among the brightest objects names
|
||||
// its class, not the 'visual' group it came in.
|
||||
const landsat = satelliteCockpitInfo(
|
||||
49260,
|
||||
{ name: 'LANDSAT 9', group: 'visual', satelliteClass: 'imaging' },
|
||||
{ latitude: 1, longitude: 2, altitude: 3 },
|
||||
);
|
||||
assert.equal(landsat.classLabel, 'IMAGING');
|
||||
assert.equal(bare.tle, null);
|
||||
assert.equal(bare.owner, null);
|
||||
assert.equal(bare.operator, null);
|
||||
assert.equal(bare.cosparId, null);
|
||||
});
|
||||
|
||||
test('a GNSS satellite carries its class and an orbital speed', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
const subject = f.methods.getCockpitSubject();
|
||||
assert.equal(subject.classLabel, 'TELECOM · GPS');
|
||||
assert.ok(subject.altitudeM > 19e6 && subject.altitudeM < 21.5e6);
|
||||
assert.ok(subject.velocityMps > 3500 && subject.velocityMps < 4200);
|
||||
assert.equal(
|
||||
satelliteCockpitInfo(
|
||||
GPS,
|
||||
{ name: 'X', group: 'gps-ops' },
|
||||
{
|
||||
latitude: 1,
|
||||
longitude: 2,
|
||||
altitude: 3,
|
||||
},
|
||||
).velocityMps,
|
||||
null,
|
||||
);
|
||||
assert.equal(satelliteCockpitInfo(GPS, null, { latitude: 0 }), null);
|
||||
});
|
||||
|
||||
test('holding the subject hides its dot, ring, docked companions and bracket', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
assert.ok(f.state._dockedCompanions.has(COMPANION));
|
||||
assert.equal(dotShown(f), true);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
assert.ok(f.detected().includes(ISS_NORAD));
|
||||
|
||||
assert.equal(f.methods.setCockpitSubject(String(ISS_NORAD)), true);
|
||||
assert.equal(dotShown(f), false);
|
||||
assert.equal(f.ring(ISS_NORAD).show, false);
|
||||
assert.equal(f.state._points.get(COMPANION).show, false);
|
||||
assert.equal(f.state._points.get(GPS).show, true);
|
||||
assert.ok(!f.detected().includes(ISS_NORAD));
|
||||
|
||||
// Toggling orbits on again cannot bring the ring back while held.
|
||||
f.methods.setParams({ showOrbits: true });
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
f.nextFrame();
|
||||
assert.equal(f.ring(ISS_NORAD).show, false);
|
||||
|
||||
f.methods.setCockpitSubject(null);
|
||||
assert.equal(dotShown(f), true);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
assert.equal(f.state._points.get(COMPANION).show, true);
|
||||
// The tracked point stays hidden: the tracked dot draws it.
|
||||
assert.equal(f.state._points.get(ISS_NORAD).show, false);
|
||||
assert.ok(f.detected().includes(ISS_NORAD));
|
||||
});
|
||||
|
||||
test('a subject that is not tracked holds nothing', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
f.methods.setCockpitSubject(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
assert.equal(dotShown(f), true);
|
||||
assert.equal(f.ring(GPS).show, true);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
});
|
||||
|
||||
test('untracking a held subject gives its marks back', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
f.methods.setCockpitSubject(ISS_NORAD);
|
||||
assert.equal(f.ring(ISS_NORAD).show, false);
|
||||
f.methods.stopTracking();
|
||||
assert.equal(f.methods.getCockpitSubject(), null);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
assert.equal(f.state._points.get(COMPANION).show, true);
|
||||
assert.equal(f.state._points.get(ISS_NORAD).show, true);
|
||||
});
|
||||
|
||||
test('a catalog refresh while held keeps the subject and its companions hidden', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
f.methods.setCockpitSubject(ISS_NORAD);
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
await f.parts.ingestion.methods.update(f.viewer);
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
f.nextFrame();
|
||||
assert.equal(f.state._points.get(COMPANION).show, false, 'companion');
|
||||
assert.equal(f.state._points.get(ISS_NORAD).show, false, 'tracked point');
|
||||
f.methods.setCockpitSubject(null);
|
||||
assert.equal(f.state._points.get(COMPANION).show, true, 'given back');
|
||||
});
|
||||
|
||||
test('untracking a held ISS leaves its ring hidden while Stations is off', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
f.methods.setCockpitSubject(ISS_NORAD);
|
||||
f.methods.setParams({ classes: 'itpd' });
|
||||
f.nextFrame();
|
||||
f.methods.stopTracking();
|
||||
assert.equal(f.ring(ISS_NORAD).show, false);
|
||||
f.methods.setParams({ classes: 'sitpd' });
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
});
|
||||
|
||||
test('tracking without a Cockpit subject keeps its marks', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
for (let i = 0; i < 3; i++) f.nextFrame();
|
||||
assert.equal(dotShown(f), true);
|
||||
assert.equal(f.ring(GPS).show, true);
|
||||
assert.equal(f.state._points.get(COMPANION).show, true);
|
||||
assert.equal(f.state._cockpitHiddenPoints.size, 0);
|
||||
assert.equal(f.state._cockpitHiddenPath, null);
|
||||
});
|
||||
|
||||
/** A ring's drawn colour and behind-the-globe colour. */
|
||||
function ringColors(f, id) {
|
||||
const item = f.ring(id);
|
||||
return { color: [...item.style.color], depthFail: [...item.depthFailColor] };
|
||||
}
|
||||
|
||||
test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
f.nextFrame();
|
||||
assert.ok(f.ring(ISS_NORAD), 'the ISS ring is drawn beside the tracked one');
|
||||
const issBuilt = ringColors(f, ISS_NORAD);
|
||||
const gpsBuilt = ringColors(f, GPS);
|
||||
|
||||
f.methods.setCockpitSubject(GPS);
|
||||
const iss = ringColors(f, ISS_NORAD);
|
||||
const near = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} vs ${b}`);
|
||||
near(iss.color[3], issBuilt.color[3] * COCKPIT_ORBIT_DIM_FACTOR);
|
||||
near(iss.depthFail[3], issBuilt.depthFail[3] * COCKPIT_ORBIT_DIM_FACTOR);
|
||||
assert.deepEqual(iss.color.slice(0, 3), issBuilt.color.slice(0, 3));
|
||||
// What the draw port holds is what the ring says.
|
||||
const rings = drawnSet(f, ':rings');
|
||||
assert.deepEqual(
|
||||
[...rings.items.get(String(ISS_NORAD)).style.color],
|
||||
iss.color,
|
||||
);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible');
|
||||
assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden');
|
||||
assert.deepEqual(ringColors(f, GPS), gpsBuilt, 'the ridden ring is not dimmed');
|
||||
// Other satellites' points stay as they are.
|
||||
assert.equal(f.state._points.get(COMPANION).show, true);
|
||||
|
||||
// A rebuilt ring arrives at full alpha and is dimmed again on the tick.
|
||||
f.parts.rendering._hideOrbitPath(ISS_NORAD);
|
||||
f.parts.rendering._showOrbitPath(ISS_NORAD, TRACKED_ORBIT_COLOR);
|
||||
const rebuiltAt = ringColors(f, ISS_NORAD);
|
||||
f.nextFrame();
|
||||
near(
|
||||
ringColors(f, ISS_NORAD).color[3],
|
||||
rebuiltAt.color[3] * COCKPIT_ORBIT_DIM_FACTOR,
|
||||
);
|
||||
|
||||
f.methods.setCockpitSubject(null);
|
||||
assert.deepEqual(
|
||||
ringColors(f, ISS_NORAD),
|
||||
rebuiltAt,
|
||||
'released rings get their built colours back exactly',
|
||||
);
|
||||
assert.equal(f.ring(GPS).show, true);
|
||||
assert.deepEqual(ringColors(f, GPS), gpsBuilt);
|
||||
});
|
||||
|
||||
test('a held subject ignores the layer Escape; refocus restores the follow', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(ISS_NORAD);
|
||||
f.nextFrame();
|
||||
f.methods.setCockpitSubject(ISS_NORAD);
|
||||
f.parts.interaction._onKeyDown({ key: 'Escape' });
|
||||
assert.equal(f.state._trackedNorad, ISS_NORAD, 'the Cockpit owns Escape');
|
||||
|
||||
// The Cockpit took the follow camera off the satellite (without telling
|
||||
// the layer); refocus puts it back.
|
||||
const target = f.camera.followed;
|
||||
assert.ok(target, 'tracking follows the satellite');
|
||||
f.camera.followed = null;
|
||||
f.methods.setCockpitSubject(null);
|
||||
assert.equal(f.methods.refocusTrackedById(GPS), false, 'not the tracked one');
|
||||
assert.equal(f.camera.followed, null);
|
||||
assert.equal(f.methods.refocusTrackedById(String(ISS_NORAD)), true);
|
||||
assert.equal(f.camera.followed, target);
|
||||
assert.equal(f.state._trackedNorad, ISS_NORAD);
|
||||
|
||||
f.parts.interaction._onKeyDown({ key: 'Escape' });
|
||||
assert.equal(f.state._trackedNorad, null, 'released, Escape untracks again');
|
||||
assert.equal(f.methods.refocusTrackedById(ISS_NORAD), false);
|
||||
});
|
||||
|
||||
test('the ground track bearing comes from the SGP4 velocity, less the Earth turning', () => {
|
||||
const near = (actual, expected) =>
|
||||
assert.ok(Math.abs(actual - expected) < 0.2, `${actual} vs ${expected}`);
|
||||
// An ISS-like orbit (51.6°, 7.66 km/s) crossing the equator northbound at
|
||||
// 0°E: inertially 38.4° from north, but the ground turns east beneath it,
|
||||
// so the track runs closer to north.
|
||||
const inclination = (51.6 * Math.PI) / 180;
|
||||
const iss = {
|
||||
position: { x: 6771, y: 0, z: 0 },
|
||||
velocity: {
|
||||
x: 0,
|
||||
y: 7.66 * Math.cos(inclination),
|
||||
z: 7.66 * Math.sin(inclination),
|
||||
},
|
||||
};
|
||||
near(groundTrackBearingDeg(iss.position, iss.velocity, 0, 0, 0), 35.4);
|
||||
// The same state given in TEME a quarter sidereal turn on (GMST 90°):
|
||||
// still over 0°E, so the same ground track.
|
||||
near(
|
||||
groundTrackBearingDeg(
|
||||
{ x: 0, y: 6771, z: 0 },
|
||||
{ x: -iss.velocity.y, y: 0, z: iss.velocity.z },
|
||||
Math.PI / 2,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
35.4,
|
||||
);
|
||||
// Geostationary: it turns with the Earth, so there is no ground track.
|
||||
assert.equal(
|
||||
groundTrackBearingDeg(
|
||||
{ x: 42164, y: 0, z: 0 },
|
||||
{ x: 0, y: 3.0747, z: 0 },
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(groundTrackBearingDeg(iss.position, null, 0, 0, 0), null);
|
||||
// The subject passes the sample's track through.
|
||||
const sat = { name: 'X', group: 'stations' };
|
||||
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
|
||||
assert.equal(
|
||||
satelliteCockpitInfo(1, sat, { ...fix, groundTrackDeg: 35.4 })
|
||||
.groundTrackDeg,
|
||||
35.4,
|
||||
);
|
||||
assert.equal(satelliteCockpitInfo(1, sat, fix).groundTrackDeg, null);
|
||||
});
|
||||
|
||||
test('the subject says whether its class may be ridden', () => {
|
||||
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
|
||||
const subject = (satelliteClass) =>
|
||||
satelliteCockpitInfo(
|
||||
1,
|
||||
{ name: 'X', group: 'visual', satelliteClass },
|
||||
fix,
|
||||
);
|
||||
assert.equal(subject('debris').enterable, false);
|
||||
for (const satelliteClass of [
|
||||
'stations',
|
||||
'imaging',
|
||||
'telecom',
|
||||
'starlink',
|
||||
'probes',
|
||||
])
|
||||
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
|
||||
});
|
||||
Vendored
+301
-80
@@ -1,11 +1,14 @@
|
||||
import {
|
||||
tallySatelliteClasses,
|
||||
satelliteClassLabel,
|
||||
satelliteClassLegend,
|
||||
} from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { decodeSatelliteClassMask } from '../../data/satelliteClassMask.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { ISS_NORAD, POINT_STYLES } from './policy.js';
|
||||
import {
|
||||
DEFAULT_SATELLITE_CLASSES,
|
||||
SATELLITE_CLASS_DISPLAY,
|
||||
SATELLITE_CLASS_IDS,
|
||||
mergeClassVisibility,
|
||||
} from './classes.js';
|
||||
import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js';
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
const { isExplicitLayerStateOrigin } = services.layerState;
|
||||
@@ -19,7 +22,83 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
function _pointStyleFor(noradId, group) {
|
||||
if (noradId === ISS_NORAD) return POINT_STYLES.iss;
|
||||
return POINT_STYLES[group] || POINT_STYLES.visual;
|
||||
return classPointStyle(
|
||||
group,
|
||||
layerState._catalog.get(noradId)?.satelliteClass,
|
||||
);
|
||||
}
|
||||
|
||||
/** The class-visibility choice, defaults filled in. */
|
||||
function _classes() {
|
||||
return layerState._params.classes || DEFAULT_SATELLITE_CLASSES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a satellite's class is shown. Starlink follows the catalog mode:
|
||||
* its points exist only in dense mode. An unclassed entry shows.
|
||||
* @param {number} noradId NORAD catalog number.
|
||||
*/
|
||||
function _classVisible(noradId) {
|
||||
const satelliteClass = layerState._catalog.get(noradId)?.satelliteClass;
|
||||
if (!satelliteClass) return true;
|
||||
if (satelliteClass === 'starlink')
|
||||
return layerState._params.catalog === 'dense';
|
||||
return _classes()[satelliteClass] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show or hide every point by its class. The tracked satellite's point
|
||||
* stays hidden (its entity draws the dot), as do points a Cockpit hold hid.
|
||||
* The ISS's ring and label go with its class.
|
||||
*/
|
||||
function _applyClassVisibility() {
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
if (noradId === layerState._trackedNorad) continue;
|
||||
if (layerState._cockpitHiddenPoints?.has(noradId)) continue;
|
||||
parts.rendering._setPointShown(noradId, _classVisible(noradId));
|
||||
}
|
||||
_syncIssOrbit();
|
||||
parts.labels?._syncIssOverlay?.();
|
||||
layerState._detectionObjects.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the ISS's ring shows: orbits on, the layer drawing, and its
|
||||
* class on or the ISS tracked (a tracked satellite keeps its ring).
|
||||
*/
|
||||
function _issOrbitVisible() {
|
||||
return (
|
||||
satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
) &&
|
||||
(_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD)
|
||||
);
|
||||
}
|
||||
|
||||
/** Show or hide the ISS's ring by _issOrbitVisible, if it is built. */
|
||||
function _syncIssOrbit() {
|
||||
parts.rendering._setOrbitPathShown(ISS_NORAD, _issOrbitVisible());
|
||||
}
|
||||
|
||||
/**
|
||||
* The row's info line while the classes rest on old or missing SATCAT
|
||||
* evidence (`_satcatState`), and an empty one otherwise.
|
||||
* @returns {{info: string, infoTitle: string}}
|
||||
*/
|
||||
function classEvidenceNotice() {
|
||||
const evidence = layerState._satcatState;
|
||||
if (evidence !== 'stale' && evidence !== 'unavailable')
|
||||
return { info: '', infoTitle: '' };
|
||||
return {
|
||||
info:
|
||||
evidence === 'stale'
|
||||
? t('Classes may lag: SATCAT is a cached copy')
|
||||
: t('Classes may lag: SATCAT unavailable'),
|
||||
infoTitle: t(
|
||||
"CelesTrak SATCAT gives each object's type and status. Without a current copy the classes rest on the UCS database, names and CelesTrak groups, so a satellite that has died since may still show as working.",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Tell the manager to re-render this layer's row (chip state / legend counts). */
|
||||
@@ -46,14 +125,11 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
) {
|
||||
return layerState._classTallyCache.counts;
|
||||
}
|
||||
const entries = [];
|
||||
// Pass the ISS flag, not just the group: during a stations-feed outage the
|
||||
// ISS is ingested as `visual`, and the legend must file it exactly where its
|
||||
// card does (STATION) rather than letting STATION vanish from the legend.
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
entries.push({ group: sat.group, isIss: noradId === ISS_NORAD });
|
||||
const counts = Object.create(null);
|
||||
for (const sat of layerState._catalog.values()) {
|
||||
const satelliteClass = sat.satelliteClass || 'probes';
|
||||
counts[satelliteClass] = (counts[satelliteClass] || 0) + 1;
|
||||
}
|
||||
const counts = tallySatelliteClasses(entries);
|
||||
layerState._classTallyCache = {
|
||||
revision: layerState._catalogRevision,
|
||||
counts,
|
||||
@@ -88,6 +164,47 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
requestedCatalog !== currentCatalog
|
||||
);
|
||||
}
|
||||
/** The STARLINK chip: the dense catalog, with its load state. */
|
||||
function _starlinkChip() {
|
||||
const loading = layerState._denseStatus === 'loading';
|
||||
const failed = layerState._denseStatus === 'failed';
|
||||
const active =
|
||||
layerState._params.catalog === 'dense' &&
|
||||
layerState._denseStatus === 'ready';
|
||||
let title = t(
|
||||
'Add the full Starlink broadband shell (thousands of extra points)',
|
||||
);
|
||||
if (loading) title = t('Loading the Starlink shell…');
|
||||
else if (failed)
|
||||
title = t('Starlink {detail} — click to retry', {
|
||||
detail: layerState._denseError || t('load failed'),
|
||||
});
|
||||
else if (active)
|
||||
title = t(
|
||||
'Showing the full Starlink shell — click for the core catalog only',
|
||||
);
|
||||
return {
|
||||
id: 'catalog',
|
||||
label: loading
|
||||
? t('STARLINK ···')
|
||||
: failed
|
||||
? t('STARLINK ✕')
|
||||
: t('STARLINK'),
|
||||
active,
|
||||
busy: loading,
|
||||
disabled: loading,
|
||||
state: loading
|
||||
? 'loading'
|
||||
: failed
|
||||
? 'error'
|
||||
: active
|
||||
? 'active'
|
||||
: 'idle',
|
||||
title,
|
||||
params: { catalog: active ? 'core' : 'dense' },
|
||||
};
|
||||
}
|
||||
|
||||
const methods = {
|
||||
id: 'satellites',
|
||||
|
||||
@@ -129,11 +246,16 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
const position = parts.rendering._pointPosition(noradId);
|
||||
if (!position) continue;
|
||||
const isTracked = noradId === layerState._trackedNorad;
|
||||
// A hidden class is not on screen, so nothing is bracketed on it.
|
||||
if (!isTracked && !_classVisible(noradId)) continue;
|
||||
// A docked companion sits at the tracked subject's own position, so its
|
||||
// mark and label would stack underneath the tracked card. It is listed on
|
||||
// that card instead. Only members of the tracked cluster are affected —
|
||||
// unrelated nearby satellites are never suppressed.
|
||||
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
|
||||
// The Cockpit camera rides a held subject; a bracket on it would sit
|
||||
// on the lens.
|
||||
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
|
||||
const cat = layerState._catalog.get(noradId);
|
||||
let object = layerState._detectionObjects.get(noradId);
|
||||
if (!object) {
|
||||
@@ -141,15 +263,16 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
sourceId: noradId,
|
||||
id: cat?.name || `SAT-${noradId}`,
|
||||
type: 'SAT',
|
||||
// Human class ("NAV · GPS"), not the raw CelesTrak tag ("GPS-OPS").
|
||||
// The detection canvas composites ABOVE the post-FX chain, so this
|
||||
// is how class survives NVG/FLIR once the dot colors are collapsed.
|
||||
klass: satelliteClassLabel(cat?.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
}),
|
||||
};
|
||||
layerState._detectionObjects.set(noradId, object);
|
||||
}
|
||||
// Human class ("TELECOM · GPS"), not the raw CelesTrak tag
|
||||
// ("GPS-OPS"). The detection canvas composites ABOVE the post-FX
|
||||
// chain, so this is how class survives NVG/FLIR once the dot colors
|
||||
// are collapsed. Read each time: SATCAT can reclassify a satellite.
|
||||
object.klass = satelliteClassText(cat?.satelliteClass, cat?.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
});
|
||||
object.position = position;
|
||||
object.skipLabel = isTracked;
|
||||
result.push(object);
|
||||
@@ -222,6 +345,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
if (result.length >= cap) break;
|
||||
const position = parts.rendering._pointPosition(noradId);
|
||||
if (!position) continue;
|
||||
if (!_classVisible(noradId)) continue;
|
||||
// Dense extras are points-only — keep voice/framing lists to the core catalog.
|
||||
if (
|
||||
layerState._denseIds.length > 0 &&
|
||||
@@ -243,6 +367,72 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
* The shown satellites nearest a position, nearest first, from per-point
|
||||
* state (no SGP4 re-propagation): a bounded pass that keeps only the
|
||||
* nearest `maxCount`, and reads latitude and longitude for those alone.
|
||||
* Dense extras are left out, as in `getAllPositions`.
|
||||
* @param {{x: number, y: number, z: number}} center Earth-fixed position.
|
||||
* @param {number} [maxCount=8] Most entries to return.
|
||||
* @param {{excludeIds?: Array<number|string>,
|
||||
* excludeClasses?: Array<string>}} [options] Satellites, and classes
|
||||
* (e.g. 'debris'), to leave out.
|
||||
* @returns {Array<{ id: number, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, satelliteClass: string|null, distanceM: number }>}
|
||||
*/
|
||||
getNearestPositions(
|
||||
center,
|
||||
maxCount = 8,
|
||||
{ excludeIds = [], excludeClasses = [] } = {},
|
||||
) {
|
||||
const nearest = [];
|
||||
const cap = Number.isFinite(maxCount) ? Math.floor(maxCount) : 8;
|
||||
if (
|
||||
cap < 1 ||
|
||||
!center ||
|
||||
!layerState._points ||
|
||||
layerState._points.size === 0
|
||||
)
|
||||
return nearest;
|
||||
const excluded = new Set(excludeIds.map(String));
|
||||
const classes = new Set(excludeClasses);
|
||||
const dense = layerState._denseIds.length > 0;
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
const p = parts.rendering._pointPosition(noradId);
|
||||
if (!p || excluded.has(String(noradId))) continue;
|
||||
if (!_classVisible(noradId)) continue;
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
if (dense && sat?.group === 'dense') continue;
|
||||
if (classes.size && classes.has(sat?.satelliteClass)) continue;
|
||||
const dx = p.x - center.x;
|
||||
const dy = p.y - center.y;
|
||||
const dz = p.z - center.z;
|
||||
const distanceSq = dx * dx + dy * dy + dz * dz;
|
||||
if (nearest.length === cap && distanceSq >= nearest[cap - 1].distanceSq)
|
||||
continue;
|
||||
// Insertion into a short sorted list: no copy or sort of the rest.
|
||||
let at = nearest.length;
|
||||
while (at > 0 && nearest[at - 1].distanceSq > distanceSq) at -= 1;
|
||||
nearest.splice(at, 0, { noradId, p, sat, distanceSq });
|
||||
if (nearest.length > cap) nearest.pop();
|
||||
}
|
||||
const result = [];
|
||||
for (const { noradId, p, sat, distanceSq } of nearest) {
|
||||
const geo = toLonLatH(p);
|
||||
if (!geo) continue;
|
||||
result.push({
|
||||
id: noradId,
|
||||
label: sat ? sat.name.trim() : String(noradId),
|
||||
position: { x: p.x, y: p.y, z: p.z },
|
||||
latitude: geo.lat,
|
||||
longitude: geo.lon,
|
||||
altitudeM: geo.height,
|
||||
satelliteClass: sat?.satelliteClass ?? null,
|
||||
distanceM: Math.sqrt(distanceSq),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
* Track a satellite by NORAD id (camera follow + orbit path + highlight),
|
||||
* same path as clicking its point.
|
||||
@@ -380,9 +570,11 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Runtime params (DataLayerManager.setLayerParams path).
|
||||
* catalog: 'core' (default, ~840 sats) | 'dense' (adds the Starlink shell
|
||||
* as points-only extras on a relaxed propagation budget).
|
||||
* @param {{ catalog?: 'core'|'dense', showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
|
||||
* catalog: 'core' (default, about 1,300 satellites from the CelesTrak
|
||||
* groups) | 'dense' (adds the Starlink shell as points-only extras on a
|
||||
* relaxed propagation budget). classes: which of the six classes show
|
||||
* (src/layers/satellites/classes.js); Starlink's toggle is the dense catalog.
|
||||
* @param {{ catalog?: 'core'|'dense', classes?: Record<string, boolean>, showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
|
||||
*/
|
||||
setParams(params = {}, { origin = 'programmatic' } = {}) {
|
||||
if (
|
||||
@@ -391,9 +583,28 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
}
|
||||
const catalog = params.catalog;
|
||||
let catalog = params.catalog;
|
||||
if (catalog !== undefined && catalog !== 'core' && catalog !== 'dense')
|
||||
return false;
|
||||
// A saved or shared choice arrives as class letters (layerState.js).
|
||||
const requestedClasses =
|
||||
typeof params.classes === 'string'
|
||||
? decodeSatelliteClassMask(params.classes)
|
||||
: params.classes;
|
||||
if (params.classes !== undefined) {
|
||||
if (!requestedClasses || typeof requestedClasses !== 'object')
|
||||
return false;
|
||||
// Starlink's toggle is the dense catalog: its points load on demand.
|
||||
if (
|
||||
typeof requestedClasses.starlink === 'boolean' &&
|
||||
catalog === undefined
|
||||
)
|
||||
catalog = requestedClasses.starlink ? 'dense' : 'core';
|
||||
layerState._params.classes = mergeClassVisibility(
|
||||
requestedClasses,
|
||||
_classes(),
|
||||
);
|
||||
}
|
||||
const catalogChanged = satelliteCatalogModeChanged(
|
||||
layerState._params.catalog,
|
||||
catalog,
|
||||
@@ -412,12 +623,16 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
if (params.showOrbits !== undefined) {
|
||||
layerState._params.showOrbits = params.showOrbits !== false;
|
||||
parts.rendering._setOrbitPathsShown(
|
||||
satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
),
|
||||
);
|
||||
for (const noradId of layerState._orbitPaths.keys())
|
||||
parts.rendering._setOrbitPathShown(
|
||||
noradId,
|
||||
noradId === ISS_NORAD
|
||||
? _issOrbitVisible()
|
||||
: satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
),
|
||||
);
|
||||
parts.labels._syncIssOverlay();
|
||||
}
|
||||
if (catalogChanged && catalog === 'dense') {
|
||||
@@ -433,6 +648,13 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
if (catalogChanged)
|
||||
console.log(`[Data:Satellites] Catalog mode: ${catalog}`);
|
||||
if (params.classes !== undefined || catalogChanged) {
|
||||
layerState._params.classes = {
|
||||
..._classes(),
|
||||
starlink: layerState._params.catalog === 'dense',
|
||||
};
|
||||
_applyClassVisibility();
|
||||
}
|
||||
if (Object.hasOwn(params, 'selectedSatTrackingId')) {
|
||||
const requested = parts.tracking._normalizeTrackedNorad(
|
||||
params.selectedSatTrackingId,
|
||||
@@ -464,25 +686,29 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
catalog: layerState._params.catalog,
|
||||
showPoints: layerState._params.showPoints,
|
||||
showOrbits: layerState._params.showOrbits,
|
||||
classes: { ..._classes() },
|
||||
selectedSatTrackingId: layerState._trackedNorad,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Layer-row sub-controls (DataLayerManager row-controls contract): the DENSE
|
||||
* catalog chip plus a class legend so the point colors are learnable without
|
||||
* a new panel.
|
||||
* Layer-row sub-controls (DataLayerManager row-controls contract): one
|
||||
* toggle chip per satellite class (src/layers/satellites/classes.js), and a legend
|
||||
* of the classes on screen so the point colours are learnable.
|
||||
*
|
||||
* The chip is stateless — it declares the params to apply and the manager
|
||||
* Chips are stateless — each declares the params to apply and the manager
|
||||
* owns the write, so the Space Missions snapshot/restore path (which drives
|
||||
* the same `catalog` param) stays the single source of truth and the chip
|
||||
* the same `catalog` param) stays the single source of truth and a chip
|
||||
* always renders whatever the layer actually has.
|
||||
*
|
||||
* The chip reports the dense LOAD state, not the catalog param: the param
|
||||
* flips synchronously while the Starlink shell takes seconds to arrive and
|
||||
* frequently 502s, so ACTIVE means "dense points are on screen" and nothing
|
||||
* less. The legend tally is cached against the catalog revision.
|
||||
* @returns {{ chips: Array<object>, legend: Array<object> }} Row controls.
|
||||
* STARLINK is the dense catalog (chip id `catalog`) and reports the dense
|
||||
* LOAD state, not the param: the param flips synchronously while the shell
|
||||
* takes seconds to arrive and frequently 502s, so ACTIVE means "Starlink
|
||||
* points are on screen" and nothing less. The legend tally is cached
|
||||
* against the catalog revision. While SATCAT is stale or unavailable the
|
||||
* info line says the classes may lag (see `classEvidenceNotice`).
|
||||
* @returns {{ chips: Array<object>, legend: Array<object>, info: string,
|
||||
* infoTitle: string }} Row controls.
|
||||
*/
|
||||
getRowControls() {
|
||||
// A dependency owner (Space Missions) borrows this layer for TLE lookup
|
||||
@@ -491,48 +717,36 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
// restore. Surrender the row rather than lie about it.
|
||||
if (!layerState._params.showPoints) return { chips: [], legend: [] };
|
||||
|
||||
const loading = layerState._denseStatus === 'loading';
|
||||
const failed = layerState._denseStatus === 'failed';
|
||||
const active =
|
||||
layerState._params.catalog === 'dense' &&
|
||||
layerState._denseStatus === 'ready';
|
||||
let title = t(
|
||||
'Add the full Starlink broadband shell (thousands of extra points)',
|
||||
const classes = _classes();
|
||||
const chips = SATELLITE_CLASS_IDS.map((id) =>
|
||||
id === 'starlink'
|
||||
? _starlinkChip()
|
||||
: {
|
||||
id: `class-${id}`,
|
||||
label: t(SATELLITE_CLASS_DISPLAY[id].label),
|
||||
active: classes[id] === true,
|
||||
state: classes[id] === true ? 'active' : 'idle',
|
||||
title: t(SATELLITE_CLASS_DISPLAY[id].blurb),
|
||||
params: { classes: { [id]: classes[id] !== true } },
|
||||
},
|
||||
);
|
||||
if (loading) title = t('Loading the Starlink shell…');
|
||||
else if (failed)
|
||||
title = t('Starlink {detail} — click to retry', {
|
||||
detail: layerState._denseError || t('load failed'),
|
||||
const counts = _classTally();
|
||||
const legend = [];
|
||||
for (const id of SATELLITE_CLASS_IDS) {
|
||||
const shown =
|
||||
id === 'starlink'
|
||||
? layerState._params.catalog === 'dense'
|
||||
: classes[id] === true;
|
||||
if (!shown || !(counts[id] > 0)) continue;
|
||||
legend.push({
|
||||
klass: id,
|
||||
label: t(SATELLITE_CLASS_DISPLAY[id].label),
|
||||
color: SATELLITE_CLASS_DISPLAY[id].color,
|
||||
blurb: t(SATELLITE_CLASS_DISPLAY[id].blurb),
|
||||
count: counts[id],
|
||||
});
|
||||
else if (active)
|
||||
title = t(
|
||||
'Showing the full Starlink shell — click for the core catalog only',
|
||||
);
|
||||
return {
|
||||
chips: [
|
||||
{
|
||||
id: 'catalog',
|
||||
label: loading
|
||||
? t('DENSE ···')
|
||||
: failed
|
||||
? t('DENSE ✕')
|
||||
: t('DENSE'),
|
||||
active,
|
||||
busy: loading,
|
||||
disabled: loading,
|
||||
state: loading
|
||||
? 'loading'
|
||||
: failed
|
||||
? 'error'
|
||||
: active
|
||||
? 'active'
|
||||
: 'idle',
|
||||
title,
|
||||
params: { catalog: active ? 'core' : 'dense' },
|
||||
},
|
||||
],
|
||||
legend: satelliteClassLegend(_classTally()),
|
||||
};
|
||||
}
|
||||
return { chips, legend, ...classEvidenceNotice() };
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -561,6 +775,9 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
? 'stale'
|
||||
: 'nominal',
|
||||
error: layerState._lastError,
|
||||
// SATCAT refines the classes; when it is stale or unavailable the
|
||||
// classes rest on UCS, names and groups alone.
|
||||
classEvidence: layerState._satcatState,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -569,6 +786,10 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
_pointStyleFor,
|
||||
_notifyRowControls,
|
||||
_classTally,
|
||||
_classVisible,
|
||||
_applyClassVisibility,
|
||||
_issOrbitVisible,
|
||||
_syncIssOrbit,
|
||||
satelliteVisualsVisible,
|
||||
satelliteCatalogModeChanged,
|
||||
methods,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createControls } from './controls.js';
|
||||
import { createCatalog } from './catalog.js';
|
||||
import { createCockpitSubject } from './cockpitSubject.js';
|
||||
import { createLabels } from './labels.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
@@ -29,9 +30,11 @@ export function createSatellitesLayer({ services, source }) {
|
||||
parts.interaction = createInteraction(context);
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.cockpit = createCockpitSubject(context);
|
||||
return Object.assign(
|
||||
{},
|
||||
parts.controls.methods,
|
||||
parts.cockpit.methods,
|
||||
parts.lifecycle.methods,
|
||||
parts.ingestion.methods,
|
||||
{
|
||||
|
||||
@@ -3,6 +3,22 @@ import { msg } from '../../i18n/index.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
|
||||
import { CATALOG_GROUPS, ISS_NORAD, POINT_STYLES } from './policy.js';
|
||||
import { classifySatellite, parseSatcatCsv } from './classes.js';
|
||||
import { matchImagingSensor } from './sensors.js';
|
||||
|
||||
/**
|
||||
* How long a catalog rebuild waits for SATCAT before it classifies without
|
||||
* it, ms. SATCAT can hang for the proxy's whole upstream timeout (20 s); the
|
||||
* late answer reclassifies in place.
|
||||
*/
|
||||
export const SATCAT_WAIT_MS = 3000;
|
||||
|
||||
/**
|
||||
* How long a complete, current SATCAT read is kept before the layer asks
|
||||
* again, ms. SATCAT changes daily and the proxy caches it a day, so the
|
||||
* five-minute TLE update does not read all eleven groups each time.
|
||||
*/
|
||||
export const SATCAT_KEEP_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
export function createIngestion({
|
||||
state: layerState,
|
||||
@@ -10,6 +26,158 @@ export function createIngestion({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
/**
|
||||
* The local packs the classes and zoom steps are read from: the UCS pack
|
||||
* and the imaging-sensor pack. Neither is needed to render: a failed read
|
||||
* leaves the last pack (or none) and classification falls back to names
|
||||
* and groups.
|
||||
*/
|
||||
async function _readLocalEvidence() {
|
||||
const ucs = layerState._ucs
|
||||
? Promise.resolve(layerState._ucs)
|
||||
: Promise.resolve()
|
||||
.then(() => source.readUcs?.())
|
||||
.then((pack) => (pack instanceof Map ? pack : null))
|
||||
.catch((error) => {
|
||||
console.warn('[Data:Satellites] UCS pack unavailable:', error);
|
||||
return null;
|
||||
});
|
||||
// The sensor pack only adds zoom steps in the orbital view; without it
|
||||
// every satellite keeps the base steps.
|
||||
const sensors = layerState._sensors
|
||||
? Promise.resolve(layerState._sensors)
|
||||
: Promise.resolve()
|
||||
.then(() => source.readSensors?.())
|
||||
.then((index) => (index?.byNorad instanceof Map ? index : null))
|
||||
.catch((error) => {
|
||||
console.warn(
|
||||
'[Data:Satellites] Imaging sensor pack unavailable:',
|
||||
error,
|
||||
);
|
||||
return null;
|
||||
});
|
||||
const [pack, sensorIndex] = await Promise.all([ucs, sensors]);
|
||||
if (pack) layerState._ucs = pack;
|
||||
if (sensorIndex) layerState._sensors = sensorIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* CelesTrak SATCAT for every core group: type and status, which refine the
|
||||
* classes. A group whose read failed gives null.
|
||||
* @returns {Promise<Array<{records: Map, stale: boolean}|null>>}
|
||||
*/
|
||||
function _readSatcat(signal) {
|
||||
if (typeof source.readSatcat !== 'function') return Promise.resolve([]);
|
||||
// A complete, current read is kept; a stale or failed one is asked again.
|
||||
if (
|
||||
layerState._satcatState === 'current' &&
|
||||
Date.now() - layerState._satcatReadAtMs < SATCAT_KEEP_MS
|
||||
)
|
||||
return Promise.resolve([]);
|
||||
return Promise.all(
|
||||
CATALOG_GROUPS.map((groupDef) =>
|
||||
source
|
||||
.readSatcat(groupDef.path, { signal })
|
||||
.then((res) =>
|
||||
res?.ok
|
||||
? { records: parseSatcatCsv(res.text), stale: Boolean(res.stale) }
|
||||
: null,
|
||||
)
|
||||
.catch((error) => {
|
||||
if (signal.aborted || error?.name === 'AbortError') throw error;
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge SATCAT reads and say how current they are: 'current', 'stale' (a
|
||||
* group came from the proxy's last copy) or 'unavailable' (a group failed;
|
||||
* its earlier records, if any, stay).
|
||||
*/
|
||||
function _mergeSatcat(groups) {
|
||||
let satcatState = 'current';
|
||||
for (const group of groups) {
|
||||
if (!group) {
|
||||
satcatState = 'unavailable';
|
||||
continue;
|
||||
}
|
||||
if (group.stale && satcatState === 'current') satcatState = 'stale';
|
||||
for (const [noradId, record] of group.records) {
|
||||
// A group served from the proxy's last copy never overrules a
|
||||
// current read of the same object, from this merge or an earlier one.
|
||||
const held = layerState._satcat.get(noradId);
|
||||
if (group.stale && held && !held.stale) continue;
|
||||
layerState._satcat.set(
|
||||
noradId,
|
||||
group.stale ? { ...record, stale: true } : record,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!groups.length) return;
|
||||
const changed = layerState._satcatState !== satcatState;
|
||||
layerState._satcatState = satcatState;
|
||||
layerState._satcatReadAtMs = Date.now();
|
||||
if (satcatState !== 'current')
|
||||
console.warn(`[Data:Satellites] SATCAT ${satcatState}: classes may lag`);
|
||||
// The row's info line says so (getRowControls).
|
||||
if (changed) parts.controls._notifyRowControls();
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the catalog again once SATCAT lands after it was built: only
|
||||
* entries whose SATCAT record changed are read again; a changed class
|
||||
* restyles its point and refreshes visibility, the legend and the overlay.
|
||||
*/
|
||||
function _reclassifyFromSatcat() {
|
||||
let changed = false;
|
||||
for (const [noradId, sat] of layerState._catalog) {
|
||||
if (sat.group === 'dense') continue;
|
||||
const satcat = layerState._satcat.get(noradId) || null;
|
||||
if (satcat === sat.satcat) continue;
|
||||
sat.satcat = satcat;
|
||||
// The Cockpit identity (owner, COSPAR id) reads SATCAT too.
|
||||
sat.cockpitIdentity = undefined;
|
||||
const next = classifySatellite({
|
||||
noradId,
|
||||
name: sat.name,
|
||||
group: sat.group,
|
||||
groups: sat.groups,
|
||||
ucs: sat.ucs,
|
||||
satcat,
|
||||
launchYear: sat.launchYear,
|
||||
});
|
||||
if (next === sat.satelliteClass) continue;
|
||||
sat.satelliteClass = next;
|
||||
changed = true;
|
||||
if (layerState._points.has(noradId))
|
||||
parts.rendering._setPointStyle(
|
||||
noradId,
|
||||
parts.controls._pointStyleFor(noradId, sat.group),
|
||||
);
|
||||
}
|
||||
if (!changed) return;
|
||||
parts.controls._applyClassVisibility();
|
||||
layerState._catalogRevision++;
|
||||
parts.controls._notifyRowControls();
|
||||
}
|
||||
|
||||
/** Resolve null after `ms`, or at once when `signal` aborts. */
|
||||
function _waitOrAbort(ms, signal) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms, null);
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
resolve(null);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
const trackingRefreshEpoch = ++layerState._trackingRefreshEpoch;
|
||||
@@ -27,6 +195,10 @@ export function createIngestion({
|
||||
updateSignal.throwIfAborted();
|
||||
// Load all core groups in parallel; a failed/empty group degrades
|
||||
// gracefully (parseTLE of an upstream error body yields []).
|
||||
const localEvidence = _readLocalEvidence();
|
||||
const satcat = _readSatcat(updateSignal);
|
||||
// An abort can reject this before the groups settle and it is awaited.
|
||||
satcat.catch(() => {});
|
||||
const results = await Promise.all(
|
||||
CATALOG_GROUPS.map(async (groupDef) => {
|
||||
try {
|
||||
@@ -49,7 +221,23 @@ export function createIngestion({
|
||||
}
|
||||
}),
|
||||
);
|
||||
await localEvidence;
|
||||
// SATCAT only refines classes: wait a moment for it, then classify
|
||||
// with what is held and let a late answer reclassify in place.
|
||||
const satcatInTime = await Promise.race([
|
||||
satcat.then((groups) => ({ groups })),
|
||||
_waitOrAbort(SATCAT_WAIT_MS, updateSignal),
|
||||
]).catch(() => null);
|
||||
updateSignal.throwIfAborted();
|
||||
if (satcatInTime) _mergeSatcat(satcatInTime.groups);
|
||||
else
|
||||
satcat
|
||||
.then((groups) => {
|
||||
if (updateSignal.aborted || !layerState._enabled) return;
|
||||
_mergeSatcat(groups);
|
||||
_reclassifyFromSatcat();
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
const failed = results.filter((r) => !r.ok).map((r) => r.path);
|
||||
if (failed.length > 0) {
|
||||
@@ -62,7 +250,7 @@ export function createIngestion({
|
||||
);
|
||||
|
||||
// CelesTrak outage guard (H3): if EVERY group failed, bail BEFORE clearing.
|
||||
// Wiping the collection + catalog here would blank all 838 satellites while
|
||||
// Wiping the collection + catalog here would blank every satellite while
|
||||
// the chip still read "just now". Keep the existing (stale) catalog on
|
||||
// screen and surface the outage instead — do NOT stamp _lastUpdate.
|
||||
if (results.every((r) => !r.ok)) {
|
||||
@@ -109,6 +297,18 @@ export function createIngestion({
|
||||
allEntries.push({ ...e, group: r.tag, stale: r.stale });
|
||||
}
|
||||
|
||||
// Every group each TLE came in, keyed by its catalog-number column:
|
||||
// the shown tag is the first, but classification reads them all.
|
||||
const groupsByNumber = new Map();
|
||||
for (const entry of allEntries) {
|
||||
const number = String(entry.line1 || '')
|
||||
.slice(2, 7)
|
||||
.trim();
|
||||
const groups = groupsByNumber.get(number);
|
||||
if (!groups) groupsByNumber.set(number, [entry.group]);
|
||||
else if (!groups.includes(entry.group)) groups.push(entry.group);
|
||||
}
|
||||
|
||||
// Deduplicate by NORAD ID — first (most specific) group tag wins
|
||||
const seen = new Set();
|
||||
let coreStale = false;
|
||||
@@ -122,12 +322,38 @@ export function createIngestion({
|
||||
seen.add(noradId);
|
||||
|
||||
// Store in catalog
|
||||
const launchYear = tleLineLaunchYear(entry.line1);
|
||||
const ucs = layerState._ucs?.get(noradId) || null;
|
||||
const satcat = layerState._satcat.get(noradId) || null;
|
||||
const groups = groupsByNumber.get(
|
||||
String(entry.line1 || '')
|
||||
.slice(2, 7)
|
||||
.trim(),
|
||||
) || [entry.group];
|
||||
layerState._catalog.set(noradId, {
|
||||
name: entry.name,
|
||||
satrec,
|
||||
group: entry.group,
|
||||
groups,
|
||||
// satellite.js does not keep the designator the year match reads.
|
||||
launchYear: tleLineLaunchYear(entry.line1),
|
||||
launchYear,
|
||||
line1: entry.line1,
|
||||
line2: entry.line2,
|
||||
satelliteClass: classifySatellite({
|
||||
noradId,
|
||||
name: entry.name,
|
||||
group: entry.group,
|
||||
groups,
|
||||
ucs,
|
||||
satcat,
|
||||
launchYear,
|
||||
}),
|
||||
ucs,
|
||||
satcat,
|
||||
sensor: matchImagingSensor(layerState._sensors, {
|
||||
noradId,
|
||||
name: entry.name,
|
||||
}),
|
||||
});
|
||||
|
||||
coreStale ||= entry.stale;
|
||||
@@ -137,20 +363,19 @@ export function createIngestion({
|
||||
if (!pos) continue;
|
||||
|
||||
// Add its dot (styling from the shared table, WS-D3)
|
||||
// Hidden classes keep their dot, so a toggle needs no rebuild.
|
||||
parts.rendering._addPoint(
|
||||
noradId,
|
||||
fromDegrees(pos.longitude, pos.latitude, pos.altitude),
|
||||
parts.controls._pointStyleFor(noradId, entry.group),
|
||||
parts.controls._classVisible(noradId),
|
||||
);
|
||||
}
|
||||
|
||||
// Show ISS orbital path by default
|
||||
if (layerState._catalog.has(ISS_NORAD)) {
|
||||
parts.rendering._showOrbitPath(ISS_NORAD, POINT_STYLES.iss.color);
|
||||
parts.rendering._setOrbitPathShown(
|
||||
ISS_NORAD,
|
||||
layerState._params.showOrbits,
|
||||
);
|
||||
parts.controls._syncIssOrbit();
|
||||
|
||||
parts.labels._syncIssOverlay();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseTleText, tleLineLaunchYear } from '../../sources/tle.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import {
|
||||
SATCAT_KEEP_MS,
|
||||
SATCAT_WAIT_MS,
|
||||
createIngestion,
|
||||
} from './ingestion.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
// The ISS set (1 January 2024) with its catalog field swapped per satellite.
|
||||
const ISS_LINE1 =
|
||||
@@ -23,7 +28,7 @@ const orbitParts = {
|
||||
rendering: { _rendererPositions: (positions) => positions },
|
||||
};
|
||||
|
||||
function ingestionFor(catalogText) {
|
||||
function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
|
||||
const state = {
|
||||
_trackingRefreshEpoch: 0,
|
||||
_activeUpdateControllers: new Set(),
|
||||
@@ -34,6 +39,8 @@ function ingestionFor(catalogText) {
|
||||
_denseLoadToken: 0,
|
||||
_catalogRevision: 0,
|
||||
_params: { catalog: 'core', showOrbits: false },
|
||||
_satcat: new Map(),
|
||||
_ucs: null,
|
||||
now: Date.now,
|
||||
coverageChanged() {},
|
||||
};
|
||||
@@ -43,7 +50,17 @@ function ingestionFor(catalogText) {
|
||||
propagatePosition: () => ({ longitude: 0, latitude: 0, altitude: 4e5 }),
|
||||
},
|
||||
labels: { _syncIssOverlay() {} },
|
||||
controls: { _pointStyleFor: () => ({}) },
|
||||
controls: {
|
||||
_pointStyleFor: () => ({}),
|
||||
_classVisible: () => true,
|
||||
_syncIssOrbit() {},
|
||||
_applyClassVisibility() {
|
||||
state.visibilityApplied = (state.visibilityApplied || 0) + 1;
|
||||
},
|
||||
_notifyRowControls() {
|
||||
state.rowNotified = (state.rowNotified || 0) + 1;
|
||||
},
|
||||
},
|
||||
rendering: {
|
||||
_clearPoints() {
|
||||
state._points.clear();
|
||||
@@ -51,9 +68,10 @@ function ingestionFor(catalogText) {
|
||||
_clearOrbitPaths() {
|
||||
state._orbitPaths.clear();
|
||||
},
|
||||
_addPoint(noradId, position) {
|
||||
state._points.set(noradId, { position });
|
||||
_addPoint(noradId, position, style, show = true) {
|
||||
state._points.set(noradId, { position, show });
|
||||
},
|
||||
_setPointStyle() {},
|
||||
_showOrbitPath() {},
|
||||
_setOrbitPathShown() {},
|
||||
},
|
||||
@@ -64,9 +82,12 @@ function ingestionFor(catalogText) {
|
||||
catalog: {},
|
||||
};
|
||||
const source = {
|
||||
async readGroup() {
|
||||
return { ok: true, text: catalogText };
|
||||
async readGroup(path) {
|
||||
const text =
|
||||
typeof catalogText === 'function' ? catalogText(path) : catalogText;
|
||||
return { ok: true, text };
|
||||
},
|
||||
...sourceExtras,
|
||||
};
|
||||
const { methods } = createIngestion({ state, services: {}, parts, source });
|
||||
return { state, update: () => methods.update({}) };
|
||||
@@ -134,3 +155,175 @@ test('a satellite with a blank designator keeps matching by name', async (t) =>
|
||||
69728,
|
||||
);
|
||||
});
|
||||
|
||||
test('a hanging SATCAT read neither holds the catalog nor is lost when it lands', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let answer;
|
||||
const satcatAnswer = new Promise((resolve) => {
|
||||
answer = resolve;
|
||||
});
|
||||
const { state, update } = ingestionFor(
|
||||
(path) => (path === 'stations' ? tleSet('OLD STAGE', '40115') : ''),
|
||||
{ source: { readSatcat: () => satcatAnswer } },
|
||||
);
|
||||
state._enabled = true;
|
||||
const settle = async () => {
|
||||
for (let turn = 0; turn < 20; turn += 1)
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
};
|
||||
const rebuilt = update();
|
||||
await settle();
|
||||
t.mock.timers.tick(SATCAT_WAIT_MS);
|
||||
await rebuilt;
|
||||
// Built without SATCAT: neither name nor group says what it is (the
|
||||
// stations group alone makes no station).
|
||||
assert.equal(state._catalog.get(40115).satelliteClass, 'probes');
|
||||
const revision = state._catalogRevision;
|
||||
// SATCAT lands late: a rocket body.
|
||||
answer({
|
||||
ok: true,
|
||||
stale: true,
|
||||
text: 'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\nOLD STAGE,2014-048B,40115,R/B,,US',
|
||||
});
|
||||
await settle();
|
||||
assert.equal(state._catalog.get(40115).satelliteClass, 'debris');
|
||||
assert.equal(state._catalogRevision, revision + 1, 'the legend refreshes');
|
||||
assert.ok(state.visibilityApplied >= 1 && state.rowNotified >= 1);
|
||||
assert.equal(state._satcatState, 'stale', 'its staleness is kept');
|
||||
});
|
||||
|
||||
test('a satellite in visual and resource is imaging, whichever group shows it', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
// A name no pattern knows, no UCS record and no SATCAT: only its groups.
|
||||
const { state, update } = ingestionFor((path) =>
|
||||
path === 'visual' || path === 'resource'
|
||||
? tleSet('ZZ TESTSAT', '50001')
|
||||
: '',
|
||||
);
|
||||
await update();
|
||||
const sat = state._catalog.get(50001);
|
||||
assert.equal(sat.group, 'visual', 'shown under the first group');
|
||||
assert.deepEqual(sat.groups, ['visual', 'resource']);
|
||||
assert.equal(sat.satelliteClass, 'imaging');
|
||||
});
|
||||
|
||||
test('a stale SATCAT copy never overrules a current read of the same object', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const header =
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\n';
|
||||
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50002'), {
|
||||
source: {
|
||||
// visual is current and says it died; resource, a cached copy, still
|
||||
// says it works.
|
||||
readSatcat: async (path) =>
|
||||
path === 'visual'
|
||||
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,-,US` }
|
||||
: path === 'resource'
|
||||
? {
|
||||
ok: true,
|
||||
stale: true,
|
||||
text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,+,US`,
|
||||
}
|
||||
: { ok: true, text: header },
|
||||
},
|
||||
});
|
||||
await update();
|
||||
assert.equal(state._catalog.get(50002).satelliteClass, 'debris');
|
||||
});
|
||||
|
||||
test('a failed SATCAT read is told on the layer row, not only the console', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
|
||||
source: { readSatcat: async () => ({ ok: false, text: '' }) },
|
||||
});
|
||||
await update();
|
||||
assert.equal(state._satcatState, 'unavailable');
|
||||
assert.ok(state.rowNotified >= 1, 'the row repaints');
|
||||
const controls = createControls({
|
||||
state: {
|
||||
...state,
|
||||
_params: { ...state._params, showPoints: true },
|
||||
_classTallyCache: {},
|
||||
},
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
const row = controls.methods.getRowControls();
|
||||
assert.equal(row.info, 'Classes may lag: SATCAT unavailable');
|
||||
assert.match(row.infoTitle, /SATCAT/);
|
||||
const current = createControls({
|
||||
state: {
|
||||
...state,
|
||||
_satcatState: 'current',
|
||||
_params: { ...state._params, showPoints: true },
|
||||
_classTallyCache: {},
|
||||
},
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
assert.equal(current.methods.getRowControls().info, '');
|
||||
});
|
||||
|
||||
test('a current SATCAT read is kept between updates; a failed one is asked again', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const header =
|
||||
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE\n';
|
||||
let reads = 0;
|
||||
let ok = true;
|
||||
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50003'), {
|
||||
source: {
|
||||
readSatcat: async () => {
|
||||
reads++;
|
||||
return ok
|
||||
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50003,PAY,-` }
|
||||
: { ok: false, text: '' };
|
||||
},
|
||||
},
|
||||
});
|
||||
await update();
|
||||
const perUpdate = reads;
|
||||
assert.ok(perUpdate > 0);
|
||||
await update();
|
||||
assert.equal(reads, perUpdate, 'a fresh read is not asked again');
|
||||
assert.equal(
|
||||
state._catalog.get(50003).satelliteClass,
|
||||
'debris',
|
||||
'the held records still class the rebuilt catalog',
|
||||
);
|
||||
|
||||
state._satcatReadAtMs -= SATCAT_KEEP_MS;
|
||||
ok = false;
|
||||
await update();
|
||||
assert.equal(reads, 2 * perUpdate, 'an old read is asked again');
|
||||
assert.equal(state._satcatState, 'unavailable');
|
||||
await update();
|
||||
assert.equal(reads, 3 * perUpdate, 'a failed read is asked again');
|
||||
});
|
||||
|
||||
test('a failed imaging-sensor pack is warned about, as the UCS pack is', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const warn = t.mock.method(console, 'warn', () => {});
|
||||
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
|
||||
source: {
|
||||
readSensors: async () => {
|
||||
throw new Error('chunk failed');
|
||||
},
|
||||
},
|
||||
});
|
||||
await update();
|
||||
assert.ok(
|
||||
warn.mock.calls.some((call) =>
|
||||
/sensor pack unavailable/i.test(call.arguments[0]),
|
||||
),
|
||||
'the failure is not swallowed',
|
||||
);
|
||||
assert.equal(state._catalog.get(40115).sensor, null, 'base zoom steps');
|
||||
});
|
||||
@@ -10,6 +10,8 @@ export function createInteraction({
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
|
||||
function _onKeyDown(e) {
|
||||
// The Cockpit owns Escape while it rides the tracked satellite.
|
||||
if (parts.cockpit?._cockpitHeld()) return;
|
||||
if (layerState._enabled && e.key === 'Escape' && layerState._trackedNorad) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
parts.tracking._clearTracking(false, { origin: 'user' });
|
||||
@@ -45,6 +47,9 @@ export function createInteraction({
|
||||
|
||||
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!layerState._enabled) return;
|
||||
// The Cockpit camera rides the tracked satellite: a click on the
|
||||
// picture below must not untrack it or switch satellites.
|
||||
if (parts.cockpit?._cockpitHeld()) return;
|
||||
const picked = event.topHit;
|
||||
const hit = event.drawHit;
|
||||
|
||||
|
||||
@@ -85,6 +85,8 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
function _dockedCompanionNames() {
|
||||
const names = [];
|
||||
for (const noradId of layerState._dockedCompanions) {
|
||||
// A hidden class is not named on the tracked card either.
|
||||
if (parts.controls?._classVisible?.(noradId) === false) continue;
|
||||
names.push(
|
||||
layerState._catalog.get(noradId)?.name?.trim() || `SAT-${noradId}`,
|
||||
);
|
||||
@@ -104,6 +106,7 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedNorad !== ISS_NORAD &&
|
||||
!layerState._dockedCompanions.has(ISS_NORAD) &&
|
||||
layerState._catalog.has(ISS_NORAD) &&
|
||||
parts.controls?._classVisible?.(ISS_NORAD) !== false &&
|
||||
_issDisplayCached();
|
||||
if (!visible) {
|
||||
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { frameOf } from '../../render/rendererOf.js';
|
||||
import { ISS_OVERLAY_SOURCE_ID, SATELLITE_COVERAGE_MS } from './policy.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ISS_OVERLAY_SOURCE_ID,
|
||||
SATELLITE_COVERAGE_MS,
|
||||
} from './policy.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
|
||||
export function createLifecycle({
|
||||
@@ -54,6 +58,10 @@ export function createLifecycle({
|
||||
layerState._trackedFrameNumber = -1;
|
||||
layerState._trackedFrameGeo = null;
|
||||
layerState._trackedFrameNowForTest = null;
|
||||
// The new catalog's points and rings carry no hold.
|
||||
layerState._cockpitHiddenPoints = new Set();
|
||||
layerState._cockpitHiddenPath = null;
|
||||
layerState._cockpitHiddenDot = false;
|
||||
layerState._lastFocusUpdate = 0;
|
||||
layerState._activeFocusCount = 0;
|
||||
layerState._enabled = false;
|
||||
@@ -91,13 +99,18 @@ export function createLifecycle({
|
||||
layerState._params.showPoints,
|
||||
),
|
||||
);
|
||||
// Orbit rings + persistent ISS host label — show them
|
||||
parts.rendering._setOrbitPathsShown(
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
),
|
||||
);
|
||||
// Orbit rings + persistent ISS host label — show them; the ISS's ring
|
||||
// follows its class (and its tracking).
|
||||
for (const noradId of layerState._orbitPaths.keys())
|
||||
parts.rendering._setOrbitPathShown(
|
||||
noradId,
|
||||
noradId === ISS_NORAD
|
||||
? parts.controls._issOrbitVisible()
|
||||
: parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
),
|
||||
);
|
||||
parts.labels._syncIssOverlay();
|
||||
// Re-attach input handlers and preRender propagation
|
||||
parts.interaction._installClickHandler(viewer);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// src/layers/satellites/nearestPositions.test.mjs — the satellites nearest a
|
||||
// position: bounded to the nearest few, nearest first, hidden classes,
|
||||
// dense extras and asked-for exclusions left out.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
function controlsWith(satellites, { classes, dense = [] } = {}) {
|
||||
const state = {
|
||||
_points: new Map(),
|
||||
_catalog: new Map(),
|
||||
_denseIds: dense,
|
||||
_params: classes ? { classes } : {},
|
||||
};
|
||||
for (const sat of satellites) {
|
||||
state._points.set(sat.id, {
|
||||
pos: fromDegrees(sat.lon, sat.lat, sat.alt),
|
||||
});
|
||||
state._catalog.set(sat.id, {
|
||||
name: `${sat.name} `,
|
||||
satelliteClass: sat.cls,
|
||||
group: sat.group,
|
||||
});
|
||||
}
|
||||
return createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {
|
||||
rendering: { _pointPosition: (id) => state._points.get(id)?.pos ?? null },
|
||||
},
|
||||
}).methods;
|
||||
}
|
||||
|
||||
const SATELLITES = [
|
||||
{ id: 1, name: 'NEAR', lat: 30.5, lon: -97, alt: 500_000, cls: 'imaging' },
|
||||
{ id: 2, name: 'MID', lat: 33, lon: -97, alt: 500_000, cls: 'stations' },
|
||||
{ id: 3, name: 'FAR', lat: -40, lon: 80, alt: 500_000, cls: 'imaging' },
|
||||
{ id: 4, name: 'DEB', lat: 30.1, lon: -97, alt: 500_000, cls: 'debris' },
|
||||
{ id: 5, name: 'TELECOM', lat: 30.2, lon: -97, alt: 500_000, cls: 'telecom' },
|
||||
{ id: 6, name: 'SELF', lat: 30, lon: -97, alt: 420_000, cls: 'stations' },
|
||||
{ id: 7, name: 'EXTRA', lat: 30.3, lon: -97, alt: 500_000, cls: 'imaging', group: 'dense' },
|
||||
];
|
||||
|
||||
const CENTRE = fromDegrees(-97, 30, 420_000);
|
||||
|
||||
test('the nearest shown satellites come first, bounded, with their distance', () => {
|
||||
const methods = controlsWith(SATELLITES, {
|
||||
classes: { stations: true, imaging: true, debris: true, telecom: false },
|
||||
dense: [7],
|
||||
});
|
||||
const nearest = methods.getNearestPositions(CENTRE, 3, {
|
||||
excludeIds: [6],
|
||||
excludeClasses: ['debris'],
|
||||
});
|
||||
assert.deepEqual(
|
||||
nearest.map((entry) => entry.label),
|
||||
['NEAR', 'MID', 'FAR'],
|
||||
'no self, debris, hidden telecom or dense extra',
|
||||
);
|
||||
for (let i = 1; i < nearest.length; i += 1)
|
||||
assert.ok(nearest[i].distanceM >= nearest[i - 1].distanceM);
|
||||
const exact = distance(CENTRE, nearest[0].position);
|
||||
assert.ok(Math.abs(nearest[0].distanceM - exact) < 1e-6);
|
||||
assert.ok(Math.abs(nearest[0].latitude - 30.5) < 1e-6);
|
||||
assert.equal(nearest[0].satelliteClass, 'imaging');
|
||||
assert.equal(methods.getNearestPositions(CENTRE, 1, { excludeIds: [6] })[0].label, 'DEB');
|
||||
assert.deepEqual(methods.getNearestPositions(null, 3), []);
|
||||
assert.deepEqual(methods.getNearestPositions(CENTRE, 0), []);
|
||||
assert.deepEqual(methods.getNearestPositions(CENTRE, 0.5), []);
|
||||
assert.equal(methods.getNearestPositions(CENTRE, 2.5).length, 2);
|
||||
});
|
||||
@@ -74,6 +74,7 @@ test('positions read back from the drawn dots match the Cesium geodetic conversi
|
||||
test('no part of the layer drives Cesium', () => {
|
||||
const offList = [
|
||||
'catalog',
|
||||
'cockpitSubject',
|
||||
'controls',
|
||||
'index',
|
||||
'ingestion',
|
||||
|
||||
@@ -15,6 +15,57 @@ import {
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js';
|
||||
|
||||
/** The Earth's rotation rate, rad/s (WGS84). */
|
||||
const EARTH_ROTATION_RAD_S = 7.292115e-5;
|
||||
|
||||
/** Below this ground speed a satellite holds still over the ground (GEO), m/s. */
|
||||
const GROUND_TRACK_MIN_SPEED_MPS = 10;
|
||||
|
||||
/**
|
||||
* The ground track's bearing, degrees clockwise from north, from one SGP4
|
||||
* state: the inertial velocity turned into the Earth-fixed frame, less the
|
||||
* Earth's rotation under the satellite, read in the east/north plane at the
|
||||
* sub-satellite point. Null without a velocity, or for a satellite that holds
|
||||
* still over the ground (geostationary).
|
||||
* @param {{x: number, y: number, z: number}} positionKm TEME position, km.
|
||||
* @param {{x: number, y: number, z: number}|null} velocityKmS TEME velocity, km/s.
|
||||
* @param {number} gmst Greenwich mean sidereal time, radians.
|
||||
* @param {number} latitudeDeg Sub-satellite latitude.
|
||||
* @param {number} longitudeDeg Sub-satellite longitude.
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function groundTrackBearingDeg(
|
||||
positionKm,
|
||||
velocityKmS,
|
||||
gmst,
|
||||
latitudeDeg,
|
||||
longitudeDeg,
|
||||
) {
|
||||
if (!positionKm || !velocityKmS || !Number.isFinite(gmst)) return null;
|
||||
const cosG = Math.cos(gmst);
|
||||
const sinG = Math.sin(gmst);
|
||||
// TEME to Earth-fixed is a turn about z by GMST.
|
||||
const rx = cosG * positionKm.x + sinG * positionKm.y;
|
||||
const ry = -sinG * positionKm.x + cosG * positionKm.y;
|
||||
const vx =
|
||||
(cosG * velocityKmS.x + sinG * velocityKmS.y + EARTH_ROTATION_RAD_S * ry) *
|
||||
1000;
|
||||
const vy =
|
||||
(-sinG * velocityKmS.x + cosG * velocityKmS.y - EARTH_ROTATION_RAD_S * rx) *
|
||||
1000;
|
||||
const vz = velocityKmS.z * 1000;
|
||||
const φ = (latitudeDeg * Math.PI) / 180;
|
||||
const λ = (longitudeDeg * Math.PI) / 180;
|
||||
const east = -Math.sin(λ) * vx + Math.cos(λ) * vy;
|
||||
const north =
|
||||
-Math.sin(φ) * Math.cos(λ) * vx -
|
||||
Math.sin(φ) * Math.sin(λ) * vy +
|
||||
Math.cos(φ) * vz;
|
||||
if (![east, north].every(Number.isFinite)) return null;
|
||||
if (Math.hypot(east, north) < GROUND_TRACK_MIN_SPEED_MPS) return null;
|
||||
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
|
||||
}
|
||||
|
||||
export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* Parse TLE text into array of { name, line1, line2 } objects.
|
||||
@@ -42,11 +93,20 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
? Math.hypot(velocity.x, velocity.y, velocity.z) * 1000
|
||||
: null;
|
||||
|
||||
const latitude = degreesLat(geo.latitude);
|
||||
const longitude = degreesLong(geo.longitude);
|
||||
return {
|
||||
longitude: degreesLong(geo.longitude),
|
||||
latitude: degreesLat(geo.latitude),
|
||||
longitude,
|
||||
latitude,
|
||||
altitude: geo.height * 1000, // km → meters
|
||||
speedMps: Number.isFinite(speedMps) ? speedMps : null,
|
||||
groundTrackDeg: groundTrackBearingDeg(
|
||||
posVel.position,
|
||||
velocity,
|
||||
gmst,
|
||||
latitude,
|
||||
longitude,
|
||||
),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { satelliteClassColor } from '../../data/satelliteClass.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { cssColor, hexColor } from '../../render/color.js';
|
||||
import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
|
||||
|
||||
/**
|
||||
* Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation.
|
||||
*
|
||||
* Loads six CelesTrak groups (~840 sats): stations, visual, GPS, GLONASS,
|
||||
* Galileo, and the geosynchronous belt. Optional dense mode (setParams
|
||||
* catalog:'dense') adds the Starlink shell as points-only extras.
|
||||
* Loads eleven CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
|
||||
* geosynchronous belt, and the Earth resources, weather, Planet, SAR and
|
||||
* science groups. Each object is filed under one of six classes
|
||||
* (src/layers/satellites/classes.js) whose visibility the layer row toggles; dense mode
|
||||
* (setParams catalog:'dense', the STARLINK toggle) adds the Starlink shell as
|
||||
* points-only extras.
|
||||
* Renders positions as points, orbital paths as polylines.
|
||||
* Click any satellite to track it with camera follow + orbital path.
|
||||
*
|
||||
@@ -58,6 +62,13 @@ export const CATALOG_GROUPS = [
|
||||
{ tag: 'glonass', path: 'glo-ops' },
|
||||
{ tag: 'galileo', path: 'galileo' },
|
||||
{ tag: 'geo', path: 'geo' },
|
||||
// Earth observation launched after the UCS snapshot, and science probes.
|
||||
// Each object's class comes from src/layers/satellites/classes.js, not its group.
|
||||
{ tag: 'resource', path: 'resource' },
|
||||
{ tag: 'weather', path: 'weather' },
|
||||
{ tag: 'planet', path: 'planet' },
|
||||
{ tag: 'sar', path: 'sar' },
|
||||
{ tag: 'science', path: 'science' },
|
||||
];
|
||||
|
||||
// Dense-catalog mode (setParams({ catalog: 'dense' })): Starlink shell as
|
||||
@@ -171,6 +182,40 @@ export const POINT_STYLES = {
|
||||
},
|
||||
};
|
||||
|
||||
const CLASS_COLORS = Object.fromEntries(
|
||||
SATELLITE_CLASS_IDS.map((id) => [
|
||||
id,
|
||||
Object.freeze(cssColor(SATELLITE_CLASS_DISPLAY[id].color)),
|
||||
]),
|
||||
);
|
||||
const _classStyles = new Map();
|
||||
|
||||
/**
|
||||
* A satellite's point style: its group's size and outline, in its class's
|
||||
* colour (src/layers/satellites/classes.js), so the dots match the class legend and
|
||||
* toggles. Styles are shared per group and class.
|
||||
* @param {string|undefined} group Catalog group tag.
|
||||
* @param {string|undefined} satelliteClass Class id.
|
||||
*/
|
||||
export function classPointStyle(group, satelliteClass) {
|
||||
const base = POINT_STYLES[group] || POINT_STYLES.visual;
|
||||
const color = CLASS_COLORS[satelliteClass];
|
||||
if (!color) return base;
|
||||
const key = `${group}|${satelliteClass}`;
|
||||
let style = _classStyles.get(key);
|
||||
if (!style) {
|
||||
style = Object.freeze({
|
||||
...base,
|
||||
color:
|
||||
group === 'dense'
|
||||
? Object.freeze([color[0], color[1], color[2], 0.9])
|
||||
: color,
|
||||
});
|
||||
_classStyles.set(key, style);
|
||||
}
|
||||
return style;
|
||||
}
|
||||
|
||||
/**
|
||||
* Physically DOCKED vehicles are separate real tracks sharing one position: the
|
||||
* station and everything berthed to it sit within metres of each other. Their
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { satelliteClassLabel } from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
@@ -38,7 +38,10 @@ export function mapAnalystRecord(raw) {
|
||||
// must not leak onto a row that has no satellite identity.
|
||||
satelliteClass:
|
||||
noradId || group
|
||||
? satelliteClassLabel(group, { isIss, localize: false })
|
||||
? satelliteClassText(text(raw?.satelliteClass), group, {
|
||||
isIss,
|
||||
localize: false,
|
||||
})
|
||||
: null,
|
||||
group,
|
||||
};
|
||||
@@ -83,6 +86,12 @@ export function createRecords({ state, parts }) {
|
||||
const result = [];
|
||||
const emit = (noradId, sat) => {
|
||||
if (result.length >= limit) return false;
|
||||
// A class the user hid stays out of answers too; the tracked one stays.
|
||||
if (
|
||||
noradId !== state._trackedNorad &&
|
||||
parts.controls?._classVisible?.(noradId) === false
|
||||
)
|
||||
return true;
|
||||
const pos = analystGeo(noradId, sat, now);
|
||||
if (!pos) return true;
|
||||
result.push(
|
||||
@@ -90,6 +99,7 @@ export function createRecords({ state, parts }) {
|
||||
noradId,
|
||||
name: sat?.name,
|
||||
group: sat?.group,
|
||||
satelliteClass: sat?.satelliteClass,
|
||||
lat: pos.lat,
|
||||
lon: pos.lon,
|
||||
altitudeM: pos.altitudeM,
|
||||
|
||||
@@ -210,6 +210,53 @@ export function createRendering({
|
||||
sets?.rings.upsert([path.item]);
|
||||
}
|
||||
|
||||
/** Whether a ring is shown; false when there is none. */
|
||||
function _orbitPathShown(noradId) {
|
||||
return layerState._orbitPaths.get(noradId)?.item.show === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a ring at `factor` times the alpha it was built with; 1 restores
|
||||
* it exactly.
|
||||
* @returns {boolean} True when the ring now carries `factor`.
|
||||
*/
|
||||
function _setOrbitPathAlpha(noradId, factor) {
|
||||
const path = layerState._orbitPaths.get(noradId);
|
||||
if (!path) return false;
|
||||
if (path.alphaFactor === factor) return true;
|
||||
path.alphaFactor = factor;
|
||||
path.item.style = {
|
||||
kind: 'solid',
|
||||
color: withAlpha(path.color, RING_ALPHA * factor),
|
||||
};
|
||||
path.item.depthFailColor = withAlpha(
|
||||
path.color,
|
||||
RING_BEHIND_ALPHA * factor,
|
||||
);
|
||||
sets?.rings.upsert([path.item]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Show or hide one satellite's dot, keeping its style. */
|
||||
function _setPointShown(noradId, show) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point || point.show === show) return;
|
||||
point.show = show;
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/** Whether a satellite's dot is shown; false when it has none. */
|
||||
function _pointShown(noradId) {
|
||||
return layerState._points.get(noradId)?.show === true;
|
||||
}
|
||||
|
||||
/** Show or hide the tracked satellite's dot (the Cockpit rides it). */
|
||||
function _setTrackedDotShown(show) {
|
||||
if (!trackedDot || trackedDot.item.show === show) return;
|
||||
trackedDot.item.show = show;
|
||||
if (trackedDot.drawn) sets?.tracked.upsert([trackedDot.item]);
|
||||
}
|
||||
|
||||
/** Remove every orbit ring. */
|
||||
function _clearOrbitPaths() {
|
||||
const ids = [...layerState._orbitPaths.values()].map(
|
||||
@@ -256,7 +303,7 @@ export function createRendering({
|
||||
* @param {{x: number, y: number, z: number}} position ECEF metres.
|
||||
* @param {object} style A `POINT_STYLES` entry.
|
||||
*/
|
||||
function _addPoint(noradId, position, style) {
|
||||
function _addPoint(noradId, position, style, show = true) {
|
||||
layerState._points.set(noradId, {
|
||||
id: String(noradId),
|
||||
pos: { x: position.x, y: position.y, z: position.z },
|
||||
@@ -266,7 +313,7 @@ export function createRendering({
|
||||
outlineWidth: style.outlineWidth,
|
||||
scaleByDistance: POINT_SCALE_BY_DISTANCE,
|
||||
disableDepthTest: 0,
|
||||
show: true,
|
||||
show,
|
||||
meta: { noradId },
|
||||
});
|
||||
_markDirty(noradId);
|
||||
@@ -310,11 +357,22 @@ export function createRendering({
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/** Show a dot again in its group's style (WS-D3). */
|
||||
function _restorePoint(noradId, style) {
|
||||
/** Draw a dot in `style` (a `POINT_STYLES` entry), keeping whether it shows. */
|
||||
function _setPointStyle(noradId, style) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point) return;
|
||||
point.show = true;
|
||||
point.pixelSize = style.pixelSize;
|
||||
point.color = style.color;
|
||||
point.outlineColor = style.outlineColor;
|
||||
point.outlineWidth = style.outlineWidth;
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/** Show a dot again in its group's style (WS-D3), or keep it hidden. */
|
||||
function _restorePoint(noradId, style, show = true) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point) return;
|
||||
point.show = show;
|
||||
point.pixelSize = style.pixelSize;
|
||||
point.color = style.color;
|
||||
point.outlineColor = style.outlineColor;
|
||||
@@ -425,6 +483,9 @@ export function createRendering({
|
||||
// GMST value (gstime is pure), so the ring starts unturned.
|
||||
gmstAtBake: gstime(bakeDate),
|
||||
item: null,
|
||||
// The alpha multiple the ring is drawn at (1: as built); the Cockpit's
|
||||
// orbit dim (cockpitSubject.js) sets it.
|
||||
alphaFactor: 1,
|
||||
};
|
||||
path.item = {
|
||||
id: String(noradId),
|
||||
@@ -495,7 +556,8 @@ export function createRendering({
|
||||
|
||||
/**
|
||||
* Propagate all CORE satellite positions and update their dots.
|
||||
* (~840 sats ≈ 1.6 ms/pass — fine at the 1s/200ms cadence.) Dense extras are
|
||||
* (About 1,300 core satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms,
|
||||
* fine at the 1s/200ms cadence.) Dense extras are
|
||||
* excluded: they refresh on the round-robin budget in _propagateDenseChunk.
|
||||
*/
|
||||
|
||||
@@ -584,6 +646,10 @@ export function createRendering({
|
||||
if (!trackedDrawnThisTick) _drawTrackedDot();
|
||||
}
|
||||
|
||||
// While the Cockpit rides the tracked satellite, keep its marks hidden.
|
||||
if (layerState._cockpitSubjectNorad !== null)
|
||||
parts.cockpit?._syncCockpitSubjectVisuals();
|
||||
|
||||
_updatePointFocus(now);
|
||||
|
||||
// Hidden standalone orbit rings do not need turning while Space Missions
|
||||
@@ -739,6 +805,12 @@ export function createRendering({
|
||||
_setPointsShown,
|
||||
_setOrbitPathsShown,
|
||||
_setOrbitPathShown,
|
||||
_orbitPathShown,
|
||||
_setOrbitPathAlpha,
|
||||
_setPointShown,
|
||||
_setPointStyle,
|
||||
_pointShown,
|
||||
_setTrackedDotShown,
|
||||
_clearOrbitPaths,
|
||||
_addPoint,
|
||||
_movePoint,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @file Imaging sensors: which Earth-observation platform a satellite is, and
|
||||
* the swath its sensor images. The orbital view draws that swath to scale and
|
||||
* lets a satellite zoom past 8x only as far as its sensor's narrowest
|
||||
* standard swath (src/cockpitOrbital.js `orbitalMaxZoom`).
|
||||
*
|
||||
* Pure: no Cesium, no fetches; the bundled pack is loaded by
|
||||
* src/data/imagingSensors.js.
|
||||
*
|
||||
* @module imagingSensors
|
||||
*/
|
||||
|
||||
/**
|
||||
* One sensor-pack entry as the app uses it.
|
||||
* @typedef {{id: string, label: string, operator: string|null,
|
||||
* sensor: string, type: string, altitudeKm: number|null,
|
||||
* modes: Array<{name: string, swathKm: number|null, gsdM: number|null}>,
|
||||
* narrowestSwathKm: number|null, swathConfirmed: boolean,
|
||||
* sources: string[], unverified: string[]}} ImagingSensor
|
||||
*/
|
||||
|
||||
/**
|
||||
* Index the pack for matching: exact NORAD numbers first, then name patterns
|
||||
* in pack order. A malformed pattern is skipped, not fatal.
|
||||
* @param {{entries?: Array<object>}} pack Parsed `imaging_sensors.json`.
|
||||
* @returns {{byNorad: Map<number, ImagingSensor>,
|
||||
* patterns: Array<{pattern: RegExp, sensor: ImagingSensor}>}}
|
||||
*/
|
||||
export function indexImagingSensors(pack) {
|
||||
const byNorad = new Map();
|
||||
const patterns = [];
|
||||
for (const entry of pack?.entries || []) {
|
||||
if (!entry?.id) continue;
|
||||
const sensor = Object.freeze({
|
||||
id: entry.id,
|
||||
label: entry.label || entry.id,
|
||||
operator: entry.operator ?? null,
|
||||
sensor: entry.sensor || '',
|
||||
type: entry.type || '',
|
||||
altitudeKm: Number.isFinite(entry.altitudeKm) ? entry.altitudeKm : null,
|
||||
modes: Object.freeze(
|
||||
(entry.modes || []).map((mode) => Object.freeze({ ...mode })),
|
||||
),
|
||||
narrowestSwathKm: Number.isFinite(entry.narrowestSwathKm)
|
||||
? entry.narrowestSwathKm
|
||||
: null,
|
||||
swathConfirmed: entry.swathConfirmed === true,
|
||||
sources: Object.freeze([...(entry.sources || [])]),
|
||||
unverified: Object.freeze([...(entry.unverified || [])]),
|
||||
});
|
||||
for (const noradId of entry.match?.norad || []) {
|
||||
if (Number.isInteger(noradId) && !byNorad.has(noradId))
|
||||
byNorad.set(noradId, sensor);
|
||||
}
|
||||
if (entry.match?.nameRegex) {
|
||||
try {
|
||||
patterns.push({ pattern: new RegExp(entry.match.nameRegex), sensor });
|
||||
} catch {
|
||||
// A bad pattern only loses its name match; NORAD ids still work.
|
||||
}
|
||||
}
|
||||
}
|
||||
return { byNorad, patterns };
|
||||
}
|
||||
|
||||
/**
|
||||
* The sensor entry for a satellite: by NORAD number, else by its CelesTrak
|
||||
* name (upper-cased, trimmed).
|
||||
* @param {ReturnType<typeof indexImagingSensors>|null|undefined} index
|
||||
* @param {{noradId?: number, name?: string}} satellite
|
||||
* @returns {ImagingSensor|null}
|
||||
*/
|
||||
export function matchImagingSensor(index, { noradId, name } = {}) {
|
||||
if (!index) return null;
|
||||
const byId = index.byNorad?.get(noradId);
|
||||
if (byId) return byId;
|
||||
const text = String(name || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (!text) return null;
|
||||
for (const { pattern, sensor } of index.patterns || [])
|
||||
if (pattern.test(text)) return sensor;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The swath the orbital view may zoom to: the narrowest standard swath, only
|
||||
* when it was confirmed on a cited page. An unconfirmed swath keeps the
|
||||
* satellite at the base zoom steps.
|
||||
* @param {ImagingSensor|null|undefined} sensor
|
||||
* @returns {number|null} Kilometres.
|
||||
*/
|
||||
export function zoomableSwathKm(sensor) {
|
||||
const swathKm = sensor?.narrowestSwathKm;
|
||||
return sensor?.swathConfirmed === true &&
|
||||
Number.isFinite(swathKm) &&
|
||||
swathKm > 0
|
||||
? swathKm
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
indexImagingSensors,
|
||||
matchImagingSensor,
|
||||
zoomableSwathKm,
|
||||
} from './sensors.js';
|
||||
import { loadImagingSensors } from '../../data/imagingSensors.js';
|
||||
|
||||
const PACK_URL = new URL(
|
||||
'../../data/local_data/imaging_sensors/imaging_sensors.json',
|
||||
import.meta.url,
|
||||
);
|
||||
|
||||
const PACK = {
|
||||
entries: [
|
||||
{
|
||||
id: 'worldview-3',
|
||||
label: 'WorldView-3',
|
||||
match: { norad: [40115], nameRegex: '^WORLDVIEW-3' },
|
||||
narrowestSwathKm: 13.1,
|
||||
swathConfirmed: true,
|
||||
},
|
||||
{
|
||||
id: 'iceye',
|
||||
label: 'ICEYE',
|
||||
match: { nameRegex: '^ICEYE-X\\d+' },
|
||||
narrowestSwathKm: 5,
|
||||
swathConfirmed: true,
|
||||
},
|
||||
{
|
||||
id: 'broken',
|
||||
label: 'Broken pattern',
|
||||
match: { norad: [1], nameRegex: '([' },
|
||||
narrowestSwathKm: 9,
|
||||
swathConfirmed: true,
|
||||
},
|
||||
{
|
||||
id: 'blacksky',
|
||||
label: 'BlackSky',
|
||||
match: { nameRegex: '^GLOBAL-\\d+$' },
|
||||
narrowestSwathKm: null,
|
||||
swathConfirmed: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
test('a satellite matches its sensor by NORAD number, then by name', () => {
|
||||
const index = indexImagingSensors(PACK);
|
||||
assert.equal(
|
||||
matchImagingSensor(index, { noradId: 40115 })?.id,
|
||||
'worldview-3',
|
||||
);
|
||||
// An id match wins over a name that says otherwise.
|
||||
assert.equal(
|
||||
matchImagingSensor(index, { noradId: 40115, name: 'ICEYE-X9' })?.id,
|
||||
'worldview-3',
|
||||
);
|
||||
assert.equal(
|
||||
matchImagingSensor(index, { noradId: 99999, name: ' iceye-x14 ' })?.id,
|
||||
'iceye',
|
||||
);
|
||||
assert.equal(matchImagingSensor(index, { noradId: 1 })?.id, 'broken');
|
||||
assert.equal(matchImagingSensor(index, { name: 'STARLINK-1007' }), null);
|
||||
assert.equal(matchImagingSensor(null, { noradId: 40115 }), null);
|
||||
});
|
||||
|
||||
test('only a confirmed swath opens zoom steps past 8x', () => {
|
||||
const index = indexImagingSensors(PACK);
|
||||
assert.equal(
|
||||
zoomableSwathKm(matchImagingSensor(index, { noradId: 40115 })),
|
||||
13.1,
|
||||
);
|
||||
assert.equal(
|
||||
zoomableSwathKm(matchImagingSensor(index, { name: 'GLOBAL-21' })),
|
||||
null,
|
||||
);
|
||||
assert.equal(zoomableSwathKm(null), null);
|
||||
assert.equal(
|
||||
zoomableSwathKm({ swathConfirmed: true, narrowestSwathKm: 0 }),
|
||||
null,
|
||||
'no swath to zoom to',
|
||||
);
|
||||
});
|
||||
|
||||
test('the bundled pack is well formed and cites its sources', () => {
|
||||
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
|
||||
assert.ok(pack.entries.length >= 40);
|
||||
assert.ok(
|
||||
readFileSync(PACK_URL).length < 60_000,
|
||||
'small enough for the layer',
|
||||
);
|
||||
const ids = new Set();
|
||||
for (const entry of pack.entries) {
|
||||
assert.ok(entry.id && !ids.has(entry.id), `unique id ${entry.id}`);
|
||||
ids.add(entry.id);
|
||||
assert.ok(entry.match.norad || entry.match.nameRegex, entry.id);
|
||||
if (entry.match.nameRegex) new RegExp(entry.match.nameRegex);
|
||||
assert.ok(entry.sources.length > 0, `${entry.id} cites a source`);
|
||||
if (entry.swathConfirmed) {
|
||||
assert.ok(entry.narrowestSwathKm > 0, entry.id);
|
||||
// The narrowest *standard* swath: sampling modes (Himawari's landmark
|
||||
// area) and older generations (Dove Classic) may be narrower.
|
||||
const swaths = entry.modes
|
||||
.map((mode) => mode.swathKm)
|
||||
.filter(Number.isFinite);
|
||||
assert.ok(
|
||||
swaths.includes(entry.narrowestSwathKm),
|
||||
`${entry.id}: the narrowest swath is one of its modes`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the pack cites no reseller, links its datasheets and names its own fields', () => {
|
||||
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
|
||||
// Resellers, Gunter's Space Page, and the Copernicus portal whose terms
|
||||
// forbid reuse.
|
||||
const excluded =
|
||||
/euspaceimaging\.com|apollomapping\.com|landinfo\.com|satimagingcorp\.com|space\.skyrocket\.de|dataspace\.copernicus\.eu/;
|
||||
const fields = new Set(['altitudeKm', 'narrowestSwathKm', 'swathKm', 'gsdM']);
|
||||
for (const entry of pack.entries) {
|
||||
for (const source of entry.sources)
|
||||
assert.doesNotMatch(source, excluded, `${entry.id}: ${source}`);
|
||||
// A bare file-host datasheet is cited beside the operator page that
|
||||
// links it.
|
||||
if (entry.sources.some((source) => /cdn\.sanity\.io/.test(source)))
|
||||
assert.ok(
|
||||
entry.sources.some((source) => /^https:\/\/vantor\.com\//.test(source)),
|
||||
`${entry.id}: the Vantor page for its datasheet`,
|
||||
);
|
||||
// An unverified value is named by the pack's own field.
|
||||
for (const note of entry.unverified) {
|
||||
const [field] = /^[A-Za-z_]+/.exec(note) ?? [''];
|
||||
if (/^[a-z]+(_[a-z]+)+$|^[a-z]+[A-Z]\w*$/.test(field))
|
||||
assert.ok(fields.has(field), `${entry.id}: unknown field ${field}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the pack loads once and matches real catalog names', async () => {
|
||||
const index = await loadImagingSensors();
|
||||
assert.equal(index, await loadImagingSensors(), 'loaded once');
|
||||
const cases = [
|
||||
[{ noradId: 49260, name: 'LANDSAT 9' }, 'landsat-8-9'],
|
||||
[{ noradId: 40115, name: 'WORLDVIEW-3 (WV-3)' }, 'worldview-3'],
|
||||
[{ noradId: 1, name: 'FLOCK 4Q-12' }, 'planetscope'],
|
||||
[{ noradId: 1, name: 'ICEYE-X40' }, 'iceye'],
|
||||
[{ noradId: 1, name: 'SKYSAT-C19' }, 'skysat'],
|
||||
];
|
||||
for (const [satellite, id] of cases)
|
||||
assert.equal(matchImagingSensor(index, satellite)?.id, id, satellite.name);
|
||||
});
|
||||
@@ -6,11 +6,31 @@ const GROUPS = new Set([
|
||||
'galileo',
|
||||
'geo',
|
||||
'starlink',
|
||||
// Imaging coverage beyond the UCS May 2023 snapshot, and science probes.
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
]);
|
||||
|
||||
/** The UCS pack, loaded on first use (see src/data/ucsSatellites.js). */
|
||||
async function loadBundledUcs() {
|
||||
const { loadUcsSatellites } = await import('../../data/ucsSatellites.js');
|
||||
return loadUcsSatellites();
|
||||
}
|
||||
|
||||
/** The imaging-sensor pack, loaded on first use (see src/data/imagingSensors.js). */
|
||||
async function loadBundledSensors() {
|
||||
const { loadImagingSensors } = await import('../../data/imagingSensors.js');
|
||||
return loadImagingSensors();
|
||||
}
|
||||
|
||||
/** Read catalog text from the existing group endpoint using a supplied transport. */
|
||||
export function createSatelliteSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
loadUcs = loadBundledUcs,
|
||||
loadSensors = loadBundledSensors,
|
||||
} = {}) {
|
||||
return {
|
||||
async readGroup(group, { signal } = {}) {
|
||||
@@ -24,5 +44,33 @@ export function createSatelliteSource({
|
||||
const stale = response.headers?.get?.('x-tle-cache') === 'STALE-ERROR';
|
||||
return { ok: response.ok, status: response.status, text, stale };
|
||||
},
|
||||
|
||||
/**
|
||||
* CelesTrak SATCAT records (CSV) for one group: object type, operational
|
||||
* status and owner, through the proxy's day-long cache.
|
||||
*/
|
||||
async readSatcat(group, { signal } = {}) {
|
||||
if (!GROUPS.has(group)) throw new TypeError('Unknown satellite group');
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl(`/api/celestrak-satcat/${group}`, {
|
||||
signal,
|
||||
});
|
||||
const text = response.ok ? await response.text() : '';
|
||||
signal?.throwIfAborted();
|
||||
// The proxy serves its last copy, marked STALE-ERROR, when CelesTrak
|
||||
// is down.
|
||||
const stale = response.headers?.get?.('x-satcat-cache') === 'STALE-ERROR';
|
||||
return { ok: response.ok, status: response.status, text, stale };
|
||||
},
|
||||
|
||||
/** The UCS Satellite Database pack, keyed by NORAD number. */
|
||||
readUcs() {
|
||||
return loadUcs();
|
||||
},
|
||||
|
||||
/** The imaging-sensor pack, indexed by NORAD number and name pattern. */
|
||||
readSensors() {
|
||||
return loadSensors();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -164,3 +164,24 @@ test('satellite pass prediction methods report no-tle on cold catalog and coerce
|
||||
{ status: 'no-tle' },
|
||||
);
|
||||
});
|
||||
|
||||
test('a SATCAT read says when the proxy served its last copy', async () => {
|
||||
const headers = (cache) => ({
|
||||
get: (name) => (name === 'x-satcat-cache' ? cache : null),
|
||||
});
|
||||
let cache = 'STALE-ERROR';
|
||||
const source = createSatelliteSource({
|
||||
fetchImpl: async (url) => {
|
||||
assert.equal(url, '/api/celestrak-satcat/visual');
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: headers(cache),
|
||||
text: async () => 'OBJECT_NAME,NORAD_CAT_ID,OBJECT_TYPE',
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal((await source.readSatcat('visual')).stale, true);
|
||||
cache = 'HIT';
|
||||
assert.equal((await source.readSatcat('visual')).stale, false);
|
||||
});
|
||||
@@ -29,7 +29,15 @@ const GROUPS = [
|
||||
'galileo',
|
||||
'geo',
|
||||
'starlink',
|
||||
// Added after Starlink so the fixture ids above keep their numbers.
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
];
|
||||
/** The core catalog's groups, one owned satellite each. */
|
||||
const CORE = GROUPS.filter((group) => group !== 'starlink');
|
||||
|
||||
function tle(id, invalid = false) {
|
||||
// Owned synthetic catalog IDs over one valid element set; never live requests.
|
||||
@@ -153,10 +161,10 @@ test('stale core records surface through actual HTTP, ingestion and feed state,
|
||||
const f = await fixture(t);
|
||||
await f.update();
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
assert.equal(f.stats().count, 6);
|
||||
f.policy.stale = new Set(GROUPS.slice(0, 6));
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
f.policy.stale = new Set(CORE);
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.policy.stale = new Set(['visual']);
|
||||
@@ -173,13 +181,13 @@ test('a stale duplicate cannot taint its earlier fresh winning record', async (t
|
||||
f.policy.stale.add('visual');
|
||||
f.policy.ids.visual = 25545;
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(f.state._catalog.get(25545).group, 'stations');
|
||||
assert.equal(f.stats().stale, false);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
f.policy.stale = new Set(['stations']);
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(
|
||||
f.stats().stale,
|
||||
true,
|
||||
@@ -192,7 +200,7 @@ test('invalid stale orbital elements are not admitted as provenance', async (t)
|
||||
f.policy.stale.add('visual');
|
||||
f.policy.invalid.add('visual');
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 5);
|
||||
assert.equal(f.stats().count, CORE.length - 1);
|
||||
assert.equal(f.state._catalog.has(25546), false);
|
||||
assert.equal(f.stats().stale, false);
|
||||
});
|
||||
@@ -204,17 +212,17 @@ test('failed and aborted core refreshes keep provenance of retained records', as
|
||||
const priorTime = f.stats().lastUpdate;
|
||||
f.policy.status = 503;
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.stats().status, 'unavailable');
|
||||
assert.equal(f.stats().lastUpdate, priorTime);
|
||||
f.policy.hold = true;
|
||||
const controller = new AbortController();
|
||||
const work = f.update({ signal: controller.signal });
|
||||
await f.waitHeld(6);
|
||||
await f.waitHeld(CORE.length);
|
||||
controller.abort();
|
||||
await assert.rejects(work, { name: 'AbortError' });
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.stats().stale, true);
|
||||
assert.equal(f.stats().lastUpdate, priorTime);
|
||||
assert.equal(f.state._activeUpdateControllers.size, 0);
|
||||
@@ -226,11 +234,11 @@ test('dense provenance belongs to its admitted records and clears on removal', a
|
||||
f.policy.stale.add('starlink');
|
||||
f.state._params.catalog = 'dense';
|
||||
assert.equal((await f.parts.catalog._loadDenseCatalog()).status, 'ready');
|
||||
assert.equal(f.stats().count, 7);
|
||||
assert.equal(f.stats().count, CORE.length + 1);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.state._params.catalog = 'core';
|
||||
f.parts.catalog._removeDenseCatalog();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
f.policy.stale = new Set(['stations']);
|
||||
await f.update();
|
||||
@@ -271,13 +279,13 @@ test('cancelling dense replacement preserves admitted stale extras until rebuild
|
||||
await f.waitHeld(1);
|
||||
controller.abort();
|
||||
assert.equal((await work).status, 'cancelled');
|
||||
assert.equal(f.stats().count, 7);
|
||||
assert.equal(f.stats().count, CORE.length + 1);
|
||||
assert.equal(f.feed(), 'stale');
|
||||
f.policy.hold = false;
|
||||
f.policy.stale.clear();
|
||||
f.state._params.catalog = 'core';
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
});
|
||||
|
||||
@@ -287,7 +295,7 @@ test('destroy aborts an in-flight response and initialization starts with new ow
|
||||
await f.update();
|
||||
f.policy.hold = true;
|
||||
const work = f.update();
|
||||
await f.waitHeld(6);
|
||||
await f.waitHeld(CORE.length);
|
||||
const rejected = assert.rejects(work, { name: 'AbortError' });
|
||||
f.parts.lifecycle.methods.destroy(f.viewer);
|
||||
assert.equal(f.stats().count, 0);
|
||||
@@ -298,6 +306,6 @@ test('destroy aborts an in-flight response and initialization starts with new ow
|
||||
f.policy.hold = false;
|
||||
f.policy.stale.clear();
|
||||
await f.update();
|
||||
assert.equal(f.stats().count, 6);
|
||||
assert.equal(f.stats().count, CORE.length);
|
||||
assert.equal(f.feed(), 'nominal');
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DEFAULT_SATELLITE_CLASSES } from './classes.js';
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
@@ -13,7 +14,9 @@ export function createState({ services }) {
|
||||
|
||||
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
|
||||
|
||||
// Satellite catalog: { noradId → { name, satrec, group } }
|
||||
// Satellite catalog: { noradId → { name, satrec, group, line1, line2,
|
||||
// satelliteClass, ucs, satcat } } — class, UCS and SATCAT records from
|
||||
// src/layers/satellites/classes.js and the sources the update read.
|
||||
|
||||
state._catalog = new Map();
|
||||
|
||||
@@ -42,6 +45,12 @@ export function createState({ services }) {
|
||||
|
||||
// Cache provenance belongs to admitted core and dense records separately.
|
||||
state._coreStale = false;
|
||||
// How current the SATCAT records behind the classes are: null before any
|
||||
// read, then 'current' | 'stale' | 'unavailable' (see ingestion.js).
|
||||
state._satcatState = null;
|
||||
// When _satcatState was last set (Date.now()); a current read is kept
|
||||
// SATCAT_KEEP_MS (src/layers/satellites/ingestion.js).
|
||||
state._satcatReadAtMs = Number.NEGATIVE_INFINITY;
|
||||
state._denseStale = false;
|
||||
|
||||
state._activeUpdateControllers = new Set();
|
||||
@@ -92,9 +101,25 @@ export function createState({ services }) {
|
||||
|
||||
// Runtime params (DataLayerManager.setLayerParams path)
|
||||
|
||||
state._params = { catalog: 'core', showPoints: true, showOrbits: true };
|
||||
state._params = {
|
||||
catalog: 'core',
|
||||
showPoints: true,
|
||||
showOrbits: true,
|
||||
// Which satellite classes show (src/layers/satellites/classes.js). Starlink
|
||||
// follows `catalog`: its points exist only in dense mode.
|
||||
classes: { ...DEFAULT_SATELLITE_CLASSES },
|
||||
};
|
||||
// 'core' | 'dense'
|
||||
|
||||
/** SATCAT records (object type, status, owner) by NORAD id, last update. */
|
||||
state._satcat = new Map();
|
||||
|
||||
/** The UCS pack by NORAD id, once loaded; null until then or if it failed. */
|
||||
state._ucs = null;
|
||||
|
||||
/** The imaging-sensor index, once loaded; null until then or if it failed. */
|
||||
state._sensors = null;
|
||||
|
||||
state._denseIds = [];
|
||||
// norad ids of dense extras, round-robin order
|
||||
|
||||
@@ -152,6 +177,17 @@ export function createState({ services }) {
|
||||
|
||||
state._trackedFrameNowForTest = null;
|
||||
|
||||
// Cockpit orbital-view hold (cockpitSubject.js): the NORAD id the Cockpit
|
||||
// camera rides, and what the hold hid so release restores exactly that.
|
||||
|
||||
state._cockpitSubjectNorad = null;
|
||||
|
||||
state._cockpitHiddenPoints = new Set();
|
||||
|
||||
state._cockpitHiddenPath = null;
|
||||
|
||||
state._cockpitHiddenDot = false;
|
||||
|
||||
/** The time satellites are propagated to, in epoch ms. */
|
||||
|
||||
state.now = worldTimeFor('satellites');
|
||||
|
||||
@@ -43,10 +43,14 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
// Extra catalog/point rows so a test can exercise a docked cluster (and a
|
||||
// control satellite that must NOT be treated as part of it).
|
||||
neighbours = [],
|
||||
// Optional class of the tracked satellite and class visibility, e.g.
|
||||
// { telecom: false }.
|
||||
satelliteClass = undefined,
|
||||
classes = null,
|
||||
}) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._catalog = new Map([
|
||||
[noradId, { name, satrec, group: 'stations' }],
|
||||
[noradId, { name, satrec, group: 'stations', satelliteClass }],
|
||||
]);
|
||||
layerState._points = new Map([[noradId, point]]);
|
||||
for (const neighbour of neighbours) {
|
||||
@@ -54,6 +58,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
name: neighbour.name,
|
||||
satrec: neighbour.satrec || satrec,
|
||||
group: neighbour.group || 'stations',
|
||||
satelliteClass: neighbour.satelliteClass,
|
||||
});
|
||||
layerState._points.set(neighbour.noradId, neighbour.point);
|
||||
}
|
||||
@@ -68,6 +73,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
catalog: 'core',
|
||||
showPoints: false,
|
||||
showOrbits: false,
|
||||
...(classes ? { classes } : {}),
|
||||
};
|
||||
layerState._enabled = true;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
import { entityFollowTarget, stopFollowing } from '../../data/followed.js';
|
||||
import { satelliteClassLabel } from '../../data/satelliteClass.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { clone, scale } from '../../geo/vector.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
@@ -98,6 +98,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedNorad,
|
||||
layerState._catalog.get(layerState._trackedNorad)?.group,
|
||||
),
|
||||
// Back to its class's visibility: a hidden class stays hidden.
|
||||
parts.controls._classVisible(layerState._trackedNorad),
|
||||
);
|
||||
|
||||
// Invalidate the per-frame tracked-position cache (WS-D2)
|
||||
@@ -116,6 +118,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
layerState._trackedEntity = null;
|
||||
}
|
||||
layerState._trackedNorad = null;
|
||||
parts.controls._syncIssOrbit?.();
|
||||
// A held Cockpit subject that stops being tracked gets its marks back.
|
||||
if (layerState._cockpitSubjectNorad !== null)
|
||||
parts.cockpit?._syncCockpitSubjectVisuals();
|
||||
parts.labels._syncIssOverlay();
|
||||
clearTrackedSubjectContext('satellites');
|
||||
layerState._contextRefreshedAtMs = 0;
|
||||
@@ -147,13 +153,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
frameNumber !== layerState._trackedFrameNumber ||
|
||||
layerState._trackedFrameGeo === null
|
||||
) {
|
||||
const pos = parts.orbits.propagatePosition(
|
||||
sat.satrec,
|
||||
layerState._trackedFrameNowForTest
|
||||
? new Date(layerState._trackedFrameNowForTest())
|
||||
: new Date(layerState.now()),
|
||||
);
|
||||
const atMs = layerState._trackedFrameNowForTest
|
||||
? layerState._trackedFrameNowForTest()
|
||||
: layerState.now();
|
||||
const pos = parts.orbits.propagatePosition(sat.satrec, new Date(atMs));
|
||||
if (!pos) return layerState._trackedFrameGeo; // propagation hiccup — keep last good sample
|
||||
// The time the sample is at: the world clock's, not the wall clock's.
|
||||
pos.atMs = atMs;
|
||||
layerState._trackedFrameGeo = pos;
|
||||
fromDegreesInto(
|
||||
pos.longitude,
|
||||
@@ -235,7 +241,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
name,
|
||||
operator: '',
|
||||
noradId: String(noradId),
|
||||
class: satelliteClassLabel(sat.group, {
|
||||
class: satelliteClassText(sat.satelliteClass, sat.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
localize: false,
|
||||
}),
|
||||
@@ -360,7 +366,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
// looking at, and it stays readable under the IR styles that flatten the
|
||||
// dot colors to a single channel (the card is painted above post-FX).
|
||||
const details = [
|
||||
satelliteClassLabel(sat?.group, {
|
||||
satelliteClassText(sat?.satelliteClass, sat?.group, {
|
||||
isIss: layerState._trackedNorad === ISS_NORAD,
|
||||
}),
|
||||
detail,
|
||||
@@ -410,6 +416,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
|
||||
// Show orbital path
|
||||
parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR);
|
||||
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
|
||||
|
||||
// The tracked position propagates per evaluation through the per-frame
|
||||
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* The selected vessel as a Cockpit bridge subject: identity, motion, its
|
||||
* displayed type and a representative bridge eye height from the AIS type.
|
||||
* The Cockpit owns camera placement; this module owns what AIS says.
|
||||
*/
|
||||
import { normalizeVesselType } from '../../data/vesselTypes.js';
|
||||
import { displayVesselType } from '../../data/vesselLabels.js';
|
||||
|
||||
/** The layer id a vessel subject carries through Cockpit events and state. */
|
||||
export const VESSEL_COCKPIT_LAYER_ID = 'ais-live-vessels';
|
||||
|
||||
/** Knots to metres per second, as the AIS source uses. */
|
||||
const KNOTS_TO_MPS = 0.514444;
|
||||
|
||||
/**
|
||||
* Bridge eye height above the waterline by normalized AIS type family. AIS
|
||||
* reports no hull height, so these are representative values: deep-sea
|
||||
* cargo and tanker bridges, passenger and cruise ship bridges, harbour
|
||||
* craft, small craft. River and harbour ferries, matched by name in the
|
||||
* patterns below, sit low. Text types from non-numeric feeds fall through
|
||||
* to the patterns.
|
||||
*/
|
||||
const EYE_HEIGHT_BY_FAMILY = Object.freeze({
|
||||
CARGO: 30,
|
||||
TANKER: 30,
|
||||
PASSENGER: 25,
|
||||
MILITARY: 18,
|
||||
'HIGH-SPEED': 8,
|
||||
DREDGER: 10,
|
||||
TOWING: 7,
|
||||
TUG: 7,
|
||||
PILOT: 6,
|
||||
SAR: 6,
|
||||
'PORT TENDER': 6,
|
||||
'ANTI-POLLUTION': 7,
|
||||
'LAW ENFORCE': 7,
|
||||
MEDICAL: 7,
|
||||
'DIVE OPS': 5,
|
||||
FISHING: 6,
|
||||
SAILING: 3,
|
||||
PLEASURE: 3,
|
||||
// AIS "Other" (90-99) is mostly small craft such as river boats. Only
|
||||
// that type takes it (see isAisOther).
|
||||
OTHER: 4,
|
||||
});
|
||||
|
||||
const EYE_HEIGHT_PATTERNS = Object.freeze([
|
||||
{ pattern: /tanker|cargo|container|bulk|carrier/i, heightM: 30 },
|
||||
{ pattern: /passenger|cruise|ro-?ro/i, heightM: 25 },
|
||||
// River and harbour ferries: a low wheelhouse just above the water.
|
||||
{ pattern: /ferry/i, heightM: 4 },
|
||||
{ pattern: /tug|tow|pilot|supply|service/i, heightM: 7 },
|
||||
{ pattern: /fishing|trawler/i, heightM: 6 },
|
||||
{ pattern: /sail|pleasure|yacht/i, heightM: 3 },
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether a raw type is AIS "Other" proper: codes 90 to 99, or a feed's text
|
||||
* type. normalizeVesselType also files the reserved, wing-in-ground and
|
||||
* spare codes (1-29, 38-39, 56-57, 59) under OTHER, but they name no family.
|
||||
*/
|
||||
function isAisOther(type) {
|
||||
const text = String(type ?? '').trim();
|
||||
if (!/^\d+$/.test(text)) return true;
|
||||
const code = Number(text);
|
||||
return code >= 90 && code <= 99;
|
||||
}
|
||||
|
||||
/**
|
||||
* Representative bridge eye height for an AIS vessel type.
|
||||
* @param {string|number} type Raw AIS type: a numeric code or feed text.
|
||||
* @returns {number|null} Metres above the waterline, or null when the type
|
||||
* names no known family (the Cockpit then uses its default).
|
||||
*/
|
||||
export function vesselEyeHeightM(type) {
|
||||
const family = normalizeVesselType(type).toUpperCase();
|
||||
if (family === 'OTHER' && !isAisOther(type)) return null;
|
||||
if (Object.hasOwn(EYE_HEIGHT_BY_FAMILY, family))
|
||||
return EYE_HEIGHT_BY_FAMILY[family];
|
||||
const matched = EYE_HEIGHT_PATTERNS.find((entry) =>
|
||||
entry.pattern.test(family),
|
||||
);
|
||||
return matched ? matched.heightM : null;
|
||||
}
|
||||
|
||||
function finiteOrNull(value) {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a selected vessel record into Cockpit subject info.
|
||||
*
|
||||
* `track` is where the camera looks and `motionCourse` is where the hull
|
||||
* moves: a ship faces its true heading while current and wind set it along
|
||||
* its course over ground. Either falls back to the other when one is missing.
|
||||
* @param {object|null} record Vessel record from the vessel layer.
|
||||
* @returns {object|null} Subject info, or null without a usable fix.
|
||||
*/
|
||||
export function vesselCockpitInfo(record) {
|
||||
if (!record?.mmsi) return null;
|
||||
const latitude = Number(record.lat);
|
||||
const longitude = Number(record.lon);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
const heading = finiteOrNull(record.heading);
|
||||
const course = finiteOrNull(record.course);
|
||||
const speedKt = finiteOrNull(record.speed);
|
||||
const epochSec = finiteOrNull(record.lastPositionEpoch);
|
||||
const feedEpochSec = finiteOrNull(record.fixFeedEpoch);
|
||||
return {
|
||||
kind: 'vessel',
|
||||
layerId: VESSEL_COCKPIT_LAYER_ID,
|
||||
id: String(record.mmsi),
|
||||
mmsi: String(record.mmsi),
|
||||
name: String(record.name || record.mmsi),
|
||||
type: String(record.type || ''),
|
||||
typeLabel: displayVesselType(record.type),
|
||||
destination: String(record.destination || '').trim(),
|
||||
latitude,
|
||||
longitude,
|
||||
heading,
|
||||
course,
|
||||
speedKt,
|
||||
velocityMps: speedKt === null ? null : Math.max(0, speedKt) * KNOTS_TO_MPS,
|
||||
track: heading ?? course,
|
||||
// What `track` is: the true heading, or course over ground standing in
|
||||
// for a ship that reports none. The HUD says which.
|
||||
trackSource:
|
||||
heading !== null ? 'heading' : course !== null ? 'course' : null,
|
||||
motionCourse: course ?? heading,
|
||||
fixEpochMs: epochSec === null ? null : epochSec * 1000,
|
||||
// When this client first received the fix (its own clock) and the
|
||||
// newest fix in that refresh (the feed's clock): the fix's age without
|
||||
// clock skew, still ageing while the feed re-serves it.
|
||||
receivedAtMs: finiteOrNull(record.fixReceivedAtMs),
|
||||
feedEpochMs: feedEpochSec === null ? null : feedEpochSec * 1000,
|
||||
eyeHeightM: vesselEyeHeightM(record.type),
|
||||
stale: (record.missedRefreshes || 0) > 0,
|
||||
onGround: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// src/layers/vessels/cockpitSubject.test.mjs — bridge eye heights by AIS
|
||||
// type and the selected vessel as Cockpit subject info.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
VESSEL_COCKPIT_LAYER_ID,
|
||||
vesselCockpitInfo,
|
||||
vesselEyeHeightM,
|
||||
} from './cockpitSubject.js';
|
||||
|
||||
test('bridge eye height follows the AIS type family', () => {
|
||||
assert.equal(vesselEyeHeightM('71'), 30, 'cargo');
|
||||
assert.equal(vesselEyeHeightM('84'), 30, 'tanker');
|
||||
assert.equal(vesselEyeHeightM('60'), 25, 'passenger');
|
||||
assert.equal(vesselEyeHeightM('52'), 7, 'tug');
|
||||
assert.equal(vesselEyeHeightM('30'), 6, 'fishing');
|
||||
assert.equal(vesselEyeHeightM('37'), 3, 'pleasure');
|
||||
assert.equal(vesselEyeHeightM('36'), 3, 'sailing');
|
||||
});
|
||||
|
||||
test('text vessel types resolve through the same families', () => {
|
||||
assert.equal(vesselEyeHeightM('Container Ship'), 30);
|
||||
assert.equal(vesselEyeHeightM('Cruise ship'), 25);
|
||||
assert.equal(vesselEyeHeightM('Ferry'), 4);
|
||||
assert.equal(vesselEyeHeightM(99), 4, 'AIS Other');
|
||||
assert.equal(vesselEyeHeightM('90'), 4, 'AIS Other');
|
||||
assert.equal(vesselEyeHeightM('Other'), 4, 'a feed text type Other');
|
||||
assert.equal(vesselEyeHeightM('Yacht'), 3);
|
||||
});
|
||||
|
||||
test('codes filed under OTHER that are not AIS Other keep the default', () => {
|
||||
// Reserved (1-19), wing in ground (20-29), reserved (38-39), spare
|
||||
// (56-57) and local (59) codes name no family.
|
||||
for (const type of ['1', '19', '20', '29', '38', '39', '56', '57', '59'])
|
||||
assert.equal(vesselEyeHeightM(type), null, type);
|
||||
});
|
||||
|
||||
test('an unknown or missing type has no eye height of its own', () => {
|
||||
for (const type of ['', '0', '255', 'Research vessel', null]) {
|
||||
assert.equal(vesselEyeHeightM(type), null, String(type));
|
||||
}
|
||||
});
|
||||
|
||||
test('vessel info faces the true heading and moves along course over ground', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
mmsi: '211000000',
|
||||
name: 'NORDIC STAR',
|
||||
type: '70',
|
||||
destination: ' KIEL ',
|
||||
lat: 54.5,
|
||||
lon: 10.2,
|
||||
speed: 12,
|
||||
course: 95,
|
||||
heading: 90,
|
||||
lastPositionEpoch: 1_700_000_000,
|
||||
missedRefreshes: 0,
|
||||
});
|
||||
assert.equal(info.kind, 'vessel');
|
||||
assert.equal(info.layerId, VESSEL_COCKPIT_LAYER_ID);
|
||||
assert.equal(info.id, '211000000');
|
||||
assert.equal(info.typeLabel, 'CARGO');
|
||||
assert.equal(info.track, 90);
|
||||
assert.equal(info.motionCourse, 95);
|
||||
assert.equal(info.destination, 'KIEL');
|
||||
assert.equal(info.eyeHeightM, 30);
|
||||
assert.equal(info.fixEpochMs, 1_700_000_000_000);
|
||||
assert.ok(Math.abs(info.velocityMps - 12 * 0.514444) < 1e-9);
|
||||
assert.equal(info.stale, false);
|
||||
assert.equal(info.onGround, false);
|
||||
});
|
||||
|
||||
test('a missing heading or course falls back to the other', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(vesselCockpitInfo({ ...base, course: 40 }).track, 40);
|
||||
assert.equal(vesselCockpitInfo({ ...base, heading: 50 }).motionCourse, 50);
|
||||
const neither = vesselCockpitInfo(base);
|
||||
assert.equal(neither.track, null);
|
||||
assert.equal(neither.motionCourse, null);
|
||||
});
|
||||
|
||||
test('the subject says whether its track is the heading or the course', () => {
|
||||
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, heading: 50, course: 40 }).trackSource,
|
||||
'heading',
|
||||
);
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, course: 40 }).trackSource,
|
||||
'course',
|
||||
);
|
||||
// A heading of 0 is due north, not a missing heading.
|
||||
assert.equal(
|
||||
vesselCockpitInfo({ ...base, heading: 0 }).trackSource,
|
||||
'heading',
|
||||
);
|
||||
assert.equal(vesselCockpitInfo(base).trackSource, null);
|
||||
});
|
||||
|
||||
test('a vessel without identity or position is not a subject', () => {
|
||||
assert.equal(vesselCockpitInfo(null), null);
|
||||
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
|
||||
assert.equal(vesselCockpitInfo({ mmsi: '1', lat: 'x', lon: 1 }), null);
|
||||
});
|
||||
|
||||
test('a vessel missing from recent refreshes reads as stale', () => {
|
||||
const info = vesselCockpitInfo({
|
||||
mmsi: '1',
|
||||
lat: 1,
|
||||
lon: 1,
|
||||
missedRefreshes: 2,
|
||||
});
|
||||
assert.equal(info.stale, true);
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { t, msg } from '../../i18n/index.js';
|
||||
import { vesselCockpitInfo } from './cockpitSubject.js';
|
||||
import { vesselTypeCss } from '../../data/vesselLabels.js';
|
||||
import { greatCircleMeters } from '../../geoDistance.js';
|
||||
|
||||
// ingestion.js is a portable export (package.json) and writes English labels
|
||||
// into state; translate the known ones here, pass anything else through.
|
||||
@@ -20,6 +23,7 @@ import {
|
||||
AIS_STATUS_REASON,
|
||||
REFRESH_MS,
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
VESSEL_LIFT_M,
|
||||
} from './policy.js';
|
||||
|
||||
export function createQueries({
|
||||
@@ -343,6 +347,59 @@ export function createQueries({
|
||||
return entries.slice(0, cap);
|
||||
},
|
||||
|
||||
/**
|
||||
* Vessels around a point for the Cockpit bridge radar, nearest first.
|
||||
* The ship whose bridge the Cockpit occupies is left out. Distances are
|
||||
* great-circle from the AIS positions, so no rendered visual is needed.
|
||||
* @param {number} lat Latitude of the centre, degrees.
|
||||
* @param {number} lon Longitude of the centre, degrees.
|
||||
* @param {number} rangeM Max distance in metres.
|
||||
* @param {number} [maxCount=60] Maximum entries to return.
|
||||
* @returns {Array<{ id: string, name: string, latitude: number,
|
||||
* longitude: number, course: number|null, heading: number|null,
|
||||
* type: string, color: string, stale: boolean }>} Empty while the
|
||||
* layer is off. A ship with no MMSI has an `unkeyed:` id.
|
||||
*/
|
||||
getRadarContacts(lat, lon, rangeM, maxCount = 60) {
|
||||
const records = state.records.all;
|
||||
if (!state.feed.enabled || !Array.isArray(records) || !records.length)
|
||||
return [];
|
||||
if (!Number.isFinite(rangeM) || rangeM <= 0) return [];
|
||||
const cap =
|
||||
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 60;
|
||||
const center = { lat, lon };
|
||||
const subject = state.cockpitSubjectMmsi;
|
||||
const finite = (value) => {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
};
|
||||
|
||||
const entries = [];
|
||||
records.forEach((record, index) => {
|
||||
if (subject && String(record.mmsi) === subject) return;
|
||||
const distanceM = greatCircleMeters(center, {
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
});
|
||||
if (!(distanceM <= rangeM)) return;
|
||||
entries.push({ record, index, distanceM });
|
||||
});
|
||||
entries.sort((a, b) => a.distanceM - b.distanceM);
|
||||
return entries.slice(0, cap).map(({ record, index }) => ({
|
||||
// A ship with no MMSI still needs a key of its own on the scope.
|
||||
id: record.mmsi ? String(record.mmsi) : `unkeyed:${index}`,
|
||||
name: String(record.name || record.mmsi || ''),
|
||||
latitude: record.lat,
|
||||
longitude: record.lon,
|
||||
course: finite(record.course),
|
||||
heading: finite(record.heading),
|
||||
type: String(record.type || ''),
|
||||
color: vesselTypeCss(record.type),
|
||||
stale: (record.missedRefreshes || 0) > 0,
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get positions of all currently loaded vessels.
|
||||
* @param {number} [maxCount=800] Maximum entries to return.
|
||||
@@ -458,6 +515,55 @@ export function createQueries({
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Describe the selected vessel for the Cockpit bridge view.
|
||||
* @returns {object|null} `vesselCockpitInfo` fields plus `seaSurfaceHeightM`
|
||||
* (the local geoid height the sprite datum uses) and `markHeightM` (the
|
||||
* height the sprite is drawn at), or null when the layer is off or
|
||||
* nothing is selected.
|
||||
*/
|
||||
getCockpitSubject() {
|
||||
if (!state.feed.enabled) return null;
|
||||
const info = vesselCockpitInfo(state.selectedRecord);
|
||||
if (!info) return null;
|
||||
const geoidN = components.tracking.currentGeoidN(
|
||||
info.latitude,
|
||||
info.longitude,
|
||||
);
|
||||
return {
|
||||
...info,
|
||||
seaSurfaceHeightM: vesselDatumHeightM(geoidN, 0),
|
||||
markHeightM: vesselDatumHeightM(geoidN, VESSEL_LIFT_M),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark the vessel whose bridge the Cockpit camera occupies, or release it.
|
||||
* Its sprite, card and detection bracket stay hidden while it is held.
|
||||
* @param {string|number|null} mmsi Subject MMSI, or null to release.
|
||||
* @returns {boolean} Always true.
|
||||
*/
|
||||
setCockpitSubject(mmsi) {
|
||||
const next = normalizeSelectionMmsi(mmsi);
|
||||
if (state.cockpitSubjectMmsi === next) return true;
|
||||
state.cockpitSubjectMmsi = next;
|
||||
// The ridden ship's trail runs from under the eye: hidden, its history
|
||||
// kept, while the bridge holds the ship it belongs to.
|
||||
state.trail?.setVisible?.(!next || next !== state.trailMmsi);
|
||||
components.rendering.updateVisibility(true);
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the camera to the selected vessel's map view, as a click on it does.
|
||||
* @returns {boolean} True when a selected vessel took the camera.
|
||||
*/
|
||||
focusSelectedVessel() {
|
||||
const record = state.selectedRecord;
|
||||
if (!record || !state.feed.enabled) return false;
|
||||
return components.selection.selectAndFocusVessel(record);
|
||||
},
|
||||
|
||||
/**
|
||||
* Return a subset of vessels for the universal detection overlay.
|
||||
* Deterministic stride sampling distributes selections evenly across the
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// src/layers/vessels/radarContacts.test.mjs — the vessels the Cockpit bridge
|
||||
// radar draws: within range, nearest first, without the ship it rides; and
|
||||
// the ridden ship's own trail, hidden while the bridge holds it.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createVesselLayer } from './index.js';
|
||||
import { vesselTypeCss } from '../../data/vesselLabels.js';
|
||||
|
||||
const noop = () => {};
|
||||
function services() {
|
||||
return {
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
registerEntityContext: () => null,
|
||||
},
|
||||
trails: {
|
||||
createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }),
|
||||
},
|
||||
labels: {},
|
||||
picking: { unregisterPickOwner: noop },
|
||||
overlay: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
geoid: {},
|
||||
sprites: {},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
forgetSpriteFocus: noop,
|
||||
},
|
||||
worldFocus: {},
|
||||
render: {
|
||||
holdContinuousRender: noop,
|
||||
releaseContinuousRender: noop,
|
||||
governorRequestRender: noop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A vessel `northNm` nautical miles north of 54.5°N 10.2°E. */
|
||||
function record(mmsi, northNm, extra = {}) {
|
||||
return {
|
||||
mmsi,
|
||||
name: `SHIP ${mmsi}`,
|
||||
type: '70',
|
||||
lat: 54.5 + northNm / 60,
|
||||
lon: 10.2,
|
||||
speed: 10,
|
||||
course: 45,
|
||||
heading: 40,
|
||||
missedRefreshes: 0,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function layerWith(records, options = {}) {
|
||||
const layer = createVesselLayer({
|
||||
source: { getSnapshot: noop },
|
||||
services: services(),
|
||||
});
|
||||
layer.testing._setVesselStateForTest({
|
||||
viewer: {},
|
||||
records,
|
||||
billboardCollection: { add: (entry) => ({ ...entry }), remove: noop },
|
||||
...options,
|
||||
});
|
||||
return layer;
|
||||
}
|
||||
|
||||
test('radar contacts are within range, nearest first and capped', () => {
|
||||
const layer = layerWith([
|
||||
record('3', 5),
|
||||
record('1', 1),
|
||||
record('far', 20),
|
||||
record('2', 3, { course: null, heading: '', missedRefreshes: 2 }),
|
||||
]);
|
||||
const contacts = layer.getRadarContacts(54.5, 10.2, 6 * 1852, 60);
|
||||
assert.deepEqual(
|
||||
contacts.map((entry) => entry.id),
|
||||
['1', '2', '3'],
|
||||
);
|
||||
assert.deepEqual(contacts[0], {
|
||||
id: '1',
|
||||
name: 'SHIP 1',
|
||||
latitude: 54.5 + 1 / 60,
|
||||
longitude: 10.2,
|
||||
course: 45,
|
||||
heading: 40,
|
||||
type: '70',
|
||||
color: vesselTypeCss('70'),
|
||||
stale: false,
|
||||
});
|
||||
assert.equal(contacts[1].course, null);
|
||||
assert.equal(contacts[1].heading, null);
|
||||
assert.equal(contacts[1].stale, true);
|
||||
assert.deepEqual(
|
||||
layer.getRadarContacts(54.5, 10.2, 6 * 1852, 2).map((entry) => entry.id),
|
||||
['1', '2'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the ship whose bridge the Cockpit rides is not its own contact', () => {
|
||||
const layer = layerWith([record('own', 0), record('other', 2)]);
|
||||
layer.setCockpitSubject('own');
|
||||
assert.deepEqual(
|
||||
layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((entry) => entry.id),
|
||||
['other'],
|
||||
);
|
||||
layer.setCockpitSubject(null);
|
||||
assert.equal(layer.getRadarContacts(54.5, 10.2, 6 * 1852).length, 2);
|
||||
});
|
||||
|
||||
test('ships with no MMSI each keep a key of their own', () => {
|
||||
const layer = layerWith([
|
||||
record('', 1, { name: 'A' }),
|
||||
record('', 2, { name: 'B' }),
|
||||
]);
|
||||
const ids = layer.getRadarContacts(54.5, 10.2, 6 * 1852).map((c) => c.id);
|
||||
assert.equal(ids.length, 2);
|
||||
assert.equal(new Set(ids).size, 2, ids.join(', '));
|
||||
assert.ok(ids.every((id) => id.startsWith('unkeyed:')));
|
||||
});
|
||||
|
||||
test("the ridden ship's trail is hidden while the bridge holds it", () => {
|
||||
const shown = [];
|
||||
const trail = {
|
||||
setPositions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
setVisible: (visible) => shown.push(visible),
|
||||
};
|
||||
const layer = layerWith([record('own', 0), record('other', 2)], {
|
||||
trail,
|
||||
trailMmsi: 'own',
|
||||
});
|
||||
layer.setCockpitSubject('own');
|
||||
assert.deepEqual(shown, [false]);
|
||||
layer.setCockpitSubject(null);
|
||||
assert.deepEqual(shown, [false, true]);
|
||||
});
|
||||
|
||||
test('a disabled layer has no radar contacts', () => {
|
||||
const layer = layerWith([record('1', 1)], { enabled: false });
|
||||
assert.deepEqual(layer.getRadarContacts(54.5, 10.2, 6 * 1852), []);
|
||||
});
|
||||
@@ -26,6 +26,18 @@ export function normalizeVessel(row) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Note when a fix was first received (`fixReceivedAtMs`, this client's
|
||||
* clock) and the newest fix in that refresh (`fixFeedEpoch`, the feed's
|
||||
* clock): its age is then read on each clock separately, so neither a
|
||||
* skewed client clock nor a re-served cached row hides how old it is.
|
||||
* `receivedAtMs` stays the time the row was last seen, for retention.
|
||||
*/
|
||||
function stampFix(record, receivedAtMs, feedLatestEpoch) {
|
||||
record.fixReceivedAtMs = receivedAtMs;
|
||||
record.fixFeedEpoch = feedLatestEpoch;
|
||||
}
|
||||
|
||||
function finiteNumber(value) {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
@@ -46,6 +58,18 @@ export class VesselRecords {
|
||||
effects,
|
||||
) {
|
||||
const receivedAtMs = this.now();
|
||||
// The newest fix in the batch: the feed's own "now", so a fix's age can
|
||||
// be read on the feed's clock rather than against this client's (see
|
||||
// stampFix).
|
||||
let feedLatestEpoch = null;
|
||||
for (const row of rows) {
|
||||
const epoch = finiteNumber(row?.last_position_epoch);
|
||||
if (
|
||||
epoch !== null &&
|
||||
(feedLatestEpoch === null || epoch > feedLatestEpoch)
|
||||
)
|
||||
feedLatestEpoch = epoch;
|
||||
}
|
||||
for (const record of this.unkeyed) effects.remove(record, false);
|
||||
this.unkeyed = [];
|
||||
const seen = new Set();
|
||||
@@ -53,6 +77,7 @@ export class VesselRecords {
|
||||
const next = normalizeVessel(row);
|
||||
if (!next) continue;
|
||||
next.receivedAtMs = receivedAtMs;
|
||||
stampFix(next, receivedAtMs, feedLatestEpoch);
|
||||
if (!next.mmsi) {
|
||||
effects.add(next);
|
||||
this.unkeyed.push(next);
|
||||
@@ -62,6 +87,12 @@ export class VesselRecords {
|
||||
seen.add(next.mmsi);
|
||||
const record = this.byMmsi.get(next.mmsi);
|
||||
if (record) {
|
||||
// A feed re-serving a cached row repeats its fix: the fix keeps the
|
||||
// time it was first received, so it goes on ageing.
|
||||
if (next.lastPositionEpoch !== record.lastPositionEpoch) {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
record.reference = next.reference;
|
||||
record.receivedAtMs = next.receivedAtMs;
|
||||
record.lat = next.lat;
|
||||
|
||||
@@ -117,3 +117,33 @@ test('unkeyed records rebuild on each refresh and numeric coercion keeps unknown
|
||||
assert.equal(probe.store.all.length, 1);
|
||||
assert.equal(normalizeVessel(row('bad', { lon: Infinity })), null);
|
||||
});
|
||||
|
||||
test("each fix keeps when it was first received and its refresh's newest fix", () => {
|
||||
const probe = setup();
|
||||
probe.reconcile([
|
||||
row('111', { last_position_epoch: 1_800_000_000 }),
|
||||
row('222', { last_position_epoch: 1_800_000_030 }),
|
||||
row('333'),
|
||||
]);
|
||||
for (const mmsi of ['111', '222', '333']) {
|
||||
const record = probe.store.byMmsi.get(mmsi);
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_030, mmsi);
|
||||
assert.equal(record.fixReceivedAtMs, 1000, mmsi);
|
||||
}
|
||||
// A new fix is stamped afresh.
|
||||
probe.advance(60_000);
|
||||
probe.reconcile([row('111', { last_position_epoch: 1_800_000_050 })]);
|
||||
const record = probe.store.byMmsi.get('111');
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.fixReceivedAtMs, 61_000);
|
||||
// The same fix re-served by later polls keeps its first receipt, while
|
||||
// the row itself counts as seen for retention.
|
||||
probe.advance(30_000);
|
||||
probe.reconcile([
|
||||
row('111', { last_position_epoch: 1_800_000_050 }),
|
||||
row('222', { last_position_epoch: 1_800_000_090 }),
|
||||
]);
|
||||
assert.equal(record.fixReceivedAtMs, 61_000);
|
||||
assert.equal(record.fixFeedEpoch, 1_800_000_050);
|
||||
assert.equal(record.receivedAtMs, 91_000);
|
||||
});
|
||||
@@ -152,12 +152,37 @@ export function createRendering({
|
||||
state.icons = null;
|
||||
}
|
||||
|
||||
/** Whether the Cockpit's bridge camera rides this record's ship. */
|
||||
function isCockpitSubject(record) {
|
||||
return (
|
||||
Boolean(state.cockpitSubjectMmsi) &&
|
||||
record.mmsi === state.cockpitSubjectMmsi
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redraw the icons of the ship the bridge camera rode and the one it now
|
||||
* rides: the camera sits on the ridden ship's icon, which would fill the
|
||||
* view, so it is hidden while held.
|
||||
*/
|
||||
function syncCockpitSubjectIcon() {
|
||||
const held = state.cockpitSubjectMmsi || null;
|
||||
if (vesselState._iconHiddenMmsi === held) return;
|
||||
const before = vesselState._iconHiddenMmsi;
|
||||
vesselState._iconHiddenMmsi = held;
|
||||
for (const mmsi of [before, held]) {
|
||||
const record = mmsi ? state.records.byMmsi.get(mmsi) : null;
|
||||
if (record) syncRecordIcon(record);
|
||||
}
|
||||
}
|
||||
|
||||
/** The icon item a record draws, as it now is. */
|
||||
function iconItem(record, visual) {
|
||||
const selected = record === state.selectedRecord;
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
return {
|
||||
id: visual.iconId,
|
||||
show: !isCockpitSubject(record),
|
||||
pos: visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
@@ -341,6 +366,7 @@ export function createRendering({
|
||||
}
|
||||
|
||||
const query = state.viewer ? findQuery(state.viewer) : null;
|
||||
syncCockpitSubjectIcon();
|
||||
if (regularPass) {
|
||||
// Candidate construction stays on the original 800 ms selector cadence.
|
||||
// The 80 ms focus-only pass below never allocates label candidates.
|
||||
@@ -466,7 +492,11 @@ export function createRendering({
|
||||
const viewer = state.viewer;
|
||||
const query = viewer ? findQuery(viewer) : null;
|
||||
const selected = state.selectedRecord;
|
||||
const entries = selected
|
||||
// From the bridge, the selected vessel is the viewer; its card would be
|
||||
// pinned to the camera position.
|
||||
const selectedCarded =
|
||||
selected && selected.mmsi !== state.cockpitSubjectMmsi;
|
||||
const entries = selectedCarded
|
||||
? [components.cards.buildSelectedVesselCard(selected)]
|
||||
: [];
|
||||
const maxLabels = labelRowLimit();
|
||||
@@ -515,7 +545,7 @@ export function createRendering({
|
||||
// Greedy min-separation pass over the priority-ranked cell winners: the
|
||||
// selected card's anchor seeds the accepted set so ambient cards keep clear.
|
||||
const accepted = [];
|
||||
if (selected) {
|
||||
if (selectedCarded) {
|
||||
const screen = query.project(iconPosition(selected));
|
||||
if (screen) accepted.push({ x: screen.x, y: screen.y });
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ export function createSelection({
|
||||
function bindVesselInteraction(viewer, keyTarget) {
|
||||
state.clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state.feed.enabled) return;
|
||||
// The bridge view owns the selection: a click on open water must not
|
||||
// deselect the vessel the camera is riding.
|
||||
if (state.cockpitSubjectMmsi) return;
|
||||
const pickedId = event.id;
|
||||
let record = pickedId ? state.records.byMmsi.get(pickedId) : null;
|
||||
// A vessel icon's pick is an item of the layer's icon set, whose id is
|
||||
|
||||
@@ -46,6 +46,8 @@ export function createVesselState({ source, services }) {
|
||||
/** Row ids for unkeyed (no-MMSI) records, which are rebuilt every poll. */
|
||||
|
||||
vesselState._unkeyedIconSequence = 0;
|
||||
// The ship whose icon is hidden under the bridge camera (cockpit subject).
|
||||
vesselState._iconHiddenMmsi = null;
|
||||
|
||||
vesselState.state = {
|
||||
feed: createVesselFeed(),
|
||||
@@ -73,6 +75,8 @@ export function createVesselState({ source, services }) {
|
||||
activeFocusCount: 0,
|
||||
activeLabelCount: 0,
|
||||
selectedRecord: null,
|
||||
/** @type {string|null} MMSI whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
|
||||
cockpitSubjectMmsi: null,
|
||||
/** @type {{setPositions: Function, clear: Function, destroy: Function}|null} Selected-vessel fading trail */
|
||||
trail: null,
|
||||
/** @type {{x: number, y: number, z: number}[]} Chronological ECEF trail vertices (oldest first) */
|
||||
|
||||
Reference in new issue
Block a user