mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 00:32:21 +00:00
feat(mobile): add the phone-tuned Cesium globe engine
createGlobe() implements the Globe API in mobile/DESIGN.md: Esri day imagery blended with NASA Black Marble night lights across the terminator, Google 3D tiles below 25 km when keyed, a single-pass grade with half-res bloom and lenses, an adaptive quality governor, live layers on the repo's /api routes and parsers, time scrubbing, picking, AR contact queries and live situation cards. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VVYRAqiQj9Y1V9ZfG1RcDH
This commit is contained in:
19 files changed
+5816
No files matched your search
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* Sky family: commercial flights, military aircraft, helicopters, private/GA
|
||||
* and emergency squawks. Every layer reads the shared flight and military
|
||||
* feeds; derived layers (helicopters, GA, squawks) are filters, never extra
|
||||
* downloads.
|
||||
*/
|
||||
import { ContactRenderer, Layer, color, FAMILY_COLORS } from './base.js';
|
||||
import { haversineKm } from '../geo.js';
|
||||
|
||||
const SKY = FAMILY_COLORS.Sky;
|
||||
const M_TO_FT = 3.28084;
|
||||
const MPS_TO_KT = 1 / 0.514444;
|
||||
const HISTORY = 24;
|
||||
|
||||
export class AircraftLayer extends Layer {
|
||||
/**
|
||||
* @param {object} ctx
|
||||
* @param {object} def layer definition
|
||||
* @param {{sources:{feed:object, filter:(r:object)=>boolean}[], tint:string,
|
||||
* lodHeightM?:number, cap?:number, alwaysGlyph?:boolean, kind?:string}} opts
|
||||
*/
|
||||
constructor(ctx, def, opts) {
|
||||
super(ctx, { pollMs: 12_000, ...def });
|
||||
this.sources = opts.sources;
|
||||
this.kind = opts.kind || 'aircraft';
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(opts.tint || SKY),
|
||||
glyphName: 'plane',
|
||||
lodHeightM: opts.lodHeightM ?? 1_800_000,
|
||||
cap: opts.cap ?? 700,
|
||||
deadReckon: true,
|
||||
dotScale: opts.dotScale ?? 0.36,
|
||||
alwaysGlyph: opts.alwaysGlyph,
|
||||
glyphScale: opts.glyphScale ?? 0.5,
|
||||
});
|
||||
this.records = new Map();
|
||||
this.history = new Map();
|
||||
this.groundTint = color(opts.tint || SKY).withAlpha(0.55);
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const results = await Promise.allSettled(
|
||||
this.sources.map((s) => s.feed.get({ maxAgeMs: 9_000 })),
|
||||
);
|
||||
const flightData = this.sources[0].feed.data;
|
||||
this._regionalNote = flightData?.regional
|
||||
? 'OpenSky unavailable — adsb.lol snapshot within 250 nm of the view'
|
||||
: '';
|
||||
const records = [];
|
||||
let anyOk = false;
|
||||
this.sources.forEach((s, i) => {
|
||||
this.fromFeed(s.feed);
|
||||
if (results[i].status !== 'fulfilled') return;
|
||||
anyOk = true;
|
||||
for (const r of results[i].value.records)
|
||||
if (s.filter(r)) records.push(r);
|
||||
});
|
||||
if (!anyOk) throw results[0].reason;
|
||||
if (this._regionalNote && !this.message) this.message = this._regionalNote;
|
||||
this.ingest(records);
|
||||
}
|
||||
|
||||
ingest(records) {
|
||||
const next = new Map();
|
||||
for (const r of records) {
|
||||
next.set(r.id, r);
|
||||
let h = this.history.get(r.id);
|
||||
if (!h) this.history.set(r.id, (h = []));
|
||||
const last = h.at(-1);
|
||||
if (!last || last[0] !== r.lon || last[1] !== r.lat) {
|
||||
h.push([r.lon, r.lat, r.altM]);
|
||||
if (h.length > HISTORY) h.shift();
|
||||
}
|
||||
}
|
||||
for (const id of this.history.keys())
|
||||
if (!next.has(id)) this.history.delete(id);
|
||||
this.records = next;
|
||||
this.count = next.size;
|
||||
this.renderer.setItems(
|
||||
records.map((r) => ({
|
||||
key: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
altM: r.altM,
|
||||
heading: r.heading,
|
||||
speed: r.speed,
|
||||
onGround: r.onGround,
|
||||
seenAt: r.seenAt || Date.now(),
|
||||
glyph: r.helicopter ? 'heli' : 'plane',
|
||||
// Parked traffic recedes so the apron does not bloom into a blob.
|
||||
color: r.emergency
|
||||
? color('#FF3B30')
|
||||
: r.onGround
|
||||
? this.groundTint
|
||||
: undefined,
|
||||
glyphScale: r.onGround
|
||||
? 0.6
|
||||
: r.helicopter
|
||||
? 0.95
|
||||
: r.cls === 'widebody'
|
||||
? 1.15
|
||||
: 1,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
// A regional fallback snapshot follows the camera: refetch once the
|
||||
// view has moved well away from the snapshot's anchor.
|
||||
const data = this.sources[0].feed.data;
|
||||
if (
|
||||
this.on &&
|
||||
data?.regional &&
|
||||
data.anchor &&
|
||||
view.center &&
|
||||
haversineKm(
|
||||
data.anchor.lat,
|
||||
data.anchor.lon,
|
||||
view.center.lat,
|
||||
view.center.lon,
|
||||
) > 300 &&
|
||||
Date.now() - (this._regionalKick || 0) > 8_000
|
||||
) {
|
||||
this._regionalKick = Date.now();
|
||||
this.kick();
|
||||
}
|
||||
}
|
||||
|
||||
onTime(ms, live) {
|
||||
// Aircraft are live-only: away from now they dim to show they are not
|
||||
// a reconstruction of that moment.
|
||||
this.renderer.setAlpha(live ? 1 : 0.3);
|
||||
}
|
||||
|
||||
onTick(nowMs, live) {
|
||||
return live && this.renderer.tick(nowMs);
|
||||
}
|
||||
|
||||
locate(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
const it = this.renderer.byKey.get(key);
|
||||
const [lon, lat] = it ? this.renderer.where(it) : [r.lon, r.lat];
|
||||
return [lon, lat, r.altM];
|
||||
}
|
||||
|
||||
trail(key) {
|
||||
const h = this.history.get(key) || [];
|
||||
const now = this.locate(key);
|
||||
return now ? [...h, now] : h;
|
||||
}
|
||||
|
||||
pick(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
const [lon, lat, altM] = this.locate(key);
|
||||
const alt = r.onGround
|
||||
? 'On ground'
|
||||
: `${Math.round((r.altM * M_TO_FT) / 100) * 100} ft`;
|
||||
const spd = Number.isFinite(r.speed)
|
||||
? `${Math.round(r.speed * MPS_TO_KT)} kt`
|
||||
: null;
|
||||
return {
|
||||
kind: this.kind,
|
||||
id: r.id,
|
||||
title: r.callsign,
|
||||
subtitle: [
|
||||
r.military ? r.type || 'Military' : r.country,
|
||||
alt,
|
||||
spd,
|
||||
r.emergency ? `SQUAWK ${r.squawk}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
lon,
|
||||
lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
icao24: r.id,
|
||||
altitudeM: r.altM,
|
||||
speedMps: r.speed,
|
||||
headingDeg: r.heading,
|
||||
verticalRateMps: r.vRate ?? null,
|
||||
squawk: r.squawk,
|
||||
type: r.type || null,
|
||||
class: r.cls,
|
||||
country: r.country || null,
|
||||
onGround: r.onGround,
|
||||
source: this.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
contacts() {
|
||||
const out = [];
|
||||
for (const r of this.records.values()) {
|
||||
const it = this.renderer.byKey.get(r.id);
|
||||
const [lon, lat] = it ? this.renderer.where(it) : [r.lon, r.lat];
|
||||
out.push({
|
||||
kind: this.kind,
|
||||
id: r.id,
|
||||
title: r.callsign,
|
||||
lon,
|
||||
lat,
|
||||
altM: r.altM,
|
||||
headingDeg: r.heading,
|
||||
speedMps: r.speed,
|
||||
layer: this.id,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
onHide() {}
|
||||
}
|
||||
|
||||
/** Build the Sky family. */
|
||||
export function createSkyLayers(ctx, { flights, military }) {
|
||||
const all = () => true;
|
||||
return [
|
||||
new AircraftLayer(
|
||||
ctx,
|
||||
{ id: 'flights', family: 'Sky', name: 'Commercial flights' },
|
||||
{
|
||||
sources: [{ feed: flights, filter: (r) => !r.ga && !r.helicopter }],
|
||||
tint: SKY,
|
||||
},
|
||||
),
|
||||
new AircraftLayer(
|
||||
ctx,
|
||||
{ id: 'military', family: 'Sky', name: 'Military aircraft' },
|
||||
{
|
||||
sources: [{ feed: military, filter: all }],
|
||||
tint: '#E3F1FF',
|
||||
kind: 'military',
|
||||
lodHeightM: 6_000_000,
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.62,
|
||||
dotScale: 0.6,
|
||||
},
|
||||
),
|
||||
new AircraftLayer(
|
||||
ctx,
|
||||
{ id: 'helicopters', family: 'Sky', name: 'Helicopters' },
|
||||
{
|
||||
sources: [
|
||||
{ feed: flights, filter: (r) => r.helicopter },
|
||||
{ feed: military, filter: (r) => r.helicopter },
|
||||
],
|
||||
tint: '#A8E0FF',
|
||||
kind: 'helicopter',
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.6,
|
||||
},
|
||||
),
|
||||
new AircraftLayer(
|
||||
ctx,
|
||||
{ id: 'ga', family: 'Sky', name: 'Private / GA' },
|
||||
{
|
||||
sources: [{ feed: flights, filter: (r) => r.ga && !r.helicopter }],
|
||||
tint: '#B9D9F5',
|
||||
dotScale: 0.3,
|
||||
glyphScale: 0.42,
|
||||
},
|
||||
),
|
||||
new AircraftLayer(
|
||||
ctx,
|
||||
{ id: 'squawk', family: 'Sky', name: 'Emergency squawks' },
|
||||
{
|
||||
sources: [
|
||||
{ feed: flights, filter: (r) => r.emergency },
|
||||
{
|
||||
feed: military,
|
||||
filter: (r) => ['7500', '7600', '7700'].includes(r.squawk),
|
||||
},
|
||||
],
|
||||
tint: '#FF3B30',
|
||||
kind: 'emergency',
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.8,
|
||||
dotScale: 0.9,
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
/**
|
||||
* Layer plumbing: lifecycle/polling/status for every live layer, and the
|
||||
* ContactRenderer that draws point contacts with semantic zoom.
|
||||
*
|
||||
* Semantic zoom: every contact is a soft glow dot (one BillboardCollection,
|
||||
* one draw call) so the planet reads as density at orbital altitude. Below the
|
||||
* layer's LOD height, the contacts nearest the view centre (capped) also get a
|
||||
* heading-aligned glyph that dead-reckons between polls.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { glyph } from '../glyphs.js';
|
||||
import { offsetLonLat } from '../geo.js';
|
||||
|
||||
export const FAMILY_COLORS = Object.freeze({
|
||||
Sky: '#7CC4FF',
|
||||
Sea: '#38E1C6',
|
||||
Orbit: '#C9A7FF',
|
||||
Hazards: '#FF6A3D',
|
||||
Eyes: '#FFD166',
|
||||
Ground: '#9BE15D',
|
||||
Weather: '#8AB4F8',
|
||||
Infra: '#B8C0CC',
|
||||
});
|
||||
|
||||
export const color = (css, alpha = 1) =>
|
||||
Cesium.Color.fromCssColorString(css).withAlpha(alpha);
|
||||
|
||||
export class Layer {
|
||||
/**
|
||||
* @param {object} ctx engine context from index.js
|
||||
* @param {{id:string,family:string,name:string,pollMs?:number}} def
|
||||
*/
|
||||
constructor(ctx, def) {
|
||||
this.ctx = ctx;
|
||||
this.id = def.id;
|
||||
this.family = def.family;
|
||||
this.name = def.name;
|
||||
this.pollMs = def.pollMs ?? 0;
|
||||
this.available = true;
|
||||
this.on = false;
|
||||
this.count = 0;
|
||||
this.status = 'off';
|
||||
this.message = '';
|
||||
this.source = def.source || '';
|
||||
this.updatedAt = null;
|
||||
this.loading = false;
|
||||
this.root = ctx.scene.primitives.add(new Cesium.PrimitiveCollection());
|
||||
this.root.show = false;
|
||||
this._timer = null;
|
||||
this._gen = 0;
|
||||
}
|
||||
|
||||
info() {
|
||||
return {
|
||||
id: this.id,
|
||||
family: this.family,
|
||||
name: this.name,
|
||||
on: this.on,
|
||||
count: this.on ? this.count : 0,
|
||||
status: this.on ? this.status : 'off',
|
||||
available: this.available,
|
||||
loading: this.on && this.loading,
|
||||
message: this.message,
|
||||
source: this.source,
|
||||
updatedAt: this.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
setOn(on) {
|
||||
on = Boolean(on);
|
||||
if (on === this.on) return;
|
||||
this.on = on;
|
||||
this.root.show = on;
|
||||
this._gen++;
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
if (on) {
|
||||
this.status = this.updatedAt ? this.status : 'stale';
|
||||
this.kick();
|
||||
} else {
|
||||
this.onHide?.();
|
||||
}
|
||||
this.ctx.layersChanged();
|
||||
this.ctx.requestRender();
|
||||
}
|
||||
|
||||
/** Refresh now (if on and active) and keep polling. */
|
||||
kick() {
|
||||
if (!this.on) return;
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
const gen = this._gen;
|
||||
if (!this.ctx.active()) return; // resume() kicks again
|
||||
this.loading = true;
|
||||
Promise.resolve()
|
||||
.then(() => this.refresh())
|
||||
.then(
|
||||
() => {
|
||||
if (gen !== this._gen) return;
|
||||
this.updatedAt = Date.now();
|
||||
},
|
||||
(error) => {
|
||||
if (gen !== this._gen) return;
|
||||
this.status = 'error';
|
||||
this.message = error?.message || String(error);
|
||||
console.warn(`[globe:${this.id}]`, this.message);
|
||||
},
|
||||
)
|
||||
.finally(() => {
|
||||
if (gen !== this._gen) return;
|
||||
this.loading = false;
|
||||
this.ctx.layersChanged();
|
||||
this.ctx.requestRender();
|
||||
if (this.pollMs && this.on)
|
||||
this._timer = setTimeout(() => this.kick(), this.pollMs);
|
||||
});
|
||||
}
|
||||
|
||||
/** Mark status from a feed after a refresh. */
|
||||
fromFeed(feed) {
|
||||
if (feed.error && !feed.data) {
|
||||
this.status = 'error';
|
||||
this.message = feed.error.message;
|
||||
} else {
|
||||
this.status = feed.stale ? 'stale' : 'live';
|
||||
this.message = feed.error ? `Refresh failed: ${feed.error.message}` : '';
|
||||
}
|
||||
if (feed.data?.source) this.source = feed.data.source;
|
||||
}
|
||||
|
||||
// Overridables
|
||||
async refresh() {}
|
||||
onView() {}
|
||||
onTime() {}
|
||||
onTick() {}
|
||||
pick() {
|
||||
return null;
|
||||
}
|
||||
contacts() {
|
||||
return [];
|
||||
}
|
||||
destroy() {
|
||||
clearTimeout(this._timer);
|
||||
this.ctx.scene.primitives.remove(this.root);
|
||||
}
|
||||
}
|
||||
|
||||
/** A catalog entry the prototype does not render yet. */
|
||||
export class UnavailableLayer {
|
||||
constructor(def) {
|
||||
Object.assign(this, def);
|
||||
this.on = false;
|
||||
this.available = false;
|
||||
}
|
||||
info() {
|
||||
return {
|
||||
id: this.id,
|
||||
family: this.family,
|
||||
name: this.name,
|
||||
on: false,
|
||||
count: 0,
|
||||
status: 'off',
|
||||
available: false,
|
||||
loading: false,
|
||||
message: this.message || 'Not in the prototype yet',
|
||||
source: '',
|
||||
updatedAt: null,
|
||||
};
|
||||
}
|
||||
setOn() {}
|
||||
kick() {}
|
||||
onView() {}
|
||||
onTime() {}
|
||||
onTick() {}
|
||||
pick() {
|
||||
return null;
|
||||
}
|
||||
contacts() {
|
||||
return [];
|
||||
}
|
||||
destroy() {}
|
||||
}
|
||||
|
||||
const DOT = () => glyph('dot');
|
||||
const GLYPH_NEAR_FAR = new Cesium.NearFarScalar(2e4, 1.25, 3e6, 0.7);
|
||||
const GLYPH_NO_DEPTH_WITHIN_M = 150_000;
|
||||
|
||||
/**
|
||||
* Point contacts with semantic zoom.
|
||||
* items: [{ key, lon, lat, altM?, heading?, speed?, seenAt?, color?, glyph?,
|
||||
* dotScale?, glyphScale? }]
|
||||
*/
|
||||
export class ContactRenderer {
|
||||
constructor(
|
||||
root,
|
||||
{
|
||||
tint,
|
||||
glyphName = 'dot',
|
||||
lodHeightM = 2_500_000,
|
||||
cap = 900,
|
||||
rotate = true,
|
||||
dotScale = 0.42,
|
||||
glyphScale = 0.5,
|
||||
layerId,
|
||||
deadReckon = false,
|
||||
dotAlpha = 0.85,
|
||||
alwaysGlyph = false,
|
||||
},
|
||||
) {
|
||||
this.layerId = layerId;
|
||||
this.tint = tint;
|
||||
this.glyphName = glyphName;
|
||||
this.lodHeightM = lodHeightM;
|
||||
this.cap = cap;
|
||||
this.rotate = rotate;
|
||||
this.dotScale = dotScale;
|
||||
this.glyphScale = glyphScale;
|
||||
this.deadReckon = deadReckon;
|
||||
this.dotAlpha = dotAlpha;
|
||||
this.alwaysGlyph = alwaysGlyph;
|
||||
this.dots = root.add(
|
||||
new Cesium.BillboardCollection({
|
||||
blendOption: Cesium.BlendOption.TRANSLUCENT,
|
||||
}),
|
||||
);
|
||||
this.glyphs = root.add(new Cesium.BillboardCollection());
|
||||
this.items = [];
|
||||
this.byKey = new Map();
|
||||
this.view = null;
|
||||
this.glyphMode = false;
|
||||
this.alpha = 1;
|
||||
this._scratch = new Cesium.Cartesian3();
|
||||
}
|
||||
|
||||
setItems(items) {
|
||||
this.items = items;
|
||||
this.byKey = new Map(items.map((it) => [it.key, it]));
|
||||
const dot = DOT();
|
||||
this.dots.removeAll();
|
||||
const near = new Cesium.NearFarScalar(4e5, 1.0, 2.2e7, 0.45);
|
||||
for (const it of items) {
|
||||
const c = it.color || this.tint;
|
||||
this.dots.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(it.lon, it.lat, it.altM || 0),
|
||||
image: dot.image,
|
||||
imageId: dot.imageId,
|
||||
color: c.withAlpha(c.alpha * this.dotAlpha * this.alpha),
|
||||
scale: (it.dotScale ?? 1) * this.dotScale,
|
||||
scaleByDistance: near,
|
||||
id: { layer: this.layerId, key: it.key },
|
||||
});
|
||||
}
|
||||
this._rebuildGlyphs();
|
||||
}
|
||||
|
||||
setAlpha(alpha) {
|
||||
if (alpha === this.alpha) return;
|
||||
this.alpha = alpha;
|
||||
this.setItems(this.items);
|
||||
}
|
||||
|
||||
setView(view) {
|
||||
this.view = view;
|
||||
this._rebuildGlyphs();
|
||||
}
|
||||
|
||||
_rebuildGlyphs() {
|
||||
const view = this.view;
|
||||
this.glyphs.removeAll();
|
||||
this.glyphMode =
|
||||
this.alwaysGlyph || Boolean(view && view.heightM < this.lodHeightM);
|
||||
if (!this.glyphMode || !view) return;
|
||||
const { rect } = view;
|
||||
const cLat = view.center?.lat ?? 0;
|
||||
const cLon = view.center?.lon ?? 0;
|
||||
const inView = [];
|
||||
for (const it of this.items) {
|
||||
if (rect && !inRect(rect, it.lon, it.lat)) continue;
|
||||
const dLat = it.lat - cLat;
|
||||
const dLon = (it.lon - cLon) * Math.cos((cLat * Math.PI) / 180);
|
||||
inView.push([dLat * dLat + dLon * dLon, it]);
|
||||
}
|
||||
inView.sort((a, b) => a[0] - b[0]);
|
||||
const n = Math.min(this.cap, inView.length);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const it = inView[i][1];
|
||||
const g = glyph(it.glyph || this.glyphName);
|
||||
it._bb = this.glyphs.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(it.lon, it.lat, it.altM || 0),
|
||||
image: g.image,
|
||||
imageId: g.imageId,
|
||||
color: (it.color || this.tint).withAlpha(
|
||||
(it.color || this.tint).alpha * this.alpha,
|
||||
),
|
||||
scale: (it.glyphScale ?? 1) * this.glyphScale,
|
||||
rotation: this.rotate ? -Cesium.Math.toRadians(it.heading || 0) : 0,
|
||||
alignedAxis: this.rotate
|
||||
? Cesium.Cartesian3.UNIT_Z
|
||||
: Cesium.Cartesian3.ZERO,
|
||||
id: { layer: this.layerId, key: it.key },
|
||||
scaleByDistance: GLYPH_NEAR_FAR,
|
||||
// Contacts report ellipsoid/MSL heights; over terrain a grounded or
|
||||
// low contact would sink below the surface. Close in, glyphs ignore
|
||||
// depth (a God's-eye HUD), far out the globe still occludes them.
|
||||
disableDepthTestDistance: GLYPH_NO_DEPTH_WITHIN_M,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move items in place (same keys, same order as the last setItems): no
|
||||
* billboard churn. `from`/`to` bound a round-robin slice of the dots;
|
||||
* glyph billboards always move.
|
||||
*/
|
||||
moveItems(from = 0, to = this.items.length) {
|
||||
const n = Math.min(to, this.items.length, this.dots.length);
|
||||
for (let i = from; i < n; i++) {
|
||||
const it = this.items[i];
|
||||
this.dots.get(i).position = Cesium.Cartesian3.fromDegrees(
|
||||
it.lon,
|
||||
it.lat,
|
||||
it.altM || 0,
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < this.glyphs.length; i++) {
|
||||
const bb = this.glyphs.get(i);
|
||||
const it = this.byKey.get(bb.id.key);
|
||||
if (it)
|
||||
bb.position = Cesium.Cartesian3.fromDegrees(
|
||||
it.lon,
|
||||
it.lat,
|
||||
it.altM || 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Dead-reckon glyphs from their last fix. Returns true when anything moved. */
|
||||
tick(nowMs) {
|
||||
if (!this.deadReckon || !this.glyphMode) return false;
|
||||
let moved = false;
|
||||
for (let i = 0; i < this.glyphs.length; i++) {
|
||||
const bb = this.glyphs.get(i);
|
||||
const it = this.byKey.get(bb.id.key);
|
||||
if (!it || !it.speed || it.onGround || !it.seenAt) continue;
|
||||
const dt = Math.min(90, Math.max(0, (nowMs - it.seenAt) / 1000));
|
||||
const [lon, lat] = offsetLonLat(
|
||||
it.lon,
|
||||
it.lat,
|
||||
it.heading,
|
||||
it.speed * dt,
|
||||
);
|
||||
bb.position = Cesium.Cartesian3.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
it.altM || 0,
|
||||
undefined,
|
||||
this._scratch,
|
||||
);
|
||||
moved = true;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** Current (dead-reckoned) lon/lat of an item. */
|
||||
where(it, nowMs = Date.now()) {
|
||||
if (!this.deadReckon || !it.speed || it.onGround || !it.seenAt)
|
||||
return [it.lon, it.lat];
|
||||
const dt = Math.min(90, Math.max(0, (nowMs - it.seenAt) / 1000));
|
||||
return offsetLonLat(it.lon, it.lat, it.heading, it.speed * dt);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.items = [];
|
||||
this.byKey.clear();
|
||||
this.dots.removeAll();
|
||||
this.glyphs.removeAll();
|
||||
}
|
||||
}
|
||||
|
||||
export function inRect(rect, lon, lat) {
|
||||
if (lat < rect.south || lat > rect.north) return false;
|
||||
if (rect.west <= rect.east) return lon >= rect.west && lon <= rect.east;
|
||||
return lon >= rect.west || lon <= rect.east; // crosses the antimeridian
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The full layer catalog (DESIGN.md §8) in display order. Entries the
|
||||
* prototype renders are built by the family factories; the rest are listed
|
||||
* honestly as unavailable so the lens dock can show the whole catalog.
|
||||
*/
|
||||
import { UnavailableLayer } from './base.js';
|
||||
import { createSkyLayers } from './air.js';
|
||||
import { createOrbitLayers } from './orbit.js';
|
||||
import { createHazardLayers } from './hazards.js';
|
||||
import { createSeaLayers, createEyesLayers } from './sea.js';
|
||||
|
||||
export const FAMILIES = Object.freeze([
|
||||
'Sky',
|
||||
'Sea',
|
||||
'Orbit',
|
||||
'Hazards',
|
||||
'Eyes',
|
||||
'Ground',
|
||||
'Weather',
|
||||
'Infra',
|
||||
]);
|
||||
|
||||
export const CATALOG = Object.freeze([
|
||||
['Sky', 'flights', 'Commercial flights'],
|
||||
['Sky', 'military', 'Military aircraft'],
|
||||
['Sky', 'helicopters', 'Helicopters'],
|
||||
['Sky', 'ga', 'Private / GA'],
|
||||
['Sky', 'squawk', 'Emergency squawks'],
|
||||
['Sky', 'drones', 'Drones (Remote ID)'],
|
||||
['Sky', 'airport-boards', 'Airport boards'],
|
||||
['Sky', 'holding', 'Holding patterns'],
|
||||
['Sea', 'vessels', 'AIS vessels'],
|
||||
['Sea', 'ports', 'Ports'],
|
||||
['Sea', 'tankers', 'Tankers / cargo'],
|
||||
['Sea', 'fishing', 'Fishing effort'],
|
||||
['Sea', 'dark-vessels', 'Dark vessels (AIS gaps)'],
|
||||
['Sea', 'cables', 'Submarine cables'],
|
||||
['Orbit', 'satellites', 'Satellites (TLE)'],
|
||||
['Orbit', 'iss', 'ISS & crewed'],
|
||||
['Orbit', 'starlink', 'Starlink trains'],
|
||||
['Orbit', 'launches', 'Launches & trajectories'],
|
||||
['Orbit', 'debris', 'Debris'],
|
||||
['Orbit', 'passes', 'Ground tracks & passes'],
|
||||
['Hazards', 'earthquakes', 'Earthquakes'],
|
||||
['Hazards', 'fires', 'Active fires (FIRMS)'],
|
||||
['Hazards', 'fire-perimeters', 'Fire perimeters'],
|
||||
['Hazards', 'floods', 'Floods'],
|
||||
['Hazards', 'cyclones', 'Tropical cyclones'],
|
||||
['Hazards', 'volcanoes', 'Volcanoes'],
|
||||
['Hazards', 'air-quality', 'Air quality'],
|
||||
['Eyes', 'cctv', 'Public CCTV'],
|
||||
['Eyes', 'captures', 'Signed captures'],
|
||||
['Eyes', 'street-level', 'Street-level imagery'],
|
||||
['Eyes', 'holograms', 'Holograms'],
|
||||
['Eyes', 'streams', 'Live streams'],
|
||||
['Ground', 'transit', 'Transit vehicles'],
|
||||
['Ground', 'traffic', 'Traffic flow'],
|
||||
['Ground', 'bikeshare', 'Bike share'],
|
||||
['Ground', 'rail', 'Rail'],
|
||||
['Ground', 'venues', 'Events & venues'],
|
||||
['Ground', 'alpr', 'ALPR cameras'],
|
||||
['Weather', 'radar', 'Radar'],
|
||||
['Weather', 'clouds', 'Clouds'],
|
||||
['Weather', 'lightning', 'Lightning'],
|
||||
['Weather', 'wind', 'Wind'],
|
||||
['Weather', 'forecast', 'Forecast models'],
|
||||
['Infra', 'datacenters', 'Datacenters'],
|
||||
['Infra', 'dams', 'Dams'],
|
||||
['Infra', 'power', 'Power plants'],
|
||||
['Infra', 'installations', 'Military installations'],
|
||||
['Infra', 'gnss', 'GNSS interference'],
|
||||
['Infra', 'recent-imagery', 'Recent satellite imagery'],
|
||||
]);
|
||||
|
||||
/** Build every catalog layer; returns a Map id → layer in catalog order. */
|
||||
export function buildLayers(ctx, feeds) {
|
||||
const live = new Map();
|
||||
for (const layer of [
|
||||
...createSkyLayers(ctx, feeds),
|
||||
...createSeaLayers(ctx, feeds),
|
||||
...createOrbitLayers(ctx, feeds),
|
||||
...createHazardLayers(ctx, feeds),
|
||||
...createEyesLayers(ctx, feeds),
|
||||
])
|
||||
live.set(layer.id, layer);
|
||||
const out = new Map();
|
||||
for (const [family, id, name] of CATALOG) {
|
||||
const layer = live.get(id);
|
||||
if (layer) {
|
||||
layer.family = family;
|
||||
out.set(id, layer);
|
||||
} else out.set(id, new UnavailableLayer({ id, family, name }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
/**
|
||||
* Hazards family: earthquakes (USGS), active fires (NASA FIRMS, or NASA EONET
|
||||
* events when no FIRMS key), tropical cyclones (NOAA NHC + EONET) with
|
||||
* forecast tracks the time ribbon can scrub into, volcanoes (EONET) and the
|
||||
* bundled Bhote Koshi flood corridor.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { ContactRenderer, Layer, color, FAMILY_COLORS } from './base.js';
|
||||
import { relTime } from '../geo.js';
|
||||
|
||||
const HAZ = FAMILY_COLORS.Hazards;
|
||||
const WEEK = 7 * 86_400_000;
|
||||
|
||||
/** A point-event layer filtered to what had happened by the clock time. */
|
||||
class EventLayer extends Layer {
|
||||
constructor(ctx, def, opts) {
|
||||
super(ctx, def);
|
||||
this.feed = opts.feed;
|
||||
this.select = opts.select; // data → records [{id, lon, lat, t, ...}]
|
||||
this.style = opts.style; // (record, ageMs) → item fields
|
||||
this.describe = opts.describe; // (record, clockMs) → {title, subtitle, meta}
|
||||
this.windowMs = opts.windowMs ?? WEEK;
|
||||
this.kind = opts.kind;
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(opts.tint || HAZ),
|
||||
glyphName: opts.glyph,
|
||||
rotate: false,
|
||||
alwaysGlyph: opts.alwaysGlyph,
|
||||
lodHeightM: opts.lodHeightM ?? 3_000_000,
|
||||
cap: opts.cap ?? 400,
|
||||
dotScale: opts.dotScale ?? 0.5,
|
||||
glyphScale: opts.glyphScale ?? 0.5,
|
||||
});
|
||||
this.records = new Map();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
try {
|
||||
await this.feed.get();
|
||||
} finally {
|
||||
this.fromFeed(this.feed);
|
||||
}
|
||||
this._draw();
|
||||
}
|
||||
|
||||
_draw() {
|
||||
const data = this.feed.data;
|
||||
if (!data) return;
|
||||
const t = this.ctx.timeMs();
|
||||
const items = [];
|
||||
this.records = new Map();
|
||||
for (const r of this.select(data)) {
|
||||
const age = Number.isFinite(r.t) ? t - r.t : 0;
|
||||
if (age < 0 || age > this.windowMs) continue;
|
||||
this.records.set(r.id, r);
|
||||
items.push({
|
||||
key: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
altM: 0,
|
||||
...this.style(r, age),
|
||||
});
|
||||
}
|
||||
this.count = items.length;
|
||||
this.renderer.setItems(items);
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
onTime() {
|
||||
if (this.on) this._draw();
|
||||
}
|
||||
locate(key) {
|
||||
const r = this.records.get(key);
|
||||
return r ? [r.lon, r.lat, 0] : null;
|
||||
}
|
||||
pick(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
const d = this.describe(r, this.ctx.timeMs());
|
||||
return {
|
||||
kind: this.kind,
|
||||
id: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
...d,
|
||||
meta: { layer: this.id, source: this.source, ...d.meta },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function quakeColor(mag) {
|
||||
if (mag >= 6) return '#FF3B30';
|
||||
if (mag >= 5) return '#FF6A3D';
|
||||
if (mag >= 4) return '#FFA23D';
|
||||
return '#FFD08A';
|
||||
}
|
||||
|
||||
export function createHazardLayers(ctx, feeds) {
|
||||
const quakes = new EventLayer(
|
||||
ctx,
|
||||
{
|
||||
id: 'earthquakes',
|
||||
family: 'Hazards',
|
||||
name: 'Earthquakes',
|
||||
pollMs: 5 * 60_000,
|
||||
},
|
||||
{
|
||||
feed: feeds.quakes,
|
||||
kind: 'earthquake',
|
||||
glyph: 'quake',
|
||||
alwaysGlyph: true,
|
||||
cap: 600,
|
||||
select: (d) =>
|
||||
d.records.map((q) => ({ ...q, id: q.stableId, t: q.time })),
|
||||
style: (q, age) => {
|
||||
const fresh = age < 86_400_000;
|
||||
return {
|
||||
color: color(quakeColor(q.mag), fresh ? 1 : 0.55),
|
||||
glyphScale: 0.32 + Math.max(0, q.mag - 2.5) * 0.24,
|
||||
dotScale: 0.6 + Math.max(0, q.mag - 2.5) * 0.4,
|
||||
};
|
||||
},
|
||||
describe: (q, t) => ({
|
||||
title: `M${q.mag.toFixed(1)} earthquake`,
|
||||
subtitle: `${q.place || 'Unknown location'} · ${relTime(q.time, t)}`,
|
||||
meta: {
|
||||
magnitude: q.mag,
|
||||
depthKm: q.depthKm,
|
||||
time: q.time ? new Date(q.time).toISOString() : null,
|
||||
usgsId: q.usgsId,
|
||||
url: q.usgsId
|
||||
? `https://earthquake.usgs.gov/earthquakes/eventpage/${q.usgsId}`
|
||||
: null,
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const fires = new EventLayer(
|
||||
ctx,
|
||||
{
|
||||
id: 'fires',
|
||||
family: 'Hazards',
|
||||
name: 'Active fires (FIRMS)',
|
||||
pollMs: 10 * 60_000,
|
||||
},
|
||||
{
|
||||
feed: feeds.fires,
|
||||
kind: 'fire',
|
||||
glyph: 'fire',
|
||||
windowMs: 3 * 86_400_000,
|
||||
lodHeightM: 1_500_000,
|
||||
cap: 500,
|
||||
select: (d) => {
|
||||
// EONET events keep their last report date; a 3-day window would
|
||||
// hide long-running fires, so events show while open.
|
||||
if (d.mode === 'events')
|
||||
return d.records.map((r) => ({ ...r, t: null }));
|
||||
return d.records;
|
||||
},
|
||||
style: (f) => {
|
||||
const big = (f.frp ?? 0) > 50 || (f.acres ?? 0) > 5000;
|
||||
return {
|
||||
color: color(big ? '#FF5A1F' : '#FF9A3D', 0.95),
|
||||
glyphScale: big ? 0.75 : 0.55,
|
||||
dotScale: big ? 0.8 : 0.5,
|
||||
};
|
||||
},
|
||||
describe: (f, t) => ({
|
||||
title: f.title || 'Fire hotspot',
|
||||
subtitle: [
|
||||
f.acres ? `${Math.round(f.acres).toLocaleString()} acres` : null,
|
||||
f.frp ? `${f.frp.toFixed(0)} MW FRP` : null,
|
||||
Number.isFinite(f.t) ? relTime(f.t, t) : 'open event',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
meta: {
|
||||
frpMw: f.frp ?? null,
|
||||
acres: f.acres ?? null,
|
||||
url: f.link || null,
|
||||
},
|
||||
}),
|
||||
},
|
||||
);
|
||||
fires.refresh = async function () {
|
||||
await EventLayer.prototype.refresh.call(this);
|
||||
const d = this.feed.data;
|
||||
this.name = 'Active fires (FIRMS)';
|
||||
if (d?.mode === 'events') {
|
||||
this.message = d.firmsKeyRequired
|
||||
? 'FIRMS key not set on server — showing NASA EONET wildfire events'
|
||||
: 'FIRMS unavailable — showing NASA EONET wildfire events';
|
||||
}
|
||||
};
|
||||
|
||||
const volcanoes = new EventLayer(
|
||||
ctx,
|
||||
{
|
||||
id: 'volcanoes',
|
||||
family: 'Hazards',
|
||||
name: 'Volcanoes',
|
||||
pollMs: 30 * 60_000,
|
||||
},
|
||||
{
|
||||
feed: feeds.eonet,
|
||||
kind: 'volcano',
|
||||
glyph: 'volcano',
|
||||
alwaysGlyph: true,
|
||||
windowMs: Infinity,
|
||||
select: (d) => d.volcanoes.map((v) => ({ ...v, t: null })),
|
||||
style: () => ({ color: color('#FF7A45'), glyphScale: 0.6 }),
|
||||
describe: (v) => ({
|
||||
title: v.title,
|
||||
subtitle: `Active · since ${new Date(v.firstT).toISOString().slice(0, 10)}`,
|
||||
meta: { url: v.link },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
return [
|
||||
quakes,
|
||||
fires,
|
||||
new CycloneLayer(ctx, { feed: feeds.cyclones }),
|
||||
new FloodLayer(ctx, { feed: feeds.flood }),
|
||||
volcanoes,
|
||||
];
|
||||
}
|
||||
|
||||
/* ───────────────────────── Cyclones ───────────────────────── */
|
||||
|
||||
/** Position of a storm at a clock time: interpolated along the forecast. */
|
||||
export function stormPositionAt(storm, ms) {
|
||||
const f = storm.forecast;
|
||||
if (!f?.length)
|
||||
return { lon: storm.lon, lat: storm.lat, windKt: storm.windKt };
|
||||
const tau = (ms - storm.t) / 3_600_000;
|
||||
if (tau <= 0) return { lon: storm.lon, lat: storm.lat, windKt: storm.windKt };
|
||||
for (let i = 1; i < f.length; i++) {
|
||||
if (tau <= f[i].tauHours) {
|
||||
const a = f[i - 1];
|
||||
const b = f[i];
|
||||
const k = (tau - a.tauHours) / Math.max(1e-6, b.tauHours - a.tauHours);
|
||||
return {
|
||||
lon: a.lon + (b.lon - a.lon) * k,
|
||||
lat: a.lat + (b.lat - a.lat) * k,
|
||||
windKt: a.windKt + (b.windKt - a.windKt) * k,
|
||||
forecast: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null; // beyond the forecast
|
||||
}
|
||||
|
||||
class CycloneLayer extends Layer {
|
||||
constructor(ctx, { feed }) {
|
||||
super(ctx, {
|
||||
id: 'cyclones',
|
||||
family: 'Hazards',
|
||||
name: 'Tropical cyclones',
|
||||
pollMs: 15 * 60_000,
|
||||
});
|
||||
this.feed = feed;
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color('#FFFFFF'),
|
||||
glyphName: 'cyclone',
|
||||
rotate: false,
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 1.1,
|
||||
dotScale: 1.3,
|
||||
});
|
||||
this.lines = this.root.add(new Cesium.PolylineCollection());
|
||||
this.records = new Map();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
try {
|
||||
await this.feed.get();
|
||||
} finally {
|
||||
this.fromFeed(this.feed);
|
||||
}
|
||||
this._draw(true);
|
||||
}
|
||||
|
||||
_draw(full) {
|
||||
const data = this.feed.data;
|
||||
if (!data) return;
|
||||
const t = this.ctx.timeMs();
|
||||
const items = [];
|
||||
this.records = new Map();
|
||||
for (const s of data.records) {
|
||||
if (t < s.t - 6 * 86_400_000) continue;
|
||||
const p = stormPositionAt(s, t);
|
||||
if (!p) continue;
|
||||
this.records.set(s.id, { ...s, now: p });
|
||||
items.push({
|
||||
key: s.id,
|
||||
lon: p.lon,
|
||||
lat: p.lat,
|
||||
altM: 0,
|
||||
color: color(p.forecast ? '#FFD2C2' : '#FFFFFF', p.forecast ? 0.8 : 1),
|
||||
glyphScale: 0.8 + Math.min(1, (p.windKt || 40) / 140) * 0.7,
|
||||
});
|
||||
}
|
||||
this.count = items.length;
|
||||
this.renderer.setItems(items);
|
||||
if (full) this._lines(data.records);
|
||||
}
|
||||
|
||||
_lines(storms) {
|
||||
this.lines.removeAll();
|
||||
const dash = (css, a) =>
|
||||
Cesium.Material.fromType('PolylineDash', {
|
||||
color: color(css, a),
|
||||
dashLength: 14,
|
||||
});
|
||||
for (const s of storms) {
|
||||
if (s.forecast?.length > 1) {
|
||||
this.lines.add({
|
||||
positions: Cesium.Cartesian3.fromDegreesArray(
|
||||
[{ lon: s.lon, lat: s.lat }, ...s.forecast].flatMap((p) => [
|
||||
p.lon,
|
||||
p.lat,
|
||||
]),
|
||||
),
|
||||
width: 2.5,
|
||||
material: dash('#FFFFFF', 0.85),
|
||||
});
|
||||
}
|
||||
const cone = outerRing(s.cone);
|
||||
if (cone) {
|
||||
this.lines.add({
|
||||
positions: Cesium.Cartesian3.fromDegreesArray(cone.flat()),
|
||||
width: 1.5,
|
||||
material: Cesium.Material.fromType('Color', {
|
||||
color: color(HAZ, 0.7),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (s.pastTrack?.length > 1) {
|
||||
this.lines.add({
|
||||
positions: Cesium.Cartesian3.fromDegreesArray(
|
||||
s.pastTrack.flatMap((p) => [p.lon, p.lat]),
|
||||
),
|
||||
width: 2,
|
||||
material: Cesium.Material.fromType('Color', {
|
||||
color: color('#FFFFFF', 0.6),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
onTime() {
|
||||
if (this.on) this._draw(false);
|
||||
}
|
||||
locate(key) {
|
||||
const s = this.records.get(key);
|
||||
return s ? [s.now.lon, s.now.lat, 0] : null;
|
||||
}
|
||||
trail(key) {
|
||||
const s = this.records.get(key);
|
||||
if (!s) return [];
|
||||
return (
|
||||
s.pastTrack || [{ lon: s.lon, lat: s.lat }, ...(s.forecast || [])]
|
||||
).map((p) => [p.lon, p.lat, 0]);
|
||||
}
|
||||
pick(key) {
|
||||
const s = this.records.get(key);
|
||||
if (!s) return null;
|
||||
const label =
|
||||
s.label ||
|
||||
{
|
||||
HU: 'Hurricane',
|
||||
TS: 'Tropical storm',
|
||||
TD: 'Tropical depression',
|
||||
TY: 'Typhoon',
|
||||
TC: 'Cyclone',
|
||||
STS: 'Subtropical storm',
|
||||
}[s.classification] ||
|
||||
'Cyclone';
|
||||
const wind = s.now.windKt
|
||||
? `${Math.round(s.now.windKt * 1.852)} km/h`
|
||||
: null;
|
||||
return {
|
||||
kind: 'cyclone',
|
||||
id: s.id,
|
||||
title: `${label} ${s.name}`,
|
||||
subtitle: [
|
||||
wind,
|
||||
s.pressureHpa ? `${s.pressureHpa} hPa` : null,
|
||||
s.now.forecast ? 'forecast' : 'observed',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
lon: s.now.lon,
|
||||
lat: s.now.lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
windKt: s.now.windKt ?? null,
|
||||
pressureHpa: s.pressureHpa ?? null,
|
||||
movement: s.movement ?? null,
|
||||
basin: s.basin,
|
||||
url: s.link,
|
||||
source: s.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Elevation of the corridor vertex nearest a point (0 without a corridor). */
|
||||
function nearestElevation(corridor, lon, lat) {
|
||||
if (!corridor?.length) return 0;
|
||||
let best = corridor[0];
|
||||
let bestD = Infinity;
|
||||
for (const c of corridor) {
|
||||
const d = (c[0] - lon) ** 2 + (c[1] - lat) ** 2;
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = c;
|
||||
}
|
||||
}
|
||||
return best[2] || 0;
|
||||
}
|
||||
|
||||
function outerRing(geom) {
|
||||
if (!geom) return null;
|
||||
if (geom.type === 'Polygon') return geom.coordinates[0];
|
||||
if (geom.type === 'MultiPolygon') {
|
||||
let best = null;
|
||||
for (const poly of geom.coordinates)
|
||||
if (!best || poly[0].length > best.length) best = poly[0];
|
||||
return best;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ───────────────────────── Bhote Koshi flood ───────────────────────── */
|
||||
|
||||
class FloodLayer extends Layer {
|
||||
constructor(ctx, { feed }) {
|
||||
super(ctx, { id: 'floods', family: 'Hazards', name: 'Floods' });
|
||||
this.feed = feed;
|
||||
this.lines = this.root.add(new Cesium.PolylineCollection());
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(HAZ),
|
||||
glyphName: 'pin',
|
||||
rotate: false,
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.62,
|
||||
});
|
||||
this.anchors = new Map();
|
||||
this.overlay = null;
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const data = await this.feed.get();
|
||||
this.status = 'live';
|
||||
this.source = data.source;
|
||||
const corridor = data.corridor || data.path;
|
||||
this._drawLines(data, null);
|
||||
this._sampleTerrain(data);
|
||||
const ev = data.event;
|
||||
const items = [];
|
||||
this.anchors = new Map();
|
||||
const head = corridor[0];
|
||||
this.anchors.set('bhote-koshi', {
|
||||
id: 'bhote-koshi',
|
||||
title: ev?.title || 'Bhote Koshi outburst flood',
|
||||
subtitle: `Observed ${ev?.observedDate || '2026-08-26'} · reconstruction`,
|
||||
lon: head[0],
|
||||
lat: head[1],
|
||||
meta: { caveat: ev?.reconstruction?.caveat || null },
|
||||
});
|
||||
for (const a of ev?.witnessAnchors || []) {
|
||||
this.anchors.set(a.id, {
|
||||
id: a.id,
|
||||
title: a.title,
|
||||
subtitle: (a.details || []).join(' · '),
|
||||
lon: a.lon,
|
||||
lat: a.lat,
|
||||
meta: { url: a.sourceUrl || null },
|
||||
});
|
||||
}
|
||||
for (const a of this.anchors.values())
|
||||
items.push({
|
||||
key: a.id,
|
||||
lon: a.lon,
|
||||
lat: a.lat,
|
||||
altM: nearestElevation(data.corridor, a.lon, a.lat) + 30,
|
||||
glyphScale: a.id === 'bhote-koshi' ? 1.2 : 0.8,
|
||||
});
|
||||
this.renderer.setItems(items);
|
||||
this.count = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The corridor carries surveyed elevations; the longer GeoPera centreline
|
||||
* has none, so it takes terrain heights once terrain is available (until
|
||||
* then, the nearest corridor elevation). Lines sit 20 m above ground so
|
||||
* they neither sink into terrain nor float in parallax.
|
||||
*/
|
||||
_drawLines(data, pathHeights) {
|
||||
this.lines.removeAll();
|
||||
const glow = (css, power, alpha) =>
|
||||
Cesium.Material.fromType('PolylineGlow', {
|
||||
color: color(css, alpha),
|
||||
glowPower: power,
|
||||
taperPower: 1,
|
||||
});
|
||||
const pathPositions = data.path.flatMap(([lon, lat], i) => [
|
||||
lon,
|
||||
lat,
|
||||
(pathHeights?.[i] ?? nearestElevation(data.corridor, lon, lat)) + 20,
|
||||
]);
|
||||
this.lines.add({
|
||||
positions: Cesium.Cartesian3.fromDegreesArrayHeights(pathPositions),
|
||||
width: 5,
|
||||
material: glow('#5EC8FF', 0.16, 0.85),
|
||||
});
|
||||
if (data.corridor)
|
||||
this.lines.add({
|
||||
positions: Cesium.Cartesian3.fromDegreesArrayHeights(
|
||||
data.corridor.flatMap(([lon, lat, h]) => [lon, lat, (h || 0) + 20]),
|
||||
),
|
||||
width: 7,
|
||||
material: glow('#A6ECFF', 0.14, 0.9),
|
||||
});
|
||||
this.ctx.requestRender();
|
||||
}
|
||||
|
||||
async _sampleTerrain(data) {
|
||||
if (this._sampled) return;
|
||||
this._sampled = true;
|
||||
const viewer = this.ctx.viewer;
|
||||
// Terrain arrives asynchronously after boot.
|
||||
for (
|
||||
let i = 0;
|
||||
i < 20 &&
|
||||
!(viewer.terrainProvider instanceof Cesium.CesiumTerrainProvider);
|
||||
i++
|
||||
)
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
if (!(viewer.terrainProvider instanceof Cesium.CesiumTerrainProvider))
|
||||
return;
|
||||
try {
|
||||
const cartos = data.path.map(([lon, lat]) =>
|
||||
Cesium.Cartographic.fromDegrees(lon, lat),
|
||||
);
|
||||
const sampled = await Cesium.sampleTerrainMostDetailed(
|
||||
viewer.terrainProvider,
|
||||
cartos,
|
||||
);
|
||||
if (viewer.isDestroyed()) return;
|
||||
this._drawLines(
|
||||
data,
|
||||
sampled.map((c) => (Number.isFinite(c.height) ? c.height : null)),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('[globe:floods] terrain sample', error);
|
||||
}
|
||||
}
|
||||
|
||||
/** The 1 MB post-event image loads only once the camera is close. */
|
||||
_overlay() {
|
||||
const ev = this.feed.data?.event;
|
||||
const rect = ev?.imagery?.rectangle;
|
||||
const path = ev?.imagery?.after?.path;
|
||||
if (!rect || !path || this.overlay) return;
|
||||
const provider = Cesium.SingleTileImageryProvider.fromUrl(
|
||||
`/events/bhote-koshi-2026/${path}`,
|
||||
{
|
||||
rectangle: Cesium.Rectangle.fromDegrees(
|
||||
rect.west,
|
||||
rect.south,
|
||||
rect.east,
|
||||
rect.north,
|
||||
),
|
||||
credit: ev.imagery.after.source,
|
||||
},
|
||||
);
|
||||
this.overlay = Cesium.ImageryLayer.fromProviderAsync(provider, {
|
||||
alpha: 0.95,
|
||||
});
|
||||
this.overlay.show = this.on;
|
||||
this.ctx.viewer.imageryLayers.add(this.overlay);
|
||||
}
|
||||
|
||||
setOn(on) {
|
||||
super.setOn(on);
|
||||
if (this.overlay) this.overlay.show = Boolean(on);
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
if (this.on && view.heightM < 400_000) this._overlay();
|
||||
}
|
||||
locate(key) {
|
||||
const a = this.anchors.get(key);
|
||||
return a ? [a.lon, a.lat, 0] : null;
|
||||
}
|
||||
trail() {
|
||||
return this.feed.data?.path?.map(([lon, lat]) => [lon, lat, 0]) || [];
|
||||
}
|
||||
pick(key) {
|
||||
const a = this.anchors.get(key);
|
||||
if (!a) return null;
|
||||
return {
|
||||
kind: 'flood',
|
||||
...a,
|
||||
meta: { layer: this.id, source: this.source, ...a.meta },
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* Orbit family: satellites (CelesTrak TLE + SGP4), ISS & crewed stations with
|
||||
* a live orbit ribbon, Starlink, and launches. Positions follow the scene
|
||||
* clock, so scrubbing the time ribbon flies every satellite to that instant.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
twoline2satrec,
|
||||
propagate,
|
||||
gstime,
|
||||
eciToGeodetic,
|
||||
degreesLat,
|
||||
degreesLong,
|
||||
} from 'satellite.js';
|
||||
import { ContactRenderer, Layer, color, FAMILY_COLORS } from './base.js';
|
||||
import { relTime } from '../geo.js';
|
||||
|
||||
const ORBIT = FAMILY_COLORS.Orbit;
|
||||
const CREWED = new Set([25544, 48274]); // ISS (ZARYA), CSS (TIANHE)
|
||||
|
||||
/** Sub-satellite point and height for a satrec at a time, or null. */
|
||||
export function satPosition(satrec, ms) {
|
||||
const date = new Date(ms);
|
||||
let pv;
|
||||
try {
|
||||
pv = propagate(satrec, date);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const p = pv?.position;
|
||||
if (!p || typeof p === 'boolean' || !Number.isFinite(p.x)) return null;
|
||||
const g = eciToGeodetic(p, gstime(date));
|
||||
const v = pv.velocity;
|
||||
return {
|
||||
lon: degreesLong(g.longitude),
|
||||
lat: degreesLat(g.latitude),
|
||||
altM: g.height * 1000,
|
||||
speedMps: v ? Math.hypot(v.x, v.y, v.z) * 1000 : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Ground-track heading (deg) from two nearby samples. */
|
||||
function trackHeading(satrec, ms) {
|
||||
const a = satPosition(satrec, ms);
|
||||
const b = satPosition(satrec, ms + 10_000);
|
||||
if (!a || !b) return 0;
|
||||
const y =
|
||||
Math.sin(((b.lon - a.lon) * Math.PI) / 180) *
|
||||
Math.cos((b.lat * Math.PI) / 180);
|
||||
const x =
|
||||
Math.cos((a.lat * Math.PI) / 180) * Math.sin((b.lat * Math.PI) / 180) -
|
||||
Math.sin((a.lat * Math.PI) / 180) *
|
||||
Math.cos((b.lat * Math.PI) / 180) *
|
||||
Math.cos(((b.lon - a.lon) * Math.PI) / 180);
|
||||
return ((Math.atan2(y, x) * 180) / Math.PI + 360) % 360;
|
||||
}
|
||||
|
||||
export class SatelliteLayer extends Layer {
|
||||
constructor(ctx, def, opts) {
|
||||
super(ctx, { pollMs: 3 * 3600_000, ...def });
|
||||
this.feeds = opts.feeds;
|
||||
this.filter = opts.filter || (() => true);
|
||||
this.kind = opts.kind || 'satellite';
|
||||
this.slice = opts.slice ?? Infinity;
|
||||
this.orbitRibbon = Boolean(opts.orbitRibbon);
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(opts.tint || ORBIT),
|
||||
glyphName: opts.glyph || 'sat',
|
||||
lodHeightM: opts.lodHeightM ?? 9_000_000,
|
||||
cap: opts.cap ?? 250,
|
||||
rotate: false,
|
||||
dotScale: opts.dotScale ?? 0.32,
|
||||
glyphScale: opts.glyphScale ?? 0.42,
|
||||
alwaysGlyph: opts.alwaysGlyph,
|
||||
});
|
||||
this.sats = []; // { key, name, satrec, norad }
|
||||
this.byKey = new Map();
|
||||
this._rr = 0;
|
||||
this._lastMs = 0;
|
||||
if (this.orbitRibbon) {
|
||||
this.ribbons = this.root.add(new Cesium.PolylineCollection());
|
||||
}
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const results = await Promise.allSettled(this.feeds.map((f) => f.get()));
|
||||
const seen = new Set();
|
||||
const sats = [];
|
||||
let ok = false;
|
||||
this.feeds.forEach((feed, i) => {
|
||||
this.fromFeed(feed);
|
||||
if (results[i].status !== 'fulfilled') return;
|
||||
ok = true;
|
||||
for (const e of results[i].value.entries) {
|
||||
const norad = Number(e.line1.slice(2, 7));
|
||||
const key = String(e.line1.slice(2, 7).trim());
|
||||
if (seen.has(key) || !this.filter(e, norad)) continue;
|
||||
seen.add(key);
|
||||
let satrec;
|
||||
try {
|
||||
satrec = twoline2satrec(e.line1, e.line2);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
sats.push({
|
||||
key,
|
||||
name: e.name.replace(/^0 /, '').trim(),
|
||||
satrec,
|
||||
norad,
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!ok) throw results[0].reason;
|
||||
this.sats = sats;
|
||||
this.byKey = new Map(sats.map((s) => [s.key, s]));
|
||||
this._place(this.ctx.timeMs(), true);
|
||||
}
|
||||
|
||||
_place(ms, full) {
|
||||
const items = [];
|
||||
const keep = [];
|
||||
for (const s of this.sats) {
|
||||
const p = satPosition(s.satrec, ms);
|
||||
if (!p) continue;
|
||||
s.pos = p;
|
||||
keep.push(s);
|
||||
const crewed = CREWED.has(s.norad);
|
||||
items.push({
|
||||
key: s.key,
|
||||
lon: p.lon,
|
||||
lat: p.lat,
|
||||
altM: p.altM,
|
||||
glyph: s.norad === 25544 ? 'iss' : undefined,
|
||||
glyphScale: s.norad === 25544 ? 1.6 : crewed ? 1.2 : 1,
|
||||
dotScale: crewed ? 2.2 : 1,
|
||||
color: crewed ? color('#FFFFFF') : undefined,
|
||||
});
|
||||
}
|
||||
this.count = keep.length;
|
||||
if (full) this.renderer.setItems(items);
|
||||
this._lastMs = ms;
|
||||
this._drawRibbons(ms);
|
||||
}
|
||||
|
||||
_drawRibbons(ms) {
|
||||
if (!this.ribbons) return;
|
||||
this.ribbons.removeAll();
|
||||
for (const s of this.sats) {
|
||||
if (!CREWED.has(s.norad)) continue;
|
||||
const positions = [];
|
||||
// One orbit ahead, 30 min behind, sampled every 60 s.
|
||||
for (let t = -30; t <= 93; t++) {
|
||||
const p = satPosition(s.satrec, ms + t * 60_000);
|
||||
if (p)
|
||||
positions.push(Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.altM));
|
||||
}
|
||||
if (positions.length < 2) continue;
|
||||
this.ribbons.add({
|
||||
positions,
|
||||
width: s.norad === 25544 ? 3 : 2,
|
||||
material: Cesium.Material.fromType('PolylineGlow', {
|
||||
color: color(s.norad === 25544 ? '#E9DDFF' : ORBIT, 0.32),
|
||||
glowPower: 0.18,
|
||||
taperPower: 1,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Propagate to `ms`: the glyph-visible satellites plus a round-robin slice. */
|
||||
_advance(ms) {
|
||||
const items = this.renderer.items;
|
||||
if (!items.length) return false;
|
||||
const n = items.length;
|
||||
const slice = Math.min(n, this.slice);
|
||||
const from = this._rr % n;
|
||||
const to = Math.min(n, from + slice);
|
||||
for (let i = from; i < to; i++) this._updateItem(items[i], ms);
|
||||
for (let i = 0; i < this.renderer.glyphs.length; i++) {
|
||||
const it = this.renderer.byKey.get(this.renderer.glyphs.get(i).id.key);
|
||||
if (it) this._updateItem(it, ms);
|
||||
}
|
||||
this.renderer.moveItems(from, to);
|
||||
this._rr = to >= n ? 0 : to;
|
||||
return true;
|
||||
}
|
||||
|
||||
_updateItem(it, ms) {
|
||||
const s = this.byKey.get(it.key);
|
||||
const p = s && satPosition(s.satrec, ms);
|
||||
if (!p) return;
|
||||
s.pos = p;
|
||||
it.lon = p.lon;
|
||||
it.lat = p.lat;
|
||||
it.altM = p.altM;
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
|
||||
onTime(ms) {
|
||||
if (!this.sats.length) return;
|
||||
if (this.sats.length <= 3000) {
|
||||
for (const it of this.renderer.items) this._updateItem(it, ms);
|
||||
this.renderer.moveItems();
|
||||
} else this._advance(ms);
|
||||
this._lastMs = ms;
|
||||
this._drawRibbons(ms);
|
||||
}
|
||||
|
||||
onTick(nowMs, live, clockMs) {
|
||||
if (!this.sats.length) return false;
|
||||
if (Math.abs(clockMs - this._lastMs) < 900) return false;
|
||||
this._advance(clockMs);
|
||||
if (this.ribbons && Math.abs(clockMs - (this._ribbonMs || 0)) > 60_000) {
|
||||
this._ribbonMs = clockMs;
|
||||
this._drawRibbons(clockMs);
|
||||
}
|
||||
this._lastMs = clockMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
locate(key) {
|
||||
const s = this.byKey.get(key);
|
||||
const p = s && satPosition(s.satrec, this.ctx.timeMs());
|
||||
return p ? [p.lon, p.lat, p.altM] : null;
|
||||
}
|
||||
|
||||
trail(key) {
|
||||
const s = this.byKey.get(key);
|
||||
if (!s) return [];
|
||||
const ms = this.ctx.timeMs();
|
||||
const out = [];
|
||||
for (let t = -45; t <= 45; t += 1) {
|
||||
const p = satPosition(s.satrec, ms + t * 60_000);
|
||||
if (p) out.push([p.lon, p.lat, p.altM]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
satrecFor(norad) {
|
||||
return this.sats.find((s) => s.norad === norad)?.satrec || null;
|
||||
}
|
||||
|
||||
pick(key) {
|
||||
const s = this.byKey.get(key);
|
||||
if (!s) return null;
|
||||
const p = satPosition(s.satrec, this.ctx.timeMs());
|
||||
if (!p) return null;
|
||||
return {
|
||||
kind: this.kind,
|
||||
id: s.key,
|
||||
title: s.name,
|
||||
subtitle: `NORAD ${s.norad} · ${Math.round(p.altM / 1000)} km · ${(p.speedMps / 1000).toFixed(1)} km/s`,
|
||||
lon: p.lon,
|
||||
lat: p.lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
norad: s.norad,
|
||||
altitudeM: p.altM,
|
||||
speedMps: p.speedMps,
|
||||
headingDeg: trackHeading(s.satrec, this.ctx.timeMs()),
|
||||
source: this.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
contacts() {
|
||||
const ms = this.ctx.timeMs();
|
||||
return this.sats
|
||||
.filter((s) => s.pos)
|
||||
.map((s) => ({
|
||||
kind: this.kind,
|
||||
id: s.key,
|
||||
title: s.name,
|
||||
lon: s.pos.lon,
|
||||
lat: s.pos.lat,
|
||||
altM: s.pos.altM,
|
||||
headingDeg: CREWED.has(s.norad) ? trackHeading(s.satrec, ms) : null,
|
||||
layer: this.id,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/** Per pad: the next pending launch beats any past one; else the latest. */
|
||||
function betterLaunch(a, b, t) {
|
||||
const ap = a.net >= t;
|
||||
const bp = b.net >= t;
|
||||
if (ap !== bp) return ap;
|
||||
return ap ? a.net < b.net : a.net > b.net;
|
||||
}
|
||||
|
||||
export class LaunchLayer extends Layer {
|
||||
constructor(ctx, def, { feed }) {
|
||||
super(ctx, { pollMs: 30 * 60_000, ...def });
|
||||
this.feed = feed;
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(ORBIT),
|
||||
glyphName: 'rocket',
|
||||
rotate: false,
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.62,
|
||||
dotScale: 0.8,
|
||||
});
|
||||
this.records = new Map();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
try {
|
||||
await this.feed.get();
|
||||
} finally {
|
||||
this.fromFeed(this.feed);
|
||||
}
|
||||
this._draw();
|
||||
}
|
||||
|
||||
_draw() {
|
||||
const data = this.feed.data;
|
||||
if (!data) return;
|
||||
const t = this.ctx.timeMs();
|
||||
const items = [];
|
||||
this.records = new Map();
|
||||
// One marker per pad: the next launch from it, or its most recent one.
|
||||
const byPad = new Map();
|
||||
for (const r of data.records) {
|
||||
const key = `${r.lat.toFixed(3)},${r.lon.toFixed(3)}`;
|
||||
const cur = byPad.get(key);
|
||||
if (!cur || betterLaunch(r, cur, t)) byPad.set(key, r);
|
||||
}
|
||||
for (const r of byPad.values()) {
|
||||
this.records.set(r.id, r);
|
||||
const pending = r.net > t;
|
||||
const soon = pending && r.net - t < 7 * 86_400_000;
|
||||
items.push({
|
||||
key: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
altM: 0,
|
||||
color: pending
|
||||
? color(soon ? '#FFFFFF' : ORBIT, soon ? 1 : 0.85)
|
||||
: color(ORBIT, 0.45),
|
||||
glyphScale: soon ? 1.25 : 0.9,
|
||||
});
|
||||
}
|
||||
this.count = data.records.filter((r) => r.net > t).length;
|
||||
this.renderer.setItems(items);
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
|
||||
onTime() {
|
||||
this._draw();
|
||||
}
|
||||
|
||||
locate(key) {
|
||||
const r = this.records.get(key);
|
||||
return r ? [r.lon, r.lat, 0] : null;
|
||||
}
|
||||
|
||||
pick(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
const t = this.ctx.timeMs();
|
||||
return {
|
||||
kind: 'launch',
|
||||
id: r.id,
|
||||
title: r.name,
|
||||
subtitle: `${r.provider || r.pad} · ${r.net > t ? 'T−' : ''}${relTime(r.net, t)}${r.status ? ` · ${r.status}` : ''}`,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
net: new Date(r.net).toISOString(),
|
||||
pad: r.pad,
|
||||
location: r.location,
|
||||
mission: r.mission,
|
||||
orbit: r.orbit,
|
||||
image: r.image,
|
||||
status: r.status,
|
||||
source: this.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function createOrbitLayers(
|
||||
ctx,
|
||||
{ visual, stations, gps, starlink, launches },
|
||||
) {
|
||||
return [
|
||||
new SatelliteLayer(
|
||||
ctx,
|
||||
{ id: 'satellites', family: 'Orbit', name: 'Satellites (TLE)' },
|
||||
{
|
||||
feeds: [visual, gps],
|
||||
filter: (e, norad) => !CREWED.has(norad),
|
||||
dotScale: 0.34,
|
||||
},
|
||||
),
|
||||
new SatelliteLayer(
|
||||
ctx,
|
||||
{ id: 'iss', family: 'Orbit', name: 'ISS & crewed' },
|
||||
{
|
||||
feeds: [stations],
|
||||
filter: (e, norad) => CREWED.has(norad),
|
||||
kind: 'station',
|
||||
alwaysGlyph: true,
|
||||
orbitRibbon: true,
|
||||
glyph: 'sat',
|
||||
},
|
||||
),
|
||||
new SatelliteLayer(
|
||||
ctx,
|
||||
{ id: 'starlink', family: 'Orbit', name: 'Starlink trains' },
|
||||
{
|
||||
feeds: [starlink],
|
||||
slice: 1500,
|
||||
dotScale: 0.22,
|
||||
tint: '#B9A2F0',
|
||||
cap: 200,
|
||||
lodHeightM: 3_000_000,
|
||||
},
|
||||
),
|
||||
new LaunchLayer(
|
||||
ctx,
|
||||
{ id: 'launches', family: 'Orbit', name: 'Launches & trajectories' },
|
||||
{ feed: launches },
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Sea family (AIS vessels, tankers/cargo, ports) and Eyes family (public
|
||||
* CCTV). AIS needs the server's AISSTREAM_API_KEY; without it the layers say
|
||||
* so instead of pretending the ocean is empty.
|
||||
*/
|
||||
import { ContactRenderer, Layer, color, FAMILY_COLORS } from './base.js';
|
||||
import { PORTS } from '../places.js';
|
||||
import { cctvFrameUrl } from '../feeds.js';
|
||||
|
||||
const SEA = FAMILY_COLORS.Sea;
|
||||
const EYES = FAMILY_COLORS.Eyes;
|
||||
const MPS_TO_KT = 1 / 0.514444;
|
||||
|
||||
class VesselLayer extends Layer {
|
||||
constructor(ctx, def, { feed, filter, tint }) {
|
||||
super(ctx, { pollMs: 20_000, ...def });
|
||||
this.feed = feed;
|
||||
this.filter = filter;
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(tint),
|
||||
glyphName: 'ship',
|
||||
lodHeightM: 1_200_000,
|
||||
cap: 800,
|
||||
deadReckon: true,
|
||||
dotScale: 0.34,
|
||||
glyphScale: 0.42,
|
||||
});
|
||||
this.records = new Map();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
try {
|
||||
await this.feed.get({ maxAgeMs: 15_000 });
|
||||
} catch (error) {
|
||||
this.fromFeed(this.feed);
|
||||
if (error.keyRequired) {
|
||||
this.status = 'error';
|
||||
this.message = error.message;
|
||||
this.count = 0;
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
this.fromFeed(this.feed);
|
||||
const records = this.feed.data.records.filter(this.filter);
|
||||
this.records = new Map(records.map((r) => [r.id, r]));
|
||||
this.count = records.length;
|
||||
const now = Date.now();
|
||||
this.renderer.setItems(
|
||||
records.map((r) => ({
|
||||
key: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
heading: r.heading,
|
||||
speed: r.speed,
|
||||
seenAt: now,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
onTime(ms, live) {
|
||||
this.renderer.setAlpha(live ? 1 : 0.3);
|
||||
}
|
||||
onTick(nowMs, live) {
|
||||
return live && this.renderer.tick(nowMs);
|
||||
}
|
||||
locate(key) {
|
||||
const it = this.renderer.byKey.get(key);
|
||||
if (!it) return null;
|
||||
const [lon, lat] = this.renderer.where(it);
|
||||
return [lon, lat, 0];
|
||||
}
|
||||
pick(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
const [lon, lat] = this.locate(key);
|
||||
return {
|
||||
kind: 'vessel',
|
||||
id: r.id,
|
||||
title: r.name,
|
||||
subtitle: [
|
||||
r.type || 'Vessel',
|
||||
Number.isFinite(r.speed)
|
||||
? `${(r.speed * MPS_TO_KT).toFixed(1)} kn`
|
||||
: null,
|
||||
r.destination ? `→ ${r.destination}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
lon,
|
||||
lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
mmsi: r.id,
|
||||
type: r.type,
|
||||
speedMps: r.speed,
|
||||
headingDeg: r.heading,
|
||||
destination: r.destination,
|
||||
source: this.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
contacts() {
|
||||
return [...this.records.values()].map((r) => {
|
||||
const [lon, lat] = this.locate(r.id) || [r.lon, r.lat];
|
||||
return {
|
||||
kind: 'vessel',
|
||||
id: r.id,
|
||||
title: r.name,
|
||||
lon,
|
||||
lat,
|
||||
altM: 0,
|
||||
headingDeg: r.heading,
|
||||
speedMps: r.speed,
|
||||
layer: this.id,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class PortsLayer extends Layer {
|
||||
constructor(ctx) {
|
||||
super(ctx, { id: 'ports', family: 'Sea', name: 'Ports' });
|
||||
this.source = 'Bundled reference (2024 throughput, M TEU)';
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(SEA),
|
||||
glyphName: 'port',
|
||||
rotate: false,
|
||||
alwaysGlyph: true,
|
||||
glyphScale: 0.5,
|
||||
});
|
||||
this.records = new Map(PORTS.map((p) => [p.id, p]));
|
||||
}
|
||||
async refresh() {
|
||||
this.status = 'live';
|
||||
this.count = PORTS.length;
|
||||
this.renderer.setItems(
|
||||
PORTS.map((p) => ({
|
||||
key: p.id,
|
||||
lon: p.lon,
|
||||
lat: p.lat,
|
||||
glyphScale: 0.7 + Math.min(1, p.teu / 40) * 0.6,
|
||||
})),
|
||||
);
|
||||
}
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
locate(key) {
|
||||
const p = this.records.get(key);
|
||||
return p ? [p.lon, p.lat, 0] : null;
|
||||
}
|
||||
pick(key) {
|
||||
const p = this.records.get(key);
|
||||
if (!p) return null;
|
||||
return {
|
||||
kind: 'port',
|
||||
id: p.id,
|
||||
title: p.name,
|
||||
subtitle: `${p.teu.toFixed(1)} M TEU / year`,
|
||||
lon: p.lon,
|
||||
lat: p.lat,
|
||||
meta: { layer: this.id, teu: p.teu, source: this.source },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class CctvLayer extends Layer {
|
||||
constructor(ctx, { feed }) {
|
||||
super(ctx, {
|
||||
id: 'cctv',
|
||||
family: 'Eyes',
|
||||
name: 'Public CCTV',
|
||||
pollMs: 30 * 60_000,
|
||||
});
|
||||
this.feed = feed;
|
||||
this.renderer = new ContactRenderer(this.root, {
|
||||
layerId: this.id,
|
||||
tint: color(EYES),
|
||||
glyphName: 'camera',
|
||||
lodHeightM: 250_000,
|
||||
cap: 250,
|
||||
dotScale: 0.3,
|
||||
glyphScale: 0.45,
|
||||
});
|
||||
this.records = new Map();
|
||||
}
|
||||
async refresh() {
|
||||
try {
|
||||
await this.feed.get();
|
||||
} finally {
|
||||
this.fromFeed(this.feed);
|
||||
}
|
||||
const records = this.feed.data.records;
|
||||
this.records = new Map(records.map((r) => [r.id, r]));
|
||||
this.count = records.length;
|
||||
this.renderer.setItems(
|
||||
records.map((r) => ({
|
||||
key: r.id,
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
altM: 0,
|
||||
heading: r.heading,
|
||||
})),
|
||||
);
|
||||
}
|
||||
onView(view) {
|
||||
this.renderer.setView(view);
|
||||
}
|
||||
locate(key) {
|
||||
const r = this.records.get(key);
|
||||
return r ? [r.lon, r.lat, 0] : null;
|
||||
}
|
||||
pick(key) {
|
||||
const r = this.records.get(key);
|
||||
if (!r) return null;
|
||||
return {
|
||||
kind: 'camera',
|
||||
id: r.id,
|
||||
title: r.name,
|
||||
subtitle: [r.city, r.provider].filter(Boolean).join(' · '),
|
||||
lon: r.lon,
|
||||
lat: r.lat,
|
||||
meta: {
|
||||
layer: this.id,
|
||||
frameUrl: cctvFrameUrl(r),
|
||||
headingDeg: r.heading,
|
||||
fovDeg: r.fovDeg,
|
||||
feedType: r.feedType,
|
||||
provider: r.provider,
|
||||
source: this.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const TANKER = /tanker|cargo|container|bulk/i;
|
||||
|
||||
export function createSeaLayers(ctx, { vessels }) {
|
||||
return [
|
||||
new VesselLayer(
|
||||
ctx,
|
||||
{ id: 'vessels', family: 'Sea', name: 'AIS vessels' },
|
||||
{ feed: vessels, filter: () => true, tint: SEA },
|
||||
),
|
||||
new PortsLayer(ctx),
|
||||
new VesselLayer(
|
||||
ctx,
|
||||
{ id: 'tankers', family: 'Sea', name: 'Tankers / cargo' },
|
||||
{ feed: vessels, filter: (r) => TANKER.test(r.type), tint: '#7FF0DC' },
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
export function createEyesLayers(ctx, { cctv }) {
|
||||
return [new CctvLayer(ctx, { feed: cctv })];
|
||||
}
|
||||
Reference in new issue
Block a user