Download app.js from udgamlabs/NanoCast: direct link, hf CLI and curl.
- Browser
- Download file 51.2 kB
-
https://huggingface.co/spaces/udgamlabs/NanoCast/resolve/main/app.js
- Command line
-
hf download hf://spaces/udgamlabs/NanoCast/app.js
-
curl -L -o app.js https://huggingface.co/spaces/udgamlabs/NanoCast/resolve/main/app.js
51.2 kB
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs";
import {
H, W, N_PROG, CH, GRAVITY, SIN_LAT, COS_LAT, LAYERS,
computeToaSolarFrame, decodeFloat16Buffer, float32ToFloat16Array,
sampleRamp, sampleFieldLatLon,
} from "./physics.js";
import { CITIES, matchLocalCities, resolveLocation, searchLocations } from "./cities.js";
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
ort.env.wasm.numThreads = 1;
ort.env.logLevel = "error";
// ---- Where the files come from ----
// The model, its config, stats and static fields load from Hugging Face (udgamlabs/NanoCast-40M), so every load is
// counted there. To use your own copy, open the page with ?base=<folder URL>/ (the folder needs the same files).
const HF = "https://huggingface.co/udgamlabs/NanoCast-40M/resolve/main/";
const BASE = new URLSearchParams(location.search).get("base") || HF;
// Today's start: a NOAA GFS analysis regridded to 1.5 degrees, refreshed every 6 hours by udgamlabs.com.
// If that cannot be reached, the page falls back to the snapshot bundled next to it (data/live/).
const LIVE = new URLSearchParams(location.search).get("live") || "https://udgamlabs.com/api/nanocast/live/";
const STATE_BYTES = 2 * 44 * 121 * 240 * 2;
// Storm replays and the bundled live snapshot: next to the page in the Space; the GitHub copy of the page reads them
// from the Space (set in index.html) so the repository stays small.
const DATA = document.querySelector('meta[name="nanocast-data"]')?.content || "./";
// ---- Anonymous counts (model, action, ok or error; never places, ids or cookies), only on the hosted Space ----
const COUNT_URL = "https://mcp.udgamlabs.com/count";
const COUNTING = location.hostname.endsWith(".hf.space");
function count(action, ok, from) {
if (!COUNTING) return;
try {
const body = { model: "nanocast", lang: "en", action, outcome: ok ? "ok" : "error", channel: "space-web" };
if (from) body.from = from;
if (location.search.includes("count=test")) body.test = true;
fetch(COUNT_URL, { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify(body), keepalive: true, credentials: "omit" }).catch(() => {});
} catch { /* counting never breaks the page */ }
}
// ---- Default place: a city near the browser's time zone (nothing is sent anywhere), else London ----
const TZ_CITY = {
"Asia/Calcutta": "Kolkata", "Asia/Kolkata": "Kolkata", "Europe/Kiev": "Warsaw", "Europe/Kyiv": "Warsaw",
"America/Sao_Paulo": "São Paulo", "America/Bogota": "Bogotá", "Asia/Saigon": "Ho Chi Minh City",
"Asia/Ho_Chi_Minh": "Ho Chi Minh City", "America/Vancouver": "Vancouver", "Pacific/Honolulu": "Honolulu",
"America/Phoenix": "Denver", "America/Detroit": "Chicago", "Europe/Brussels": "Amsterdam", "Europe/Prague": "Vienna",
"Europe/Budapest": "Vienna", "Europe/Copenhagen": "Stockholm", "Europe/Helsinki": "Stockholm",
"Asia/Riyadh": "Riyadh", "Asia/Karachi": "Karachi", "Asia/Dhaka": "Dhaka", "Asia/Kathmandu": "Kathmandu",
"Asia/Colombo": "Colombo", "Australia/Brisbane": "Sydney", "Australia/Perth": "Melbourne", "Africa/Casablanca": "Lisbon",
"America/Halifax": "Montreal", "America/Edmonton": "Denver", "America/Winnipeg": "Chicago", "Asia/Shanghai": "Shanghai",
};
function defaultPlace() {
let tz = "";
try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch {}
const want = TZ_CITY[tz] || tz.split("/").pop().replace(/_/g, " ");
let c = CITIES.find((x) => x.name.toLowerCase() === want.toLowerCase());
if (!c) {
// Not in the list: take the city in the same region whose longitude best fits the current UTC offset.
const box = { Europe: [35, 72, -25, 45], America: [-56, 72, -170, -30], Asia: [-11, 60, 25, 150],
Africa: [-35, 38, -20, 52], Australia: [-45, -10, 110, 155] }[tz.split("/")[0]];
if (box) {
const lonGuess = -new Date().getTimezoneOffset() / 4;
const near = CITIES.filter((x) => x.lat >= box[0] && x.lat <= box[1] && x.lon >= box[2] && x.lon <= box[3])
.sort((x, y) => Math.abs(x.lon - lonGuess) - Math.abs(y.lon - lonGuess));
c = near[0];
}
}
c = c || CITIES.find((x) => x.name === "London");
return { name: c.name, country: c.country, lat: c.lat, lon: c.lon };
}
const noteEl = document.getElementById("note");
function showNote(html) { noteEl.innerHTML = html; noteEl.hidden = false; }
// DOM refs
const container = document.getElementById("globe-container");
const pillGpu = document.getElementById("pill-gpu");
const pillModel = document.getElementById("pill-model");
const pillLatency = document.getElementById("pill-latency");
const scenarioSelect = document.getElementById("scenario-select");
const scenarioDesc = document.getElementById("scenario-desc");
const runBtn = document.getElementById("run-btn");
const progressWrap = document.getElementById("progress-wrap");
const progressFill = document.getElementById("progress-fill");
const progressStep = document.getElementById("progress-step");
const progressMs = document.getElementById("progress-ms");
const layerGrid = document.getElementById("layer-grid");
const legendTitle = document.getElementById("legend-title");
const legendBar = document.getElementById("legend-bar");
const legendMin = document.getElementById("legend-min");
const legendMid = document.getElementById("legend-mid");
const legendMax = document.getElementById("legend-max");
const toggleWind = document.getElementById("toggle-wind");
const toggleCoast = document.getElementById("toggle-coast");
const truthRow = document.getElementById("truth-row");
const toggleTruth = document.getElementById("toggle-truth");
const playBtn = document.getElementById("play-btn");
const stepSlider = document.getElementById("step-slider");
const leadLabel = document.getElementById("lead-label");
const utcLabel = document.getElementById("utc-label");
// Right-panel City + Exact Date/Time controls
const cityInput = document.getElementById("city-input");
const cityGoBtn = document.getElementById("city-go-btn");
const cityDropdown = document.getElementById("city-dropdown");
const quickCities = document.getElementById("quick-cities");
const tzLabel = document.getElementById("tz-label");
const pickerLead = document.getElementById("picker-lead");
const forecastDatetime = document.getElementById("forecast-datetime");
const quickTimes = document.getElementById("quick-times");
const pinTitle = document.getElementById("pin-title");
const pinSub = document.getElementById("pin-sub");
const pinCond = document.getElementById("pin-cond");
const pinT2m = document.getElementById("pin-t2m");
const pinT2mF = document.getElementById("pin-t2m-f");
const pinWind = document.getElementById("pin-wind");
const pinWindDir = document.getElementById("pin-wind-dir");
const pinTp = document.getElementById("pin-tp");
const pinTpNote = document.getElementById("pin-tp-note");
const pinMslp = document.getElementById("pin-mslp");
const pinT850 = document.getElementById("pin-t850");
const pinQ700 = document.getElementById("pin-q700");
const pinZ500 = document.getElementById("pin-z500");
const pinStatsEl = document.getElementById("pin-stats");
const chartTitleEl = document.getElementById("chart-title");
const chartMetaEl = document.getElementById("chart-meta");
const rolloutCta = document.getElementById("rollout-cta");
const meteogramSvg = document.getElementById("meteogram-svg");
const dailyStrip = document.getElementById("daily-strip");
// Local timezone short name (e.g. IST, PST, UTC)
const LOCAL_TZ = (() => {
try {
const parts = new Intl.DateTimeFormat(undefined, { timeZoneName: "short" }).formatToParts(new Date());
return parts.find((p) => p.type === "timeZoneName")?.value || "Local";
} catch { return "Local"; }
})();
tzLabel.textContent = LOCAL_TZ;
// Global app state
let session = null;
let stats = null;
let staticFields = null;
let scenarios = [];
let activeScenario = null;
let initPrevRaw = null;
let initCurRaw = null;
let truthSnapshots = null;
let frames = [];
let currentStep = 0; // integer step 0..40 for globe display
let exactLeadHours = 0.0; // exact lead hours [0..240] for interpolated city+time readout
let activeLayer = "t2m";
let activeChartMetric = "t2m"; // t2m | wspd | tp6h | mslp | t850 | q700
let playing = false;
let lastPlayMs = 0;
let selectedPin = defaultPlace();
let isRunning = false;
// ================= THREE.JS 3D EARTH GLOBE =================
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0.9, 3.05);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
container.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.06;
controls.enablePan = false;
controls.minDistance = 1.35;
controls.maxDistance = 5.0;
// Starfield
const starPos = new Float32Array(1200 * 3);
for (let i = 0; i < 1200; i++) {
const r = 18 + Math.random() * 20;
const th = Math.random() * Math.PI * 2;
const ph = Math.acos(2 * Math.random() - 1);
starPos[i * 3] = r * Math.sin(ph) * Math.cos(th);
starPos[i * 3 + 1] = r * Math.cos(ph);
starPos[i * 3 + 2] = r * Math.sin(ph) * Math.sin(th);
}
const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute("position", new THREE.BufferAttribute(starPos, 3));
scene.add(new THREE.Points(starGeo, new THREE.PointsMaterial({ color: 0x9ab8e8, size: 0.06, transparent: true, opacity: 0.65 })));
const texCanvas = document.createElement("canvas");
texCanvas.width = W;
texCanvas.height = H;
const texCtx = texCanvas.getContext("2d");
const texImg = texCtx.createImageData(W, H);
const globeTex = new THREE.CanvasTexture(texCanvas);
globeTex.wrapS = THREE.RepeatWrapping;
globeTex.wrapT = THREE.ClampToEdgeWrapping;
globeTex.minFilter = THREE.LinearFilter;
globeTex.magFilter = THREE.LinearFilter;
globeTex.colorSpace = THREE.SRGBColorSpace;
const earthGeo = new THREE.SphereGeometry(1.0, 96, 64);
const earthMat = new THREE.MeshBasicMaterial({ map: globeTex });
const earthMesh = new THREE.Mesh(earthGeo, earthMat);
scene.add(earthMesh);
// Atmospheric halo
const atmoGeo = new THREE.SphereGeometry(1.032, 64, 48);
const atmoMat = new THREE.ShaderMaterial({
transparent: true,
side: THREE.BackSide,
blending: THREE.AdditiveBlending,
depthWrite: false,
vertexShader: `
varying vec3 vNormal;
varying vec3 vViewPos;
void main() {
vNormal = normalize(normalMatrix * normal);
vec4 mv = modelViewMatrix * vec4(position, 1.0);
vViewPos = -mv.xyz;
gl_Position = projectionMatrix * mv;
}
`,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vViewPos;
void main() {
float rim = pow(0.62 - dot(vNormal, normalize(vViewPos)), 3.2);
gl_FragColor = vec4(0.22, 0.68, 1.0, clamp(rim * 0.9, 0.0, 0.7));
}
`,
});
scene.add(new THREE.Mesh(atmoGeo, atmoMat));
function latLonToVec3(latDeg, lonDeg, r = 1.003) {
const phi = ((90 - latDeg) * Math.PI) / 180;
const theta = ((lonDeg + 180) * Math.PI) / 180;
const x = -r * Math.sin(phi) * Math.cos(theta);
const y = r * Math.cos(phi);
const z = r * Math.sin(phi) * Math.sin(theta);
return new THREE.Vector3(x, y, z);
}
function vec3ToLatLon(v) {
const p = v.clone().normalize();
const lat = 90 - (Math.acos(Math.max(-1, Math.min(1, p.y))) * 180) / Math.PI;
let lon = (Math.atan2(p.z, -p.x) * 180) / Math.PI - 180;
if (lon < -180) lon += 360;
if (lon > 180) lon -= 360;
return { lat, lon };
}
// Coastlines
const coastGroup = new THREE.Group();
scene.add(coastGroup);
async function loadCoastlines() {
try {
const gj = await (await fetch("./data/coastlines_110m.geojson")).json();
const positions = [];
const addRing = (coords) => {
for (let i = 0; i < coords.length - 1; i++) {
const a = latLonToVec3(coords[i][1], coords[i][0], 1.003);
const b = latLonToVec3(coords[i + 1][1], coords[i + 1][0], 1.003);
positions.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
};
for (const f of gj.features) {
if (f.geometry.type === "LineString") addRing(f.geometry.coordinates);
else if (f.geometry.type === "MultiLineString") f.geometry.coordinates.forEach(addRing);
}
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
coastGroup.add(new THREE.LineSegments(geo, new THREE.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.58 })));
const gPos = [];
for (let lat = -60; lat <= 60; lat += 30) {
for (let lon = -180; lon < 180; lon += 6) {
const a = latLonToVec3(lat, lon, 1.002);
const b = latLonToVec3(lat, lon + 6, 1.002);
gPos.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
}
for (let lon = -180; lon < 180; lon += 30) {
for (let lat = -84; lat < 84; lat += 6) {
const a = latLonToVec3(lat, lon, 1.002);
const b = latLonToVec3(lat + 6, lon, 1.002);
gPos.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
}
const gGeo = new THREE.BufferGeometry();
gGeo.setAttribute("position", new THREE.Float32BufferAttribute(gPos, 3));
coastGroup.add(new THREE.LineSegments(gGeo, new THREE.LineBasicMaterial({ color: 0x9ec5ff, transparent: true, opacity: 0.14 })));
} catch (e) {
console.warn("Coastlines failed:", e);
}
}
// Animated 3D Wind Streamlines
const N_WIND = 2400;
const windLat = new Float32Array(N_WIND);
const windLon = new Float32Array(N_WIND);
const windAge = new Float32Array(N_WIND);
const windPos = new Float32Array(N_WIND * 6);
function resetWindParticle(i) {
windLat[i] = ((Math.asin(2 * Math.random() - 1) * 180) / Math.PI) * 0.94;
windLon[i] = Math.random() * 360 - 180;
windAge[i] = Math.random() * 60;
}
for (let i = 0; i < N_WIND; i++) resetWindParticle(i);
const windGeo = new THREE.BufferGeometry();
windGeo.setAttribute("position", new THREE.BufferAttribute(windPos, 3));
const windLines = new THREE.LineSegments(
windGeo,
new THREE.LineBasicMaterial({ color: 0xe6f4ff, transparent: true, opacity: 0.42 }),
);
scene.add(windLines);
function stepWindStreamlines() {
windLines.visible = toggleWind.checked && frames.length > 0;
if (!windLines.visible) return;
const f = frames[Math.min(currentStep, frames.length - 1)];
if (!f || !f.u10) return;
const u10 = f.u10;
const v10 = f.v10;
for (let i = 0; i < N_WIND; i++) {
windAge[i] += 1;
if (windAge[i] > 65 || Math.abs(windLat[i]) > 85) resetWindParticle(i);
const lat0 = windLat[i];
const lon0 = windLon[i];
const u = sampleFieldLatLon(u10, lat0, lon0);
const v = sampleFieldLatLon(v10, lat0, lon0);
const cosL = Math.max(0.18, Math.cos((lat0 * Math.PI) / 180));
const dt = 0.032;
const dLat = v * dt;
const dLon = (u / cosL) * dt;
const lat1 = Math.max(-85, Math.min(85, lat0 + dLat));
let lon1 = lon0 + dLon;
if (lon1 > 180) lon1 -= 360;
if (lon1 < -180) lon1 += 360;
windLat[i] = lat1;
windLon[i] = lon1;
const p0 = latLonToVec3(lat0, lon0, 1.007);
const p1 = latLonToVec3(lat0 + dLat * 3.0, lon0 + dLon * 3.0, 1.007);
const o = i * 6;
windPos[o] = p0.x; windPos[o + 1] = p0.y; windPos[o + 2] = p0.z;
windPos[o + 3] = p1.x; windPos[o + 4] = p1.y; windPos[o + 5] = p1.z;
}
windGeo.attributes.position.needsUpdate = true;
}
// Pin marker (outer glow + crisp cyan dot)
const pinGroup = new THREE.Group();
const pinCore = new THREE.Mesh(new THREE.SphereGeometry(0.017, 16, 16), new THREE.MeshBasicMaterial({ color: 0x38bdf8 }));
const pinRing = new THREE.Mesh(new THREE.SphereGeometry(0.030, 16, 16), new THREE.MeshBasicMaterial({ color: 0x38bdf8, transparent: true, opacity: 0.3 }));
pinGroup.add(pinCore, pinRing);
scene.add(pinGroup);
function placePin(lat, lon) {
pinGroup.position.copy(latLonToVec3(lat, lon, 1.013));
pinGroup.visible = true;
}
function focusCameraOn(latDeg, lonDeg) {
const dir = latLonToVec3(latDeg, lonDeg, 1.0).normalize();
camera.position.copy(dir.multiplyScalar(3.05));
controls.update();
}
// ================= WEATHER FIELD EXTRACTION & INTERPOLATION =================
function extractDisplayFrame(rawProg, diagTpModel = null) {
const N = H * W;
const t2m = new Float32Array(N);
const u10 = new Float32Array(N);
const v10 = new Float32Array(N);
const wspd10 = new Float32Array(N);
const mslp = new Float32Array(N);
const z500 = new Float32Array(N);
const t850 = new Float32Array(N);
const q700 = new Float32Array(N);
const tp6h = new Float32Array(N);
const oT2m = CH.T2M * N;
const oU10 = CH.U10 * N;
const oV10 = CH.V10 * N;
const oMslp = CH.MSLP * N;
const oZ500 = CH.Z500 * N;
const oT850 = CH.T850 * N;
const oQ700 = CH.Q700 * N;
for (let i = 0; i < N; i++) {
t2m[i] = rawProg[oT2m + i];
const u = rawProg[oU10 + i];
const v = rawProg[oV10 + i];
u10[i] = u;
v10[i] = v;
wspd10[i] = Math.sqrt(u * u + v * v);
mslp[i] = (rawProg[oMslp + i] + 101325.0) * 0.01;
z500[i] = (rawProg[oZ500 + i] + 55000.0) / (GRAVITY * 10.0);
t850[i] = rawProg[oT850 + i];
q700[i] = Math.max(0, rawProg[oQ700 + i]); // already g/kg in storage units
if (diagTpModel) {
const y = Math.max(0, Math.min(8, diagTpModel[i]));
tp6h[i] = Math.expm1(y);
}
}
return { t2m, u10, v10, wspd10, mslp, z500, t850, q700, tp6h };
}
// Bilinear (spatial) + Linear (temporal) interpolation at ANY (lat, lon, exactLeadHours)
function samplePointAtTime(lat, lon, leadH) {
if (frames.length === 0) return null;
const maxStep = frames.length - 1;
const fStep = Math.max(0, Math.min(maxStep, leadH / 6.0));
const s0 = Math.floor(fStep);
const s1 = Math.min(maxStep, Math.ceil(fStep));
const w = fStep - s0;
const interp = (key) => {
const v0 = sampleFieldLatLon(frames[s0][key], lat, lon);
if (s0 === s1 || w < 1e-4) return v0;
const v1 = sampleFieldLatLon(frames[s1][key], lat, lon);
return v0 * (1 - w) + v1 * w;
};
const u = interp("u10");
const v = interp("v10");
const wspd = Math.sqrt(u * u + v * v);
// Meteorological wind direction: direction wind blows FROM (deg clockwise from N)
const fromDeg = (((Math.atan2(-u, -v) * 180) / Math.PI) + 360) % 360;
const dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
const windDir = dirs[Math.round(fromDeg / 22.5) % 16];
return {
t2m: interp("t2m"),
u10: u,
v10: v,
wspd,
windDir,
mslp: interp("mslp"),
z500: interp("z500"),
t850: interp("t850"),
q700: interp("q700"),
tp6h: interp("tp6h"),
interpolated: s0 !== s1 && w > 0.02 && w < 0.98,
clampedToZero: frames.length === 1 && leadH > 0,
};
}
function classifyCondition(pt) {
if (pt.tp6h >= 15) return { label: "Heavy rain", rainNote: "Heavy downpour" };
if (pt.tp6h >= 4) return { label: "Rainy", rainNote: "Moderate rain" };
if (pt.tp6h >= 0.8) return { label: "Light rain", rainNote: "Light showers" };
if (pt.wspd >= 14) return { label: "Very windy", rainNote: "Dry, strong wind" };
if (pt.t2m <= 0) return { label: "Freezing, dry", rainNote: "Sub-zero" };
if (pt.t2m >= 36) return { label: "Hot, dry", rainNote: "Heat stress" };
if (pt.q700 >= 4.5) return { label: "Humid", rainNote: "Humid aloft" };
if (pt.t2m >= 26) return { label: "Warm, dry", rainNote: "Dry" };
if (pt.t2m >= 15) return { label: "Mild, dry", rainNote: "Dry" };
return { label: "Cool, dry", rainNote: "Dry" };
}
// Convert Unix seconds -> YYYY-MM-DDTHH:MM in browser's LOCAL timezone for <input type="datetime-local">
function unixToLocalInputValue(tsSec) {
const d = new Date(tsSec * 1000);
const pad = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function syncDatetimePickerFromLead() {
if (!activeScenario) return;
const ts = activeScenario.timestamp_s + Math.round(exactLeadHours * 3600);
forecastDatetime.min = unixToLocalInputValue(activeScenario.timestamp_s);
forecastDatetime.max = unixToLocalInputValue(activeScenario.timestamp_s + 240 * 3600);
forecastDatetime.value = unixToLocalInputValue(ts);
pickerLead.textContent = `+${exactLeadHours.toFixed(exactLeadHours % 1 === 0 ? 0 : 1)}h (day ${(exactLeadHours / 24).toFixed(1)})`;
quickTimes.querySelectorAll(".chip").forEach((c) => {
const h = Number(c.dataset.hours);
c.classList.toggle("active", Math.abs(h - exactLeadHours) < 0.5);
});
}
function renderGlobeTexture() {
if (frames.length === 0) return;
const step = Math.min(currentStep, frames.length - 1);
const cfg = LAYERS[activeLayer];
let field = frames[step][activeLayer];
if (toggleTruth.checked && truthSnapshots && truthSnapshots.has(step)) {
const tr = truthSnapshots.get(step);
if (tr[activeLayer]) field = tr[activeLayer];
}
const data = texImg.data;
const rgb = [0, 0, 0];
const invSpan = 1.0 / (cfg.max - cfg.min);
const halfW = W >> 1;
for (let y = 0; y < H; y++) {
const srcRow = (H - 1 - y) * W;
const dstRow = y * W;
for (let x = 0; x < W; x++) {
const srcX = (x + halfW) % W;
const v = field[srcRow + srcX];
const t = (v - cfg.min) * invSpan;
sampleRamp(cfg.stops, t, rgb);
const p = (dstRow + x) * 4;
data[p] = rgb[0];
data[p + 1] = rgb[1];
data[p + 2] = rgb[2];
data[p + 3] = 255;
}
}
texCtx.putImageData(texImg, 0, 0);
globeTex.needsUpdate = true;
const leadH = step * 6;
const day = (leadH / 24).toFixed(1);
const truthTag = (toggleTruth.checked && truthSnapshots && truthSnapshots.has(step)) ? " · ERA5 REALITY" : "";
leadLabel.textContent = `+${leadH}h (day ${day})${truthTag}`;
if (activeScenario) {
const d = new Date((activeScenario.timestamp_s + leadH * 3600) * 1000);
utcLabel.textContent = d.toISOString().slice(0, 16).replace("T", " ") + " UTC";
}
updatePinCard();
}
function updateLegend() {
const cfg = LAYERS[activeLayer];
legendTitle.textContent = `${cfg.name} (${cfg.unit})`;
const grad = cfg.stops
.map(([t, c]) => `rgb(${c[0]},${c[1]},${c[2]}) ${(t * 100).toFixed(0)}%`)
.join(", ");
legendBar.style.background = `linear-gradient(90deg, ${grad})`;
legendMin.textContent = `${cfg.min} ${cfg.unit}`;
legendMid.textContent = `${Math.round((cfg.min + cfg.max) / 2)}`;
legendMax.textContent = `${cfg.max} ${cfg.unit}`;
}
function updatePinCard() {
if (!selectedPin || frames.length === 0 || !activeScenario) return;
const { lat, lon, name, country } = selectedPin;
placePin(lat, lon);
const pt = samplePointAtTime(lat, lon, exactLeadHours);
if (!pt) return;
const ns = lat >= 0 ? "N" : "S";
const ew = lon >= 0 ? "E" : "W";
pinTitle.textContent = country && country !== "Custom" ? `${name}, ${country}` : name;
const targetDate = new Date((activeScenario.timestamp_s + exactLeadHours * 3600) * 1000);
const localStr = targetDate.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
const utcStr = targetDate.toISOString().slice(11, 16) + "Z";
pinSub.textContent = `${Math.abs(lat).toFixed(1)}°${ns}, ${Math.abs(lon).toFixed(1)}°${ew} · ${localStr} (${utcStr})`;
const cond = classifyCondition(pt);
pinCond.textContent = cond.label;
const tempF = pt.t2m * 1.8 + 32;
pinT2m.textContent = `${pt.t2m.toFixed(1)} °C`;
pinT2mF.textContent = `${tempF.toFixed(0)} °F`;
pinWind.textContent = `${(pt.wspd * 3.6).toFixed(0)} km/h`;
pinWindDir.textContent = `${pt.wspd.toFixed(1)} m/s · ${pt.windDir}`;
pinTp.textContent = `${pt.tp6h.toFixed(1)} mm`;
pinTpNote.textContent = frames.length === 1 ? "run the forecast" : cond.rainNote;
pinMslp.textContent = `${pt.mslp.toFixed(0)} hPa`;
pinT850.textContent = `${pt.t850.toFixed(1)} °C`;
pinQ700.textContent = `${pt.q700.toFixed(1)} g/kg`;
pinZ500.textContent = `Z500 ${pt.z500.toFixed(0)} dam`;
rolloutCta.style.display = frames.length <= 1 ? "block" : "none";
// 10-Day Interactive Multi-Metric Chart (switchable by clicking any of the 6 metric cards!)
const nF = frames.length;
const temps = [];
const rains = [];
const series = [];
for (let s = 0; s < nF; s++) {
const f = frames[s];
const t2 = sampleFieldLatLon(f.t2m, lat, lon);
const rn = sampleFieldLatLon(f.tp6h, lat, lon);
temps.push(t2);
rains.push(rn);
if (activeChartMetric === "t2m") series.push(t2);
else if (activeChartMetric === "wspd") series.push(sampleFieldLatLon(f.wspd10, lat, lon) * 3.6);
else if (activeChartMetric === "tp6h") series.push(rn);
else if (activeChartMetric === "mslp") series.push(sampleFieldLatLon(f.mslp, lat, lon));
else if (activeChartMetric === "t850") series.push(sampleFieldLatLon(f.t850, lat, lon));
else if (activeChartMetric === "q700") series.push(sampleFieldLatLon(f.q700, lat, lon));
}
const CHART_CFG = {
t2m: { title: "10 days of 2 m temperature (°C)", color: "#F3EFE6", fill: "rgba(157,185,230,0.16)", fmtAxis: (v) => `${Math.round(v)}°`, mode: "line", minZero: false },
wspd: { title: "10 days of 10 m wind (km/h)", color: "#F3EFE6", fill: "rgba(157,185,230,0.18)", fmtAxis: (v) => `${Math.round(v)}`, mode: "area", minZero: true },
tp6h: { title: "10 days of 6-hour rain (mm)", color: "#9DB9E6", fill: "rgba(157,185,230,0.75)", fmtAxis: (v) => `${v.toFixed(v < 10 ? 1 : 0)}`, mode: "bars", minZero: true },
mslp: { title: "10 days of sea-level pressure (hPa)", color: "#F3EFE6", fill: "rgba(157,185,230,0.16)", fmtAxis: (v) => `${Math.round(v)}`, mode: "area", minZero: false, refVal: 1013.25 },
t850: { title: "10 days of 850 hPa temperature (°C)", color: "#F3EFE6", fill: "rgba(157,185,230,0.16)", fmtAxis: (v) => `${Math.round(v)}°`, mode: "area", minZero: false },
q700: { title: "10 days of 700 hPa moisture (g/kg)", color: "#F3EFE6", fill: "rgba(157,185,230,0.16)", fmtAxis: (v) => `${v.toFixed(1)}`, mode: "area", minZero: true },
};
const cfg = CHART_CFG[activeChartMetric] || CHART_CFG.t2m;
chartTitleEl.textContent = cfg.title;
const sMinRaw = Math.min(...series);
const sMaxRaw = Math.max(...series);
if (activeChartMetric === "tp6h") {
const totalMm = rains.slice(1).reduce((a, b) => a + b, 0);
chartMetaEl.textContent = `10-day total: ${totalMm.toFixed(1)} mm`;
} else if (activeChartMetric === "wspd") {
chartMetaEl.textContent = `Peak: ${sMaxRaw.toFixed(0)} km/h`;
} else if (activeChartMetric === "mslp") {
chartMetaEl.textContent = `${Math.round(sMinRaw)}–${Math.round(sMaxRaw)} hPa`;
} else if (activeChartMetric === "q700") {
chartMetaEl.textContent = `${sMinRaw.toFixed(1)}–${sMaxRaw.toFixed(1)} g/kg`;
} else {
chartMetaEl.textContent = `${sMinRaw.toFixed(0)}° to ${sMaxRaw.toFixed(0)}°C`;
}
let yMin = cfg.minZero ? 0 : sMinRaw - Math.max(1.5, (sMaxRaw - sMinRaw) * 0.15);
let yMax = cfg.minZero ? Math.max(activeChartMetric === "tp6h" ? 5 : 10, sMaxRaw * 1.15) : sMaxRaw + Math.max(1.5, (sMaxRaw - sMinRaw) * 0.15);
if (yMax - yMin < 1e-3) yMax = yMin + 1;
const Wsvg = 306, Hsvg = 110, padL = 34, padR = 8, padT = 8, padB = 18;
const pw = Wsvg - padL - padR, ph = Hsvg - padT - padB;
const xAt = (i) => padL + (i / Math.max(1, nF - 1)) * pw;
const yAt = (v) => padT + ph - ((v - yMin) / (yMax - yMin)) * ph;
let bodySvg = "";
if (cfg.refVal !== undefined && cfg.refVal > yMin && cfg.refVal < yMax) {
const ry = yAt(cfg.refVal);
bodySvg += `<line x1="${padL}" y1="${ry.toFixed(1)}" x2="${Wsvg - padR}" y2="${ry.toFixed(1)}" stroke="rgba(255,255,255,0.16)" stroke-dasharray="2,3"/>`;
}
if (cfg.mode === "bars") {
const bw = Math.max(3, Math.min(7, pw / Math.max(1, nF) - 1.2));
bodySvg += series.map((v, i) => {
const x = xAt(i);
const y = yAt(v);
const bh = Math.max(0, padT + ph - y);
return `<rect x="${(x - bw / 2).toFixed(1)}" y="${y.toFixed(1)}" width="${bw.toFixed(1)}" height="${bh.toFixed(1)}" fill="${cfg.fill}" rx="1.2"/>`;
}).join("");
} else {
// On t2m chart, also show subtle background rain bars
if (activeChartMetric === "t2m") {
const rMax = Math.max(8, ...rains);
bodySvg += rains.map((r, i) => {
const bh = (r / rMax) * ph * 0.65;
return bh > 0.5 ? `<rect x="${(xAt(i) - 2).toFixed(1)}" y="${(padT + ph - bh).toFixed(1)}" width="4" height="${bh.toFixed(1)}" fill="rgba(157,185,230,0.36)" rx="1"/>` : "";
}).join("");
}
const pts = series.map((v, i) => `${xAt(i).toFixed(1)},${yAt(v).toFixed(1)}`).join(" ");
const areaPts = `${xAt(0).toFixed(1)},${(padT + ph).toFixed(1)} ${pts} ${xAt(nF - 1).toFixed(1)},${(padT + ph).toFixed(1)}`;
bodySvg += `<polygon points="${areaPts}" fill="${cfg.fill}"/>`;
bodySvg += `<polyline fill="none" stroke="${cfg.color}" stroke-width="2" points="${pts}"/>`;
}
const curFrac = nF > 1 ? Math.max(0, Math.min(1, exactLeadHours / ((nF - 1) * 6))) : 0;
const cx = padL + curFrac * pw;
const curVal = (() => {
if (activeChartMetric === "t2m") return pt.t2m;
if (activeChartMetric === "wspd") return pt.wspd * 3.6;
if (activeChartMetric === "tp6h") return pt.tp6h;
if (activeChartMetric === "mslp") return pt.mslp;
if (activeChartMetric === "t850") return pt.t850;
return pt.q700;
})();
const cy = yAt(Math.max(yMin, Math.min(yMax, curVal)));
meteogramSvg.innerHTML = `
<line x1="${padL}" y1="${padT}" x2="${padL}" y2="${padT + ph}" stroke="rgba(255,255,255,0.15)"/>
<line x1="${padL}" y1="${padT + ph}" x2="${Wsvg - padR}" y2="${padT + ph}" stroke="rgba(255,255,255,0.15)"/>
<text x="2" y="${padT + 8}" fill="#C9C3B6" font-size="9">${cfg.fmtAxis(yMax)}</text>
<text x="2" y="${padT + ph * 0.5 + 3}" fill="#8F8A7E" font-size="8.5">${cfg.fmtAxis((yMin + yMax) / 2)}</text>
<text x="2" y="${padT + ph}" fill="#C9C3B6" font-size="9">${cfg.fmtAxis(yMin)}</text>
<text x="${padL}" y="${Hsvg - 4}" fill="#C9C3B6" font-size="9">D0</text>
<text x="${padL + pw * 0.5 - 6}" y="${Hsvg - 4}" fill="#C9C3B6" font-size="9">D5</text>
<text x="${Wsvg - padR - 16}" y="${Hsvg - 4}" fill="#C9C3B6" font-size="9">D10</text>
${bodySvg}
<line x1="${cx.toFixed(1)}" y1="${padT}" x2="${cx.toFixed(1)}" y2="${padT + ph}" stroke="#9DB9E6" stroke-width="1.5" stroke-dasharray="3,2"/>
<circle cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="3.4" fill="${cfg.color}" stroke="#1C1B18" stroke-width="1.4"/>
`;
// Clickable 10-day daily High/Low/Rain strip (10 days -> 2 neat rows of 5)
if (nF > 4) {
const cards = [];
for (let day = 0; day < 10; day++) {
const sStart = day * 4;
const sEnd = Math.min(nF - 1, sStart + 4);
let hi = -Infinity, lo = Infinity, rn = 0;
for (let s = sStart; s <= sEnd; s++) {
if (temps[s] > hi) hi = temps[s];
if (temps[s] < lo) lo = temps[s];
if (s > sStart) rn += rains[s];
}
const dObj = new Date((activeScenario.timestamp_s + (sStart + 2) * 21600) * 1000);
const dLbl = dObj.toLocaleDateString(undefined, { month: "short", day: "numeric" });
const activeDay = Math.floor(exactLeadHours / 24) === day;
cards.push(`
<div class="day-card ${activeDay ? "active" : ""}" data-day-h="${(sStart + 2) * 6}">
<div class="d-lbl">${dLbl}</div>
<div class="d-hi">${Math.round(hi)}°</div>
<div class="d-lo">${Math.round(lo)}°</div>
<div class="d-rn">${rn >= 0.5 ? `${rn.toFixed(0)}mm` : "—"}</div>
</div>
`);
}
dailyStrip.innerHTML = cards.join("");
dailyStrip.querySelectorAll(".day-card").forEach((el) => {
el.addEventListener("click", () => {
setExactLeadHours(Number(el.dataset.dayH));
});
});
} else {
dailyStrip.innerHTML = "";
}
}
async function setExactLeadHours(hours, autoRunIfNeeded = true) {
const clamped = Math.max(0, Math.min(240, hours));
exactLeadHours = clamped;
playing = false;
playBtn.textContent = "▶";
if (autoRunIfNeeded && frames.length <= 1 && clamped > 0 && session && !isRunning) {
await runForecast10Days(false);
}
currentStep = Math.min(Math.round(exactLeadHours / 6), Math.max(0, frames.length - 1));
stepSlider.value = String(currentStep);
syncDatetimePickerFromLead();
renderGlobeTexture();
}
async function selectLocationObject(loc, autoRun = true) {
if (!loc) return;
selectedPin = { name: loc.name, country: loc.country || "", lat: loc.lat, lon: loc.lon };
cityInput.value = loc.name;
cityDropdown.classList.remove("open");
focusCameraOn(loc.lat, loc.lon);
placePin(loc.lat, loc.lon);
quickCities.querySelectorAll(".chip").forEach((c) => {
c.classList.toggle("active", c.dataset.city.toLowerCase() === loc.name.toLowerCase());
});
if (autoRun && frames.length <= 1 && session && !isRunning) {
await runForecast10Days(false);
}
updatePinCard();
}
// ================= WEBGPU MODEL LOADING & 10-DAY ROLLOUT =================
async function initWebGPUAndModel() {
if (!navigator.gpu) {
pillGpu.innerHTML = `WebGPU: <strong>not available</strong>`;
showNote("This demo needs WebGPU: Chrome or Edge on a desktop or laptop. The model card has a Python example that runs anywhere: <a href=\"https://huggingface.co/udgamlabs/NanoCast-40M\">huggingface.co/udgamlabs/NanoCast-40M</a>.");
} else {
try {
const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
const info = adapter?.info?.architecture || adapter?.info?.vendor || "ready";
const f16 = adapter?.features?.has("shader-f16") ? "FP16" : "FP32";
pillGpu.innerHTML = `WebGPU: <strong>${info} (${f16})</strong>`;
} catch {
pillGpu.innerHTML = `WebGPU: <strong>available</strong>`;
}
}
try {
// config.json first: it is the file Hugging Face counts as a download, and it names the other files.
const cfgResp = await fetch(BASE + "config.json", { credentials: "omit" });
if (!cfgResp.ok) throw new Error(`config.json: HTTP ${cfgResp.status}`);
const cfg = await cfgResp.json();
const [statsResp, stResp] = await Promise.all([
fetch(BASE + cfg.stats_file, { credentials: "omit" }),
fetch(BASE + cfg.static_file, { credentials: "omit" }),
]);
if (!statsResp.ok || !stResp.ok) throw new Error("stats or static fields missing");
stats = await statsResp.json();
const f32 = new Float32Array(await stResp.arrayBuffer());
const N = H * W;
staticFields = { orog: f32.subarray(0, N), lsm: f32.subarray(N, 2 * N) };
pillModel.innerHTML = `Model: <strong>downloading 80 MB</strong>`;
const modelResp = await fetch(BASE + cfg.model_file, { credentials: "omit" });
if (!modelResp.ok) throw new Error(`model: HTTP ${modelResp.status}`);
const buf = new Uint8Array(await modelResp.arrayBuffer());
const mb = (buf.byteLength / 1e6).toFixed(1);
pillModel.innerHTML = `Model: <strong>starting ${mb} MB</strong>`;
const t0 = performance.now();
session = await ort.InferenceSession.create(buf, {
executionProviders: [{ name: "webgpu" }],
graphOptimizationLevel: "all",
});
const loadMs = (performance.now() - t0).toFixed(0);
pillModel.innerHTML = `Model: <strong>${mb} MB, ready in ${loadMs} ms</strong>`;
runBtn.disabled = false;
count("load", true, "download");
} catch (e) {
pillModel.innerHTML = `Model: <strong>could not load</strong>`;
runBtn.textContent = "Model unavailable";
runBtn.disabled = true;
console.error("Model load error:", e);
count("load", false);
}
}
async function runForecast10Days(autoPlayAfter = true) {
if (!session || !stats || !staticFields || !initCurRaw || isRunning) return;
isRunning = true;
playing = false;
playBtn.textContent = "▶";
runBtn.disabled = true;
progressWrap.classList.add("active");
const N = H * W;
const mean = stats.mean;
const std = stats.std;
const normPrev = new Float32Array(N_PROG * N);
const normCur = new Float32Array(N_PROG * N);
for (let c = 0; c < N_PROG; c++) {
const m = mean[c], invS = 1.0 / std[c];
const off = c * N;
for (let i = 0; i < N; i++) {
normPrev[off + i] = (initPrevRaw[off + i] - m) * invS;
normCur[off + i] = (initCurRaw[off + i] - m) * invS;
}
}
const forcF32 = new Float32Array(6 * N);
forcF32.set(staticFields.orog, 0);
forcF32.set(staticFields.lsm, N);
for (let y = 0; y < H; y++) {
const sl = SIN_LAT[y], cl = COS_LAT[y];
const ro = y * W;
for (let x = 0; x < W; x++) {
forcF32[2 * N + ro + x] = sl;
forcF32[3 * N + ro + x] = cl;
}
}
let tPrev = new ort.Tensor("float16", float32ToFloat16Array(normPrev), [1, N_PROG, H, W]);
let tCur = new ort.Tensor("float16", float32ToFloat16Array(normCur), [1, N_PROG, H, W]);
const solar0 = new Float32Array(N);
const solar1 = new Float32Array(N);
const rawScratch = new Float32Array(N_PROG * N);
frames = [extractDisplayFrame(initCurRaw)];
const baseTs = activeScenario.timestamp_s;
computeToaSolarFrame(baseTs, solar0);
const inNames = session.inputNames;
const outNames = session.outputNames;
const dispChs = [CH.T2M, CH.U10, CH.V10, CH.MSLP, CH.Z500, CH.T850, CH.Q700];
const tStart = performance.now();
for (let s = 1; s <= 40; s++) {
computeToaSolarFrame(baseTs + s * 21600, solar1);
forcF32.set(solar0, 4 * N);
forcF32.set(solar1, 5 * N);
const tForc = new ort.Tensor("float16", float32ToFloat16Array(forcF32), [1, 6, H, W]);
const feeds = inNames.length === 3
? { [inNames[0]]: tCur, [inNames[1]]: tPrev, [inNames[2]]: tForc }
: { [inNames[0]]: tCur, [inNames[1]]: tForc };
const out = await session.run(feeds);
const nextTensor = out[outNames[0]];
const diagTensor = out[outNames[1]];
const nextData = nextTensor.data;
for (let k = 0; k < dispChs.length; k++) {
const c = dispChs[k];
const m = mean[c], sd = std[c];
const off = c * N;
for (let i = 0; i < N; i++) {
rawScratch[off + i] = Number(nextData[off + i]) * sd + m;
}
}
const diagData = diagTensor.data;
const diagF32 = new Float32Array(N);
for (let i = 0; i < N; i++) diagF32[i] = Number(diagData[i]);
frames.push(extractDisplayFrame(rawScratch, diagF32));
tPrev = tCur;
tCur = nextTensor;
solar0.set(solar1);
const elapsed = performance.now() - tStart;
progressFill.style.width = `${(s / 40) * 100}%`;
progressStep.textContent = `Step ${s} / 40 (day ${(s * 0.25).toFixed(2)})`;
progressMs.textContent = `${(elapsed / 1000).toFixed(2)}s (${(elapsed / s).toFixed(0)} ms/step)`;
if (s % 4 === 0 || s === 40) {
currentStep = s;
stepSlider.max = 40;
stepSlider.value = s;
renderGlobeTexture();
await new Promise((r) => setTimeout(r, 0));
}
}
const totalS = ((performance.now() - tStart) / 1000).toFixed(2);
pillLatency.innerHTML = `10 days: <strong>${totalS} s</strong>`;
count("run", true);
runBtn.disabled = false;
isRunning = false;
if (autoPlayAfter) {
currentStep = 0;
exactLeadHours = 0;
stepSlider.value = "0";
syncDatetimePickerFromLead();
renderGlobeTexture();
playing = true;
playBtn.textContent = "⏸";
} else {
currentStep = Math.min(Math.round(exactLeadHours / 6), 40);
stepSlider.value = String(currentStep);
syncDatetimePickerFromLead();
renderGlobeTexture();
}
}
// ================= SCENARIO LOADING =================
async function loadScenarios() {
scenarios = [];
const live = await loadLiveMeta();
if (live) {
const m = live.meta;
const bundled = live.from === "bundled";
scenarios.push({
id: "live_gfs",
title: `${bundled ? "Recent" : "Today"} · ${m.cycle_utc.slice(0, 16).replace("T", " ")} UTC`,
description: `The atmosphere as NOAA's GFS analysis saw it at ${m.cycle_utc.slice(0, 16).replace("T", " ")} UTC, regridded to 1.5°.` +
(bundled ? " Today's start could not be reached, so this is the snapshot bundled with the page." : " Refreshed every 6 hours."),
timestamp_s: m.timestamp_s,
bin: live.bin,
focus_lat: selectedPin.lat,
focus_lon: selectedPin.lon,
default_layer: "t2m",
});
}
try {
const storms = await (await fetch(DATA + "data/storms/storms_index.json")).json();
for (const st of storms) {
scenarios.push({ ...st, title: `${st.title} (${st.subtitle})`, bin: DATA + st.bin, truth_bin: DATA + st.truth_bin });
}
} catch (e) {
console.warn("No storms pack:", e);
}
scenarioSelect.innerHTML = scenarios
.map((s, idx) => `<option value="${idx}">${s.title}</option>`)
.join("");
if (scenarios.length > 0) await selectScenario(0);
}
// Today's start from udgamlabs.com, else the bundled snapshot. Returns { meta, bin, from } or null.
async function loadLiveMeta() {
const tries = [
{ json: LIVE + "latest.json", bin: LIVE + "latest.bin", from: "live" },
{ json: DATA + "data/live/gfs_latest.json", bin: DATA + "data/live/gfs_latest.bin", from: "bundled" },
];
for (const t of tries) {
try {
const r = await fetch(t.json, { credentials: "omit", cache: "no-cache" });
if (!r.ok) continue;
const meta = await r.json();
if (!meta || !meta.cycle_utc || !Number.isFinite(meta.timestamp_s)) continue;
return { meta, bin: t.bin, from: t.from, fallback: tries[1] };
} catch (e) {
console.warn("Live start not reachable:", t.json, e);
}
}
return null;
}
async function fetchState(url) {
const r = await fetch(url, { credentials: "omit" });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const buf = await r.arrayBuffer();
if (buf.byteLength !== STATE_BYTES) throw new Error(`unexpected size ${buf.byteLength}`);
return buf;
}
async function selectScenario(idx) {
activeScenario = scenarios[idx];
scenarioDesc.textContent = activeScenario.description || "";
activeLayer = activeScenario.default_layer || "t2m";
updateLayerButtons();
updateLegend();
focusCameraOn(activeScenario.focus_lat ?? selectedPin.lat, activeScenario.focus_lon ?? selectedPin.lon);
let stateBuf;
try {
stateBuf = await fetchState(activeScenario.bin);
} catch (e) {
if (activeScenario.id !== "live_gfs") throw e;
// The live file failed after its metadata loaded: fall back to the bundled snapshot.
console.warn("Live start failed, using the bundled snapshot:", e);
const meta = await (await fetch(DATA + "data/live/gfs_latest.json")).json();
activeScenario.bin = DATA + "data/live/gfs_latest.bin";
activeScenario.timestamp_s = meta.timestamp_s;
activeScenario.title = `Recent · ${meta.cycle_utc.slice(0, 16).replace("T", " ")} UTC`;
activeScenario.description = `The atmosphere as NOAA's GFS analysis saw it at ${meta.cycle_utc.slice(0, 16).replace("T", " ")} UTC, regridded to 1.5°. Today's start could not be reached, so this is the snapshot bundled with the page.`;
scenarioDesc.textContent = activeScenario.description;
scenarioSelect.options[idx].textContent = activeScenario.title;
stateBuf = await fetchState(activeScenario.bin);
}
const f32 = decodeFloat16Buffer(stateBuf);
const stride = N_PROG * H * W;
initPrevRaw = f32.subarray(0, stride);
initCurRaw = f32.subarray(stride, 2 * stride);
truthSnapshots = null;
toggleTruth.checked = false;
if (activeScenario.truth_bin) {
try {
const trResp = await fetch(activeScenario.truth_bin);
if (trResp.ok) {
const tf = decodeFloat16Buffer(await trResp.arrayBuffer());
truthSnapshots = new Map();
const N = H * W;
const leadSteps = [4, 12, 20, 28, 40];
leadSteps.forEach((L, k) => {
const base = k * 4 * N;
truthSnapshots.set(L, {
t2m: tf.subarray(base, base + N),
wspd10: tf.subarray(base + N, base + 2 * N),
mslp: tf.subarray(base + 2 * N, base + 3 * N),
z500: tf.subarray(base + 3 * N, base + 4 * N),
});
});
truthRow.style.display = "flex";
}
} catch {}
} else {
truthRow.style.display = "none";
}
frames = [extractDisplayFrame(initCurRaw)];
currentStep = 0;
exactLeadHours = 0;
stepSlider.value = "0";
stepSlider.max = "40";
playing = false;
playBtn.textContent = "▶";
syncDatetimePickerFromLead();
renderGlobeTexture();
}
// ================= UI WIRING =================
function updateLayerButtons() {
layerGrid.querySelectorAll(".layer-btn").forEach((b) => {
b.classList.toggle("active", b.dataset.layer === activeLayer);
});
}
Object.values(LAYERS).forEach((l) => {
const btn = document.createElement("button");
btn.className = "layer-btn";
btn.dataset.layer = l.id;
btn.textContent = l.short;
btn.addEventListener("click", () => {
activeLayer = l.id;
updateLayerButtons();
updateLegend();
renderGlobeTexture();
});
layerGrid.appendChild(btn);
});
scenarioSelect.addEventListener("change", () => selectScenario(Number(scenarioSelect.value)));
runBtn.addEventListener("click", () => runForecast10Days(true));
toggleCoast.addEventListener("change", () => { coastGroup.visible = toggleCoast.checked; });
toggleTruth.addEventListener("change", renderGlobeTexture);
stepSlider.addEventListener("input", () => {
playing = false;
playBtn.textContent = "▶";
currentStep = Math.min(Number(stepSlider.value), Math.max(0, frames.length - 1));
exactLeadHours = currentStep * 6;
syncDatetimePickerFromLead();
renderGlobeTexture();
});
playBtn.addEventListener("click", () => {
if (frames.length <= 1) {
if (session && !isRunning) runForecast10Days(true);
return;
}
playing = !playing;
playBtn.textContent = playing ? "⏸" : "▶";
});
// Click any of the 6 metric cards to switch the 10-day forecast chart
pinStatsEl.querySelectorAll(".stat-box[data-chart]").forEach((box) => {
box.addEventListener("click", () => {
activeChartMetric = box.dataset.chart;
pinStatsEl.querySelectorAll(".stat-box").forEach((b) => {
b.classList.toggle("active", b === box);
});
updatePinCard();
});
});
// Click directly anywhere on the 10-day SVG graph to jump to that exact time
meteogramSvg.addEventListener("click", (e) => {
if (frames.length <= 1) return;
const rect = meteogramSvg.getBoundingClientRect();
const relX = ((e.clientX - rect.left) / rect.width) * 306;
const padL = 34, padR = 8, pw = 306 - padL - padR;
const frac = Math.max(0, Math.min(1, (relX - padL) / pw));
setExactLeadHours(Math.round(frac * 240), false);
});
// City autocomplete & search
let searchTimer = null;
function renderCityDropdown(items) {
if (!items || items.length === 0) {
cityDropdown.classList.remove("open");
return;
}
cityDropdown.innerHTML = items
.map((c, i) => `<div class="city-opt" data-idx="${i}"><span>${c.name}</span><span class="ctry">${c.country || ""}</span></div>`)
.join("");
cityDropdown.classList.add("open");
cityDropdown.querySelectorAll(".city-opt").forEach((el) => {
el.addEventListener("mousedown", (e) => {
e.preventDefault();
selectLocationObject(items[Number(el.dataset.idx)], true);
});
});
}
cityInput.addEventListener("input", () => {
const q = cityInput.value.trim();
if (!q) { cityDropdown.classList.remove("open"); return; }
renderCityDropdown(matchLocalCities(q, 6));
clearTimeout(searchTimer);
searchTimer = setTimeout(async () => {
if (cityInput.value.trim() !== q) return;
const res = await searchLocations(q);
if (cityInput.value.trim() === q) renderCityDropdown(res);
}, 240);
});
cityInput.addEventListener("keydown", async (e) => {
if (e.key === "Enter") {
e.preventDefault();
const loc = await resolveLocation(cityInput.value);
if (loc) selectLocationObject(loc, true);
}
});
cityInput.addEventListener("blur", () => {
setTimeout(() => cityDropdown.classList.remove("open"), 150);
});
cityGoBtn.addEventListener("click", async () => {
const loc = await resolveLocation(cityInput.value || selectedPin.name);
if (loc) selectLocationObject(loc, true);
});
quickCities.querySelectorAll(".chip").forEach((btn) => {
btn.addEventListener("click", async () => {
const loc = await resolveLocation(btn.dataset.city);
if (loc) selectLocationObject(loc, true);
});
});
// Exact Date & Time picker -> temporal interpolation!
forecastDatetime.addEventListener("change", () => {
if (!activeScenario || !forecastDatetime.value) return;
const chosenMs = new Date(forecastDatetime.value).getTime();
if (!Number.isFinite(chosenMs)) return;
const diffH = (chosenMs / 1000 - activeScenario.timestamp_s) / 3600.0;
setExactLeadHours(diffH, true);
});
quickTimes.querySelectorAll(".chip").forEach((btn) => {
btn.addEventListener("click", () => {
setExactLeadHours(Number(btn.dataset.hours), true);
});
});
// Click anywhere on globe -> drop pin + show forecast
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let downPos = null;
renderer.domElement.addEventListener("pointerdown", (e) => { downPos = { x: e.clientX, y: e.clientY }; });
renderer.domElement.addEventListener("pointerup", (e) => {
if (!downPos) return;
const dist = Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y);
downPos = null;
if (dist > 6) return;
mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObject(earthMesh);
if (hits.length > 0) {
const { lat, lon } = vec3ToLatLon(hits[0].point);
const ns = lat >= 0 ? "N" : "S";
const ew = lon >= 0 ? "E" : "W";
selectLocationObject({
name: `${Math.abs(lat).toFixed(1)}°${ns}, ${Math.abs(lon).toFixed(1)}°${ew}`,
country: "picked on the globe",
lat,
lon,
}, false);
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
function animate(now) {
requestAnimationFrame(animate);
controls.update();
stepWindStreamlines();
if (playing && frames.length > 1 && now - lastPlayMs > 180) {
lastPlayMs = now;
currentStep = (currentStep + 1) % frames.length;
exactLeadHours = currentStep * 6;
stepSlider.value = String(currentStep);
syncDatetimePickerFromLead();
renderGlobeTexture();
}
renderer.render(scene, camera);
}
// Boot
updateLegend();
updateLayerButtons();
await Promise.all([loadCoastlines(), initWebGPUAndModel(), loadScenarios()]);
cityInput.value = selectedPin.name;
placePin(selectedPin.lat, selectedPin.lon);
updatePinCard();
requestAnimationFrame(animate);
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs";
import {
H, W, N_PROG, CH, GRAVITY, SIN_LAT, COS_LAT, LAYERS,
computeToaSolarFrame, decodeFloat16Buffer, float32ToFloat16Array,
sampleRamp, sampleFieldLatLon,
} from "./physics.js";
import { CITIES, matchLocalCities, resolveLocation, searchLocations } from "./cities.js";
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
ort.env.wasm.numThreads = 1;
ort.env.logLevel = "error";
// ---- Where the files come from ----
// The model, its config, stats and static fields load from Hugging Face (udgamlabs/NanoCast-40M), so every load is
// counted there. To use your own copy, open the page with ?base=<folder URL>/ (the folder needs the same files).
const HF = "https://huggingface.co/udgamlabs/NanoCast-40M/resolve/main/";
const BASE = new URLSearchParams(location.search).get("base") || HF;
// Today's start: a NOAA GFS analysis regridded to 1.5 degrees, refreshed every 6 hours by udgamlabs.com.
// If that cannot be reached, the page falls back to the snapshot bundled next to it (data/live/).
const LIVE = new URLSearchParams(location.search).get("live") || "https://udgamlabs.com/api/nanocast/live/";
const STATE_BYTES = 2 * 44 * 121 * 240 * 2;
// Storm replays and the bundled live snapshot: next to the page in the Space; the GitHub copy of the page reads them
// from the Space (set in index.html) so the repository stays small.
const DATA = document.querySelector('meta[name="nanocast-data"]')?.content || "./";
// ---- Anonymous counts (model, action, ok or error; never places, ids or cookies), only on the hosted Space ----
const COUNT_URL = "https://mcp.udgamlabs.com/count";
const COUNTING = location.hostname.endsWith(".hf.space");
function count(action, ok, from) {
if (!COUNTING) return;
try {
const body = { model: "nanocast", lang: "en", action, outcome: ok ? "ok" : "error", channel: "space-web" };
if (from) body.from = from;
if (location.search.includes("count=test")) body.test = true;
fetch(COUNT_URL, { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify(body), keepalive: true, credentials: "omit" }).catch(() => {});
} catch { /* counting never breaks the page */ }
}
// ---- Default place: a city near the browser's time zone (nothing is sent anywhere), else London ----
const TZ_CITY = {
"Asia/Calcutta": "Kolkata", "Asia/Kolkata": "Kolkata", "Europe/Kiev": "Warsaw", "Europe/Kyiv": "Warsaw",
"America/Sao_Paulo": "São Paulo", "America/Bogota": "Bogotá", "Asia/Saigon": "Ho Chi Minh City",
"Asia/Ho_Chi_Minh": "Ho Chi Minh City", "America/Vancouver": "Vancouver", "Pacific/Honolulu": "Honolulu",
"America/Phoenix": "Denver", "America/Detroit": "Chicago", "Europe/Brussels": "Amsterdam", "Europe/Prague": "Vienna",
"Europe/Budapest": "Vienna", "Europe/Copenhagen": "Stockholm", "Europe/Helsinki": "Stockholm",
"Asia/Riyadh": "Riyadh", "Asia/Karachi": "Karachi", "Asia/Dhaka": "Dhaka", "Asia/Kathmandu": "Kathmandu",
"Asia/Colombo": "Colombo", "Australia/Brisbane": "Sydney", "Australia/Perth": "Melbourne", "Africa/Casablanca": "Lisbon",
"America/Halifax": "Montreal", "America/Edmonton": "Denver", "America/Winnipeg": "Chicago", "Asia/Shanghai": "Shanghai",
};
function defaultPlace() {
let tz = "";
try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch {}
const want = TZ_CITY[tz] || tz.split("/").pop().replace(/_/g, " ");
let c = CITIES.find((x) => x.name.toLowerCase() === want.toLowerCase());
if (!c) {
// Not in the list: take the city in the same region whose longitude best fits the current UTC offset.
const box = { Europe: [35, 72, -25, 45], America: [-56, 72, -170, -30], Asia: [-11, 60, 25, 150],
Africa: [-35, 38, -20, 52], Australia: [-45, -10, 110, 155] }[tz.split("/")[0]];
if (box) {
const lonGuess = -new Date().getTimezoneOffset() / 4;
const near = CITIES.filter((x) => x.lat >= box[0] && x.lat <= box[1] && x.lon >= box[2] && x.lon <= box[3])
.sort((x, y) => Math.abs(x.lon - lonGuess) - Math.abs(y.lon - lonGuess));
c = near[0];
}
}
c = c || CITIES.find((x) => x.name === "London");
return { name: c.name, country: c.country, lat: c.lat, lon: c.lon };
}
const noteEl = document.getElementById("note");
function showNote(html) { noteEl.innerHTML = html; noteEl.hidden = false; }
// DOM refs
const container = document.getElementById("globe-container");
const pillGpu = document.getElementById("pill-gpu");
const pillModel = document.getElementById("pill-model");
const pillLatency = document.getElementById("pill-latency");
const scenarioSelect = document.getElementById("scenario-select");
const scenarioDesc = document.getElementById("scenario-desc");
const runBtn = document.getElementById("run-btn");
const progressWrap = document.getElementById("progress-wrap");
const progressFill = document.getElementById("progress-fill");
const progressStep = document.getElementById("progress-step");
const progressMs = document.getElementById("progress-ms");
const layerGrid = document.getElementById("layer-grid");
const legendTitle = document.getElementById("legend-title");
const legendBar = document.getElementById("legend-bar");
const legendMin = document.getElementById("legend-min");
const legendMid = document.getElementById("legend-mid");
const legendMax = document.getElementById("legend-max");
const toggleWind = document.getElementById("toggle-wind");
const toggleCoast = document.getElementById("toggle-coast");
const truthRow = document.getElementById("truth-row");
const toggleTruth = document.getElementById("toggle-truth");
const playBtn = document.getElementById("play-btn");
const stepSlider = document.getElementById("step-slider");
const leadLabel = document.getElementById("lead-label");
const utcLabel = document.getElementById("utc-label");