diff --git a/src/data/rocketLaunches.test.mjs b/src/data/rocketLaunches.test.mjs index 41b2bc964..3ca9e8662 100644 --- a/src/data/rocketLaunches.test.mjs +++ b/src/data/rocketLaunches.test.mjs @@ -1,6 +1,8 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs'; import { gstime } from 'satellite.js'; import { createModel } from '../layers/launches/model.js'; import rocketLaunchesLayer, { @@ -1187,6 +1189,7 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths }, selectedEntity: undefined, }; + bindRenderer(viewer, { frame: fakeSceneFrame(viewer) }); const hostCalls = []; const host = { setEntries: (...args) => hostCalls.push(['entries', ...args]), diff --git a/src/layers/launches/hover.test.mjs b/src/layers/launches/hover.test.mjs index d09e5168b..40097209d 100644 --- a/src/layers/launches/hover.test.mjs +++ b/src/layers/launches/hover.test.mjs @@ -2,6 +2,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { Event } from 'cesium'; import { createLaunchHover } from './lifecycle.js'; +import { + bindFakeCesiumCamera, + fakeCameraPort, +} from '../../testSupport/fakeCameraPort.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; function fakeTimers() { const timers = new Map(); @@ -31,20 +36,17 @@ function hoverRig({ overMarker }) { enabled = true, free = true; const timers = fakeTimers(); - const viewer = { + const viewer = bindFakeCesiumCamera({ camera: { moveStart: new Event(), moveEnd: new Event() }, - scene: { - canvas: { style: { cursor: '' } }, - drillPick(position) { - picks++; - return overMarker(position) ? [{ id: 'launch' }] : []; - }, - }, - }; + scene: { canvas: { style: { cursor: '' } } }, + }); const hover = createLaunchHover({ viewer, enabled: () => enabled, - entityLaunchId: (id) => id === 'launch', + launchAt(position) { + picks++; + return overMarker(position); + }, now: () => at, documentRef: { hidden: false }, pointerFree: () => free, @@ -153,20 +155,16 @@ test('mission hover throttles, clears on motion/hidden, and releases listeners', addEventListener: (_n, fn) => listeners.add(fn), removeEventListener: (_n, fn) => listeners.delete(fn), }; - const viewer = { - camera: { moveStart: new Event(), moveEnd: new Event() }, - scene: { - canvas: { style: {} }, - drillPick() { - picks++; - return [{ id: 'launch' }]; - }, - }, - }; + const camera = fakeCameraPort(); + const viewer = { scene: { canvas: { style: {} } } }; + bindRenderer(viewer, { camera: camera.port }); const hover = createLaunchHover({ viewer, enabled: () => enabled, - entityLaunchId: (id) => id === 'launch', + launchAt() { + picks++; + return true; + }, now: () => at, documentRef: doc, pointerFree: () => true, @@ -177,12 +175,12 @@ test('mission hover throttles, clears on motion/hidden, and releases listeners', assert.equal(viewer.scene.canvas.style.cursor, 'pointer'); hover.move({ endPosition: {} }); assert.equal(picks, 2); - viewer.camera.moveStart.raiseEvent(); + camera.emit('moveStart'); at = 500; hover.move({ endPosition: {} }); assert.equal(picks, 2); assert.equal(viewer.scene.canvas.style.cursor, ''); - viewer.camera.moveEnd.raiseEvent(); + camera.emit('moveEnd'); hover.move({ endPosition: {} }); assert.equal(picks, 3); doc.hidden = true; @@ -196,27 +194,24 @@ test('mission hover throttles, clears on motion/hidden, and releases listeners', assert.equal(picks, 3); hover.destroy(); assert.equal(listeners.size, 0); - assert.equal(viewer.camera.moveStart.numberOfListeners, 0); - assert.equal(viewer.camera.moveEnd.numberOfListeners, 0); + assert.equal(camera.listenerCount('moveStart'), 0); + assert.equal(camera.listenerCount('moveEnd'), 0); }); test('mission hover preserves the cursor of a pointer-owning tool', () => { let free = true, picks = 0; - const viewer = { + const viewer = bindFakeCesiumCamera({ camera: { moveStart: new Event(), moveEnd: new Event() }, - scene: { - canvas: { style: { cursor: '' } }, - drillPick() { - picks++; - return [{ id: 'launch' }]; - }, - }, - }; + scene: { canvas: { style: { cursor: '' } } }, + }); const hover = createLaunchHover({ viewer, enabled: () => true, - entityLaunchId: () => true, + launchAt() { + picks++; + return true; + }, documentRef: null, pointerFree: () => free, }); @@ -230,3 +225,33 @@ test('mission hover preserves the cursor of a pointer-owning tool', () => { assert.equal(picks, 1); assert.equal(viewer.scene.canvas.style.cursor, 'crosshair'); }); + +test('mission picks are read by the rendering part, which owns the entities', async () => { + const { createRendering } = await import('./rendering.js'); + const mission = { id: 'rocket-launch:abc' }; + const drilled = []; + const state = { + _viewer: { + scene: { + drillPick(position, limit) { + drilled.push([position, limit]); + return [{ id: { id: 'cable:1' } }, { id: mission }]; + }, + }, + }, + }; + const rendering = createRendering({ + state, + services: { satellites: {} }, + parts: {}, + }); + assert.equal(rendering.launchMarkerAt({ x: 3, y: 4 }), true); + assert.deepEqual(drilled, [[{ x: 3, y: 4 }, 12]]); + assert.equal( + rendering.launchIdFromPicks([{ id: 'x' }, { id: mission }]), + 'abc', + ); + assert.equal(rendering.launchIdFromPicks([{ id: 'x' }]), null); + state._viewer = null; + assert.equal(rendering.launchMarkerAt({ x: 3, y: 4 }), false); +}); diff --git a/src/layers/launches/ingestion.js b/src/layers/launches/ingestion.js index bd1529c0b..57a06e3c5 100644 --- a/src/layers/launches/ingestion.js +++ b/src/layers/launches/ingestion.js @@ -189,7 +189,7 @@ export function createIngestion({ if (layerState._replayCameraLaunchId) parts.replay.stopMissionReplay(); layerState._launches = launches; parts.orbitRendering.removeMissionOrbitPrimitives(); - layerState._dataSource.entities.removeAll(); + parts.rendering.clearLaunchEntities(); layerState._missionOverlayRecords.clear(); layerState._satelliteTelemetry.clear(); layerState._replayTracks.clear(); diff --git a/src/layers/launches/ingestion.test.mjs b/src/layers/launches/ingestion.test.mjs index f24082dcb..c991eae22 100644 --- a/src/layers/launches/ingestion.test.mjs +++ b/src/layers/launches/ingestion.test.mjs @@ -10,6 +10,8 @@ import { createControls } from './controls.js'; import { createLifecycle } from './lifecycle.js'; import { layerFeedState } from '../../data/feedState.js'; import { inputFor } from '../../input/dispatcher.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs'; const noop = () => {}; @@ -79,6 +81,7 @@ async function fixture({ legacySource = false } = {}) { dataSources: new Cesium.DataSourceCollection(), 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. @@ -124,6 +127,13 @@ async function fixture({ legacySource = false } = {}) { state._dataSource = null; }, updateMissionFrame: noop, + missionsShown: () => Boolean(state._dataSource?.show), + showMissions(shown) { + if (state._dataSource) state._dataSource.show = shown; + }, + clearLaunchEntities: () => state._dataSource?.entities.removeAll(), + launchIdFromPicks: () => null, + launchMarkerAt: () => false, addLaunchEntity(record) { state._dataSource.entities.add({ id: record.id, diff --git a/src/layers/launches/lifecycle.js b/src/layers/launches/lifecycle.js index 2787d17de..1255d790e 100644 --- a/src/layers/launches/lifecycle.js +++ b/src/layers/launches/lifecycle.js @@ -1,5 +1,6 @@ import { isPointerFree } from '../../data/inputOwnership.js'; import { inputFor } from '../../input/dispatcher.js'; +import { findCamera, findFrame } from '../../render/rendererOf.js'; const HOVER_PICK_INTERVAL_MS = 120; @@ -11,7 +12,7 @@ const HOVER_PICK_INTERVAL_MS = 120; export function createLaunchHover({ viewer, enabled, - entityLaunchId, + launchAt, now = () => performance.now(), documentRef = globalThis.document, pointerFree = isPointerFree, @@ -58,10 +59,7 @@ export function createLaunchHover({ pointerFree(); const pick = (position, at) => { lastPick = at; - const found = viewer.scene - .drillPick(position, 12) - .some((picked) => entityLaunchId(picked?.id)); - if (found) { + if (launchAt(position)) { viewer.scene.canvas.style.cursor = 'pointer'; ownsCursor = true; } else clearCursor(); @@ -78,8 +76,9 @@ export function createLaunchHover({ } pick(position, now()); }; - const removeStart = viewer.camera?.moveStart?.addEventListener(start); - const removeEnd = viewer.camera?.moveEnd?.addEventListener(end); + const camera = findCamera(viewer); + const removeStart = camera?.on('moveStart', start); + const removeEnd = camera?.on('moveEnd', end); documentRef?.addEventListener?.('visibilitychange', visibility); return { move(movement) { @@ -139,12 +138,8 @@ export function createLifecycle({ parts.overlays.clearMissionOverlaySources(); const input = inputFor(viewer); const unsubscribeClick = input.onClick((event) => { - if (!layerState._enabled || !layerState._dataSource?.show) return; - const entity = event - .drill(12) - .map((picked) => picked?.id) - .find((candidate) => parts.selection.entityLaunchId(candidate)); - const launchId = parts.selection.entityLaunchId(entity); + if (!layerState._enabled || !parts.rendering.missionsShown()) return; + const launchId = parts.rendering.launchIdFromPicks(event.drill(12)); if (!launchId) return; parts.selection.setSelectedMission(launchId); parts.selection.focusMission( @@ -153,8 +148,8 @@ export function createLifecycle({ }); hover = createLaunchHover({ viewer, - enabled: () => layerState._enabled && layerState._dataSource?.show, - entityLaunchId: parts.selection.entityLaunchId, + enabled: () => layerState._enabled && parts.rendering.missionsShown(), + launchAt: parts.rendering.launchMarkerAt, }); const unsubscribeHover = input.onPointer('move', hover.move); layerState._inputSubscription = () => { @@ -164,9 +159,10 @@ export function createLifecycle({ // Apply horizon visibility before Cesium traverses and picks the scene. // 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 = viewer.scene.preRender.addEventListener( - parts.rendering.updateMissionFrame, - ); + layerState._declutterHandler = + findFrame(viewer)?.on('preRender', () => + parts.rendering.updateMissionFrame(), + ) ?? null; parts.launchPad.initLaunchPadZonePrimitive(); }, @@ -194,7 +190,7 @@ export function createLifecycle({ async _enableBody() { layerState._updateDirty = false; - if (layerState._dataSource) layerState._dataSource.show = true; + parts.rendering.showMissions(true); parts.orbitRendering.syncMissionOrbitPrimitiveVisibility(); parts.selection.focusFullGlobe(layerState._viewer); if (layerState._selectedLaunchId) @@ -217,7 +213,7 @@ export function createLifecycle({ parts.panel.clearMissionRosterHover(); parts.replay.stopMissionReplay(); parts.selection.stopMissionZoomAnchor(); - if (layerState._dataSource) layerState._dataSource.show = false; + parts.rendering.showMissions(false); parts.orbitRendering.syncMissionOrbitPrimitiveVisibility(); if (layerState._viewer?.scene?.canvas) layerState._viewer.scene.canvas.style.cursor = ''; diff --git a/src/layers/launches/overlays.js b/src/layers/launches/overlays.js index 9bd77ea47..1e66c467d 100644 --- a/src/layers/launches/overlays.js +++ b/src/layers/launches/overlays.js @@ -352,7 +352,7 @@ export function createOverlays({ state: layerState, services, parts, source }) { } function syncMissionOverlayEntries() { - if (!layerState._enabled || !layerState._dataSource?.show) { + if (!layerState._enabled || !parts.rendering.missionsShown()) { clearMissionOverlaySources(); return; } diff --git a/src/layers/launches/rendering.js b/src/layers/launches/rendering.js index 9a6d10f63..2b1d2cce8 100644 --- a/src/layers/launches/rendering.js +++ b/src/layers/launches/rendering.js @@ -55,6 +55,46 @@ export function createRendering({ layerState._dataSource = null; } + /** Whether the missions' entities are shown. */ + function missionsShown() { + return Boolean(layerState._dataSource?.show); + } + + /** Show or hide the missions' entities. */ + function showMissions(shown) { + if (layerState._dataSource) layerState._dataSource.show = shown; + } + + /** Remove every mission entity, ahead of a rebuild. */ + function clearLaunchEntities() { + layerState._dataSource?.entities.removeAll(); + } + + /** 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; + } + + /** 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); + 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)); + } + /** Make a launch's site marker the viewer's selected entity, or none. */ function selectLaunchEntity(launchId) { const viewer = layerState._viewer; @@ -71,7 +111,7 @@ export function createRendering({ function isolateMission(launchId) { if (!layerState._dataSource) return; for (const entity of layerState._dataSource.entities.values) { - const relatedId = parts.selection.entityLaunchId(entity); + const relatedId = entityLaunchId(entity); entity.show = launchId ? relatedId === launchId : entity.id.startsWith('rocket-launch:'); @@ -103,7 +143,7 @@ export function createRendering({ for (const entity of layerState._dataSource.entities.values) { if (!entity.show) continue; if (!entity.position) continue; - const id = parts.selection.entityLaunchId(entity); + const id = entityLaunchId(entity); if (!id) continue; const position = entity.position.getValue(time); let horizonVisible = Boolean( @@ -646,6 +686,11 @@ export function createRendering({ return { attach, detach, + missionsShown, + showMissions, + clearLaunchEntities, + launchIdFromPicks, + launchMarkerAt, setGraphicVisibility, selectLaunchEntity, isolateMission, diff --git a/src/layers/launches/replay.js b/src/layers/launches/replay.js index 57805edd7..a0e134ea1 100644 --- a/src/layers/launches/replay.js +++ b/src/layers/launches/replay.js @@ -2,7 +2,7 @@ import { stopFollowing } from '../../data/followed.js'; import { toCartographicRadians } from '../../geo/ellipsoid.js'; import { clamp, distance, toRadians } from '../../geo/vector.js'; import { t } from '../../i18n/index.js'; -import { cameraOf, findCamera } from '../../render/rendererOf.js'; +import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js'; import { lerp } from './geometry.js'; import { REPLAY_ASCENT_FALLBACK_SEC, @@ -329,7 +329,9 @@ export function createReplay({ state: layerState, services, parts, source }) { function startMissionReplay(launchId) { const launch = layerState._launches.find((item) => item.id === launchId); const track = layerState._replayTracks.get(launchId); - if (!layerState._viewer || !launch || !track) return false; + // The chase camera moves on the frame loop; without one, no replay. + const frame = findFrame(layerState._viewer); + if (!layerState._viewer || !launch || !track || !frame) return false; if (layerState._replayCameraLaunchId === launchId) { stopMissionReplay(); return false; @@ -366,122 +368,112 @@ export function createReplay({ state: layerState, services, parts, source }) { // Move the chase camera before scene traversal. Mutating it in preRender // makes Cesium discover a new view after 3D-tile refinement, which can cause // a self-sustaining refinement loop and visible stutter during slow replay. - layerState._replayCameraRemover = - layerState._viewer.scene.preUpdate.addEventListener(() => { - if ( - token !== layerState._replayCameraToken || - layerState._replayCameraLaunchId !== launchId - ) - return; - const state = track.beginReplayFrame(); - // Asked for each frame, not kept: a renderer bound meanwhile - // replaces the port. - const chaseCamera = cameraOf(layerState._viewer); - syncReplayCountdownButton(state); - if (!cameraReady) return; - const path = state.ascending - ? track.ascentPath - : track.animatedOrbitPath; - const position = parts.paths.samplePath(path, state.phaseProgress); - if (!position) return; - const pathHeading = parts.camera.cameraHeadingForPath( - path, - state.phaseProgress, - track.lastCameraHeading, - ); - const orbitBlend = !state.ascending - ? clamp( - (Number(state.phaseProgress) || 0) / - REPLAY_ORBIT_PULLBACK_FRACTION, - 0, - 1, - ) - : 0; - const desiredHeading = parts.camera.replayChaseCameraHeading( - pathHeading, - orbitBlend, - ); - if (state.ascending) track.orbitCameraWorldFrame = false; - const nowMs = performance.now(); - const frameDurationMs = Number.isFinite(lastCameraUpdateMs) - ? clamp(nowMs - lastCameraUpdateMs, 4, 50) - : 1000 / 60; - lastCameraUpdateMs = nowMs; - track.lastCameraHeading = parts.camera.smoothReplayCameraHeading( - track.lastCameraHeading, - desiredHeading, - (toRadians(2) * frameDurationMs) / (1000 / 60), - ); - const cartographic = toCartographicRadians(position); - const altitude = Math.max(0, cartographic?.height || 0); - const cameraView = parts.camera.replayCameraView(state, altitude); - const defaultOrbitTarget = !state.ascending - ? parts.camera.replayOrbitGlobeAnchor(position, orbitBlend) - : position; - const cameraTarget = !state.ascending - ? parts.camera.replayOrbitCameraTarget( - defaultOrbitTarget, - track.orbitFrameSphere?.center, - orbitBlend, - ) - : defaultOrbitTarget; - const cameraRange = !state.ascending - ? parts.camera.replayOrbitGlobeRange( - cameraView.range, - altitude, - orbitBlend, - track.orbitFrameSphere?.radius, - ) - : cameraView.range; - if (state.ascending) { - chaseCamera.lookAt(cameraTarget, { - heading: track.lastCameraHeading, - pitch: cameraView.pitch, - range: cameraRange, - }); - } else { - const tangentStep = Math.max( - 0.002, - 0.8 / Math.max(2, path.length - 1), - ); - const tangentProgress = Math.min( + layerState._replayCameraRemover = frame.on('preUpdate', () => { + if ( + token !== layerState._replayCameraToken || + layerState._replayCameraLaunchId !== launchId + ) + return; + const state = track.beginReplayFrame(); + // Asked for each frame, not kept: a renderer bound meanwhile + // replaces the port. + const chaseCamera = cameraOf(layerState._viewer); + syncReplayCountdownButton(state); + if (!cameraReady) return; + const path = state.ascending ? track.ascentPath : track.animatedOrbitPath; + const position = parts.paths.samplePath(path, state.phaseProgress); + if (!position) return; + const pathHeading = parts.camera.cameraHeadingForPath( + path, + state.phaseProgress, + track.lastCameraHeading, + ); + const orbitBlend = !state.ascending + ? clamp( + (Number(state.phaseProgress) || 0) / REPLAY_ORBIT_PULLBACK_FRACTION, + 0, 1, - state.phaseProgress + tangentStep, - ); - const tangentPosition = parts.paths.samplePath( - path, - tangentProgress > state.phaseProgress - ? tangentProgress - : Math.max(0, state.phaseProgress - tangentStep), - ); - const orbitPose = parts.camera.replayOrbitCameraPose( - position, - tangentPosition, - cameraTarget, - cameraRange, - cameraView.pitch, - ); - if (orbitPose) { - if (!track.orbitCameraWorldFrame) { - chaseCamera.release(); - track.orbitCameraWorldFrame = true; - } - chaseCamera.setView({ - destination: orbitPose.destination, - orientation: { - direction: orbitPose.direction, - up: orbitPose.up, - }, - }); + ) + : 0; + const desiredHeading = parts.camera.replayChaseCameraHeading( + pathHeading, + orbitBlend, + ); + if (state.ascending) track.orbitCameraWorldFrame = false; + const nowMs = performance.now(); + const frameDurationMs = Number.isFinite(lastCameraUpdateMs) + ? clamp(nowMs - lastCameraUpdateMs, 4, 50) + : 1000 / 60; + lastCameraUpdateMs = nowMs; + track.lastCameraHeading = parts.camera.smoothReplayCameraHeading( + track.lastCameraHeading, + desiredHeading, + (toRadians(2) * frameDurationMs) / (1000 / 60), + ); + const cartographic = toCartographicRadians(position); + const altitude = Math.max(0, cartographic?.height || 0); + const cameraView = parts.camera.replayCameraView(state, altitude); + const defaultOrbitTarget = !state.ascending + ? parts.camera.replayOrbitGlobeAnchor(position, orbitBlend) + : position; + const cameraTarget = !state.ascending + ? parts.camera.replayOrbitCameraTarget( + defaultOrbitTarget, + track.orbitFrameSphere?.center, + orbitBlend, + ) + : defaultOrbitTarget; + const cameraRange = !state.ascending + ? parts.camera.replayOrbitGlobeRange( + cameraView.range, + altitude, + orbitBlend, + track.orbitFrameSphere?.radius, + ) + : cameraView.range; + if (state.ascending) { + chaseCamera.lookAt(cameraTarget, { + heading: track.lastCameraHeading, + pitch: cameraView.pitch, + range: cameraRange, + }); + } else { + const tangentStep = Math.max(0.002, 0.8 / Math.max(2, path.length - 1)); + const tangentProgress = Math.min(1, state.phaseProgress + tangentStep); + const tangentPosition = parts.paths.samplePath( + path, + tangentProgress > state.phaseProgress + ? tangentProgress + : Math.max(0, state.phaseProgress - tangentStep), + ); + const orbitPose = parts.camera.replayOrbitCameraPose( + position, + tangentPosition, + cameraTarget, + cameraRange, + cameraView.pitch, + ); + if (orbitPose) { + if (!track.orbitCameraWorldFrame) { + chaseCamera.release(); + track.orbitCameraWorldFrame = true; } + chaseCamera.setView({ + destination: orbitPose.destination, + orientation: { + direction: orbitPose.direction, + up: orbitPose.up, + }, + }); } - if ( - state.elapsedSinceStart >= - ascentDurationSec + REPLAY_ORBIT_DURATION_SEC - ) { - stopMissionReplay(); - } - }); + } + if ( + state.elapsedSinceStart >= + ascentDurationSec + REPLAY_ORBIT_DURATION_SEC + ) { + stopMissionReplay(); + } + }); camera.flyToBounds( { center: track.ascentPath[0], radius: 0 }, diff --git a/src/layers/launches/selection.js b/src/layers/launches/selection.js index c3cef876b..ae4267c62 100644 --- a/src/layers/launches/selection.js +++ b/src/layers/launches/selection.js @@ -60,12 +60,6 @@ export function createSelection({ ); } - function entityLaunchId(entity) { - if (!entity?.id || typeof entity.id !== 'string') return null; - const match = entity.id.match(/^rocket-[^:]+:([^:]+)/); - return match?.[1] || null; - } - function setSelectedMission(launchId, isolate = true) { if (launchId) parts.panel.clearMissionRosterHover(); if ( @@ -187,7 +181,6 @@ export function createSelection({ } return { focusFullGlobe, - entityLaunchId, setSelectedMission, stopMissionZoomAnchor, startMissionZoomAnchor,