Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions infra/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ land):
| Anthropic | ≈ $0.10 per case (narrate + review) | — | ≤ 10 cases | $3 | — | — |

The caps, not Lambda time, set the revisit rate. FIRMS's own limit is per 10 minutes, so
`EARTHDECK_MAX_FIRMS_CALLS` can be raised (≈ 3,000 covers four full passes; one shard spends
~90) without risk; raising CDSE needs the account's monthly PU budget checked first. Caps
`EARTHDECK_MAX_FIRMS_CALLS` can be raised without risk (deployed: 6,000 — measured 2026-09-28,
a full pass now spends ~1,000–1,250, so 3,000 ran out by ~13:00 UTC and starved the evening sweep); raising CDSE needs the account's monthly PU budget checked first. Caps
reset at 00:00 UTC, so the 00:00 window's shards spend them first; later windows sweep what
is left, least-recently-swept first within each shard.

Expand Down
2 changes: 1 addition & 1 deletion infra/earthdeck.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ Resources:
# methane_anomaly may spend at most 10 of those; forest confirmations keep the rest.
EARTHDECK_MAX_CDSE_CALLS_METHANE_ANOMALY: "10"
EARTHDECK_MAX_GFW_CALLS: "400"
EARTHDECK_MAX_FIRMS_CALLS: "3000"
EARTHDECK_MAX_FIRMS_CALLS: "6000"
EARTHDECK_MAX_ANALYST_CASES: "10"
EARTHDECK_MAX_ANALYST_USD: "3"
NODE_OPTIONS: --enable-source-maps
Expand Down
28 changes: 27 additions & 1 deletion test/basemap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { test } from "node:test";
import assert from "node:assert/strict";
import { activeAt, availableBasemaps, basemaps, basemapStyle, captionAt, gibsDay, opacityFor } from "../web/src/layers/basemap.js";
import { activeAt, availableBasemaps, basemaps, basemapStyle, captionAt, gibsDay, knockOutNoData, liveDays, opacityFor } from "../web/src/layers/basemap.js";

const NOW = new Date("2026-09-27T12:00:00Z");

Expand Down Expand Up @@ -62,3 +62,29 @@ test("GIBS day: the last complete UTC day", () => {
assert.equal(gibsDay(new Date("2026-09-27T03:00:00Z")), "2026-09-25", "early UTC: yesterday's last passes may still be processing");
assert.equal(gibsDay(new Date("2026-03-01T08:00:00Z")), "2026-02-28");
});

test("live days: the partial days above the complete base day, oldest first", () => {
assert.deepEqual(liveDays(new Date("2026-09-27T12:00:00Z")), ["2026-09-27"]);
assert.deepEqual(liveDays(new Date("2026-09-27T03:00:00Z")), ["2026-09-26", "2026-09-27"], "before 06 UTC yesterday is partial too");
assert.deepEqual(liveDays(new Date("2026-03-01T00:30:00Z")), ["2026-02-28", "2026-03-01"]);
});

test("live imagery: today's passes sit right above the base, same zoom span; caption says today", () => {
const style = basemapStyle({ now: NOW, live: true });
const ids = style.layers.map((l) => l.id);
assert.deepEqual(ids.slice(0, 4), ["bm-gibs", "bm-live-2026-09-27-VIIRS_SNPP", "bm-live-2026-09-27-VIIRS_NOAA20", "bm-eox"]);
const overlay = style.layers[1]!;
assert.equal(overlay.maxzoom, 9, "fetched no deeper than the base");
assert.equal(
(style.sources[overlay.id] as { tiles: string[] }).tiles[0],
"gibs-live://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/2026-09-27/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg",
);
assert.equal(captionAt(2, basemaps(NOW, true)), "Satellite view today (NASA), rest from Sep 26");
assert.ok(!basemapStyle({ now: NOW }).layers.some((l) => l.id.startsWith("bm-live")), "off unless the browser can do it");
});

test("knockOutNoData: black (with JPEG noise) goes transparent, dark ocean stays", () => {
const px = new Uint8ClampedArray([0, 0, 0, 255, 6, 3, 8, 255, 12, 20, 45, 255, 200, 200, 200, 255]);
assert.equal(knockOutNoData(px), 2);
assert.deepEqual([px[3], px[7], px[11], px[15]], [0, 0, 255, 255]);
});
116 changes: 101 additions & 15 deletions web/src/layers/basemap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// The zoom-dependent basemap shared by the public site's map (web/src/site/map/explore.ts) and the
// live dashboard map (web/src/map.ts): today-ish NASA imagery when zoomed out, a sharp 10 m
// live dashboard map (web/src/map.ts): today's NASA imagery (filling in over yesterday's) when zoomed out, a sharp 10 m
// cloud-free Sentinel-2 mosaic when zoomed in, and light OpenStreetMap place names + roads on top.
//
// new maplibregl.Map({ style: basemapStyle(), … }); // sources + layers + glyphs, globe
Expand All @@ -9,6 +9,9 @@
// z0–9 NASA GIBS VIIRS SNPP Corrected Reflectance true colour, one day (Level9 = 375 m) — public
// domain. Yesterday UTC (two days back before 06 UTC): "today" is mostly black until the
// day's passes are processed, and a JPEG can't be transparent where there is no data yet.
// Live on top (`live: true`): the newer days' passes so far (VIIRS SNPP + NOAA-20), fetched
// through the `gibs-live://` protocol, which turns GIBS's no-data black transparent in the
// browser — so the globe fills in with today as the satellites pass, no deploy or job needed.
// z6–14 EOxCloudless (Sentinel-2 cloudless) 2025, 10 m, whole Earth — CC BY-NC-SA 4.0, free for
// non-commercial use with the attribution below, verbatim (https://cloudless.eox.at/license-non-commercial).
// The 2016 layer (`s2cloudless_3857`) is CC BY 4.0 if the site ever becomes commercial.
Expand All @@ -35,6 +38,8 @@ export interface BasemapEntry {
caption: string;
/** Name of a key this layer needs (env / config); the layer is skipped when it is absent. */
requiresKey?: string;
/** Partial newer-day layers drawn right above this one (bottom → top), same zoom span. */
overlays?: { id: string; tiles: string[] }[];
}

const GIBS = "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best";
Expand All @@ -50,16 +55,36 @@ export function gibsDay(now: Date): string {

const fmtDay = (day: string) => new Date(`${day}T00:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });

/** Bottom → top. Later entries fade in over earlier ones as you zoom in. */
export function basemaps(now: Date = new Date()): BasemapEntry[] {
/** URL scheme whose tiles get GIBS's no-data black made transparent (see `registerLiveImagery`). */
export const LIVE_SCHEME = "gibs-live";
const LIVE_SATS = ["VIIRS_SNPP", "VIIRS_NOAA20"] as const;
const gibsTile = (sat: string, day: string, scheme = "https") =>
`${scheme}://${GIBS.slice("https://".length)}/${sat}_CorrectedReflectance_TrueColor/default/${day}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg`;

/** The UTC days after the complete base day, up to today (oldest first): today's passes, and yesterday's
* too before 06 UTC — the partial days drawn over the base. */
export function liveDays(now: Date): string[] {
const out: string[] = [];
const today = now.toISOString().slice(0, 10);
for (let t = Date.parse(`${gibsDay(now)}T00:00:00Z`) + DAY_MS; ; t += DAY_MS) {
const d = new Date(t).toISOString().slice(0, 10);
out.push(d);
if (d >= today) return out;
}
}

/** Bottom → top. Later entries fade in over earlier ones as you zoom in. `live` adds today's passes. */
export function basemaps(now: Date = new Date(), live = false): BasemapEntry[] {
const day = gibsDay(now);
const overlays = live ? liveDays(now).flatMap((d) => LIVE_SATS.map((sat) => ({ id: `bm-live-${d}-${sat}`, tiles: [gibsTile(sat, d, LIVE_SCHEME)] }))) : undefined;
return [
{
id: "bm-gibs",
tiles: [`${GIBS}/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/${day}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg`],
tiles: [gibsTile("VIIRS_SNPP", day)],
maxzoom: 9,
attribution: `NASA EOSDIS GIBS · VIIRS ${day}`,
caption: `Daily satellite view, ${fmtDay(day)} (NASA)`,
attribution: live ? `NASA EOSDIS GIBS · VIIRS ${day} + today` : `NASA EOSDIS GIBS · VIIRS ${day}`,
caption: live ? `Satellite view today (NASA), rest from ${fmtDay(day)}` : `Daily satellite view, ${fmtDay(day)} (NASA)`,
...(overlays ? { overlays } : {}),
},
{
id: "bm-eox",
Expand Down Expand Up @@ -106,15 +131,71 @@ export function activeAt(zoom: number, list: BasemapEntry[]): BasemapEntry | und

export const captionAt = (zoom: number, list: BasemapEntry[]): string => activeAt(zoom, list)?.caption ?? "";

/** Raster layers: each drawn from its fade start, and dropped (no more fetching) once the next one is opaque. */
/** Raster layers: each drawn from its fade start, and dropped (no more fetching) once the next one is opaque.
* An entry's overlays sit right above it with the same zoom span. */
function rasterLayers(list: BasemapEntry[]): LayerSpecification[] {
return list.map((b, i) => {
return list.flatMap((b, i) => {
const next = list[i + 1];
const l: LayerSpecification = { id: b.id, type: "raster", source: b.id, paint: { "raster-opacity": opacityFor(b), "raster-fade-duration": 200 } };
if (b.fadeIn) l.minzoom = b.fadeIn[0];
if (next?.fadeIn) l.maxzoom = next.fadeIn[1] + 1;
return l;
const layer = (id: string): LayerSpecification => {
const l: LayerSpecification = { id, type: "raster", source: id, paint: { "raster-opacity": opacityFor(b), "raster-fade-duration": 200 } };
if (b.fadeIn) l.minzoom = b.fadeIn[0];
if (next?.fadeIn) l.maxzoom = next.fadeIn[1] + 1;
return l;
};
return [layer(b.id), ...(b.overlays ?? []).map((o) => layer(o.id))];
});
}

/** Make GIBS's no-data (pure black, give or take JPEG noise) transparent, in place. Returns pixels changed. */
export function knockOutNoData(rgba: Uint8ClampedArray, max = 8): number {
let n = 0;
for (let i = 0; i < rgba.length; i += 4) {
if (rgba[i]! <= max && rgba[i + 1]! <= max && rgba[i + 2]! <= max) {
rgba[i + 3] = 0;
n++;
}
}
return n;
}

// Browser canvas APIs, typed locally: the test build has no DOM lib.
interface Bmp { width: number; height: number; close(): void }
interface Ctx2d {
drawImage(b: Bmp, x: number, y: number): void;
getImageData(x: number, y: number, w: number, h: number): { data: Uint8ClampedArray };
putImageData(d: { data: Uint8ClampedArray }, x: number, y: number): void;
}
interface Canvas { width: number; height: number; getContext(k: "2d", o: object): Ctx2d | null; convertToBlob(o: { type: string }): Promise<Blob> }
const web = globalThis as unknown as { OffscreenCanvas?: new (w: number, h: number) => Canvas; createImageBitmap?: (b: Blob) => Promise<Bmp> };

/** Can this browser run the `gibs-live://` protocol? (OffscreenCanvas + createImageBitmap.) */
export const liveImagerySupported = (): boolean => !!web.OffscreenCanvas && !!web.createImageBitmap;

type AddProtocol = (name: string, load: (req: { url: string }, abort: AbortController) => Promise<{ data: ArrayBuffer }>) => void;
let registered = false;

/**
* Register `gibs-live://` once: fetch the https tile, make its no-data black transparent, hand MapLibre a
* PNG. Returns whether live imagery can be used (pass it to basemapStyle/mountBasemapCaption as `live`).
*/
export function registerLiveImagery(ml: { addProtocol: AddProtocol }): boolean {
if (!liveImagerySupported()) return false;
if (registered) return true;
registered = true;
ml.addProtocol(LIVE_SCHEME, async (req, abort) => {
const res = await fetch(`https${req.url.slice(LIVE_SCHEME.length)}`, { signal: abort.signal });
if (!res.ok) throw new Error(`${res.status} ${req.url}`);
const bmp = await web.createImageBitmap!(await res.blob());
const canvas = new web.OffscreenCanvas!(bmp.width, bmp.height);
const ctx = canvas.getContext("2d", { willReadFrequently: true })!;
ctx.drawImage(bmp, 0, 0);
bmp.close();
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
knockOutNoData(img.data);
ctx.putImageData(img, 0, 0);
return { data: await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer() };
});
return true;
}

// ---- labels + roads (OpenFreeMap, OpenMapTiles schema) --------------------------------------------------
Expand Down Expand Up @@ -167,15 +248,20 @@ function labelLayers(): LayerSpecification[] {

export interface BasemapOptions {
now?: Date;
/** Draw today's passes over the base day (needs `registerLiveImagery` to have returned true). */
live?: boolean;
/** Keys for optional keyed layers, by name (e.g. { ARCGIS_API_KEY: "…" }). */
keys?: Record<string, string | undefined>;
}

/** A complete globe style: imagery stack + OpenFreeMap names/roads. Callers may spread extra fields (sky). */
export function basemapStyle(opts: BasemapOptions = {}): StyleSpecification {
const list = availableBasemaps(basemaps(opts.now), opts.keys);
const list = availableBasemaps(basemaps(opts.now, opts.live), opts.keys);
const sources: Record<string, SourceSpecification> = {};
for (const b of list) sources[b.id] = { type: "raster", tiles: b.tiles, tileSize: 256, maxzoom: b.maxzoom, attribution: b.attribution };
for (const b of list) {
sources[b.id] = { type: "raster", tiles: b.tiles, tileSize: 256, maxzoom: b.maxzoom, attribution: b.attribution };
for (const o of b.overlays ?? []) sources[o.id] = { type: "raster", tiles: o.tiles, tileSize: 256, maxzoom: b.maxzoom };
}
sources[LABEL_SRC] = {
type: "vector",
url: `${OFM}/planet`, // TileJSON → dated tile path; its attribution: OpenFreeMap © OpenMapTiles, OpenStreetMap
Expand All @@ -194,7 +280,7 @@ export function basemapStyle(opts: BasemapOptions = {}): StyleSpecification {
* "Cloud-free mosaic, Sentinel-2 2025 (EOX)"), updated as the zoom crosses a fade midpoint.
*/
export function mountBasemapCaption(map: MlMap, opts: BasemapOptions = {}): IControl {
const list = availableBasemaps(basemaps(opts.now), opts.keys);
const list = availableBasemaps(basemaps(opts.now, opts.live), opts.keys);
const box = map.getContainer().ownerDocument.createElement("div"); // (no DOM lib in the test build)
box.className = "maplibregl-ctrl bm-caption";
const sync = () => {
Expand Down
2 changes: 1 addition & 1 deletion web/src/layers/weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const WEATHER_LAYERS = {
opacity: 0.85,
attribution: `${GIBS_CREDIT} · VIIRS`,
publicSafe: true,
note: "VIIRS true colour, latest day — one pass per place per day, not live.",
note: "VIIRS true colour, the last complete day — one pass per place per day, not live.",
},
precip: {
kind: "raster",
Expand Down
7 changes: 4 additions & 3 deletions web/src/map.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import maplibregl from "maplibre-gl";
import { EASE_IN_OUT } from "./site/map/model";
import { WEATHER_LAYERS, addLayer, mountLayerToggles, stormsLayer, type LayerHandle } from "./layers/weather";
import { basemapStyle, mountBasemapCaption } from "./layers/basemap";
import { basemapStyle, mountBasemapCaption, registerLiveImagery } from "./layers/basemap";
import type { BBox, Card, EventItem, FireItem, QuakeItem } from "./types";

let map: maplibregl.Map | null = null;
Expand All @@ -16,17 +16,18 @@ const FINDING_LAYER = "finding-src";
* create a WebGL context, so the rest of the dashboard (the live feed) keeps working.
*/
export function createMap(): boolean {
const liveSat = registerLiveImagery(maplibregl);
try {
map = new maplibregl.Map({
container: "map",
// Same globe + zoom-dependent imagery stack as the public site's map (web/src/layers/basemap.ts).
style: basemapStyle(),
style: basemapStyle({ live: liveSat }),
center: [0, 20],
zoom: 1.4,
attributionControl: { compact: true },
});
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "bottom-right");
mountBasemapCaption(map);
mountBasemapCaption(map, { live: liveSat });
// Keyless weather overlays (local dashboard = personal use, so RainViewer radar is allowed here).
const m = map;
const container = document.getElementById("map");
Expand Down
9 changes: 5 additions & 4 deletions web/src/site/map/explore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import maplibregl, { type GeoJSONSource, type MapLayerMouseEvent } from "maplibr
import "maplibre-gl/dist/maplibre-gl.css";
import "./explore.css";
import { el, reducedMotion } from "../../ui";
import { BASEMAP_LABELS_BELOW, basemaps, basemapStyle, captionAt, mountBasemapCaption } from "../../layers/basemap";
import { BASEMAP_LABELS_BELOW, basemaps, basemapStyle, captionAt, mountBasemapCaption, registerLiveImagery } from "../../layers/basemap";
import { addLayer, stormsLayer, WEATHER_LAYERS, type LayerHandle, type RasterSpec } from "../../layers/weather";
import { layerGroups, onLayerGroup, registerLayerGroup, type LayerGroup, type RegisteredLayer } from "../../layers/registry";
import type { Hub } from "../hub";
Expand Down Expand Up @@ -128,10 +128,11 @@ export function mountExplorer({ figure, data, hub }: Options): void {
figure.appendChild(xp);

let map: maplibregl.Map;
const liveSat = registerLiveImagery(maplibregl);
try {
map = new maplibregl.Map({
container: mapBox,
style: { ...basemapStyle(), sky: { "atmosphere-blend": ["interpolate", ["linear"], ["zoom"], 0, 0.9, 4, 0.5, 7, 0] } },
style: { ...basemapStyle({ live: liveSat }), sky: { "atmosphere-blend": ["interpolate", ["linear"], ["zoom"], 0, 0.9, 4, 0.5, 7, 0] } },
center: v0.center,
zoom: v0.zoom,
pitch: v0.pitch,
Expand All @@ -149,8 +150,8 @@ export function mountExplorer({ figure, data, hub }: Options): void {
// Test hook (browser tests project a case to screen pixels); read-only use, nothing secret.
(xp as HTMLElement & { xpMap?: maplibregl.Map }).xpMap = map;
map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), "bottom-right");
let caption = mountBasemapCaption(map);
const capList = basemaps();
let caption = mountBasemapCaption(map, { live: liveSat });
const capList = basemaps(new Date(), liveSat);
const capBox = document.getElementById("imagery-cap");
const syncCap = () => {
if (capBox) capBox.textContent = `Base imagery here: ${captionAt(map.getZoom(), capList)}.`;
Expand Down
Loading