Files
gods-eye-view/src/layers/bikeshare/viewport.js
T
Sameh Khamis 8fe4be484f Bike Share marks its covered cities on the globe
Above the height stations draw at, the layer only said "Fly below 48 km to
a covered city" without showing which cities those are. Every system in
the registry now has a marker there: a green, white-ringed dot over its
city, 5 km up so terrain never hides it, shown only while the layer is on
and stations are not drawn.

Clicking a marker flies straight down into its city from 20 km, as an
explicit camera action through the shell's runNavigation, like News and
the weather layers. The markers belong to the layer for picking.
2026-11-17 20:30:04 -08:00

309 lines
10 KiB
JavaScript

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,
ACTIVATION_ENTER_ALTITUDE_M,
CITY_RANGE_BASE_KM,
CAMERA_DEBOUNCE_MS,
} from './policy.js';
export function createViewport({ state: layerState, services, parts, source }) {
const { governorRequestRender } = services.render;
/**
* Get the camera's current altitude in meters above the ellipsoid.
* @param {object} viewer - The viewer the layer draws on.
* @returns {number} Altitude in meters, or Infinity if unavailable.
*/
function getCameraAltitude(viewer) {
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 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 = camera?.viewRectangle();
if (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: (rect.south + rect.north) * 0.5,
lon: toDegrees(negativePiToPi((west + east) * 0.5)),
};
}
// Fallback: use the camera's own position
const pose = camera?.pose();
if (pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon))
return { lat: pose.lat, lon: pose.lon };
return null;
}
/**
* Determine whether the layer should be active at the given camera altitude.
* Uses hysteresis (separate enter/exit thresholds) to avoid rapid toggling
* when the camera hovers near the activation boundary.
* @param {number} altitude - Camera altitude in meters.
* @returns {boolean} True if the layer should remain/become active.
*/
function shouldActivateAtAltitude(altitude) {
if (!Number.isFinite(altitude)) {
layerState._altitudeGateEnabled = false;
return false;
}
if (layerState._altitudeGateEnabled) {
// Deactivate only after crossing the higher exit threshold
if (altitude >= ACTIVATION_EXIT_ALTITUDE_M)
layerState._altitudeGateEnabled = false;
} else if (altitude <= ACTIVATION_ENTER_ALTITUDE_M) {
// Activate when dropping below the lower enter threshold
layerState._altitudeGateEnabled = true;
}
return layerState._altitudeGateEnabled;
}
/**
* Determine which cities are close enough to the camera to warrant loading.
* Compares haversine distance from the camera center to each city's center
* against the city's configured load radius.
* @param {{ lat: number, lon: number }} center - Camera center in degrees.
* @returns {Set<string>} Set of city ids currently within load range.
*/
function computeInRangeCities(center) {
const active = new Set();
if (!center) return active;
for (const city of GBFS_CITY_REGISTRY) {
const distance = parts.model.haversineKm(
center.lat,
center.lon,
city.centerLat,
city.centerLon,
);
const radius = Math.max(CITY_RANGE_BASE_KM, city.loadRadiusKm);
if (distance <= radius) active.add(city.id);
}
return active;
}
/**
* Fully deactivate a single city: abort pending fetches and remove rendered points.
* @param {string} cityId - City identifier to deactivate.
*/
function deactivateCity(cityId) {
governorRequestRender('bikeshare-deactivate');
parts.ingestion.abortInFlight(layerState._inFlightInfo, cityId);
parts.ingestion.abortInFlight(layerState._inFlightStatus, cityId);
parts.rendering.removeCityPoints(cityId);
}
/**
* Show the covered cities' markers, or hide them: shown while the layer is
* on and the camera is too high for stations.
* @param {boolean} shown
*/
function showCoverage(shown) {
const set = layerState._coverageSet;
if (!set || set.show === shown) return;
set.show = shown;
governorRequestRender('bikeshare-coverage');
}
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
function refreshRow() {
layerState._dataManager?.refreshLayerStats?.('bikeshare');
}
/** Deactivate all currently active cities and clear the active set. */
function deactivateAllCities() {
const cityIds = Array.from(layerState._activeCityIds);
for (const cityId of cityIds) deactivateCity(cityId);
layerState._activeCityIds.clear();
// A failure belongs to a city in range; none are once everything is off.
layerState._failedCityIds.clear();
layerState._count = 0;
// Nothing is left on the map to date.
layerState._lastUpdate = null;
}
/**
* Activate a city: fetch station info, create point primitives, fetch status,
* and apply availability colors. Checks generation at each async boundary
* to bail out if the proximity context has changed.
* @param {string} cityId - City identifier to activate.
* @param {number} generation - Proximity generation at time of invocation.
*/
async function activateCity(cityId, generation) {
if (!layerState._enabled || !layerState._activeCityIds.has(cityId)) return;
try {
const stationMap = await parts.ingestion.loadCityStationInfo(
cityId,
generation,
);
// Bail if context changed during fetch
if (
!layerState._enabled ||
!layerState._activeCityIds.has(cityId) ||
generation !== layerState._proximityGeneration
)
return;
parts.rendering.ensureCityPoints(cityId, stationMap);
// Apply any cached status immediately for snappier initial rendering
const cachedStatus = layerState._statusCache.get(cityId)?.statusMap;
if (cachedStatus) {
parts.rendering.applyStatusToPoints(cityId, cachedStatus);
}
const statusMap = await parts.ingestion.loadCityStationStatus(
cityId,
generation,
);
if (
!layerState._enabled ||
!layerState._activeCityIds.has(cityId) ||
generation !== layerState._proximityGeneration
)
return;
parts.rendering.applyStatusToPoints(cityId, statusMap);
layerState._lastUpdate = Date.now();
layerState._failedCityIds.delete(cityId);
} catch (error) {
if (error?.name === 'AbortError') return;
// A rejection from superseded work must not mark (or tear down) a city
// that a newer proximity check or re-enable now owns.
if (
!layerState._enabled ||
!layerState._activeCityIds.has(cityId) ||
generation !== layerState._proximityGeneration
)
return;
console.warn(`[Data:Bikeshare] ${cityId} activate error:`, error);
layerState._failedCityIds.add(cityId);
deactivateCity(cityId);
layerState._activeCityIds.delete(cityId);
} finally {
layerState._count = layerState._stationRenderMap.size;
}
}
/**
* Core proximity check: determines which cities are in camera range at the
* current altitude, deactivates out-of-range cities, and activates newly
* in-range ones. Increments the generation counter to invalidate stale work.
* @returns {Promise<void>}
*/
async function runProximityCheck() {
if (!layerState._enabled || !layerState._viewer) return;
const generation = ++layerState._proximityGeneration;
const altitude = getCameraAltitude(layerState._viewer);
const wasGateEnabled = layerState._altitudeGateEnabled;
// Altitude gate: disable all cities when camera is too high
if (!shouldActivateAtAltitude(altitude)) {
showCoverage(true);
deactivateAllCities();
if (wasGateEnabled) refreshRow();
return;
}
showCoverage(false);
const center = getCameraCenterLatLon(layerState._viewer);
if (!center) return;
// Diff active set against newly computed in-range set
const nextActive = computeInRangeCities(center);
for (const cityId of layerState._activeCityIds) {
if (!nextActive.has(cityId)) {
deactivateCity(cityId);
}
}
// A failure never outlives its city's range.
let failureCleared = false;
for (const cityId of layerState._failedCityIds) {
if (!nextActive.has(cityId)) {
layerState._failedCityIds.delete(cityId);
failureCleared = true;
}
}
const changed =
!wasGateEnabled ||
failureCleared ||
nextActive.size !== layerState._activeCityIds.size ||
[...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId));
layerState._activeCityIds = nextActive;
if (nextActive.size === 0) {
layerState._count = 0;
layerState._lastUpdate = null;
}
if (changed) refreshRow();
// Only activate cities that don't already have rendered points
const toActivate = [];
for (const cityId of layerState._activeCityIds) {
if (!layerState._cityRuntime.has(cityId)) toActivate.push(cityId);
}
if (toActivate.length === 0) return;
await Promise.all(
toActivate.map((cityId) => activateCity(cityId, generation)),
);
// Superseded loads repaint too: a newer check may have painted the row
// while this one was still loading, or found nothing to load itself.
if (layerState._enabled) refreshRow();
}
/** Schedule a debounced proximity check after camera movement. */
function scheduleProximityCheck() {
clearTimeout(layerState._cameraDebounceTimer);
layerState._cameraDebounceTimer = setTimeout(() => {
void runProximityCheck();
}, CAMERA_DEBOUNCE_MS);
}
/** Camera change event handler — triggers a debounced proximity check. */
function onCameraChanged() {
if (!layerState._enabled) return;
scheduleProximityCheck();
}
return {
getCameraAltitude,
getCameraCenterLatLon,
shouldActivateAtAltitude,
computeInRangeCities,
deactivateCity,
deactivateAllCities,
activateCity,
runProximityCheck,
scheduleProximityCheck,
showCoverage,
onCameraChanged,
};
}