mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-21 02:32:18 +00:00
Merge upstream main into feat/iss-3d-model
Main's renderer seam (#1760) keeps Cesium inside src/render/cesium/, so the ISS model now draws through the renderer contract: - issModel.js draws the station as an item of a draw-port `models` set (url, position, heading/pitch/roll from its flight axes, scale, minimum pixel size, display range), hands the near range over through the dots' `displayRange`, and reads the eye from the camera port. - issArticulation.js computes each joint's matrix as plain numbers and the Sun from geo/celestial, and hands them over by node name. - The contract's ModelItem gains `nodes`: transforms of a model's named glTF nodes, which the Cesium port writes once the model is ready and again only when they change; a dropped name gets its authored pose back. - issCommand.js asks the frame port for frames and zooms by shortening the camera port's follow offset. - A click on the model is told by its draw hit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
c737a354c4
1129 files changed
+150420
-46238
No files matched your search
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { gstime, twoline2satrec } from 'satellite.js';
|
||||
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
@@ -67,7 +66,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
*/
|
||||
|
||||
async function _loadDenseCatalog({ signal = null } = {}) {
|
||||
if (!layerState._viewer || !layerState._pointCollection)
|
||||
if (!layerState._viewer || !parts.rendering._hasPointCollection())
|
||||
return { status: 'source-unavailable', reason: 'layer-unavailable' };
|
||||
layerState._denseLoadController?.abort();
|
||||
const resourceController = new AbortController();
|
||||
@@ -114,7 +113,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
if (
|
||||
token !== layerState._denseLoadToken ||
|
||||
layerState._params.catalog !== 'dense' ||
|
||||
!layerState._pointCollection
|
||||
!parts.rendering._hasPointCollection()
|
||||
) {
|
||||
return { status: 'superseded', reason: 'dense-load-superseded' };
|
||||
}
|
||||
@@ -143,21 +142,11 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
sensor: null,
|
||||
orbitSample,
|
||||
});
|
||||
const point = layerState._pointCollection.add({
|
||||
position: reckonEarthFixed(
|
||||
orbitSample,
|
||||
nowMs,
|
||||
gmst,
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
pixelSize: style.pixelSize,
|
||||
color: style.color,
|
||||
outlineColor: style.outlineColor,
|
||||
outlineWidth: style.outlineWidth,
|
||||
scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6),
|
||||
id: noradId,
|
||||
});
|
||||
layerState._points.set(noradId, point);
|
||||
parts.rendering._addPoint(
|
||||
noradId,
|
||||
reckonEarthFixed(orbitSample, nowMs, gmst, { x: 0, y: 0, z: 0 }),
|
||||
style,
|
||||
);
|
||||
layerState._denseIds.push(noradId);
|
||||
layerState._denseStale ||= Boolean(res.stale);
|
||||
added++;
|
||||
@@ -249,10 +238,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
parts.tracking._clearTracking();
|
||||
}
|
||||
for (const noradId of layerState._denseIds) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (point && layerState._pointCollection)
|
||||
layerState._pointCollection.remove(point);
|
||||
layerState._points.delete(noradId);
|
||||
parts.rendering._removePoint(noradId);
|
||||
layerState._catalog.delete(noradId);
|
||||
}
|
||||
layerState._denseIds = [];
|
||||
|
||||
@@ -279,10 +279,28 @@ test('SATCAT CSV parses, quoted commas included, keyed by NORAD id', () => {
|
||||
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 ring = { primitive: { show: true } };
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_params: {
|
||||
@@ -292,23 +310,27 @@ test('turning Stations off takes the ISS ring and label with its point', async (
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, ring]]),
|
||||
_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) } },
|
||||
parts: {
|
||||
labels: { _syncIssOverlay: () => (overlaySyncs += 1) },
|
||||
rendering,
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
controls._applyClassVisibility();
|
||||
assert.equal(state._points.get(25544).show, false);
|
||||
assert.equal(ring.primitive.show, false, 'the ring goes with the class');
|
||||
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(ring.primitive.show, true, 'and comes back with it');
|
||||
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 () => {
|
||||
@@ -375,18 +397,17 @@ test('every ingested group names the class its unnamed members fall back to', ()
|
||||
|
||||
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],
|
||||
[25544, {}],
|
||||
[90001, {}],
|
||||
]),
|
||||
_points: new Map(),
|
||||
coverageChanged() {},
|
||||
};
|
||||
const rendering = recordingRendering(state);
|
||||
const { methods } = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
@@ -402,15 +423,15 @@ test('enabling the layer leaves a hidden Stations class without its ISS ring', a
|
||||
labels: { _syncIssOverlay() {} },
|
||||
interaction: { _installClickHandler() {} },
|
||||
tracking: { _applyPendingTrackingRestore() {} },
|
||||
rendering: {},
|
||||
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');
|
||||
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(iss.primitive.show, true);
|
||||
assert.equal(rendering.rings.get(25544), true);
|
||||
});
|
||||
|
||||
test('a mission group outranks an orbit group, and an Unknown UCS purpose is no evidence', () => {
|
||||
@@ -442,7 +463,6 @@ test('a mission group outranks an orbit group, and an Unknown UCS purpose is no
|
||||
|
||||
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: {
|
||||
@@ -452,22 +472,23 @@ test('a tracked ISS keeps its ring while Stations is hidden', async () => {
|
||||
},
|
||||
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
|
||||
_points: new Map([[25544, { show: true }]]),
|
||||
_orbitPaths: new Map([[25544, ring]]),
|
||||
_orbitPaths: new Map([[25544, {}]]),
|
||||
_detectionObjects: new Map(),
|
||||
_trackedNorad: null,
|
||||
};
|
||||
const rendering = recordingRendering(state);
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: { labels: { _syncIssOverlay() {} } },
|
||||
parts: { labels: { _syncIssOverlay() {} }, rendering },
|
||||
source: {},
|
||||
});
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, false);
|
||||
assert.equal(rendering.rings.get(25544), false);
|
||||
state._trackedNorad = 25544;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, true, 'tracked, it keeps its ring');
|
||||
assert.equal(rendering.rings.get(25544), true, 'tracked, it keeps its ring');
|
||||
state._params.showOrbits = false;
|
||||
controls._syncIssOrbit();
|
||||
assert.equal(ring.primitive.show, false, 'orbits off still hides it');
|
||||
assert.equal(rendering.rings.get(25544), false, 'orbits off still hides it');
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import {
|
||||
classifySatellite,
|
||||
@@ -20,38 +20,6 @@ export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
|
||||
*/
|
||||
export const COCKPIT_ORBIT_DIM_FACTOR = 0.3;
|
||||
|
||||
/**
|
||||
* Write an orbit ring's alpha as a multiple of the alpha it was built with.
|
||||
* The ring's per-instance attributes exist only once Cesium has updated the
|
||||
* primitive; until then nothing is written and the next tick retries.
|
||||
* @param {{primitive: object, instanceId: string, baseColor: Cesium.Color,
|
||||
* baseDepthFailColor: Cesium.Color, alphaFactor: number}} path
|
||||
* @param {number} factor 1 restores the built colours exactly.
|
||||
* @returns {boolean} True when the ring now carries `factor`.
|
||||
*/
|
||||
export function applyOrbitPathAlpha(path, factor) {
|
||||
if (!path?.primitive || !path.baseColor) return false;
|
||||
if ((path.alphaFactor ?? 1) === factor) return true;
|
||||
let attributes;
|
||||
try {
|
||||
attributes = path.primitive.getGeometryInstanceAttributes?.(
|
||||
path.instanceId,
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (!attributes) return false;
|
||||
const scaled = (color) => color.withAlpha(color.alpha * factor);
|
||||
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
|
||||
factor === 1 ? path.baseColor : scaled(path.baseColor),
|
||||
);
|
||||
attributes.depthFailColor = Cesium.ColorGeometryInstanceAttribute.toValue(
|
||||
factor === 1 ? path.baseDepthFailColor : scaled(path.baseDepthFailColor),
|
||||
);
|
||||
path.alphaFactor = factor;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -173,9 +141,11 @@ export function createCockpitSubject({ state: layerState, parts }) {
|
||||
}
|
||||
|
||||
function _setPointShown(noradId, show) {
|
||||
const point = layerState._points.get(noradId);
|
||||
// Released points go back to their class's visibility.
|
||||
if (point) point.show = show && parts.controls._classVisible(noradId);
|
||||
parts.rendering._setPointShown(
|
||||
noradId,
|
||||
show && parts.controls._classVisible(noradId),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,12 +158,11 @@ export function createCockpitSubject({ state: layerState, parts }) {
|
||||
const held = _cockpitHeld();
|
||||
const tracked = layerState._trackedNorad;
|
||||
|
||||
const dot = layerState._trackedEntity?.point;
|
||||
if (held) {
|
||||
if (dot) dot.show = false;
|
||||
parts.rendering._setTrackedDotShown(false);
|
||||
layerState._cockpitHiddenDot = true;
|
||||
} else if (layerState._cockpitHiddenDot) {
|
||||
if (dot) dot.show = true;
|
||||
parts.rendering._setTrackedDotShown(true);
|
||||
layerState._cockpitHiddenDot = false;
|
||||
}
|
||||
|
||||
@@ -202,47 +171,47 @@ export function createCockpitSubject({ state: layerState, parts }) {
|
||||
for (const noradId of [...hiddenPoints]) {
|
||||
if (companions.has(noradId)) continue;
|
||||
hiddenPoints.delete(noradId);
|
||||
// The tracked primitive stays hidden: its entity draws the dot.
|
||||
// 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 point
|
||||
// primitives, and the new ones arrive shown.
|
||||
// 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) {
|
||||
const trackedPoint = layerState._points.get(tracked);
|
||||
if (trackedPoint) trackedPoint.show = false;
|
||||
}
|
||||
if (held) parts.rendering._setPointShown(tracked, false);
|
||||
|
||||
const hiddenPath = layerState._cockpitHiddenPath;
|
||||
if (hiddenPath !== null && (!held || hiddenPath !== tracked)) {
|
||||
const path = layerState._orbitPaths.get(hiddenPath);
|
||||
const hasPath = layerState._orbitPaths.has(hiddenPath);
|
||||
// The ISS's ring also follows its class (and its tracking).
|
||||
if (path && hiddenPath === ISS_NORAD) parts.controls._syncIssOrbit();
|
||||
else if (path)
|
||||
path.primitive.show = parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showOrbits,
|
||||
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) {
|
||||
const path = layerState._orbitPaths.get(tracked);
|
||||
if (path) {
|
||||
path.primitive.show = false;
|
||||
layerState._cockpitHiddenPath = tracked;
|
||||
}
|
||||
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, path] of layerState._orbitPaths) {
|
||||
for (const noradId of layerState._orbitPaths.keys()) {
|
||||
const dim = subject !== null && noradId !== subject;
|
||||
applyOrbitPathAlpha(path, dim ? COCKPIT_ORBIT_DIM_FACTOR : 1);
|
||||
parts.rendering._setOrbitPathAlpha(
|
||||
noradId,
|
||||
dim ? COCKPIT_ORBIT_DIM_FACTOR : 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,15 +244,21 @@ export function createCockpitSubject({ state: layerState, parts }) {
|
||||
/**
|
||||
* The tracked satellite's Earth-fixed position this frame: the per-frame
|
||||
* cache the dot and follow camera read, never a separate propagation.
|
||||
* @param {Cesium.Cartesian3} [result] Receives the position.
|
||||
* @returns {Cesium.Cartesian3|null} Null while the layer is off, nothing
|
||||
* @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;
|
||||
return Cesium.Cartesian3.clone(layerState._trackedFrameCartesian, result);
|
||||
const { x, y, z } = layerState._trackedFrameCartesian;
|
||||
const out = result ?? {};
|
||||
out.x = x;
|
||||
out.y = y;
|
||||
out.z = z;
|
||||
return out;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -313,17 +288,16 @@ export function createCockpitSubject({ state: layerState, parts }) {
|
||||
refocusTrackedById(noradId) {
|
||||
const id = parts.tracking._normalizeTrackedNorad(noradId);
|
||||
const viewer = layerState._viewer;
|
||||
const entity = layerState._trackedEntity;
|
||||
if (
|
||||
id === null ||
|
||||
id !== layerState._trackedNorad ||
|
||||
!viewer ||
|
||||
!entity ||
|
||||
!viewer.entities?.contains?.(entity)
|
||||
!layerState._followTarget
|
||||
)
|
||||
return false;
|
||||
viewer.camera?.cancelFlight?.();
|
||||
viewer.trackedEntity = entity;
|
||||
const camera = cameraOf(viewer);
|
||||
camera.cancelFlight();
|
||||
camera.follow(layerState._followTarget);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createState } from './state.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createOrbits } from './orbits.js';
|
||||
@@ -13,13 +12,15 @@ import { createInteraction } from './interaction.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import {
|
||||
COCKPIT_ORBIT_DIM_FACTOR,
|
||||
applyOrbitPathAlpha,
|
||||
createCockpitSubject,
|
||||
satelliteCockpitInfo,
|
||||
} from './cockpitSubject.js';
|
||||
import { groundTrackBearingDeg } from './orbits.js';
|
||||
import { indexImagingSensors } from './sensors.js';
|
||||
import { ISS_NORAD } from './policy.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;
|
||||
@@ -38,10 +39,63 @@ const GROUP_TEXT = {
|
||||
'gps-ops': tle('GPS FIXTURE', GPS, ' 2.00563000', ' 55.0000'),
|
||||
};
|
||||
|
||||
/** Whether the tracked entity draws its dot (an unset show is shown). */
|
||||
/** 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 show = f.state._trackedEntity.point.show;
|
||||
return show === undefined ? true : show.getValue();
|
||||
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 =
|
||||
@@ -104,6 +158,10 @@ async function fixture(t) {
|
||||
focus: {
|
||||
clearFocusTarget: noop,
|
||||
publishFocusTargetFromCachedPosition: noop,
|
||||
publishFocusTargetAt: noop,
|
||||
nearFarScalarValueAtDistance: () => 1,
|
||||
advanceSpriteFocus: () => false,
|
||||
focusAlphaNeedsWrite: () => false,
|
||||
getFocusTarget: () => null,
|
||||
focusNowMs: (now) => now,
|
||||
focusPassIsNeeded: () => false,
|
||||
@@ -116,7 +174,12 @@ async function fixture(t) {
|
||||
},
|
||||
readout: { refreshTrackedReadout: noop },
|
||||
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
|
||||
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
|
||||
picking: {
|
||||
registerPickOwner: noop,
|
||||
unregisterPickOwner: noop,
|
||||
resolvePickId: () => null,
|
||||
isOwnedByOtherLayer: () => false,
|
||||
},
|
||||
};
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
@@ -137,17 +200,12 @@ async function fixture(t) {
|
||||
})) {
|
||||
parts[name] = factory(context);
|
||||
}
|
||||
const viewer = {
|
||||
trackedEntity: undefined,
|
||||
entities: new Cesium.EntityCollection(),
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
primitives: new Cesium.PrimitiveCollection(),
|
||||
preRender: new Cesium.Event(),
|
||||
frameState: { frameNumber: 1 },
|
||||
},
|
||||
trackedEntityChanged: new Cesium.Event(),
|
||||
};
|
||||
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;
|
||||
@@ -159,9 +217,10 @@ async function fixture(t) {
|
||||
Object.assign(console, { log, warn });
|
||||
t.after(() => {
|
||||
console.log = noop;
|
||||
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer);
|
||||
parts.lifecycle.methods.destroy(viewer);
|
||||
console.log = log;
|
||||
viewer.scene.primitives.destroy();
|
||||
input.destroy();
|
||||
unbind();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
@@ -170,6 +229,8 @@ async function fixture(t) {
|
||||
state,
|
||||
parts,
|
||||
viewer,
|
||||
camera,
|
||||
draw,
|
||||
methods,
|
||||
track(id) {
|
||||
const log = console.log;
|
||||
@@ -181,10 +242,10 @@ async function fixture(t) {
|
||||
}
|
||||
},
|
||||
nextFrame() {
|
||||
viewer.scene.frameState.frameNumber += 1;
|
||||
parts.rendering._preRenderTick();
|
||||
frameNumber += 1;
|
||||
frame.step({ frame: frameNumber, time: Date.now() });
|
||||
},
|
||||
ring: (id) => state._orbitPaths.get(id)?.primitive,
|
||||
ring: (id) => state._orbitPaths.get(id)?.item,
|
||||
detected: () =>
|
||||
methods.getDetectableObjects().map((object) => object.sourceId),
|
||||
};
|
||||
@@ -209,7 +270,8 @@ test('the tracked satellite is a subject read from the per-frame sample', async
|
||||
propagations += 1;
|
||||
return propagate(...args);
|
||||
};
|
||||
f.viewer.scene.frameState.frameNumber += 1;
|
||||
// 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();
|
||||
@@ -227,15 +289,11 @@ test('the tracked satellite is a subject read from the per-frame sample', async
|
||||
|
||||
// The same point the tracked dot and follow camera use, as a copy.
|
||||
const cached = f.state._trackedFrameCartesian;
|
||||
assert.ok(Cesium.Cartesian3.equals(position, cached));
|
||||
assert.deepEqual({ ...position }, { x: cached.x, y: cached.y, z: cached.z });
|
||||
assert.notEqual(position, cached);
|
||||
const target = new Cesium.Cartesian3();
|
||||
const target = { x: 0, y: 0, z: 0 };
|
||||
assert.equal(f.methods.getCockpitPosition(target), target);
|
||||
const geodetic = Cesium.Cartographic.fromCartesian(position);
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Math.toDegrees(geodetic.latitude) - subject.latitude) <
|
||||
1e-6,
|
||||
);
|
||||
assert.ok(Math.abs(toLonLatH(position).lat - subject.latitude) < 1e-6);
|
||||
f.parts.orbits.propagatePosition = propagate;
|
||||
});
|
||||
|
||||
@@ -349,7 +407,7 @@ test('holding the subject hides its dot, ring, docked companions and bracket', a
|
||||
assert.equal(dotShown(f), true);
|
||||
assert.equal(f.ring(ISS_NORAD).show, true);
|
||||
assert.equal(f.state._points.get(COMPANION).show, true);
|
||||
// The tracked primitive stays hidden: the tracked entity draws the dot.
|
||||
// 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));
|
||||
});
|
||||
@@ -420,95 +478,63 @@ test('tracking without a Cockpit subject keeps its marks', async (t) => {
|
||||
assert.equal(f.state._cockpitHiddenPath, null);
|
||||
});
|
||||
|
||||
/**
|
||||
* Give a ring the per-instance attributes Cesium creates on its first
|
||||
* update, starting from the colours it was built with. Rings in this
|
||||
* fixture are never rendered, so the test stands in for that update.
|
||||
*/
|
||||
function readyRing(f, id) {
|
||||
const path = f.state._orbitPaths.get(id);
|
||||
const attributes = {
|
||||
color: Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor),
|
||||
depthFailColor: Cesium.ColorGeometryInstanceAttribute.toValue(
|
||||
path.baseDepthFailColor,
|
||||
),
|
||||
/** 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.depthFail.color],
|
||||
};
|
||||
path.primitive.getGeometryInstanceAttributes = (instanceId) =>
|
||||
instanceId === path.instanceId ? attributes : undefined;
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** A colour attribute's alpha byte. */
|
||||
const alphaByte = (value) => value[3];
|
||||
|
||||
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 iss = readyRing(f, ISS_NORAD);
|
||||
const gps = readyRing(f, GPS);
|
||||
const builtColor = [...iss.color];
|
||||
const builtDepthFail = [...iss.depthFailColor];
|
||||
const gpsBuilt = [...gps.color];
|
||||
const issBuilt = ringColors(f, ISS_NORAD);
|
||||
const gpsBuilt = ringColors(f, GPS);
|
||||
|
||||
f.methods.setCockpitSubject(GPS);
|
||||
const dimmed = (byte) => Math.round(byte * COCKPIT_ORBIT_DIM_FACTOR);
|
||||
assert.ok(Math.abs(alphaByte(iss.color) - dimmed(builtColor[3])) <= 1);
|
||||
assert.ok(
|
||||
Math.abs(alphaByte(iss.depthFailColor) - dimmed(builtDepthFail[3])) <= 1,
|
||||
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.deepEqual([...iss.color].slice(0, 3), builtColor.slice(0, 3));
|
||||
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([...gps.color], gpsBuilt, 'the ridden ring is not dimmed');
|
||||
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, Cesium.Color.YELLOW);
|
||||
const rebuilt = readyRing(f, ISS_NORAD);
|
||||
f.parts.rendering._showOrbitPath(ISS_NORAD, TRACKED_ORBIT_COLOR);
|
||||
const rebuiltAt = ringColors(f, ISS_NORAD);
|
||||
f.nextFrame();
|
||||
assert.ok(alphaByte(rebuilt.color) < builtColor[3]);
|
||||
near(
|
||||
ringColors(f, ISS_NORAD).color[3],
|
||||
rebuiltAt.color[3] * COCKPIT_ORBIT_DIM_FACTOR,
|
||||
);
|
||||
|
||||
f.methods.setCockpitSubject(null);
|
||||
assert.deepEqual(
|
||||
[...rebuilt.color],
|
||||
[
|
||||
...Cesium.ColorGeometryInstanceAttribute.toValue(
|
||||
f.state._orbitPaths.get(ISS_NORAD).baseColor,
|
||||
),
|
||||
],
|
||||
ringColors(f, ISS_NORAD),
|
||||
rebuiltAt,
|
||||
'released rings get their built colours back exactly',
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...rebuilt.depthFailColor],
|
||||
[
|
||||
...Cesium.ColorGeometryInstanceAttribute.toValue(
|
||||
f.state._orbitPaths.get(ISS_NORAD).baseDepthFailColor,
|
||||
),
|
||||
],
|
||||
);
|
||||
assert.equal(f.ring(GPS).show, true);
|
||||
assert.deepEqual([...gps.color], gpsBuilt);
|
||||
});
|
||||
|
||||
test('a ring not yet updated by Cesium is dimmed once it is', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.track(GPS);
|
||||
f.methods.setCockpitSubject(GPS);
|
||||
const path = f.state._orbitPaths.get(ISS_NORAD);
|
||||
assert.equal(path.alphaFactor, 1, 'nothing written before the first update');
|
||||
const iss = readyRing(f, ISS_NORAD);
|
||||
f.nextFrame();
|
||||
assert.equal(path.alphaFactor, COCKPIT_ORBIT_DIM_FACTOR);
|
||||
assert.ok(alphaByte(iss.color) < 100);
|
||||
assert.equal(applyOrbitPathAlpha(path, 1), true);
|
||||
assert.deepEqual(
|
||||
[...iss.color],
|
||||
[...Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor)],
|
||||
);
|
||||
assert.deepEqual(ringColors(f, GPS), gpsBuilt);
|
||||
});
|
||||
|
||||
test('a held subject ignores the layer Escape; refocus restores the follow', async (t) => {
|
||||
@@ -519,13 +545,16 @@ test('a held subject ignores the layer Escape; refocus restores the follow', asy
|
||||
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 entity; refocus puts it back.
|
||||
f.viewer.trackedEntity = undefined;
|
||||
// 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.viewer.trackedEntity, undefined);
|
||||
assert.equal(f.camera.followed, null);
|
||||
assert.equal(f.methods.refocusTrackedById(String(ISS_NORAD)), true);
|
||||
assert.equal(f.viewer.trackedEntity, f.state._trackedEntity);
|
||||
assert.equal(f.camera.followed, target);
|
||||
assert.equal(f.state._trackedNorad, ISS_NORAD);
|
||||
|
||||
f.parts.interaction._onKeyDown({ key: 'Escape' });
|
||||
|
||||
Vendored
+41
-42
@@ -1,6 +1,6 @@
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { decodeSatelliteClassMask } from '../../data/satelliteClassMask.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_SATELLITE_CLASSES,
|
||||
@@ -17,7 +17,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* Resolve the canonical point style for a satellite.
|
||||
* @param {number} noradId NORAD catalog number.
|
||||
* @param {string|undefined} group Catalog group tag (see CATALOG_GROUPS / 'dense').
|
||||
* @returns {{ pixelSize: number, color: Cesium.Color, outlineColor: Cesium.Color, outlineWidth: number }}
|
||||
* @returns {{ pixelSize: number, color: number[], outlineColor: number[], outlineWidth: number }}
|
||||
*/
|
||||
|
||||
function _pointStyleFor(noradId, group) {
|
||||
@@ -52,10 +52,10 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* The ISS's ring and label go with its class.
|
||||
*/
|
||||
function _applyClassVisibility() {
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
if (noradId === layerState._trackedNorad) continue;
|
||||
if (layerState._cockpitHiddenPoints?.has(noradId)) continue;
|
||||
point.show = _classVisible(noradId);
|
||||
parts.rendering._setPointShown(noradId, _classVisible(noradId));
|
||||
}
|
||||
_syncIssOrbit();
|
||||
parts.labels?._syncIssOverlay?.();
|
||||
@@ -78,8 +78,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
/** 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();
|
||||
parts.rendering._setOrbitPathShown(ISS_NORAD, _issOrbitVisible());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,8 +219,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
refreshInterval: 5 * 60 * 1000,
|
||||
|
||||
getDetectableObjects(options = {}) {
|
||||
if (!layerState._pointCollection || !layerState._pointCollection.show)
|
||||
return [];
|
||||
if (!parts.rendering._pointsShown()) return [];
|
||||
// Dense extras are points-only: excluded from the detection overlay.
|
||||
const eligibleCount = Math.max(
|
||||
1,
|
||||
@@ -236,7 +234,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
const result = [];
|
||||
let idx = 0;
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
if (
|
||||
layerState._denseIds.length > 0 &&
|
||||
layerState._catalog.get(noradId)?.group === 'dense'
|
||||
@@ -245,7 +243,8 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
const shouldTake = (idx - start) % stride === 0;
|
||||
idx++;
|
||||
if (!shouldTake) continue;
|
||||
if (!point.position) continue;
|
||||
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;
|
||||
@@ -281,7 +280,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
object.klass = satelliteClassText(cat?.satelliteClass, cat?.group, {
|
||||
isIss: noradId === ISS_NORAD,
|
||||
});
|
||||
object.position = point.position;
|
||||
object.position = position;
|
||||
object.skipLabel = isTracked;
|
||||
result.push(object);
|
||||
if (result.length >= maxCount) break;
|
||||
@@ -293,7 +292,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* Find a satellite by exact NORAD id (numeric string) or case-insensitive
|
||||
* name substring. Position is freshly propagated via SGP4.
|
||||
* @param {string|number} query NORAD id or partial name.
|
||||
* @returns {{ noradId: number, name: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number }|null}
|
||||
* @returns {{ noradId: number, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number }|null}
|
||||
*/
|
||||
findByQuery(query) {
|
||||
if (
|
||||
@@ -330,11 +329,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
return {
|
||||
noradId,
|
||||
name: sat.name.trim(),
|
||||
position: Cesium.Cartesian3.fromDegrees(
|
||||
pos.longitude,
|
||||
pos.latitude,
|
||||
pos.altitude,
|
||||
),
|
||||
position: fromDegrees(pos.longitude, pos.latitude, pos.altitude),
|
||||
latitude: pos.latitude,
|
||||
longitude: pos.longitude,
|
||||
altitudeM: pos.altitude,
|
||||
@@ -345,7 +340,7 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* Get positions of currently rendered satellites from per-point state
|
||||
* (no SGP4 re-propagation).
|
||||
* @param {number} [maxCount=300] Maximum entries to return.
|
||||
* @returns {Array<{ id: number, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number }>}
|
||||
* @returns {Array<{ id: number, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number }>}
|
||||
*/
|
||||
getAllPositions(maxCount = 300) {
|
||||
const result = [];
|
||||
@@ -353,9 +348,10 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
const cap =
|
||||
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 300;
|
||||
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
if (result.length >= cap) break;
|
||||
if (!point.position) continue;
|
||||
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 (
|
||||
@@ -363,15 +359,15 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
layerState._catalog.get(noradId)?.group === 'dense'
|
||||
)
|
||||
continue;
|
||||
const carto = Cesium.Cartographic.fromCartesian(point.position);
|
||||
const carto = toLonLatH(position);
|
||||
if (!carto) continue;
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
result.push({
|
||||
id: noradId,
|
||||
label: sat ? sat.name.trim() : String(noradId),
|
||||
position: point.position,
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
position,
|
||||
latitude: carto.lat,
|
||||
longitude: carto.lon,
|
||||
altitudeM: carto.height,
|
||||
});
|
||||
}
|
||||
@@ -383,12 +379,12 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* 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 {Cesium.Cartesian3} center Earth-fixed position.
|
||||
* @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: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, satelliteClass: string|null, distanceM: number }>}
|
||||
* @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,
|
||||
@@ -407,8 +403,8 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
const excluded = new Set(excludeIds.map(String));
|
||||
const classes = new Set(excludeClasses);
|
||||
const dense = layerState._denseIds.length > 0;
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
const p = point.position;
|
||||
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);
|
||||
@@ -423,20 +419,20 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
// 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, point, sat, distanceSq });
|
||||
nearest.splice(at, 0, { noradId, p, sat, distanceSq });
|
||||
if (nearest.length > cap) nearest.pop();
|
||||
}
|
||||
const result = [];
|
||||
for (const { noradId, point, sat, distanceSq } of nearest) {
|
||||
const carto = Cesium.Cartographic.fromCartesian(point.position);
|
||||
if (!carto) continue;
|
||||
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: point.position,
|
||||
latitude: Cesium.Math.toDegrees(carto.latitude),
|
||||
longitude: Cesium.Math.toDegrees(carto.longitude),
|
||||
altitudeM: carto.height,
|
||||
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),
|
||||
});
|
||||
@@ -625,22 +621,25 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
if (params.showPoints !== undefined) {
|
||||
layerState._params.showPoints = params.showPoints !== false;
|
||||
if (layerState._pointCollection)
|
||||
layerState._pointCollection.show = satelliteVisualsVisible(
|
||||
parts.rendering._setPointsShown(
|
||||
satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showPoints,
|
||||
);
|
||||
),
|
||||
);
|
||||
}
|
||||
if (params.showOrbits !== undefined) {
|
||||
layerState._params.showOrbits = params.showOrbits !== false;
|
||||
for (const [noradId, path] of layerState._orbitPaths)
|
||||
path.primitive.show =
|
||||
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') {
|
||||
|
||||
@@ -51,7 +51,7 @@ export function createSatellitesLayer({
|
||||
satelliteVisualsVisible: parts.controls.satelliteVisualsVisible,
|
||||
satelliteCatalogModeChanged: parts.controls.satelliteCatalogModeChanged,
|
||||
createIssOverlayEntry: parts.labels.createIssOverlayEntry,
|
||||
orbitFrameModelMatrix: parts.orbits.orbitFrameModelMatrix,
|
||||
orbitFrameModelMatrix: parts.rendering.orbitFrameModelMatrix,
|
||||
_setTrackedSatelliteRefreshStateForTest:
|
||||
parts.testing._setTrackedSatelliteRefreshStateForTest,
|
||||
_setSatelliteTrackingRefreshOutcomeForTest:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { twoline2satrec } from 'satellite.js';
|
||||
import * as Cesium from 'cesium';
|
||||
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';
|
||||
@@ -151,14 +151,11 @@ export function createIngestion({
|
||||
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 (layerState._points.has(noradId))
|
||||
parts.rendering._setPointStyle(
|
||||
noradId,
|
||||
parts.controls._pointStyleFor(noradId, sat.group),
|
||||
);
|
||||
}
|
||||
if (!changed) return;
|
||||
parts.controls._applyClassVisibility();
|
||||
@@ -275,11 +272,8 @@ export function createIngestion({
|
||||
: null;
|
||||
|
||||
// Clear existing
|
||||
layerState._pointCollection.removeAll();
|
||||
layerState._points.clear();
|
||||
for (const path of layerState._orbitPaths.values())
|
||||
viewer.scene.primitives.remove(path.primitive);
|
||||
layerState._orbitPaths.clear();
|
||||
parts.rendering._clearPoints();
|
||||
parts.rendering._clearOrbitPaths(viewer);
|
||||
layerState._catalog.clear();
|
||||
// The detection overlay caches one record per satellite and stamps its
|
||||
// id/class at creation only. A rebuild can re-tag a satellite (a failed
|
||||
@@ -368,27 +362,14 @@ export function createIngestion({
|
||||
const pos = parts.orbits.propagatePosition(satrec, now);
|
||||
if (!pos) continue;
|
||||
|
||||
const cartesian = Cesium.Cartesian3.fromDegrees(
|
||||
pos.longitude,
|
||||
pos.latitude,
|
||||
pos.altitude,
|
||||
// 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),
|
||||
);
|
||||
|
||||
// Add point primitive (styling from the shared table, WS-D3)
|
||||
const style = parts.controls._pointStyleFor(noradId, entry.group);
|
||||
const point = layerState._pointCollection.add({
|
||||
position: cartesian,
|
||||
pixelSize: style.pixelSize,
|
||||
color: style.color,
|
||||
outlineColor: style.outlineColor,
|
||||
outlineWidth: style.outlineWidth,
|
||||
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);
|
||||
}
|
||||
|
||||
// Show ISS orbital path by default
|
||||
|
||||
@@ -23,14 +23,15 @@ function tleSet(name, field) {
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// Orbit tracks hand their path to the renderer; positions pass through here.
|
||||
const orbitParts = {
|
||||
rendering: { _rendererPositions: (positions) => positions },
|
||||
};
|
||||
|
||||
function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
|
||||
const state = {
|
||||
_trackingRefreshEpoch: 0,
|
||||
_activeUpdateControllers: new Set(),
|
||||
_pointCollection: {
|
||||
removeAll() {},
|
||||
add: (point) => point,
|
||||
},
|
||||
_points: new Map(),
|
||||
_orbitPaths: new Map(),
|
||||
_catalog: new Map(),
|
||||
@@ -60,7 +61,20 @@ function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
|
||||
state.rowNotified = (state.rowNotified || 0) + 1;
|
||||
},
|
||||
},
|
||||
rendering: { _showOrbitPath() {} },
|
||||
rendering: {
|
||||
_clearPoints() {
|
||||
state._points.clear();
|
||||
},
|
||||
_clearOrbitPaths() {
|
||||
state._orbitPaths.clear();
|
||||
},
|
||||
_addPoint(noradId, position, style, show = true) {
|
||||
state._points.set(noradId, { position, show });
|
||||
},
|
||||
_setPointStyle() {},
|
||||
_showOrbitPath() {},
|
||||
_setOrbitPathShown() {},
|
||||
},
|
||||
tracking: {
|
||||
async _reconcileTrackedSubjectContext() {},
|
||||
_applyPendingTrackingRestore() {},
|
||||
@@ -76,7 +90,7 @@ function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
|
||||
...sourceExtras,
|
||||
};
|
||||
const { methods } = createIngestion({ state, services: {}, parts, source });
|
||||
return { state, update: () => methods.update({ scene: {} }) };
|
||||
return { state, update: () => methods.update({}) };
|
||||
}
|
||||
|
||||
test('every Alpha-5 satellite keeps its own catalog entry through dedupe', async (t) => {
|
||||
@@ -114,7 +128,7 @@ test('a mission payload does not match a loaded satellite from another launch ye
|
||||
].join('\n'),
|
||||
);
|
||||
await update();
|
||||
const { getSatelliteOrbitTrack } = createOrbits({ state });
|
||||
const { getSatelliteOrbitTrack } = createOrbits({ state, parts: orbitParts });
|
||||
const track = (launchTime) =>
|
||||
getSatelliteOrbitTrack('Sirius SXM-11', { launchTime });
|
||||
assert.equal(track('2026-06-29T02:25:00Z')?.noradId, 69728);
|
||||
@@ -132,7 +146,7 @@ test('a satellite with a blank designator keeps matching by name', async (t) =>
|
||||
].join('\n'),
|
||||
);
|
||||
await update();
|
||||
const { getSatelliteOrbitTrack } = createOrbits({ state });
|
||||
const { getSatelliteOrbitTrack } = createOrbits({ state, parts: orbitParts });
|
||||
assert.equal(tleLineLaunchYear('1 69728U 26208.65166678'), null);
|
||||
assert.equal(
|
||||
getSatelliteOrbitTrack('Sirius SXM-11', {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { onFollowChanged } from '../../data/followed.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
export function createInteraction({
|
||||
state: layerState,
|
||||
@@ -19,62 +20,62 @@ export function createInteraction({
|
||||
}
|
||||
|
||||
function _installClickHandler(viewer) {
|
||||
if (layerState._clickHandler) return; // already installed
|
||||
if (layerState._clickSubscription) return; // already installed
|
||||
|
||||
// Cross-layer untrack (H2, mirror of flights): if ANOTHER layer (flights,
|
||||
// military, …) grabs the follow-camera, drop our tracking so the orbit ring /
|
||||
// tracked entity don't orphan — without touching viewer.trackedEntity (the
|
||||
// tracked dot don't orphan — without touching viewer.trackedEntity (the
|
||||
// new owner controls it). Guarded so our OWN switch (viewer.trackedEntity
|
||||
// briefly undefined mid-_trackSatellite) doesn't self-clear.
|
||||
if (!layerState._trackedEntityChangedRemove) {
|
||||
layerState._trackedEntityChangedRemove =
|
||||
viewer.trackedEntityChanged.addEventListener(() => {
|
||||
layerState._trackedEntityChangedRemove = onFollowChanged(
|
||||
viewer,
|
||||
(followed) => {
|
||||
if (!layerState._enabled) return;
|
||||
if (
|
||||
layerState._trackedNorad &&
|
||||
layerState._viewer &&
|
||||
layerState._viewer.trackedEntity &&
|
||||
layerState._viewer.trackedEntity !== layerState._trackedEntity
|
||||
followed &&
|
||||
followed !== layerState._followTarget
|
||||
) {
|
||||
parts.tracking._clearTracking(true, {
|
||||
origin:
|
||||
layerState._viewer.trackedEntity?.gevSelectionOrigin ||
|
||||
'programmatic',
|
||||
origin: followed.selectionOrigin || 'programmatic',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
|
||||
viewer.scene.canvas,
|
||||
);
|
||||
layerState._clickHandler.setInputAction((click) => {
|
||||
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
|
||||
if (!isPointerFree()) return;
|
||||
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 = viewer.scene.pick(click.position);
|
||||
const picked = event.topHit;
|
||||
const hit = event.drawHit;
|
||||
|
||||
if (picked) {
|
||||
// Clicking tracked entity itself — ignore
|
||||
if (picked.id === layerState._trackedEntity) return;
|
||||
// Clicking the tracked satellite's own dot — ignore
|
||||
if (parts.rendering._hitIsTracked(hit)) return;
|
||||
|
||||
// Check if it's a satellite point (id is NORAD catalog number)
|
||||
const prim = picked.primitive;
|
||||
if (prim && prim.id != null) {
|
||||
const noradId = Number(prim.id);
|
||||
// A click on the tracked ISS's own model: it is already tracked.
|
||||
if (noradId === layerState._trackedNorad) return;
|
||||
if (!isNaN(noradId) && layerState._catalog.has(noradId)) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
parts.tracking._trackSatellite(noradId, { origin: 'user' });
|
||||
return;
|
||||
}
|
||||
// A click on the ISS's 3D model: it tracks the ISS, as its dot does,
|
||||
// and is ignored while the ISS is tracked already.
|
||||
if (parts.issModel?._hitIsIss?.(hit)) {
|
||||
if (layerState._trackedNorad === ISS_NORAD) return;
|
||||
if (layerState._catalog.has(ISS_NORAD)) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
parts.tracking._trackSatellite(ISS_NORAD, { origin: 'user' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// A satellite dot (its item id is the NORAD catalog number)
|
||||
const noradId = parts.rendering._hitPointId(hit);
|
||||
if (noradId !== null && layerState._catalog.has(noradId)) {
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
parts.tracking._trackSatellite(noradId, { origin: 'user' });
|
||||
return;
|
||||
}
|
||||
|
||||
// A pick that belongs to a sibling layer (plane, vessel, station, CCTV
|
||||
// camera…) is not "empty space" — leave OUR tracking (and crucially
|
||||
// viewer.trackedEntity, which that sibling may have JUST set) alone (H2).
|
||||
@@ -88,7 +89,7 @@ export function createInteraction({
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
parts.tracking._clearTracking(false, { origin: 'user' });
|
||||
}
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', _onKeyDown);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { sunPositionFixed } from '../../geo/celestial.js';
|
||||
|
||||
/**
|
||||
* The ISS model's moving parts. NASA's file names its joints; the build keeps
|
||||
@@ -189,8 +189,8 @@ export function issStepAngle(current, target, maxStep) {
|
||||
* @param {'x'|'z'} axis
|
||||
* @param {number[]} pivot
|
||||
* @param {number} angle Radians.
|
||||
* @param {Cesium.Matrix4} result
|
||||
* @returns {Cesium.Matrix4}
|
||||
* @param {number[]} [result] 16 numbers to write, else a new array.
|
||||
* @returns {number[]} Column-major.
|
||||
*/
|
||||
export function issJointMatrix(axis, pivot, angle, result) {
|
||||
const c = Math.cos(angle);
|
||||
@@ -236,8 +236,13 @@ export function issJointMatrix(axis, pivot, angle, result) {
|
||||
]);
|
||||
}
|
||||
|
||||
/** Row-major numbers written column-major into `result` (or a new array). */
|
||||
function set(result, rowMajor) {
|
||||
return Cesium.Matrix4.fromRowMajorArray(rowMajor, result);
|
||||
const out = result ?? new Array(16);
|
||||
for (let row = 0; row < 4; row++)
|
||||
for (let column = 0; column < 4; column++)
|
||||
out[column * 4 + row] = rowMajor[row * 4 + column];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -416,8 +421,8 @@ export function issStepDirection(current, target, maxStep) {
|
||||
* @param {number[]} pivot
|
||||
* @param {number[]} axis Unit vector.
|
||||
* @param {number} angle Radians.
|
||||
* @param {Cesium.Matrix4} result
|
||||
* @returns {Cesium.Matrix4}
|
||||
* @param {number[]} [result] 16 numbers to write, else a new array.
|
||||
* @returns {number[]} Column-major.
|
||||
*/
|
||||
export function issAxisMatrix(pivot, axis, angle, result) {
|
||||
const [x, y, z] = axis;
|
||||
@@ -440,8 +445,8 @@ export function issAxisMatrix(pivot, axis, angle, result) {
|
||||
* A dish node's matrix that turns its rest boresight (+Y) onto `direction`.
|
||||
* @param {number[]} pivot
|
||||
* @param {number[]} direction Unit vector on the model's axes.
|
||||
* @param {Cesium.Matrix4} result
|
||||
* @returns {Cesium.Matrix4}
|
||||
* @param {number[]} [result] 16 numbers to write, else a new array.
|
||||
* @returns {number[]} Column-major.
|
||||
*/
|
||||
export function issAimMatrix(pivot, direction, result) {
|
||||
// Y × direction
|
||||
@@ -460,12 +465,14 @@ export function issAimMatrix(pivot, direction, result) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives the loaded model's joints. Stateless about the model: `update` looks
|
||||
* the nodes up once per model and only writes a node whose angle moved.
|
||||
* Poses the model's joints: `update` works out each joint's transform and
|
||||
* `poses()` hands them over by node name, for the model item's `nodes`
|
||||
* (render contract). A joint's matrix is changed where it is, and only when
|
||||
* its angle moved.
|
||||
*/
|
||||
export function createIssArticulation() {
|
||||
let boundModel = null;
|
||||
let nodes = null;
|
||||
/** Node name → its column-major matrix, as last posed. */
|
||||
let poses = {};
|
||||
let angles = null;
|
||||
let targets = { alpha: 0, gamma: 0 };
|
||||
let lastMs = 0;
|
||||
@@ -475,7 +482,6 @@ export function createIssArticulation() {
|
||||
let lastSunlit = null;
|
||||
/** Command panel state: the arm is being posed by hand, so the sway is off. */
|
||||
let armManual = false;
|
||||
let armNodes = null;
|
||||
/** Command panel state: how far the arrays are rolled out, 0.05 to 1. */
|
||||
let deploy = 1;
|
||||
let deployTarget = 1;
|
||||
@@ -493,55 +499,26 @@ export function createIssArticulation() {
|
||||
const SMALL_RADIATOR_ROOT_Y = -1.6;
|
||||
/** Where each dish looks now, on the model's axes. */
|
||||
let dishes = null;
|
||||
const scratchJulian = new Cesium.JulianDate();
|
||||
const scratchSun = new Cesium.Cartesian3();
|
||||
const scratchToFixed = new Cesium.Matrix3();
|
||||
const scratchMatrix = new Cesium.Matrix4();
|
||||
|
||||
function bind(model) {
|
||||
boundModel = model;
|
||||
const get = (joint) => model.getNode(joint.node) ?? null;
|
||||
nodes = {
|
||||
alpha: ISS_ALPHA_JOINTS.map(get),
|
||||
beta: ISS_BETA_JOINTS.map(get),
|
||||
gamma: ISS_RADIATOR_JOINTS.map(get),
|
||||
dish: ISS_DISH_JOINTS.map(get),
|
||||
};
|
||||
angles = null;
|
||||
dishes = null;
|
||||
armNodes = null;
|
||||
}
|
||||
|
||||
function sunEcef(date) {
|
||||
const julian = Cesium.JulianDate.fromDate(date, scratchJulian);
|
||||
const inertial =
|
||||
Cesium.Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame(
|
||||
julian,
|
||||
scratchSun,
|
||||
);
|
||||
const toFixed =
|
||||
Cesium.Transforms.computeIcrfToFixedMatrix(julian, scratchToFixed) ??
|
||||
Cesium.Transforms.computeTemeToPseudoFixedMatrix(julian, scratchToFixed);
|
||||
Cesium.Matrix3.multiplyByVector(toFixed, inertial, scratchSun);
|
||||
Cesium.Cartesian3.normalize(scratchSun, scratchSun);
|
||||
return [scratchSun.x, scratchSun.y, scratchSun.z];
|
||||
const sun = sunPositionFixed(date.getTime());
|
||||
const length = Math.hypot(sun.x, sun.y, sun.z);
|
||||
return [sun.x / length, sun.y / length, sun.z / length];
|
||||
}
|
||||
|
||||
function write(node, axis, pivot, angle) {
|
||||
if (!node) return;
|
||||
node.matrix = issJointMatrix(axis, pivot, angle, scratchMatrix);
|
||||
/** The node's matrix, kept per node so each is changed where it is. */
|
||||
const matrixOf = (name) => (poses[name] ??= new Array(16));
|
||||
|
||||
function write(name, axis, pivot, angle) {
|
||||
issJointMatrix(axis, pivot, angle, matrixOf(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Cesium.Model} model A ready model.
|
||||
* @param {Date} date The instant the model is placed at.
|
||||
* @param {Cesium.Cartesian3} position Earth-fixed station position.
|
||||
* @param {{x:number,y:number,z:number}} position Earth-fixed station position.
|
||||
* @param {{x:number[], y:number[], z:number[]}} axes Its flight axes.
|
||||
* @param {number} [nowMs] Wall clock, for the turn rate.
|
||||
*/
|
||||
function update(model, date, position, axes, nowMs = Date.now()) {
|
||||
if (!model.ready) return;
|
||||
if (model !== boundModel) bind(model);
|
||||
function update(date, position, axes, nowMs = Date.now()) {
|
||||
const forced = override?.(nowMs) ?? null;
|
||||
if (forced) {
|
||||
lastSunlit = Boolean(forced.sunlit);
|
||||
@@ -568,7 +545,7 @@ export function createIssArticulation() {
|
||||
};
|
||||
if (!angles || next.alpha !== angles.alpha)
|
||||
ISS_ALPHA_JOINTS.forEach((joint, i) =>
|
||||
write(nodes.alpha[i], 'x', joint.pivot, next.alpha),
|
||||
write(joint.node, 'x', joint.pivot, next.alpha),
|
||||
);
|
||||
// Command panel: squash the arrays along their masts (see setDeploy).
|
||||
const deployStep = Number.isFinite(maxStep) ? elapsed / 8 : 1;
|
||||
@@ -583,12 +560,14 @@ export function createIssArticulation() {
|
||||
nextDeploy !== deploy ||
|
||||
nextDeploy !== 1
|
||||
) {
|
||||
const node = nodes.beta[i];
|
||||
if (!node) return;
|
||||
const m = issJointMatrix('z', joint.pivot, next.beta[i], scratchMatrix);
|
||||
const m = issJointMatrix(
|
||||
'z',
|
||||
joint.pivot,
|
||||
next.beta[i],
|
||||
matrixOf(joint.node),
|
||||
);
|
||||
m[10] = nextDeploy;
|
||||
m[14] = joint.pivot[2] * (1 - nextDeploy);
|
||||
node.matrix = m;
|
||||
}
|
||||
});
|
||||
deploy = nextDeploy;
|
||||
@@ -603,39 +582,36 @@ export function createIssArticulation() {
|
||||
nextRadiator !== radiatorDeploy
|
||||
)
|
||||
ISS_RADIATOR_JOINTS.forEach((joint, i) => {
|
||||
const node = nodes.gamma[i];
|
||||
if (!node) return;
|
||||
const m = issJointMatrix('z', joint.pivot, next.gamma, scratchMatrix);
|
||||
const m = issJointMatrix(
|
||||
'z',
|
||||
joint.pivot,
|
||||
next.gamma,
|
||||
matrixOf(joint.node),
|
||||
);
|
||||
m[10] = nextRadiator;
|
||||
m[14] = RADIATOR_ROOT_Z * (1 - nextRadiator);
|
||||
node.matrix = m;
|
||||
});
|
||||
// The four small radiators fold up to the truss, along Y.
|
||||
if (nextRadiator !== radiatorDeploy)
|
||||
for (const name of SMALL_RADIATOR_NODES) {
|
||||
const node = model.getNode(name);
|
||||
if (!node) continue;
|
||||
node.matrix = Cesium.Matrix4.fromRowMajorArray(
|
||||
[
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
nextRadiator,
|
||||
0,
|
||||
SMALL_RADIATOR_ROOT_Y * (1 - nextRadiator),
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
],
|
||||
scratchMatrix,
|
||||
);
|
||||
set(matrixOf(name), [
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
nextRadiator,
|
||||
0,
|
||||
SMALL_RADIATOR_ROOT_Y * (1 - nextRadiator),
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
]);
|
||||
}
|
||||
radiatorDeploy = nextRadiator;
|
||||
angles = next;
|
||||
@@ -652,13 +628,7 @@ export function createIssArticulation() {
|
||||
const stepped = issStepDirection(current, target, maxStep);
|
||||
const moved =
|
||||
!dishes || stepped.some((c, k) => Math.abs(c - current[k]) > 1e-9);
|
||||
if (moved)
|
||||
if (nodes.dish[i])
|
||||
nodes.dish[i].matrix = issAimMatrix(
|
||||
joint.pivot,
|
||||
stepped,
|
||||
scratchMatrix,
|
||||
);
|
||||
if (moved) issAimMatrix(joint.pivot, stepped, matrixOf(joint.node));
|
||||
return stepped;
|
||||
});
|
||||
dishes = nextDishes;
|
||||
@@ -668,16 +638,7 @@ export function createIssArticulation() {
|
||||
const arm = issArmAngles(nowMs / 1000, ISS_SWAY_JOINTS);
|
||||
ISS_SWAY_JOINTS.forEach((joint, i) => {
|
||||
if (!joint.sway) return;
|
||||
const node = (armNodes ??= ISS_SWAY_JOINTS.map(
|
||||
(entry) => model.getNode(entry.node) ?? null,
|
||||
))[i];
|
||||
if (node)
|
||||
node.matrix = issAxisMatrix(
|
||||
joint.pivot,
|
||||
joint.axis,
|
||||
arm[i],
|
||||
scratchMatrix,
|
||||
);
|
||||
issAxisMatrix(joint.pivot, joint.axis, arm[i], matrixOf(joint.node));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -691,16 +652,13 @@ export function createIssArticulation() {
|
||||
*/
|
||||
function setJoint(name, pivot, axis, angle) {
|
||||
armManual = true;
|
||||
const node = boundModel?.getNode(name);
|
||||
if (node) node.matrix = issAxisMatrix(pivot, axis, angle, scratchMatrix);
|
||||
issAxisMatrix(pivot, axis, angle, matrixOf(name));
|
||||
}
|
||||
|
||||
function reset() {
|
||||
boundModel = null;
|
||||
nodes = null;
|
||||
poses = {};
|
||||
angles = null;
|
||||
dishes = null;
|
||||
armNodes = null;
|
||||
targets = { alpha: 0, gamma: 0 };
|
||||
}
|
||||
|
||||
@@ -749,6 +707,8 @@ export function createIssArticulation() {
|
||||
|
||||
return {
|
||||
update,
|
||||
/** The joints' matrices by node name, for the model item's `nodes`. */
|
||||
poses: () => poses,
|
||||
reset,
|
||||
setOverride,
|
||||
setDishOverride,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { onLocaleChange, t } from '../../i18n/index.js';
|
||||
import { ISS_ARM_JOINTS } from './issArticulation.js';
|
||||
import { makePanelDraggable } from './issLive.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
/**
|
||||
@@ -111,11 +112,31 @@ export function createIssCommand({ state: layerState, parts }) {
|
||||
renderUntil = Math.max(renderUntil, Date.now() + ms);
|
||||
if (renderTimer) return;
|
||||
renderTimer = setInterval(() => {
|
||||
layerState._viewer?.scene?.requestRender?.();
|
||||
_requestFrame();
|
||||
if (Date.now() > renderUntil) _stopRendering();
|
||||
}, 33);
|
||||
}
|
||||
|
||||
/** Ask the renderer for a frame, so the layer's tick poses the joints. */
|
||||
function _requestFrame() {
|
||||
findFrame(layerState._viewer)?.requestRender('satellites:iss-command');
|
||||
}
|
||||
|
||||
/** The eye's ECEF position, or null. */
|
||||
function _eye() {
|
||||
return findCamera(layerState._viewer)?.pose?.()?.position ?? null;
|
||||
}
|
||||
|
||||
/** Where the station is drawn now, or null. */
|
||||
function _stationPosition() {
|
||||
return (
|
||||
parts.issModel?._issVisualPosition?.() ??
|
||||
layerState._trackedFrameCartesian ??
|
||||
layerState._points.get(ISS_NORAD)?.pos ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function _stopRendering() {
|
||||
if (renderTimer) clearInterval(renderTimer);
|
||||
renderTimer = null;
|
||||
@@ -141,13 +162,10 @@ export function createIssCommand({ state: layerState, parts }) {
|
||||
|
||||
/** Meters from the camera to the station, or null when unknown. */
|
||||
function _stationDistance() {
|
||||
const viewer = layerState._viewer;
|
||||
const target =
|
||||
parts.issModel?._issVisualPosition?.() ??
|
||||
layerState._trackedFrameCartesian ??
|
||||
layerState._points.get(ISS_NORAD)?.position;
|
||||
if (!viewer || !target) return null;
|
||||
return Cesium.Cartesian3.distance(viewer.camera.positionWC, target);
|
||||
const eye = _eye();
|
||||
const target = _stationPosition();
|
||||
if (!eye || !target) return null;
|
||||
return distance(eye, target);
|
||||
}
|
||||
|
||||
function _syncZoomButton() {
|
||||
@@ -164,36 +182,40 @@ export function createIssCommand({ state: layerState, parts }) {
|
||||
|
||||
/**
|
||||
* Bring the follow camera in to the station. The camera already tracks the
|
||||
* ISS, so this only shortens its range, a step per frame.
|
||||
* ISS, so this only shortens its offset from the station, a step per
|
||||
* frame.
|
||||
*/
|
||||
function _zoomToStation() {
|
||||
_stopZoom();
|
||||
let steps = 0;
|
||||
zoomTimer = setInterval(() => {
|
||||
const viewer = layerState._viewer;
|
||||
const target =
|
||||
parts.issModel?._issVisualPosition?.() ??
|
||||
layerState._trackedFrameCartesian ??
|
||||
layerState._points.get(ISS_NORAD)?.position;
|
||||
const camera = findCamera(layerState._viewer);
|
||||
const range = _stationDistance();
|
||||
const offset = camera?.followOffset.get();
|
||||
steps += 1;
|
||||
if (
|
||||
!viewer ||
|
||||
!target ||
|
||||
!camera ||
|
||||
range === null ||
|
||||
!offset ||
|
||||
layerState._trackedNorad !== ISS_NORAD ||
|
||||
steps > 400
|
||||
) {
|
||||
_stopZoom();
|
||||
return;
|
||||
}
|
||||
const step = issCommandZoomStep(
|
||||
Cesium.Cartesian3.distance(viewer.camera.positionWC, target),
|
||||
);
|
||||
if (!step) {
|
||||
const step = issCommandZoomStep(range);
|
||||
const length = Math.hypot(offset.x, offset.y, offset.z);
|
||||
if (!step || !(length > step)) {
|
||||
_stopZoom();
|
||||
return;
|
||||
}
|
||||
viewer.camera.zoomIn(step);
|
||||
viewer.scene.requestRender?.();
|
||||
const k = (length - step) / length;
|
||||
camera.followOffset.set({
|
||||
x: offset.x * k,
|
||||
y: offset.y * k,
|
||||
z: offset.z * k,
|
||||
});
|
||||
_requestFrame();
|
||||
}, 16);
|
||||
}
|
||||
|
||||
|
||||
+177
-137
@@ -1,5 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { eciToGeodetic, gstime, propagate } from 'satellite.js';
|
||||
import { fromRadians } from '../../geo/ellipsoid.js';
|
||||
import { eastNorthUp } from '../../geo/frames.js';
|
||||
import { distance, dot, vec } from '../../geo/vector.js';
|
||||
import { canvasOf, drawOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { createIssArticulation } from './issArticulation.js';
|
||||
import {
|
||||
ISS_COMPANION_COARSE_M,
|
||||
@@ -79,6 +82,31 @@ export function temeToEcefAxes(v, gmst) {
|
||||
return { x: c * v.x + s * v.y, y: -s * v.x + c * v.y, z: v.z };
|
||||
}
|
||||
|
||||
/**
|
||||
* The heading, pitch and roll (the render contract's model orientation, in
|
||||
* the east-north-up frame at `origin`) that turn the model's local axes onto
|
||||
* `axes` (ECEF unit vectors, for local X, Y and Z): the inverse of
|
||||
* `geo/quaternion`'s `headingPitchRollFrame`, whose rotation is
|
||||
* Rz(−heading)·Ry(−pitch)·Rx(roll).
|
||||
* @param {{x:number,y:number,z:number}} origin ECEF metres.
|
||||
* @param {number[][]} axes The ECEF directions of local X, Y and Z.
|
||||
* @returns {{heading:number, pitch:number, roll:number}}
|
||||
*/
|
||||
export function issOrientation(origin, axes) {
|
||||
const enu = eastNorthUp(origin);
|
||||
const local = axes.map((a) => {
|
||||
const v = vec(a[0], a[1], a[2]);
|
||||
return [dot(enu.x, v), dot(enu.y, v), dot(enu.z, v)];
|
||||
});
|
||||
// local[column][row]: the rotation in the east-north-up frame.
|
||||
const m20 = Math.max(-1, Math.min(1, local[0][2]));
|
||||
return {
|
||||
heading: -Math.atan2(local[0][1], local[0][0]),
|
||||
pitch: Math.asin(m20),
|
||||
roll: Math.atan2(local[1][2], local[2][2]),
|
||||
};
|
||||
}
|
||||
|
||||
function cross(a, b) {
|
||||
return [
|
||||
a[1] * b[2] - a[2] * b[1],
|
||||
@@ -94,38 +122,41 @@ function unit(a) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The ISS as a 3D model when the camera is close. Far out the dot stays: the
|
||||
* The ISS as a 3D model when the camera is close, drawn as an item of a
|
||||
* `models` set of the renderer's draw port. Far out the dot stays: the
|
||||
* model and the dot (ambient and tracked) split the distance range, so exactly
|
||||
* one of them draws. The model loads on first need and only if the ISS is
|
||||
* shown, and positions itself every frame from its own SGP4 sample (the dot
|
||||
* moves once a second, which at model range would show as a jump).
|
||||
* moves once a second, which at model range would show as a jump). Its
|
||||
* joints are posed through the item's `nodes`.
|
||||
*/
|
||||
export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
let model = null;
|
||||
let loading = false;
|
||||
/** The models set, made on first need; null until then or after a failure. */
|
||||
let set = null;
|
||||
/** Whether the model has loaded and draws. */
|
||||
let ready = false;
|
||||
let failed = false;
|
||||
let generation = 0;
|
||||
let instances = 0;
|
||||
/** Whether the item was last sent shown. */
|
||||
let shown = false;
|
||||
/** Turns the solar arrays and radiators by where the Sun is. */
|
||||
const articulation = createIssArticulation();
|
||||
const nearCondition = new Cesium.DistanceDisplayCondition(
|
||||
0,
|
||||
const nearRange = Object.freeze([0, ISS_MODEL_MAX_DISTANCE_M]);
|
||||
const farRange = Object.freeze([
|
||||
ISS_MODEL_MAX_DISTANCE_M,
|
||||
);
|
||||
const farCondition = new Cesium.DistanceDisplayCondition(
|
||||
ISS_MODEL_MAX_DISTANCE_M,
|
||||
Number.MAX_VALUE,
|
||||
);
|
||||
Number.POSITIVE_INFINITY,
|
||||
]);
|
||||
/** @type {Set<number>} Docked objects whose dots the model stands in for. */
|
||||
const handedCompanions = new Set();
|
||||
let lastCompanionScanMs = Number.NEGATIVE_INFINITY;
|
||||
/** Whether the ISS's orbit ring is hidden for the close-up. */
|
||||
let orbitHidden = false;
|
||||
const scratchPosition = new Cesium.Cartesian3();
|
||||
/** The station centre the model last rendered at (for the tracked card). */
|
||||
const visualPosition = new Cesium.Cartesian3();
|
||||
const visualPosition = { x: 0, y: 0, z: 0 };
|
||||
let visualValid = false;
|
||||
const scratchRotation = new Cesium.Matrix3();
|
||||
const scratchColumn = new Cesium.Cartesian3();
|
||||
/** The model's item, changed where it is and sent each frame it shows. */
|
||||
let item = null;
|
||||
|
||||
function _shouldShow() {
|
||||
const tracked = layerState._trackedNorad === ISS_NORAD;
|
||||
@@ -141,33 +172,61 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
});
|
||||
}
|
||||
|
||||
async function _load() {
|
||||
loading = true;
|
||||
const loadGeneration = generation;
|
||||
try {
|
||||
const loaded = await Cesium.Model.fromGltfAsync({
|
||||
url: resolveAsset(ISS_MODEL_URL),
|
||||
scale: ISS_MODEL_SCALE,
|
||||
minimumPixelSize: ISS_MODEL_MIN_PX,
|
||||
distanceDisplayCondition: nearCondition,
|
||||
// So a click on the model tracks the ISS, as a click on its dot does.
|
||||
id: ISS_NORAD,
|
||||
show: false,
|
||||
});
|
||||
const viewer = layerState._viewer;
|
||||
if (loadGeneration !== generation || !viewer) {
|
||||
loaded.destroy();
|
||||
return;
|
||||
}
|
||||
viewer.scene.primitives.add(loaded);
|
||||
model = loaded;
|
||||
} catch (error) {
|
||||
// The dot keeps drawing at every distance; nothing else depends on this.
|
||||
/** The eye's ECEF position, or null. */
|
||||
function _eye() {
|
||||
return findCamera(layerState._viewer)?.pose?.()?.position ?? null;
|
||||
}
|
||||
|
||||
/** Make the models set and add the model to it (fetched from now on). */
|
||||
function _load() {
|
||||
const draw = layerState._viewer ? drawOf(layerState._viewer) : null;
|
||||
if (!draw?.models) {
|
||||
// A renderer without models: the dot keeps drawing at every distance.
|
||||
failed = true;
|
||||
console.warn('[Data:Satellites] ISS model failed to load:', error);
|
||||
} finally {
|
||||
if (loadGeneration === generation) loading = false;
|
||||
return;
|
||||
}
|
||||
const loadGeneration = generation;
|
||||
set = draw.models({ id: `satellites:iss-model:${++instances}` });
|
||||
set.on('ready', () => {
|
||||
if (loadGeneration === generation) ready = true;
|
||||
});
|
||||
set.on('loadFailed', (_id, message) => {
|
||||
if (loadGeneration !== generation) return;
|
||||
// The dot keeps drawing at every distance; nothing else depends on this.
|
||||
console.warn('[Data:Satellites] ISS model failed to load:', message);
|
||||
_disposeSet();
|
||||
failed = true;
|
||||
});
|
||||
item = {
|
||||
id: 'iss',
|
||||
url: resolveAsset(ISS_MODEL_URL),
|
||||
pos: { x: 0, y: 0, z: 0 },
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
scale: ISS_MODEL_SCALE,
|
||||
minPixelSize: ISS_MODEL_MIN_PX,
|
||||
displayRange: nearRange,
|
||||
nodes: articulation.poses(),
|
||||
show: false,
|
||||
meta: { noradId: ISS_NORAD },
|
||||
};
|
||||
shown = false;
|
||||
set.upsert([item]);
|
||||
}
|
||||
|
||||
function _disposeSet() {
|
||||
set?.dispose();
|
||||
set = null;
|
||||
item = null;
|
||||
ready = false;
|
||||
shown = false;
|
||||
}
|
||||
|
||||
/** Hide the model (sent only when it showed). */
|
||||
function _hide() {
|
||||
if (!set || !item || !shown) return;
|
||||
item.show = false;
|
||||
shown = false;
|
||||
set.upsert([item]);
|
||||
}
|
||||
|
||||
/** An object's inertial position at `date`, km, or null. */
|
||||
@@ -183,15 +242,15 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
|
||||
/** Leave the near range to the model: the dots draw only beyond it. */
|
||||
function _handOverDots() {
|
||||
const point = layerState._points.get(ISS_NORAD);
|
||||
if (point && point.distanceDisplayCondition !== farCondition)
|
||||
point.distanceDisplayCondition = farCondition;
|
||||
const dot =
|
||||
layerState._trackedNorad === ISS_NORAD
|
||||
? layerState._trackedEntity?.point
|
||||
: null;
|
||||
if (dot && !dot.distanceDisplayCondition)
|
||||
dot.distanceDisplayCondition = farCondition;
|
||||
parts.rendering._setPointRange(ISS_NORAD, farRange);
|
||||
if (layerState._trackedNorad === ISS_NORAD)
|
||||
parts.rendering._setTrackedDotRange(farRange);
|
||||
}
|
||||
|
||||
/** Give the ISS's dots back their whole range. */
|
||||
function _releaseDots() {
|
||||
parts.rendering._setPointRange(ISS_NORAD, undefined);
|
||||
parts.rendering._setTrackedDotRange(undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,7 +265,7 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
function _handOverCompanions(nowMs) {
|
||||
if (nowMs - lastCompanionScanMs < ISS_COMPANION_SCAN_MS) return;
|
||||
lastCompanionScanMs = nowMs;
|
||||
const issPosition = layerState._points.get(ISS_NORAD)?.position;
|
||||
const issPosition = layerState._points.get(ISS_NORAD)?.pos;
|
||||
// The dots are placed at different moments (far apart with the clock sped
|
||||
// up), so their spacing only rules out what is nowhere near. Whether an
|
||||
// object is docked is read from both orbits at one instant.
|
||||
@@ -214,14 +273,11 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
const issTeme = _temeKm(layerState._catalog.get(ISS_NORAD)?.satrec, date);
|
||||
if (!issPosition || !issTeme) return;
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (noradId === ISS_NORAD || !point?.position) continue;
|
||||
if (noradId === ISS_NORAD || !point?.pos) continue;
|
||||
const entry = layerState._catalog.get(noradId);
|
||||
if (entry?.group === 'dense') continue;
|
||||
let docked = false;
|
||||
if (
|
||||
Cesium.Cartesian3.distance(point.position, issPosition) <=
|
||||
ISS_COMPANION_COARSE_M
|
||||
) {
|
||||
if (distance(point.pos, issPosition) <= ISS_COMPANION_COARSE_M) {
|
||||
const teme = _temeKm(entry?.satrec, date);
|
||||
docked =
|
||||
Boolean(teme) &&
|
||||
@@ -234,10 +290,10 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
ISS_COMPANION_RADIUS_M;
|
||||
}
|
||||
if (docked) {
|
||||
point.distanceDisplayCondition = farCondition; // no-op when equal
|
||||
parts.rendering._setPointRange(noradId, farRange); // no-op when equal
|
||||
handedCompanions.add(noradId);
|
||||
} else if (handedCompanions.has(noradId)) {
|
||||
point.distanceDisplayCondition = undefined;
|
||||
parts.rendering._setPointRange(noradId, undefined);
|
||||
handedCompanions.delete(noradId);
|
||||
}
|
||||
}
|
||||
@@ -245,10 +301,8 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
|
||||
/** Give docked objects their dots back at every distance. */
|
||||
function _releaseCompanions() {
|
||||
for (const noradId of handedCompanions) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (point) point.distanceDisplayCondition = undefined;
|
||||
}
|
||||
for (const noradId of handedCompanions)
|
||||
parts.rendering._setPointRange(noradId, undefined);
|
||||
handedCompanions.clear();
|
||||
lastCompanionScanMs = Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
@@ -259,9 +313,8 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
* @param {boolean} near Camera within ISS_ORBIT_HIDE_M of the station.
|
||||
*/
|
||||
function _syncOrbitCloseUp(near) {
|
||||
const path = layerState._orbitPaths.get(ISS_NORAD);
|
||||
if (near) {
|
||||
if (path) path.primitive.show = false;
|
||||
parts.rendering._setOrbitPathShown(ISS_NORAD, false);
|
||||
orbitHidden = true;
|
||||
} else if (orbitHidden) {
|
||||
orbitHidden = false;
|
||||
@@ -272,42 +325,42 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-frame update from the layer's preRender tick.
|
||||
* Per-frame update from the layer's tick.
|
||||
* @returns {void}
|
||||
*/
|
||||
function _updateIssModel() {
|
||||
visualValid = false;
|
||||
const show = _shouldShow();
|
||||
if (!show) {
|
||||
if (model) model.show = false;
|
||||
_hide();
|
||||
if (ready) _releaseDots();
|
||||
if (handedCompanions.size) _releaseCompanions();
|
||||
_syncOrbitCloseUp(false);
|
||||
return;
|
||||
}
|
||||
const point = layerState._points.get(ISS_NORAD);
|
||||
const camera = layerState._viewer?.camera;
|
||||
const eye = _eye();
|
||||
const cameraDistance =
|
||||
point?.position && camera
|
||||
? Cesium.Cartesian3.distance(camera.positionWC, point.position)
|
||||
: Number.POSITIVE_INFINITY;
|
||||
if (!model) {
|
||||
point?.pos && eye ? distance(eye, point.pos) : Number.POSITIVE_INFINITY;
|
||||
if (!set) {
|
||||
// The file is fetched only once the camera nears the model's range, so
|
||||
// a globe-wide view of the layer never downloads it.
|
||||
if (
|
||||
!loading &&
|
||||
!failed &&
|
||||
resolveAsset &&
|
||||
cameraDistance <= ISS_MODEL_MAX_DISTANCE_M * 1.5
|
||||
)
|
||||
_load();
|
||||
return;
|
||||
if (!set) return;
|
||||
}
|
||||
if (ready) {
|
||||
_handOverDots();
|
||||
_handOverCompanions(Date.now());
|
||||
_syncOrbitCloseUp(cameraDistance < ISS_ORBIT_HIDE_M);
|
||||
}
|
||||
_handOverDots();
|
||||
_handOverCompanions(Date.now());
|
||||
_syncOrbitCloseUp(cameraDistance < ISS_ORBIT_HIDE_M);
|
||||
// Out of range the model would not draw anyway: skip the SGP4 sample.
|
||||
if (cameraDistance > ISS_MODEL_MAX_DISTANCE_M * 1.5) {
|
||||
model.show = false;
|
||||
_hide();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -332,54 +385,40 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
!posVel.velocity ||
|
||||
typeof posVel.velocity === 'boolean'
|
||||
) {
|
||||
model.show = false;
|
||||
_hide();
|
||||
return;
|
||||
}
|
||||
const gmst = gstime(date);
|
||||
let position;
|
||||
if (trackedSample) {
|
||||
// The sample the follow camera and the tracked dot were placed from.
|
||||
Cesium.Cartesian3.clone(
|
||||
layerState._trackedFrameCartesian,
|
||||
scratchPosition,
|
||||
);
|
||||
const c = layerState._trackedFrameCartesian;
|
||||
position = { x: c.x, y: c.y, z: c.z };
|
||||
} else {
|
||||
const geo = eciToGeodetic(posVel.position, gmst);
|
||||
Cesium.Cartesian3.fromRadians(
|
||||
geo.longitude,
|
||||
geo.latitude,
|
||||
geo.height * 1000,
|
||||
undefined,
|
||||
scratchPosition,
|
||||
);
|
||||
position = fromRadians(geo.longitude, geo.latitude, geo.height * 1000);
|
||||
}
|
||||
Cesium.Cartesian3.clone(scratchPosition, visualPosition);
|
||||
const axes = issFlightAxes(
|
||||
scratchPosition,
|
||||
temeToEcefAxes(posVel.velocity, gmst),
|
||||
);
|
||||
const axes = issFlightAxes(position, temeToEcefAxes(posVel.velocity, gmst));
|
||||
if (!axes) {
|
||||
model.show = false;
|
||||
_hide();
|
||||
return;
|
||||
}
|
||||
ISS_MODEL_LOCAL_AXES.forEach((key, column) => {
|
||||
scratchColumn.x = axes[key][0];
|
||||
scratchColumn.y = axes[key][1];
|
||||
scratchColumn.z = axes[key][2];
|
||||
Cesium.Matrix3.setColumn(
|
||||
scratchRotation,
|
||||
column,
|
||||
scratchColumn,
|
||||
scratchRotation,
|
||||
);
|
||||
});
|
||||
Cesium.Matrix4.fromRotationTranslation(
|
||||
scratchRotation,
|
||||
scratchPosition,
|
||||
model.modelMatrix,
|
||||
articulation.update(date, position, axes);
|
||||
item.pos.x = position.x;
|
||||
item.pos.y = position.y;
|
||||
item.pos.z = position.z;
|
||||
item.orientation = issOrientation(
|
||||
position,
|
||||
ISS_MODEL_LOCAL_AXES.map((key) => axes[key]),
|
||||
);
|
||||
articulation.update(model, date, scratchPosition, axes);
|
||||
model.show = true;
|
||||
visualValid = true;
|
||||
item.nodes = articulation.poses();
|
||||
item.show = true;
|
||||
shown = true;
|
||||
set.upsert([item]);
|
||||
visualPosition.x = position.x;
|
||||
visualPosition.y = position.y;
|
||||
visualPosition.z = position.z;
|
||||
visualValid = ready;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -387,16 +426,12 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
* rendering at this frame, or null while the model is not drawn (the card
|
||||
* then keeps the dot's position). Up close the dot's cache can be a frame
|
||||
* ahead of the rendered model, ~130 m of orbit, which shook the card.
|
||||
* @returns {Cesium.Cartesian3|null}
|
||||
* @returns {{x:number,y:number,z:number}|null}
|
||||
*/
|
||||
function _issVisualPosition() {
|
||||
if (!visualValid || !model?.show) return null;
|
||||
const camera = layerState._viewer?.camera;
|
||||
if (
|
||||
camera &&
|
||||
Cesium.Cartesian3.distance(camera.positionWC, visualPosition) >
|
||||
ISS_MODEL_MAX_DISTANCE_M
|
||||
)
|
||||
if (!visualValid || !shown) return null;
|
||||
const eye = _eye();
|
||||
if (eye && distance(eye, visualPosition) > ISS_MODEL_MAX_DISTANCE_M)
|
||||
return null;
|
||||
return visualPosition;
|
||||
}
|
||||
@@ -407,14 +442,13 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
*/
|
||||
function _issCardClearPx() {
|
||||
const position = _issVisualPosition();
|
||||
const viewer = layerState._viewer;
|
||||
const camera = viewer?.camera;
|
||||
const height = viewer?.scene?.canvas?.clientHeight;
|
||||
const fovy = camera?.frustum?.fovy;
|
||||
if (!position || !height || !fovy) return null;
|
||||
const distance = Cesium.Cartesian3.distance(camera.positionWC, position);
|
||||
if (!(distance > 0)) return null;
|
||||
const pixelsPerMeter = height / (2 * Math.tan(fovy / 2)) / distance;
|
||||
const pose = findCamera(layerState._viewer)?.pose?.();
|
||||
const height = canvasOf(layerState._viewer)?.clientHeight;
|
||||
const fovy = pose?.fovy;
|
||||
if (!position || !pose?.position || !height || !fovy) return null;
|
||||
const range = distance(pose.position, position);
|
||||
if (!(range > 0)) return null;
|
||||
const pixelsPerMeter = height / (2 * Math.tan(fovy / 2)) / range;
|
||||
return Math.min(
|
||||
height * 0.45,
|
||||
Math.max(ISS_MODEL_MIN_PX * 0.35, ISS_CARD_CLEAR_M * pixelsPerMeter),
|
||||
@@ -423,19 +457,13 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
|
||||
function _destroyIssModel() {
|
||||
generation += 1;
|
||||
loading = false;
|
||||
failed = false;
|
||||
visualValid = false;
|
||||
articulation.reset();
|
||||
if (ready) _releaseDots();
|
||||
_releaseCompanions();
|
||||
_syncOrbitCloseUp(false);
|
||||
if (model) {
|
||||
const scene = layerState._viewer?.scene;
|
||||
if (scene && scene.primitives.contains(model))
|
||||
scene.primitives.remove(model); // remove() destroys
|
||||
else if (!model.isDestroyed()) model.destroy();
|
||||
model = null;
|
||||
}
|
||||
_disposeSet();
|
||||
}
|
||||
|
||||
/** Whether the model is standing in for this docked object's dot. */
|
||||
@@ -443,12 +471,24 @@ export function createIssModel({ state: layerState, parts, resolveAsset }) {
|
||||
return handedCompanions.has(noradId) && _issVisualPosition() !== null;
|
||||
}
|
||||
|
||||
/** Whether a click's draw hit is on the model. */
|
||||
function _hitIsIss(hit) {
|
||||
return Boolean(set) && hit?.set === set.id;
|
||||
}
|
||||
|
||||
/** Ask for a frame: the command panel's changes between ticks. */
|
||||
function _requestRender() {
|
||||
if (set && item) set.upsert([item]);
|
||||
}
|
||||
|
||||
return {
|
||||
_updateIssModel,
|
||||
_destroyIssModel,
|
||||
_issVisualPosition,
|
||||
_issCardClearPx,
|
||||
_issStandsInFor,
|
||||
_hitIsIss,
|
||||
_requestRender,
|
||||
/** The joint driver, for the command panel. */
|
||||
_issArticulation: articulation,
|
||||
};
|
||||
|
||||
@@ -38,7 +38,7 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
/** Cached ISS point only; never performs a fresh SGP4 propagation. */
|
||||
|
||||
function _issDisplayCached() {
|
||||
return layerState._points.get(ISS_NORAD)?.position || null;
|
||||
return parts.rendering._pointPosition(ISS_NORAD);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,11 +63,13 @@ export function createLabels({ state: layerState, services, parts, source }) {
|
||||
let changed = false;
|
||||
let found = 0;
|
||||
const next = new Set();
|
||||
for (const [noradId, point] of layerState._points) {
|
||||
if (noradId === layerState._trackedNorad || !point?.position) continue;
|
||||
const dx = point.position.x - trackedPosition.x;
|
||||
const dy = point.position.y - trackedPosition.y;
|
||||
const dz = point.position.z - trackedPosition.z;
|
||||
for (const noradId of layerState._points.keys()) {
|
||||
if (noradId === layerState._trackedNorad) continue;
|
||||
const position = parts.rendering._pointPosition(noradId);
|
||||
if (!position) continue;
|
||||
const dx = position.x - trackedPosition.x;
|
||||
const dy = position.y - trackedPosition.y;
|
||||
const dz = position.z - trackedPosition.z;
|
||||
if (dx * dx + dy * dy + dz * dz > radiusSq) continue;
|
||||
next.add(noradId);
|
||||
found++;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { frameOf } from '../../render/rendererOf.js';
|
||||
import {
|
||||
ISS_NORAD,
|
||||
ISS_OVERLAY_SOURCE_ID,
|
||||
@@ -30,10 +30,17 @@ export function createLifecycle({
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
/** Run the shared per-frame tick before each frame draws. */
|
||||
function onEachFrame(frame) {
|
||||
return frame.on('preRender', (t) => parts.rendering._preRenderTick(t));
|
||||
}
|
||||
|
||||
const methods = {
|
||||
// Catalog data refresh; propagation remains preRender-owned.
|
||||
|
||||
async init(viewer) {
|
||||
// Asked first: a viewer without one fails before anything is built.
|
||||
const frame = frameOf(viewer);
|
||||
parts.catalog._abortActiveUpdates();
|
||||
clearFocusTarget('satellites');
|
||||
parts.issModel?._destroyIssModel();
|
||||
@@ -72,17 +79,14 @@ export function createLifecycle({
|
||||
layerState._catalogRevision++;
|
||||
layerState.coverageChanged();
|
||||
|
||||
// Point primitives for satellite dots
|
||||
layerState._pointCollection = new Cesium.PointPrimitiveCollection();
|
||||
viewer.scene.primitives.add(layerState._pointCollection);
|
||||
// The sets the satellite dots, the tracked dot and the rings draw in
|
||||
parts.rendering._attach(viewer);
|
||||
|
||||
parts.interaction._installClickHandler(viewer);
|
||||
|
||||
// Pre-render listener for real-time position updates
|
||||
// (fleet propagation + tracked per-frame dot + orbit ring GMST rotation)
|
||||
layerState._preRenderListener = viewer.scene.preRender.addEventListener(
|
||||
parts.rendering._preRenderTick,
|
||||
);
|
||||
layerState._preRenderListener = onEachFrame(frame);
|
||||
|
||||
console.log('[Data:Satellites] Initialized');
|
||||
},
|
||||
@@ -90,21 +94,24 @@ export function createLifecycle({
|
||||
enable(viewer) {
|
||||
layerState._enabled = true;
|
||||
holdContinuousRender('satellites'); // per-frame animator (perf wave 2)
|
||||
if (layerState._pointCollection)
|
||||
layerState._pointCollection.show =
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showPoints,
|
||||
);
|
||||
// Orbit ring primitives + persistent ISS host label — show them
|
||||
for (const [noradId, path] of layerState._orbitPaths)
|
||||
path.primitive.show =
|
||||
parts.rendering._setPointsShown(
|
||||
parts.controls.satelliteVisualsVisible(
|
||||
layerState._enabled,
|
||||
layerState._params.showPoints,
|
||||
),
|
||||
);
|
||||
// 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);
|
||||
@@ -115,9 +122,7 @@ export function createLifecycle({
|
||||
return Number.isFinite(norad) && layerState._points.has(norad);
|
||||
});
|
||||
if (!layerState._preRenderListener && viewer) {
|
||||
layerState._preRenderListener = viewer.scene.preRender.addEventListener(
|
||||
parts.rendering._preRenderTick,
|
||||
);
|
||||
layerState._preRenderListener = onEachFrame(frameOf(viewer));
|
||||
}
|
||||
parts.tracking._applyPendingTrackingRestore();
|
||||
layerState.coverageChanged();
|
||||
@@ -128,19 +133,16 @@ export function createLifecycle({
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
layerState._enabled = false;
|
||||
releaseContinuousRender('satellites');
|
||||
if (layerState._pointCollection) layerState._pointCollection.show = false;
|
||||
for (const path of layerState._orbitPaths.values())
|
||||
path.primitive.show = false;
|
||||
parts.rendering._setPointsShown(false);
|
||||
parts.rendering._setOrbitPathsShown(false);
|
||||
parts.issModel?._updateIssModel(); // off: hides the model
|
||||
parts.tracking._clearTracking();
|
||||
parts.issLive?._syncIssLive(); // off: closes the live video
|
||||
parts.issCommand?._syncIssCommand(); // off: closes the command panel
|
||||
parts.labels._syncIssOverlay();
|
||||
// Remove click handler + keydown listener + preRender propagation while disabled
|
||||
if (layerState._clickHandler) {
|
||||
layerState._clickHandler.destroy();
|
||||
layerState._clickHandler = null;
|
||||
}
|
||||
layerState._clickSubscription?.();
|
||||
layerState._clickSubscription = null;
|
||||
if (layerState._trackedEntityChangedRemove) {
|
||||
layerState._trackedEntityChangedRemove();
|
||||
layerState._trackedEntityChangedRemove = null;
|
||||
@@ -160,10 +162,8 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
if (layerState._clickHandler) {
|
||||
layerState._clickHandler.destroy();
|
||||
layerState._clickHandler = null;
|
||||
}
|
||||
layerState._clickSubscription?.();
|
||||
layerState._clickSubscription = null;
|
||||
if (layerState._trackedEntityChangedRemove) {
|
||||
layerState._trackedEntityChangedRemove();
|
||||
layerState._trackedEntityChangedRemove = null;
|
||||
@@ -179,14 +179,8 @@ export function createLifecycle({
|
||||
parts.issModel?._destroyIssModel();
|
||||
parts.issLive?._destroyIssLive();
|
||||
parts.issCommand?._destroyIssCommand();
|
||||
if (layerState._pointCollection) {
|
||||
viewer.scene.primitives.remove(layerState._pointCollection);
|
||||
layerState._pointCollection = null;
|
||||
}
|
||||
// Orbit ring primitives are removed (and destroyed) here
|
||||
for (const path of layerState._orbitPaths.values()) {
|
||||
viewer.scene.primitives.remove(path.primitive);
|
||||
}
|
||||
// The dots', tracked dot's and rings' sets are disposed of
|
||||
parts.rendering._detach(viewer);
|
||||
layerState._points.clear();
|
||||
layerState._detectionObjects.clear();
|
||||
layerState._orbitPaths.clear();
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// dense extras and asked-for exclusions left out.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
function controlsWith(satellites, { classes, dense = [] } = {}) {
|
||||
@@ -15,7 +16,7 @@ function controlsWith(satellites, { classes, dense = [] } = {}) {
|
||||
};
|
||||
for (const sat of satellites) {
|
||||
state._points.set(sat.id, {
|
||||
position: Cesium.Cartesian3.fromDegrees(sat.lon, sat.lat, sat.alt),
|
||||
pos: fromDegrees(sat.lon, sat.lat, sat.alt),
|
||||
});
|
||||
state._catalog.set(sat.id, {
|
||||
name: `${sat.name} `,
|
||||
@@ -26,7 +27,9 @@ function controlsWith(satellites, { classes, dense = [] } = {}) {
|
||||
return createControls({
|
||||
state,
|
||||
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
|
||||
parts: {},
|
||||
parts: {
|
||||
rendering: { _pointPosition: (id) => state._points.get(id)?.pos ?? null },
|
||||
},
|
||||
}).methods;
|
||||
}
|
||||
|
||||
@@ -40,7 +43,7 @@ const SATELLITES = [
|
||||
{ id: 7, name: 'EXTRA', lat: 30.3, lon: -97, alt: 500_000, cls: 'imaging', group: 'dense' },
|
||||
];
|
||||
|
||||
const CENTRE = Cesium.Cartesian3.fromDegrees(-97, 30, 420_000);
|
||||
const CENTRE = fromDegrees(-97, 30, 420_000);
|
||||
|
||||
test('the nearest shown satellites come first, bounded, with their distance', () => {
|
||||
const methods = controlsWith(SATELLITES, {
|
||||
@@ -58,7 +61,7 @@ test('the nearest shown satellites come first, bounded, with their distance', ()
|
||||
);
|
||||
for (let i = 1; i < nearest.length; i += 1)
|
||||
assert.ok(nearest[i].distanceM >= nearest[i - 1].distanceM);
|
||||
const exact = Cesium.Cartesian3.distance(CENTRE, nearest[0].position);
|
||||
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');
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassColor } from '../../data/satelliteClass.js';
|
||||
import satellitesLayer, {
|
||||
_clearSatelliteLabelLifecycleForTest,
|
||||
_setSatelliteLabelLifecycleStateForTest,
|
||||
} from '../../data/satellites.js';
|
||||
import {
|
||||
POINT_STYLES,
|
||||
TRACK_VIEW_FROM_LEO,
|
||||
TRACKED_ORBIT_COLOR,
|
||||
} from './policy.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { gstime } from 'satellite.js';
|
||||
import * as focusDeemphasis from '../../data/focusDeemphasis.js';
|
||||
|
||||
const rgba = (color) => [color.red, color.green, color.blue, color.alpha];
|
||||
|
||||
test('point styles keep the colours the dots were drawn in', () => {
|
||||
const outline = rgba(Cesium.Color.WHITE.withAlpha(0.3));
|
||||
const expected = {
|
||||
iss: Cesium.Color.fromCssColorString('#ff4444'),
|
||||
dense: Cesium.Color.fromCssColorString(
|
||||
satelliteClassColor('dense'),
|
||||
).withAlpha(0.9),
|
||||
};
|
||||
for (const [group, style] of Object.entries(POINT_STYLES)) {
|
||||
const color =
|
||||
expected[group] ??
|
||||
Cesium.Color.fromCssColorString(satelliteClassColor(group));
|
||||
assert.deepEqual([...style.color], rgba(color), `${group} colour`);
|
||||
assert.deepEqual([...style.outlineColor], outline, `${group} outline`);
|
||||
}
|
||||
assert.deepEqual([...TRACKED_ORBIT_COLOR], rgba(Cesium.Color.YELLOW));
|
||||
assert.deepEqual(
|
||||
{ ...TRACK_VIEW_FROM_LEO },
|
||||
{
|
||||
x: -450000,
|
||||
y: -450000,
|
||||
z: 350000,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('positions read back from the drawn dots match the Cesium geodetic conversion', () => {
|
||||
const position = Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 420_000);
|
||||
const point = { pos: position, show: true };
|
||||
_setSatelliteLabelLifecycleStateForTest({
|
||||
viewer: {},
|
||||
satrec: null,
|
||||
point,
|
||||
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
|
||||
});
|
||||
try {
|
||||
const [row] = satellitesLayer.getAllPositions();
|
||||
const carto = Cesium.Cartographic.fromCartesian(position);
|
||||
assert.equal(row.id, 25544);
|
||||
assert.equal(row.position, position, 'the drawn position itself');
|
||||
assert.ok(
|
||||
Math.abs(row.latitude - Cesium.Math.toDegrees(carto.latitude)) < 1e-9,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(row.longitude - Cesium.Math.toDegrees(carto.longitude)) < 1e-9,
|
||||
);
|
||||
assert.ok(Math.abs(row.altitudeM - carto.height) < 1e-6);
|
||||
} finally {
|
||||
_clearSatelliteLabelLifecycleForTest();
|
||||
}
|
||||
});
|
||||
|
||||
test('no part of the layer drives Cesium', () => {
|
||||
const offList = [
|
||||
'catalog',
|
||||
'cockpitSubject',
|
||||
'controls',
|
||||
'index',
|
||||
'ingestion',
|
||||
'interaction',
|
||||
'labels',
|
||||
'lifecycle',
|
||||
'orbits',
|
||||
'policy',
|
||||
'records',
|
||||
'source',
|
||||
'state',
|
||||
'testing',
|
||||
'tracking',
|
||||
];
|
||||
const forbidden = [
|
||||
/from 'cesium'/,
|
||||
/render\/cesium\//,
|
||||
/\bCesium\./,
|
||||
/viewer\??\.entities\b/,
|
||||
/\.scene\b/,
|
||||
/\bscene\./,
|
||||
/\.primitive\b/,
|
||||
// The dots, rings and tracked entity are the rendering part's. Elsewhere
|
||||
// the handles are only stored, cleared, tested or passed on whole, and
|
||||
// the maps answer by id: no member of a handle is read, with or without
|
||||
// optional chaining, and no handle is taken into a local name.
|
||||
/\b_(pointCollection|trackedEntity)\s*(\?\.|\.|\[)/,
|
||||
/\b_(points|orbitPaths)\s*(\?\.|\.|\[)\s*(?!(has|keys|size|clear|set|delete)\b)/,
|
||||
/of\s+[\w.?]*\b_(points|orbitPaths)\s*\)/,
|
||||
/(\.\.\.|Array\.from\()\s*[\w.?]*\b_(points|orbitPaths)\b(?!\s*\??\.)/,
|
||||
/(^|[;{}(\s])\w+\s*=\s*\(*\s*[\w.?]*\b_(pointCollection|trackedEntity|points|orbitPaths)\s*(;|,|\)|\?\?|\|\||&&)/,
|
||||
/\}\s*=\s*\(*\s*[\w.?]*\b_(pointCollection|trackedEntity|points|orbitPaths)\b/,
|
||||
/[\w)\]]\s*(\?\.)?\[\s*['"`]_(pointCollection|trackedEntity|points|orbitPaths)\b/,
|
||||
/\{[^}]*\b_(pointCollection|trackedEntity|points|orbitPaths)\b[^}]*\}\s*=[^=]/,
|
||||
];
|
||||
for (const name of offList) {
|
||||
const source = readFileSync(
|
||||
new URL(`./${name}.js`, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
for (const pattern of forbidden)
|
||||
assert.doesNotMatch(source, pattern, `${name}.js: ${pattern}`);
|
||||
}
|
||||
// The rendering part owns the handles, and draws through the draw port.
|
||||
const rendering = readFileSync(
|
||||
new URL('./rendering.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
for (const pattern of forbidden.slice(0, 7))
|
||||
assert.doesNotMatch(rendering, pattern, `rendering.js: ${pattern}`);
|
||||
// The patterns themselves still catch what they are for.
|
||||
const caught = [
|
||||
'layerState._trackedEntity.position.setValue(p)',
|
||||
'layerState._pointCollection?.removeAll()',
|
||||
'state._trackedEntity?.["position"]',
|
||||
'layerState._points.get(id).show = false',
|
||||
'layerState._orbitPaths?.values()',
|
||||
'for (const p of layerState._points) {}',
|
||||
'const pc = layerState._pointCollection;',
|
||||
'const { _trackedEntity: e } = layerState;',
|
||||
'const e = layerState?._trackedEntity;',
|
||||
'for (const p of layerState?._points) {}',
|
||||
'[...layerState._points]',
|
||||
'Array.from(layerState._orbitPaths)',
|
||||
'e = layerState._trackedEntity;',
|
||||
'let e; e = layerState._trackedEntity;',
|
||||
'const { position } = layerState._trackedEntity;',
|
||||
'const e = layerState._trackedEntity ?? null;',
|
||||
'const e = (layerState._trackedEntity);',
|
||||
'const { get } = layerState._points;',
|
||||
'layerState["_trackedEntity"].position',
|
||||
];
|
||||
for (const line of caught)
|
||||
assert.ok(
|
||||
forbidden.some((pattern) => pattern.test(line)),
|
||||
`not caught: ${line}`,
|
||||
);
|
||||
const allowed = [
|
||||
'layerState._points.has(id)',
|
||||
'layerState._points.size',
|
||||
'layerState._trackedEntity = null;',
|
||||
'parts.rendering._removeTrackedEntity(layerState._trackedEntity);',
|
||||
'layerState._trackedEntityChangedRemove();',
|
||||
'const had = layerState._points.has(id);',
|
||||
'const t = layerState._trackedEntity\n ? a\n : b;',
|
||||
'const ids = ["_points", "_orbitPaths"];',
|
||||
'const n = layerState._orbitPaths.size;',
|
||||
'[...layerState._points.keys()]',
|
||||
'layerState._trackedEntity = parts.rendering._addTrackedEntity({',
|
||||
];
|
||||
for (const line of allowed)
|
||||
assert.ok(
|
||||
!forbidden.some((pattern) => pattern.test(line)),
|
||||
`wrongly caught: ${line}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('the rendering part draws the dots, the tracked dot and the rings through the draw port', () => {
|
||||
const viewer = {};
|
||||
const { draw, unbind } = bindFakeDraw(viewer);
|
||||
try {
|
||||
const state = {
|
||||
now: Date.now,
|
||||
_points: new Map(),
|
||||
_orbitPaths: new Map(),
|
||||
_catalog: new Map([[25544, { satrec: {} }]]),
|
||||
_viewer: viewer,
|
||||
_trackedNorad: null,
|
||||
_enabled: false,
|
||||
};
|
||||
const path = [
|
||||
{ x: 7e6, y: 0, z: 0 },
|
||||
{ x: 0, y: 7e6, z: 0 },
|
||||
{ x: -7e6, y: 0, z: 0 },
|
||||
];
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: {
|
||||
focus: {
|
||||
focusNowMs: (ms) => ms,
|
||||
getFocusTarget: () => null,
|
||||
focusPassIsNeeded: () => false,
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
orbits: { computeOrbitPath: () => path },
|
||||
tracking: { _getTrackedFramePosition: () => sampleFrame() },
|
||||
},
|
||||
});
|
||||
// The frame's own sample, taken after the tick's first part.
|
||||
let sampleFrame = () => null;
|
||||
rendering._attach(viewer);
|
||||
const points = draw.find('satellites:').spec.id;
|
||||
assert.match(points, /^satellites:\d+:points$/);
|
||||
rendering._addPoint(25544, { x: 1, y: 2, z: 3 }, POINT_STYLES.iss);
|
||||
const point = state._points.get(25544);
|
||||
assert.deepEqual(point.pos, { x: 1, y: 2, z: 3 });
|
||||
assert.equal(draw.set(points).items.size, 0, 'sent with the frame');
|
||||
rendering._preRenderTick({ frame: 1 });
|
||||
const drawn = draw.set(points).items.get('25544');
|
||||
assert.equal(drawn, point);
|
||||
assert.deepEqual(
|
||||
[...drawn.color],
|
||||
rgba(Cesium.Color.fromCssColorString('#ff4444')),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...drawn.outlineColor],
|
||||
rgba(Cesium.Color.WHITE.withAlpha(0.3)),
|
||||
);
|
||||
assert.equal(drawn.pixelSize, 12);
|
||||
assert.equal(drawn.outlineWidth, 2);
|
||||
assert.deepEqual(drawn.meta, { noradId: 25544 });
|
||||
assert.deepEqual(
|
||||
{ ...drawn.scaleByDistance },
|
||||
{ near: 1e6, nearValue: 1.5, far: 2e7, farValue: 0.6 },
|
||||
);
|
||||
// Moves go out in one upsert a frame.
|
||||
const writes = draw.set(points).writes;
|
||||
rendering._movePoint(25544, { x: 4, y: 5, z: 6 });
|
||||
rendering._movePoint(25544, { x: 7, y: 8, z: 9 });
|
||||
rendering._preRenderTick({ frame: 2 });
|
||||
assert.equal(draw.set(points).writes, writes + 1);
|
||||
assert.deepEqual(draw.set(points).items.get('25544').pos, {
|
||||
x: 7,
|
||||
y: 8,
|
||||
z: 9,
|
||||
});
|
||||
// A pick on a dot names its satellite; one on another set does not.
|
||||
assert.equal(rendering._hitPointId({ set: points, id: '25544' }), 25544);
|
||||
assert.equal(rendering._hitPointId({ set: 'other:1', id: '25544' }), null);
|
||||
|
||||
rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR);
|
||||
const rings = draw.sets.get(points.replace(':points', ':rings'));
|
||||
assert.equal(rings.spec.pickable, false, 'ring clicks fall through');
|
||||
const ring = rings.items.get('25544');
|
||||
assert.deepEqual(ring.style, { kind: 'solid', color: [1, 1, 0, 0.6] });
|
||||
assert.deepEqual(ring.depthFail, { kind: 'solid', color: [1, 1, 0, 0.35] });
|
||||
assert.equal(ring.widthPx, 2.5, 'the ISS ring is wider');
|
||||
assert.equal(ring.mode, 'geodesic');
|
||||
assert.deepEqual([...ring.positions.slice(0, 3)], [7e6, 0, 0]);
|
||||
// Turned with the Earth: by minus the GMST elapsed since its bake.
|
||||
const path0 = state._orbitPaths.get(25544);
|
||||
const later = new Date(Date.now() + 600_000);
|
||||
rendering._updateOrbitPathRotations(later);
|
||||
const angle = -(gstime(later) - path0.gmstAtBake);
|
||||
const turned = rings.items.get('25544').positions;
|
||||
assert.ok(Math.abs(turned[0] - 7e6 * Math.cos(angle)) < 1e-3);
|
||||
assert.ok(Math.abs(turned[1] - 7e6 * Math.sin(angle)) < 1e-3);
|
||||
rendering._hideOrbitPath(25544);
|
||||
assert.equal(rings.items.size, 0);
|
||||
|
||||
// The tracked dot draws at the tracker's position, from the next frame.
|
||||
state._trackedNorad = 25544;
|
||||
state._enabled = true;
|
||||
state._params = { showPoints: false, showOrbits: false };
|
||||
let at = { x: 10, y: 20, z: 30 };
|
||||
const carrier = rendering._addTrackedEntity({ position: () => at });
|
||||
assert.deepEqual(carrier, { noradId: 25544 });
|
||||
const tracked = draw.set(points.replace(':points', ':tracked'));
|
||||
assert.equal(tracked.items.size, 0);
|
||||
rendering._preRenderTick({ frame: 3 });
|
||||
assert.deepEqual(tracked.items.get('25544').pos, at);
|
||||
assert.equal(tracked.items.get('25544').pixelSize, 14);
|
||||
assert.equal(tracked.items.get('25544').disableDepthTest, Infinity);
|
||||
at = { x: 11, y: 21, z: 31 };
|
||||
rendering._preRenderTick({ frame: 4 });
|
||||
assert.deepEqual(tracked.items.get('25544').pos, at);
|
||||
// When the follow camera has already sampled this frame's key, the dot
|
||||
// draws at that sample, before the frame's own sample moves it on.
|
||||
const framed = { x: 12, y: 22, z: 32 };
|
||||
at = framed;
|
||||
state._trackedFrameGeo = {};
|
||||
state._trackedFrameNumber = 4;
|
||||
sampleFrame = () => {
|
||||
at = { x: 13, y: 23, z: 33 };
|
||||
return at;
|
||||
};
|
||||
rendering._preRenderTick({ frame: 5 });
|
||||
assert.deepEqual(tracked.items.get('25544').pos, framed);
|
||||
// With no sample under the frame's key, it draws after the frame's own.
|
||||
state._trackedFrameNumber = 3;
|
||||
at = framed;
|
||||
rendering._preRenderTick({ frame: 6 });
|
||||
assert.deepEqual(tracked.items.get('25544').pos, { x: 13, y: 23, z: 33 });
|
||||
assert.equal(
|
||||
rendering._hitIsTracked({ set: tracked.spec.id, id: '25544' }),
|
||||
true,
|
||||
);
|
||||
rendering._removeTrackedEntity(carrier);
|
||||
assert.equal(tracked.items.size, 0);
|
||||
rendering._detach(viewer);
|
||||
assert.ok([...draw.sets.values()].every((set) => set.disposed));
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('the orbit frame matrix turns ECEF about Z by minus the GMST elapsed', () => {
|
||||
const rendering = createRendering({
|
||||
state: {},
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
const bake = new Date('2026-07-20T10:00:00Z');
|
||||
const now = new Date('2026-07-20T10:10:00Z');
|
||||
const m = rendering.orbitFrameModelMatrix(gstime(bake), now);
|
||||
const angle = -(gstime(now) - gstime(bake));
|
||||
assert.equal(m.length, 16);
|
||||
assert.ok(Math.abs(m[0] - Math.cos(angle)) < 1e-12);
|
||||
assert.ok(Math.abs(m[1] - Math.sin(angle)) < 1e-12);
|
||||
assert.ok(Math.abs(m[4] + Math.sin(angle)) < 1e-12);
|
||||
assert.equal(m[10], 1);
|
||||
assert.equal(m[15], 1);
|
||||
// Written in place into a matrix it is handed.
|
||||
const into = new Cesium.Matrix4();
|
||||
assert.equal(rendering.orbitFrameModelMatrix(gstime(bake), now, into), into);
|
||||
assert.ok(Math.abs(into[0] - Math.cos(angle)) < 1e-12);
|
||||
});
|
||||
|
||||
test('the focus pass projects every dot in one call and dims the dot under the focus', () => {
|
||||
const viewer = {};
|
||||
const calls = [];
|
||||
const { unbind } = bindFakeDraw(viewer, {
|
||||
camera: { pose: () => ({ position: { x: 0, y: 0, z: 0 } }) },
|
||||
query: {
|
||||
// Screen x, y are the point's own x, y.
|
||||
projectMany(source, out) {
|
||||
calls.push(source.length / 3);
|
||||
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
|
||||
out[j] = source[i];
|
||||
out[j + 1] = source[i + 1];
|
||||
}
|
||||
},
|
||||
project: () => {
|
||||
throw new Error('the pass projects in one batch');
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const target = {
|
||||
screenRect: { left: 90, right: 110, top: 90, bottom: 110 },
|
||||
cameraDistance: 1,
|
||||
};
|
||||
const state = {
|
||||
now: Date.now,
|
||||
_points: new Map(),
|
||||
_orbitPaths: new Map(),
|
||||
_catalog: new Map(),
|
||||
_viewer: viewer,
|
||||
_trackedNorad: null,
|
||||
_enabled: true,
|
||||
_params: { showPoints: true, showOrbits: false },
|
||||
_activeFocusCount: 0,
|
||||
_lastFocusUpdate: -Infinity,
|
||||
};
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: {
|
||||
focus: {
|
||||
...focusDeemphasis,
|
||||
focusNowMs: (ms) => ms,
|
||||
getFocusTarget: () => target,
|
||||
focusPassIsNeeded: () => true,
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
controls: { _pointStyleFor: () => ({ color: [1, 1, 1, 1] }) },
|
||||
tracking: { _getTrackedFramePosition: () => null },
|
||||
},
|
||||
});
|
||||
rendering._attach(viewer);
|
||||
const style = { ...POINT_STYLES.iss, color: [1, 1, 1, 1] };
|
||||
rendering._addPoint(1, { x: 100, y: 100, z: 0 }, style);
|
||||
rendering._addPoint(2, { x: 100, y: 100, z: 0 }, style);
|
||||
rendering._addPoint(3, { x: 500, y: 500, z: 0 }, style);
|
||||
rendering._addPoint(4, { x: 100, y: 100, z: 0 }, style);
|
||||
state._points.get(2).show = false;
|
||||
state._trackedNorad = 4;
|
||||
for (let now = 0; now <= 5000; now += 100) rendering._updatePointFocus(now);
|
||||
assert.ok(calls.length > 0);
|
||||
assert.ok(
|
||||
calls.every((n) => n === 4),
|
||||
'one call over every dot',
|
||||
);
|
||||
const alpha = (id) => state._points.get(id).color[3];
|
||||
assert.ok(alpha(1) < 1, 'the dot under the focus dims');
|
||||
assert.equal(alpha(2), 1, 'a hidden dot is not dimmed');
|
||||
assert.equal(alpha(3), 1, 'a dot away from the focus is not dimmed');
|
||||
assert.equal(alpha(4), 1, 'the tracked dot is not dimmed');
|
||||
rendering._detach(viewer);
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
gstime,
|
||||
propagate,
|
||||
@@ -13,6 +12,7 @@ import {
|
||||
parseTleText,
|
||||
tleLineLaunchYear,
|
||||
} from '../../sources/tle.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js';
|
||||
|
||||
/** The Earth's rotation rate, rad/s (WGS84). */
|
||||
@@ -67,32 +67,6 @@ export function groundTrackBearingDeg(
|
||||
}
|
||||
|
||||
export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
|
||||
* aligned with live SGP4 positions propagated at another epoch.
|
||||
* @param {number} gmstAtBake GMST used when the path positions were baked.
|
||||
* @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed.
|
||||
* @param {Cesium.Matrix4} [result] Optional matrix to update in place.
|
||||
* @returns {Cesium.Matrix4} Z-rotation from bake-time ECEF to current ECEF.
|
||||
*/
|
||||
|
||||
function orbitFrameModelMatrix(
|
||||
gmstAtBake,
|
||||
nowDate,
|
||||
result = new Cesium.Matrix4(),
|
||||
) {
|
||||
const deltaGmst = gstime(nowDate) - gmstAtBake;
|
||||
const rotation = Cesium.Matrix3.fromRotationZ(
|
||||
-deltaGmst,
|
||||
layerState._scratchRingRotation,
|
||||
);
|
||||
return Cesium.Matrix4.fromRotationTranslation(
|
||||
rotation,
|
||||
Cesium.Cartesian3.ZERO,
|
||||
result,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse TLE text into array of { name, line1, line2 } objects.
|
||||
*/
|
||||
@@ -145,7 +119,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute full orbital path as array of Cartesian3 positions.
|
||||
* Compute full orbital path as ECEF `{x, y, z}` positions, metres.
|
||||
* Steps around one full orbit based on the satellite's mean motion.
|
||||
*/
|
||||
|
||||
@@ -167,7 +141,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
if (!posVel.position || typeof posVel.position === 'boolean') continue;
|
||||
const geo = eciToGeodetic(posVel.position, fixedGmst);
|
||||
positions.push(
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
fromDegrees(
|
||||
degreesLong(geo.longitude),
|
||||
degreesLat(geo.latitude),
|
||||
geo.height * 1000,
|
||||
@@ -339,7 +313,10 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
name: String(name || '').trim(),
|
||||
current,
|
||||
periodSec: orbitalPeriodSeconds(satrec),
|
||||
orbitPath: computeOrbitPath(satrec, referenceDate),
|
||||
// Handed to the renderer's own polylines by the launches layer.
|
||||
orbitPath: parts.rendering._rendererPositions(
|
||||
computeOrbitPath(satrec, referenceDate),
|
||||
),
|
||||
gmstAtBake: gstime(referenceDate),
|
||||
positionAt: (date) => propagatePosition(satrec, date),
|
||||
};
|
||||
@@ -352,7 +329,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
* @param {string} tleText Three-line-element catalog text.
|
||||
* @param {string} query Mission or payload name.
|
||||
* @param {{launchTime?: string|null}} [options] Optional launch epoch for namesake rejection.
|
||||
* @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Cesium.Cartesian3[],positionAt:function(Date):object|null}|null}
|
||||
* @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Array<{x:number,y:number,z:number}>,positionAt:function(Date):object|null}|null}
|
||||
*/
|
||||
|
||||
function findSatelliteOrbitTrackInTle(tleText, query, options = {}) {
|
||||
@@ -386,7 +363,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
* Return the current propagated position and one-orbit path for a catalog satellite.
|
||||
* @param {string|number} query NORAD id or mission/payload name.
|
||||
* @param {{launchTime?: string|null}} [options] Optional launch epoch used to reject namesakes from another launch year.
|
||||
* @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Cesium.Cartesian3[],positionAt:function(Date):object|null}|null}
|
||||
* @returns {{noradId:number,name:string,current:object,periodSec:number,orbitPath:Array<{x:number,y:number,z:number}>,positionAt:function(Date):object|null}|null}
|
||||
*/
|
||||
|
||||
function getSatelliteOrbitTrack(query, options = {}) {
|
||||
@@ -421,7 +398,6 @@ export function createOrbits({ state: layerState, services, parts, source }) {
|
||||
return orbitTrackFromRecord(sat.name, sat.satrec);
|
||||
}
|
||||
return {
|
||||
orbitFrameModelMatrix,
|
||||
parseTLE,
|
||||
propagatePosition,
|
||||
orbitalPeriodSeconds,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassColor } from '../../data/satelliteClass.js';
|
||||
import { cssColor, hexColor } from '../../render/color.js';
|
||||
import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
|
||||
|
||||
/**
|
||||
@@ -11,7 +11,7 @@ import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
|
||||
* (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.
|
||||
* Renders positions as points, orbital paths as polylines.
|
||||
* Click any satellite to track it with camera follow + orbital path.
|
||||
*
|
||||
* ISS gets special treatment: larger point, persistent host label, path shown by default.
|
||||
@@ -196,11 +196,14 @@ export const DENSE_CREATE_CHUNK = 1500;
|
||||
* High orbits (MEO nav / GEO belt) scale this up so the ring stays in frame.
|
||||
*/
|
||||
|
||||
export const TRACK_VIEW_FROM_LEO = new Cesium.Cartesian3(
|
||||
-450000,
|
||||
-450000,
|
||||
350000,
|
||||
);
|
||||
export const TRACK_VIEW_FROM_LEO = Object.freeze({
|
||||
x: -450000,
|
||||
y: -450000,
|
||||
z: 350000,
|
||||
});
|
||||
|
||||
/** The tracked satellite's orbit ring. */
|
||||
export const TRACKED_ORBIT_COLOR = Object.freeze([1, 1, 0, 1]);
|
||||
|
||||
export const HIGH_ORBIT_ALTITUDE_M = 2000000;
|
||||
|
||||
@@ -215,14 +218,16 @@ export const TRACK_VIEW_FROM_HIGH_SCALE = 4;
|
||||
* Colors come from `satelliteClass.js` so the dot, the class label on the
|
||||
* card, and the legend swatch on the layer row can never disagree. Only
|
||||
* pixelSize/outline live here — those encode per-group prominence, not class.
|
||||
* Converted once at module load; per-point color is a plain primitive
|
||||
* attribute, so classification costs nothing per frame.
|
||||
* Colours are the render contract's `[r, g, b, a]` (0..1); the rendering
|
||||
* part turns each style into the renderer's own colours once.
|
||||
*/
|
||||
|
||||
const POINT_OUTLINE = Cesium.Color.WHITE.withAlpha(0.3);
|
||||
const POINT_OUTLINE = Object.freeze([1, 1, 1, 0.3]);
|
||||
|
||||
const _classColor = (group) =>
|
||||
Cesium.Color.fromCssColorString(satelliteClassColor(group));
|
||||
const rgba = (hex, alpha = 1) => Object.freeze(hexColor(hex, alpha));
|
||||
|
||||
const _classColor = (group, alpha = 1) =>
|
||||
rgba(satelliteClassColor(group), alpha);
|
||||
|
||||
export const POINT_STYLES = {
|
||||
// The ISS keeps its own long-standing red hero styling rather than the
|
||||
@@ -231,7 +236,7 @@ export const POINT_STYLES = {
|
||||
// Its card still reads "STATION · ISS", so the class stays legible.
|
||||
iss: {
|
||||
pixelSize: 12,
|
||||
color: Cesium.Color.fromCssColorString('#ff4444'),
|
||||
color: rgba('#ff4444'),
|
||||
outlineColor: POINT_OUTLINE,
|
||||
outlineWidth: 2,
|
||||
},
|
||||
@@ -276,7 +281,7 @@ export const POINT_STYLES = {
|
||||
// Dense-mode extras (Starlink): dim, small, points-only.
|
||||
dense: {
|
||||
pixelSize: 3,
|
||||
color: _classColor('dense').withAlpha(0.9),
|
||||
color: _classColor('dense', 0.9),
|
||||
outlineColor: POINT_OUTLINE,
|
||||
outlineWidth: 0,
|
||||
},
|
||||
@@ -285,7 +290,7 @@ export const POINT_STYLES = {
|
||||
const CLASS_COLORS = Object.fromEntries(
|
||||
SATELLITE_CLASS_IDS.map((id) => [
|
||||
id,
|
||||
Cesium.Color.fromCssColorString(SATELLITE_CLASS_DISPLAY[id].color),
|
||||
Object.freeze(cssColor(SATELLITE_CLASS_DISPLAY[id].color)),
|
||||
]),
|
||||
);
|
||||
const _classStyles = new Map();
|
||||
@@ -306,7 +311,10 @@ export function classPointStyle(group, satelliteClass) {
|
||||
if (!style) {
|
||||
style = Object.freeze({
|
||||
...base,
|
||||
color: group === 'dense' ? color.withAlpha(0.9) : color,
|
||||
color:
|
||||
group === 'dense'
|
||||
? Object.freeze([color[0], color[1], color[2], 0.9])
|
||||
: color,
|
||||
});
|
||||
_classStyles.set(key, style);
|
||||
}
|
||||
|
||||
@@ -24,20 +24,26 @@ const ISS = twoline2satrec(
|
||||
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
|
||||
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
|
||||
|
||||
/** A point primitive that counts position writes. */
|
||||
/** A dot's point item that counts moves (a write of its `pos`). */
|
||||
function point(show = true) {
|
||||
let position = new Cesium.Cartesian3();
|
||||
return {
|
||||
let x = 0;
|
||||
const item = {
|
||||
show,
|
||||
writes: 0,
|
||||
pos: { y: 0, z: 0 },
|
||||
get position() {
|
||||
return position;
|
||||
},
|
||||
set position(value) {
|
||||
this.writes++;
|
||||
position = Cesium.Cartesian3.clone(value);
|
||||
return item.pos;
|
||||
},
|
||||
};
|
||||
Object.defineProperty(item.pos, 'x', {
|
||||
enumerable: true,
|
||||
get: () => x,
|
||||
set(value) {
|
||||
item.writes++;
|
||||
x = value;
|
||||
},
|
||||
});
|
||||
return item;
|
||||
}
|
||||
|
||||
function scene(entries, { tracked = null } = {}) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { satelliteClassText } from '../../data/satelliteClass.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { ISS_NORAD } from './policy.js';
|
||||
|
||||
/**
|
||||
@@ -65,13 +65,13 @@ export function createRecords({ state, parts }) {
|
||||
speedMps: Number.isFinite(pos.speedMps) ? pos.speedMps : null,
|
||||
};
|
||||
}
|
||||
const point = state._points.get(noradId);
|
||||
if (!point?.position) return null;
|
||||
const carto = Cesium.Cartographic.fromCartesian(point.position);
|
||||
const position = parts.rendering._pointPosition(noradId);
|
||||
if (!position) return null;
|
||||
const carto = toLonLatH(position);
|
||||
if (!carto) return null;
|
||||
return {
|
||||
lat: Cesium.Math.toDegrees(carto.latitude),
|
||||
lon: Cesium.Math.toDegrees(carto.longitude),
|
||||
lat: carto.lat,
|
||||
lon: carto.lon,
|
||||
altitudeM: carto.height,
|
||||
speedMps: null,
|
||||
};
|
||||
|
||||
+634
-118
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { gstime } from 'satellite.js';
|
||||
import { reckonEarthFixed, sampleOrbit } from './motion.js';
|
||||
import {
|
||||
@@ -10,8 +11,52 @@ import {
|
||||
RING_ROTATION_MS,
|
||||
} from './policy.js';
|
||||
|
||||
/** Scratch for a point's reckoned position. */
|
||||
const _reckoned = new Cesium.Cartesian3();
|
||||
/**
|
||||
* The satellites layer's drawing, through the renderer contract's draw port:
|
||||
* a points set of the satellite dots, a points set of the tracked
|
||||
* satellite's dot, and a lines set of the orbit rings, with the per-frame
|
||||
* tick that moves them. The other parts hand it render-contract values
|
||||
* (ECEF `{x, y, z}`, colours as `[r, g, b, a]`).
|
||||
*
|
||||
* `layerState._points` keeps each satellite's dot as the point item it is
|
||||
* drawn from (NORAD id → item): its `pos` is moved in place, so a reader
|
||||
* holding it sees where the dot is now, as one holding a point primitive's
|
||||
* position did. Writes are kept and sent to the set once per frame, at the
|
||||
* end of the tick, so a catalog of thousands moves in one upsert.
|
||||
*/
|
||||
|
||||
/** Points shrink with distance as they always have. */
|
||||
const POINT_SCALE_BY_DISTANCE = Object.freeze({
|
||||
near: 1e6,
|
||||
nearValue: 1.5,
|
||||
far: 2e7,
|
||||
farValue: 0.6,
|
||||
});
|
||||
|
||||
/**
|
||||
* The tracked satellite's dot: 14 px yellow with a white outline, drawn
|
||||
* over everything.
|
||||
*/
|
||||
const TRACKED_DOT = Object.freeze({
|
||||
pixelSize: 14,
|
||||
color: Object.freeze([1, 1, 0, 1]),
|
||||
outlineColor: Object.freeze([1, 1, 1, 1]),
|
||||
outlineWidth: 2,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
|
||||
/** An orbit ring's colour when none is given (cyan). */
|
||||
const DEFAULT_RING_COLOR = Object.freeze([0, 1, 1, 1]);
|
||||
|
||||
/** Rings: this alpha in front of the globe, the dimmer one behind it. */
|
||||
const RING_ALPHA = 0.6;
|
||||
const RING_BEHIND_ALPHA = 0.35;
|
||||
|
||||
/** An RGBA colour with another alpha. */
|
||||
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
|
||||
|
||||
/** Layer instances so far: set ids unique to each. */
|
||||
let instances = 0;
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
@@ -26,25 +71,418 @@ export function createRendering({
|
||||
nearFarScalarValueAtDistance,
|
||||
advanceSpriteFocus,
|
||||
focusAlphaNeedsWrite,
|
||||
publishFocusTargetAt,
|
||||
} = services.focus;
|
||||
|
||||
// The tracked satellite's per-frame ECEF sample (WS-D2), shared with the
|
||||
// tracked dot, the follow camera and the tracked card. Tracking writes its
|
||||
// x/y/z in place.
|
||||
layerState._trackedFrameCartesian = { x: 0, y: 0, z: 0 };
|
||||
|
||||
/** The draw sets, while attached: `{points, tracked, rings}`. */
|
||||
let sets = null;
|
||||
/** Dots changed since the last write to the set, by NORAD id. */
|
||||
const dirty = new Set();
|
||||
/** Dots removed since the last write to the set, by NORAD id. */
|
||||
const gone = new Set();
|
||||
/** Whether every dot was removed since the last write. */
|
||||
let cleared = false;
|
||||
/** Whether the satellite dots are shown. */
|
||||
let pointsShown = true;
|
||||
/**
|
||||
* Show orbital path for a satellite.
|
||||
*
|
||||
* RING FLICKER FIX: this is a one-instance Cesium.Primitive built
|
||||
* synchronously ONCE (asynchronous: false), then re-aligned to current GMST
|
||||
* each tick via its modelMatrix. The previous Entity-polyline approach
|
||||
* rebuilt geometry ASYNCHRONOUSLY on every positions assignment, which made
|
||||
* both the selected ring and the ISS ring blink once per second while the
|
||||
* rebuild was in flight. A rigid Z-rotation needs no rebuild at all.
|
||||
*
|
||||
* Why not a CallbackProperty entity (dynamic mode)? Verified in Cesium
|
||||
* 1.138 source: the dynamic polyline updater renders through a shared
|
||||
* PolylineCollection and applies only the fill material —
|
||||
* `depthFailMaterial` is silently dropped, losing the dimmed behind-Earth
|
||||
* segment. The Primitive keeps it via depthFailAppearance + the per-instance
|
||||
* depthFailColor attribute (same mechanism the entity STATIC batch uses):
|
||||
* bright where above the horizon, dimmed where behind the globe.
|
||||
* The tracked dot: its item and how its position is read (the tracker's
|
||||
* callback, read as the follow camera reads it).
|
||||
*/
|
||||
let trackedDot = null;
|
||||
let trackedDrawnThisTick = false;
|
||||
/** The frame the tick last ran in: the tracked sample's cache key. */
|
||||
let renderedFrame = -1;
|
||||
|
||||
/**
|
||||
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
|
||||
* aligned with live SGP4 positions propagated at another epoch: a column-
|
||||
* major 4×4 rotation about Z.
|
||||
* @param {number} gmstAtBake GMST used when the path positions were baked.
|
||||
* @param {Date} nowDate Epoch whose rotating-Earth frame should be displayed.
|
||||
* @param {ArrayLike<number>} [result] A 16-element matrix to update in place.
|
||||
* @returns {ArrayLike<number>} Z-rotation from bake-time ECEF to current ECEF.
|
||||
*/
|
||||
|
||||
function orbitFrameModelMatrix(gmstAtBake, nowDate, result = new Array(16)) {
|
||||
const angle = -(gstime(nowDate) - gmstAtBake);
|
||||
const c = Math.cos(angle);
|
||||
const s = Math.sin(angle);
|
||||
result[0] = c;
|
||||
result[1] = s;
|
||||
result[2] = 0;
|
||||
result[3] = 0;
|
||||
result[4] = -s;
|
||||
result[5] = c;
|
||||
result[6] = 0;
|
||||
result[7] = 0;
|
||||
result[8] = 0;
|
||||
result[9] = 0;
|
||||
result[10] = 1;
|
||||
result[11] = 0;
|
||||
result[12] = 0;
|
||||
result[13] = 0;
|
||||
result[14] = 0;
|
||||
result[15] = 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** ECEF `{x, y, z}` positions as the renderer's own: plain copies. */
|
||||
function _rendererPositions(positions) {
|
||||
return positions.map((p) => ({ x: p.x, y: p.y, z: p.z }));
|
||||
}
|
||||
|
||||
/** The frame the tick last ran in, the tracked sample's cache key. */
|
||||
function _drawnFrameNumber() {
|
||||
return renderedFrame;
|
||||
}
|
||||
|
||||
/** Make the sets the dots, the tracked dot and the rings draw in. */
|
||||
function _attach(viewer) {
|
||||
_attachTo(drawOf(viewer));
|
||||
}
|
||||
|
||||
/** Make the layer's sets on `draw`, a draw port. */
|
||||
function _attachTo(draw) {
|
||||
if (sets) _detach();
|
||||
const prefix = `satellites:${++instances}`;
|
||||
pointsShown = true;
|
||||
sets = {
|
||||
points: draw.points({ id: `${prefix}:points`, show: pointsShown }),
|
||||
tracked: draw.points({ id: `${prefix}:tracked` }),
|
||||
// Ring clicks fall through to the satellites and the deselect.
|
||||
rings: draw.lines({ id: `${prefix}:rings`, pickable: false }),
|
||||
};
|
||||
layerState._sets = sets;
|
||||
dirty.clear();
|
||||
gone.clear();
|
||||
cleared = false;
|
||||
// Dots kept while detached draw once attached.
|
||||
for (const noradId of layerState._points.keys()) dirty.add(noradId);
|
||||
}
|
||||
|
||||
/** Dispose of the sets; the dots and rings go with them. */
|
||||
function _detach(viewer) {
|
||||
if (!sets) return;
|
||||
sets.points.dispose();
|
||||
sets.tracked.dispose();
|
||||
sets.rings.dispose();
|
||||
sets = null;
|
||||
layerState._sets = null;
|
||||
trackedDot = null;
|
||||
dirty.clear();
|
||||
gone.clear();
|
||||
cleared = false;
|
||||
}
|
||||
|
||||
/** Whether there is a set to draw satellites in. */
|
||||
function _hasPointCollection() {
|
||||
return Boolean(sets);
|
||||
}
|
||||
|
||||
/** Whether the satellite dots are shown. */
|
||||
function _pointsShown() {
|
||||
return Boolean(sets) && pointsShown;
|
||||
}
|
||||
|
||||
function _setPointsShown(show) {
|
||||
if (!sets) return;
|
||||
pointsShown = show;
|
||||
sets.points.show = show;
|
||||
}
|
||||
|
||||
/** Show or hide every ring. */
|
||||
function _setOrbitPathsShown(show) {
|
||||
const changed = [];
|
||||
for (const path of layerState._orbitPaths.values()) {
|
||||
path.item.show = show;
|
||||
changed.push(path.item);
|
||||
}
|
||||
if (sets && changed.length) sets.rings.upsert(changed);
|
||||
}
|
||||
|
||||
function _setOrbitPathShown(noradId, show) {
|
||||
const path = layerState._orbitPaths.get(noradId);
|
||||
if (!path) return;
|
||||
path.item.show = show;
|
||||
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.depthFail = {
|
||||
kind: 'solid',
|
||||
color: 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(
|
||||
(path) => path.item.id,
|
||||
);
|
||||
layerState._orbitPaths.clear();
|
||||
if (sets && ids.length) sets.rings.remove(ids);
|
||||
}
|
||||
|
||||
/** Note a dot's change, sent at the end of the frame's tick. */
|
||||
function _markDirty(noradId) {
|
||||
gone.delete(noradId);
|
||||
dirty.add(noradId);
|
||||
}
|
||||
|
||||
/** Send the dots changed since the last frame to the points set. */
|
||||
function _flushPoints() {
|
||||
if (!sets) return;
|
||||
if (cleared) {
|
||||
cleared = false;
|
||||
gone.clear();
|
||||
dirty.clear();
|
||||
sets.points.set([...layerState._points.values()]);
|
||||
return;
|
||||
}
|
||||
if (gone.size) {
|
||||
sets.points.remove([...gone].map(String));
|
||||
gone.clear();
|
||||
}
|
||||
if (dirty.size) {
|
||||
const items = [];
|
||||
for (const noradId of dirty) {
|
||||
const item = layerState._points.get(noradId);
|
||||
if (item) items.push(item);
|
||||
}
|
||||
dirty.clear();
|
||||
if (items.length) sets.points.upsert(items);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw one satellite's dot.
|
||||
* @param {number} noradId
|
||||
* @param {{x: number, y: number, z: number}} position ECEF metres.
|
||||
* @param {object} style A `POINT_STYLES` entry.
|
||||
*/
|
||||
function _addPoint(noradId, position, style, show = true) {
|
||||
layerState._points.set(noradId, {
|
||||
id: String(noradId),
|
||||
pos: { x: position.x, y: position.y, z: position.z },
|
||||
pixelSize: style.pixelSize,
|
||||
color: style.color,
|
||||
outlineColor: style.outlineColor,
|
||||
outlineWidth: style.outlineWidth,
|
||||
scaleByDistance: POINT_SCALE_BY_DISTANCE,
|
||||
disableDepthTest: 0,
|
||||
show,
|
||||
meta: { noradId },
|
||||
});
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/** Move a drawn dot to ECEF `position`; false when it has none. */
|
||||
function _movePoint(noradId, position) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point) return false;
|
||||
point.pos.x = position.x;
|
||||
point.pos.y = position.y;
|
||||
point.pos.z = position.z;
|
||||
_markDirty(noradId);
|
||||
return true;
|
||||
}
|
||||
|
||||
function _removePoint(noradId) {
|
||||
if (!layerState._points.delete(noradId)) return;
|
||||
dirty.delete(noradId);
|
||||
if (!cleared) gone.add(noradId);
|
||||
}
|
||||
|
||||
/** Remove every dot. */
|
||||
function _clearPoints() {
|
||||
layerState._points.clear();
|
||||
dirty.clear();
|
||||
gone.clear();
|
||||
cleared = true;
|
||||
}
|
||||
|
||||
/** Where a dot is drawn (ECEF), or null. */
|
||||
function _pointPosition(noradId) {
|
||||
return layerState._points.get(noradId)?.pos || null;
|
||||
}
|
||||
|
||||
/** Hide a dot while the tracked dot draws it. */
|
||||
function _hidePoint(noradId) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point) return;
|
||||
point.show = false;
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a dot only at eye distances in `range` (`[near, far)` metres), or
|
||||
* at every distance (`undefined`): the ISS's 3D model takes the near range.
|
||||
*/
|
||||
function _setPointRange(noradId, range) {
|
||||
const point = layerState._points.get(noradId);
|
||||
if (!point || point.displayRange === range) return;
|
||||
if (range) point.displayRange = range;
|
||||
else delete point.displayRange;
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/** The tracked dot's distance range, as `_setPointRange` (sent each frame). */
|
||||
function _setTrackedDotRange(range) {
|
||||
if (!trackedDot || trackedDot.item.displayRange === range) return;
|
||||
if (range) trackedDot.item.displayRange = range;
|
||||
else delete trackedDot.item.displayRange;
|
||||
}
|
||||
|
||||
/** 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.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;
|
||||
point.outlineWidth = style.outlineWidth;
|
||||
point.disableDepthTest = 0;
|
||||
_markDirty(noradId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the tracked satellite's dot and make the carrier the follow target
|
||||
* and the tracked card read (its entity record holds the card).
|
||||
* @param {{position: () => object, viewFrom: {x: number, y: number,
|
||||
* z: number}}} options `position` is read as the follow camera reads
|
||||
* it, once each frame before the tick moves the sample on.
|
||||
* @returns {object} The carrier.
|
||||
*/
|
||||
function _addTrackedEntity({ position }) {
|
||||
const noradId = layerState._trackedNorad;
|
||||
const carrier = { noradId };
|
||||
trackedDot = {
|
||||
position,
|
||||
item: {
|
||||
id: String(noradId),
|
||||
pos: { x: 0, y: 0, z: 0 },
|
||||
...TRACKED_DOT,
|
||||
meta: { noradId },
|
||||
},
|
||||
drawn: false,
|
||||
};
|
||||
// Drawn from the next frame's tick on, as the camera first frames it.
|
||||
return carrier;
|
||||
}
|
||||
|
||||
function _removeTrackedEntity() {
|
||||
if (trackedDot?.drawn) sets?.tracked.clear();
|
||||
trackedDot = null;
|
||||
}
|
||||
|
||||
/** Put the tracked dot where the tracker says it is now. */
|
||||
function _drawTrackedDot() {
|
||||
if (!trackedDot || !sets) return;
|
||||
const at = trackedDot.position();
|
||||
if (!at) return;
|
||||
const pos = trackedDot.item.pos;
|
||||
pos.x = at.x;
|
||||
pos.y = at.y;
|
||||
pos.z = at.z;
|
||||
sets.tracked.upsert([trackedDot.item]);
|
||||
trackedDot.drawn = true;
|
||||
}
|
||||
|
||||
/** Whether a click's draw hit is the tracked satellite's dot. */
|
||||
function _hitIsTracked(hit) {
|
||||
return Boolean(sets) && hit?.set === sets.tracked.id;
|
||||
}
|
||||
|
||||
/** The NORAD id of the satellite dot a click's draw hit is on, or null. */
|
||||
function _hitPointId(hit) {
|
||||
if (!sets || hit?.set !== sets.points.id) return null;
|
||||
const noradId = Number(hit.id);
|
||||
return Number.isFinite(noradId) ? noradId : null;
|
||||
}
|
||||
|
||||
/** Publish the tracked satellite's focus rectangle from its cached position. */
|
||||
function _publishTrackedFocus(target) {
|
||||
publishFocusTargetAt({ ...target, viewer: layerState._viewer });
|
||||
}
|
||||
|
||||
/** A ring's positions rotated from its bake-time frame to `gmst`'s. */
|
||||
function _ringPositions(path, gmst) {
|
||||
const angle = -(gmst - path.gmstAtBake);
|
||||
const c = Math.cos(angle);
|
||||
const s = Math.sin(angle);
|
||||
const base = path.base;
|
||||
const out = new Float64Array(base.length * 3);
|
||||
for (let i = 0; i < base.length; i++) {
|
||||
const p = base[i];
|
||||
out[i * 3] = c * p.x - s * p.y;
|
||||
out[i * 3 + 1] = s * p.x + c * p.y;
|
||||
out[i * 3 + 2] = p.z;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show orbital path for a satellite: the ring over one orbit, baked once
|
||||
* in ECEF at the current GMST, bright in front of the globe and dimmed
|
||||
* behind it (`depthFail`), and turned with the Earth each
|
||||
* `RING_ROTATION_MS` (`_updateOrbitPathRotations`).
|
||||
*/
|
||||
|
||||
function _showOrbitPath(noradId, color) {
|
||||
@@ -54,87 +492,68 @@ export function createRendering({
|
||||
if (!sat || !layerState._viewer) return;
|
||||
|
||||
const bakeDate = new Date(layerState.now());
|
||||
const basePositions = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
|
||||
if (basePositions.length < 2) return;
|
||||
const base = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
|
||||
if (base.length < 2) return;
|
||||
|
||||
const pathColor = color || Cesium.Color.CYAN;
|
||||
// Kept so the Cockpit's orbit dim (cockpitSubject.js) restores exactly.
|
||||
const baseColor = pathColor.withAlpha(0.6);
|
||||
const baseDepthFailColor = pathColor.withAlpha(0.35);
|
||||
const instanceId = `satellite-orbit:${noradId}`;
|
||||
|
||||
const primitive = new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
id: instanceId,
|
||||
geometry: new Cesium.PolylineGeometry({
|
||||
positions: basePositions,
|
||||
width: noradId === ISS_NORAD ? 2.5 : 2.0,
|
||||
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
|
||||
}),
|
||||
attributes: {
|
||||
color: Cesium.ColorGeometryInstanceAttribute.fromColor(baseColor),
|
||||
depthFailColor:
|
||||
Cesium.ColorGeometryInstanceAttribute.fromColor(baseDepthFailColor),
|
||||
},
|
||||
}),
|
||||
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
|
||||
depthFailAppearance: new Cesium.PolylineColorAppearance({
|
||||
translucent: true,
|
||||
}),
|
||||
asynchronous: false, // build this frame — no async-rebuild blink window
|
||||
allowPicking: false, // ring clicks fall through to satellites/deselect
|
||||
});
|
||||
layerState._viewer.scene.primitives.add(primitive);
|
||||
|
||||
layerState._orbitPaths.set(noradId, {
|
||||
primitive,
|
||||
const pathColor = color || DEFAULT_RING_COLOR;
|
||||
const path = {
|
||||
color: pathColor,
|
||||
bakeMs: bakeDate.getTime(),
|
||||
base,
|
||||
// Same Date object as computeOrbitPath's internal fixedGmst → identical
|
||||
// GMST value (gstime is pure), so delta starts at exactly 0 and the
|
||||
// initial identity modelMatrix is correct until the first ring tick.
|
||||
// GMST value (gstime is pure), so the ring starts unturned.
|
||||
gmstAtBake: gstime(bakeDate),
|
||||
instanceId,
|
||||
baseColor,
|
||||
baseDepthFailColor,
|
||||
// The alpha multiple last written to the instance (1: as built).
|
||||
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),
|
||||
positions: _ringPositions(path, path.gmstAtBake),
|
||||
widthPx: noradId === ISS_NORAD ? 2.5 : 2.0,
|
||||
// Along the ellipsoid between samples, as the ring always ran.
|
||||
mode: 'geodesic',
|
||||
style: { kind: 'solid', color: withAlpha(pathColor, RING_ALPHA) },
|
||||
depthFail: {
|
||||
kind: 'solid',
|
||||
color: withAlpha(pathColor, RING_BEHIND_ALPHA),
|
||||
},
|
||||
show: true,
|
||||
};
|
||||
layerState._orbitPaths.set(noradId, path);
|
||||
sets?.rings.upsert([path.item]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate every baked orbit ring from its bake-time ECEF snapshot to current
|
||||
* Turn every baked orbit ring from its bake-time ECEF snapshot to current
|
||||
* GMST (WS-D1). The baked ring is an inertial-frame snapshot frozen at
|
||||
* gmstAtBake; the live dot lives in true rotating-frame ECEF, so without this
|
||||
* the dot slides west off the ring at Earth-rotation rate (~0.25°/min).
|
||||
*
|
||||
* Sign derivation: a point fixed in inertial space keeps its right ascension
|
||||
* α, so its ECEF longitude λ = α − gmst DECREASES by ΔGMST as time advances
|
||||
* (it drifts WEST). Cesium.Matrix3.fromRotationZ(θ) rotates +X toward +Y,
|
||||
* i.e. INCREASES longitude by θ — so we rotate the baked points by −ΔGMST.
|
||||
* Mental check: ISS baked over Austin at t0; 10 min later Austin has rotated
|
||||
* east under the (inertial) ring, so the ring must sit further WEST in ECEF.
|
||||
* (it drifts WEST). A rotation about Z by θ INCREASES longitude by θ — so
|
||||
* the baked points are rotated by −ΔGMST. Mental check: ISS baked over
|
||||
* Austin at t0; 10 min later Austin has rotated east under the (inertial)
|
||||
* ring, so the ring must sit further WEST in ECEF.
|
||||
*
|
||||
* Wraparound: gstime returns radians in [0, 2π), so the raw difference can be
|
||||
* off from the continuous ΔGMST — but only by exact multiples of 2π, which a
|
||||
* rotation cannot distinguish. Tiny negative deltas right after bake are
|
||||
* likewise harmless. No unwrapping needed.
|
||||
*
|
||||
* No SGP4 here — the rotation is applied as the ring primitive's modelMatrix
|
||||
* (exact compensation; WGS84 is rotationally symmetric about Z, so rotating
|
||||
* the baked curve rigidly equals rebaking from rotated points). modelMatrix
|
||||
* updates are synchronous uniforms — no geometry rebuild, no flicker. Post-
|
||||
* creation modelMatrix changes are supported for one-instance primitives in
|
||||
* 3D mode, which these rings are. In-place mutation is safe: Primitive.update
|
||||
* diffs modelMatrix against an internal clone.
|
||||
* No SGP4 here: WGS84 is rotationally symmetric about Z, so rotating the
|
||||
* baked curve rigidly equals rebaking from rotated points. A ring with a
|
||||
* `depthFail` style is built at once where it now runs, so it never blinks.
|
||||
* @param {Date} nowDate Epoch used for current GMST.
|
||||
*/
|
||||
|
||||
function _updateOrbitPathRotations(nowDate) {
|
||||
if (layerState._orbitPaths.size === 0) return;
|
||||
|
||||
const gmst = gstime(nowDate);
|
||||
const changed = [];
|
||||
for (const [noradId, path] of [...layerState._orbitPaths]) {
|
||||
if (!path.primitive) continue;
|
||||
// The rotation keeps the ring under the dot for minutes; the plane
|
||||
// itself precesses, so a world time moved far from the bake re-bakes.
|
||||
if (Math.abs(nowDate.getTime() - path.bakeMs) > ORBIT_REBAKE_MS) {
|
||||
@@ -142,12 +561,10 @@ export function createRendering({
|
||||
_showOrbitPath(noradId, path.color);
|
||||
continue;
|
||||
}
|
||||
parts.orbits.orbitFrameModelMatrix(
|
||||
path.gmstAtBake,
|
||||
nowDate,
|
||||
path.primitive.modelMatrix,
|
||||
);
|
||||
path.item.positions = _ringPositions(path, gmst);
|
||||
changed.push(path.item);
|
||||
}
|
||||
sets?.rings.upsert(changed);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,11 +573,9 @@ export function createRendering({
|
||||
|
||||
function _hideOrbitPath(noradId) {
|
||||
const path = layerState._orbitPaths.get(noradId);
|
||||
if (path) {
|
||||
if (layerState._viewer)
|
||||
layerState._viewer.scene.primitives.remove(path.primitive); // remove() destroys
|
||||
layerState._orbitPaths.delete(noradId);
|
||||
}
|
||||
if (!path) return;
|
||||
layerState._orbitPaths.delete(noradId);
|
||||
sets?.rings.remove([path.item.id]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,12 +612,13 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* Move every shown point to where its satellite is at the world time,
|
||||
* reckoned from its last sample, so points glide every frame between
|
||||
* samples instead of stepping once a second. A core sample more than
|
||||
* Move every shown dot to where its satellite is at the world time,
|
||||
* reckoned from its last sample, so dots glide every frame between
|
||||
* samples instead of stepping once a second; the moved dots go to the
|
||||
* points set with the frame's other dot changes. A core sample more than
|
||||
* ORBIT_SAMPLE_HORIZON_MS from the world time (time playing fast, or a
|
||||
* seek) is taken again first; dense extras are resampled by their own
|
||||
* round-robin. A hidden point is moved when it is shown again, and the
|
||||
* round-robin. A hidden dot is moved when it is shown again, and the
|
||||
* tracked satellite is placed by its per-frame path.
|
||||
* @param {number} nowMs World time, epoch ms.
|
||||
*/
|
||||
@@ -221,22 +637,51 @@ export function createRendering({
|
||||
sample = _sample(sat, nowMs) ? sat.orbitSample : null;
|
||||
if (!sample || Math.abs(nowMs - sample[0]) > ORBIT_RECKON_LIMIT_MS)
|
||||
continue;
|
||||
point.position = reckonEarthFixed(sample, nowMs, gmst, _reckoned); // setter clones
|
||||
reckonEarthFixed(sample, nowMs, gmst, point.pos);
|
||||
_markDirty(noradId);
|
||||
sat.reckonedAtMs = nowMs;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared scene.preRender tick (single definition for init + enable):
|
||||
* Shared preRender tick (single definition for init + enable):
|
||||
* - the tracked dot where the follow camera put it this frame,
|
||||
* - core fleet SGP4 samples at 200ms-tracked / 1s-idle cadence,
|
||||
* - dense extras sampled on a per-frame round-robin budget,
|
||||
* - every point reckoned from its sample each frame (motion.js),
|
||||
* - tracked satellite's point primitive per frame (WS-D2),
|
||||
* - orbit ring GMST re-alignment every ~1s (WS-D1).
|
||||
* - every dot reckoned from its sample each frame (motion.js),
|
||||
* - tracked satellite's dot sample per frame (WS-D2),
|
||||
* - orbit ring GMST re-alignment every ~1s (WS-D1),
|
||||
* - the frame's dot changes sent to the points set.
|
||||
* @param {{frame: number}} [t] The frame port's tick.
|
||||
*/
|
||||
|
||||
function _preRenderTick() {
|
||||
if (!layerState._enabled) return;
|
||||
function _preRenderTick(t) {
|
||||
if (layerState._enabled) _tick();
|
||||
// The frame's sample is taken from here on (the tracked dot above was
|
||||
// drawn from the last one, as the camera framed it).
|
||||
renderedFrame = Number.isFinite(t?.frame) ? t.frame : renderedFrame + 1;
|
||||
if (layerState._enabled) _tickAfterFrame();
|
||||
_flushPoints();
|
||||
}
|
||||
|
||||
/** The tick's part read before the frame's own sample is taken. */
|
||||
function _tick() {
|
||||
// The tracked dot draws at the sample the follow camera framed this frame.
|
||||
// With no camera reading it this frame, it is drawn after the frame's own
|
||||
// sample instead, so the tracked satellite is propagated once a frame.
|
||||
trackedDrawnThisTick = false;
|
||||
if (
|
||||
layerState._trackedNorad !== null &&
|
||||
layerState._trackedFrameGeo !== null &&
|
||||
layerState._trackedFrameNumber === renderedFrame
|
||||
) {
|
||||
_drawTrackedDot();
|
||||
trackedDrawnThisTick = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The tick's part that takes the frame's own sample. */
|
||||
function _tickAfterFrame() {
|
||||
const now = focusNowMs(Date.now());
|
||||
|
||||
// The ISS as a 3D model up close. First, before the tracked sample below
|
||||
@@ -264,14 +709,14 @@ export function createRendering({
|
||||
_reckonPoints(worldMs);
|
||||
}
|
||||
|
||||
// Keep the tracked dot on the per-frame epoch shared with label + camera —
|
||||
// runs after _propagateAll so the per-frame sample wins over the 200ms one.
|
||||
// Keep the tracked satellite's (hidden) dot on the per-frame epoch shared
|
||||
// with label + camera — runs after _propagateAll so the per-frame sample
|
||||
// wins over the 200ms one.
|
||||
if (layerState._trackedNorad !== null) {
|
||||
const pos = parts.tracking._getTrackedFramePosition();
|
||||
const point = layerState._points.get(layerState._trackedNorad);
|
||||
if (pos && point) {
|
||||
point.position = layerState._trackedFrameCartesian; // primitive setter clones
|
||||
}
|
||||
if (pos && layerState._points.has(layerState._trackedNorad))
|
||||
_movePoint(layerState._trackedNorad, layerState._trackedFrameCartesian);
|
||||
if (!trackedDrawnThisTick) _drawTrackedDot();
|
||||
}
|
||||
|
||||
// While the Cockpit rides the tracked satellite, keep its marks hidden.
|
||||
@@ -284,8 +729,8 @@ export function createRendering({
|
||||
|
||||
_updatePointFocus(now);
|
||||
|
||||
// Hidden standalone orbit primitives do not need GMST matrix writes while
|
||||
// Space Missions draws the selected mission orbit itself.
|
||||
// Hidden standalone orbit rings do not need turning while Space Missions
|
||||
// draws the selected mission orbit itself.
|
||||
if (
|
||||
layerState._params.showOrbits &&
|
||||
now - layerState._lastRingRotation >= RING_ROTATION_MS
|
||||
@@ -297,6 +742,12 @@ export function createRendering({
|
||||
|
||||
/** Focus alpha for satellite points, inside the existing shared preRender tick. */
|
||||
|
||||
// The focus pass projects every dot in one call, into buffers kept between
|
||||
// passes, so a pass over thousands of dots allocates nothing per dot.
|
||||
let focusSource = new Float64Array(0);
|
||||
let focusScreen = new Float32Array(0);
|
||||
const focusOrder = [];
|
||||
const focusScreenXY = { x: 0, y: 0 };
|
||||
function _updatePointFocus(nowMs) {
|
||||
const target = getFocusTarget();
|
||||
if (
|
||||
@@ -306,22 +757,51 @@ export function createRendering({
|
||||
return;
|
||||
if (nowMs - layerState._lastFocusUpdate < 80) return;
|
||||
layerState._lastFocusUpdate = nowMs;
|
||||
const scene = layerState._viewer.scene;
|
||||
const camera = layerState._viewer.camera;
|
||||
const query = findQuery(layerState._viewer);
|
||||
const eye = findCamera(layerState._viewer)?.pose()?.position;
|
||||
if (!query || !eye) return;
|
||||
const count = layerState._points.size;
|
||||
if (focusSource.length < count * 3) {
|
||||
focusSource = new Float64Array(count * 3);
|
||||
focusScreen = new Float32Array(count * 2);
|
||||
}
|
||||
focusOrder.length = 0;
|
||||
for (const point of layerState._points.values()) {
|
||||
const pos = point?.pos;
|
||||
const i = focusOrder.length * 3;
|
||||
focusSource[i] = pos ? pos.x : NaN;
|
||||
focusSource[i + 1] = pos ? pos.y : NaN;
|
||||
focusSource[i + 2] = pos ? pos.z : NaN;
|
||||
focusOrder.push(pos);
|
||||
}
|
||||
query.projectMany(
|
||||
focusSource.subarray(0, focusOrder.length * 3),
|
||||
focusScreen,
|
||||
);
|
||||
// The pass asks in the points' own order, skipping some: a cursor finds
|
||||
// each asked position in one sweep.
|
||||
let cursor = 0;
|
||||
const result = applySatellitePointFocusDeemphasis({
|
||||
points: layerState._points,
|
||||
trackedId: layerState._trackedNorad,
|
||||
target,
|
||||
previousActiveCount: layerState._activeFocusCount,
|
||||
nowMs,
|
||||
screenPositionFor: (position) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
layerState._scratchFocusScreen,
|
||||
),
|
||||
cameraDistanceFor: (position) =>
|
||||
Cesium.Cartesian3.distance(camera.positionWC, position),
|
||||
screenPositionFor: (position) => {
|
||||
while (cursor < focusOrder.length && focusOrder[cursor] !== position)
|
||||
cursor++;
|
||||
if (cursor >= focusOrder.length) {
|
||||
cursor = 0;
|
||||
return query.project(position);
|
||||
}
|
||||
const x = focusScreen[cursor * 2];
|
||||
const y = focusScreen[cursor * 2 + 1];
|
||||
if (Number.isNaN(x) || Number.isNaN(y)) return null;
|
||||
focusScreenXY.x = x;
|
||||
focusScreenXY.y = y;
|
||||
return focusScreenXY;
|
||||
},
|
||||
cameraDistanceFor: (position) => distance(eye, position),
|
||||
baseColorFor: (noradId) =>
|
||||
parts.controls._pointStyleFor(
|
||||
noradId,
|
||||
@@ -334,6 +814,8 @@ export function createRendering({
|
||||
/**
|
||||
* Apply the gated satellite-point focus pass through the production color path.
|
||||
* @param {object} input
|
||||
* @param {Map<number, object>} input.points Point items by NORAD id; a
|
||||
* written colour is sent to the set with the frame's other changes.
|
||||
* @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}}
|
||||
*/
|
||||
|
||||
@@ -355,8 +837,8 @@ export function createRendering({
|
||||
let transitioning = false;
|
||||
let activeCount = 0;
|
||||
for (const [noradId, point] of points || []) {
|
||||
if (noradId === trackedId || !point?.position) continue;
|
||||
const cameraDistance = cameraDistanceFor(point.position);
|
||||
if (noradId === trackedId || !point?.pos) continue;
|
||||
const cameraDistance = cameraDistanceFor(point.pos);
|
||||
const distanceScale = nearFarScalarValueAtDistance(
|
||||
point.scaleByDistance,
|
||||
cameraDistance,
|
||||
@@ -366,7 +848,7 @@ export function createRendering({
|
||||
// Hidden points still release toward identity, preventing stale dim
|
||||
// alpha if a catalog/presentation toggle later makes them visible.
|
||||
screenPosition:
|
||||
point.show === false ? null : screenPositionFor(point.position),
|
||||
point.show === false ? null : screenPositionFor(point.pos),
|
||||
cameraDistance,
|
||||
nowMs,
|
||||
target,
|
||||
@@ -377,17 +859,50 @@ export function createRendering({
|
||||
transitioning ||= focus.transitioning;
|
||||
if (focus.active) activeCount += 1;
|
||||
const base = baseColorFor(noradId);
|
||||
const alpha = base.alpha * focus.factor;
|
||||
if (focusAlphaNeedsWrite(point.color?.alpha, alpha, params)) {
|
||||
const alpha = base[3] * focus.factor;
|
||||
if (focusAlphaNeedsWrite(point.color?.[3], alpha, params)) {
|
||||
// Point stays continuously present at the non-zero emphasis floor; its
|
||||
// own alpha yields around the tracked target, independent of draw order.
|
||||
point.color = base.withAlpha(alpha);
|
||||
point.color = withAlpha(base, alpha);
|
||||
if (points === layerState._points) _markDirty(noradId);
|
||||
writes += 1;
|
||||
}
|
||||
}
|
||||
return { writes, transitioning, activeCount, ran: true };
|
||||
}
|
||||
return {
|
||||
orbitFrameModelMatrix,
|
||||
_rendererPositions,
|
||||
_drawnFrameNumber,
|
||||
_attach,
|
||||
_attachTo,
|
||||
_detach,
|
||||
_hasPointCollection,
|
||||
_pointsShown,
|
||||
_setPointsShown,
|
||||
_setOrbitPathsShown,
|
||||
_setOrbitPathShown,
|
||||
_orbitPathShown,
|
||||
_setOrbitPathAlpha,
|
||||
_setPointShown,
|
||||
_setPointStyle,
|
||||
_pointShown,
|
||||
_setTrackedDotShown,
|
||||
_clearOrbitPaths,
|
||||
_addPoint,
|
||||
_movePoint,
|
||||
_removePoint,
|
||||
_clearPoints,
|
||||
_pointPosition,
|
||||
_hidePoint,
|
||||
_setPointRange,
|
||||
_setTrackedDotRange,
|
||||
_restorePoint,
|
||||
_addTrackedEntity,
|
||||
_removeTrackedEntity,
|
||||
_publishTrackedFocus,
|
||||
_hitIsTracked,
|
||||
_hitPointId,
|
||||
_showOrbitPath,
|
||||
_updateOrbitPathRotations,
|
||||
_hideOrbitPath,
|
||||
@@ -396,5 +911,6 @@ export function createRendering({
|
||||
_preRenderTick,
|
||||
_updatePointFocus,
|
||||
applySatellitePointFocusDeemphasis,
|
||||
_flushPoints,
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// The click dispatcher's input port over a viewer double: the Cesium adapter's.
|
||||
import '../../render/cesium/input.js';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { EventEmitter, once } from 'node:events';
|
||||
@@ -10,6 +12,9 @@ import { createOrbits } from './orbits.js';
|
||||
import { createLabels } from './labels.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { createCatalog } from './catalog.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createInteraction } from './interaction.js';
|
||||
@@ -72,7 +77,7 @@ async function fixture(t) {
|
||||
fetchImpl: (path, options) =>
|
||||
fetch(`http://127.0.0.1:${server.address().port}${path}`, options),
|
||||
});
|
||||
// Application host services and native EventTargets; actual Cesium collections,
|
||||
// Application host services and native EventTargets; a fake draw port,
|
||||
// input handler, events, SGP4, ingestion and lifecycle run without a WebGL scene.
|
||||
const noop = () => {};
|
||||
const services = {
|
||||
@@ -84,7 +89,7 @@ async function fixture(t) {
|
||||
layerState: { isExplicitLayerStateOrigin: () => false },
|
||||
focus: {
|
||||
clearFocusTarget: noop,
|
||||
publishFocusTargetFromCachedPosition: noop,
|
||||
publishFocusTargetAt: noop,
|
||||
getFocusTarget: () => null,
|
||||
},
|
||||
context: {
|
||||
@@ -123,9 +128,14 @@ async function fixture(t) {
|
||||
},
|
||||
trackedEntityChanged: new Cesium.Event(),
|
||||
};
|
||||
const unbind = bindRenderer(viewer, {
|
||||
frame: fakeSceneFrame(viewer),
|
||||
draw: fakeDrawPort(),
|
||||
});
|
||||
await parts.lifecycle.methods.init(viewer);
|
||||
t.after(async () => {
|
||||
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer);
|
||||
unbind();
|
||||
if (state._sets) parts.lifecycle.methods.destroy(viewer);
|
||||
viewer.scene.primitives.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { DEFAULT_SATELLITE_CLASSES } from './classes.js';
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
|
||||
@@ -21,18 +20,18 @@ export function createState({ services }) {
|
||||
|
||||
state._catalog = new Map();
|
||||
|
||||
state._pointCollection = null;
|
||||
/** The draw sets (`{points, tracked, rings}`), owned by the rendering part. */
|
||||
state._sets = null;
|
||||
|
||||
state._points = new Map();
|
||||
// noradId → point primitive
|
||||
// noradId → the point item its dot is drawn from (the rendering part's)
|
||||
/** Stable lightweight records reused by the detection overlay between updates. */
|
||||
|
||||
state._detectionObjects = new Map();
|
||||
|
||||
// noradId → { primitive, gmstAtBake }
|
||||
// primitive is a one-instance Cesium.Primitive holding the ring baked in ECEF
|
||||
// at gmstAtBake; the preRender tick re-aligns it to current GMST by updating
|
||||
// its modelMatrix (rigid Z-rotation — no geometry rebuild, WS-D1).
|
||||
// noradId → { base, gmstAtBake, item }, owned by the rendering part: base
|
||||
// is the ring baked in ECEF at gmstAtBake; the preRender tick turns it to
|
||||
// current GMST (rigid Z-rotation, WS-D1) into the line item drawn.
|
||||
|
||||
state._orbitPaths = new Map();
|
||||
|
||||
@@ -76,8 +75,6 @@ export function createState({ services }) {
|
||||
|
||||
state._activeFocusCount = 0;
|
||||
|
||||
state._scratchFocusScreen = new Cesium.Cartesian2();
|
||||
|
||||
state._enabled = false;
|
||||
|
||||
// Click-to-track state
|
||||
@@ -97,10 +94,12 @@ export function createState({ services }) {
|
||||
};
|
||||
|
||||
state._trackedEntity = null;
|
||||
/** The FollowTarget the camera follows the tracked satellite with. */
|
||||
state._followTarget = null;
|
||||
|
||||
state._clickHandler = null;
|
||||
state._clickSubscription = null;
|
||||
|
||||
/** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */
|
||||
/** @type {(() => void)|null} follow-changed listener disposer (cross-layer untrack) */
|
||||
|
||||
state._trackedEntityChangedRemove = null;
|
||||
|
||||
@@ -168,14 +167,15 @@ export function createState({ services }) {
|
||||
|
||||
// Per-frame cache for the tracked satellite (WS-D2): dot, host readout, camera, and
|
||||
// getTrackedInfo all read one SGP4 sample per rendered frame, keyed on
|
||||
// scene.frameState.frameNumber, so they never diverge in epoch.
|
||||
// the rendered-frame number, so they never diverge in epoch.
|
||||
|
||||
state._trackedFrameNumber = -1;
|
||||
|
||||
state._trackedFrameGeo = null;
|
||||
// { longitude, latitude, altitude } or null
|
||||
|
||||
state._trackedFrameCartesian = new Cesium.Cartesian3();
|
||||
// The matching ECEF sample; the rendering part creates it.
|
||||
state._trackedFrameCartesian = null;
|
||||
|
||||
/** Optional deterministic clock used only by the production-frame test seam. */
|
||||
|
||||
@@ -200,12 +200,6 @@ export function createState({ services }) {
|
||||
|
||||
state.coverageChanged = () => worldClock.coverageChanged();
|
||||
|
||||
// Scratch variables
|
||||
|
||||
state._scratchCartesian = new Cesium.Cartesian3();
|
||||
|
||||
state._scratchRingRotation = new Cesium.Matrix3();
|
||||
|
||||
/** Update the explicit model only when the rounded altitude line changes. */
|
||||
/** Epoch of the last shared-context refresh for the tracked satellite. */
|
||||
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { rendererOf } from '../../render/rendererOf.js';
|
||||
import { ISS_NORAD, ISS_OVERLAY_SOURCE_ID } from './policy.js';
|
||||
|
||||
/** A draw port that draws nothing, for seams that need sets but no renderer. */
|
||||
const NO_DRAW = (() => {
|
||||
const set = (spec) => ({
|
||||
id: spec.id,
|
||||
show: spec.show !== false,
|
||||
set() {},
|
||||
upsert() {},
|
||||
remove() {},
|
||||
clear() {},
|
||||
setOptions() {},
|
||||
size: () => 0,
|
||||
on: () => () => {},
|
||||
dispose() {},
|
||||
});
|
||||
return { points: set, lines: set, icons: set, shapes: set };
|
||||
})();
|
||||
|
||||
export function createTesting({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
* Seed a single tracked satellite so tests can invoke the exact production
|
||||
@@ -9,8 +26,8 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
* @param {number} state.noradId
|
||||
* @param {string} state.name
|
||||
* @param {object} state.satrec
|
||||
* @param {object} state.entity
|
||||
* @param {object} state.point
|
||||
* @param {object} state.entity The tracked carrier.
|
||||
* @param {object} state.point The satellite's point item (`pos` ECEF).
|
||||
* @param {object} state.viewer
|
||||
* @param {() => (number|Date)} state.now
|
||||
*/
|
||||
@@ -87,7 +104,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
return layerState._trackedFrameCartesian;
|
||||
}
|
||||
|
||||
/** Invoke the same callback registered on `scene.preRender` in production. */
|
||||
/** Invoke the same per-frame tick the frame port runs in production. */
|
||||
|
||||
function _runSatellitePreRenderForTest() {
|
||||
parts.rendering._preRenderTick();
|
||||
@@ -104,9 +121,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
catalog = 'core',
|
||||
showPoints = true,
|
||||
} = {}) {
|
||||
layerState._viewer = {
|
||||
scene: { primitives: { add: (p) => p, remove() {} } },
|
||||
};
|
||||
layerState._viewer = {};
|
||||
// Neutralize the shared world-overlay host: these tests exercise catalog and
|
||||
// row-control logic, not the ISS callout.
|
||||
layerState._overlayHost = {
|
||||
@@ -114,12 +129,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
};
|
||||
layerState._pointCollection = {
|
||||
show: true,
|
||||
add: (opts) => ({ ...opts }),
|
||||
remove() {},
|
||||
removeAll() {},
|
||||
};
|
||||
parts.rendering._attachTo(NO_DRAW);
|
||||
layerState._catalog = new Map();
|
||||
layerState._points = new Map();
|
||||
layerState._detectionObjects = new Map();
|
||||
@@ -143,7 +153,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
layerState._overlayHost = layerState.DEFAULT_OVERLAY_HOST;
|
||||
layerState._orbitPaths = new Map();
|
||||
layerState._viewer = null;
|
||||
layerState._pointCollection = null;
|
||||
parts.rendering._detach();
|
||||
layerState._catalog = new Map();
|
||||
layerState._points = new Map();
|
||||
layerState._denseIds = [];
|
||||
@@ -183,13 +193,23 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
[
|
||||
ISS_NORAD,
|
||||
{
|
||||
primitive: { show: true, modelMatrix: new Cesium.Matrix4() },
|
||||
// A stand-in ring: shown, baked with no points.
|
||||
base: [],
|
||||
gmstAtBake: 0,
|
||||
item: {
|
||||
id: String(ISS_NORAD),
|
||||
positions: new Float64Array(0),
|
||||
show: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
]);
|
||||
layerState._trackedNorad = null;
|
||||
layerState._trackedEntity = null;
|
||||
// Drawn through the viewer's renderer when it has one bound.
|
||||
parts.rendering._detach();
|
||||
const draw = rendererOf(viewer)?.draw;
|
||||
if (draw) parts.rendering._attachTo(draw);
|
||||
if (!preservePending) parts.tracking._cancelPendingTrackingRestore();
|
||||
layerState._trackedFrameNumber = -1;
|
||||
layerState._trackedFrameGeo = null;
|
||||
@@ -234,6 +254,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
|
||||
function _clearSatelliteLabelLifecycleForTest() {
|
||||
parts.tracking._clearTracking();
|
||||
parts.rendering._detach();
|
||||
layerState._enabled = false;
|
||||
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
|
||||
layerState._overlayHost.setVisible(ISS_OVERLAY_SOURCE_ID, false);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
import { entityFollowTarget, stopFollowing } from '../../data/followed.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';
|
||||
import { formatQuantity, unitLabel } from '../../ui/unitLabels.js';
|
||||
import {
|
||||
@@ -8,11 +11,12 @@ import {
|
||||
HIGH_ORBIT_ALTITUDE_M,
|
||||
TRACK_VIEW_FROM_HIGH_SCALE,
|
||||
TRACK_VIEW_FROM_LEO,
|
||||
TRACKED_ORBIT_COLOR,
|
||||
} from './policy.js';
|
||||
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
export function createTracking({ state: layerState, services, parts, source }) {
|
||||
const { clearFocusTarget, publishFocusTargetFromCachedPosition } =
|
||||
services.focus;
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const {
|
||||
clearTrackedSubjectContext,
|
||||
getContextStore,
|
||||
@@ -86,36 +90,31 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
const clearedNorad = layerState._trackedNorad;
|
||||
clearFocusTarget('satellites', layerState._trackedNorad);
|
||||
|
||||
const lastPos = layerState._points.get(layerState._trackedNorad);
|
||||
|
||||
// Re-show the primitive (hidden while the tracked entity rendered the dot)
|
||||
// and restore the original group palette from the shared style table (WS-D3)
|
||||
if (lastPos) {
|
||||
const style = parts.controls._pointStyleFor(
|
||||
// Re-show the dot (hidden while the tracked dot drew it) and
|
||||
// restore the original group palette from the shared style table (WS-D3)
|
||||
parts.rendering._restorePoint(
|
||||
layerState._trackedNorad,
|
||||
parts.controls._pointStyleFor(
|
||||
layerState._trackedNorad,
|
||||
layerState._catalog.get(layerState._trackedNorad)?.group,
|
||||
);
|
||||
),
|
||||
// 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;
|
||||
lastPos.outlineWidth = style.outlineWidth;
|
||||
lastPos.disableDepthTestDistance = 0;
|
||||
}
|
||||
parts.controls._classVisible(layerState._trackedNorad),
|
||||
);
|
||||
|
||||
// Invalidate the per-frame tracked-position cache (WS-D2)
|
||||
layerState._trackedFrameNumber = -1;
|
||||
layerState._trackedFrameGeo = null;
|
||||
|
||||
// Remove tracked entity and orbit path (unless ISS — keep its path)
|
||||
// Remove the tracked dot and orbit path (unless ISS — keep its path)
|
||||
if (layerState._trackedNorad !== ISS_NORAD) {
|
||||
parts.rendering._hideOrbitPath(layerState._trackedNorad);
|
||||
}
|
||||
if (layerState._viewer && !skipViewerUntrack)
|
||||
layerState._viewer.trackedEntity = undefined;
|
||||
stopFollowing(layerState._viewer);
|
||||
layerState._followTarget = null;
|
||||
if (layerState._trackedEntity) {
|
||||
layerState._viewer.entities.remove(layerState._trackedEntity);
|
||||
parts.rendering._removeTrackedEntity(layerState._trackedEntity);
|
||||
layerState._trackedEntity = null;
|
||||
}
|
||||
layerState._trackedNorad = null;
|
||||
@@ -135,8 +134,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Get the tracked satellite's geodetic position, propagated at most once per
|
||||
* rendered frame (WS-D2). All tracked-satellite consumers (entity position
|
||||
* callback → camera, host model, point primitive, getTrackedInfo) share this
|
||||
* rendered frame (WS-D2). All tracked-satellite consumers (the tracked dot
|
||||
* and follow camera, host model, the hidden dot, getTrackedInfo) share this
|
||||
* single `new Date()` epoch per frame, so they can never diverge by the old
|
||||
* 200ms throttle. The matching ECEF position is left in
|
||||
* `_trackedFrameCartesian`. SGP4 for one satellite per frame is cheap.
|
||||
@@ -148,8 +147,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
const sat = layerState._catalog.get(layerState._trackedNorad);
|
||||
if (!sat) return null;
|
||||
|
||||
const frameNumber =
|
||||
layerState._viewer?.scene?.frameState?.frameNumber ?? -1;
|
||||
const frameNumber = parts.rendering._drawnFrameNumber();
|
||||
if (
|
||||
frameNumber === -1 ||
|
||||
frameNumber !== layerState._trackedFrameNumber ||
|
||||
@@ -163,11 +161,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
// The time the sample is at: the world clock's, not the wall clock's.
|
||||
pos.atMs = atMs;
|
||||
layerState._trackedFrameGeo = pos;
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
fromDegreesInto(
|
||||
pos.longitude,
|
||||
pos.latitude,
|
||||
pos.altitude,
|
||||
undefined,
|
||||
layerState._trackedFrameCartesian,
|
||||
);
|
||||
layerState._trackedFrameNumber = frameNumber;
|
||||
@@ -191,11 +188,9 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
const trackedPointDiameterPx = 14 + 4; // point plus its 2 px outline on both sides
|
||||
// Exact SGP4 frame cache only: dot, host readout, camera, and focus rectangle all
|
||||
// share one epoch, avoiding a second propagation phase and its old jitter.
|
||||
publishFocusTargetFromCachedPosition({
|
||||
parts.rendering._publishTrackedFocus({
|
||||
ownerLayer: 'satellites',
|
||||
id: layerState._trackedNorad,
|
||||
scene: layerState._viewer?.scene,
|
||||
camera: layerState._viewer?.camera,
|
||||
displayPosition: layerState._trackedFrameCartesian,
|
||||
widthPx: Math.max(trackedPointDiameterPx, Math.min(260, labelWidthPx)),
|
||||
// Union of the 14 px point and the two-line label shifted 18 px upward.
|
||||
@@ -398,7 +393,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
: null;
|
||||
// The overlay's gap is twice the anchor radius, so half the clearance.
|
||||
const anchorRadiusPx = clearPx ? Math.round(clearPx / 8) * 4 : null;
|
||||
const current = layerState._trackedEntity.gevLabelModel;
|
||||
const current = readEntityRecord(layerState._trackedEntity)?.labelModel;
|
||||
// Compare the WHOLE detail array: comparing only `details[0]` swallowed any
|
||||
// change confined to the companions line, so the card would never republish.
|
||||
const unchanged =
|
||||
@@ -407,7 +402,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
current?.details?.length === details.length &&
|
||||
details.every((line, index) => current.details[index] === line);
|
||||
if (unchanged) return;
|
||||
layerState._trackedEntity.gevLabelModel = {
|
||||
entityRecord(layerState._trackedEntity).labelModel = {
|
||||
title,
|
||||
details,
|
||||
accent: '#ffd84d',
|
||||
@@ -419,32 +414,30 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
function _trackSatellite(noradId, { origin = 'programmatic' } = {}) {
|
||||
_clearTracking(false, { origin });
|
||||
|
||||
const point = layerState._points.get(noradId);
|
||||
const sat = layerState._catalog.get(noradId);
|
||||
if (!point || !sat) return;
|
||||
if (!layerState._points.has(noradId) || !sat) return;
|
||||
|
||||
layerState._trackedNorad = noradId;
|
||||
layerState._trackedFrameNumber = -1;
|
||||
layerState._trackedFrameGeo = null;
|
||||
parts.labels._syncIssOverlay();
|
||||
|
||||
// Hide the primitive — the tracked ENTITY renders the dot below. The
|
||||
// entity must own a point graphic so the Viewer's tracking camera can
|
||||
// resolve a bounding sphere and engage viewFrom (a label-only entity
|
||||
// left the camera stranded; this mirrors the proven flights pattern).
|
||||
point.show = false;
|
||||
// Hide the dot — the tracked dot draws it, larger and over everything.
|
||||
parts.rendering._hidePoint(noradId);
|
||||
|
||||
// Show orbital path
|
||||
parts.rendering._showOrbitPath(noradId, Cesium.Color.YELLOW);
|
||||
parts.rendering._showOrbitPath(noradId, TRACKED_ORBIT_COLOR);
|
||||
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
|
||||
|
||||
// Tracked entity position propagates per evaluation through the per-frame
|
||||
// The tracked position propagates per evaluation through the per-frame
|
||||
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
|
||||
// Falls back to the point primitive's reckoned position if SGP4 fails.
|
||||
const positionProperty = new Cesium.CallbackProperty(() => {
|
||||
// Falls back to the dot's reckoned position if SGP4 fails.
|
||||
const trackedPosition = () => {
|
||||
const pos = _getTrackedFramePosition();
|
||||
return pos ? layerState._trackedFrameCartesian : point.position;
|
||||
}, false);
|
||||
return pos
|
||||
? layerState._trackedFrameCartesian
|
||||
: parts.rendering._pointPosition(noradId);
|
||||
};
|
||||
|
||||
const name = sat.name.trim();
|
||||
|
||||
@@ -459,43 +452,42 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
initialPos && initialPos.altitude > HIGH_ORBIT_ALTITUDE_M
|
||||
? TRACK_VIEW_FROM_HIGH_SCALE
|
||||
: 1;
|
||||
const viewFrom = Cesium.Cartesian3.multiplyByScalar(
|
||||
TRACK_VIEW_FROM_LEO,
|
||||
viewScale,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const viewFrom = scale(TRACK_VIEW_FROM_LEO, viewScale);
|
||||
|
||||
layerState._trackedEntity = layerState._viewer.entities.add({
|
||||
position: positionProperty,
|
||||
layerState._trackedEntity = parts.rendering._addTrackedEntity({
|
||||
position: trackedPosition,
|
||||
viewFrom,
|
||||
point: {
|
||||
pixelSize: 14,
|
||||
color: Cesium.Color.YELLOW,
|
||||
outlineColor: Cesium.Color.WHITE,
|
||||
outlineWidth: 2,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
});
|
||||
layerState._trackedEntity.gevSelectionOrigin = origin;
|
||||
layerState._trackedEntity.gevTrackedId = `satellites:${noradId}`;
|
||||
layerState._trackedEntity.gevDisplayPosition = _trackedDisplayCached;
|
||||
entityRecord(layerState._trackedEntity).selectionOrigin = origin;
|
||||
entityRecord(layerState._trackedEntity).trackedId = `satellites:${noradId}`;
|
||||
entityRecord(layerState._trackedEntity).displayPosition =
|
||||
_trackedDisplayCached;
|
||||
// Up close the ISS is a 3D model: the card welds to where it is drawn.
|
||||
if (noradId === ISS_NORAD)
|
||||
layerState._trackedEntity.gevVisualPosition = () =>
|
||||
entityRecord(layerState._trackedEntity).visualPosition = () =>
|
||||
parts.issModel?._issVisualPosition?.() ?? null;
|
||||
_updateTrackedSatelliteLabelModel(initialPos?.altitude ?? null);
|
||||
|
||||
const dotPosition = parts.rendering._pointPosition(noradId);
|
||||
_emitAwarenessEvent('gev:awareness-subject-selected', {
|
||||
layerId: 'satellites',
|
||||
id: noradId,
|
||||
label: name,
|
||||
position: Cesium.Cartesian3.clone(point.position),
|
||||
position: dotPosition ? clone(dotPosition) : undefined,
|
||||
origin,
|
||||
});
|
||||
selectTrackedSubjectContext(_contextSubjectMetadata(noradId, initialPos));
|
||||
layerState._contextRefreshedAtMs = Date.now();
|
||||
|
||||
layerState._viewer.trackedEntity = layerState._trackedEntity;
|
||||
// The renderer's own frame for a fast mover (autodetect), as the tracked
|
||||
// entity had; no close-range rules at orbital distances. The carrier is
|
||||
// what the tracked card reads (its entity record).
|
||||
layerState._followTarget = entityFollowTarget(layerState._trackedEntity, {
|
||||
position: trackedPosition,
|
||||
frame: 'autodetect',
|
||||
viewFrom,
|
||||
});
|
||||
cameraOf(layerState._viewer).follow(layerState._followTarget);
|
||||
console.log(`[Data:Satellites] Tracking ${name} (NORAD ${noradId})`);
|
||||
}
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user