Draw rocket launches through the renderer ports, off Cesium

The launches layer's sites, markers, reticles, mission lines, live orbit
rings and pad zone are now renderer draw sets. Picks go through the query
port, double-click follow through the camera port (shared with other layers
in src/data/stockFollow.js), and per-frame work through the frame port.
rendering.js, orbitRendering.js and launchPad.js leave the Cesium list.

The Cesium draw port gains what these need: pattern line styles, lines in
the inertial frame turned each frame by the set's motion clock, radial-rim
fills on clamped ellipses with a depth bias, and parking for hidden lines
that cannot settle into a static batch, so a hidden line no longer costs a
draw each frame. A roster writes each set once, and a followed live payload
shares one position sample with its marker each frame.
This commit is contained in:
Sameh Khamis committed 2026-11-08 11:26:21 -08:00
1 parent fa762f808e
commit 4a9b1389ba
22 files changed
+1476 -717

No files matched your search

+31 -14
View File
@@ -231,32 +231,49 @@ test('mission hover preserves the cursor of a pointer-owning tool', () => {
assert.equal(viewer.scene.canvas.style.cursor, 'crosshair');
});
test('mission picks are read by the rendering part, which owns the entities', async () => {
test('mission picks are read by the rendering part, which owns the draw sets', async () => {
const { createRendering } = await import('./rendering.js');
const mission = { id: 'rocket-launch:abc' };
const { bindFakeDraw } = await import('../../testSupport/fakeDrawPort.mjs');
const drilled = [];
const state = {
_viewer: {
scene: {
drillPick(position, limit) {
drilled.push([position, limit]);
return [{ id: { id: 'cable:1' } }, { id: mission }];
},
const viewer = {};
let hits = [];
const { unbind } = bindFakeDraw(viewer, {
query: {
drillPick(x, y, options) {
drilled.push([x, y, options]);
return hits;
},
},
};
});
const state = { _viewer: viewer };
const rendering = createRendering({
state,
services: { satellites: {} },
parts: {},
});
rendering.attach(viewer);
const { sites, lines } = rendering.setIds;
hits = [
{ set: 'cables:1', id: 'rocket-launch:zzz', surface: false },
{ set: sites, id: 'rocket-launch:abc', surface: false },
];
assert.equal(rendering.launchMarkerAt({ x: 3, y: 4 }), true);
assert.deepEqual(drilled, [[{ x: 3, y: 4 }, 12]]);
assert.deepEqual(drilled, [[3, 4, { limit: 12 }]]);
assert.equal(rendering.launchIdFromPicks(hits), 'abc');
assert.equal(
rendering.launchIdFromPicks([{ id: 'x' }, { id: mission }]),
'abc',
rendering.launchIdFromPicks([
{ set: lines, id: 'rocket-trajectory:def:0', surface: false },
]),
'def',
);
assert.equal(rendering.launchIdFromPicks([{ id: 'x' }]), null);
assert.equal(
rendering.launchIdFromPicks([{ set: sites, id: 'x', surface: false }]),
null,
);
hits = [hits[0]];
assert.equal(rendering.launchMarkerAt({ x: 3, y: 4 }), false);
state._viewer = null;
assert.equal(rendering.launchMarkerAt({ x: 3, y: 4 }), false);
rendering.detach();
unbind();
});
+3 -2
View File
@@ -182,7 +182,7 @@ export function createIngestion({
if (
!layerState._enabled ||
token !== layerState._lifecycleToken ||
!layerState._dataSource
!layerState._missionSets
)
return;
const activeTleText = layerState._activeTleText;
@@ -195,8 +195,9 @@ export function createIngestion({
layerState._replayTracks.clear();
layerState._orbitMatches = 0;
launches.forEach((launch) =>
parts.rendering.addLaunchEntity(launch, activeTleText),
parts.rendering.addLaunchEntity(launch, activeTleText, { defer: true }),
);
parts.rendering.flushLaunchEntities();
layerState._renderedTleText = activeTleText;
if (layerState._renderedTleText === layerState._activeTleText)
clearPostTleRetry();
+28 -23
View File
@@ -71,7 +71,7 @@ async function fixture({ legacySource = false } = {}) {
const state = createState({ services });
state._enabled = true;
state._lifecycleToken = 1;
state._dataSource = new Cesium.CustomDataSource('owned-qualification');
state._missionSets = { show: false, items: [] };
const canvas = Object.assign(new EventTarget(), {
disableRootEvents: true,
onwheel: null,
@@ -82,9 +82,10 @@ async function fixture({ legacySource = false } = {}) {
scene: { canvas, preRender: new Cesium.Event(), drillPick: () => [] },
};
bindRenderer(viewer, { frame: fakeSceneFrame(viewer) });
await viewer.dataSources.add(state._dataSource);
// Only presentation boundaries are inert. Source, normalization, state,
// ingestion, lifecycle, stats and feed-state policy execute unchanged.
// Mission draw sets attached and not let go: the fixture starts with one.
let attached = 1;
const parts = {
panel: {
createMissionPanel: noop,
@@ -115,32 +116,31 @@ async function fixture({ legacySource = false } = {}) {
destroyLaunchPadZonePrimitive: noop,
},
rendering: {
// As the rendering part owns the entities' data source.
attach(target) {
state._dataSource = new Cesium.CustomDataSource('rocket-launches');
state._dataSource.show = false;
target.dataSources.add(state._dataSource);
// As the rendering part owns the mission draw sets.
attach() {
state._missionSets = { show: false, items: [] };
attached += 1;
},
detach(target) {
if (state._dataSource)
target.dataSources.remove(state._dataSource, true);
state._dataSource = null;
detach() {
if (state._missionSets) attached -= 1;
state._missionSets = null;
},
updateMissionFrame: noop,
missionsShown: () => Boolean(state._dataSource?.show),
missionsShown: () => Boolean(state._missionSets?.show),
showMissions(shown) {
if (state._dataSource) state._dataSource.show = shown;
if (state._missionSets) state._missionSets.show = shown;
},
clearLaunchEntities: () => {
if (state._missionSets) state._missionSets.items = [];
},
clearLaunchEntities: () => state._dataSource?.entities.removeAll(),
launchIdFromPicks: () => null,
missionHitsAt: () => [],
followTargetFor: () => null,
launchMarkerAt: () => false,
addLaunchEntity(record) {
state._dataSource.entities.add({
id: record.id,
name: record.name,
position: Cesium.Cartesian3.fromDegrees(record.lon, record.lat),
});
state._missionSets.items.push(record.id);
},
flushLaunchEntities() {},
},
};
const context = { state, services, parts, source };
@@ -153,7 +153,7 @@ async function fixture({ legacySource = false } = {}) {
return {
stats,
feed: layerFeedState(stats),
rendered: state._dataSource?.entities.values.map((x) => x.id) || [],
rendered: state._missionSets?.items.slice() || [],
enabled: state._enabled,
};
};
@@ -163,6 +163,7 @@ async function fixture({ legacySource = false } = {}) {
source,
current,
viewer,
attachedSets: () => attached,
init: () => parts.lifecycle.methods.init(viewer),
update: () => parts.ingestion.methods.update(),
disable: () => parts.lifecycle.methods.disable(),
@@ -317,15 +318,19 @@ test('destroy followed by actual init starts a clean instance with owned handler
assert.equal(value.stats.lastUpdate, null);
assert.equal(value.stats.error, null);
assert.equal(value.enabled, false);
assert.equal(f.viewer.dataSources.length, 1);
assert.equal(f.attachedSets(), 1);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 1);
const input = inputFor(f.viewer);
const before = input.subscriberCount();
assert.equal(typeof f.state._inputSubscription, 'function');
await f.destroy();
assert.equal(f.state._inputSubscription, null);
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
assert.equal(f.viewer.dataSources.length, 0);
assert.equal(
input.subscriberCount(),
before - 3,
'click, hover and double-click follow',
);
assert.equal(f.attachedSets(), 0);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
} finally {
await f.close();
+92 -119
View File
@@ -1,146 +1,118 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { hexColor } from '../../render/color.js';
import { LAUNCH_PAD_ZONE_RADIUS_M } from './policy.js';
/** The zone's colour: a faint fill under a brighter rim. */
const ZONE_COLOR = '#22e6e6';
const ZONE_FILL_ALPHA = 0.105;
const ZONE_RIM_ALPHA = 0.72;
/** The rim's width, a fraction of the zone's radius. */
const ZONE_RIM_WIDTH = 0.033;
/**
* Pulled toward the eye, metres, so the zone is not buried by the pad's
* mesh at oblique angles, without a height that would float it.
*/
const ZONE_DEPTH_BIAS_M = 1;
export function createLaunchPad({
state: layerState,
services,
parts,
source,
}) {
function zoneSet() {
return layerState._missionSets?.pad ?? null;
}
function hideLaunchPadZone() {
if (layerState._launchPadZonePrimitive)
layerState._launchPadZonePrimitive.show = false;
const item = layerState._launchPadZoneItem;
if (!item || item.show === false) return;
layerState._launchPadZoneItem = { ...item, show: false };
zoneSet()?.upsert([layerState._launchPadZoneItem]);
}
function removeLaunchPadZonePrimitive() {
if (
layerState._launchPadZonePrimitive &&
layerState._viewer?.scene?.primitives
) {
layerState._viewer.scene.primitives.remove(
layerState._launchPadZonePrimitive,
);
}
layerState._launchPadZonePrimitive = null;
if (layerState._launchPadZoneItem) zoneSet()?.clear();
layerState._launchPadZoneItem = null;
layerState._launchPadZoneLaunchId = null;
}
/** The zone drawn around a launch's pad, draped on the ground. */
function createLaunchPadZonePrimitive(launch) {
removeLaunchPadZonePrimitive();
const material = new Cesium.Material({
fabric: {
type: 'GevLaunchPadZone',
uniforms: {
color: Cesium.Color.fromCssColorString('#22e6e6'),
fillAlpha: 0.105,
rimAlpha: 0.72,
},
source: `
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 centered = (materialInput.st - vec2(0.5)) * 2.0;
float radius = length(centered);
float inside = 1.0 - smoothstep(0.985, 1.0, radius);
float rim = smoothstep(0.952, 0.985, radius) * inside;
material.diffuse = color.rgb;
material.emission = color.rgb * rim * 0.35;
material.alpha = color.a * inside * mix(fillAlpha, rimAlpha, rim);
return material;
}`,
const item = {
id: `rocket-pad-zone:${launch.id}`,
geometry: {
kind: 'ellipse',
center: { lon: launch.lon, lat: launch.lat },
semiMajor: LAUNCH_PAD_ZONE_RADIUS_M,
semiMinor: LAUNCH_PAD_ZONE_RADIUS_M,
},
});
const geometry = new Cesium.EllipseGeometry({
center: Cesium.Cartesian3.fromDegrees(launch.lon, launch.lat),
semiMajorAxis: LAUNCH_PAD_ZONE_RADIUS_M,
semiMinorAxis: LAUNCH_PAD_ZONE_RADIUS_M,
granularity: Cesium.Math.toRadians(0.08),
vertexFormat:
Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat,
});
layerState._launchPadZonePrimitive =
layerState._viewer.scene.primitives.add(
new Cesium.GroundPrimitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
id: `rocket-pad-zone:${launch.id}`,
}),
appearance: new Cesium.MaterialAppearance({
material,
translucent: true,
closed: false,
faceForward: true,
flat: true,
// Keep the zone classified onto the photoreal surface, but bias only its
// rasterized depth toward the camera. This avoids coplanar fragments
// being intermittently buried by the launch-pad mesh at oblique angles
// without adding a world-space height that would make the ring float.
renderState: {
depthTest: {
enabled: true,
},
depthMask: false,
polygonOffset: {
enabled: true,
factor: -1,
units: -4,
},
blending: Cesium.BlendingState.ALPHA_BLEND,
},
}),
classificationType: Cesium.ClassificationType.BOTH,
asynchronous: true,
show: true,
}),
);
fill: {
preset: 'radialRim',
color: hexColor(ZONE_COLOR, ZONE_FILL_ALPHA),
rimColor: hexColor(ZONE_COLOR, ZONE_RIM_ALPHA),
rimWidth: ZONE_RIM_WIDTH,
},
height: 'clampGround',
clampTo: 'both',
depthBias: ZONE_DEPTH_BIAS_M,
show: true,
};
layerState._launchPadZoneItem = item;
zoneSet()?.set([item]);
layerState._launchPadZoneLaunchId = launch.id;
}
/** Before each frame: the rings' labels, and the selected pad's zone. */
function updateLaunchPadZone() {
if (!layerState._enabled || !parts.rendering.missionsShown()) {
hideLaunchPadZone();
return;
}
const nowMs = Date.now();
if (nowMs - layerState._lastMissionRingRotationMs >= 1000) {
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(nowMs);
layerState._lastMissionRingRotationMs = nowMs;
}
const launch = layerState._launches.find(
(item) => item.id === layerState._selectedLaunchId,
);
const pose = findCamera(layerState._viewer)?.pose();
if (!launch || !pose) {
hideLaunchPadZone();
return;
}
const launchPosition = fromDegrees(launch.lon, launch.lat);
const visible = parts.policyHelpers.launchPadZoneVisible({
layerActive: parts.rendering.missionsShown(),
selectedLaunchId: layerState._selectedLaunchId,
launchId: launch.id,
cameraHeightM: pose.height,
cameraDistanceM: distance(pose.position, launchPosition),
});
if (!visible) {
hideLaunchPadZone();
return;
}
if (layerState._launchPadZoneLaunchId !== launch.id)
createLaunchPadZonePrimitive(launch);
else if (layerState._launchPadZoneItem.show === false) {
layerState._launchPadZoneItem = {
...layerState._launchPadZoneItem,
show: true,
};
zoneSet()?.upsert([layerState._launchPadZoneItem]);
}
}
function initLaunchPadZonePrimitive() {
if (!layerState._viewer || layerState._launchPadZoneRemover) return;
layerState._launchPadZoneRemover =
layerState._viewer.scene.preRender.addEventListener(() => {
if (!layerState._enabled || !layerState._dataSource?.show) {
hideLaunchPadZone();
return;
}
const nowMs = Date.now();
if (nowMs - layerState._lastMissionRingRotationMs >= 1000) {
layerState._missionRingDate.setTime(nowMs);
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(
layerState._missionRingDate,
);
layerState._lastMissionRingRotationMs = nowMs;
}
const launch = layerState._launches.find(
(item) => item.id === layerState._selectedLaunchId,
);
const camera = layerState._viewer?.camera;
if (!launch || !camera) {
hideLaunchPadZone();
return;
}
const launchPosition = Cesium.Cartesian3.fromDegrees(
launch.lon,
launch.lat,
);
const visible = parts.policyHelpers.launchPadZoneVisible({
layerActive: Boolean(layerState._dataSource?.show),
selectedLaunchId: layerState._selectedLaunchId,
launchId: launch.id,
cameraHeightM: camera.positionCartographic?.height,
cameraDistanceM: Cesium.Cartesian3.distance(
camera.positionWC,
launchPosition,
),
});
if (!visible) {
hideLaunchPadZone();
return;
}
if (layerState._launchPadZoneLaunchId !== launch.id)
createLaunchPadZonePrimitive(launch);
layerState._launchPadZonePrimitive.show = true;
});
findFrame(layerState._viewer)?.on('preRender', updateLaunchPadZone) ??
null;
}
function destroyLaunchPadZonePrimitive() {
@@ -154,5 +126,6 @@ export function createLaunchPad({
createLaunchPadZonePrimitive,
initLaunchPadZonePrimitive,
destroyLaunchPadZonePrimitive,
updateLaunchPadZone,
};
}
+19 -3
View File
@@ -1,6 +1,7 @@
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -140,7 +141,10 @@ export function createLifecycle({
const input = inputFor(viewer);
const unsubscribeClick = input.onClick((event) => {
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
const launchId = parts.rendering.launchIdFromPicks(event.drill(12));
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
);
if (!launchId) return;
parts.selection.setSelectedMission(launchId);
parts.selection.focusMission(
@@ -153,11 +157,22 @@ export function createLifecycle({
launchAt: parts.rendering.launchMarkerAt,
});
const unsubscribeHover = input.onPointer('move', hover.move);
// A double-click follows a mission point, as the default renderer
// followed the missions' entities.
layerState._stockFollow = followOnDoubleClick({
viewer,
inputFor: () => input,
name: 'rocket-launches',
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
targetFor: parts.rendering.followTargetFor,
});
layerState._inputSubscription = () => {
unsubscribeClick();
unsubscribeHover();
layerState._stockFollow?.destroy();
layerState._stockFollow = null;
};
// Apply horizon visibility before Cesium traverses and picks the scene.
// Apply horizon visibility before the renderer draws and picks.
// A postRender write is one frame late and can remain visibly stale when
// request-on-demand rendering stops after a globe camera move.
layerState._declutterHandler =
@@ -215,6 +230,7 @@ export function createLifecycle({
parts.replay.stopMissionReplay();
parts.selection.stopMissionZoomAnchor();
parts.rendering.showMissions(false);
layerState._stockFollow?.stop();
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
const canvas = canvasOf(layerState._viewer);
if (canvas) canvas.style.cursor = '';
@@ -254,7 +270,7 @@ export function createLifecycle({
layerState._replayTracks.clear();
parts.panel.clearMissionPanel();
layerState._viewer = null;
parts.rendering.detach(viewer);
parts.rendering.detach();
layerState._count = 0;
layerState._orbitMatches = 0;
layerState._lastUpdate = null;
+150 -132
View File
@@ -1,183 +1,201 @@
import * as Cesium from 'cesium';
import { temeToPseudoFixed } from '../../geo/celestial.js';
import {
MISSION_ORBIT_PATTERN_GROUPS,
MISSION_ORBIT_DASHES_PER_GROUP,
} from './policy.js';
/** Pattern cells' width in the mission orbit image, pixels. */
const CELL_PX = 8;
/** The pattern image's height: the line's width, across. */
const PATTERN_HEIGHT_PX = 16;
const smoothstep = (edge0, edge1, x) => {
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
};
/**
* The selected-orbit tactical pattern, one group of it: a compact round dot
* followed by one hundred short dashes, in `css` (`#rrggbb`) at `alpha`.
* Lit as the line drew it: the dot glows brighter than the dashes. Along
* the image is along the line; across is across its width.
*/
function drawMissionOrbitPattern(canvas, css, alpha) {
const cells = MISSION_ORBIT_DASHES_PER_GROUP + 1;
const width = cells * CELL_PX;
const height = PATTERN_HEIGHT_PX;
canvas.width = width;
canvas.height = height;
const context = canvas.getContext?.('2d');
// A canvas that cannot draw (no 2D context) stays blank.
if (typeof context?.createImageData !== 'function') return;
const image = context.createImageData(width, height);
const n = Number.parseInt(css.slice(1), 16);
const rgb = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
// Antialiased across a pixel, as the pattern's edges were.
const edge = 1 / CELL_PX;
for (let px = 0; px < width; px++) {
const markPosition = (px + 0.5) / CELL_PX;
const markIndex = Math.floor(markPosition);
const local = markPosition - markIndex;
const isDot = markIndex === 0;
const centerDistance = Math.abs(local - 0.5);
const dashAlong =
1 - smoothstep(0.27 - edge * 1.35, 0.27 + edge * 1.35, centerDistance);
const dotAlong = (local - 0.5) / 0.32;
const glow = 1 + (isDot ? 0.65 : 0.07);
for (let py = 0; py < height; py++) {
const t = (py + 0.5) / height;
let visible;
if (isDot) {
const across = (t - 0.5) / 0.5;
visible = 1 - smoothstep(0.78, 1, Math.hypot(dotAlong, across));
} else {
const dashAcross = 1 - smoothstep(0.12, 0.24, Math.abs(t - 0.5));
visible = dashAlong * dashAcross;
}
const at = (py * width + px) * 4;
image.data[at] = Math.min(255, rgb[0] * glow);
image.data[at + 1] = Math.min(255, rgb[1] * glow);
image.data[at + 2] = Math.min(255, rgb[2] * glow);
image.data[at + 3] = Math.round(
255 * alpha * visible * (isDot ? 1 : 0.58),
);
}
}
context.putImageData(image, 0, 0);
}
/**
* The sidereal angle the inertial frame is turned by at `ms`, radians:
* a point there is drawn at that angle less around the Earth's axis.
*/
function siderealAngle(ms) {
const frame = temeToPseudoFixed(ms);
return Math.atan2(-frame.x.y, frame.x.x);
}
/** `p` turned by `angle` about the Earth's axis. */
function turned(p, angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z };
}
export function createOrbitRendering({
state: layerState,
services,
parts,
source,
}) {
const { orbitFrameModelMatrix } = services.satellites;
/** Pattern images by colour. */
const patterns = new Map();
/**
* Register the selected-orbit tactical material once. Each group begins with
* one compact round dot followed by one hundred short dashes.
* The mission orbit's line style: the tactical pattern in `css` (at
* 0.95 alpha), repeated in groups along the whole orbit.
*/
function ensureMissionOrbitPatternRegistered() {
if (layerState._missionOrbitPatternRegistered) return;
new Cesium.Material({
fabric: {
type: 'GevMissionOrbitTactical',
uniforms: {
color: Cesium.Color.CYAN,
groupCount: MISSION_ORBIT_PATTERN_GROUPS,
dashCount: MISSION_ORBIT_DASHES_PER_GROUP,
},
source: `
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
float groupPosition = fract(materialInput.st.s * groupCount);
float markPosition = groupPosition * (dashCount + 1.0);
float markIndex = floor(markPosition);
float localPosition = fract(markPosition);
float centerDistance = abs(localPosition - 0.5);
float edge = max(fwidth(localPosition) * 1.35, 0.012);
float dashAlong = 1.0 - smoothstep(0.27 - edge, 0.27 + edge, centerDistance);
float dashAcross = 1.0 - smoothstep(0.12, 0.24, abs(materialInput.st.t - 0.5));
float dash = dashAlong * dashAcross;
float dotAlong = (localPosition - 0.5) / 0.32;
float dotAcross = (materialInput.st.t - 0.5) / 0.5;
float dot = 1.0 - smoothstep(0.78, 1.0, length(vec2(dotAlong, dotAcross)));
float isDot = 1.0 - step(0.5, markIndex);
float visible = mix(dash, dot, isDot);
material.diffuse = color.rgb;
material.emission = color.rgb * mix(0.07, 0.65, isDot);
material.alpha = color.a * visible * mix(0.58, 1.0, isDot);
return material;
}`,
},
});
layerState._missionOrbitPatternRegistered = true;
}
function createMissionOrbitPatternMaterial(color) {
ensureMissionOrbitPatternRegistered();
return Cesium.Material.fromType('GevMissionOrbitTactical', {
color,
groupCount: MISSION_ORBIT_PATTERN_GROUPS,
dashCount: MISSION_ORBIT_DASHES_PER_GROUP,
});
function missionOrbitPatternStyle(css) {
let canvas = patterns.get(css);
if (!canvas) {
canvas = globalThis.document?.createElement?.('canvas') ?? null;
if (canvas) drawMissionOrbitPattern(canvas, css, 0.95);
patterns.set(css, canvas);
}
return {
kind: 'pattern',
image: { canvas, key: `rocket-mission-orbit:${css}` },
repeat: MISSION_ORBIT_PATTERN_GROUPS,
};
}
function missionOrbitPrimitiveVisible(launchId) {
return Boolean(
layerState._enabled &&
layerState._dataSource?.show &&
parts.rendering.missionsShown() &&
(!layerState._selectedLaunchId ||
layerState._selectedLaunchId === launchId),
);
}
/** Show each live ring as its mission's selection allows. */
function syncMissionOrbitPrimitiveVisibility() {
const set = layerState._missionSets?.orbits;
if (!set) return;
const changed = [];
for (const [launchId, path] of layerState._missionOrbitPrimitives) {
if (path.primitive)
path.primitive.show = missionOrbitPrimitiveVisible(launchId);
const show = missionOrbitPrimitiveVisible(launchId);
if (path.item.show === show) continue;
path.item = { ...path.item, show };
changed.push(path.item);
}
if (changed.length) set.upsert(changed);
}
function removeMissionOrbitPrimitives() {
for (const path of layerState._missionOrbitPrimitives.values()) {
if (path.primitive && layerState._viewer?.scene?.primitives) {
layerState._viewer.scene.primitives.remove(path.primitive);
}
}
layerState._missionSets?.orbits.clear();
layerState._missionOrbitPrimitives.clear();
}
function updateMissionOrbitPrimitiveFrames(nowDate) {
/**
* Where a point of a live ring, baked in ECEF at the ring's GMST, is
* drawn at `ms`: the ring turns with the sky as its line does.
*/
function drawnRingPoint(path, bakePosition, ms) {
return turned(turned(bakePosition, path.gmstAtBake), -siderealAngle(ms));
}
/** Move the live rings' labels with their rings, at `nowMs`. */
function updateMissionOrbitPrimitiveFrames(nowMs = Date.now()) {
for (const [launchId, path] of layerState._missionOrbitPrimitives) {
if (!path.primitive || !missionOrbitPrimitiveVisible(launchId)) continue;
orbitFrameModelMatrix(
path.gmstAtBake,
nowDate,
path.primitive.modelMatrix,
);
if (path.labelBakePosition && path.labelPosition) {
Cesium.Matrix4.multiplyByPoint(
path.primitive.modelMatrix,
if (!missionOrbitPrimitiveVisible(launchId)) continue;
if (path.labelBakePosition)
path.labelPosition = drawnRingPoint(
path,
path.labelBakePosition,
path.labelPosition,
nowMs,
);
}
}
}
/**
* A live satellite's ring, baked in ECEF at its track's GMST, in the
* inertial frame, for the caller to write to the `orbits` set. Returns
* its record, or null when the track has no bake (the ring is then an
* ordinary mission line).
*/
function addMissionOrbitPrimitive(launch, orbitPath, satelliteTrack) {
if (
!layerState._viewer ||
!satelliteTrack ||
!Number.isFinite(satelliteTrack.gmstAtBake)
)
return false;
const collection = new Cesium.PolylineCollection();
collection.add({
positions: orbitPath,
width: 3,
material: createMissionOrbitPatternMaterial(
Cesium.Color.fromCssColorString('#22e6e6').withAlpha(0.95),
),
const set = layerState._missionSets?.orbits;
if (!set || !satelliteTrack || !Number.isFinite(satelliteTrack.gmstAtBake))
return null;
const positions = new Float64Array(orbitPath.length * 3);
orbitPath.forEach((point, i) => {
const p = turned(point, satelliteTrack.gmstAtBake);
positions[i * 3] = p.x;
positions[i * 3 + 1] = p.y;
positions[i * 3 + 2] = p.z;
});
collection.show = missionOrbitPrimitiveVisible(launch.id);
orbitFrameModelMatrix(
satelliteTrack.gmstAtBake,
new Date(),
collection.modelMatrix,
);
layerState._viewer.scene.primitives.add(collection);
layerState._missionOrbitPrimitives.set(launch.id, {
primitive: collection,
gmstAtBake: satelliteTrack.gmstAtBake,
});
return true;
const item = {
id: `rocket-orbit:${launch.id}`,
positions,
widthPx: 3,
mode: '3d',
frame: 'inertial',
style: missionOrbitPatternStyle('#22e6e6'),
show: missionOrbitPrimitiveVisible(launch.id),
};
const path = { item, gmstAtBake: satelliteTrack.gmstAtBake };
layerState._missionOrbitPrimitives.set(launch.id, path);
return path;
}
function MissionOrbitPatternMaterialProperty(color) {
ensureMissionOrbitPatternRegistered();
this._color = color;
this._definitionChanged = new Cesium.Event();
}
Object.defineProperties(MissionOrbitPatternMaterialProperty.prototype, {
isConstant: {
get() {
return true;
},
},
definitionChanged: {
get() {
return this._definitionChanged;
},
},
});
MissionOrbitPatternMaterialProperty.prototype.getType = function getType() {
return 'GevMissionOrbitTactical';
};
MissionOrbitPatternMaterialProperty.prototype.getValue = function getValue(
time,
result,
) {
if (!Cesium.defined(result)) result = {};
result.color = this._color;
result.groupCount = MISSION_ORBIT_PATTERN_GROUPS;
result.dashCount = MISSION_ORBIT_DASHES_PER_GROUP;
return result;
};
MissionOrbitPatternMaterialProperty.prototype.equals = function equals(
other,
) {
return this === other;
};
return {
ensureMissionOrbitPatternRegistered,
createMissionOrbitPatternMaterial,
missionOrbitPatternStyle,
missionOrbitPrimitiveVisible,
syncMissionOrbitPrimitiveVisibility,
removeMissionOrbitPrimitives,
updateMissionOrbitPrimitiveFrames,
addMissionOrbitPrimitive,
MissionOrbitPatternMaterialProperty,
drawnRingPoint,
};
}
+1 -1
View File
@@ -313,7 +313,7 @@ export function createPanel({ state: layerState, services, parts, source }) {
if (
!layerState._missionPanelReady ||
!layerState._selectedLaunchId ||
!layerState._dataSource
!layerState._missionSets
)
return;
const now = performance.now();
+405 -279
View File
@@ -1,8 +1,9 @@
import * as Cesium from 'cesium';
// Still Cesium for its entities, so this layer loads the unbound camera
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { clamp } from '../../geo/vector.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
import {
TRAJECTORY_STAGE_COLORS,
REPLAY_ORBIT_DURATION_SEC,
@@ -10,6 +11,24 @@ import {
STAGE_REENTRY_ALTITUDE_M,
} from './policy.js';
/** Layer instances made so far: each one's draw sets get their own ids. */
let instances = 0;
/** The mission draw sets: shown and hidden together, as one layer. */
const MISSION_SETS = ['lines', 'sites', 'markers', 'reticles'];
/** The reticle a hovered roster row draws over its launch site. */
const RETICLE_KEY = 'rocket-mission-hover-reticle';
/** The launch id in a mission item id (`rocket-<kind>:<launch id>...`). */
function launchIdOf(id) {
if (typeof id !== 'string') return null;
const match = id.match(/^rocket-[^:]+:([^:]+)/);
return match?.[1] || null;
}
const copy = (p) => ({ x: p.x, y: p.y, z: p.z });
export function createRendering({
state: layerState,
services,
@@ -18,164 +37,283 @@ export function createRendering({
}) {
const { getSatelliteOrbitTrack, findSatelliteOrbitTrackInTle } =
services.satellites;
const declutterTime = new Cesium.JulianDate();
/** A plain ECEF point (the paths are plain) as the entities take one. */
const cartesian = (point) => Cesium.Cartesian3.clone(point);
const cartesians = (points) => points.map(cartesian);
/** The ids of this layer's draw sets, by name. */
let setIds = null;
/** Frames the mission sets have been walked in, the live cache's key. */
let frameNumber = 0;
// The follow reads its target before preRender (once a tick, and again
// in preUpdate while it first frames), so a follow read opens the live
// sample the next preRender keeps: the camera and the marker stand at
// the same instant, and every read until then shares it.
let followSampled = false;
/** A launch's marker colour, for the entities. */
/** Open the live sample a follow read and the next preRender share. */
function openFollowSample() {
if (followSampled) return;
followSampled = true;
frameNumber += 1;
}
/**
* Every drawn mission item by set and id, with what decides whether it
* shows: `isolated` (the mission's selection), and for points and icons
* `graphicShow` (the horizon, and for the reticle the roster's hover).
*/
const records = new Map();
/** Items to write at the next flush, by set name. */
const pending = new Map();
/** A launch's marker colour. */
function markerColor(launch) {
const [r, g, b, a] = parts.model.missionMarkerColor(launch);
return new Cesium.Color(r, g, b, a);
return [r, g, b, a];
}
function setGraphicVisibility(graphic, visible, time) {
if (!graphic) return;
const next = Boolean(visible);
const current = graphic.show?.getValue?.(time);
if (current !== next) graphic.show = next;
const recordKey = (set, id) => `${set}\u0000${id}`;
/** Queue `item` for its set, replacing one queued under its id. */
function queue(set, item) {
let items = pending.get(set);
if (!items) pending.set(set, (items = new Map()));
items.set(item.id, item);
}
/** Write what was queued, one upsert a set. */
function flush() {
const sets = layerState._missionSets;
if (!sets) {
pending.clear();
return;
}
for (const [name, items] of pending)
if (items.size) sets[name].upsert([...items.values()]);
pending.clear();
}
/** What a record draws now. */
const drawnShow = (record) => record.isolated && record.graphicShow;
/** Add a mission item; it draws once flushed. */
function addItem(set, item, { graphicShow = true, position = null } = {}) {
const record = {
set,
id: item.id,
launchId: launchIdOf(item.id),
// Every item shows until the selection isolates a mission, as the
// entities did; `isolateMission` runs once a build is done.
isolated: true,
graphicShow,
// Where the horizon pass reads it; null for lines.
position,
item: { ...item, show: graphicShow },
};
records.set(recordKey(set, item.id), record);
queue(set, record.item);
return record;
}
/** Write a record again if what it draws changed. */
function refresh(record, moved = null) {
const show = drawnShow(record);
if (record.item.show === show && !moved) return;
record.item = moved
? { ...record.item, pos: moved, show }
: { ...record.item, show };
queue(record.set, record.item);
}
/**
* The layer's entities, hidden until enabled. They stay entities: the
* replay vehicle and the live payload move every frame, the selected site
* is the viewer's selected entity, and the orbits draw with their own
* materials.
* The layer's draw sets, hidden until enabled. The live satellite rings
* (`orbits`) and the pad zone (`pad`) show by their own rules.
*/
function attach(viewer) {
layerState._dataSource = new Cesium.CustomDataSource('rocket-launches');
layerState._dataSource.show = false;
viewer.dataSources.add(layerState._dataSource);
const draw = drawOf(viewer);
const base = `rocket-launches:${++instances}`;
setIds = {
lines: `${base}:lines`,
sites: `${base}:sites`,
markers: `${base}:markers`,
reticles: `${base}:reticles`,
orbits: `${base}:orbits`,
pad: `${base}:pad`,
};
const sets = {
lines: draw.lines({ id: setIds.lines, show: false }),
sites: draw.points({ id: setIds.sites, show: false }),
markers: draw.points({ id: setIds.markers, show: false }),
reticles: draw.icons({ id: setIds.reticles, show: false }),
orbits: draw.lines({ id: setIds.orbits }),
pad: draw.shapes({ id: setIds.pad }),
};
layerState._missionSets = sets;
}
function detach(viewer) {
if (layerState._dataSource)
viewer.dataSources.remove(layerState._dataSource, true);
layerState._dataSource = null;
function detach() {
const sets = layerState._missionSets;
layerState._missionSets = null;
records.clear();
pending.clear();
if (!sets) return;
for (const set of Object.values(sets)) set.dispose();
}
/** Whether the missions' entities are shown. */
/** Whether the missions are shown. */
function missionsShown() {
return Boolean(layerState._dataSource?.show);
return Boolean(layerState._missionSets?.lines.show);
}
/** Show or hide the missions' entities. */
/** Show or hide the missions. */
function showMissions(shown) {
if (layerState._dataSource) layerState._dataSource.show = shown;
const sets = layerState._missionSets;
if (!sets) return;
for (const name of MISSION_SETS) sets[name].show = shown;
}
/** Remove every mission entity, ahead of a rebuild. */
/** Remove every mission item, ahead of a rebuild. */
function clearLaunchEntities() {
layerState._dataSource?.entities.removeAll();
// A followed item goes with them, as a removed entity stopped being
// followed.
layerState._stockFollow?.stop();
const sets = layerState._missionSets;
records.clear();
pending.clear();
if (!sets) return;
for (const name of MISSION_SETS) sets[name].clear();
}
/** The launch id of a mission entity, or null for anything else. */
function entityLaunchId(entity) {
if (!entity?.id || typeof entity.id !== 'string') return null;
const match = entity.id.match(/^rocket-[^:]+:([^:]+)/);
return match?.[1] || null;
/** Whether a hit is one of this layer's mission items. */
function missionHit(hit) {
if (!hit || !setIds) return false;
return (
hit.set === setIds.lines ||
hit.set === setIds.sites ||
hit.set === setIds.markers ||
hit.set === setIds.reticles
);
}
/** The launch of the first mission entity among a click's drilled picks. */
function launchIdFromPicks(picks) {
for (const picked of picks) {
const launchId = entityLaunchId(picked?.id);
/**
* What a double-click on a mission item follows: a point by where it is
* drawn (the payload as it moves), a line zoomed to by its bounds.
*/
function followTargetFor(hit) {
if (!missionHit(hit)) return null;
const name = Object.keys(setIds).find((key) => setIds[key] === hit.set);
const record = records.get(recordKey(name, hit.id));
if (!record) return null;
if (!record.position)
return { zoomTo: sphereFromPoints(record.item.positions) };
const at = record.position;
return {
key: `${setIds.sites}:${hit.id}`,
position: () => {
if (typeof at === 'function') openFollowSample();
const p = typeof at === 'function' ? at() : at;
return p ? copy(p) : null;
},
};
}
/** The launch of the first mission item among a click's drilled hits. */
function launchIdFromPicks(hits) {
for (const hit of hits) {
if (!missionHit(hit)) continue;
const launchId = launchIdOf(hit.id);
if (launchId) return launchId;
}
return null;
}
/** Whether a mission entity is under a screen position (CSS px). */
function launchMarkerAt(position) {
const scene = layerState._viewer?.scene;
if (!scene) return false;
return scene
.drillPick(position, 12)
.some((picked) => entityLaunchId(picked?.id));
/** The mission items under a screen position (CSS px), at most `limit`. */
function missionHitsAt(position, limit = 12) {
const query = findQuery(layerState._viewer);
if (!query || !position) return [];
return query.drillPick(position.x, position.y, { limit });
}
/** Make a launch's site marker the viewer's selected entity, or none. */
function selectLaunchEntity(launchId) {
const viewer = layerState._viewer;
if (!viewer) return;
viewer.selectedEntity = launchId
? layerState._dataSource?.entities.getById(`rocket-launch:${launchId}`)
: undefined;
/** Whether a mission item is under a screen position (CSS px). */
function launchMarkerAt(position) {
return Boolean(launchIdFromPicks(missionHitsAt(position)));
}
/**
* Show only the selected mission's entities, or every site marker and
* Note the selected launch site. Nothing draws it differently; the
* selected mission is the layer's own (`_selectedLaunchId`).
*/
function selectLaunchEntity() {}
/**
* Show only the selected mission's items, or every site marker and
* nothing else when none is selected.
*/
function isolateMission(launchId) {
if (!layerState._dataSource) return;
for (const entity of layerState._dataSource.entities.values) {
const relatedId = entityLaunchId(entity);
entity.show = launchId
? relatedId === launchId
: entity.id.startsWith('rocket-launch:');
if (!layerState._missionSets) return;
for (const record of records.values()) {
record.isolated = launchId
? record.launchId === launchId
: record.id.startsWith('rocket-launch:');
refresh(record);
}
flush();
}
/**
* The projected (estimated) orbit drawn as an entity for a launch, ECEF;
* null when its orbit is a live satellite ring or it has none.
* The projected (estimated) orbit drawn as a mission line for a launch,
* ECEF; null when its orbit is a live satellite ring or it has none.
*/
function projectedOrbitPath(launchId) {
return layerState._replayTracks.get(launchId)?.projectedOrbitPath ?? null;
}
function updateMissionFrame() {
if (
!layerState._enabled ||
!layerState._viewer ||
!layerState._dataSource?.show
) {
if (followSampled) followSampled = false;
else frameNumber += 1;
if (!layerState._enabled || !layerState._viewer || !missionsShown()) {
parts.overlays.hideReplayVehicleOverlay();
return;
}
parts.panel.updateMissionTelemetry();
const time = Cesium.JulianDate.now(declutterTime);
const occluder = horizonFrom(layerState._viewer.scene.camera.positionWC);
const eye = findCamera(layerState._viewer)?.pose().position;
const occluder = eye ? horizonFrom(eye) : null;
parts.overlays.updateReplayVehicleOverlay(occluder);
parts.overlays.refreshSelectedMissionOverlayText();
for (const entity of layerState._dataSource.entities.values) {
if (!entity.show) continue;
if (!entity.position) continue;
const id = entityLaunchId(entity);
if (!id) continue;
const position = entity.position.getValue(time);
for (const record of records.values()) {
if (!record.isolated || !record.position) continue;
const live = typeof record.position === 'function';
const position = live ? record.position() : record.position;
let horizonVisible = Boolean(
position && occluder.isPointVisible(position),
position && occluder?.isPointVisible(position),
);
const launchAnchor = entity.id.startsWith('rocket-launch:');
if (launchAnchor) {
if (record.id.startsWith('rocket-launch:')) {
horizonVisible = parts.overlays.missionAnchorVisible(
layerState._viewer.scene.camera.positionWC,
eye,
position,
id,
record.launchId,
layerState._selectedLaunchId,
);
// Keep entity.show reserved for mission-selection isolation. Horizon
// state is applied to the individual graphics below so a rear-side
// anchor remains eligible for reevaluation as the camera moves.
}
if (entity.point) {
setGraphicVisibility(entity.point, horizonVisible, time);
}
if (launchAnchor && entity.billboard) {
setGraphicVisibility(
entity.billboard,
horizonVisible && id === layerState._hoveredRosterLaunchId,
time,
);
// The selection's isolation stays its own; horizon state is kept
// apart, so a rear-side anchor is judged again as the camera moves.
}
record.graphicShow =
record.set === 'reticles'
? horizonVisible &&
record.launchId === layerState._hoveredRosterLaunchId
: horizonVisible;
refresh(record, live && position ? copy(position) : null);
}
flush();
}
function addLaunchEntity(launch, activeTleText = layerState._activeTleText) {
const position = Cesium.Cartesian3.fromDegrees(launch.lon, launch.lat);
/**
* Draw a launch's items. With `defer`, they wait for `flushLaunchEntities`,
* so a whole roster writes each set once.
*/
function addLaunchEntity(
launch,
activeTleText = layerState._activeTleText,
{ defer = false } = {},
) {
const position = fromDegrees(launch.lon, launch.lat);
const overlayRecord = {
launch,
anchorPosition: position,
@@ -212,39 +350,50 @@ export function createRendering({
);
});
if (satelliteTrack) layerState._orbitMatches++;
layerState._dataSource.entities.add({
id: `rocket-launch:${launch.id}`,
position,
point: {
const siteMeta = {
launchId: launch.id,
launchName: launch.name,
launchTime: launch.launchTime,
launchSite: launch.launchSite,
provider: launch.provider,
mission: launch.mission,
status: launch.status,
source: launch.source,
orbit: JSON.stringify(launch.orbit || {}),
satelliteName: satelliteTrack?.name || '',
noradId: satelliteTrack?.noradId || '',
};
const color = markerColor(launch);
addItem(
'sites',
{
id: `rocket-launch:${launch.id}`,
pos: position,
pixelSize: 5,
color: markerColor(launch),
outlineColor: markerColor(launch),
color,
outlineColor: color,
outlineWidth: 0,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: siteMeta,
},
billboard: {
image: parts.overlays.missionHoverReticleImage(),
width: 24,
height: 24,
show: false,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
{ position },
);
addItem(
'reticles',
{
id: `rocket-launch:${launch.id}`,
pos: position,
image: {
canvas: parts.overlays.missionHoverReticleImage(),
key: RETICLE_KEY,
},
size: [24, 24],
anchor: 'center',
disableDepthTest: Number.POSITIVE_INFINITY,
meta: siteMeta,
},
properties: {
launchId: launch.id,
launchName: launch.name,
launchTime: launch.launchTime,
launchSite: launch.launchSite,
provider: launch.provider,
mission: launch.mission,
status: launch.status,
source: launch.source,
orbit: JSON.stringify(launch.orbit || {}),
satelliteName: satelliteTrack?.name || '',
noradId: satelliteTrack?.noradId || '',
},
});
{ position, graphicShow: false },
);
const points = launch.trajectory
.filter(
(point) =>
@@ -259,7 +408,7 @@ export function createRendering({
point.stageName ||
'trajectory',
),
position: Cesium.Cartesian3.fromDegrees(
position: fromDegrees(
Number(point.longitude),
Number(point.latitude),
Number(point.altitude || 0),
@@ -275,20 +424,19 @@ export function createRendering({
});
segments.forEach((segment, index) => {
if (segment.positions.length < 2) return;
layerState._dataSource.entities.add({
addItem('lines', {
id: `rocket-trajectory:${launch.id}:${index}`,
polyline: {
positions: cartesians(
parts.paths.surfaceSafePath(segment.positions),
),
width: 2,
material: Cesium.Color.fromCssColorString(
positions: parts.paths.surfaceSafePath(segment.positions).map(copy),
widthPx: 2,
mode: '3d',
style: {
kind: 'solid',
color: hexColor(
TRAJECTORY_STAGE_COLORS[index % TRAJECTORY_STAGE_COLORS.length],
).withAlpha(0.8),
clampToGround: false,
arcType: Cesium.ArcType.NONE,
0.8,
),
},
properties: {
meta: {
launchId: launch.id,
stage: segment.stage,
source: launch.source,
@@ -324,7 +472,7 @@ export function createRendering({
new Date(insertionEpochMs),
);
if (propagatedInsertion) {
insertionReference = Cesium.Cartesian3.fromDegrees(
insertionReference = fromDegrees(
propagatedInsertion.longitude,
propagatedInsertion.latitude,
propagatedInsertion.altitude,
@@ -337,7 +485,7 @@ export function createRendering({
// ascent duration, and join the forward orbit tangent. Using the UTC
// epoch as phase sent some ascents toward the far side of Earth and
// forced a visible 180-degree corrective hook before insertion.
const insertionProgress = Cesium.Math.clamp(
const insertionProgress = clamp(
insertionDurationSec / orbitPeriodSec,
1 / 96,
0.16,
@@ -357,11 +505,10 @@ export function createRendering({
launch,
ascentPath,
);
// Cesium can evaluate CallbackProperty values multiple times while it
// traverses one frame. Camera tracking and the HTML replay overlay must
// use the exact same replay epoch as those callbacks; sampling Date.now()
// independently made the vehicle advance relative to the camera and then
// snap back on the next frame.
// Camera tracking and the HTML replay overlay must use the exact same
// replay epoch within a frame; sampling Date.now() independently made
// the vehicle advance relative to the camera and then snap back on the
// next frame.
let replayStateForFrame = null;
const sampleReplayState = () =>
parts.replay.replayState(
@@ -375,10 +522,8 @@ export function createRendering({
REPLAY_TILE_SETTLE_DELAY_SEC,
layerState._replayCameraLaunchId !== launch.id,
);
// preUpdate runs before Cesium evaluates entity CallbackProperties. Seed
// one state there and retain it through postRender so every consumer in
// that traversal sees the same timestamp. scene.frameState.frameNumber is
// advanced between some of those phases, so it is not a reliable cache key.
// The replay camera seeds one state in preUpdate, and every consumer
// through postRender reads that one.
const beginReplayFrame = () => {
replayStateForFrame = sampleReplayState();
return replayStateForFrame;
@@ -404,24 +549,22 @@ export function createRendering({
if (path.length < 2) return;
const reentryIndex = parts.paths.atmosphericReentryIndex(path);
const reentryPath = path.slice(reentryIndex);
const color = Cesium.Color.fromCssColorString(
const stageColor =
TRAJECTORY_STAGE_COLORS[
(stageIndex + 1) % TRAJECTORY_STAGE_COLORS.length
],
);
layerState._dataSource.entities.add({
];
addItem('lines', {
id: `rocket-reentry-recovery:${launch.id}:${stageIndex}`,
polyline: {
positions: cartesians(path),
width: 2,
material: new Cesium.PolylineDashMaterialProperty({
color: color.withAlpha(0.82),
dashLength: 12,
dashPattern: 0xaaaa,
}),
arcType: Cesium.ArcType.NONE,
positions: path.map(copy),
widthPx: 2,
mode: '3d',
style: {
kind: 'dash',
color: hexColor(stageColor, 0.82),
length: 12,
pattern16: 0xaaaa,
},
properties: {
meta: {
launchId: launch.id,
stageId: stage.id,
phase: 'STAGE_REENTRY_RECOVERY',
@@ -430,20 +573,18 @@ export function createRendering({
},
});
if (reentryPath.length > 1) {
layerState._dataSource.entities.add({
addItem('lines', {
id: `rocket-reentry:${launch.id}:${stageIndex}`,
polyline: {
positions: cartesians(reentryPath),
width: 2.5,
material: new Cesium.PolylineDashMaterialProperty({
color:
Cesium.Color.fromCssColorString('#ffd166').withAlpha(0.9),
dashLength: 8,
dashPattern: 0xf0f0,
}),
arcType: Cesium.ArcType.NONE,
positions: reentryPath.map(copy),
widthPx: 2.5,
mode: '3d',
style: {
kind: 'dash',
color: hexColor('#ffd166', 0.9),
length: 8,
pattern16: 0xf0f0,
},
properties: {
meta: {
launchId: launch.id,
stageId: stage.id,
phase: 'ATMOSPHERIC_REENTRY',
@@ -451,7 +592,7 @@ export function createRendering({
source: 'Estimated 100 km atmospheric interface',
},
});
const reentryPosition = cartesian(path[reentryIndex]);
const reentryPosition = copy(path[reentryIndex]);
overlayRecord.elementEntryFactories.push(() =>
parts.overlays.createRocketMissionElementOverlayEntry({
id: `reentry:${launch.id}:${stageIndex}`,
@@ -463,22 +604,25 @@ export function createRendering({
}),
);
}
layerState._dataSource.entities.add({
id: `rocket-recovery-end:${launch.id}:${stageIndex}`,
position: cartesian(path.at(-1)),
point: {
const endpoint = copy(path.at(-1));
addItem(
'markers',
{
id: `rocket-recovery-end:${launch.id}:${stageIndex}`,
pos: endpoint,
pixelSize: 4,
color,
color: hexColor(stageColor),
outlineWidth: 0,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: {
launchId: launch.id,
stageId: stage.id,
phase: 'RECOVERY_ENDPOINT',
source: launch.source,
},
},
properties: {
launchId: launch.id,
stageId: stage.id,
phase: 'RECOVERY_ENDPOINT',
source: launch.source,
},
});
{ position: endpoint },
);
});
layerState._replayTracks.set(launch.id, {
ascentPath,
@@ -494,7 +638,7 @@ export function createRendering({
lastOverlayWindowPosition: null,
lastOverlayMode: null,
});
let livePosition = Cesium.Cartesian3.fromDegrees(
let livePosition = fromDegrees(
orbitCurrent.longitude,
orbitCurrent.latitude,
orbitCurrent.altitude,
@@ -502,7 +646,7 @@ export function createRendering({
const liveTime = new Date();
const liveTelemetry = {
speedMps: null,
// Where the entity draws the payload now, for the mission panel.
// Where the payload draws now, for the mission panel.
position: () => {
updateLiveState();
return livePosition;
@@ -512,10 +656,10 @@ export function createRendering({
let liveFrameNumber = -1;
const fallbackPeriodSec =
parts.paths.estimatedOrbitPeriodSeconds(orbitPath);
// Propagated at most once a frame, so the marker and the label
// reading the same cache never stand at different instants.
const updateLiveState = () => {
const frameNumber =
layerState._viewer?.scene?.frameState?.frameNumber ?? -1;
if (frameNumber !== -1 && frameNumber === liveFrameNumber) return;
if (frameNumber !== 0 && frameNumber === liveFrameNumber) return;
liveFrameNumber = frameNumber;
const nowMs = Date.now();
liveTime.setTime(nowMs);
@@ -523,11 +667,10 @@ export function createRendering({
const propagated =
satelliteTrack.positionAt?.(liveTime) || satelliteTrack.current;
if (propagated) {
Cesium.Cartesian3.fromDegrees(
fromDegreesInto(
propagated.longitude,
propagated.latitude,
propagated.altitude,
undefined,
livePosition,
);
liveTelemetry.speedMps = Number.isFinite(propagated.speedMps)
@@ -535,8 +678,7 @@ export function createRendering({
: null;
}
} else {
// In-place write keeps one Cartesian3 for the mission's lifetime —
// the estimated branch previously reallocated per propagation.
// In-place write keeps one position for the mission's lifetime.
livePosition =
parts.paths.samplePath(
orbitPath,
@@ -545,31 +687,34 @@ export function createRendering({
) || livePosition;
}
};
layerState._dataSource.entities.add({
id: `rocket-satellite:${launch.id}`,
position: new Cesium.CallbackProperty(() => {
updateLiveState();
return livePosition;
}, false),
point: {
updateLiveState();
addItem(
'markers',
{
id: `rocket-satellite:${launch.id}`,
pos: copy(livePosition),
pixelSize: 6,
color: Cesium.Color.fromCssColorString(
satelliteTrack ? '#7bed9f' : '#ffd166',
),
color: hexColor(satelliteTrack ? '#7bed9f' : '#ffd166'),
outlineWidth: 0,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: {
launchId: launch.id,
noradId: satelliteTrack?.noradId || '',
phase: satelliteTrack
? 'CURRENT_SATELLITE_POSITION'
: 'ESTIMATED_ORBIT_POSITION',
source: satelliteTrack
? 'Satellites layer'
: 'Approximate mission orbit',
},
},
properties: {
launchId: launch.id,
noradId: satelliteTrack?.noradId || '',
phase: satelliteTrack
? 'CURRENT_SATELLITE_POSITION'
: 'ESTIMATED_ORBIT_POSITION',
source: satelliteTrack
? 'Satellites layer'
: 'Approximate mission orbit',
{
position: () => {
updateLiveState();
return livePosition;
},
},
});
);
overlayRecord.liveEventTime = () => liveTime;
overlayRecord.elementEntryFactories.push(() => {
const name = satelliteTrack
@@ -586,29 +731,26 @@ export function createRendering({
gapPx: 12,
});
});
// Live satellite rings use a primitive collection so the core Satellite
// GMST transform can rotate their baked ECEF geometry without rebuilding
// it. Estimated launch-site-relative rings remain ordinary entities.
const primitiveOrbitAdded = parts.orbitRendering.addMissionOrbitPrimitive(
// A live satellite's ring is drawn in the inertial frame its GMST
// bake puts it in, so it turns with the sky as the payload does.
// An estimated, launch-site-relative ring is an ordinary line.
const ringPath = parts.orbitRendering.addMissionOrbitPrimitive(
launch,
orbitPath,
satelliteTrack,
);
if (!primitiveOrbitAdded) {
layerState._dataSource.entities.add({
if (ringPath) queue('orbits', ringPath.item);
else {
addItem('lines', {
id: `rocket-orbit:${launch.id}`,
polyline: {
positions: cartesians(orbitPath),
// The 3 px canvas gives the periodic dot room to read as round; the
// shader masks the ten intervening dashes down to a thin center stroke.
width: 3,
material:
new parts.orbitRendering.MissionOrbitPatternMaterialProperty(
Cesium.Color.fromCssColorString('#c084fc').withAlpha(0.95),
),
arcType: Cesium.ArcType.NONE,
},
properties: {
positions: orbitPath.map(copy),
// The 3 px width gives the periodic dot room to read as round;
// the pattern masks the intervening dashes down to a thin
// centre stroke.
widthPx: 3,
mode: '3d',
style: parts.orbitRendering.missionOrbitPatternStyle('#c084fc'),
meta: {
launchId: launch.id,
satelliteName: '',
noradId: '',
@@ -617,17 +759,16 @@ export function createRendering({
});
layerState._replayTracks.get(launch.id).projectedOrbitPath = orbitPath;
}
const orbitLabelBakePosition = cartesian(ascentPath.at(-1));
const orbitLabelBakePosition = copy(ascentPath.at(-1));
let orbitLabelPosition = orbitLabelBakePosition;
const primitivePath = layerState._missionOrbitPrimitives.get(launch.id);
if (primitivePath) {
primitivePath.labelBakePosition = orbitLabelBakePosition;
primitivePath.labelPosition = Cesium.Matrix4.multiplyByPoint(
primitivePath.primitive.modelMatrix,
if (ringPath) {
ringPath.labelBakePosition = orbitLabelBakePosition;
ringPath.labelPosition = parts.orbitRendering.drawnRingPoint(
ringPath,
orbitLabelBakePosition,
new Cesium.Cartesian3(),
Date.now(),
);
orbitLabelPosition = () => primitivePath.labelPosition;
orbitLabelPosition = () => ringPath.labelPosition;
}
overlayRecord.elementEntryFactories.push(() =>
parts.overlays.createRocketMissionElementOverlayEntry({
@@ -639,41 +780,20 @@ export function createRendering({
gapPx: 8,
}),
);
const replayPosition = new Cesium.CallbackProperty(() => {
const state = getReplayState();
const sample = state.ascending
? parts.paths.samplePath(ascentPath, state.phaseProgress)
: parts.paths.samplePath(animatedOrbitPath, state.phaseProgress);
return sample && cartesian(sample);
}, false);
layerState._dataSource.entities.add({
id: `rocket-vehicle:${launch.id}`,
position: replayPosition,
properties: {
launchId: launch.id,
noradId: satelliteTrack?.noradId || '',
phase: 'ASCENT_THEN_ORBIT',
source: satelliteTrack
? 'Satellite trajectory animation'
: 'Approximate trajectory animation',
},
});
layerState._dataSource.entities.add({
addItem('lines', {
id: `rocket-transfer:${launch.id}`,
polyline: {
positions: cartesians(ascentPath),
width: 1.5,
// The animated vehicle uses Cartesian interpolation between these
// exact samples. Prevent Cesium from replacing each segment with a
// geodesic arc, which would visually separate the dot from the line.
arcType: Cesium.ArcType.NONE,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString('#7bed9f').withAlpha(0.8),
dashLength: 24,
dashPattern: 0xf0f0,
}),
positions: ascentPath.map(copy),
widthPx: 1.5,
// The replay vehicle moves straight between these exact samples:
// the line runs straight between them too, so the dot stays on it.
mode: '3d',
style: {
kind: 'dash',
color: hexColor('#7bed9f', 0.8),
length: 24,
pattern16: 0xf0f0,
},
properties: {
meta: {
launchId: launch.id,
phase: 'APPROXIMATE_TRANSFER',
source: satelliteTrack
@@ -682,6 +802,7 @@ export function createRendering({
},
});
}
if (!defer) flush();
}
return {
attach,
@@ -690,12 +811,17 @@ export function createRendering({
showMissions,
clearLaunchEntities,
launchIdFromPicks,
followTargetFor,
missionHitsAt,
launchMarkerAt,
setGraphicVisibility,
selectLaunchEntity,
isolateMission,
projectedOrbitPath,
updateMissionFrame,
addLaunchEntity,
flushLaunchEntities: flush,
get setIds() {
return setIds;
},
};
}
+1 -1
View File
@@ -79,7 +79,7 @@ export function createSelection({
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(null);
}
if (!layerState._dataSource) return;
if (!layerState._missionSets) return;
parts.rendering.isolateMission(launchId);
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
parts.overlays.syncMissionOverlayEntries();
+6 -6
View File
@@ -9,7 +9,8 @@ export function createState({ services }) {
clearSource: clearOverlaySource,
});
state._dataSource = null;
// The layer's draw sets by name, while it is initialised.
state._missionSets = null;
state._count = 0;
@@ -23,6 +24,9 @@ export function createState({ services }) {
state._inputSubscription = null;
// The double-click follow of mission points, while initialised.
state._stockFollow = null;
state._viewer = null;
state._declutterHandler = null;
@@ -126,7 +130,7 @@ export function createState({ services }) {
state._missionZoomAnchorId = null;
state._launchPadZonePrimitive = null;
state._launchPadZoneItem = null;
state._launchPadZoneRemover = null;
@@ -134,10 +138,6 @@ export function createState({ services }) {
state._missionOrbitPrimitives = new Map();
state._missionRingDate = new Date(0);
state._missionOrbitPatternRegistered = false;
state._pathDistanceCache = new WeakMap();
state._sourceController = new AbortController();
return state;