diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index c43731616..ee95f4f89 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1073,6 +1073,10 @@ fresh core rebuild or lifecycle reset replaces the corresponding ownership. Source adapters retain the existing CelesTrak and Launch Library endpoints; standalone entries provide scene services and the satellite dependency. The mission factory separates paths, replay, camera, panel, overlays and placement. +Its markers, lines, live rings and pad zone are renderer draw sets, and it +follows a mission through the camera port, so a caller handing it a Cesium +viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Launch Library pad coordinates retain unknown values: missing fields use the reported location coordinates when available, and launches without a known pad position stay off the map. Genuine zero coordinates remain valid. Undisclosed diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 6cf1247a2..5a2c7f644 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -51,6 +51,14 @@ optional, so a renderer written before it still conforms: on a ground primitive of its own. A renderer that predates it draws the rectangle unturned. +The Cesium port also draws `pattern` line styles (the image repeated +`repeat` times along the line, in the translucent pass), lines in the +`inertial` frame (turned each frame by the set's motion clock; never draped +and never batched), and `radialRim` fills on clamped ellipses (`rimWidth` a +fraction of the radius; `depthBias` pulls the fill toward the eye). A hidden +line that cannot settle into a static batch leaves its polyline collection +until it shows again, since the collection draws every line it holds. + The renderer itself (`renderer.d.ts`) adds capture, pixel reads, settling, resize, context loss and `destroy`. `common.d.ts` holds the shared shapes (ECEF positions, colours, listener semantics) and the capability list. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 981ebe787..da7df1827 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -8,6 +8,7 @@ "modules": [ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", + "src/data/stockFollow.js", "src/data/geojsonPins.js", "src/render/cesium/heights.js", "src/render/cesium/camera.js", @@ -2103,6 +2104,7 @@ "src/layers/launches/ingestion.js", "src/layers/launches/launchPad.js", "src/layers/launches/lifecycle.js", + "src/data/stockFollow.js", "src/layers/launches/model.js", "src/render/color.js", "src/geo/index.js", @@ -3318,6 +3320,7 @@ "src/data/layerStateTokenReservations.json", "src/data/lifecycle.js", "src/data/localGeojsonCore.js", + "src/data/stockFollow.js", "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", @@ -4304,6 +4307,7 @@ "src/data/layerState.js", "src/data/layerStateTokenReservations.json", "src/data/localGeojsonCore.js", + "src/data/stockFollow.js", "src/data/geojsonPins.js", "src/data/localGeojsonLod.js", "src/data/local_data/natural_earth/marine.json", diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index be8e196f1..8c2a4ec4c 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -224,6 +224,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'scenePick.js', 'sensorPick.js', 'sphere.js', + 'stockFollow.js', 'styleStages.js', 'vector.js', ]); diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js index e55a87bfc..4b74eee10 100644 --- a/src/data/localGeojsonCore.js +++ b/src/data/localGeojsonCore.js @@ -8,13 +8,7 @@ import { findQuery, } from '../render/rendererOf.js'; import { cssColor } from '../render/color.js'; -import { - WGS84, - fromDegrees, - fromDegreesInto, - toLonLatH, -} from '../geo/ellipsoid.js'; -import { offsetFromHeadingPitchRange } from '../geo/frames.js'; +import { fromDegrees, fromDegreesInto, toLonLatH } from '../geo/ellipsoid.js'; import { sphereFromPoints } from '../geo/sphere.js'; import { densifyRhumb } from '../geo/rhumb.js'; import { heightsOf } from '../queries/heights.js'; @@ -25,6 +19,7 @@ import { } from '../sources/infrastructureData.js'; import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js'; import { createGeojsonPins } from './geojsonPins.js'; +import { followViewFrom } from './stockFollow.js'; import { inputFor as defaultInputFor } from '../input/dispatcher.js'; import { selectInfraLod, @@ -321,34 +316,6 @@ const STEM_WIDTH_PX = 3.5; const PIN_SIZE_PX = 8; const BLACK = Object.freeze([0, 0, 0, 1]); -/** The range the default renderer frames a sphere of no size from. */ -const MINIMUM_FIT_RANGE_M = 100; - -/** - * Where the camera frames a part it starts following, as the default - * renderer framed an entity it started following with no view of its own: - * looking at the bounds' centre, heading north, pitched down 45° (steeper - * far from the ground), at the range that fits the bounds in view, within - * the camera's zoom limits. Returned as the eye's offset from the centre, - * east-north-up there; `at` is where the part stands. - */ -function followViewFrom(sphere, at, camera) { - const pose = camera.pose?.(); - const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3; - const aspect = Number.isFinite(pose?.aspectRatio) ? pose.aspectRatio : 1; - const tanPhi = Math.tan(fovy / 2); - const tanTheta = aspect * tanPhi; - let range = - sphere.radius === 0 - ? MINIMUM_FIT_RANGE_M - : Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi); - const { minDistance = 0, maxDistance = Infinity } = camera.controls ?? {}; - range = Math.min(Math.max(range, minDistance), maxDistance); - const factor = - 2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x); - return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range); -} - /** The GeoJSON loader's `marker-size` names, in pixels. */ const MARKER_SIZES = Object.freeze({ small: 24, medium: 48, large: 64 }); /** diff --git a/src/data/rocketLaunches.test.mjs b/src/data/rocketLaunches.test.mjs index 3ca9e8662..c92406749 100644 --- a/src/data/rocketLaunches.test.mjs +++ b/src/data/rocketLaunches.test.mjs @@ -1,7 +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 { fromDegrees } from '../geo/ellipsoid.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs'; import { gstime } from 'satellite.js'; import { createModel } from '../layers/launches/model.js'; @@ -1159,37 +1160,34 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths removeEventListener(type) { listeners.delete(`document:${type}`); }, }; const canvas = new FakeElement('canvas'); - const dataSources = []; - const camera = { - positionCartographic: null, - positionWC: Cesium.Cartesian3.fromDegrees(-80.604, 28.608, 18_000_000), - cancelFlight() {}, - lookAtTransform() {}, - }; + let eye = fromDegrees(-80.604, 28.608, 18_000_000); const scene = { canvas, - camera, - frameState: { frameNumber: 1 }, postRender: new Cesium.Event(), preRender: new Cesium.Event(), preUpdate: new Cesium.Event(), - primitives: { add: (primitive) => primitive, remove: () => true }, - drillPick: () => [], }; - const viewer = { - camera, - scene, - dataSources: { - add(dataSource) { dataSources.push(dataSource); return dataSource; }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, + const viewer = { scene }; + const { draw } = bindFakeDraw(viewer, { + frame: fakeSceneFrame(viewer), + camera: { + // No pose to fly from: the full-globe framing on enable stays put. + pose: () => ({ lon: Number.NaN, lat: Number.NaN, height: 18_000_000, position: eye, fovy: Number.NaN }), + on: () => () => {}, + release() {}, + cancelFlight() {}, }, - selectedEntity: undefined, + query: { drillPick: () => [] }, + }); + // The mission sets' items by id, across the layer's draw sets. + const missionItems = () => { + const items = new Map(); + for (const record of draw.sets.values()) + if (!record.disposed && /:(lines|sites|markers)$/.test(record.spec.id)) + for (const [id, item] of record.items) items.set(id, item); + return items; }; - bindRenderer(viewer, { frame: fakeSceneFrame(viewer) }); + const item = (id) => missionItems().get(id); const hostCalls = []; const host = { setEntries: (...args) => hostCalls.push(['entries', ...args]), @@ -1245,9 +1243,10 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths await rocketLaunchesLayer.enable(); await rocketLaunchesLayer.update(); - const entities = dataSources[0].entities.values; - assert.ok(entities.length >= 7, 'runtime guard requires the populated mission build path'); - assert.ok(entities.every((entity) => entity.label === undefined)); + assert.ok(missionItems().size >= 7, 'runtime guard requires the populated mission build path'); + // Every set is a kind with no world text: labels are the host's. + const kinds = new Set(['lines', 'points', 'icons', 'shapes']); + assert.ok([...draw.sets.values()].every((record) => kinds.has(record.kind))); const ambientPublication = hostCalls.findLast(([type, sourceId]) => ( type === 'entries' && sourceId === ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID )); @@ -1259,26 +1258,25 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths collisionCapacity: ROCKET_MISSION_AMBIENT_OVERLAY_COLLISION_CAPACITY, moving: false, }); - const launchEntity = dataSources[0].entities.getById('rocket-launch:mission-runtime'); - assert.deepEqual( + assert.equal( ambientPublication[2][0].position, - launchEntity.position.getValue(Cesium.JulianDate.now()), - 'ambient host marker must reuse the entity anchor Cartesian', + item('rocket-launch:mission-runtime').pos, + 'ambient host marker must reuse the site marker anchor', ); const frameTime = Cesium.JulianDate.now(); scene.preRender.raiseEvent(scene, frameTime); - assert.equal(launchEntity.point.show.getValue(frameTime), true); - camera.positionWC = Cesium.Cartesian3.fromDegrees(99.396, -28.608, 18_000_000); + assert.equal(item('rocket-launch:mission-runtime').show, true); + eye = fromDegrees(99.396, -28.608, 18_000_000); scene.preRender.raiseEvent(scene, frameTime); assert.equal( - launchEntity.point.show.getValue(frameTime), + item('rocket-launch:mission-runtime').show, false, 'pre-render horizon pass must hide a rear-side depth-free mission dot before draw and pick', ); - camera.positionWC = Cesium.Cartesian3.fromDegrees(-80.604, 28.608, 18_000_000); + eye = fromDegrees(-80.604, 28.608, 18_000_000); scene.preRender.raiseEvent(scene, frameTime); assert.equal( - launchEntity.point.show.getValue(frameTime), + item('rocket-launch:mission-runtime').show, true, 'mission dot must return when its surface anchor faces the camera again', ); @@ -1304,17 +1302,16 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths && entry.paintLane === 'selected' && entry.edgeFade === 'keyhole' ))); - const satelliteEntity = dataSources[0].entities.getById('rocket-satellite:mission-runtime'); - const satellitePosition = satelliteEntity.position.getValue(Cesium.JulianDate.now()); - assert.equal( + scene.preRender.raiseEvent(scene, frameTime); + assert.deepEqual( selectedPublication[2][2].position(), - satellitePosition, - 'payload host getter must return the exact per-frame live-position cache', + item('rocket-satellite:mission-runtime').pos, + 'payload host getter must return where the frame drew the payload', ); - // Jitter regression net: live-state propagation advances at most once per - // frameNumber, and the host getter is a pure read that never advances it. - // Without both halves, the host label and the native dot can propagate to + // Jitter regression net: live-state propagation advances at most once a + // frame, and the host getter is a pure read that never advances it. + // Without both halves, the host label and the drawn dot can propagate to // different wall-clock instants inside one frame — the documented // label-separation jitter class. const payloadEntry = selectedPublication[2][2]; @@ -1322,52 +1319,40 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths try { let nowMs = realDateNow(); Date.now = () => nowMs; - scene.frameState.frameNumber = 41; - const frameA = Cesium.Cartesian3.clone( - satelliteEntity.position.getValue(Cesium.JulianDate.now()), - ); + scene.preRender.raiseEvent(scene, frameTime); + const frameA = { ...item('rocket-satellite:mission-runtime').pos }; + assert.deepEqual({ ...payloadEntry.position() }, frameA); nowMs += 30_000; assert.deepEqual( - Cesium.Cartesian3.clone(satelliteEntity.position.getValue(Cesium.JulianDate.now())), + { ...payloadEntry.position() }, frameA, - 'a second native read in the same frame must not re-propagate', + 'host getter must not advance propagation between frames', ); - nowMs += 30_000; - scene.frameState.frameNumber = 42; + scene.preRender.raiseEvent(scene, frameTime); + const frameB = { ...item('rocket-satellite:mission-runtime').pos }; + assert.notDeepEqual(frameB, frameA, 'a new frame propagates (non-vacuous)'); assert.deepEqual( - Cesium.Cartesian3.clone(payloadEntry.position()), - frameA, - 'host getter must not advance propagation, even on a new frame', - ); - const frameB = Cesium.Cartesian3.clone( - satelliteEntity.position.getValue(Cesium.JulianDate.now()), - ); - assert.notDeepEqual(frameB, frameA, 'native read on a new frame propagates (non-vacuous)'); - assert.deepEqual( - Cesium.Cartesian3.clone(payloadEntry.position()), + { ...payloadEntry.position() }, frameB, - 'host getter reads the advanced cache after native propagation', + 'host getter reads the advanced cache after the frame drew it', ); } finally { Date.now = realDateNow; - scene.frameState.frameNumber = 1; } - const reentryEntity = dataSources[0].entities.getById('rocket-reentry:mission-runtime:0'); assert.deepEqual( selectedPublication[2][1].position, - reentryEntity.polyline.positions.getValue(Cesium.JulianDate.now())[0], - 're-entry host label must reuse the recovery-path interface Cartesian', + item('rocket-reentry:mission-runtime:0').positions[0], + 're-entry host label must reuse the recovery-path interface point', ); - const transferEntity = dataSources[0].entities.getById('rocket-transfer:mission-runtime'); assert.deepEqual( selectedPublication[2][3].position, - transferEntity.polyline.positions.getValue(Cesium.JulianDate.now()).at(-1), - 'orbit host label must reuse the insertion Cartesian', + item('rocket-transfer:mission-runtime').positions.at(-1), + 'orbit host label must reuse the insertion point', ); launchName = 'Mission Refresh | Gauntlet Payload'; await rocketLaunchesLayer.update(); - assert.ok(dataSources[0].entities.values.every((entity) => entity.label === undefined)); + assert.ok(missionItems().size >= 7); const refreshPublication = hostCalls.findLast(([type, sourceId]) => ( type === 'entries' && sourceId === ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID )); @@ -1390,7 +1375,7 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths ]); await rocketLaunchesLayer.destroy(viewer); initialized = false; - assert.equal(dataSources.length, 0); + assert.ok([...draw.sets.values()].every((record) => record.disposed)); assert.deepEqual(hostCalls.slice(-4), [ ['clear', ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID], ['visible', ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID, false], diff --git a/src/data/stockFollow.js b/src/data/stockFollow.js new file mode 100644 index 000000000..5791dc092 --- /dev/null +++ b/src/data/stockFollow.js @@ -0,0 +1,127 @@ +/** + * @module data/stockFollow + * @description A double-click on a layer's drawn item follows it, as the + * default renderer's own double-click followed the entities layers drew + * before they drew through the draw port: an item with a position is + * followed, framed as that renderer framed an entity it started following; + * one without (a line) is zoomed to at once instead. It runs only while the + * renderer's own double-click follow is on (a tool can hold it off). + */ +import { WGS84 } from '../geo/ellipsoid.js'; +import { offsetFromHeadingPitchRange } from '../geo/frames.js'; +import { findCamera, findQuery } from '../render/rendererOf.js'; + +/** The range the default renderer frames a sphere of no size from. */ +const MINIMUM_FIT_RANGE_M = 100; + +/** + * Where the camera frames a part it starts following, as the default + * renderer framed an entity it started following with no view of its own: + * looking at the bounds' centre, heading north, pitched down 45° (steeper + * far from the ground), at the range that fits the bounds in view, within + * the camera's zoom limits. Returned as the eye's offset from the centre, + * east-north-up there; `at` is where the part stands. + * @param {{center: {x: number, y: number, z: number}, radius: number}} sphere + * @param {{x: number, y: number, z: number}} at + * @param {object} camera The camera port. + */ +export function followViewFrom(sphere, at, camera) { + const pose = camera.pose?.(); + const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3; + const aspect = Number.isFinite(pose?.aspectRatio) ? pose.aspectRatio : 1; + const tanPhi = Math.tan(fovy / 2); + const tanTheta = aspect * tanPhi; + let range = + sphere.radius === 0 + ? MINIMUM_FIT_RANGE_M + : Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi); + const { minDistance = 0, maxDistance = Infinity } = camera.controls ?? {}; + range = Math.min(Math.max(range, minDistance), maxDistance); + const factor = + 2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x); + return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range); +} + +/** + * Follow (or zoom to) a layer's item on a double-click. + * @param {object} options + * @param {object} options.viewer + * @param {(viewer: object) => object} options.inputFor The click dispatcher. + * @param {string} options.name The layer, for warnings. + * @param {() => boolean} options.enabled Whether the layer takes clicks now. + * @param {(hit: import('../render/contract/query').Hit) => + * ({key: string, position: () => ({x: number, y: number, z: number}|null), + * sphere?: {center: object, radius: number}} + * | {zoomTo: {center: object, radius: number}} + * | null)} options.targetFor What a hit on one of the layer's items is + * followed by (`key`, its live `position`, the bounds it is framed by, + * radius 0 by default), or zoomed to (`zoomTo`); null for anything else. + * @returns {{readonly following: object|null, stop(): void, destroy(): void}} + */ +export function followOnDoubleClick({ + viewer, + inputFor, + name, + enabled, + targetFor, +}) { + const input = inputFor(viewer); + /** The follow a double-click started, while the camera keeps it. */ + let follow = null; + const off = + input.onPointer?.('dblclick', (event) => { + if (!enabled()) return; + // The renderer's own double-click follow, off while a tool holds it + // or on a renderer without one. + if (input.stockEnabled?.('dblclickFollow') !== true) return; + const hit = findQuery(viewer)?.pick(event.position.x, event.position.y); + const found = hit && !hit.surface ? targetFor(hit) : null; + if (!found) return; + const camera = findCamera(viewer); + if (!camera) return; + try { + if (found.zoomTo) { + // As the default renderer zoomed to an entity with no position: + // at once, north up, pitched down 45°, at the range that fits it + // in view. Following nothing then, as that zoom stopped any + // follow first. + if (camera.followed) camera.follow(null); + camera.flyToBounds(found.zoomTo, { durationS: 0 }); + return; + } + const at = found.position(); + if (!at) return; + const target = { + key: found.key, + position: found.position, + frame: 'enu', + viewFrom: followViewFrom( + found.sphere ?? { center: at, radius: 0 }, + at, + camera, + ), + }; + camera.follow(target); + follow = target; + } catch (error) { + // A camera that cannot follow leaves the view where it is, as a + // viewer without entity tracking did. + console.warn(`${name}: cannot follow`, error); + } + }) ?? null; + return { + get following() { + return follow && findCamera(viewer)?.followed === follow ? follow : null; + }, + /** Stop a follow this started, if the camera still keeps it. */ + stop() { + const camera = findCamera(viewer); + if (follow && camera?.followed === follow) camera.follow(null); + follow = null; + }, + destroy() { + this.stop(); + off?.(); + }, + }; +} diff --git a/src/data/stockFollow.test.mjs b/src/data/stockFollow.test.mjs new file mode 100644 index 000000000..ccc1f986f --- /dev/null +++ b/src/data/stockFollow.test.mjs @@ -0,0 +1,119 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { followOnDoubleClick, followViewFrom } from './stockFollow.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { WGS84 } from '../geo/ellipsoid.js'; + +/** A viewer whose renderer answers picks with `hit` and records the camera. */ +function scene({ hit, stock = true, enabled = true }) { + const viewer = {}; + const handlers = new Map(); + const calls = []; + const camera = { + followed: null, + controls: { minDistance: 0, maxDistance: Infinity }, + pose: () => ({ fovy: Math.PI / 3, aspectRatio: 2 }), + follow(target) { + calls.push(['follow', target]); + camera.followed = target; + }, + flyToBounds(sphere, options) { + calls.push(['flyToBounds', sphere, options]); + }, + }; + const unbind = bindRenderer(viewer, { + camera, + query: { pick: () => hit }, + }); + const input = { + onPointer(type, handler) { + handlers.set(type, handler); + return () => handlers.delete(type); + }, + stockEnabled: (name) => name === 'dblclickFollow' && stock, + }; + const at = { x: WGS84.radii.x, y: 0, z: 0 }; + const follow = followOnDoubleClick({ + viewer, + inputFor: () => input, + name: 'test-layer', + enabled: () => enabled, + targetFor: (picked) => + picked.id === 'point' + ? { key: 'layer:point', position: () => at } + : picked.id === 'line' + ? { zoomTo: { center: at, radius: 50 } } + : null, + }); + const dblclick = () => + handlers.get('dblclick')?.({ position: { x: 1, y: 2 } }); + return { follow, camera, calls, dblclick, handlers, unbind }; +} + +test('a double-click follows a point, framed as the default renderer framed an entity', () => { + const s = scene({ hit: { set: 'layer', id: 'point', surface: false } }); + s.dblclick(); + const [[kind, target]] = s.calls; + assert.equal(kind, 'follow'); + assert.equal(target.key, 'layer:point'); + assert.equal(target.frame, 'enu'); + // No size: the minimum fit range, 45 degrees down on the ground. + const range = Math.hypot( + target.viewFrom.x, + target.viewFrom.y, + target.viewFrom.z, + ); + assert.ok(Math.abs(range - 100) < 1e-6); + assert.ok(Math.abs(target.viewFrom.z + target.viewFrom.y) < 1e-6); + assert.equal(s.follow.following, target); + // Stopping ends only the follow it started. + s.follow.stop(); + assert.equal(s.camera.followed, null); + s.follow.destroy(); + assert.equal(s.handlers.size, 0); + s.unbind(); +}); + +test('a double-click on a line zooms to it at once, following nothing', () => { + const s = scene({ hit: { set: 'layer', id: 'line', surface: false } }); + s.camera.followed = { key: 'other' }; + s.dblclick(); + assert.deepEqual( + s.calls.map(([kind]) => kind), + ['follow', 'flyToBounds'], + ); + assert.equal(s.calls[0][1], null); + assert.deepEqual(s.calls[1][2], { durationS: 0 }); + s.follow.destroy(); + s.unbind(); +}); + +test('no follow while the stock double-click is held off, the layer is off, or the pick is not its own', () => { + for (const options of [ + { hit: { id: 'point', surface: false }, stock: false }, + { hit: { id: 'point', surface: false }, enabled: false }, + { hit: { id: 'other', surface: false } }, + { hit: { surface: true } }, + { hit: null }, + ]) { + const s = scene(options); + s.dblclick(); + assert.deepEqual(s.calls, []); + s.follow.destroy(); + s.unbind(); + } +}); + +test('the frame view fits a sphere and steepens far from the ground', () => { + const camera = { pose: () => ({ fovy: Math.PI / 2, aspectRatio: 1 }) }; + const ground = { x: WGS84.radii.x, y: 0, z: 0 }; + const near = followViewFrom({ center: ground, radius: 1000 }, ground, camera); + assert.ok(Math.abs(Math.hypot(near.x, near.y, near.z) - 1000) < 1e-6); + const high = { x: WGS84.radii.x * 2, y: 0, z: 0 }; + const far = followViewFrom({ center: high, radius: 0 }, high, camera); + // Looking down 45 degrees times 1.5 at twice the radius: the eye that + // far above, south of the point. + const elevation = Math.atan2(far.z, Math.hypot(far.x, far.y)); + assert.ok(Math.abs(elevation - (Math.PI / 4) * 1.5) < 1e-9); + assert.ok(far.y < 0); +}); diff --git a/src/layers/launches/hover.test.mjs b/src/layers/launches/hover.test.mjs index 6cfe42b2d..a1dd944b2 100644 --- a/src/layers/launches/hover.test.mjs +++ b/src/layers/launches/hover.test.mjs @@ -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(); }); diff --git a/src/layers/launches/ingestion.js b/src/layers/launches/ingestion.js index 57a06e3c5..5d8e895ab 100644 --- a/src/layers/launches/ingestion.js +++ b/src/layers/launches/ingestion.js @@ -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(); diff --git a/src/layers/launches/ingestion.test.mjs b/src/layers/launches/ingestion.test.mjs index c991eae22..02824cd01 100644 --- a/src/layers/launches/ingestion.test.mjs +++ b/src/layers/launches/ingestion.test.mjs @@ -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(); diff --git a/src/layers/launches/launchPad.js b/src/layers/launches/launchPad.js index f0a87ce6a..1ccbf20fe 100644 --- a/src/layers/launches/launchPad.js +++ b/src/layers/launches/launchPad.js @@ -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, }; } diff --git a/src/layers/launches/lifecycle.js b/src/layers/launches/lifecycle.js index ad1ecde76..c863ba8ec 100644 --- a/src/layers/launches/lifecycle.js +++ b/src/layers/launches/lifecycle.js @@ -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; diff --git a/src/layers/launches/orbitRendering.js b/src/layers/launches/orbitRendering.js index d907904eb..04fe18963 100644 --- a/src/layers/launches/orbitRendering.js +++ b/src/layers/launches/orbitRendering.js @@ -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, }; } diff --git a/src/layers/launches/panel.js b/src/layers/launches/panel.js index 7b278cbbd..ac746d4d7 100644 --- a/src/layers/launches/panel.js +++ b/src/layers/launches/panel.js @@ -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(); diff --git a/src/layers/launches/rendering.js b/src/layers/launches/rendering.js index 2b1d2cce8..8fe5e085a 100644 --- a/src/layers/launches/rendering.js +++ b/src/layers/launches/rendering.js @@ -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-:...`). */ +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; + }, }; } diff --git a/src/layers/launches/selection.js b/src/layers/launches/selection.js index 24afd6463..40df0713a 100644 --- a/src/layers/launches/selection.js +++ b/src/layers/launches/selection.js @@ -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(); diff --git a/src/layers/launches/state.js b/src/layers/launches/state.js index d043e7b1b..ba6a41e78 100644 --- a/src/layers/launches/state.js +++ b/src/layers/launches/state.js @@ -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; diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index bc93c9692..1fd50fab5 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -32,6 +32,7 @@ * `findDraw` for one (`rendererOf.js`). */ import * as Cesium from 'cesium'; +import { temeToPseudoFixed } from '../../geo/celestial.js'; import { alongLength } from '../../geo/polyline.js'; import { provideUnboundDraw } from '../rendererOf.js'; import { listenerList, toCartesian, uncaught } from './common.js'; @@ -185,6 +186,56 @@ czm_material czm_getMaterial(czm_materialInput materialInput) { return m; }`; +/** The `radialRim` fill's material type. */ +const RADIAL_RIM_MATERIAL = 'DrawRadialRimFill'; + +/** + * Across the ellipse (`st` from its centre, 1 at its edge) the fill's + * colour, easing into the rim's over `rimWidth` (a fraction of the + * radius) just inside a soft edge; the rim glows a little. + */ +const RADIAL_RIM_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.985 - rimWidth, 0.985, radius) * inside; + material.diffuse = mix(color.rgb, rimColor.rgb, rim); + material.emission = rimColor.rgb * rim * 0.35; + material.alpha = inside * mix(color.a, rimColor.a, rim); + return material; +}`; + +/** How finely a rim-filled ellipse is cut, radians. */ +const RIM_GRANULARITY = Cesium.Math.toRadians(0.08); + +/** + * A ground fill pulled toward the eye (`depthBias`): depth-tested, not + * writing depth, offset toward the camera, alpha blended. + */ +const DEPTH_BIASED_STATE = Object.freeze({ + depthTest: { enabled: true }, + depthMask: false, + polygonOffset: { enabled: true, factor: -1, units: -4 }, + blending: Cesium.BlendingState.ALPHA_BLEND, +}); + +/** A `radialRim` fill's material. */ +function radialRimMaterial(fill) { + const uniforms = { + color: toColor(fill.color), + rimColor: toColor(fill.rimColor), + rimWidth: fill.rimWidth, + }; + // Built from its type, then given its values, as the line materials are. + const material = new Cesium.Material({ + fabric: { type: RADIAL_RIM_MATERIAL, uniforms, source: RADIAL_RIM_SOURCE }, + }); + Object.assign(material.uniforms, uniforms); + return material; +} + /** The line styles the port drapes. */ const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow']); @@ -1385,9 +1436,12 @@ export function createCesiumDraw({ // values in the fabric would be merged into copies of the type's. const template = ({ type, source, uniforms }) => source ? { type, source, uniforms } : { type }; + // A pattern's image carries its own alpha: drawn in the translucent + // pass, whatever its colour. + const translucent = style.kind === 'pattern' ? { translucent: true } : {}; const material = reveal === undefined - ? new Cesium.Material({ fabric: template(fabric) }) + ? new Cesium.Material({ fabric: template(fabric), ...translucent }) : new Cesium.Material({ fabric: { type: `${REVEAL_MATERIAL}_${style.kind}`, @@ -1395,6 +1449,7 @@ export function createCesiumDraw({ uniforms: { reveal }, source: REVEAL_SOURCE, }, + ...translucent, }); const drawn = reveal === undefined ? material : material.materials.revealed; Object.assign(drawn.uniforms, fabric.uniforms); @@ -1467,6 +1522,15 @@ export function createCesiumDraw({ type: 'PolylineArrow', uniforms: { color: toColor(style.color) }, }; + case 'pattern': + // The image along the line `repeat` times, across its width once. + return { + type: 'Image', + uniforms: { + image: toImage(style.image), + repeat: new Cesium.Cartesian2(style.repeat, 1), + }, + }; default: throw new Error(`the Cesium renderer has no ${style.kind} lines`); } @@ -1628,6 +1692,28 @@ export function createCesiumDraw({ }); } + /** + * Turn a line set's inertial lines to the sky at its motion clock's time + * now: the frame rotated by sidereal time from the Earth-fixed one. + */ + function turnInertial(record) { + const lines = record.inertialLines; + if (!lines || lines.isDestroyed()) return; + const clock = record.spec.motionClock; + const ms = + clock?.kind === 'scene' + ? Cesium.JulianDate.toDate( + scene.frameState?.time ?? Cesium.JulianDate.now(), + ).getTime() + : Date.now() - (clock?.delayMs ?? 0); + const { x, y, z } = temeToPseudoFixed(ms); + lines.modelMatrix = Cesium.Matrix4.fromRotationTranslation( + new Cesium.Matrix3(x.x, y.x, z.x, x.y, y.y, z.y, x.z, y.z, z.z), + Cesium.Cartesian3.ZERO, + lines.modelMatrix, + ); + } + function buildLines(record) { // Refused before anything changes, so the set keeps drawing as it was. for (const item of record.items.values()) @@ -1635,6 +1721,13 @@ export function createCesiumDraw({ throw new Error( 'the Cesium renderer drapes solid, glow, dash and flow lines only', ); + else if ( + item.frame === 'inertial' && + (item.mode === 'draped' || item.depthFailColor) + ) + throw new Error( + 'the Cesium renderer draws inertial lines undraped, without depth-fail colours', + ); else if ( segmented(item) && (item.mode !== 'draped' || @@ -1645,6 +1738,8 @@ export function createCesiumDraw({ 'the Cesium renderer colours and shows segments of draped solid lines only', ); const polylines = new Cesium.PolylineCollection(); + // Lines in the inertial frame, turned with the sky each frame. + let inertial = null; const draped = new Map(); // Draped glow lines that look alike: one ground primitive and one // material for them all, so they recolour together in place. @@ -1712,8 +1807,37 @@ export function createCesiumDraw({ continue; } const id = pickId(record, item); - const { polyline, reveal } = addPolyline(record, polylines, item, id); + if (item.frame === 'inertial') { + inertial ??= new Cesium.PolylineCollection(); + const { polyline, reveal, parked } = addPolyline( + record, + inertial, + item, + id, + true, + ); + // Never settled into a static batch, which would not turn. + parts.set(item.id, { + look: lineLook(item), + shape: null, + positions: null, + id, + polyline, + reveal, + parked, + home: inertial, + batched: null, + }); + continue; + } const settled = settles(item); + const { polyline, reveal, parked } = addPolyline( + record, + polylines, + item, + id, + !settled, + ); parts.set(item.id, { look: lineLook(item), // How it draws but for its colour, and where it runs, to tell a @@ -1723,6 +1847,9 @@ export function createCesiumDraw({ id, polyline, reveal, + // Hidden, out of the collection until it shows (`addPolyline`). + parked, + home: polylines, // Drawn in the set's static batch instead (`settleLines`). batched: null, }); @@ -1731,12 +1858,15 @@ export function createCesiumDraw({ // Lines in the collection that can settle into a static batch draw // beside it once they do. const settling = [...record.items.values()].some(settles); - if (deep || settling) { + if (deep || settling || inertial) { own = new Cesium.PrimitiveCollection(); own.add(polylines); if (deep) own.add(deep); + if (inertial) own.add(inertial); } record.deepLines = deep; + record.inertialLines = inertial; + if (inertial) turnInertial(record); record.polylines = polylines; record.lineBox = settling ? own : null; record.batch = null; @@ -1995,6 +2125,7 @@ export function createCesiumDraw({ return false; // A viewer destroyed under the set took its batch with it. if (was.batched?.isDestroyed()) return false; + if (was.home?.isDestroyed()) return false; looks.push(look); if (was.deep !== undefined && record.deepLines?.isDestroyed()) return false; @@ -2021,7 +2152,7 @@ export function createCesiumDraw({ const item = list[k]; const was = parts.get(item.id); const show = item.show !== false; - if (was.polyline || was.batched) { + if (was.polyline || was.parked || was.batched) { patchUndraped(record, was, item, looks[k]); continue; } @@ -2080,9 +2211,15 @@ export function createCesiumDraw({ /** * An undraped line without a depth-fail colour in the set's polyline * collection, under pick id `id`; `reveal` is the material its reveal - * is set on, or null. + * is set on, or null. A hidden line that never settles (`park`) is + * parked instead, out of the collection (`polyline` null, `parked` + * true): the collection draws every line it holds, shown or not, each + * on a material and command of its own, every frame; a hidden line + * that settles costs nothing once in its static batch. */ - function addPolyline(record, polylines, item, id) { + function addPolyline(record, polylines, item, id, park = false) { + if (park && item.show === false) + return { polyline: null, reveal: null, parked: true }; const positions = linePositions(item); const reveal = revealed(item) ? revealUniform(item.revealFraction, positions) @@ -2095,7 +2232,11 @@ export function createCesiumDraw({ show: item.show !== false, id, }); - return { polyline, reveal: reveal === undefined ? null : material }; + return { + polyline, + reveal: reveal === undefined ? null : material, + parked: false, + }; } /** @@ -2105,6 +2246,7 @@ export function createCesiumDraw({ */ const settles = (item) => item.mode !== 'draped' && + item.frame !== 'inertial' && !item.depthFailColor && item.style.kind === 'solid' && !revealed(item) && @@ -2174,6 +2316,25 @@ export function createCesiumDraw({ unsettle(record); return; } + if (!show && !was.shape) { + // Parked out of the collection, which would draw it on regardless + // (a line that settles is hidden in its batch instead). + if (was.polyline) { + dropFlow(record, was.polyline.material, item.style); + was.home.remove(was.polyline); + was.polyline = null; + was.reveal = null; + requestRender(); + } + was.parked = true; + return; + } + if (was.parked) { + // Back in the collection, as it now is. + Object.assign(was, addPolyline(record, was.home, item, was.id)); + requestRender(); + return; + } // Only a change a batch would draw unsettles the set: a show is taken // when the batch swaps in, and lines that cannot settle are not in it. if (was.shape && (recolour || !flatEquals(item.positions, was.positions))) { @@ -2578,8 +2739,11 @@ export function createCesiumDraw({ } } - /** A clamped shape's fill geometry, on the ellipsoid for draping. */ - function groundGeometry(item) { + /** + * A clamped shape's fill geometry, on the ellipsoid for draping; an + * ellipse with a rim fill is cut finely, so its rim runs round. + */ + function groundGeometry(item, rimFill = null) { const g = item.geometry; switch (g.kind) { case 'polygon': { @@ -2599,6 +2763,14 @@ export function createCesiumDraw({ semiMajorAxis: g.semiMajor, semiMinorAxis: g.semiMinor, rotation: g.rotation ?? 0, + ...(rimFill + ? { + granularity: RIM_GRANULARITY, + vertexFormat: + Cesium.MaterialAppearance.MaterialSupport.TEXTURED + .vertexFormat, + } + : {}), }); case 'rectangle': return new Cesium.RectangleGeometry({ @@ -2634,10 +2806,15 @@ export function createCesiumDraw({ parts.set(item.id, { look: lookOf(item), id: null, ground: null }); continue; } - const imageFill = + const objectFill = typeof item.fill === 'object' && !Array.isArray(item.fill) ? item.fill : null; + const rimFill = + objectFill?.preset === 'radialRim' && item.geometry.kind === 'ellipse' + ? objectFill + : null; + const imageFill = rimFill ? null : objectFill; if (imageFill && !imageFill.image) throw new Error('the Cesium renderer fills shapes with colours only'); if (item.extrudeHeight !== undefined) @@ -2654,7 +2831,7 @@ export function createCesiumDraw({ // load when they show. let geometry; try { - geometry = groundGeometry(item); + geometry = groundGeometry(item, rimFill); } catch (error) { if (item.show === false) continue; throw error; @@ -2670,17 +2847,29 @@ export function createCesiumDraw({ ); const instance = new Cesium.GeometryInstance({ geometry, - attributes: imageFill - ? { show } - : { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - toColor(item.fill), - ), - show, - }, + attributes: + imageFill || rimFill + ? { show } + : { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + show, + }, id: part.id, }); const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; + if (rimFill) { + // A rim fill is a ground primitive of its own, with its material. + batches.push({ + clampTo, + instances: [instance], + parts: [part], + rimFill, + depthBias: item.depthBias, + }); + continue; + } if (imageFill) { // An image fill is a ground primitive of its own, with its material. // (Cesium turns its texture wrongly across the antimeridian: its @@ -2726,7 +2915,9 @@ export function createCesiumDraw({ ...(batch.imageFill.repeat ?? [1, 1]), ), }) - : null; + : batch.rimFill + ? radialRimMaterial(batch.rimFill) + : null; const ground = new Ground({ geometryInstances: batch.instances, classificationType: classificationOf(batch.clampTo), @@ -2739,6 +2930,15 @@ export function createCesiumDraw({ Cesium.MaterialAppearance.MaterialSupport.TEXTURED, translucent: true, flat: true, + ...(batch.rimFill + ? { + closed: false, + faceForward: true, + ...(batch.depthBias + ? { renderState: DEPTH_BIASED_STATE } + : {}), + } + : {}), }), } : {}), @@ -3074,6 +3274,8 @@ export function createCesiumDraw({ beforeRender() { cullHorizon(); runFlows(); + for (const record of sets.values()) + if (record.inertialLines) turnInertial(record); modelSets.beforeRender(sets.values()); }, /** Each frame, after it drew: clamp state, and ground swaps. */ diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 98870e9c6..7cf02bc11 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -595,8 +595,24 @@ test('clamped shapes refuse what they cannot draw', () => { fill: '#fff', height: 'clampGround', }; + // A rim fill is drawn on ellipses alone. assert.throws( - () => set.set([{ ...disc, fill: { preset: 'radialRim' } }]), + () => + set.set([ + { + ...disc, + geometry: { + kind: 'rectangle', + rect: { west: 0, south: 0, east: 1, north: 1 }, + }, + fill: { + preset: 'radialRim', + color: '#fff', + rimColor: '#fff', + rimWidth: 0.1, + }, + }, + ]), /colours only/, ); assert.throws( @@ -2114,8 +2130,9 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac s.built(translucentAgain); frame(); assert.equal(opaqueAgain.show, true, 'swapped in once built'); - assert.equal(polylines.length, 1, 'the glow alone left in the collection'); - assert.equal(polylines.get(0).id.id, 'glow'); + // The glow, hidden, is parked out of the collection, which would draw + // it on regardless; the batch took the rest. + assert.equal(polylines.length, 0, 'none left in the collection'); // Show, colour and meta change in place on the batch. set.upsert([ stem('a', 100, { show: false }), @@ -2124,7 +2141,7 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac assert.equal(s.host(), host); assert.deepEqual([...s.attrs(opaqueAgain, 'a').show], [0]); assert.deepEqual([...s.attrs(opaqueAgain, 'c').color], [0, 0, 255, 255]); - assert.equal(polylines.length, 1, 'nothing left the batch'); + assert.equal(polylines.length, 0, 'nothing left the batch'); set.upsert([stem('a', 100, { meta: 'new' })]); assert.deepEqual([...s.attrs(opaqueAgain, 'a').show], [1]); assert.equal(opaqueAgain.geometryInstances[0].id.meta, 'new'); @@ -2133,8 +2150,8 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac set.upsert([stem('a', 900)]); assert.equal(s.host(), host); assert.deepEqual([...s.attrs(opaqueAgain, 'a').show], [0]); - assert.equal(polylines.length, 2); - const moved = polylines.get(1); + assert.equal(polylines.length, 1); + const moved = polylines.get(0); assert.equal(moved.id.id, 'a'); assert.ok( Cesium.Cartesian3.equalsEpsilon( @@ -2147,7 +2164,7 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac set.upsert([ stem('c', 300, { style: { kind: 'solid', color: [0, 0, 1, 0.4] } }), ]); - assert.equal(polylines.length, 3); + assert.equal(polylines.length, 2); // Two lines are few beside a batch: they wait longer. s.settle(); assert.equal(s.batches().length, 2, 'not yet'); @@ -2173,7 +2190,12 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac assert.deepEqual(s.batches(), next, 'the old batches are gone'); assert.equal(opaqueAgain.isDestroyed(), true); assert.deepEqual([...s.attrs(next[1], 'b').show], [0]); + assert.equal(polylines.length, 0); + // The glow shown again draws in the collection, in place. + set.upsert([glow]); + assert.equal(s.host(), host); assert.equal(polylines.length, 1); + assert.equal(polylines.get(0).id.id, 'glow'); // A line that looks different is still a rebuild. set.upsert([stem('b', 200, { widthPx: 5 })]); assert.notEqual(s.host(), host); @@ -5163,3 +5185,167 @@ test('a raised polygon outlines its holes as well as its outer ring', () => } set.dispose(); })); + +test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', () => + withImageClasses(() => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'orbit-rings' }); + const ring = [ + { x: 7e6, y: 0, z: 0 }, + { x: 0, y: 7e6, z: 0 }, + { x: -7e6, y: 0, z: 0 }, + ]; + const pattern = { kind: 'pattern', image: 'marks.png', repeat: 4 }; + set.set([ + { id: 'fixed', positions: ring, widthPx: 3, mode: '3d', style: pattern }, + { + id: 'sky', + positions: ring, + widthPx: 3, + mode: '3d', + style: pattern, + frame: 'inertial', + }, + ]); + const host = scene.added[0]; + assert.ok(host instanceof Cesium.PrimitiveCollection); + const fixed = host.get(0); + const inertial = host.get(1); + assert.ok(inertial instanceof Cesium.PolylineCollection); + const material = fixed.get(0).material; + assert.equal(material.type, 'Image'); + assert.equal(material.uniforms.image, 'marks.png'); + assert.deepEqual(material.uniforms.repeat, new Cesium.Cartesian2(4, 1)); + assert.equal(material.isTranslucent(), true, 'its image has its alpha'); + assert.equal(inertial.get(0).id.id, 'sky'); + // Turned by sidereal time: the inertial x axis is drawn where the + // pseudo-fixed frame puts it now. + const turnedTo = () => + Cesium.Matrix4.multiplyByPointAsVector( + inertial.modelMatrix, + Cesium.Cartesian3.UNIT_X, + new Cesium.Cartesian3(), + ); + const expected = Cesium.Matrix3.multiplyByVector( + Cesium.Transforms.computeTemeToPseudoFixedMatrix(Cesium.JulianDate.now()), + Cesium.Cartesian3.UNIT_X, + new Cesium.Cartesian3(), + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon(turnedTo(), expected, 1e-6), + 'turned as Cesium turns TEME', + ); + const realNow = Date.now; + try { + const at = realNow(); + Date.now = () => at + 3_600_000; + frame(); + const later = turnedTo(); + // An hour turns the frame about 15 degrees about the pole. + const angle = Cesium.Cartesian3.angleBetween(later, expected); + assert.ok(Math.abs(Cesium.Math.toDegrees(angle) - 15.04) < 0.05); + assert.ok(Math.abs(later.z) < 1e-9); + } finally { + Date.now = realNow; + } + // Never settled into a static batch; shown and hidden in place. A + // hidden line that never settles leaves its collection, which would + // draw it on regardless, until it shows again. + for (let i = 0; i < SETTLE_FRAMES + 2; i++) frame(); + const sky = (show) => ({ + id: 'sky', + positions: ring, + widthPx: 3, + mode: '3d', + style: pattern, + frame: 'inertial', + show, + }); + set.upsert([sky(false), { ...sky(false), id: 'fixed', frame: undefined }]); + assert.equal(scene.added[0], host, 'patched, not rebuilt'); + assert.equal(inertial.length, 0); + assert.equal(fixed.length, 0); + set.upsert([sky(true)]); + assert.equal(scene.added[0], host); + assert.equal(inertial.length, 1); + assert.equal(inertial.get(0).show, true); + assert.equal(inertial.get(0).id.id, 'sky'); + assert.equal(inertial.get(0).material.type, 'Image'); + // Built hidden, it starts out of its collection. + const later = draw.lines({ id: 'orbit-rings-hidden' }); + later.set([{ ...sky(false), id: 'parked' }]); + assert.equal(scene.added.at(-1).get(1).length, 0); + later.upsert([{ ...sky(true), id: 'parked' }]); + assert.equal(scene.added.at(-1).get(1).length, 1); + later.dispose(); + assert.throws( + () => + set.upsert([ + { + id: 'draped', + positions: ring, + widthPx: 3, + mode: 'draped', + style: { kind: 'solid', color: '#fff' }, + frame: 'inertial', + }, + ]), + /inertial lines undraped/, + ); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('a clamped ellipse filled with a radial rim drapes its material, finely cut, pulled toward the eye', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.shapes({ id: 'pad-zone' }); + const zone = { + id: 'zone', + geometry: { + kind: 'ellipse', + center: { lon: -80.6, lat: 28.6 }, + semiMajor: 500, + semiMinor: 500, + }, + fill: { + preset: 'radialRim', + color: [0.13, 0.9, 0.9, 0.105], + rimColor: [0.13, 0.9, 0.9, 0.72], + rimWidth: 0.033, + }, + height: 'clampGround', + depthBias: 1, + }; + set.set([zone]); + const host = scene.added[0]; + let ground = null; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) ground = host.get(i); + assert.ok(ground); + const { appearance } = ground; + assert.ok(appearance instanceof Cesium.MaterialAppearance); + assert.equal(appearance.material.type, 'DrawRadialRimFill'); + const { color, rimColor, rimWidth } = appearance.material.uniforms; + assert.ok(color.equalsEpsilon(new Cesium.Color(0.13, 0.9, 0.9, 0.105), 1e-9)); + assert.ok(rimColor.equalsEpsilon(new Cesium.Color(0.13, 0.9, 0.9, 0.72), 1e-9)); + assert.equal(rimWidth, 0.033); + assert.equal(appearance.renderState.polygonOffset.enabled, true); + assert.equal(appearance.renderState.depthMask, false); + assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); + const [instance] = ground.geometryInstances; + assert.ok(instance.geometry instanceof Cesium.EllipseGeometry); + assert.ok( + Math.abs(instance.geometry._granularity - Cesium.Math.toRadians(0.08)) < + 1e-12, + ); + assert.equal(instance.id.id, 'zone'); + // Hidden and shown in place, once its primitive is ready. + Object.defineProperty(ground, 'ready', { value: true }); + const shows = { show: Uint8Array.of(1) }; + ground.getGeometryInstanceAttributes = () => shows; + set.upsert([{ ...zone, show: false }]); + assert.equal(scene.added[0], host, 'patched, not rebuilt'); + assert.deepEqual([...shows.show], [0]); + set.dispose(); + })); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 469d285d0..7ff397090 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -16,9 +16,6 @@ "src/layers/firms/rendering.js", "src/layers/ghostMaps/index.js", "src/layers/installations/rendering.js", - "src/layers/launches/launchPad.js", - "src/layers/launches/orbitRendering.js", - "src/layers/launches/rendering.js", "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index a6829ec8d..473464049 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -100,6 +100,9 @@ const DRAW_FROM_CALLER = new Set([ // draw, size and fly through the ports alone. './infrastructure', './infrastructure/geojson', + // Not wholly Cesium-free (its pointer input still is), but its missions + // draw, pick and fly through the ports alone. + './layers/launches', ]); /**