diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index dd5d22bfb..d4ded2b2a 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1048,8 +1048,12 @@ Traffic and bikeshare expose factories through `./layers/traffic` and flow matching, styling, viewport lifecycle and development timing. Each source owns its decoded flow cache; cancelled bodies cannot refill it. Bikeshare separates its city registry, station source, parsing, rendering, selection and -proximity lifecycle. Existing standalone sources, live/simulated labels, road -budgets, station availability and polling behavior are retained. +proximity lifecycle; its station dots and selected-station highlight are two +renderer draw sets and it no longer reaches Cesium, so a caller handing it a +Cesium viewer, with no renderer bound, loads the +`./render/cesium/unbound` export once first. Existing standalone sources, +live/simulated labels, road budgets, station availability and polling behavior +are retained. Installations and proximity context now expose `./layers/installations` and `./layers/awareness` factories. Each owns its records, selection, presentation, diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 1aed8938e..bb96d7e9b 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2150,6 +2150,7 @@ "src/layers/bikeshare/index.js", "src/layers/bikeshare/ingestion.js", "src/layers/bikeshare/lifecycle.js", + "src/render/rendererOf.js", "src/layers/bikeshare/model.js", "src/geoDistance.js", "src/sources/gbfsStations.js", @@ -2157,11 +2158,13 @@ "src/layers/bikeshare/queries.js", "src/layers/bikeshare/registry.js", "src/layers/bikeshare/rendering.js", + "src/geo/ellipsoid.js", "src/layers/bikeshare/selection.js", "src/layers/bikeshare/source.js", "src/layers/bikeshare/state.js", "src/layers/bikeshare/testing.js", "src/layers/bikeshare/viewport.js", + "src/geo/vector.js", "src/data/inputOwnership.js", "src/data/cameraSensitivity.js", "src/i18n/index.js", diff --git a/src/data/bikeshare.test.mjs b/src/data/bikeshare.test.mjs index 308135d4a..8bf3de554 100644 --- a/src/data/bikeshare.test.mjs +++ b/src/data/bikeshare.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS, _clearBikeshareSelectionForTest, @@ -19,17 +20,17 @@ function makeRecord() { isInstalled: true, isRenting: false, isReturning: true, - point: { - position: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 2), - show: true, - }, + key: 'austin-capmetro:3790', + position: fromDegrees(-97.7431, 30.2672, 2), + pixelSize: 8, + color: [0, 1, 0, 1], }; } test('selected bikeshare entry preserves source copy and protected-lane policy', () => { const record = makeRecord(); const entry = createBikeshareSelectedOverlayEntry('austin-capmetro:3790', record); - assert.equal(entry.position, record.point.position); + assert.equal(entry.position, record.position); assert.equal(entry.title, 'Congress & 6th'); assert.deepEqual(entry.details, [ '🚲 7 avail Β· 4 docks Β· 11 cap', @@ -44,7 +45,7 @@ test('selected bikeshare entry preserves source copy and protected-lane policy', assert.equal(entry.horizonCull, true); }); -test('real station select/clear path publishes one card and creates no native label graphic', () => { +test('real station select/clear path publishes one card and draws no native label', () => { const calls = []; const overlayHost = { setEntries: (...args) => calls.push(['entries', ...args]), @@ -53,27 +54,36 @@ test('real station select/clear path publishes one card and creates no native la }; const key = 'austin-capmetro:3790'; const record = makeRecord(); - const viewer = { entities: new Cesium.EntityCollection() }; + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); _setBikeshareSelectionStateForTest({ viewer, key, record, overlayHost }); + const live = (suffix) => + [...draw.sets.values()].find((set) => !set.disposed && set.spec.id.endsWith(suffix)); + const stations = live(':stations'); + const selected = live(':selected'); try { _selectBikeshareStationForTest(key); - assert.equal(record.point.show, false); - assert.equal(viewer.entities.values.length, 1, 'runtime guard requires a real selected entity'); - assert.equal(viewer.entities.values[0].label, undefined); - assert.ok(viewer.entities.values[0].point, 'selected point highlight remains native'); + assert.equal(stations.items.get(key).show, false, 'the station’s own dot is hidden'); + assert.equal(selected.items.size, 1, 'one highlight dot replaces it'); + const [highlight] = selected.items.values(); + assert.equal(highlight.pos, record.position); + assert.deepEqual(highlight.color, [0, 1, 1, 1], 'cyan'); + assert.equal(highlight.pixelSize, 14); + assert.equal(highlight.disableDepthTest, Infinity); const publication = calls.find(([type]) => type === 'entries'); assert.ok(publication); assert.equal(publication[1], 'bikeshare-selected'); assert.equal(publication[2].length, 1); - assert.equal(publication[2][0].position, record.point.position); + assert.equal(publication[2][0].position, record.position); assert.deepEqual(publication[3], BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS); _clearBikeshareSelectionForTest(); - assert.equal(record.point.show, true); - assert.equal(viewer.entities.values.length, 0); + assert.equal(stations.items.get(key).show, true); + assert.equal(selected.items.size, 0); assert.deepEqual(calls.at(-1), ['clear', 'bikeshare-selected']); } finally { _clearBikeshareSelectionForTest(); + unbind(); } }); diff --git a/src/data/cameraSensitivity.js b/src/data/cameraSensitivity.js index 87933dc9e..f6d764f72 100644 --- a/src/data/cameraSensitivity.js +++ b/src/data/cameraSensitivity.js @@ -4,9 +4,11 @@ * * `camera.changed` fires once the view has moved by this fraction, and it is a * single number on the camera that every listener in the app shares. Several - * layers want it finer than the default β€” traffic, bikeshare and transit all - * ask for 0.05 so they notice they have entered a coverage area β€” and each of - * them used to write the number directly and hand back whatever it remembered. + * layers want it finer than the default β€” traffic and transit ask for 0.05 so + * they notice they have entered a coverage area (bikeshare did too, before it + * listened through the renderer's camera port at its own threshold) β€” and + * each of them used to write the number directly and hand back whatever it + * remembered. * * That cannot work, because a number is not an owner. Two layers asking for the * same 0.05 write the same value, so when the first one leaves it sees its own diff --git a/src/data/spriteOrder.js b/src/data/spriteOrder.js index 2dd10925c..d0193cb9f 100644 --- a/src/data/spriteOrder.js +++ b/src/data/spriteOrder.js @@ -25,6 +25,35 @@ export function registerSpriteCollection(layerId, collection) { _collections.set(layerId, collection); } +/** + * Register a renderer draw set for a sprite layer, by its set id. The + * default renderer names each set's host primitive with `drawSetId`; the + * restorer raises the host it finds under that name, whichever host the + * set draws with now. + * @param {string} layerId - Stable sprite-order layer key. + * @param {string} setId - The draw set's id. + * @returns {object} The registration, for `unregisterSpriteCollection`'s guard. + */ +export function registerSpriteSet(layerId, setId) { + const entry = Object.freeze({ drawSetId: setId }); + if (layerId && typeof setId === 'string') _collections.set(layerId, entry); + return entry; +} + +/** + * The primitive `entry` names: itself, or a draw set's host found by its id. + * The topmost match wins, so a host still retiring below its replacement is + * skipped. + */ +function resolveSprite(primitives, entry) { + if (typeof entry?.drawSetId !== 'string') return entry; + for (let i = (primitives.length ?? 0) - 1; i >= 0; i--) { + const primitive = primitives.get(i); + if (primitive?.drawSetId === entry.drawSetId) return primitive; + } + return null; +} + /** * Remove a registered collection (primarily useful to lifecycle tests). * @param {string} layerId - Stable sprite-order layer key. @@ -51,7 +80,7 @@ export function restoreSpriteOrder(viewer) { return; for (const layerId of SPRITE_LAYER_ORDER) { - const collection = _collections.get(layerId); + const collection = resolveSprite(primitives, _collections.get(layerId)); if (!collection || collection.isDestroyed?.()) continue; if (primitives.contains?.(collection) === false) continue; primitives.raiseToTop(collection); diff --git a/src/layers/bikeshare/controls.js b/src/layers/bikeshare/controls.js index 5f73a2dc9..a1464330c 100644 --- a/src/layers/bikeshare/controls.js +++ b/src/layers/bikeshare/controls.js @@ -16,7 +16,7 @@ export function createControls({ state: layerState, services, parts, source }) { /** * Return a sampled array of detectable station objects for HUD overlay rendering. * @param {Object} [options] - Sampling options (maxCount, seed). - * @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>} + * @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>} */ getDetectableObjects(options = {}) { return parts.queries.collectDetectableStations(options); diff --git a/src/layers/bikeshare/failureReporting.test.mjs b/src/layers/bikeshare/failureReporting.test.mjs index e49ebd962..bb4c81530 100644 --- a/src/layers/bikeshare/failureReporting.test.mjs +++ b/src/layers/bikeshare/failureReporting.test.mjs @@ -83,7 +83,8 @@ test('a recovered city clears its own failure', () => { // drive the real proximity check, status poll and lifecycle against a fake // GBFS source, so the failure state they read is the state the layer builds. -import * as Cesium from 'cesium'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import { CITY_BY_ID } from './registry.js'; import { createIngestion } from './ingestion.js'; import { createModel } from './model.js'; @@ -195,21 +196,9 @@ function makeLiveLayer() { parts.lifecycle = createLifecycle(context); const { methods: controls } = createControls(context); - const camera = { ...BETWEEN, height: LOW_M }; - const viewer = { - camera: { - get positionCartographic() { - return Cesium.Cartographic.fromDegrees( - camera.lon, - camera.lat, - camera.height, - ); - }, - computeViewRectangle: () => undefined, - changed: { addEventListener() {}, removeEventListener() {} }, - }, - scene: { globe: {}, primitives: { add() {}, remove() {} } }, - }; + const camera = fakeCameraPort({ pose: { ...BETWEEN, height: LOW_M } }); + const viewer = {}; + bindFakeDraw(viewer, { camera: camera.port }); parts.lifecycle.methods.init(viewer); return { @@ -217,7 +206,7 @@ function makeLiveLayer() { source, stats: () => controls.getStats(), moveTo(place, height = LOW_M) { - Object.assign(camera, place, { height }); + camera.setPose({ ...place, height }); return parts.viewport.runProximityCheck(); }, async enable() { diff --git a/src/layers/bikeshare/lifecycle.js b/src/layers/bikeshare/lifecycle.js index d6086b78c..2da7ee865 100644 --- a/src/layers/bikeshare/lifecycle.js +++ b/src/layers/bikeshare/lifecycle.js @@ -1,10 +1,9 @@ -import * as Cesium from 'cesium'; import { GBFS_CITY_REGISTRY } from './registry.js'; -import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID } from './policy.js'; import { - claimCameraSensitivity, - releaseCameraSensitivity, -} from '../../data/cameraSensitivity.js'; + BIKESHARE_SELECTED_OVERLAY_SOURCE_ID, + CAMERA_CHANGED_THRESHOLD, +} from './policy.js'; +import { cameraOf } from '../../render/rendererOf.js'; export function createLifecycle({ state: layerState, @@ -12,28 +11,31 @@ export function createLifecycle({ parts, source, }) { - const { registerSpriteCollection, restoreSpriteOrder } = services.sprites; + const { restoreSpriteOrder } = services.sprites; const { registerPickOwner, unregisterPickOwner } = services.picking; + /** Stop listening to the camera, if the layer is. */ + function detachCamera() { + layerState._cameraChangedOff?.(); + layerState._cameraChangedOff = null; + } + const methods = { /** - * Initialize the bikeshare layer. Creates the point primitive collection, - * resets all internal state, and installs the click handler. - * Called once during app bootstrap. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. + * Initialize the bikeshare layer. Makes the station draw sets on the + * viewer's renderer (`drawOf`), resets all internal state, and installs + * the click handler. Called once during app bootstrap. Given a Cesium + * viewer with no renderer bound, the caller loads + * the package's `./render/cesium/unbound` export first. + * @param {object} viewer - The viewer the layer draws on. */ init(viewer) { + parts.rendering.attachSets(viewer); layerState._viewer = viewer; - layerState._pointCollection = new Cesium.PointPrimitiveCollection({ - blendOption: Cesium.BlendOption.TRANSLUCENT, - }); - viewer.scene.primitives.add(layerState._pointCollection); - registerSpriteCollection('bikeshare', layerState._pointCollection); - layerState._pointCollection.show = false; layerState._enabled = false; layerState._cameraDebounceTimer = null; - layerState._cameraChangedAttached = false; + detachCamera(); layerState._altitudeGateEnabled = false; layerState._proximityGeneration = 0; @@ -46,7 +48,6 @@ export function createLifecycle({ layerState._stationRenderMap = new Map(); layerState._clickSubscription = null; layerState._selectedKey = null; - layerState._selectedEntity = null; layerState._count = 0; layerState._lastUpdate = null; layerState._loading = false; @@ -71,12 +72,12 @@ export function createLifecycle({ /** * Enable the bikeshare layer. Shows points, attaches the camera listener, * and triggers an initial proximity check. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. + * @param {object} viewer - The viewer the layer draws on. */ enable(viewer) { layerState._enabled = true; layerState._failedCityIds.clear(); - layerState._pointCollection.show = true; + layerState._stationSet.show = true; layerState._overlayHost.setVisible( BIKESHARE_SELECTED_OVERLAY_SOURCE_ID, true, @@ -87,13 +88,13 @@ export function createLifecycle({ layerState._stationRenderMap.has(pickedId), ); - if (!layerState._cameraChangedAttached) { - viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged); - // Through the shared ledger: this is a single number every layer's - // camera.changed listener shares, and a layer leaving must not hand - // back a coarse default while this one is still driving off it. - claimCameraSensitivity(viewer.camera, 'bikeshare', 0.05); - layerState._cameraChangedAttached = true; + if (!layerState._cameraChangedOff) { + // Its own threshold: the camera measures it for this listener alone. + layerState._cameraChangedOff = cameraOf(viewer).on( + 'changed', + parts.viewport.onCameraChanged, + { threshold: CAMERA_CHANGED_THRESHOLD }, + ); } void parts.viewport.runProximityCheck(); @@ -103,9 +104,8 @@ export function createLifecycle({ /** * Disable the bikeshare layer. Hides points, removes event listeners, * aborts all pending fetches, and tears down all city data. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. */ - disable(viewer) { + disable() { layerState._enabled = false; layerState._proximityGeneration++; layerState._altitudeGateEnabled = false; @@ -122,26 +122,20 @@ export function createLifecycle({ document.removeEventListener('keydown', parts.selection._onKeyDown); unregisterPickOwner('bikeshare'); - if (layerState._cameraChangedAttached) { - viewer.camera.changed.removeEventListener( - parts.viewport.onCameraChanged, - ); - releaseCameraSensitivity(viewer.camera, 'bikeshare'); - layerState._cameraChangedAttached = false; - } + detachCamera(); parts.ingestion.abortAllInFlight(); parts.viewport.deactivateAllCities(); layerState._cityRuntime.clear(); - layerState._pointCollection.show = false; + if (layerState._stationSet) layerState._stationSet.show = false; layerState._count = 0; layerState._loading = false; layerState._loadingOps = 0; }, - /** Permanently release primitives, handlers, and the selected host source. */ - destroy(viewer) { - if (layerState._enabled) this.disable(viewer); + /** Permanently release draw sets, handlers, and the selected host source. */ + destroy() { + if (layerState._enabled) this.disable(); else { parts.selection._clearSelection(); layerState._overlayHost.setVisible( @@ -153,18 +147,9 @@ export function createLifecycle({ document.removeEventListener('keydown', parts.selection._onKeyDown); unregisterPickOwner('bikeshare'); } - if (layerState._cameraChangedAttached) { - viewer.camera.changed.removeEventListener( - parts.viewport.onCameraChanged, - ); - releaseCameraSensitivity(viewer.camera, 'bikeshare'); - layerState._cameraChangedAttached = false; - } + detachCamera(); parts.ingestion.abortAllInFlight(); - if (layerState._pointCollection) { - viewer.scene.primitives.remove(layerState._pointCollection); - layerState._pointCollection = null; - } + parts.rendering.detachSets(); layerState._viewer = null; }, }; diff --git a/src/layers/bikeshare/policy.js b/src/layers/bikeshare/policy.js index 1b9c1579f..cf928a9da 100644 --- a/src/layers/bikeshare/policy.js +++ b/src/layers/bikeshare/policy.js @@ -1,5 +1,3 @@ -import * as Cesium from 'cesium'; - export const BIKESHARE_SELECTED_OVERLAY_SOURCE_ID = 'bikeshare-selected'; export const BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS = Object.freeze({ @@ -25,6 +23,13 @@ export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000; export const CAMERA_DEBOUNCE_MS = 340; +/** + * How far the view moves before the camera tells the layer (the camera's + * `changed` threshold): fine, so it notices entering a city's range. + */ + +export const CAMERA_CHANGED_THRESHOLD = 0.05; + /** Default radius (km) for determining whether a city is in camera range. */ export const CITY_RANGE_BASE_KM = 100; @@ -55,31 +60,74 @@ export const POINT_HEIGHT_OFFSET_M = 2.0; export const MAX_TOTAL_POINTS = 8000; // --- Availability color palette --- +// Renderer colours, `[r, g, b, a]` in 0..1: the CSS colours below at the +// alphas the points draw them with. + +/** A CSS `#rrggbb` colour at `alpha`, as a renderer colour. */ +const hex = (css, alpha) => + Object.freeze([ + parseInt(css.slice(1, 3), 16) / 255, + parseInt(css.slice(3, 5), 16) / 255, + parseInt(css.slice(5, 7), 16) / 255, + alpha, + ]); + /** Station has >60% bikes available. */ -export const COLOR_GREEN = - Cesium.Color.fromCssColorString('#00ff88').withAlpha(0.95); +export const COLOR_GREEN = hex('#00ff88', 0.95); /** Station has 30-60% bikes available. */ -export const COLOR_YELLOW = - Cesium.Color.fromCssColorString('#ffaa00').withAlpha(0.94); +export const COLOR_YELLOW = hex('#ffaa00', 0.94); /** Station has <30% bikes available. */ -export const COLOR_RED = - Cesium.Color.fromCssColorString('#ff4444').withAlpha(0.94); +export const COLOR_RED = hex('#ff4444', 0.94); /** No status data available for station. */ -export const COLOR_NEUTRAL = - Cesium.Color.fromCssColorString('#91a4b4').withAlpha(0.62); +export const COLOR_NEUTRAL = hex('#91a4b4', 0.62); /** Station is offline (not installed, not renting, or not returning). */ -export const COLOR_MUTED = - Cesium.Color.fromCssColorString('#687581').withAlpha(0.48); +export const COLOR_MUTED = hex('#687581', 0.48); /** Outline color for all station points. */ -export const COLOR_OUTLINE = Cesium.Color.BLACK.withAlpha(0.25); +export const COLOR_OUTLINE = Object.freeze([0, 0, 0, 0.25]); + +// --- Selected-station highlight --- + +/** The selected station's dot: cyan, outlined black, drawn over everything. */ + +export const SELECTED_POINT_STYLE = Object.freeze({ + pixelSize: 14, + color: Object.freeze([0, 1, 1, 1]), + outlineColor: Object.freeze([0, 0, 0, 1]), + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, +}); + +// --- Station dot distance falloff --- + +/** Station dots grow near the eye and shrink far from it. */ + +export const POINT_SCALE_BY_DISTANCE = Object.freeze({ + near: 200, + nearValue: 1.35, + far: 130000, + farValue: 0.4, +}); + +/** Station dots fade out with distance. */ + +export const POINT_FADE_BY_DISTANCE = Object.freeze({ + near: 200, + nearValue: 1.0, + far: 180000, + farValue: 0.15, +}); + +/** Station dots draw over the ground within this many metres of the eye. */ + +export const POINT_DISABLE_DEPTH_TEST_M = 2500; diff --git a/src/layers/bikeshare/proxyRoute.test.mjs b/src/layers/bikeshare/proxyRoute.test.mjs index 05e31fc03..58a63af6f 100644 --- a/src/layers/bikeshare/proxyRoute.test.mjs +++ b/src/layers/bikeshare/proxyRoute.test.mjs @@ -459,7 +459,7 @@ test('a station without a published capacity re-derives it from every status pol const state = { _cityRuntime: new Map(), _stationRenderMap: new Map(), - _pointCollection: { add: (options) => ({ ...options }) }, + _stationSet: { upsert() {}, remove() {} }, }; const rendering = createRendering({ state, @@ -502,7 +502,7 @@ test('a station without a published capacity re-derives it from every status pol { station_id: 'fixed', num_bikes_available: 2, num_docks_available: 3 }, ]); assert.equal(open.capacity, 30, 'the first poll fixed the capacity'); - assert.equal(open.point.color, COLOR_YELLOW, '10 of 30 is not plenty'); + assert.equal(open.color, COLOR_YELLOW, '10 of 30 is not plenty'); assert.equal(fixed.capacity, 13, 'a published capacity is kept'); poll([ diff --git a/src/layers/bikeshare/queries.js b/src/layers/bikeshare/queries.js index 550dbf030..06d9bec0f 100644 --- a/src/layers/bikeshare/queries.js +++ b/src/layers/bikeshare/queries.js @@ -26,24 +26,23 @@ export function createQueries({ state: layerState, services, parts, source }) { * @param {Object} [options] * @param {number} [options.maxCount] - Maximum number of detectable objects to return. * @param {number} [options.seed] - Seed for deterministic stride offset selection. - * @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>} + * @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>} */ function collectDetectableStations(options = {}) { if ( !layerState._enabled || - !layerState._pointCollection || - !layerState._pointCollection.show || + !layerState._stationSet || + !layerState._stationSet.show || layerState._stationRenderMap.size === 0 ) return []; - // Gather all visible station records (include selected even though its point is hidden) + // Gather all station records (the selected one too, though its own dot + // is hidden under the highlight) const records = []; for (const record of layerState._stationRenderMap.values()) { - const isSelected = record.key === layerState._selectedKey; - if ((!record.point?.show && !isSelected) || !record.point?.position) - continue; + if (!record.position) continue; records.push(record); } if (records.length === 0) return []; @@ -60,7 +59,7 @@ export function createQueries({ state: layerState, services, parts, source }) { for (let i = start; i < records.length; i += stride) { const record = records[i]; result.push({ - position: record.point.position, + position: record.position, sourceId: record.key, id: buildDetectionId(record), type: 'VEH', diff --git a/src/layers/bikeshare/rendering.js b/src/layers/bikeshare/rendering.js index 70f319967..073617359 100644 --- a/src/layers/bikeshare/rendering.js +++ b/src/layers/bikeshare/rendering.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { DEFAULT_CAPACITY, POINT_SIZE_MIN, @@ -11,8 +10,21 @@ import { POINT_HEIGHT_OFFSET_M, MAX_TOTAL_POINTS, COLOR_OUTLINE, + POINT_SCALE_BY_DISTANCE, + POINT_FADE_BY_DISTANCE, + POINT_DISABLE_DEPTH_TEST_M, } from './policy.js'; import { heightsFor } from '../../queries/heights.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { drawOf } from '../../render/rendererOf.js'; + +/** + * The draw sets the stations are drawn in start with this; each layer has + * its own (`bikeshare:1:stations`, `bikeshare:1:selected`), so several can + * share a renderer. Picks name them as `Hit.set`. + */ +export const BIKESHARE_SET_ID = 'bikeshare'; +let instances = 0; export function createRendering({ state: layerState, @@ -22,6 +34,68 @@ export function createRendering({ }) { const { governorRequestRender } = services.render; + /** + * Make the layer's draw sets on `viewer`'s renderer (`drawOf`): the + * station dots, hidden until the layer is enabled, and the selected + * station's highlight. Sets made before are let go first. + * @param {object} viewer + */ + function attachSets(viewer) { + const draw = drawOf(viewer); + detachSets(); + const prefix = `${BIKESHARE_SET_ID}:${++instances}`; + layerState._stationSet = draw.points({ + id: `${prefix}:stations`, + blend: 'translucent', + show: false, + }); + layerState._selectedSet = draw.points({ id: `${prefix}:selected` }); + // Drawn from the start, empty, so both take their place in the scene + // now, as the layer's collections did; the stations' place among the + // other sprite layers is the sprite order's (`restoreSpriteOrder`). + layerState._stationSet.set([]); + layerState._selectedSet.set([]); + layerState._spriteEntry = services.sprites?.registerSpriteSet?.( + 'bikeshare', + layerState._stationSet.id, + ); + } + + /** Let the layer's draw sets go. */ + function detachSets() { + if (layerState._spriteEntry) + services.sprites?.unregisterSpriteCollection?.( + 'bikeshare', + layerState._spriteEntry, + ); + layerState._spriteEntry = null; + layerState._stationSet?.dispose(); + layerState._selectedSet?.dispose(); + layerState._stationSet = null; + layerState._selectedSet = null; + } + + /** + * A station's dot, from its render record; the selected station's own dot + * is hidden while its highlight replaces it. + * @param {Object} record - Render record from _stationRenderMap. + * @returns {import('../../render/contract/draw').PointItem} + */ + function stationItem(record) { + return { + id: record.key, + pos: record.position, + pixelSize: record.pixelSize, + color: record.color, + outlineColor: COLOR_OUTLINE, + outlineWidth: 1, + scaleByDistance: POINT_SCALE_BY_DISTANCE, + fadeByDistance: POINT_FADE_BY_DISTANCE, + disableDepthTest: POINT_DISABLE_DEPTH_TEST_M, + show: record.key !== layerState._selectedKey, + }; + } + /** * Resolve the effective dock capacity for a station. * Prefers the explicit capacity from station_information; falls back to @@ -69,7 +143,7 @@ export function createRendering({ * - <30% bikes available: red. * @param {Object|null} status - Station status object. * @param {number} capacity - Resolved station capacity. - * @returns {Cesium.Color} Color to apply to the station point. + * @returns {readonly number[]} Renderer colour `[r, g, b, a]` for the station point. */ function statusToColor(status, capacity) { @@ -88,10 +162,10 @@ export function createRendering({ } /** - * Create a Cartesian3 position for a station, terrain-clamped when possible. + * The ECEF position for a station, on the sampled surface when possible. * Falls back to a fixed small height offset if terrain sampling is unsupported. * @param {Object} station - Station info object with lat/lon. - * @returns {Cesium.Cartesian3|null} World position, or null if coordinates are invalid. + * @returns {{x: number, y: number, z: number}|null} ECEF metres, or null if coordinates are invalid. */ function createStationPosition(station) { @@ -107,7 +181,7 @@ export function createRendering({ if (sampled !== null) height = sampled + POINT_HEIGHT_OFFSET_M; } - return Cesium.Cartesian3.fromDegrees(lon, lat, height); + return fromDegrees(lon, lat, height); } /** @@ -125,8 +199,8 @@ export function createRendering({ } /** - * Ensure point primitives exist for all stations in a city. - * Creates new points for stations not yet rendered; skips existing ones. + * Ensure dots exist for all stations in a city. + * Creates new dots for stations not yet rendered; skips existing ones. * Respects the MAX_TOTAL_POINTS global cap to prevent GPU overload. * @param {string} cityId - City identifier. * @param {Map} stationMap - Parsed station info map for the city. @@ -138,6 +212,7 @@ export function createRendering({ governorRequestRender('bikeshare-points'); const runtime = ensureCityRuntime(cityId); + const added = []; for (const station of stationMap.values()) { const key = parts.model.stationKey(cityId, station.stationId); if (layerState._stationRenderMap.has(key)) { @@ -159,30 +234,14 @@ export function createRendering({ const position = createStationPosition(station); if (!position) continue; - // Add a point primitive with distance-based scale and translucency falloff - const point = layerState._pointCollection.add({ - position, - pixelSize: capacityToPixelSize(station.capacity), - color: COLOR_NEUTRAL, - outlineColor: COLOR_OUTLINE, - outlineWidth: 1, - scaleByDistance: new Cesium.NearFarScalar(200, 1.35, 130000, 0.4), - translucencyByDistance: new Cesium.NearFarScalar( - 200, - 1.0, - 180000, - 0.15, - ), - disableDepthTestDistance: 2500, - id: key, - }); - - layerState._stationRenderMap.set(key, { + const record = { key, cityId, stationId: station.stationId, stationName: station.name, - point, + position, + pixelSize: capacityToPixelSize(station.capacity), + color: COLOR_NEUTRAL, capacity: parts.model.toNonNegativeInteger(station.capacity), publishedCapacity: parts.model.toNonNegativeInteger(station.capacity), bikesAvailable: null, @@ -190,16 +249,20 @@ export function createRendering({ isInstalled: station.isInstalled, isRenting: station.isRenting, isReturning: station.isReturning, - }); + }; + layerState._stationRenderMap.set(key, record); + // A dot with distance-based scale and translucency falloff. + added.push(stationItem(record)); runtime.stationKeys.add(key); } + if (added.length) layerState._stationSet?.upsert(added); layerState._count = layerState._stationRenderMap.size; } /** - * Remove all rendered point primitives for a city and clean up runtime state. + * Remove all rendered dots for a city and clean up runtime state. * Also clears any active selection if it belongs to this city. * @param {string} cityId - City identifier to remove. */ @@ -216,12 +279,13 @@ export function createRendering({ parts.selection._clearSelection(); } + const removed = []; for (const key of runtime.stationKeys) { - const record = layerState._stationRenderMap.get(key); - if (!record) continue; - layerState._pointCollection.remove(record.point); + if (!layerState._stationRenderMap.has(key)) continue; + removed.push(key); layerState._stationRenderMap.delete(key); } + if (removed.length) layerState._stationSet?.remove(removed); layerState._cityRuntime.delete(cityId); layerState._count = layerState._stationRenderMap.size; @@ -240,6 +304,7 @@ export function createRendering({ const runtime = layerState._cityRuntime.get(cityId); if (!runtime) return; + const updated = []; for (const key of runtime.stationKeys) { const record = layerState._stationRenderMap.get(key); if (!record) continue; @@ -266,11 +331,16 @@ export function createRendering({ ); // Update visual properties based on current status - record.point.pixelSize = capacityToPixelSize(capacity); - record.point.color = statusToColor(status, capacity); + record.pixelSize = capacityToPixelSize(capacity); + record.color = statusToColor(status, capacity); + updated.push(stationItem(record)); } + if (updated.length) layerState._stationSet?.upsert(updated); } return { + attachSets, + detachSets, + stationItem, resolveCapacity, capacityToPixelSize, statusToColor, diff --git a/src/layers/bikeshare/selection.js b/src/layers/bikeshare/selection.js index f293dcaac..bbf962d8d 100644 --- a/src/layers/bikeshare/selection.js +++ b/src/layers/bikeshare/selection.js @@ -1,9 +1,9 @@ -import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; import { inputFor } from '../../input/dispatcher.js'; import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID, BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS, + SELECTED_POINT_STYLE, } from './policy.js'; export function createSelection({ @@ -63,7 +63,7 @@ export function createSelection({ */ function createBikeshareSelectedOverlayEntry(key, record) { - const position = record?.point?.position; + const position = record?.position; if (!key || !position) return null; const [title, ...details] = buildSelectionLabel(record).split('\n'); return { @@ -91,29 +91,22 @@ export function createSelection({ /** * Clear the current station selection. - * Re-shows the hidden point primitive and removes the highlight entity. + * Shows the station's own dot again and removes the highlight. */ function _clearSelection() { - if (layerState._selectedKey) { - const record = layerState._stationRenderMap.get(layerState._selectedKey); - if (record?.point) { - record.point.show = true; - } - } - - if (layerState._selectedEntity && layerState._viewer) { - layerState._viewer.entities.remove(layerState._selectedEntity); - } - + const key = layerState._selectedKey; layerState._selectedKey = null; - layerState._selectedEntity = null; + const record = key ? layerState._stationRenderMap.get(key) : null; + if (record?.position) + layerState._stationSet?.upsert([parts.rendering.stationItem(record)]); + if (layerState._selectedSet?.size()) layerState._selectedSet.clear(); layerState._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID); } /** - * Select a station by key: hides the original point primitive and adds a - * highlighted cyan entity plus a protected shared-host availability card. + * Select a station by key: hides its own dot and draws a highlighted cyan + * one in its place, plus a protected shared-host availability card. * @param {string} key - Composite "cityId:stationId" key. */ @@ -121,22 +114,14 @@ export function createSelection({ _clearSelection(); const record = layerState._stationRenderMap.get(key); - if (!record || !record.point?.position || !layerState._viewer) return; + if (!record || !record.position || !layerState._stationSet) return; layerState._selectedKey = key; - // Hide the base point so the highlight entity replaces it visually - record.point.show = false; - - layerState._selectedEntity = layerState._viewer.entities.add({ - position: record.point.position, - point: { - pixelSize: 14, - color: Cesium.Color.CYAN, - outlineColor: Cesium.Color.BLACK, - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + // Hide the base dot so the highlight replaces it visually + layerState._stationSet.upsert([parts.rendering.stationItem(record)]); + layerState._selectedSet?.set([ + { id: 'selected', pos: record.position, ...SELECTED_POINT_STYLE }, + ]); const entry = createBikeshareSelectedOverlayEntry(key, record); if (entry) { layerState._overlayHost.setEntries( @@ -151,39 +136,30 @@ export function createSelection({ * Install a screen-space click handler for station selection/deselection. * Also registers a global keydown listener for Escape-to-deselect. * Idempotent β€” does nothing if a handler is already installed. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. + * @param {object} viewer - The viewer the layer draws on. */ function _installClickHandler(viewer) { if (layerState._clickSubscription) return; layerState._clickSubscription = inputFor(viewer).onClick((event) => { - const picked = event.pick; + const hit = event.drawHit; - if (picked) { - // Clicking selected entity itself β€” ignore (don't deselect). - if (picked.id === layerState._selectedEntity) return; + if (hit) { + // Clicking the selected highlight itself β€” ignore (don't deselect). + if (hit.set === layerState._selectedSet?.id) return; - // Check if the picked primitive or entity id matches a station key - const primitive = picked.primitive; + // A station dot of this layer's own set if ( - primitive && - typeof primitive.id === 'string' && - layerState._stationRenderMap.has(primitive.id) + hit.set === layerState._stationSet?.id && + layerState._stationRenderMap.has(hit.id) ) { - _selectStation(primitive.id); - return; - } - if ( - typeof picked.id === 'string' && - layerState._stationRenderMap.has(picked.id) - ) { - _selectStation(picked.id); + _selectStation(hit.id); return; } } - // Clicked empty space β€” deselect. + // Clicked anything else β€” deselect. if (layerState._selectedKey) _clearSelection(); }); diff --git a/src/layers/bikeshare/state.js b/src/layers/bikeshare/state.js index bc63d081f..0b7ab7e9d 100644 --- a/src/layers/bikeshare/state.js +++ b/src/layers/bikeshare/state.js @@ -15,13 +15,21 @@ export function createState({ services }) { // Module-level mutable state // --------------------------------------------------------------------------- - /** @type {Cesium.Viewer|null} Active Cesium viewer instance. */ + /** @type {object|null} The viewer the layer draws on. */ layerState._viewer = null; - /** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */ + /** Draw set of the station dots (`drawOf(viewer).points`), or null. */ - layerState._pointCollection = null; + layerState._stationSet = null; + + /** Draw set of the selected station's highlight dot, or null. */ + + layerState._selectedSet = null; + + /** The station set's sprite-order registration, while it has one. */ + + layerState._spriteEntry = null; /** Whether the bikeshare layer is currently enabled. */ @@ -31,9 +39,9 @@ export function createState({ services }) { layerState._cameraDebounceTimer = null; - /** Whether the camera.changed listener is currently attached. */ + /** @type {(() => void)|null} Stops the camera `changed` listener, while attached. */ - layerState._cameraChangedAttached = false; + layerState._cameraChangedOff = null; /** Hysteresis flag for altitude-based activation. */ @@ -79,10 +87,6 @@ export function createState({ services }) { layerState._selectedKey = null; - /** @type {Cesium.Entity|null} Entity used to display the selected-station point highlight. */ - - layerState._selectedEntity = null; - /** Total number of currently rendered station points. */ layerState._count = 0; diff --git a/src/layers/bikeshare/testing.js b/src/layers/bikeshare/testing.js index 6dca0e658..22f1b24ca 100644 --- a/src/layers/bikeshare/testing.js +++ b/src/layers/bikeshare/testing.js @@ -8,9 +8,9 @@ export function createTesting({ state: layerState, services, parts, source }) { overlayHost, }) { layerState._viewer = viewer; + parts.rendering.attachSets(viewer); layerState._stationRenderMap = new Map([[key, record]]); layerState._selectedKey = null; - layerState._selectedEntity = null; layerState._overlayHost = overlayHost || layerState.DEFAULT_OVERLAY_HOST; } diff --git a/src/layers/bikeshare/viewport.js b/src/layers/bikeshare/viewport.js index 25a4df7d0..bec59e9c6 100644 --- a/src/layers/bikeshare/viewport.js +++ b/src/layers/bikeshare/viewport.js @@ -1,4 +1,5 @@ -import * as Cesium from 'cesium'; +import { negativePiToPi, toDegrees, toRadians } from '../../geo/vector.js'; +import { findCamera } from '../../render/rendererOf.js'; import { GBFS_CITY_REGISTRY } from './registry.js'; import { ACTIVATION_EXIT_ALTITUDE_M, @@ -12,44 +13,42 @@ export function createViewport({ state: layerState, services, parts, source }) { /** * Get the camera's current altitude in meters above the ellipsoid. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. + * @param {object} viewer - The viewer the layer draws on. * @returns {number} Altitude in meters, or Infinity if unavailable. */ function getCameraAltitude(viewer) { - const carto = viewer?.camera?.positionCartographic; - return carto && Number.isFinite(carto.height) ? carto.height : Infinity; + const height = findCamera(viewer)?.pose().height; + return Number.isFinite(height) ? height : Infinity; } /** * Determine the lat/lon the camera is currently looking at. - * Prefers the center of the computed view rectangle; falls back to the - * camera's own cartographic position when the rectangle is unavailable. - * @param {Cesium.Viewer} viewer - Cesium viewer instance. + * Prefers the center of the view rectangle; falls back to the camera's + * own position when the rectangle is unavailable. + * @param {object} viewer - The viewer the layer draws on. * @returns {{ lat: number, lon: number }|null} Center coordinates in degrees, or null. */ function getCameraCenterLatLon(viewer) { + const camera = findCamera(viewer); // Try view rectangle center first (more accurate for tilted views) - const rect = viewer?.camera?.computeViewRectangle?.( - viewer.scene.globe?.ellipsoid, - ); + const rect = camera?.viewRectangle(); if (rect) { - const center = Cesium.Rectangle.center(rect); + // Across the antimeridian the east edge is west of the west one. + let east = toRadians(rect.east); + const west = toRadians(rect.west); + if (east < west) east += 2 * Math.PI; return { - lat: Cesium.Math.toDegrees(center.latitude), - lon: Cesium.Math.toDegrees(center.longitude), + lat: (rect.south + rect.north) * 0.5, + lon: toDegrees(negativePiToPi((west + east) * 0.5)), }; } // Fallback: use the camera's own position - const carto = viewer?.camera?.positionCartographic; - if (carto) { - return { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; - } + const pose = camera?.pose(); + if (pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon)) + return { lat: pose.lat, lon: pose.lon }; return null; } diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 948449730..e84bbef7b 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -43,6 +43,8 @@ import { uninstallRenderGovernor, } from '../../renderGovernor.js'; import { fakeInput } from '../../input/testDoubles.mjs'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { bindRenderer } from '../../render/rendererOf.js'; import { framePortFor } from '../../testSupport/fakeFramePort.mjs'; import { registerStyleStages } from '../../styles/styleStages.js'; @@ -3561,7 +3563,7 @@ test('reject then selected history backfill cannot resurrect a 111 km displaceme assert.equal(entry.track.resets, 0); }); -test('actual Traffic, Bikeshare and Transit lifecycles retain sensitivity in every enable/disable order', async (t) => { +test('actual Traffic and Transit lifecycles retain sensitivity in every enable/disable order, Bikeshare among them', async (t) => { const { createLifecycle: trafficLifecycle } = await import('../traffic/lifecycle.js'); const { createLifecycle: bikeLifecycle } = @@ -3583,7 +3585,7 @@ test('actual Traffic, Bikeshare and Transit lifecycles retain sensitivity in eve }).methods; const bike = bikeLifecycle({ state: { - _pointCollection: {}, + _stationSet: {}, _overlayHost: { setVisible: noop }, _cityRuntime: new Map(), _failedCityIds: new Set(), @@ -3608,7 +3610,21 @@ test('actual Traffic, Bikeshare and Transit lifecycles retain sensitivity in eve }, }).methods; app.viewer.camera.moveEnd = new Cesium.Event(); - const layers = { traffic, bikeshare: bike, transit: app.layer }; + // Bikeshare listens through its renderer's camera port, at its own + // threshold: it takes no claim on the shared camera's sensitivity. + const bikeCamera = fakeCameraPort(); + const bikeViewer = {}; + const unbindBike = bindRenderer(bikeViewer, { camera: bikeCamera.port }); + t.after(unbindBike); + const layers = { + traffic, + bikeshare: { + enable: () => bike.enable(bikeViewer), + disable: () => bike.disable(bikeViewer), + }, + transit: app.layer, + }; + const claimants = new Set(['traffic', 'transit']); const orders = [ ['traffic', 'bikeshare', 'transit'], ['traffic', 'transit', 'bikeshare'], @@ -3623,8 +3639,13 @@ test('actual Traffic, Bikeshare and Transit lifecycles retain sensitivity in eve const active = new Set(); for (const id of enable) { layers[id].enable(app.viewer); - active.add(id); - assert.equal(app.viewer.camera.percentageChanged, 0.05); + if (claimants.has(id)) active.add(id); + if (id === 'bikeshare') + assert.equal(bikeCamera.listenerCount('changed'), 1); + assert.equal( + app.viewer.camera.percentageChanged, + active.size ? 0.05 : 0.5, + ); assert.deepEqual( new Set(cameraSensitivityClaims(app.viewer.camera)), active, @@ -3643,6 +3664,7 @@ test('actual Traffic, Bikeshare and Transit lifecycles retain sensitivity in eve active, ); } + assert.equal(bikeCamera.listenerCount('changed'), 0); } } finally { for (const layer of Object.values(layers)) layer.disable(app.viewer); diff --git a/src/overlays/worldOverlayAllocation.worker.mjs b/src/overlays/worldOverlayAllocation.worker.mjs index 30ee4d7f1..520484162 100644 --- a/src/overlays/worldOverlayAllocation.worker.mjs +++ b/src/overlays/worldOverlayAllocation.worker.mjs @@ -805,7 +805,7 @@ function buildPhase5BikeshareWorkload(count) { isInstalled: true, isRenting: true, isReturning: true, - point: { position }, + position, }); entry.horizonCull = false; workload.registrations.push({ diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index c25956202..0ee68c83d 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -67,6 +67,24 @@ const classificationOf = (clampTo = 'both') => tiles: Cesium.ClassificationType.CESIUM_3D_TILE, })[clampTo] ?? Cesium.ClassificationType.BOTH; +/** A distance curve as Cesium's, or undefined. */ +const nearFarOf = (curve) => + curve + ? new Cesium.NearFarScalar( + curve.near, + curve.nearValue, + curve.far, + curve.farValue, + ) + : undefined; + +/** Cesium's point blending for a set's `blend`. */ +const pointBlendOf = (blend) => + ({ + opaque: Cesium.BlendOption.OPAQUE, + translucent: Cesium.BlendOption.TRANSLUCENT, + })[blend] ?? Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT; + const ANCHORS = { center: Cesium.VerticalOrigin.CENTER, bottom: Cesium.VerticalOrigin.BOTTOM, @@ -115,6 +133,7 @@ export function createCesiumDraw({ scene, report }) { const rebuild = () => { record.pickIds = []; record.placed = []; + record.patchable = null; build(record); setsVersion += 1; }; @@ -128,6 +147,13 @@ export function createCesiumDraw({ scene, report }) { requestRender(); }, upsert(list) { + // Items that only change how they look are changed where they are. + if (patchPoints(record, list)) { + for (const item of list) items.set(item.id, item); + setsVersion += 1; + requestRender(); + return; + } for (const item of list) items.set(item.id, item); rebuild(); requestRender(); @@ -145,9 +171,10 @@ export function createCesiumDraw({ scene, report }) { setOptions(options) { const culled = spec.horizonCull; const clampTo = spec.clampTo; + const blend = spec.blend; Object.assign(spec, options); - // What clamped items clamp to is built into them. - if (spec.clampTo !== clampTo) rebuild(); + // What clamped items clamp to, and how points blend, are built in. + if (spec.clampTo !== clampTo || spec.blend !== blend) rebuild(); setsVersion += 1; showHosts(record); // No longer culled: what the cull hid comes back. @@ -203,6 +230,17 @@ export function createCesiumDraw({ scene, report }) { function replaceHost(record, host, ground = null, own = null) { const old = record.host; const waiting = ground?.length ? ground : null; + // The set keeps its place among the scene's primitives: a rebuild draws + // where it drew, so stacking (and picks among overlapping items) does + // not change with each update. Its place is under whatever was above + // the host it replaces (indices shift as older hosts go). + const slot = old ? slotOf(old) : -1; + const above = + slot >= 0 && slot + 1 < scene.primitives.length + ? scene.primitives.get(slot + 1) + : null; + // Named for code that orders the scene's primitives (`spriteOrder.js`). + host.drawSetId = record.spec.id; // Only old ground primitives wait for the new ones: the rest of the old // host goes now, as the new host's own parts draw at once. if ( @@ -222,10 +260,20 @@ export function createCesiumDraw({ scene, report }) { record.ground = waiting; record.own = waiting ? own : null; record.host = host; - scene.primitives.add(host); + const at = above ? slotOf(above) : -1; + if (at >= 0) scene.primitives.add(host, at); + else scene.primitives.add(host); showHosts(record); } + /** Where `primitive` is among the scene's primitives, or -1. */ + function slotOf(primitive) { + const primitives = scene.primitives; + const n = primitives?.length ?? 0; + for (let i = 0; i < n; i++) if (primitives.get(i) === primitive) return i; + return -1; + } + function showHosts(record) { const show = record.spec.show !== false; if (record.host) record.host.show = show; @@ -284,7 +332,9 @@ export function createCesiumDraw({ scene, report }) { /** Remember a drawn point or icon for the horizon cull. */ function place(record, primitive, position, shown) { - record.placed.push({ primitive, position, shown }); + const placed = { primitive, position, shown }; + record.placed.push(placed); + return placed; } // Atlases icons name images from, by id: `{atlas, slot}` reads the slot @@ -353,17 +403,24 @@ export function createCesiumDraw({ scene, report }) { ); let primitive; if (heightReference === Cesium.HeightReference.NONE) { - points ??= new Cesium.PointPrimitiveCollection(); + points ??= new Cesium.PointPrimitiveCollection({ + blendOption: pointBlendOf(record.spec.blend), + }); primitive = points.add({ position, - pixelSize: item.pixelSize, - color: toColor(item.color), - outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]), - outlineWidth: item.outlineWidth ?? 0, - disableDepthTestDistance: item.disableDepthTest ?? 0, + ...pointLook(item), show, id: pickId(record, item), }); + const placed = place(record, primitive, position, show); + record.patchable ??= new Map(); + record.patchable.set(item.id, { + primitive, + placed, + at: placeOf(item), + lodGroup: item.lodGroup, + }); + continue; } else { // Point primitives cannot follow the ground. dots ??= new Cesium.BillboardCollection({ scene }); @@ -385,6 +442,61 @@ export function createCesiumDraw({ scene, report }) { replaceHost(record, host); } + /** How a point primitive draws an unclamped point item. */ + function pointLook(item) { + return { + pixelSize: item.pixelSize, + color: toColor(item.color), + outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]), + outlineWidth: item.outlineWidth ?? 0, + disableDepthTestDistance: item.disableDepthTest ?? 0, + scaleByDistance: nearFarOf(item.scaleByDistance), + translucencyByDistance: nearFarOf(item.fadeByDistance), + }; + } + + const PLACE_KEYS = ['x', 'y', 'z', 'lon', 'lat', 'height']; + + /** + * Where an item is, as its values when drawn: a caller may change the + * position object it passes and send the same one again. + */ + const placeOf = (item) => + PLACE_KEYS.map((key) => item.pos?.[key]).concat(item.height); + + /** + * Upsert unclamped points in place, without a rebuild, when every item + * is one the set draws as a point primitive now and keeps its position, + * height mode and LOD group: then only how it looks, its `meta` and + * whether it shows change. False, changing nothing, otherwise. + */ + function patchPoints(record, list) { + const patchable = record.patchable; + if (record.kind !== 'points' || !patchable) return false; + for (const item of list) { + const was = patchable.get(item.id); + if ( + !was || + heightReferenceOf(item.height, record.spec.clampTo) !== + Cesium.HeightReference.NONE || + item.lodGroup !== was.lodGroup || + placeOf(item).some((value, i) => value !== was.at[i]) + ) + return false; + } + for (const item of list) { + const was = patchable.get(item.id); + const show = item.show !== false; + Object.assign(was.primitive, pointLook(item)); + was.primitive.id.meta = item.meta; + was.placed.shown = show; + // As a rebuild would; the horizon cull, where it runs, hides it again + // past the horizon before the next frame draws. + was.primitive.show = show; + } + return true; + } + /** * A clamped point as Cesium's entity points draw one: a billboard of a * dot drawn at its pixel size, one texture per look. diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index fc9777d55..f784405bb 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -448,3 +448,236 @@ test('the cyclones layer draws clamped dots, draped tracks and holed cones on a rendering.destroy(); assert.equal(scene.added.length, 0); }); + +test('point sets blend as asked and fall off with distance', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'falloff', blend: 'translucent' }); + set.set([ + { + id: 'a', + pos: { lon: 0, lat: 0, height: 2 }, + pixelSize: 6, + color: [1, 0, 0, 0.5], + scaleByDistance: { near: 200, nearValue: 1.35, far: 1e5, farValue: 0.4 }, + fadeByDistance: { near: 200, nearValue: 1, far: 2e5, farValue: 0.15 }, + }, + { id: 'b', pos: { lon: 1, lat: 0 }, pixelSize: 6, color: '#fff' }, + ]); + const [points] = scene.added; + assert.equal(points.blendOption, Cesium.BlendOption.TRANSLUCENT); + const a = points.get(0); + assert.ok( + Cesium.NearFarScalar.equals( + a.scaleByDistance, + new Cesium.NearFarScalar(200, 1.35, 1e5, 0.4), + ), + ); + assert.ok( + Cesium.NearFarScalar.equals( + a.translucencyByDistance, + new Cesium.NearFarScalar(200, 1, 2e5, 0.15), + ), + ); + assert.equal(points.get(1).scaleByDistance, undefined, 'none asked'); + set.setOptions({ blend: 'opaque' }); + assert.equal(scene.added[0].blendOption, Cesium.BlendOption.OPAQUE); + set.setOptions({ blend: undefined }); + assert.equal( + scene.added[0].blendOption, + Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT, + 'the default, as before', + ); + set.dispose(); +}); + +test('the bikeshare layer draws its stations as point primitives on a viewer of its own', async () => { + const { createState } = await import('../../layers/bikeshare/state.js'); + const { createModel } = await import('../../layers/bikeshare/model.js'); + const { createRendering } = + await import('../../layers/bikeshare/rendering.js'); + const { createSelection } = + await import('../../layers/bikeshare/selection.js'); + const scene = fakeScene(); + const viewer = { scene }; + const services = { + render: { governorRequestRender() {} }, + overlays: { + setOverlayEntries() {}, + setOverlaySourceVisible() {}, + clearOverlaySource() {}, + }, + }; + const state = createState({ services }); + const parts = {}; + const context = { state, services, parts, source: {} }; + parts.model = createModel(context); + parts.rendering = createRendering(context); + parts.selection = createSelection(context); + state._viewer = viewer; + parts.rendering.attachSets(viewer); + state._stationSet.show = true; + const info = parts.model.parseStationInformation({ + data: { + stations: [ + { station_id: 'a', name: 'A', lat: 30.26, lon: -97.74, capacity: 20 }, + { station_id: 'b', name: 'B', lat: 30.27, lon: -97.75, capacity: 4 }, + ], + }, + }); + parts.rendering.ensureCityPoints('austin', info); + parts.rendering.applyStatusToPoints( + 'austin', + parts.model.parseStationStatus({ + data: { + stations: [ + { station_id: 'a', num_bikes_available: 18, num_docks_available: 2 }, + ], + }, + }), + ); + const points = scene.added.find((host) => host.get(0)?.id?.id === 'austin:a'); + assert.ok(points instanceof Cesium.PointPrimitiveCollection); + assert.equal(points.blendOption, Cesium.BlendOption.TRANSLUCENT); + assert.equal(points.length, 2); + const a = points.get(0); + assert.match(a.id.set, /^bikeshare:\d+:stations$/); + assert.equal(a.disableDepthTestDistance, 2500); + assert.equal(a.outlineWidth, 1); + assert.ok( + a.color.equalsEpsilon( + Cesium.Color.fromCssColorString('#00ff88').withAlpha(0.95), + 1e-9, + ), + 'plenty of bikes: green, as before', + ); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + a.position, + Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 2), + 0, + 1e-6, + ), + ); + assert.ok( + Cesium.NearFarScalar.equals( + a.scaleByDistance, + new Cesium.NearFarScalar(200, 1.35, 130000, 0.4), + ), + ); + + // Selected: its own dot goes, a cyan one over everything takes its place. + parts.selection._selectStation('austin:a'); + const stations = scene.added.find( + (host) => host.get(0)?.id?.set === a.id.set, + ); + assert.equal(stations.get(0).show, false); + const highlight = scene.added.find((host) => + host.get(0)?.id?.set?.endsWith(':selected'), + ); + const dot = highlight.get(0); + assert.ok(Cesium.Color.equals(dot.color, Cesium.Color.CYAN)); + assert.equal(dot.pixelSize, 14); + assert.equal(dot.outlineWidth, 2); + assert.equal(dot.disableDepthTestDistance, Infinity); + parts.selection._clearSelection(); + parts.rendering.detachSets(); + assert.equal(scene.added.length, 0); +}); + +test('a rebuilt set keeps its place among the scene primitives, and names its host', async () => { + const { + registerSpriteSet, + registerSpriteCollection, + restoreSpriteOrder, + unregisterSpriteCollection, + } = await import('../../data/spriteOrder.js'); + const scene = fakeScene(); + scene.primitives = new Cesium.PrimitiveCollection(); + const { draw } = drawOver(scene); + const below = scene.primitives.add(new Cesium.PrimitiveCollection()); + const set = draw.points({ id: 'kept' }); + set.set([]); + const above = scene.primitives.add(new Cesium.PrimitiveCollection()); + const order = () => { + const out = []; + for (let i = 0; i < scene.primitives.length; i++) { + const p = scene.primitives.get(i); + out.push(p === below ? 'below' : p === above ? 'above' : p.drawSetId); + } + return out; + }; + assert.deepEqual(order(), ['below', 'kept', 'above']); + set.set([{ id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' }]); + set.upsert([ + { id: 'b', pos: { lon: 1, lat: 0 }, pixelSize: 4, color: '#fff' }, + ]); + assert.deepEqual( + order(), + ['below', 'kept', 'above'], + 'not raised by updates', + ); + + // The sprite order finds the set's host by its id, whichever host it is. + const cctv = registerSpriteCollection('cctv', below); + const flights = registerSpriteCollection('flights', above); + const entry = registerSpriteSet('bikeshare', 'kept'); + scene.primitives.raiseToTop(below); + assert.deepEqual(order(), ['kept', 'above', 'below']); + restoreSpriteOrder({ scene }); + assert.deepEqual(order(), ['below', 'kept', 'above']); + unregisterSpriteCollection('bikeshare', entry); + unregisterSpriteCollection('cctv', cctv); + unregisterSpriteCollection('flights', flights); + set.dispose(); +}); + +test('restyling points that stay put changes them in place; moving one rebuilds', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'restyled', blend: 'translucent' }); + const dot = (id, lon, extra = {}) => ({ + id, + pos: { lon, lat: 0, height: 2 }, + pixelSize: 6, + color: [1, 0, 0, 1], + ...extra, + }); + set.set([dot('a', 0), dot('b', 1)]); + const [host] = scene.added; + const a = host.get(0); + set.upsert([ + dot('a', 0, { color: [0, 1, 0, 1], pixelSize: 9, show: false, meta: 7 }), + ]); + assert.equal(scene.added[0], host, 'the same collection'); + assert.equal(host.get(0), a, 'the same point'); + assert.ok(Cesium.Color.equals(a.color, Cesium.Color.LIME)); + assert.equal(a.pixelSize, 9); + assert.equal(a.show, false); + assert.equal(a.id.meta, 7, 'picks read the new meta'); + assert.equal(set.size(), 2); + + set.upsert([dot('b', 2)]); + assert.notEqual(scene.added[0], host, 'moved: rebuilt'); + set.upsert([dot('c', 3)]); + assert.equal(set.size(), 3, 'a new item rebuilds too'); + assert.equal(scene.added[0].length, 3); + set.dispose(); +}); + +test('a position object changed and sent again moves its point', () => { + const { scene, draw } = drawOver(); + const set = draw.points({ id: 'moved-in-place' }); + const item = { + id: 'a', + pos: { lon: 0, lat: 0 }, + pixelSize: 4, + color: '#fff', + }; + set.set([item]); + const host = scene.added[0]; + item.pos.lon = 90; + set.upsert([item]); + assert.notEqual(scene.added[0], host, 'rebuilt where it now is'); + const at = Cesium.Cartographic.fromCartesian(scene.added[0].get(0).position); + assert.ok(Math.abs(Cesium.Math.toDegrees(at.longitude) - 90) < 1e-9); + set.dispose(); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 3f73505ac..11d751696 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -49,11 +49,6 @@ "src/layers/awareness/rendering.js", "src/layers/awareness/state.js", "src/layers/awareness/subject.js", - "src/layers/bikeshare/lifecycle.js", - "src/layers/bikeshare/policy.js", - "src/layers/bikeshare/rendering.js", - "src/layers/bikeshare/selection.js", - "src/layers/bikeshare/viewport.js", "src/layers/cctv/cards.js", "src/layers/cctv/geometry.js", "src/layers/cctv/geometryQueue.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 1cf86e359..3025b772c 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -64,7 +64,10 @@ const FALLS_BACK = new Set(['src/data/followed.js']); * export loads the camera factory too, so these entries' camera is the * caller's to load the same way. */ -const DRAW_FROM_CALLER = new Set(['./layers/earthquakes']); +const DRAW_FROM_CALLER = new Set([ + './layers/earthquakes', + './layers/bikeshare', +]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));