diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 205512676..009861a81 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 @@ -5694,14 +5698,14 @@ request viewbox and continues searching without that geographic preference. - Only a new head costs REST calls: one recursive tree and one commit. An optional `GITHUB_TOKEN` raises the REST limit. - After an upstream outage, a successful branch-head check clears the error and pushes a recovered catalog even when the commit is unchanged. Cached products stay in place; subsequent healthy unchanged checks stay silent. - The new catalog goes to `.gev-cache/ghostmaps/catalog.json` and to every open page over server-sent events (`/api/ghostmaps/events`, 25 s heartbeat, at most 64 subscribers). Default products are downloaded at once. - - The layer reloads only products whose blob changed. The new edition's data source is added before the old one is removed. A product that leaves the catalog leaves the globe. + - The layer reloads only products whose blob changed. The new edition's draw sets are added before the old ones are removed. A product that leaves the catalog leaves the globe. - The row reads `LIVE` while the stream is open. A five-minute catalog read is the backstop. - **Files.** `/api/ghostmaps/file/{product}` serves only catalog products. Files are downloaded by commit-pinned raw URLs, so a CDN cannot return an older edition. They are cached on disk by blob sha, and blobs no current product uses are pruned. A request whose `?v=` names the current blob is `immutable`. Repository paths never reach the page. - **Source ownership.** The application catalog receives `sources['s2-ghostmaps']` through the shared source contracts; an omitted or null source stays unavailable without opening a stream or fetching. The standalone source factory supplies the same-origin implementation and accepts replacements. Packed-image URLs are released on cancelled or failed product construction, and remain owned by a successfully loaded product until it is removed. - **Voice and locales.** S2 can be toggled through its registered id and aliases. The model already sees the S2 GhostMaps brand in the id, and compact alias-hint separators keep the complete voice prompt within its existing 52,000-character limit; accepted aliases are unchanged. The row and reports are translated in Spanish, Russian and Simplified Chinese. -- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into one `CustomDataSource` per product. - - Points become ground-clamped billboards with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. - - Lines and polygon outlines are ground-clamped polylines. +- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into renderer draw sets (icons, lines and shapes) per product edition. The layer no longer reaches Cesium, so a consumer handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. + - Points become ground-clamped icons with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. + - Lines and polygon outlines are ground-clamped lines; polygon fills are ground-clamped shapes. - Styles, StyleMaps and inline styles are honoured. Icons come only from images packed in the same KMZ and at most 512 KB. Anything else uses a per-product round marker. - Network links, overlays, models and remote hrefs are never followed. Hidden placemarks are skipped. Bounds are 20,000 placemarks and 250,000 positions per product. - **Reports.** Clicking a marker opens a card with the product, folder, edition date and the placemark's report fields. `src/layers/ghostMaps/records.js` reads ArcGIS popup tables as text only: `` and internal fields are dropped and values are capped. Description markup is never inserted into the page. The first `http(s)` research link opens from the card. The card is `stateless`, so it comes and goes with the click, as CCTV cards do. It is also `horizonCull`ed, so it hides when its marker turns behind the planet. Picks are registered under `s2-ghostmaps`. 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 967edb508..a88788895 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", @@ -2113,6 +2114,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", @@ -3344,6 +3346,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", @@ -4333,6 +4336,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", @@ -5978,6 +5982,7 @@ "exports": ["./layers/ghostmaps"], "modules": [ "src/layers/ghostMaps/index.js", + "src/render/color.js", "src/geo/index.js", "src/geo/julian.js", "src/layers/ghostMaps/catalog.js", diff --git a/scripts/qa-ghostmaps.mjs b/scripts/qa-ghostmaps.mjs index 83dc8ed97..45f94ebb2 100644 --- a/scripts/qa-ghostmaps.mjs +++ b/scripts/qa-ghostmaps.mjs @@ -8,7 +8,7 @@ * * (i) LIVE — enabling the layer loads the default products (Common * Intelligence Picture and the 30-day kinetic pull) from the live - * repository through /api/ghostmaps, one data source per product, + * repository through /api/ghostmaps, one pin set per product, * matching the proxy's catalog commit; the row shows one chip per * catalog product with the defaults active, and the page holds an * open event stream to /api/ghostmaps/events. @@ -17,12 +17,14 @@ * and clicking empty ground clears it. * (iii) PUSH (synthetic) — the event stream is replaced in the page and a * catalog naming a new edition of one product is pushed: only that - * product reloads (a new data source replaces the old one, no - * duplicates), the other keeps its data source. A catalog without a + * product reloads (a new pin set replaces the old one, no + * duplicates), the other keeps its pin set. A catalog without a * product removes it. * (iv) CHIPS — clicking an active product chip removes that product, * clicking it again restores it; the choice survives a reload. - * (v) DISABLE — every GhostMaps data source leaves the viewer. + * (v) DISABLE — every GhostMaps pin set leaves the viewer. + * The checks read pins (billboards) only: a product's lines and fills + * are not counted. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips * fit the panel width with no horizontal overflow. * (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled: @@ -76,18 +78,43 @@ async function boot(page) { await page.keyboard.press('Escape'); } -/** GhostMaps data sources on the viewer: name → entity count. */ -function ghostSources(prefix) { - const { dataSources } = window.__godsEyeView.viewer; - const out = []; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (ds.name?.startsWith(prefix)) - out.push({ name: ds.name, count: ds.entities.values.length }); - } +/** + * The GhostMaps pins drawn, by edition: each product's pins are drawn in a + * billboard collection of their own (a data source's, or a draw set's), so + * whatever draws them is read the same way. In the page: `layerId:product` + * → `{collection, pins: [{show, position}]}`. + */ +function ghostPins(prefix) { + const out = new Map(); + const seen = new Set(); + const visit = (node) => { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node._billboards)) { + for (const billboard of node._billboards) { + const id = String(billboard?.id?.id ?? billboard?.id ?? ''); + if (!id.startsWith('ghostmaps:')) continue; + const name = `${prefix}${id.split(':')[1]}`; + if (!out.has(name)) out.set(name, { collection: node, pins: [] }); + out.get(name).pins.push(billboard); + } + return; + } + if (Array.isArray(node._primitives)) node._primitives.forEach(visit); + visit(node._billboardCollection); + }; + visit(window.__godsEyeView.viewer.scene.primitives); return out; } +/** GhostMaps editions drawn: name → pin count. */ +function ghostSources(prefix) { + return [...ghostPins(prefix)].map(([name, { pins }]) => ({ + name, + count: pins.length, + })); +} + function paintedOverlayPixels() { const canvas = document.getElementById('world-overlay-canvas'); if (!canvas) return -1; @@ -124,7 +151,9 @@ const stats = (page) => LAYER_ID, ); const sources = (page) => - page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`); + page.evaluate( + `${ghostPins};(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`, + ); async function showRow(page) { await page.evaluate((id) => { @@ -175,7 +204,7 @@ async function main() { const live = await stats(page); const liveSources = await sources(page); record( - 'LIVE: default products load as one data source each', + 'LIVE: default products load as one pin set each', liveSources.length === 2 && liveSources.every((s) => s.count > 0) && live.products.sort().join() === 'cip,kinetic-30d', @@ -225,14 +254,14 @@ async function main() { await page.screenshot({ path: path.join(SHOTS_DIR, 'ghostmaps-live.png') }); // ---- (ii) PICK ---------------------------------------------------------- - const target = await page.evaluate((id) => { + const target = await page.evaluate(`(() => { + ${ghostPins}; const gev = window.__godsEyeView; - const ds = [...Array(gev.viewer.dataSources.length).keys()] - .map((i) => gev.viewer.dataSources.get(i)) - .find((item) => item.name === `${id}:cip`); - const entity = ds.entities.values.find((e) => e.billboard); + const pin = ghostPins(${JSON.stringify(`${LAYER_ID}:`)}).get( + ${JSON.stringify(`${LAYER_ID}:cip`)}, + ).pins[0]; const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic( - entity.position.getValue(gev.viewer.clock.currentTime), + pin.position, ); try { gev.viewer.camera.cancelFlight(); @@ -248,8 +277,8 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); gev.viewer.scene.requestRender?.(); - return entity.id; - }, LAYER_ID); + return String(pin.id?.id ?? pin.id); + })()`); await page .waitForFunction( () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, @@ -300,7 +329,7 @@ async function main() { }; }); record( - 'PICK: the centred marker picks as a GhostMaps entity', + 'PICK: the centred marker picks as a GhostMaps pin', probe.ids.some((id) => id.startsWith('ghostmaps:cip:')), `${target} → [${probe.ids.slice(0, 3).join(', ')}]`, ); @@ -366,7 +395,9 @@ async function main() { // be hidden, and pins facing the camera must still show. const horizonCounts = (lon, lat) => page.evaluate( - async (id, lo, la) => { + async (id, lo, la, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); const gev = window.__godsEyeView; const d2r = Math.PI / 180; try { @@ -389,12 +420,9 @@ async function main() { const norm = (v) => Math.hypot(v.x, v.y, v.z); let far = 0; let nearShown = 0; - for (let i = 0; i < gev.viewer.dataSources.length; i++) { - const ds = gev.viewer.dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - for (const e of ds.entities.values) { - if (!e.billboard) continue; - const p = e.position.getValue(gev.viewer.clock.currentTime); + for (const { pins } of ghostPins(`${id}:`).values()) { + for (const e of pins) { + const p = e.position; // Angle from the camera's nadir to the pin, against the // geometric horizon angle; the cull's 1 km margin shows pins up // to about 1° past it, so "clearly behind" is beyond 2°. @@ -412,6 +440,7 @@ async function main() { LAYER_ID, lon, lat, + String(ghostPins), ); const fromIndianOcean = await horizonCounts(80, -30); record( @@ -459,7 +488,7 @@ async function main() { ); const without = await sources(page); record( - 'CHIPS: turning a product off removes only its data source', + 'CHIPS: turning a product off removes only its pins', without.length === 1 && without[0].name === `${LAYER_ID}:cip`, without.map((s) => s.name).join(', '), ); @@ -498,7 +527,7 @@ async function main() { ); await sleep(500); record( - 'DISABLE: every GhostMaps data source leaves the viewer', + 'DISABLE: every GhostMaps pin leaves the viewer', (await sources(page)).length === 0, ); await page.close(); @@ -533,20 +562,23 @@ async function main() { await boot(push); await enableAndSettle(push); const identity = () => - push.evaluate((id) => { - const { dataSources } = window.__godsEyeView.viewer; - window.__qaIds ||= new WeakMap(); - window.__qaNext ||= 1; - const out = {}; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - if (!window.__qaIds.has(ds)) - window.__qaIds.set(ds, window.__qaNext++); - out[ds.name] = window.__qaIds.get(ds); - } - return out; - }, LAYER_ID); + push.evaluate( + (id, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); + window.__qaIds ||= new WeakMap(); + window.__qaNext ||= 1; + const out = {}; + for (const [name, { collection }] of ghostPins(`${id}:`)) { + if (!window.__qaIds.has(collection)) + window.__qaIds.set(collection, window.__qaNext++); + out[name] = window.__qaIds.get(collection); + } + return out; + }, + LAYER_ID, + String(ghostPins), + ); const first = await identity(); const pushed = Date.now(); await push.evaluate(async (id) => { 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/ghostMaps/index.js b/src/layers/ghostMaps/index.js index ee69a044d..664d7885b 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { decodeXml, kmzImageResolver, @@ -15,9 +14,9 @@ import { tn, } from '../../i18n/index.js'; import { createHorizonCull } from '../streetLevel/view.js'; -// The horizon cull reads the camera and frame ports: a viewer of a -// caller's own gets them from the unbound factories this loads. -import '../../render/cesium/camera.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { hexColor } from '../../render/color.js'; +import { drawOf, findFrame } from '../../render/rendererOf.js'; import { readGhostMapsKml } from './kml.js'; import { fieldLabel, parseDescriptionFields, wrapCardText } from './records.js'; import { inputFor as defaultInputFor } from '../../input/dispatcher.js'; @@ -110,10 +109,34 @@ function markerImage(color) { return url; } -const cesiumColor = (rgba, fallback, alpha) => +const drawColor = (rgba, fallback, alpha) => rgba - ? new Cesium.Color(rgba[0], rgba[1], rgba[2], alpha ?? rgba[3]) - : Cesium.Color.fromCssColorString(fallback).withAlpha(alpha ?? 1); + ? [rgba[0], rgba[1], rgba[2], alpha ?? rgba[3]] + : hexColor(fallback, alpha ?? 1); + +/** The size a marker image draws at, before its scale: the product marker. */ +const MARKER_SIZE = [20, 20]; + +/** + * An image's own size in pixels, as an icon drew it unsized; null when it + * cannot be read here (no DOM, or the image does not decode). + */ +async function imageSizeOf(url) { + if (typeof globalThis.Image !== 'function' || !url) return null; + try { + const image = new globalThis.Image(); + image.src = url; + await image.decode(); + return image.naturalWidth > 0 && image.naturalHeight > 0 + ? [image.naturalWidth, image.naturalHeight] + : null; + } catch { + return null; + } +} + +/** Each layer's draw sets have ids of their own. */ +let instances = 0; function anchorOf(geometry) { if (geometry.type === 'point') return geometry.position; @@ -157,7 +180,7 @@ export function createGhostMapsLayer({ let _selectedLink = null; let _lifetime = new AbortController(); let _selection = readStoredSelection(storage); - /** productId → {version, dataSource, urls, count, features} */ + /** productId → {version, sets, urls, features, pins} */ const _loaded = new Map(); /** productId → in-flight version */ const _loading = new Map(); @@ -165,7 +188,11 @@ export function createGhostMapsLayer({ const _failed = new Map(); const notifyRow = () => _rowListener?.(); - const render = () => _viewer?.scene?.requestRender?.(); + const render = () => + _viewer && findFrame(_viewer)?.requestRender?.('ghostmaps'); + /** This layer's draw sets' ids start with this; one set per edition. */ + const setBase = `${GHOSTMAPS_LAYER_ID}:${++instances}`; + let editions = 0; // Pins skip the depth test, and with Google 3D tiles the globe is hidden, // so nothing else stops far-side pins drawing through the planet. const _horizon = createHorizonCull({ @@ -173,7 +200,16 @@ export function createGhostMapsLayer({ items: function* () { for (const item of _loaded.values()) yield* item.pins; }, - onChange: render, + // Pins the cull turned are written to their editions' icon sets. + onChange: (changed) => { + const bySet = new Map(); + for (const pin of changed) { + if (!bySet.has(pin.set)) bySet.set(pin.set, []); + bySet.get(pin.set).push(pin.item); + } + for (const [set, items] of bySet) set?.upsert(items); + render(); + }, }); const canSelect = () => overlayHost && inputFor && picking; @@ -189,12 +225,61 @@ export function createGhostMapsLayer({ const item = _loaded.get(id); if (!item) return; _loaded.delete(id); - _viewer?.dataSources?.remove(item.dataSource, true); + disposeSets(item.sets); item.urls.forEach((url) => URL.revokeObjectURL(url)); if (_selectedKey?.startsWith(`${id}:`)) clearSelection(); } - /** Build one product's data source off-scene, then swap it in. */ + function disposeSets(sets) { + if (!sets) return; + for (const set of Object.values(sets)) set.dispose(); + } + + /** + * Draw a loaded edition in sets of its own, beside any edition drawing + * now. One that cannot be drawn draws nothing and lets its images go. + */ + function mount(next) { + const base = `${setBase}:${++editions}`; + const sets = {}; + try { + // Inside the try: a viewer with no renderer bound draws nothing and + // still lets the edition's images go. + const draw = drawOf(_viewer); + sets.shapes = draw.shapes({ id: `${base}:shapes`, clampTo: 'both' }); + sets.lines = draw.lines({ id: `${base}:lines`, clampTo: 'both' }); + sets.icons = draw.icons({ id: `${base}:icons`, clampTo: 'both' }); + sets.shapes.set(next.items.shapes); + sets.lines.set(next.items.lines); + sets.icons.set(next.items.icons); + } catch (error) { + disposeSets(sets); + next.urls.forEach((url) => URL.revokeObjectURL(url)); + throw error; + } + for (const pin of next.pins) pin.set = sets.icons; + next.sets = sets; + } + + /** The placemark a hit on one of this layer's items is, or null. */ + function hitKey(hit) { + if ( + !hit?.set?.startsWith(`${setBase}:`) || + !hit.id?.startsWith(PICK_PREFIX) + ) + return null; + const [productId, index] = hit.id.slice(PICK_PREFIX.length).split(':'); + const loaded = _loaded.get(productId); + // Only the drawing edition's sets: a retiring one may still pick. + const current = loaded?.sets + ? Object.values(loaded.sets).some((set) => set?.id === hit.set) + : false; + return current && loaded.features[Number(index)] + ? `${productId}:${index}` + : null; + } + + /** Build one product's draw items off-scene, then swap them in. */ async function load(product, signal) { const bytes = await source.getFile(product.id, product.version, { signal }); signal.throwIfAborted(); @@ -222,93 +307,113 @@ export function createGhostMapsLayer({ entries.clear(); signal.throwIfAborted(); const color = PRODUCT_COLORS[product.id] || ACCENT; - const dataSource = new Cesium.CustomDataSource( - `${GHOSTMAPS_LAYER_ID}:${product.id}`, - ); + const icons = []; + const lines = []; + const shapes = []; const features = []; const pins = []; - dataSource.entities.suspendEvents(); + // Each distinct icon's own size, read once: icons draw at it, scaled. + const sizes = new Map(); + const marker = markerImage(color); + for (const feature of parsed.features) + for (const geometry of feature.geometries) + if (geometry.type === 'point') { + const image = feature.style.icon || marker; + if (image && !sizes.has(image)) + sizes.set( + image, + image === marker ? MARKER_SIZE : imageSizeOf(image), + ); + } + for (const [image, size] of sizes) sizes.set(image, await size); + signal.throwIfAborted(); parsed.features.forEach((feature, index) => { const key = `${product.id}:${index}`; const { style } = feature; feature.geometries.forEach((geometry, part) => { const id = `${PICK_PREFIX}${key}:${part}`; if (geometry.type === 'point') { - const position = Cesium.Cartesian3.fromDegrees( - ...geometry.position, - ); - const entity = dataSource.entities.add({ + const position = fromDegrees(...geometry.position); + const image = style.icon || marker; + // An image that cannot be drawn shows nothing, as before. + if (!image) return; + const item = { id, - position, - billboard: { - image: style.icon || markerImage(color), - scale: Math.min( - 1.5, - Math.max(0.35, (style.iconScale ?? 1) * 0.7), - ), - color: - style.icon && style.iconColor - ? cesiumColor(style.iconColor) - : undefined, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - verticalOrigin: Cesium.VerticalOrigin.CENTER, - // Ground-clamped icons would sink into terrain and 3D tiles; the - // horizon cull hides the far side instead (see `_horizon`). - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + pos: position, + image, + size: sizes.get(image) ?? MARKER_SIZE, + scale: Math.min( + 1.5, + Math.max(0.35, (style.iconScale ?? 1) * 0.7), + ), + ...(style.icon && style.iconColor + ? { color: style.iconColor } + : {}), + height: 'clampGround', + anchor: 'center', + // Ground-clamped icons would sink into terrain and 3D tiles; the + // horizon cull hides the far side instead (see `_horizon`). + disableDepthTest: Number.POSITIVE_INFINITY, + }; + const at = icons.push(item) - 1; + // What the horizon cull turns: the icon as it draws now, in its + // edition's icon set once mounted. pins.push({ position, + set: null, + get item() { + return icons[at]; + }, get show() { - return entity.show; + return icons[at].show !== false; }, set show(value) { - entity.show = value; + icons[at] = { ...icons[at], show: value }; }, }); } else if (geometry.type === 'line') { - dataSource.entities.add({ + lines.push({ id, - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - geometry.positions.flat(), - ), - width: Math.min(8, Math.max(1.5, style.lineWidth ?? 2)), - material: cesiumColor(style.lineColor, color), - clampToGround: true, + positions: geometry.positions.map(([lon, lat]) => + fromDegrees(lon, lat), + ), + widthPx: Math.min(8, Math.max(1.5, style.lineWidth ?? 2)), + mode: 'draped', + style: { + kind: 'solid', + color: drawColor(style.lineColor, color), }, }); } else { - const ring = (points) => - Cesium.Cartesian3.fromDegreesArray(points.flat()); - dataSource.entities.add({ + const ring = (points) => points.map(([lon, lat]) => ({ lon, lat })); + shapes.push({ id, - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - ring(geometry.outer), - geometry.holes.map( - (hole) => new Cesium.PolygonHierarchy(ring(hole)), - ), - ), - material: - style.fill === false - ? Cesium.Color.TRANSPARENT - : cesiumColor( - style.polyColor, - color, - style.polyColor ? undefined : 0.25, - ), - classificationType: Cesium.ClassificationType.BOTH, + geometry: { + kind: 'polygon', + rings: [ring(geometry.outer), ...geometry.holes.map(ring)], }, + // An unfilled polygon is still there to click, as before. + fill: + style.fill === false + ? [0, 0, 0, 0] + : drawColor( + style.polyColor, + color, + style.polyColor ? undefined : 0.25, + ), + height: 'clampGround', }); if (style.outline !== false) - dataSource.entities.add({ + lines.push({ id: `${id}:outline`, - polyline: { - positions: ring([...geometry.outer, geometry.outer[0]]), - width: Math.min(6, Math.max(1.5, style.lineWidth ?? 2)), - material: cesiumColor(style.lineColor, color), - clampToGround: true, + positions: [...geometry.outer, geometry.outer[0]].map( + ([lon, lat]) => fromDegrees(lon, lat), + ), + widthPx: Math.min(6, Math.max(1.5, style.lineWidth ?? 2)), + mode: 'draped', + style: { + kind: 'solid', + color: drawColor(style.lineColor, color), }, }); } @@ -320,8 +425,14 @@ export function createGhostMapsLayer({ anchor: anchorOf(feature.geometries[0]), }); }); - dataSource.entities.resumeEvents(); - return { version: product.version, dataSource, urls, features, pins }; + return { + version: product.version, + items: { icons, lines, shapes }, + sets: null, + urls, + features, + pins, + }; } catch (error) { urls.forEach((url) => URL.revokeObjectURL(url)); throw error; @@ -351,8 +462,8 @@ export function createGhostMapsLayer({ return; } // Cull before the first frame so far-side pins never flash. - _horizon.update(next.pins); - await _viewer.dataSources.add(next.dataSource); + _horizon.update(next.pins, { quiet: true }); + mount(next); // The new edition is on the globe before the old one leaves. unload(product.id); _loaded.set(product.id, next); @@ -459,7 +570,7 @@ export function createGhostMapsLayer({ // when its marker turns behind the planet. stateless: true, horizonCull: true, - position: Cesium.Cartesian3.fromDegrees(...feature.anchor), + position: fromDegrees(...feature.anchor), }; if (card.interactive) { const link = _selectedLink; @@ -487,16 +598,6 @@ export function createGhostMapsLayer({ overlayHost?.setEntries(GHOSTMAPS_OVERLAY_SOURCE_ID, [], CARD_HOST_OPTIONS); } - function pickedKey(picked) { - const pickId = picking.resolvePickId(picked); - if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX)) - return null; - const [productId, index] = pickId.slice(PICK_PREFIX.length).split(':'); - return _loaded.get(productId)?.features[Number(index)] - ? `${productId}:${index}` - : null; - } - function installClickHandler() { if (!canSelect() || _clickSubscription || !_viewer) return; picking.registerPickOwner?.( @@ -515,7 +616,7 @@ export function createGhostMapsLayer({ return; } const picked = event.pick; - const key = picked ? pickedKey(picked) : null; + const key = picked ? hitKey(event.drawHit) : null; if (key) { _selectedKey = key; publishCard(); @@ -563,7 +664,8 @@ export function createGhostMapsLayer({ enable() { _enabled = true; _lifetime = new AbortController(); - for (const item of _loaded.values()) item.dataSource.show = true; + for (const item of _loaded.values()) + for (const set of Object.values(item.sets ?? {})) set.show = true; installClickHandler(); if (!_unsubscribe && typeof source.subscribe === 'function') _unsubscribe = source.subscribe( diff --git a/src/layers/ghostMaps/lifecycle.test.mjs b/src/layers/ghostMaps/lifecycle.test.mjs index 51d546017..ab0515168 100644 --- a/src/layers/ghostMaps/lifecycle.test.mjs +++ b/src/layers/ghostMaps/lifecycle.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import * as Cesium from 'cesium'; import { createGhostMapsLayer } from './index.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function element(localName, children = [], value = '', attributes = {}) { const node = { @@ -104,17 +104,17 @@ function fixture(t, { beforeFileReturns, onCreateUrl } = {}) { }); t.mock.method(URL, 'revokeObjectURL', (url) => revoked.push(url)); t.mock.method(console, 'warn', () => {}); - const mounted = new Set(); - const viewer = { - scene: { requestRender() {} }, - dataSources: { - async add(dataSource) { - mounted.add(dataSource); - return dataSource; - }, - remove(dataSource) { - return mounted.delete(dataSource); - }, + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + t.after(unbind); + // The editions drawn: each draws in sets of its own. + const mounted = { + get size() { + return new Set( + [...draw.sets.values()] + .filter((set) => !set.disposed) + .map((set) => set.spec.id.split(':').slice(0, 3).join(':')), + ).size; }, }; const layer = createGhostMapsLayer({ @@ -132,7 +132,7 @@ function fixture(t, { beforeFileReturns, onCreateUrl } = {}) { layer.init(viewer); layer.enable(); t.after(() => layer.destroy()); - return { layer, viewer, mounted, created, revoked }; + return { layer, viewer, draw, unbind, mounted, created, revoked }; } test('cancelling a file read does not allocate packed-image URLs', async (t) => { @@ -155,9 +155,9 @@ test('cancellation during parsing releases every packed-image URL', async (t) => assert.equal(mounted.size, 0); }); -test('entity construction failure releases parsed image URLs', async (t) => { - const { layer, viewer, mounted, created, revoked } = fixture(t); - t.mock.method(Cesium.EntityCollection.prototype, 'add', () => { +test('a draw failure releases parsed image URLs', async (t) => { + const { layer, viewer, draw, mounted, created, revoked } = fixture(t); + t.mock.method(draw, 'icons', () => { throw new Error('fixture entity failure'); }); await layer.update(viewer); @@ -167,13 +167,34 @@ test('entity construction failure releases parsed image URLs', async (t) => { assert.equal(layer.getStats().error, 'fixture entity failure'); }); +test('a viewer with no renderer bound releases parsed image URLs', async (t) => { + const { layer, viewer, unbind, mounted, created, revoked } = fixture(t); + unbind(); + await layer.update(viewer); + assert.equal(created.length, 1); + assert.deepEqual(revoked, created); + assert.equal(mounted.size, 0); + assert.ok(layer.getStats().error); +}); + test('successful load keeps icons until the product is disabled', async (t) => { - const { layer, viewer, mounted, created, revoked } = fixture(t); + const { layer, viewer, draw, mounted, created, revoked } = fixture(t); await layer.update(viewer); assert.equal(created.length, 1); assert.equal(revoked.length, 0); assert.equal(mounted.size, 1); assert.equal(layer.getStats().count, 1); + const pins = [...draw.sets.values()].find( + (set) => !set.disposed && set.kind === 'icons', + ); + const [pin] = pins.items.values(); + assert.equal(pin.id, 'ghostmaps:cip:0:0'); + assert.equal(pin.image, 'blob:local-0'); + assert.equal(pin.height, 'clampGround'); + assert.equal(pins.spec.clampTo, 'both'); + assert.equal(pin.disableDepthTest, Infinity); + assert.equal(pin.scale, 0.7); + assert.deepEqual(pin.size, [20, 20], 'unread in Node: the marker size'); layer.disable(); assert.deepEqual(revoked, created); assert.equal(mounted.size, 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 ab5573ede..9c15d4e6a 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'; @@ -187,6 +188,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']); @@ -1392,9 +1443,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}`, @@ -1402,6 +1456,7 @@ export function createCesiumDraw({ uniforms: { reveal }, source: REVEAL_SOURCE, }, + ...translucent, }); const drawn = reveal === undefined ? material : material.materials.revealed; Object.assign(drawn.uniforms, fabric.uniforms); @@ -1474,6 +1529,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`); } @@ -1635,6 +1699,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()) @@ -1642,6 +1728,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' || @@ -1652,6 +1745,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. @@ -1719,8 +1814,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 @@ -1730,6 +1854,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, }); @@ -1738,12 +1865,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; @@ -2002,6 +2132,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; @@ -2028,7 +2159,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; } @@ -2087,9 +2218,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) @@ -2102,7 +2239,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, + }; } /** @@ -2112,6 +2253,7 @@ export function createCesiumDraw({ */ const settles = (item) => item.mode !== 'draped' && + item.frame !== 'inertial' && !item.depthFailColor && item.style.kind === 'solid' && !revealed(item) && @@ -2181,6 +2323,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))) { @@ -2585,8 +2746,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': { @@ -2606,6 +2770,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({ @@ -2641,10 +2813,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) @@ -2661,7 +2838,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; @@ -2677,17 +2854,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 @@ -2733,7 +2922,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), @@ -2746,6 +2937,15 @@ export function createCesiumDraw({ Cesium.MaterialAppearance.MaterialSupport.TEXTURED, translucent: true, flat: true, + ...(batch.rimFill + ? { + closed: false, + faceForward: true, + ...(batch.depthBias + ? { renderState: DEPTH_BIASED_STATE } + : {}), + } + : {}), }), } : {}), @@ -3103,6 +3303,8 @@ export function createCesiumDraw({ beforeRender() { cullHorizon(); runFlows(); + for (const record of sets.values()) + if (record.inertialLines) turnInertial(record); modelSets.beforeRender(sets.values()); quadSets.beforeRender(sets.values()); }, diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index afead0d81..eb4826594 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); @@ -2981,12 +3003,15 @@ test('the FIRMS layer draws its fire glows as one GPU icon set on a viewer of it const at = Cesium.Cartographic.fromCartesian(set.position(strong, tau)); assert.ok(Math.abs(Cesium.Math.toDegrees(at.longitude) + 97.7) < 1e-6); assert.ok(Math.abs(at.height - 40) < 1e-3, 'at its anchor'); - assert.deepEqual(drawHitOf(host._pickObject('firms-0', null, { show: true })), { - set: host.drawSetId, - id: 'firms-0', - meta: { layer: 'firms', id: 'firms-0' }, - surface: false, - }); + assert.deepEqual( + drawHitOf(host._pickObject('firms-0', null, { show: true })), + { + set: host.drawSetId, + id: 'firms-0', + meta: { layer: 'firms', id: 'firms-0' }, + surface: false, + }, + ); // A rebuild that keeps one fire writes nothing for it and drops the other. const written = []; @@ -3071,14 +3096,21 @@ test('the Radio layer draws its stations, clusters and selected marker as point assert.equal(dots.length, 4); assert.ok(dots.every((dot) => dot instanceof Cesium.PointPrimitive)); const lone = dots.find((dot) => dot.show); - assert.equal(lone.id.id, `radio:${stations[3].id}`, 'the others are in a cluster'); + assert.equal( + lone.id.id, + `radio:${stations[3].id}`, + 'the others are in a cluster', + ); assert.equal(lone.pixelSize, 13); assert.equal(lone.outlineWidth, 1); assert.ok(Math.abs(lone.color.alpha - 0.86) < 1e-6); assert.equal(lone.disableDepthTestDistance, Number.POSITIVE_INFINITY); assert.equal(lone.distanceDisplayCondition.far, 50_000_000); assert.equal(lone.scaleByDistance.nearValue, 1.15); - assert.equal(radioStationIdFromPick({ primitive: lone, id: lone.id }), stations[3].id); + assert.equal( + radioStationIdFromPick({ primitive: lone, id: lone.id }), + stations[3].id, + ); const [cluster] = rows(/^radio:\d+:clusters$/); assert.deepEqual( @@ -3087,7 +3119,10 @@ test('the Radio layer draws its stations, clusters and selected marker as point ); assert.equal(cluster.pixelSize, 12 + Math.log2(3) * 1.6); assert.equal(cluster.outlineWidth, 2); - assert.equal(radioStationIdFromPick({ primitive: cluster, id: cluster.id }), stations[0].id); + assert.equal( + radioStationIdFromPick({ primitive: cluster, id: cluster.id }), + stations[0].id, + ); radioLayer.selectStation(stations[3].id, { autoplay: false, focus: false }); const [selected] = rows(/^radio:\d+:selected$/); @@ -3097,7 +3132,10 @@ test('the Radio layer draws its stations, clusters and selected marker as point assert.ok(bracket instanceof Cesium.Billboard); assert.equal(bracket.width, 40); assert.equal(bracket.scaleByDistance.farValue, 0.72); - assert.equal(radioStationIdFromPick({ primitive: bracket, id: bracket.id }), stations[3].id); + assert.equal( + radioStationIdFromPick({ primitive: bracket, id: bracket.id }), + stations[3].id, + ); }); assert.equal(scene.added.length, 0, 'gone with the layer'); }); @@ -5643,3 +5681,171 @@ test('meshes draw their triangles in the frame at their origin', () => assert.equal(host.length, 0); 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 cddeacc54..ff766d960 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -10,11 +10,7 @@ "src/data/geoImportPins.js", "src/input/dispatcher.js", "src/input/sensorPick.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/recentImagery/rendering.js", "src/layers/satellites/rendering.js", "src/layers/traffic/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index e277cd85a..c9946b6b9 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -109,6 +109,12 @@ 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', + // Its pins, footprints and outlines draw through `drawOf`; its horizon + // cull reads the camera and frame ports. + './layers/ghostmaps', ]); /**