Compare commits

..
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 17dc7c8a69 docs(changelog): add the #1721 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 18:03:30 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 e3f28a391f perf(weather): apply the infrared cloud key in the shell's shader
On the 3D Tiles host each Satellite clouds image (4096x2048 for the
regional product and for every detail window) was drawn to a canvas, read
back, given its transparency curve on the page and written back. The
lookup table halved that pass; this removes it. The shell's material now
samples the image as it was decoded and applies the same curve (brightest
channel, 2.2 power, smoothstep 0.40-0.70) in its fragment shader, scaled
by a strength uniform.

The shell's image cache no longer keys on the infrared mode, so changing
the filter strength sets one uniform: no fetch, no decode and no second
33 MB canvas per mode. Globe hosts keep the per-pixel transfer for their
draped imagery.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:05:56 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 ad369eb0de docs(changelog): add the #1713 fragment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:06:06 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 0b5ae6386e perf(weather): apply the infrared cloud transfer from a lookup table, in place
The Satellite clouds transfer ran a power curve per pixel and wrote the
result back from a full-size copy. On the 4096x2048 images the 3D Tiles
host draws, that held the page for about 150 ms per image. The scale
depends only on the brightest channel, so it is now worked out once per
byte value and applied to the canvas pixels in place. Output bytes are
unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 14:42:57 +01:00
14 changed files with 258 additions and 276 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
- `/api/firms` keeps its response bytes and sends them gzipped instead of
serialising the whole fire set for every request (mazy1998, #1711).
+3
View File
@@ -0,0 +1,3 @@
- Halve the time the satellite cloud image takes to prepare on the 3D Tiles
map by applying its transparency curve from a lookup table, in place
(mazy1998, #1713).
@@ -0,0 +1,3 @@
- Satellite clouds on the 3D Tiles map apply their transparency in the shader
instead of rewriting each 4096 x 2048 image on the page, and changing the
cloud strength no longer builds a new image (mazy1998, #1721).
+6 -13
View File
@@ -891,9 +891,11 @@ image proxy accepts `bbox=west,south,east,north` for every product: inside the
product bounds, 2:1 within 1 %, rounded to 0.25°, up to 4096×2048 (the
default), cached by product, time, size and bbox. Diagnostics report
`shell.detail` (`bbox`, `size`, `ready`, `enabled`).
Clouds only applies a soft brightness ramp to decoded pixels once, using
Clouds only applies a soft brightness ramp, using
Cesium's sRGB-to-linear conversion (`channel ** 2.2`) and smoothstep from 0.40
to 0.70. The old 0.55 threshold is the ramp midpoint. RGB and source alpha are
to 0.70. Globe hosts apply it to decoded pixels once; a shell applies the same
ramp in its fragment shader from a strength uniform, so its images are drawn
as decoded and a strength change neither fetches nor rewrites an image. The old 0.55 threshold is the ramp midpoint. RGB and source alpha are
preserved in Full image mode; both modes use the chosen layer opacity. This
is a display filter, not a cloud mask. The cloud-filter slider is a continuous
0–100% strength: 0% is Full, 100% is the existing Clouds only key, and
@@ -909,13 +911,13 @@ and processes it before staging. Globe hosts crop that canvas into 256 px tiles
to maximum level 3 on a geographic 2×1 root grid bounded to the manifest extent,
avoiding request-dependent contrast seams.
On globe hosts, regional infrared retains network tiles and processes each
decoded tile once; shells process each whole frame once.
decoded tile once; shells never read a frame's pixels back.
Exact-time tile and image responses are immutable for 24 hours; manifests and
errors remain uncached. Each globe renderer retains up to 6 processed global
mosaics in a least-recently-used cache keyed by observation time and infrared
mode (up to 48 MiB of canvas pixels). Each shell keeps decoded full-extent and
detail images in one least-recently-used cache bounded at 128 MiB, keyed by
time, mode and window: the shown frame and the warmed next frame, each
time and window: the shown frame and the warmed next frame, each
full-extent and detail; nothing older survives them. Disable clears the caches.
Cache hits skip
fetch/decode and report `mosaic.cached: true` with zero decode time.
@@ -3297,15 +3299,6 @@ The `get_active_fires` tool reports acquisition times as UTC ISO timestamps,
including zero-padded hours and minutes; missing or invalid dates and times
remain `null`, including impossible calendar dates from a custom source.
`/api/firms` keeps its last response body as bytes and reuses it for requests
that would get the same payload: the same cache entry and `stale` flag, while
the clock stays inside the span over which the trailing-24-hour filter keeps
the same detections. That span ends when the oldest kept acquisition minute
turns 24 hours old, so requests minutes apart are still serialised afresh. A
client that sends `Accept-Encoding: gzip` gets the body gzipped (compressed
once per kept body, `Content-Encoding: gzip`); every response carries
`Vary: Accept-Encoding`. The JSON is unchanged.
The FIRMS proxy records source success after appending its rows. If aggregation
throws, that source reports failure without a contradictory success entry.
The existing per-record append continues to support large feeds; sequential
-1
View File
@@ -376,7 +376,6 @@
"modules": [
"server/providers/firms.js",
"server/providers/common/http.js",
"server/providers/common/compress.js",
"src/sources/httpBody.js",
"src/i18n/marker.js",
"src/data/firmsCsv.js"
+10 -58
View File
@@ -3,12 +3,7 @@ import https from 'node:https';
import { promises as fsp } from 'node:fs';
import { Readable } from 'node:stream';
import {
filterTrailing24h,
parseFirmsCsv,
trailing24hWindow,
} from '../../src/data/firmsCsv.js';
import { acceptsGzip, encodedBody, gzipBody } from './common/compress.js';
import { filterTrailing24h, parseFirmsCsv } from '../../src/data/firmsCsv.js';
import { readResponseTextCapped } from './common/http.js';
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
@@ -184,11 +179,6 @@ export function firmsProxy() {
let statusCache = null;
/** @type {?Promise<?{used: number, limit: number}>} */
let statusInflight = null;
/**
* The last /api/firms payload as bytes, with its gzip. One slot.
* @type {?{entry: object, stale: boolean, from: number, until: number, body: Buffer, gzip: ?Promise<?Buffer>}}
*/
let served = null;
const mapKey = () => String(process.env.FIRMS_MAP_KEY || '').trim();
@@ -269,8 +259,12 @@ export function firmsProxy() {
return { at: now, sources, fires };
}
/** Cache entry and the fires to serve from it → response payload. */
function buildPayload(entry, stale, fires) {
/**
* Cache entry → response payload. Fires are RE-filtered to the trailing
* 24 h at serve time so a stale cache never serves >24h-old detections.
*/
function buildPayload(entry, stale) {
const fires = filterTrailing24h(entry.fires, Date.now());
return {
fetchedAt: entry.at,
stale,
@@ -281,32 +275,6 @@ export function firmsProxy() {
};
}
/**
* The payload as the bytes to send. Serialising the whole fire set is tens
* of MB in a heavy season, so it is done once and kept, not once per request.
*
* Fires are RE-filtered to the trailing 24 h at serve time so a stale cache
* never serves >24h-old detections. The kept bytes are therefore reused only
* for the same entry and stale flag while the clock is inside the span over
* which that filter keeps the same records: a request never gets a body that
* serialising for it would not have produced.
*/
function payloadBody(entry, stale) {
const now = Date.now();
if (
served?.entry === entry &&
served.stale === stale &&
now >= served.from &&
now <= served.until
) {
return served;
}
const { kept, from, until } = trailing24hWindow(entry.fires, now);
const body = Buffer.from(JSON.stringify(buildPayload(entry, stale, kept)));
served = { entry, stale, from, until, body, gzip: null };
return served;
}
/** mapkey_status transactions, cached 5 min, best-effort (null on failure). */
function getTransactions(key) {
const now = Date.now();
@@ -359,22 +327,6 @@ export function firmsProxy() {
});
res.end(JSON.stringify(obj));
};
const sendPayload = async (entry, stale) => {
const kept = payloadBody(entry, stale);
// Compressed once per kept body, on the first request that accepts
// gzip, so an identity response never pays or waits for it.
const gzip = acceptsGzip(req)
? await (kept.gzip ??= gzipBody(kept.body).catch(() => null))
: null;
const encoded = encodedBody(req, kept.body, gzip);
if (res.headersSent) return;
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
...encoded.headers,
});
res.end(encoded.body);
};
try {
const subPath = String(req.url || '').split('?')[0];
const key = mapKey();
@@ -411,7 +363,7 @@ export function firmsProxy() {
const entry = mem;
if (entry && Date.now() - entry.at < TTL_MS) {
await sendPayload(entry, false);
sendJson(200, buildPayload(entry, false));
return;
}
// Stale or missing → refresh, single-flight (concurrent requests
@@ -437,9 +389,9 @@ export function firmsProxy() {
const pending = inflight;
const fresh = await pending;
if (fresh) {
await sendPayload(fresh, false);
sendJson(200, buildPayload(fresh, false));
} else if (entry) {
await sendPayload(entry, true); // upstream down — stale beats empty
sendJson(200, buildPayload(entry, true)); // upstream down — stale beats empty
} else {
sendJson(502, {
error: 'firms fetch failed and no cache available',
+2 -27
View File
@@ -182,44 +182,19 @@ export function acquisitionMsUtc(acqDate, acqTime) {
* @returns {Array<Object>} Filtered records (original objects, order preserved).
*/
export function filterTrailing24h(records, nowMs) {
return trailing24hWindow(records, nowMs).kept;
}
/**
* {@link filterTrailing24h} with the span of `nowMs` values, inclusive, over
* which it keeps exactly these records. A caller holding something built from
* `kept` can reuse it while its clock stays inside `from..until`.
* @param {Array<{acqDate: string, acqTime: string|number}>} records - Parser records.
* @param {number} nowMs - Reference epoch milliseconds.
* @returns {{kept: Array<Object>, from: number, until: number}} Span in epoch
* ms; NaN (never reusable) for unusable input.
*/
export function trailing24hWindow(records, nowMs) {
if (!Array.isArray(records) || !Number.isFinite(nowMs))
return { kept: [], from: NaN, until: NaN };
if (!Array.isArray(records) || !Number.isFinite(nowMs)) return [];
const oldest = nowMs - WINDOW_MS;
const newest = nowMs + FORWARD_SLACK_MS;
let from = -Infinity;
let until = Infinity;
const memo = new Map();
const kept = records.filter((record) => {
return records.filter((record) => {
const key = `${record.acqDate}:${record.acqTime}`;
let ms = memo.get(key);
if (ms === undefined) {
ms = acquisitionMsUtc(record.acqDate, record.acqTime);
memo.set(key, ms);
// Each distinct time narrows the span to the clock values that leave
// it on the same side of the window.
if (ms < oldest) from = Math.max(from, ms + WINDOW_MS + 1);
else if (ms > newest) until = Math.min(until, ms - FORWARD_SLACK_MS - 1);
else if (Number.isFinite(ms)) {
from = Math.max(from, ms - FORWARD_SLACK_MS);
until = Math.min(until, ms + WINDOW_MS);
}
}
return Number.isFinite(ms) && ms >= oldest && ms <= newest;
});
return { kept, from, until };
}
/** Trimmed string cell at index, '' for missing columns. */
+1 -121
View File
@@ -7,15 +7,11 @@ import dnsLookup from 'node:dns';
import https from 'node:https';
import net from 'node:net';
import { Readable } from 'node:stream';
import os from 'node:os';
import path from 'node:path';
import { gunzipSync } from 'node:zlib';
import { filterTrailing24h, parseFirmsCsv, trailing24hWindow } from './firmsCsv.js';
import { filterTrailing24h, parseFirmsCsv } from './firmsCsv.js';
import {
describeFetchError,
fetchFirms,
fetchIpv4,
firmsProxy,
isAddressSelectionFailure,
} from '../../server/providers/firms.js';
@@ -320,119 +316,3 @@ test('FIRMS requests only the satellites NASA still delivers', () => {
// a MAP_KEY transaction.
assert.ok(!SOURCES.includes('VIIRS_SNPP_NRT'));
});
// The /api/firms handler itself, over a disk cache seeded in a temp directory:
// no server, no upstream, and a placeholder MAP_KEY that is never sent anywhere.
const TTL_MS = 30 * 60_000;
const fire = (acqDate, acqTime, lat = 1) => ({ lat, lon: 2, frp: 4.5, confidence: 'n', brightness: 330.1,
brightnessTi5: 290.2, daynight: 'D', acqDate, acqTime, satellite: 'N20', instrument: 'VIIRS' });
const SERVED_SOURCES = SOURCES.map((source, index) => ({ source, count: index === 0 ? 20_001 : 0, ok: true }));
// 20,000 detections an hour old and one that turns 24 h old five minutes after NOW.
const SERVED_FIRES = [fire('2026-09-10', '1205'), ...Array.from({ length: 20_000 }, (_, i) => fire('2026-09-11', '1100', i / 1000))];
const LEAVES_AT = NOW + 5 * 60_000;
/** What the handler sent before it kept a body: one JSON.stringify of the payload per request. */
const unfixedBody = (at, stale, now) => {
const fires = filterTrailing24h(SERVED_FIRES, now);
return JSON.stringify({ fetchedAt: at, stale, ttlMs: TTL_MS, sources: SERVED_SOURCES, count: fires.length, fires });
};
function createFirmsHandler(t, at) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'firms-proxy-'));
fs.mkdirSync(path.join(dir, '.gev-cache'));
fs.writeFileSync(path.join(dir, '.gev-cache', 'firms.json'), JSON.stringify({ at, sources: SERVED_SOURCES, fires: SERVED_FIRES }));
const cwd = process.cwd();
const key = process.env.FIRMS_MAP_KEY;
const realFetch = globalThis.fetch;
process.env.FIRMS_MAP_KEY = 'unit-test-placeholder';
// A refresh must never reach NASA from a test: every upstream call fails.
globalThis.fetch = async () => { throw new Error('upstream down'); };
t.mock.method(console, 'warn', () => {});
t.mock.timers.enable({ apis: ['Date'], now: NOW });
t.after(() => {
globalThis.fetch = realFetch;
if (key === undefined) delete process.env.FIRMS_MAP_KEY; else process.env.FIRMS_MAP_KEY = key;
fs.rmSync(dir, { recursive: true, force: true });
});
let handler;
process.chdir(dir); // the proxy resolves its cache directory when created
try {
firmsProxy().configureServer({ middlewares: { use: (route, fn) => { handler = fn; } } });
} finally {
process.chdir(cwd);
}
return (acceptEncoding) => new Promise((resolve, reject) => {
const res = {
headersSent: false,
writeHead(status, headers) { this.headersSent = true; this.status = status; this.headers = headers; },
end(body) { resolve({ status: this.status, headers: this.headers, body }); },
};
handler({ url: '/', headers: acceptEncoding === undefined ? {} : { 'accept-encoding': acceptEncoding } }, res).catch(reject);
});
}
test('/api/firms serialises once for requests that share a payload', async (t) => {
const request = createFirmsHandler(t, NOW);
const first = await request();
t.mock.timers.setTime(LEAVES_AT); // exactly 24 h old is still inside the window
const second = await request();
assert.equal(first.status, 200);
assert.ok(Buffer.isBuffer(first.body), 'the body is kept as bytes');
assert.equal(second.body, first.body, 'the second request sends the kept bytes, not a new serialisation');
assert.equal(first.body.toString(), unfixedBody(NOW, false, NOW), 'byte-identical to the per-request serialisation');
assert.equal(JSON.parse(first.body).count, 20_001);
});
test('/api/firms sends gzip only to a client that accepts it', async (t) => {
const request = createFirmsHandler(t, NOW);
const identity = await request();
const gzipped = await request('gzip, deflate, br');
const refused = await request('gzip;q=0, br');
assert.deepEqual(identity.headers,
{ 'Content-Type': 'application/json', 'Cache-Control': 'no-store', Vary: 'Accept-Encoding' });
assert.deepEqual(gzipped.headers, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store',
'Content-Encoding': 'gzip', Vary: 'Accept-Encoding' });
assert.deepEqual(refused.headers, identity.headers);
assert.equal(refused.body, identity.body);
assert.ok(gzipped.body.byteLength < identity.body.byteLength / 4, 'the fire set compresses');
assert.equal(gunzipSync(gzipped.body).toString(), unfixedBody(NOW, false, NOW), 'decodes to the identity bytes');
assert.equal((await request('gzip')).body, gzipped.body, 'compressed once');
});
test('/api/firms never reuses a body the request would not have produced', async (t) => {
const request = createFirmsHandler(t, NOW - TTL_MS + 6 * 60_000);
const at = NOW - TTL_MS + 6 * 60_000;
const before = await request();
t.mock.timers.setTime(LEAVES_AT + 1); // one detection is now older than 24 h
const after = await request('gzip');
assert.equal(before.body.toString(), unfixedBody(at, false, NOW));
assert.equal(gunzipSync(after.body).toString(), unfixedBody(at, false, LEAVES_AT + 1));
assert.equal(JSON.parse(gunzipSync(after.body)).count, 20_000);
t.mock.timers.setTime(NOW + 6 * 60_000); // the entry reaches its TTL and the refresh fails
const stale = await request();
assert.equal(stale.body.toString(), unfixedBody(at, true, NOW + 6 * 60_000));
assert.equal((await request()).body, stale.body, 'the stale body is kept too');
});
test('trailing24hWindow spans the clock values that keep the same records', () => {
const records = [fire('2026-09-10', '1205'), fire('2026-09-10', '1300'), fire('2026-09-11', '1100'),
fire('2026-09-11', '1430'), fire('2026-09-11', '1600'), fire('bad-date', '1006')];
const edges = records.map((r) => Date.parse(`${r.acqDate}T${r.acqTime.slice(0, 2)}:${r.acqTime.slice(2)}Z`))
.filter(Number.isFinite).flatMap((ms) => [ms - 2 * 3600_000, ms + 24 * 3600_000]);
assert.equal(edges.length, 10);
const clocks = [NOW, ...edges.flatMap((ms) => [ms - 1, ms, ms + 1])];
for (const now of clocks) {
const { kept, from, until } = trailing24hWindow(records, now);
assert.deepEqual(kept, filterTrailing24h(records, now));
assert.ok(from <= now && now <= until, 'the span holds its own clock');
for (const other of clocks) {
const then = filterTrailing24h(records, other);
const same = then.length === kept.length && then.every((r, i) => r === kept[i]);
// Before the first record and after the last both keep nothing; the span covers one side.
const bothEmpty = then.length === 0 && kept.length === 0;
if (other >= from && other <= until) assert.ok(same, `${other} is inside the span of ${now}`);
else assert.ok(!same || bothEmpty, `${other} is outside the span of ${now}`);
}
}
assert.deepEqual(trailing24hWindow([], NOW), { kept: [], from: -Infinity, until: Infinity });
assert.deepEqual(trailing24hWindow(records, NaN), { kept: [], from: NaN, until: NaN });
});
+36 -13
View File
@@ -1,22 +1,31 @@
export const INFRARED_ALPHA_T0 = 0.4;
export const INFRARED_ALPHA_T1 = 0.7;
/** Return display pixels without changing RGB or the source RGBA bytes.
/** How much of the cloud key applies, 0–1, for a display mode or a 0–100
* strength. The weather shell passes it to its fragment shader. */
export function infraredAmount(strength) {
return strength === 'full'
? 0
: strength === 'filtered' || !Number.isFinite(strength)
? 1
: Math.max(0, Math.min(100, strength)) / 100;
}
/** Scale each pixel's alpha in place; RGB is left as it is. The scale depends
* only on the brightest channel, so it is worked out once for each of the 256
* byte values instead of once per pixel: a 4096×2048 image has 8.4 million
* pixels and the power curve per pixel held the page for over 100 ms. The
* table holds the same numbers the per-pixel formula produced, so the output
* bytes are unchanged.
* `strength` is 0–100: zero is the full image and 100 is the cloud key.
*/
export function infraredAlpha(rgba, strength = 'filtered') {
const pixels = new Uint8ClampedArray(rgba);
const amount =
strength === 'full'
? 0
: strength === 'filtered' || !Number.isFinite(strength)
? 1
: Math.max(0, Math.min(100, strength)) / 100;
export function applyInfraredAlpha(pixels, strength = 'filtered') {
const amount = infraredAmount(strength);
if (amount === 0) return pixels;
for (let i = 0; i < pixels.length; i += 4) {
const scale = new Float64Array(256);
for (let value = 0; value < 256; value++) {
// Match Cesium's czm_srgbToLinear conversion in draped imagery.
const linearMax =
(Math.max(rgba[i], rgba[i + 1], rgba[i + 2]) / 255) ** 2.2;
const linearMax = (value / 255) ** 2.2;
const t = Math.max(
0,
Math.min(
@@ -26,7 +35,21 @@ export function infraredAlpha(rgba, strength = 'filtered') {
),
);
const filtered = t * t * (3 - 2 * t);
pixels[i + 3] = rgba[i + 3] * (1 - amount + filtered * amount);
scale[value] = 1 - amount + filtered * amount;
}
for (let i = 0; i < pixels.length; i += 4) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
const max = r > g ? (r > b ? r : b) : g > b ? g : b;
pixels[i + 3] = pixels[i + 3] * scale[max];
}
return pixels;
}
/** Return display pixels without changing RGB or the source RGBA bytes.
* `strength` is 0–100: zero is the full image and 100 is the cloud key.
*/
export function infraredAlpha(rgba, strength = 'filtered') {
return applyInfraredAlpha(new Uint8ClampedArray(rgba), strength);
}
+41
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
applyInfraredAlpha,
infraredAlpha,
INFRARED_ALPHA_T0,
INFRARED_ALPHA_T1,
@@ -61,3 +62,43 @@ test('full infrared preserves every channel including partial and zero alpha', (
]);
assert.deepEqual(infraredAlpha(pixels, 'full'), pixels);
});
test('the lookup table gives the per-pixel curve byte for byte, in place', () => {
// The transfer as it was written per pixel, before the table.
const perPixel = (rgba, amount) => {
const out = new Uint8ClampedArray(rgba);
for (let i = 0; i < out.length; i += 4) {
const linearMax =
(Math.max(rgba[i], rgba[i + 1], rgba[i + 2]) / 255) ** 2.2;
const t = Math.max(
0,
Math.min(
1,
(linearMax - INFRARED_ALPHA_T0) /
(INFRARED_ALPHA_T1 - INFRARED_ALPHA_T0),
),
);
out[i + 3] = rgba[i + 3] * (1 - amount + t * t * (3 - 2 * t) * amount);
}
return out;
};
// Every brightest-channel value in each channel, against a spread of alphas.
const bytes = [];
for (let value = 0; value < 256; value++)
for (const alpha of [0, 1, 37, 128, 200, 254, 255]) {
bytes.push(value, 0, 0, alpha);
bytes.push(value >> 1, value, 0, alpha);
bytes.push(0, value >> 2, value, alpha);
}
const source = new Uint8ClampedArray(bytes);
for (const strength of [1, 33, 50, 99, 100, 'filtered', Number.NaN]) {
const amount = Number.isFinite(strength) ? strength / 100 : 1;
const pixels = source.slice();
assert.equal(applyInfraredAlpha(pixels, strength), pixels);
assert.deepEqual(pixels, perPixel(source, amount), `strength ${strength}`);
}
for (const strength of [0, 'full']) {
const pixels = source.slice();
assert.deepEqual(applyInfraredAlpha(pixels, strength), source);
}
});
+18 -6
View File
@@ -6,7 +6,7 @@ import {
drawWeatherPixels,
closeWeatherPixels,
} from './source.js';
import { infraredAlpha } from './infraredAlpha.js';
import { applyInfraredAlpha } from './infraredAlpha.js';
export const MAX_MOSAIC_BYTES = 4 * 1024 * 1024;
@@ -31,13 +31,22 @@ export function processInfraredImage(
function applyInfraredTransfer(context, canvas, mode) {
const pixels = context.getImageData(0, 0, canvas.width, canvas.height);
pixels.data.set(infraredAlpha(pixels.data, mode));
// In place: a copy of a 4096×2048 image is 33 MB, made and written back.
applyInfraredAlpha(pixels.data, mode);
context.putImageData(pixels, 0, 0);
}
/** Draw pixels a frame source supplied into a new canvas, with the display
* transfer for infrared products, and release them. They must be `size`. */
function drawSuppliedImage(pixels, product, mode, size, signal, createCanvas) {
function drawSuppliedImage(
pixels,
product,
mode,
size,
signal,
createCanvas,
transfer,
) {
try {
signal.throwIfAborted();
const { width, height } = weatherPixelSize(pixels);
@@ -48,7 +57,7 @@ function drawSuppliedImage(pixels, product, mode, size, signal, createCanvas) {
texture.height = height;
const context = texture.getContext('2d');
drawWeatherPixels(context, pixels);
if (product === 'clouds' || product === 'clouds-regional')
if (transfer && (product === 'clouds' || product === 'clouds-regional'))
applyInfraredTransfer(context, texture, mode);
return texture;
} finally {
@@ -88,7 +97,8 @@ export function decodeInfraredImage(blob, signal) {
}
/** Fetch one capped whole-extent frame, or a `bbox` detail window of it, and draw
* it into a canvas. Infrared frames get the display transfer; a canvas also keeps
* it into a canvas. Infrared frames get the display transfer unless `transfer`
* is false, for a caller that applies it when drawing; a canvas also keeps
* Cesium's texture row order, which an ImageBitmap upload would not. The decoded
* image is always released. With a `frameSource` that has `getImage`, the host
* supplies the decoded pixels instead and nothing is fetched or decoded here. */
@@ -107,6 +117,7 @@ export async function acquireWeatherImage(
now = () => performance.now(),
onFetched = () => {},
frameSource = null,
transfer = true,
},
) {
if (frameSource?.getImage) {
@@ -127,6 +138,7 @@ export async function acquireWeatherImage(
size,
signal,
createCanvas,
transfer,
);
return { texture, decodeMs: now() - started };
}
@@ -147,7 +159,7 @@ export async function acquireWeatherImage(
if (image.width !== size.width || image.height !== size.height)
throw new Error('Invalid weather image dimensions');
let texture;
if (product === 'clouds' || product === 'clouds-regional')
if (transfer && (product === 'clouds' || product === 'clouds-regional'))
texture = processInfraredImage(image, mode, createCanvas);
else {
texture = createCanvas();
+69
View File
@@ -26,6 +26,75 @@ function canvas() {
return output;
}
test('the transfer is applied to the canvas pixels in place, with no copy written back', () => {
let read = null;
const output = {};
output.getContext = () => ({
drawImage() {},
getImageData: () => {
read = { data: new Uint8ClampedArray([194, 0, 0, 200]) };
// A second full-size buffer copied over the first is what this guards.
read.data.set = () => {
throw new Error('the canvas pixels were overwritten from a copy');
};
return read;
},
putImageData: (pixels) => {
output.pixels = pixels;
},
});
processInfraredImage({ width: 1, height: 1 }, 'filtered', () => output);
assert.equal(output.pixels, read);
assert.deepEqual([...read.data], [194, 0, 0, 98]);
});
test('with transfer off an infrared frame is drawn and never read back', async () => {
const drawn = [];
const createCanvas = () => {
const output = {};
output.getContext = () => ({
drawImage: (image) => drawn.push(image),
getImageData: () => {
throw new Error('the frame was read back on the page');
},
putImageData: () => {
throw new Error('the frame was rewritten on the page');
},
});
return output;
};
const size = { width: 4096, height: 2048 };
const image = { ...size, close() {} };
const options = {
signal: new AbortController().signal,
mode: 'filtered',
size,
maxBytes: 1024,
createCanvas,
transfer: false,
};
const fetched = await acquireWeatherImage(
'clouds-regional',
'2026-09-15T20:00:00.000Z',
{
...options,
fetchImpl: async () => ({
ok: true,
headers: new Headers(),
arrayBuffer: async () => new ArrayBuffer(1),
}),
decodeImage: async () => image,
},
);
assert.equal(fetched.texture.width, 4096);
const supplied = { ...size };
await acquireWeatherImage('clouds-regional', '2026-09-15T20:00:00.000Z', {
...options,
frameSource: { getImage: async () => supplied },
});
assert.deepEqual(drawn, [image, supplied]);
});
test('decoded pixels are processed once on a same-sized canvas', () => {
const image = { width: 1, height: 1 };
const output = processInfraredImage(image, 'filtered', canvas);
+34 -17
View File
@@ -1,4 +1,9 @@
import { acquireWeatherImage } from './infraredImage.js';
import {
INFRARED_ALPHA_T0,
INFRARED_ALPHA_T1,
infraredAmount,
} from './infraredAlpha.js';
import { imageryHostStatus } from './imageryHost.js';
import { WEATHER_DETAIL_SIZE, WEATHER_IMAGE_SIZES } from './source.js';
import { msg } from '../../i18n/index.js';
@@ -36,6 +41,10 @@ const LIFT_STEP = 500;
// draw nothing until the full-extent image has arrived, and sample the detail
// image only once it has arrived. The window is west, south, east, north in the
// full-extent image's texture coordinates.
// `infrared` is how much of the cloud key applies, 0–1 (infraredAlpha.js has
// the same curve for the globe's draped imagery). It is applied here, to the
// image as it was decoded, so a 4096×2048 frame is never read back and
// rewritten on the page, and a strength change is one uniform, not a new image.
const MATERIAL_SOURCE = `czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
@@ -46,7 +55,8 @@ const MATERIAL_SOURCE = `czm_material czm_getMaterial(czm_materialInput material
float useDetail = inside * step(1.5, float(detailDimensions.x));
vec4 c = mix(coarse, texture(detail, clamp(dst, 0.0, 1.0)), useDetail);
material.diffuse = czm_gammaCorrect(c.rgb);
material.alpha = c.a * alpha * step(1.5, float(imageDimensions.x));
float key = smoothstep(${INFRARED_ALPHA_T0.toFixed(4)}, ${INFRARED_ALPHA_T1.toFixed(4)}, pow(max(c.r, max(c.g, c.b)), 2.2));
material.alpha = c.a * mix(1.0, key, infrared) * alpha * step(1.5, float(imageDimensions.x));
return material;
}
`;
@@ -63,6 +73,7 @@ function registerMaterial(cesium) {
image: cesium.Material.DefaultImageId,
detail: cesium.Material.DefaultImageId,
alpha: 1,
infrared: 0,
window: { type: 'vec4', x: 0, y: 0, z: -1, w: -1 },
},
// Diffuse and alpha share these samples, so one source, not components.
@@ -245,6 +256,12 @@ export function createShellSurface({
material.uniforms.alpha = value;
scene.requestRender();
},
/** How much of the infrared cloud key applies, 0–1. */
setInfrared(value) {
if (destroyed || material.uniforms.infrared === value) return;
material.uniforms.infrared = value;
scene.requestRender();
},
/** Draw `next` inside `rect` (west, south, east, north in the full-extent
* image's texture coordinates, 0–1); null clears it. In the same window only
* the image changes, and Cesium keeps drawing the previous texture until
@@ -438,10 +455,11 @@ export function createWeatherShell({
const visible = () => !hidden && !suspended();
const boundsKey = ({ west, south, east, north }) =>
`${west},${south},${east},${north}`;
const cacheKey = (time, mode, box = null) =>
`${time}|${infrared ? mode : 'none'}${box ? `|${boundsKey(box)}` : ''}`;
// One image per time and window: the infrared mode is a uniform, not pixels.
const cacheKey = (time, box = null) =>
box ? `${time}|${boundsKey(box)}` : time;
const wantedDetail = () =>
current && view ? cacheKey(current.time, current.infrared, view) : null;
current && view ? cacheKey(current.time, view) : null;
function evict(keep = []) {
const kept = new Set([...keep, current?.key, detail?.key]);
@@ -454,12 +472,11 @@ export function createWeatherShell({
}
async function acquire(
time,
mode,
signal,
{ box = null, keep = [], onFetched } = {},
) {
signal.throwIfAborted();
const key = cacheKey(time, mode, box);
const key = cacheKey(time, box);
const entry = images.get(key);
if (entry) {
images.delete(key);
@@ -468,7 +485,8 @@ export function createWeatherShell({
}
const result = await acquireWeatherImage(product, time, {
signal,
mode,
// The surface's shader applies the infrared transfer.
transfer: false,
size: box ? detailSize : size,
bbox: box,
maxBytes: MAX_IMAGE_BYTES,
@@ -564,9 +582,7 @@ export function createWeatherShell({
const job = { key, box: view, controller: new AbortController() };
detailJob = job;
job.timeout = setTimeout(() => job.controller.abort(), timeoutMs);
void acquire(current.time, current.infrared, job.controller.signal, {
box: view,
})
void acquire(current.time, job.controller.signal, { box: view })
.then(({ texture }) => installDetail(job, texture))
.catch(() => failDetail(job));
}
@@ -661,6 +677,7 @@ export function createWeatherShell({
loadMs: now() - frame.startedAt,
};
surface.setAlpha(alpha);
surface.setInfrared(infrared ? infraredAmount(frame.infrared) : 0);
applyVisibility();
lastError = null;
evict();
@@ -715,7 +732,7 @@ export function createWeatherShell({
return changed;
},
cancelPrefetch,
async prefetch(snapshot, time, { infrared: mode = 'filtered' } = {}) {
async prefetch(snapshot, time) {
let job;
try {
if (
@@ -729,8 +746,8 @@ export function createWeatherShell({
// Warm the next frame's detail window too while the window stays put.
const box =
view && viewBounds === boundsKey(snapshot.bounds) ? view : null;
const coarse = cacheKey(time, mode);
const key = box ? cacheKey(time, mode, box) : coarse;
const coarse = cacheKey(time);
const key = box ? cacheKey(time, box) : coarse;
if (prefetchJob?.key === key || prefetchedKey === key) return false;
cancelPrefetch();
job = { key, controller: new AbortController() };
@@ -739,8 +756,8 @@ export function createWeatherShell({
job.timeout = setTimeout(() => job.controller.abort(), timeoutMs);
// Both images at once: one after the other would outlast playback's step.
await Promise.all([
acquire(time, mode, signal, { keep: box ? [key] : [] }),
box ? acquire(time, mode, signal, { box, keep: [coarse] }) : null,
acquire(time, signal, { keep: box ? [key] : [] }),
box ? acquire(time, signal, { box, keep: [coarse] }) : null,
]);
signal.throwIfAborted();
if (prefetchJob === job) prefetchedKey = key;
@@ -782,7 +799,7 @@ export function createWeatherShell({
infrared: mode,
bounds,
product: snapshot.product,
key: cacheKey(time, mode),
key: cacheKey(time),
mosaic: { fetched: false, decodeMs: null, cached: false },
controller: new AbortController(),
startedAt: now(),
@@ -797,7 +814,7 @@ export function createWeatherShell({
});
watch(frame, signal);
frame.timeout = setTimeout(() => fail(frame), timeoutMs);
void acquire(time, mode, frame.controller.signal, {
void acquire(time, frame.controller.signal, {
onFetched: () => {
frame.mosaic.fetched = true;
},
+35 -18
View File
@@ -11,6 +11,7 @@ import {
WEATHER_SHELL_HEIGHTS,
} from './shellRendering.js';
import { NO_IMAGERY_HOST } from './imageryHost.js';
import { INFRARED_ALPHA_T0, INFRARED_ALPHA_T1 } from './infraredAlpha.js';
import {
createShellCesium,
createShellScene,
@@ -147,12 +148,13 @@ test('surface builds a flat raised rectangle drawn in primitive order without de
image: Cesium.Material.DefaultImageId,
detail: Cesium.Material.DefaultImageId,
alpha: 1,
infrared: 0,
window: { type: 'vec4', x: 0, y: 0, z: -1, w: -1 },
});
const { source } = template.fabric;
assert.match(
source,
/material\.alpha = c\.a \* alpha \* step\(1\.5, float\(imageDimensions\.x\)\);/,
/material\.alpha = c\.a \* mix\(1\.0, key, infrared\) \* alpha \* step\(1\.5, float\(imageDimensions\.x\)\);/,
'nothing draws before the full-extent image',
);
assert.match(
@@ -373,6 +375,7 @@ test('real Cesium builds the two-texture material, the opaque-pass appearance an
/uniform sampler2D image_\d+;/,
/uniform sampler2D detail_\d+;/,
/uniform float alpha_\d+;/,
/uniform float infrared_\d+;/,
/uniform vec4 window_\d+;/,
/uniform ivec3 imageDimensions_\d+;/,
/uniform ivec3 detailDimensions_\d+;/,
@@ -384,9 +387,16 @@ test('real Cesium builds the two-texture material, the opaque-pass appearance an
assert.match(shader, /step\(1\.5, float\(detailDimensions_\d+\.x\)\)/);
assert.match(
shader,
/material\.alpha = c\.a \* alpha_\d+ \* step\(1\.5, float\(imageDimensions_\d+\.x\)\);/,
/material\.alpha = c\.a \* mix\(1\.0, key, infrared_\d+\) \* alpha_\d+ \* step\(1\.5, float\(imageDimensions_\d+\.x\)\);/,
'the uniform is renamed, the material field is not',
);
// The cloud key the globe's draped imagery gets from infraredAlpha.js:
// brightest channel, 2.2 power, the shared thresholds.
assert.ok(
shader.includes(
`float key = smoothstep(${INFRARED_ALPHA_T0.toFixed(4)}, ${INFRARED_ALPHA_T1.toFixed(4)}, pow(max(c.r, max(c.g, c.b)), 2.2));`,
),
);
assert.match(shader, /float useDetail = inside \* step/, 'locals keep names');
const detail = { width: 4096, height: 2048 };
surface.setDetail(detail, { west: 0.1, south: 0.2, east: 0.3, north: 0.4 });
@@ -743,12 +753,12 @@ test('prefetch warms a decoded frame without staging and cancels cleanly', async
h.shell.clear();
});
test('infrared frames get the display transfer; radar and lightning keep their pixels', async () => {
for (const [product, transfer] of [
['clouds-regional', true],
['clouds', true],
['radar', false],
['lightning', false],
test('infrared frames reach the shader as decoded, with the cloud key as a uniform; radar and lightning get none', async () => {
for (const [product, amount] of [
['clouds-regional', 1],
['clouds', 1],
['radar', 0],
['lightning', 0],
]) {
const h = harness({ product });
const pending = h.shell.setFrame(snapshot(product), times[0]);
@@ -756,11 +766,10 @@ test('infrared frames get the display transfer; radar and lightning keep their p
const image = h.material().uniforms.image;
assert.equal(image.source, h.decoded[0], 'drawn into a canvas');
assert.equal(h.decoded[0].closed, true);
assert.equal(image.pixels !== undefined, transfer, product);
if (transfer)
assert.deepEqual([...image.pixels], [194, 0, 0, 98], 'clouds only');
assert.equal(image.pixels, undefined, `${product}: pixels never rewritten`);
h.render();
assert.equal(await pending, true);
assert.equal(h.material().uniforms.infrared, amount, product);
assert.equal(
h.shell.getDiagnostics().height,
WEATHER_SHELL_HEIGHTS[product],
@@ -769,20 +778,28 @@ test('infrared frames get the display transfer; radar and lightning keep their p
}
});
test('an infrared mode change restages the same time with its own cached canvas', async () => {
test('an infrared mode change is a uniform on the same image: no fetch, no new canvas', async () => {
const h = harness({ product: 'clouds' });
assert.equal(await show(h, times[0]), true);
const filtered = h.material().uniforms.image;
const image = h.material().uniforms.image;
assert.equal(h.material().uniforms.infrared, 1);
assert.equal(await show(h, times[0]), true, 'same frame is a no-op');
assert.equal(h.fetches.length, 1);
const renders = h.scene.renders;
assert.equal(await show(h, times[0], { infrared: 'full' }), true);
const full = h.material().uniforms.image;
assert.notEqual(full, filtered);
assert.deepEqual([...full.pixels], [194, 0, 0, 200]);
assert.equal(h.material().uniforms.image, image);
assert.equal(h.material().uniforms.infrared, 0);
assert.equal(h.shell.getDiagnostics().infrared, 'full');
assert.ok(h.scene.renders > renders, 'the new strength is drawn');
assert.equal(await show(h, times[0], { infrared: 40 }), true);
assert.equal(h.material().uniforms.infrared, 0.4);
assert.equal(h.shell.getDiagnostics().infrared, 40);
assert.equal(await show(h, times[0], { infrared: 'filtered' }), true);
assert.equal(h.material().uniforms.image, filtered, 'cache hit');
assert.equal(h.fetches.length, 2);
assert.equal(h.material().uniforms.image, image);
assert.equal(h.material().uniforms.infrared, 1);
assert.equal(h.fetches.length, 1);
assert.equal(h.decoded.length, 1);
assert.equal(h.shell.getDiagnostics().cache.mosaics, 1);
h.shell.clear();
});