Merge upstream main into pr/street-level-show-action

Locale conflicts: main's catalogs plus the PR's 10 street-level strings.
This commit is contained in:
Said Turksever committed 2026-11-09 00:22:26 +00:00
commit 7efcf37c62
55 files changed
+2773 -393

No files matched your search

+12
View File
@@ -124,6 +124,10 @@ export function createCatalog({ state: layerState, services, parts, source }) {
satrec,
group: 'dense',
launchYear: tleLineLaunchYear(entry.line1),
// The dense feed is CelesTrak's Starlink group.
satelliteClass: 'starlink',
ucs: null,
satcat: null,
});
const point = layerState._pointCollection.add({
position: Cesium.Cartesian3.fromDegrees(
@@ -204,6 +208,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();
+309
View File
@@ -0,0 +1,309 @@
/**
* @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';
}
/**
* 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;
}
/** 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,
* 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'),
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),
launchDate: text(col.launch) || null,
});
}
return records;
}
+487
View File
@@ -0,0 +1,487 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_SATELLITE_CLASSES,
PRESUMED_DEAD_AFTER_YEARS,
SATELLITE_CLASS_DISPLAY,
SATELLITE_CLASS_IDS,
classifySatellite,
mergeClassVisibility,
parseSatcatCsv,
} from './classes.js';
import { CATALOG_GROUPS } from './policy.js';
const NOW = 2026;
const classify = (subject) => classifySatellite({ nowYear: NOW, ...subject });
test('six classes, every one but Starlink on by default', () => {
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('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('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: '+',
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);
});
test('turning Stations off takes the ISS ring and label with its point', async () => {
const { createControls } = await import('./controls.js');
let overlaySyncs = 0;
const ring = { primitive: { show: true } };
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, ring]]),
_detectionObjects: new Map(),
_trackedNorad: null,
};
const controls = createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: { labels: { _syncIssOverlay: () => (overlaySyncs += 1) } },
source: {},
});
controls._applyClassVisibility();
assert.equal(state._points.get(25544).show, false);
assert.equal(ring.primitive.show, 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(ring.primitive.show, 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');
const iss = { primitive: { show: false } };
const other = { primitive: { show: false } };
let issVisible = false;
const state = {
_params: { showPoints: true, showOrbits: true },
_orbitPaths: new Map([
[25544, iss],
[90001, other],
]),
_points: new Map(),
coverageChanged() {},
};
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(iss.primitive.show, false, 'the ISS ring follows its class');
assert.equal(other.primitive.show, true, 'other rings follow showOrbits');
issVisible = true;
methods.enable(null);
assert.equal(iss.primitive.show, 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 ring = { primitive: { show: true } };
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, ring]]),
_detectionObjects: new Map(),
_trackedNorad: null,
};
const controls = createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: { labels: { _syncIssOverlay() {} } },
source: {},
});
controls._syncIssOrbit();
assert.equal(ring.primitive.show, false);
state._trackedNorad = 25544;
controls._syncIssOrbit();
assert.equal(ring.primitive.show, true, 'tracked, it keeps its ring');
state._params.showOrbits = false;
controls._syncIssOrbit();
assert.equal(ring.primitive.show, false, 'orbits off still hides it');
});
+230 -79
View File
@@ -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 * as Cesium from 'cesium';
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). The ISS's ring and label go
* with its class.
*/
function _applyClassVisibility() {
for (const [noradId, point] of layerState._points) {
if (noradId === layerState._trackedNorad) continue;
point.show = _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() {
const issPath = layerState._orbitPaths.get(ISS_NORAD);
if (issPath) issPath.primitive.show = _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,6 +246,8 @@ export function createControls({ state: layerState, services, parts, source }) {
if (!shouldTake) continue;
if (!point.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 —
@@ -141,15 +260,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 = point.position;
object.skipLabel = isTracked;
result.push(object);
@@ -225,6 +345,7 @@ export function createControls({ state: layerState, services, parts, source }) {
for (const [noradId, point] of layerState._points) {
if (result.length >= cap) break;
if (!point.position) continue;
if (!_classVisible(noradId)) continue;
// Dense extras are points-only — keep voice/framing lists to the core catalog.
if (
layerState._denseIds.length > 0 &&
@@ -383,9 +504,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 (
@@ -394,9 +517,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,
@@ -414,11 +556,14 @@ export function createControls({ state: layerState, services, parts, source }) {
}
if (params.showOrbits !== undefined) {
layerState._params.showOrbits = params.showOrbits !== false;
for (const path of layerState._orbitPaths.values())
path.primitive.show = satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
for (const [noradId, path] of layerState._orbitPaths)
path.primitive.show =
noradId === ISS_NORAD
? _issOrbitVisible()
: satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
parts.labels._syncIssOverlay();
}
if (catalogChanged && catalog === 'dense') {
@@ -434,6 +579,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,
@@ -465,25 +617,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
@@ -492,48 +648,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() };
},
/**
@@ -562,6 +706,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,
};
},
};
@@ -570,6 +717,10 @@ export function createControls({ state: layerState, services, parts, source }) {
_pointStyleFor,
_notifyRowControls,
_classTally,
_classVisible,
_applyClassVisibility,
_issOrbitVisible,
_syncIssOrbit,
satelliteVisualsVisible,
satelliteCatalogModeChanged,
methods,
+207 -4
View File
@@ -3,6 +3,21 @@ import * as Cesium from 'cesium';
import { msg } from '../../i18n/index.js';
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
import { CATALOG_GROUPS, ISS_NORAD, POINT_STYLES } from './policy.js';
import { classifySatellite, parseSatcatCsv } from './classes.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 +25,141 @@ export function createIngestion({
parts,
source,
}) {
/**
* The local pack the classes are read from: the UCS pack. It is not needed
* to render: a failed read leaves the last pack (or none) and
* classification falls back to names and groups.
*/
async function _readLocalEvidence() {
if (layerState._ucs) return;
const pack = await Promise.resolve()
.then(() => source.readUcs?.())
.then((loaded) => (loaded instanceof Map ? loaded : null))
.catch((error) => {
console.warn('[Data:Satellites] UCS pack unavailable:', error);
return null;
});
if (pack) layerState._ucs = pack;
}
/**
* 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;
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;
const point = layerState._points.get(noradId);
if (point) {
const style = parts.controls._pointStyleFor(noradId, sat.group);
point.pixelSize = style.pixelSize;
point.color = style.color;
point.outlineColor = style.outlineColor;
point.outlineWidth = style.outlineWidth;
}
}
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 +177,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 +203,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 +232,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)) {
@@ -112,6 +282,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;
@@ -125,12 +307,32 @@ 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,
satelliteClass: classifySatellite({
noradId,
name: entry.name,
group: entry.group,
groups,
ucs,
satcat,
launchYear,
}),
ucs,
satcat,
});
coreStale ||= entry.stale;
@@ -156,6 +358,8 @@ export function createIngestion({
scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6),
id: noradId,
});
// Hidden classes keep their point, so a toggle needs no rebuild.
point.show = parts.controls._classVisible(noradId);
layerState._points.set(noradId, point);
}
@@ -163,8 +367,7 @@ export function createIngestion({
// Show ISS orbital path by default
if (layerState._catalog.has(ISS_NORAD)) {
parts.rendering._showOrbitPath(ISS_NORAD, POINT_STYLES.iss.color);
const issPath = layerState._orbitPaths.get(ISS_NORAD);
if (issPath) issPath.primitive.show = layerState._params.showOrbits;
parts.controls._syncIssOrbit();
parts.labels._syncIssOverlay();
}
+177 -5
View File
@@ -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 =
@@ -18,7 +23,7 @@ function tleSet(name, field) {
].join('\n');
}
function ingestionFor(catalogText) {
function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
const state = {
_trackingRefreshEpoch: 0,
_activeUpdateControllers: new Set(),
@@ -33,6 +38,8 @@ function ingestionFor(catalogText) {
_denseLoadToken: 0,
_catalogRevision: 0,
_params: { catalog: 'core', showOrbits: false },
_satcat: new Map(),
_ucs: null,
now: Date.now,
coverageChanged() {},
};
@@ -42,7 +49,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: { _showOrbitPath() {} },
tracking: {
async _reconcileTrackedSubjectContext() {},
@@ -51,9 +68,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({ scene: {} }) };
@@ -121,3 +141,155 @@ 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');
});
+3
View File
@@ -83,6 +83,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}`,
);
@@ -102,6 +104,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);
+13 -6
View File
@@ -1,5 +1,9 @@
import * as Cesium from 'cesium';
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({
@@ -88,11 +92,14 @@ export function createLifecycle({
layerState._params.showPoints,
);
// Orbit ring primitives + persistent ISS host label — show them
for (const path of layerState._orbitPaths.values())
path.primitive.show = parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
for (const [noradId, path] of layerState._orbitPaths)
path.primitive.show =
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);
+45 -3
View File
@@ -1,12 +1,16 @@
import * as Cesium from 'cesium';
import { satelliteClassColor } from '../../data/satelliteClass.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 via PointPrimitiveCollection, 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
@@ -166,6 +177,37 @@ export const POINT_STYLES = {
},
};
const CLASS_COLORS = Object.fromEntries(
SATELLITE_CLASS_IDS.map((id) => [
id,
Cesium.Color.fromCssColorString(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' ? color.withAlpha(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
+12 -2
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { satelliteClassLabel } from '../../data/satelliteClass.js';
import { satelliteClassText } from '../../data/satelliteClass.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,
+2 -1
View File
@@ -152,7 +152,8 @@ export function createRendering({
/**
* Propagate all CORE satellite positions and update point primitives.
* (~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.
*/
+36
View File
@@ -6,11 +6,24 @@ 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();
}
/** Read catalog text from the existing group endpoint using a supplied transport. */
export function createSatelliteSource({
fetchImpl = (...args) => globalThis.fetch(...args),
loadUcs = loadBundledUcs,
} = {}) {
return {
async readGroup(group, { signal } = {}) {
@@ -24,5 +37,28 @@ 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();
},
};
}
+21
View File
@@ -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);
});
+23 -15
View File
@@ -24,7 +24,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.
@@ -143,10 +151,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']);
@@ -163,13 +171,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,
@@ -182,7 +190,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);
});
@@ -194,17 +202,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);
@@ -216,11 +224,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();
@@ -261,13 +269,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');
});
@@ -277,7 +285,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);
@@ -288,6 +296,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');
});
+24 -2
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { DEFAULT_SATELLITE_CLASSES } from './classes.js';
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
export function createState({ services }) {
@@ -14,7 +15,9 @@ export function createState({ services }) {
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
// Satellite catalog: { noradId → { name, satrec, group } }
// Satellite catalog: { noradId → { name, satrec, group, launchYear,
// satelliteClass, ucs, satcat } } — class, UCS and SATCAT records from
// src/layers/satellites/classes.js and the sources the update read.
state._catalog = new Map();
@@ -43,6 +46,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();
@@ -93,9 +102,22 @@ 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;
state._denseIds = [];
// norad ids of dense extras, round-robin order
+7 -1
View File
@@ -26,10 +26,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) {
@@ -37,6 +41,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);
}
@@ -51,6 +56,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
catalog: 'core',
showPoints: false,
showOrbits: false,
...(classes ? { classes } : {}),
};
layerState._enabled = true;
}
+7 -4
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { satelliteClassLabel } from '../../data/satelliteClass.js';
import { satelliteClassText } from '../../data/satelliteClass.js';
import { t } from '../../i18n/index.js';
import { formatQuantity, unitLabel } from '../../ui/unitLabels.js';
import {
@@ -95,7 +95,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedNorad,
layerState._catalog.get(layerState._trackedNorad)?.group,
);
lastPos.show = true;
// Back to its class's visibility: a hidden class stays hidden.
lastPos.show = parts.controls._classVisible(layerState._trackedNorad);
lastPos.pixelSize = style.pixelSize;
lastPos.color = style.color;
lastPos.outlineColor = style.outlineColor;
@@ -118,6 +119,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedEntity = null;
}
layerState._trackedNorad = null;
parts.controls._syncIssOrbit?.();
parts.labels._syncIssOverlay();
clearTrackedSubjectContext('satellites');
layerState._contextRefreshedAtMs = 0;
@@ -241,7 +243,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,
}),
@@ -366,7 +368,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,
@@ -420,6 +422,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
// Show orbital path
parts.rendering._showOrbitPath(noradId, Cesium.Color.YELLOW);
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
// Tracked entity position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.