Move the bikeshare layer onto the renderer's draw and camera ports

Station dots and the selected-station highlight are now two point draw
sets, picked through the draw hit, and the layer follows the camera
through the camera port at its own threshold instead of the shared
percentageChanged ledger. Altitude and view centre come from the camera
pose and view rectangle. All five bikeshare files leave the Cesium
allow-list.

The Cesium draw port now keeps a rebuilt host in its place in the scene
instead of re-adding it on top, tags hosts with their set id so sprite
order can raise a draw set (registerSpriteSet), and restyles unclamped
points in place when they have not moved, so a status poll or selection
no longer rebuilds every station. Other draw-port layers (cyclone
markers, earthquake discs) now also keep their first-build slot rather
than jumping above the sprite layers on each rebuild.
This commit is contained in:
Sameh Khamis committed 2026-11-06 20:26:35 -08:00
1 parent 2b66c46a30
commit 8c6fa6258b
22 files changed
+732 -249

No files matched your search

+1 -1
View File
@@ -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);
+6 -17
View File
@@ -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() {
+36 -51
View File
@@ -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;
},
};
+61 -13
View File
@@ -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;
+2 -2
View File
@@ -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([
+7 -8
View File
@@ -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',
+104 -34
View File
@@ -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<string, Object>} 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,
+26 -50
View File
@@ -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();
});
+13 -9
View File
@@ -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;
+1 -1
View File
@@ -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;
}
+19 -20
View File
@@ -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;
}
+27 -5
View File
@@ -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);