Draw tropical cyclones through the renderer's draw port

The cyclone layer no longer imports Cesium. Its advisories are three draw
sets per rendering (points, lines, cones) taken from drawOf(viewer): the
centers and forecast points are clamped dots culled past the horizon, the
tracks and cone outlines are draped lines, and the cones are clamped
polygons that keep their holes. Flights go through cameraOf, and the focus
sphere comes from a port of BoundingSphere.fromPoints in src/geo/sphere.js.

Clicks read the new ClickEvent.drawHit: the dispatcher's pick as the
contract's Hit when it is a draw-set item. The Cesium port's query uses the
same conversion, now in render/cesium/drawHit.js. pickStorm takes that hit
and accepts only current items of the layer's own sets.

Every advisory commit redraws the points, so an empty advisory clears them;
an unchanged selection draws nothing. Far-side tracks and cones are left
to the globe's depth instead of a per-frame occluder. Both cyclone files
leave the Cesium allow-list.
This commit is contained in:
Sameh Khamis committed 2026-11-06 19:15:09 -08:00
1 parent bb3106991e
commit bd5a688144
14 files changed
+818 -783

No files matched your search

+207 -245
View File
@@ -1,3 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { drawOf } from '../../render/rendererOf.js';
import {
CYCLONE_ACCENT,
CYCLONE_MARKER_PX,
@@ -5,6 +8,14 @@ import {
createCycloneLabels,
} from './labels.js';
/**
* The draw sets the advisories are drawn in start with this; each rendering
* has its own (`weather-cyclones:1:points`, …), so several can share a
* renderer. Picks name them as `Hit.set`.
*/
export const CYCLONE_SET_PREFIX = 'weather-cyclones';
let renderings = 0;
/** Only geometry from the displayed status advisory is eligible for rendering. */
export function coherentCycloneGeometry(storm) {
return (
@@ -13,299 +24,250 @@ export function coherentCycloneGeometry(storm) {
);
}
/** A `#rrggbb` colour at `alpha`, as CSS. */
function withAlpha(hex, alpha) {
const n = Number.parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;
}
const BLACK = [0, 0, 0, 1];
const WHITE = [1, 1, 1, 1];
/**
* Static Cesium entities with owned horizon culling; no timers or clock.
* Storm names and lead hours are published to the shared overlay host at the
* same anchors the points use.
* Static renderer draw sets with the renderer's horizon cull; no timers or
* clock. Points are clamped and drawn over depth, so the points set culls
* them past the horizon; tracks, cones and their outlines drape on the
* ground, where the globe hides the far side. Storm names and lead hours
* are published to the shared overlay host at the same anchors the points
* use.
*/
export function createCycloneRendering({ viewer, cesium: C, overlayHost }) {
export function createCycloneRendering({ viewer, overlayHost }) {
const labels = createCycloneLabels({ host: overlayHost });
let source = null,
generation = 0,
const draw = drawOf(viewer);
const prefix = `${CYCLONE_SET_PREFIX}:${++renderings}`;
const setIds = new Set(
['points', 'lines', 'cones'].map((kind) => `${prefix}:${kind}`),
);
const points = draw.points({
id: `${prefix}:points`,
horizonCull: true,
clampTo: 'both',
});
const lines = draw.lines({ id: `${prefix}:lines`, clampTo: 'both' });
const cones = draw.shapes({ id: `${prefix}:cones`, clampTo: 'both' });
let committed = false,
selected = null,
destroyed = false;
// Per storm: its center point (redrawn on selection), forecast points and
// focus sphere; per drawn item, the storm it belongs to.
let centers = new Map(),
spheres = new Map();
let entityStorms = new WeakMap();
let entityIds = new Set();
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let horizonStorms = [],
removePreRender = null,
pointOccluder = null,
sphereOccluder = null;
const blue = C.Color.fromCssColorString(CYCLONE_ACCENT);
const gold = C.Color.fromCssColorString(CYCLONE_SELECTED_ACCENT);
const white = C.Color.WHITE;
const render = () => {
if (!viewer.isDestroyed?.()) viewer.scene.requestRender();
};
function cullHorizon() {
pointOccluder.cameraPosition = viewer.camera.positionWC;
sphereOccluder.cameraPosition = viewer.camera.positionWC;
let changed = false;
for (let i = 0; i < horizonStorms.length; i++) {
const storm = horizonStorms[i];
for (let j = 0; j < storm.points.length; j++) {
const { entity, position } = storm.points[j];
const show = pointOccluder.isPointVisible(position);
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
if (!storm.shapes.length) continue;
const show = sphereOccluder.isBoundingSphereVisible(storm.sphere);
for (let j = 0; j < storm.shapes.length; j++) {
const entity = storm.shapes[j];
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
}
if (changed) render();
let itemCount = 0;
function centerItem(storm) {
const chosen = storm.id === selected;
return {
id: `cyclone:${storm.id}:center`,
pos: storm.at,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: chosen ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm,
color: chosen ? CYCLONE_SELECTED_ACCENT : CYCLONE_ACCENT,
outlineColor: BLACK,
outlineWidth: 2,
};
}
function syncHorizonListener() {
if (!horizonStorms.length) {
removePreRender?.();
removePreRender = null;
return;
}
if (removePreRender) return;
pointOccluder ||= new C.EllipsoidalOccluder(
C.Ellipsoid.WGS84,
viewer.camera.positionWC,
);
// EllipsoidalOccluder only tests points. An inscribed WGS84 sphere
// conservatively culls extents, retaining partially visible tracks/cones.
sphereOccluder ||= new C.Occluder(
new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius),
viewer.camera.positionWC,
);
removePreRender = viewer.scene.preRender.addEventListener(cullHorizon);
}
function remove(value) {
if (!value) return;
if (!viewer.dataSources.isDestroyed?.())
viewer.dataSources.remove(value, true);
value.entities.removeAll();
function drawPoints() {
points.set([...[...centers.values()].map(centerItem), ...forecasts]);
}
// Only the centers show the selection: a change redraws the points set.
function select(id) {
if (destroyed || id === selected) return;
selected = id;
for (const [stormId, entity] of centers) {
entity.point.color = stormId === id ? gold : blue;
entity.point.pixelSize =
stormId === id ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm;
}
drawPoints();
labels.setSelection(id);
render();
}
return {
async setSnapshot(snapshot, { signal } = {}) {
signal?.throwIfAborted();
if (destroyed) return false;
const owner = ++generation;
const next = new C.CustomDataSource('weather-cyclones');
const nextCenters = new Map(),
nextSpheres = new Map();
const nextEntityStorms = new WeakMap();
const nextEntityIds = new Set();
nextSpheres = new Map(),
nextItemStorms = new Map();
const nextForecasts = [],
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const nextHorizonStorms = [];
const nextLabels = [];
const position = ({ longitude, latitude }) =>
C.Cartesian3.fromDegrees(longitude, latitude, 0);
const coordinate = (pair) =>
position({ longitude: pair[0], latitude: pair[1] });
try {
for (const storm of snapshot.storms) {
const horizon = { points: [], shapes: [], sphere: null };
const addEntity = (options) => {
const entity = next.entities.add(options);
if (options.position)
horizon.points.push({ entity, position: options.position });
else horizon.shapes.push(entity);
nextEntityStorms.set(entity, storm.id);
nextEntityIds.add(entity.id);
return entity;
};
const center = position(storm.position),
extent = [center];
const entity = addEntity({
id: `cyclone:${storm.id}:center`,
name: storm.name,
position: center,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.storm,
color: blue,
outlineColor: C.Color.BLACK,
outlineWidth: 2,
},
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
height: 0,
});
const pair = (coordinate) => ({
lon: coordinate[0],
lat: coordinate[1],
height: 0,
});
const ecef = (p) => fromDegrees(p.lon, p.lat, 0);
for (const storm of snapshot.storms) {
const own = (id) => (nextItemStorms.set(id, storm.id), id);
const at = lonLat(storm.position);
const center = ecef(at);
const extent = [center];
own(`cyclone:${storm.id}:center`);
nextCenters.set(storm.id, { id: storm.id, at });
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const tracks =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
tracks.forEach((line, index) => {
// Lines take ECEF (draw.d.ts `LineItem`).
const positions = line.map((c) => ecef(pair(c)));
extent.push(...positions);
nextLines.push({
id: own(`cyclone:${storm.id}:track:${index}`),
positions,
widthPx: 2.5,
mode: 'draped',
style: { kind: 'solid', color: CYCLONE_ACCENT },
});
nextCounts.tracks++;
});
nextCenters.set(storm.id, entity);
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const lines =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
lines.forEach((line, index) => {
const positions = line.map(coordinate);
extent.push(...positions);
addEntity({
id: `cyclone:${storm.id}:track:${index}`,
polyline: {
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
positions,
width: 2.5,
material: blue,
arcType: C.ArcType.GEODESIC,
},
});
nextCounts.tracks++;
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(CYCLONE_ACCENT, 0.16),
height: 'clampGround',
});
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const exterior = rings[0].map(coordinate);
extent.push(...exterior);
const holes = rings
.slice(1)
.map((ring) => new C.PolygonHierarchy(ring.map(coordinate)));
addEntity({
id: `cyclone:${storm.id}:cone:${index}`,
polygon: {
hierarchy: new C.PolygonHierarchy(exterior, holes),
classificationType: C.ClassificationType.BOTH,
material: blue.withAlpha(0.16),
arcType: C.ArcType.GEODESIC,
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: 1,
mode: 'draped',
style: {
kind: 'solid',
color: withAlpha(CYCLONE_ACCENT, 0.55),
},
});
[exterior, ...holes.map((hole) => hole.positions)].forEach(
(positions, ringIndex) => {
addEntity({
id: `cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
polyline: {
positions,
width: 1,
material: blue.withAlpha(0.55),
arcType: C.ArcType.GEODESIC,
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
},
});
},
);
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const p = position(point.position);
extent.push(p);
addEntity({
id: `cyclone:${storm.id}:forecast:${index}`,
position: p,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: white,
outlineColor: C.Color.BLACK,
outlineWidth: 1,
},
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
const p = ecef(pos);
extent.push(p);
nextForecasts.push({
id: own(`cyclone:${storm.id}:forecast:${index}`),
pos,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: WHITE,
outlineColor: BLACK,
outlineWidth: 1,
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
const sphere = C.BoundingSphere.fromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
horizon.sphere = sphere;
nextHorizonStorms.push(horizon);
}
await viewer.dataSources.add(next);
if (destroyed || generation !== owner || signal?.aborted) {
remove(next);
return false;
}
remove(source);
source = next;
centers = nextCenters;
spheres = nextSpheres;
entityStorms = nextEntityStorms;
entityIds = nextEntityIds;
counts = nextCounts;
horizonStorms = nextHorizonStorms;
syncHorizonListener();
labels.setSnapshot(nextLabels, selected);
select(selected);
return true;
} catch (error) {
remove(next);
if (signal?.aborted || generation !== owner || destroyed) return false;
throw error;
const sphere = sphereFromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
}
if (destroyed || signal?.aborted) return false;
centers = nextCenters;
forecasts = nextForecasts;
spheres = nextSpheres;
itemStorms = nextItemStorms;
counts = nextCounts;
itemCount = nextItemStorms.size;
committed = true;
lines.set(nextLines);
cones.set(nextCones);
// Every commit redraws the points, an empty advisory included.
drawPoints();
labels.setSnapshot(nextLabels, selected);
return true;
},
setSelection: select,
ownsPickId(id) {
return source !== null && typeof id === 'string' && entityIds.has(id);
return committed && typeof id === 'string' && itemStorms.has(id);
},
pickStorm(picked) {
// Cesium Entity picks carry the exact entity in `id`. IDs/prefixes alone
// cannot establish ownership, especially after an advisory replacement.
const entity = picked?.id;
return source && entity && typeof entity === 'object'
? entityStorms.get(entity) || null
: null;
/**
* The storm a click's draw hit (`Hit`, query.d.ts) belongs to: an item
* of these sets in the advisory drawn now, never an id from another.
*/
pickStorm(hit) {
if (!committed || !hit || hit.surface) return null;
if (!setIds.has(hit.set)) return null;
return itemStorms.get(hit.id) ?? null;
},
getFocusSphere(id) {
return spheres.get(id) || null;
},
clear() {
++generation;
horizonStorms = [];
syncHorizonListener();
pointOccluder = null;
sphereOccluder = null;
remove(source);
source = null;
committed = false;
if (!destroyed) {
points.clear();
lines.clear();
cones.clear();
}
labels.clear();
centers.clear();
spheres.clear();
entityStorms = new WeakMap();
entityIds.clear();
centers = new Map();
forecasts = [];
spheres = new Map();
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
render();
},
destroy() {
if (destroyed) return;
this.clear();
destroyed = true;
points.dispose();
lines.dispose();
cones.dispose();
},
getDiagnostics() {
return {
...counts,
dataSources: Number(!!source),
entities: source?.entities.values.length || 0,
// One display: the committed advisory's sets, and the items in them.
dataSources: Number(committed),
entities: itemCount,
selectedId: selected,
timerActive: false,
};