Compare commits

..
Author SHA1 Message Date
Mazeyar Moeini FeizabadiandClaude Fable 5.2 72d9f91ad6 docs(performance): cables rewrite in #1722 and clouds shader in #1721
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 18:03:54 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 fda54f6611 docs(performance): detection overlay fixed in #1719
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:28:23 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 0760733780 docs(performance): NVG and FLIR measured and fixed in #1718
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:26:26 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 6b4b9e43c8 docs(performance): Wind server decode measured and fixed in #1717; Wind zoom stalls traced to Cesium's globe shaders
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:18:56 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 c16bfa5abd docs(performance): name the fix pull request for each finding
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:06:26 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 22bdf14be1 docs(performance): camera crash cause pinned to Cesium's centre-pixel zoom; detection cost re-measured
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:07:49 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 5aed9ce064 docs(performance): Wind re-measured and cleared; Shipwrecks and cables causes refined
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:06:37 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 96847d5856 docs(performance): pointer pick and imported geo files measured again and cleared
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 14:51:44 +01:00
Mazeyar Moeini FeizabadiandClaude Fable 5.2 5eb6515f44 docs(performance): slowdown audit of main, with the cause and fix for each finding
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 14:23:35 +01:00
11 changed files with 383 additions and 245 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
- 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).
@@ -1,3 +0,0 @@
- 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).
+4 -6
View File
@@ -891,11 +891,9 @@ 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, using
Clouds only applies a soft brightness ramp to decoded pixels once, using
Cesium's sRGB-to-linear conversion (`channel ** 2.2`) and smoothstep from 0.40
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
to 0.70. 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
@@ -911,13 +909,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 never read a frame's pixels back.
decoded tile once; shells process each whole frame once.
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 and window: the shown frame and the warmed next frame, each
time, mode 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.
+322
View File
@@ -0,0 +1,322 @@
# Slowdown audit, November 2026
A sweep of `main` (`c02ede3bb`, 13 November 2026) for bugs that freeze the page
or hold the frame rate down. This page lists what was found, why it happens and
how to fix it, and names the pull request that carries each fix.
[PERFORMANCE.md](PERFORMANCE.md) is the measured baseline of a healthy build;
this page is the list of things that fall outside it.
## How it was measured
- Keyless dev server, headless Chrome at 1440 x 900 on Apple silicon (Metal
through ANGLE), default globe map.
- Per scenario: load, a spell at rest, scripted drags and wheel zooms, then a
settle. Long tasks were counted with a `PerformanceObserver`, the hot function
named from a CPU profile, and `globe.getHeight`, `scene.sampleHeight`,
`scene.pick` and friends wrapped to count calls and time.
- A long task is one main-thread task over 50 ms. With no layers on, the
baseline is two at load (longest about 240 ms) and none afterwards, with zero
frames rendered while the camera is still.
- Four profiling sessions ran on one machine at the same time, so absolute
timings carry some noise. Ratios against the baseline are what to read.
Nothing here was measured on Google Photorealistic 3D Tiles, on a discrete or
integrated PC GPU, or with keyed feeds (AISStream, FIRMS, TomTom). Those rows
are marked "read in code".
## Findings and fixes
Worst first. "Fix" names the pull request that carries the fix.
### Measured
| # | Where | What happens | Fix |
| ---: | --- | --- | --- |
| 1 | Bike Share, local data layers, Transit, Rail | 18 s freeze switching Bike Share on over New York (2,519 stations); 2.7 s on Data Centers; multi-second freezes with Transit while zooming | #1688, #1689 |
| 2 | Shipwrecks | 3 to 5 s freeze when the markers are built over loaded terrain; a share link with the layer on held the loading screen for 22.9 s in one run | #1703 |
| 3 | Camera | Rendering stops until reload: at a whole-globe view looking straight down, pan a few times, then scroll one notch | #1704 |
| 4 | Street Traffic | Zooming at 250 m over Manhattan: 25 long tasks in 24 s, longest 746 ms, 6.6 s in total | #1705 |
| 5 | ALPR cameras | Depth samples inside the overlay paint, repeated on every re-enable: 240 samples and about 1 s across eight toggles. A first-sample freeze of up to 1.9 s was seen in the sweep but not on a second day | #1706 |
| 6 | Wind | First zoom after load: up to 14 long tasks (longest 414 ms). Re-measured as one-off shader links, not a standing cost: see below | none proposed |
| 7 | Submarine cables | About 2 s of long tasks on load, heap briefly at 1 GB, about 0.5 s again on each re-enable | #1707 (first step), #1722 (batched primitives) |
| 8 | Live Flights at whole-globe view with detection labels | Fine on the test machine; at 4x CPU throttle, 8 fps with 143 long tasks in 15 s | #1708 (fleet pass), #1719 (overlay) |
| 9 | Radio | 7 to 10 long tasks when the directory loads, longest 447 ms | #1709 |
| 10 | Pointer pick | Not reproduced on a second look: see below | none needed |
| 11 | CCTV | A still-image camera holds continuous rendering at 60 frames a second although its picture changes about every 10 s | #1710 |
### Read in code
| # | Where | What happens | Fix |
| ---: | --- | --- | --- |
| 12 | `/api/firms` | The whole fire set is filtered, serialised and sent uncompressed on every request; 15 to 55 MB estimated in a heavy season | #1711 |
| 13 | AIS store | Both vessel maps are walked on every position message, and sorted whole once past the cap | #1712 |
| 14 | Satellite clouds on the 3D Tiles map | A CPU pass over a 4096 x 2048 image, 90 to 180 ms measured on a synthetic canvas, twice in a row | #1713 (canvas path), #1721 (shader) |
| 15 | NVG and FLIR styles | Over 100 texture reads per pixel, and 60 renders a second while the style is on. Measured afterwards: the reads cost 0.4 ms a frame at 1440 x 900 and 1.2 ms at 2560 x 1440 | #1718 |
| 16 | Wind server | Full 0.25 degree GRIB fields decoded on the event loop. Measured afterwards: 68 ms blocked per warm refresh, about 250 ms on the first, about 400 ms when all six keys refresh together | #1717 |
| 17 | Imported geo files and other per-feature ground clamps | Measured afterwards: imported files do not freeze; see below | none needed |
## Cause and fix, per finding
### 1. Terrain height reads
`globe.getHeight` casts a ray against the mesh of the tile under the point, and
`scene.sampleHeight` renders a depth pass. Transit asked for every trail fix of
every vehicle several times per poll; Bike Share sampled every station in one
go. The fix keeps heights per point in one shared reader with a read budget
(`src/services/terrainSurface.js`) and spreads the depth samples across frames.
### 2. Shipwrecks
`rebuild()` in `src/layers/shipwrecks/index.js` adds 7,958 billboards with
`heightReference: CLAMP_TO_GROUND`. Each constructor runs
`Billboard._updateClamping`, which intersects a ray with the terrain mesh,
synchronously: 4.8 of the 4.9 s. The cost is only paid when terrain is loaded
at the time the markers are built, so a cold start with the layer in the URL
sometimes escapes it.
Fix: do not clamp. Wrecks are at sea and the markers already ignore the depth
test, so place them on the ellipsoid with `HeightReference.NONE`.
### 3. Camera: rendering stops after pan then zoom
Pure Cesium; no application code is involved. Above 1,000 km,
`ScreenSpaceCameraController` `handleZoom` rotates the camera about the cross
product of the picked point's normal and the screen centre's normal whenever
their dot product is between 0 and 1. With the pointer on the exact centre pixel
the two are the same vector, yet `n · n` often rounds to `0.9999999999999999`,
so the check passes with a zero axis. `Camera.rotate` then throws
`DeveloperError: normalized result is not a number` from
`Scene.initializeFrame`, outside the scene's own try/catch, so
`scene.renderError` never fires and Cesium stops its render loop for good. The
pans in the first reproduction only moved the camera to a pose where the
rounding goes that way.
Fix: make `camera.rotate` ignore a zero or non-finite axis, and recover from any
stopped loop by restoring the last drawn camera pose and restarting it a bounded
number of times before showing Cesium's error panel.
### 4. Street Traffic road loading
Three costs in one task after the detail tiles arrive, in
`src/layers/traffic/source.js`:
- `outsideDetailTiles` clips every coarse z12 road against every loaded detail
tile (up to 16) for four regions.
- The composed set is then handed on with `replace: true`, so
`ingestion.js` parses every road again although each tile was parsed as it
streamed.
- `parseRoads` (`model.js`) asks `cachedGroundFloor` once per coordinate, and
each call builds several string keys.
Fix: clip once per coarse tile against the detail tiles' union box and slice the
work across frames (or do it in the vector-tile worker); reuse the roads parsed
while streaming and parse only the clipped coarse remainder; look the floor up
once per floor cell within a parse.
This is separate from the one-viewport-tile-at-a-time loading recorded in
[KNOWN-ISSUES.md](KNOWN-ISSUES.md).
### 5. ALPR cameras
`refineAnchors` and `anchorFor` in `src/layers/alpr/overlay.js` call
`scene.sampleHeight` from the overlay's paint, four per paint. Each is a depth
render and a `readPixels`; the first one also compiles the pick shader. Results
are kept on the entity, so a rebuild or a re-enable samples everything again.
Fix: on a terrain globe read `globe.getHeight` through the shared terrain reader
instead of sampling; keep the answers in a map keyed by camera that outlives the
entities; move what sampling remains out of the paint into a queue of one per
frame.
### 6. Wind
The first reading blamed the layer's 916,476 vertices for slow depth reads
during zoom. Measuring again did not support that: depth reads cost the same
with and without Wind, hiding every wind primitive left pick time unchanged, and
the stalls appear on the first zoom only, as shader programs link (seven
programs, about 0.5 s, long tasks up to 166 ms). Later zooms had none.
The roughly 30 renders a second are the animation itself. It is already capped
at 30 Hz and stops when paused, hidden, out of view or under reduced motion;
lowering the rate would change how the layer looks. `disable()` releases the
baked geometry on purpose, at the price of one task of about 130 ms on
re-enable.
A third look, timing every program link on a preview build, settled it: Wind
owns two shader programs, both link during load in 9 to 18 ms, and none ever
linked during a zoom. The programs that do link on a zoom are Cesium's own
globe-surface variants, with Wind on or off, and Cesium links them
synchronously. No fix is proposed.
### 7. Submarine cables
`src/layers/submarineCables/ingestion.js` loads both collections through
`Cesium.GeoJsonDataSource` with `clampToGround`. Switching the layer on is one
task of about 1.4 s, and 1.2 s of it is Cesium reading the terrain height for
the 1,917 ground-clamped landing markers, all created in the first frame,
including the ones behind the globe.
Fix, first step: start the landing markers hidden and let the existing horizon
sweep show the visible ones a few dozen per frame.
Fix, second step: draw from batched primitives in place of the entity data
sources: one ground polyline primitive for the lines, one billboard collection
for the landing markers, one point collection and one static polyline primitive
for the reference stems, all kept while the layer is off. That removes the
visualiser tasks, the stall on switch-off and on re-enable, and about 900 MB of
heap. The first switch-on still links shaders and builds the ground-line
geometry once.
### 8. Live Flights at whole-globe view
Two costs that scale with the 7,500 aircraft of a full poll:
- The fleet pass (`src/layers/flights/rendering.js`, every 80 ms) dead-reckons
each visible aircraft and asks `cachedGroundFloor` for it, including aircraft
at cruise altitude that can never touch the floor. Each lookup formats numbers
to strings several times and rewrites a cache entry: 40% of the busy time.
- The detection overlay (`src/data/detection.js` `_drawOverlay`) collects every
detectable object and strokes every bracket on every frame.
Fix for the first: skip the floor path for a contact clearly above any terrain,
make the floor-cell key a number, and stop promoting the cache entry on every
read.
The second turned out smaller than it looked. The bracket strokes are already
one path per colour, and collecting the objects is about 3 ms of a 56 ms frame
at 4x throttle once the first fix is in. What costs is the per-object loop in
`_drawOverlay` (projection, occlusion, alpha, twelve path calls per bracket).
Fix for the second: keep what a sweep built and reuse it on the next paint when
the view and every contact are exactly what it was built from, compared value
by value so no layer has to announce a change. Between two fleet passes most
paints qualify, which cuts frame work by a fifth to a third on a still camera
at full speed. At 4x throttle a frame outlasts a fleet pass, no paint
qualifies, and the gain is a few milliseconds; the fleet pass is what
dominates there.
### 9. Radio
`stationTags()` in `src/layers/radio/categories.js` splits and normalises a
station's tags on every `hasTag` call, and `buildRadioCategories` runs that for
every station against every category, twice.
Fix: normalise once per station at ingest and count categories from that.
### 10. Pointer pick
Three sessions saw a single `scene.pick` of 207 to 342 ms during a gesture and
attributed it to `pickPointer` in `src/voice/pointerPick.js`. Timing every pick
across pointer rests, drags and wheel bursts did not bear that out: of 78 picks
with CCTV on over London all but two took 3 to 8 ms, and with five heavy layers
on, 81 picks took 5 to 30 ms apart from the first (135 ms). `pickPointer` picks
at most once per pointer rest.
The slow pick is the first pick after a layer appears, once per page load, most
likely the pick shader compiling, and its stack is CCTV's own hover pick
(`src/layers/cctv/hover.js`). No fix is proposed: removing the dwell pick would
only move the one-off cost to the next click.
### 11. CCTV still-image cameras
`src/layers/cctv/projection.js` holds continuous rendering for as long as any
projected camera is active and redraws the projection every frame.
Fix: hold only for video. For a still image, request one render when a new image
lands or while a focus fade runs.
### 12. `/api/firms`
`server/providers/firms.js` builds the payload and calls `JSON.stringify` per
request, with no kept body and no compression, and the client refetches every
ten minutes.
Fix: keep the response bytes and their gzip and serve those, as the OpenSky
provider does. The route filters to the trailing 24 hours at serve time, so the
bytes can only be reused while that filter keeps the same records (about a
minute at a time): bursts and several clients gain most, and every response is
about seven times smaller.
### 13. AIS store
`server/providers/vessels/ais-store.js` calls `pruneAisStreamCache()` for every
message; the static-data map is never pruned.
Fix: prune on a timer, evict in insertion order, and drop a vessel's static
entry with the vessel.
### 14. Satellite clouds on the 3D Tiles map
`src/layers/weather/infraredImage.js` runs `getImageData`, a per-pixel power
curve and `putImageData` over the whole canvas.
Fix: a 256-entry lookup table applied in place for the canvas path, which
halves it; then, for the shell on the 3D Tiles map, the same curve in its
fragment shader from a strength uniform, so the image is never read back and a
strength change builds no new image.
### 15. NVG and FLIR styles
`src/styles/surveillance.js` loops 11 x 11 texture reads per pixel and
`src/styles/thermal.js` totals 106. Timed on the GPU, those loops cost about
0.4 ms a frame at 1440 x 900 and 1.2 ms at 2560 x 1440 on the test machine:
real, but small there. The standing cost is that a style with animated grain
holds continuous rendering at 60 frames a second.
Fix: split the bloom into a row pass and a column pass, which gives the same
picture from a fifth to a half of the reads, and step the grain's clock at
15 Hz, asking for one frame per step instead of holding the render loop. The
grain then changes 15 times a second, which is visible in motion.
Switching on any style stage at all costs more than the bloom did (1.8 ms a
frame at 1440 x 900 for the one-line noir style). That was not looked into.
### 16. Wind server
`server/providers/wind/decode.js` decodes about a million doubles per message
synchronously, hourly, for six keys.
Fix: decode on a worker thread, and keep the sampled U and V of the last
forecast file per model so that choosing an overlay fetches only its field.
### 17. Per-feature ground clamps
`heightReference: CLAMP_TO_GROUND` per feature is also set in
`installations/rendering.js`, `alpr/presentation.js`, `ghostMaps/index.js`,
`earthquakes/index.js`, `airQuality/index.js`, `news/index.js` and
`osmPlaces/index.js`. Their counts were small in these runs (30 to 1,500) and
none froze.
Imported geo files were the one unbounded case, and measuring them cleared
them: 20,000 generated points (the import cap) finish in about 1.5 s with a
longest task near 0.5 s, because `settleGroundPins` in
`src/data/geoFileImport.js` already places pins with `HeightReference.NONE` and
resolves heights 256 at a time with a yield between batches. No fix is needed.
## Checked and fine
- Start-up of a production build: viewer ready in about 0.5 s, loading screen
gone at 1.6 s, three long tasks totalling about 300 ms.
- Idle: no frames rendered with no layers on; every render hold was released
when its layer went off.
- Leaks: all 41 layers toggled three times and ten of them eight times; no
timer, scene listener, primitive or data source grew per cycle. The heap
levelled off near 320 MB over 7.5 minutes of toggling eleven layers.
- At most one long task after load: Military, Satellites (including 11,903
Starlink points), Earthquakes, News, Wildlife, GNSS, Drone Airspace, Military
Installations, Fire Perimeters, rain radar, lightning, and satellite clouds on
the globe map.
- Live Flights at city scale with the same 7,500 aircraft loaded: 60 fps, no
long tasks.
## Not covered
- Google Photorealistic 3D Tiles: nothing was run there. Depth sampling is the
only height source on that map, so findings 4, 5 and 17 may be worse.
- Live Vessels, FIRMS with data, TomTom traffic, Local ADS-B.
- Frame rate on anything but one Apple silicon machine.
- One all-layers run over Manhattan grew the heap from 346 to 638 MB in 60 s;
whether that is retained was not established.
- One Satellites load showed a 5.2 s long task once and never again in four more
loads.
+3
View File
@@ -6,6 +6,9 @@ specification and should not be used to predict performance on untested systems.
The original capture artifacts are not included here, so this page records
results rather than defining a runnable benchmark.
For slowdowns found since, with their causes and fixes, see
[PERFORMANCE-AUDIT-2026-11.md](PERFORMANCE-AUDIT-2026-11.md).
## Test context
The baseline was captured on 22 August 2026 with these conditions:
+13 -36
View File
@@ -1,31 +1,22 @@
export const INFRARED_ALPHA_T0 = 0.4;
export const INFRARED_ALPHA_T1 = 0.7;
/** 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.
/** 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 applyInfraredAlpha(pixels, strength = 'filtered') {
const amount = infraredAmount(strength);
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;
if (amount === 0) return pixels;
const scale = new Float64Array(256);
for (let value = 0; value < 256; value++) {
for (let i = 0; i < pixels.length; i += 4) {
// Match Cesium's czm_srgbToLinear conversion in draped imagery.
const linearMax = (value / 255) ** 2.2;
const linearMax =
(Math.max(rgba[i], rgba[i + 1], rgba[i + 2]) / 255) ** 2.2;
const t = Math.max(
0,
Math.min(
@@ -35,21 +26,7 @@ export function applyInfraredAlpha(pixels, strength = 'filtered') {
),
);
const filtered = t * t * (3 - 2 * t);
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];
pixels[i + 3] = rgba[i + 3] * (1 - amount + filtered * amount);
}
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,7 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
applyInfraredAlpha,
infraredAlpha,
INFRARED_ALPHA_T0,
INFRARED_ALPHA_T1,
@@ -62,43 +61,3 @@ 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);
}
});
+6 -18
View File
@@ -6,7 +6,7 @@ import {
drawWeatherPixels,
closeWeatherPixels,
} from './source.js';
import { applyInfraredAlpha } from './infraredAlpha.js';
import { infraredAlpha } from './infraredAlpha.js';
export const MAX_MOSAIC_BYTES = 4 * 1024 * 1024;
@@ -31,22 +31,13 @@ export function processInfraredImage(
function applyInfraredTransfer(context, canvas, mode) {
const pixels = context.getImageData(0, 0, canvas.width, canvas.height);
// In place: a copy of a 4096×2048 image is 33 MB, made and written back.
applyInfraredAlpha(pixels.data, mode);
pixels.data.set(infraredAlpha(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,
transfer,
) {
function drawSuppliedImage(pixels, product, mode, size, signal, createCanvas) {
try {
signal.throwIfAborted();
const { width, height } = weatherPixelSize(pixels);
@@ -57,7 +48,7 @@ function drawSuppliedImage(
texture.height = height;
const context = texture.getContext('2d');
drawWeatherPixels(context, pixels);
if (transfer && (product === 'clouds' || product === 'clouds-regional'))
if (product === 'clouds' || product === 'clouds-regional')
applyInfraredTransfer(context, texture, mode);
return texture;
} finally {
@@ -97,8 +88,7 @@ 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 unless `transfer`
* is false, for a caller that applies it when drawing; a canvas also keeps
* it into a canvas. Infrared frames get the display transfer; 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. */
@@ -117,7 +107,6 @@ export async function acquireWeatherImage(
now = () => performance.now(),
onFetched = () => {},
frameSource = null,
transfer = true,
},
) {
if (frameSource?.getImage) {
@@ -138,7 +127,6 @@ export async function acquireWeatherImage(
size,
signal,
createCanvas,
transfer,
);
return { texture, decodeMs: now() - started };
}
@@ -159,7 +147,7 @@ export async function acquireWeatherImage(
if (image.width !== size.width || image.height !== size.height)
throw new Error('Invalid weather image dimensions');
let texture;
if (transfer && (product === 'clouds' || product === 'clouds-regional'))
if (product === 'clouds' || product === 'clouds-regional')
texture = processInfraredImage(image, mode, createCanvas);
else {
texture = createCanvas();
-69
View File
@@ -26,75 +26,6 @@ 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);
+17 -34
View File
@@ -1,9 +1,4 @@
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';
@@ -41,10 +36,6 @@ 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);
@@ -55,8 +46,7 @@ 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);
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));
material.alpha = c.a * alpha * step(1.5, float(imageDimensions.x));
return material;
}
`;
@@ -73,7 +63,6 @@ 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.
@@ -256,12 +245,6 @@ 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
@@ -455,11 +438,10 @@ export function createWeatherShell({
const visible = () => !hidden && !suspended();
const boundsKey = ({ west, south, east, north }) =>
`${west},${south},${east},${north}`;
// 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 cacheKey = (time, mode, box = null) =>
`${time}|${infrared ? mode : 'none'}${box ? `|${boundsKey(box)}` : ''}`;
const wantedDetail = () =>
current && view ? cacheKey(current.time, view) : null;
current && view ? cacheKey(current.time, current.infrared, view) : null;
function evict(keep = []) {
const kept = new Set([...keep, current?.key, detail?.key]);
@@ -472,11 +454,12 @@ export function createWeatherShell({
}
async function acquire(
time,
mode,
signal,
{ box = null, keep = [], onFetched } = {},
) {
signal.throwIfAborted();
const key = cacheKey(time, box);
const key = cacheKey(time, mode, box);
const entry = images.get(key);
if (entry) {
images.delete(key);
@@ -485,8 +468,7 @@ export function createWeatherShell({
}
const result = await acquireWeatherImage(product, time, {
signal,
// The surface's shader applies the infrared transfer.
transfer: false,
mode,
size: box ? detailSize : size,
bbox: box,
maxBytes: MAX_IMAGE_BYTES,
@@ -582,7 +564,9 @@ export function createWeatherShell({
const job = { key, box: view, controller: new AbortController() };
detailJob = job;
job.timeout = setTimeout(() => job.controller.abort(), timeoutMs);
void acquire(current.time, job.controller.signal, { box: view })
void acquire(current.time, current.infrared, job.controller.signal, {
box: view,
})
.then(({ texture }) => installDetail(job, texture))
.catch(() => failDetail(job));
}
@@ -677,7 +661,6 @@ export function createWeatherShell({
loadMs: now() - frame.startedAt,
};
surface.setAlpha(alpha);
surface.setInfrared(infrared ? infraredAmount(frame.infrared) : 0);
applyVisibility();
lastError = null;
evict();
@@ -732,7 +715,7 @@ export function createWeatherShell({
return changed;
},
cancelPrefetch,
async prefetch(snapshot, time) {
async prefetch(snapshot, time, { infrared: mode = 'filtered' } = {}) {
let job;
try {
if (
@@ -746,8 +729,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);
const key = box ? cacheKey(time, box) : coarse;
const coarse = cacheKey(time, mode);
const key = box ? cacheKey(time, mode, box) : coarse;
if (prefetchJob?.key === key || prefetchedKey === key) return false;
cancelPrefetch();
job = { key, controller: new AbortController() };
@@ -756,8 +739,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, signal, { keep: box ? [key] : [] }),
box ? acquire(time, signal, { box, keep: [coarse] }) : null,
acquire(time, mode, signal, { keep: box ? [key] : [] }),
box ? acquire(time, mode, signal, { box, keep: [coarse] }) : null,
]);
signal.throwIfAborted();
if (prefetchJob === job) prefetchedKey = key;
@@ -799,7 +782,7 @@ export function createWeatherShell({
infrared: mode,
bounds,
product: snapshot.product,
key: cacheKey(time),
key: cacheKey(time, mode),
mosaic: { fetched: false, decodeMs: null, cached: false },
controller: new AbortController(),
startedAt: now(),
@@ -814,7 +797,7 @@ export function createWeatherShell({
});
watch(frame, signal);
frame.timeout = setTimeout(() => fail(frame), timeoutMs);
void acquire(time, frame.controller.signal, {
void acquire(time, mode, frame.controller.signal, {
onFetched: () => {
frame.mosaic.fetched = true;
},
+18 -35
View File
@@ -11,7 +11,6 @@ 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,
@@ -148,13 +147,12 @@ 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 \* mix\(1\.0, key, infrared\) \* alpha \* step\(1\.5, float\(imageDimensions\.x\)\);/,
/material\.alpha = c\.a \* alpha \* step\(1\.5, float\(imageDimensions\.x\)\);/,
'nothing draws before the full-extent image',
);
assert.match(
@@ -375,7 +373,6 @@ 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+;/,
@@ -387,16 +384,9 @@ 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 \* mix\(1\.0, key, infrared_\d+\) \* alpha_\d+ \* step\(1\.5, float\(imageDimensions_\d+\.x\)\);/,
/material\.alpha = c\.a \* 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 });
@@ -753,12 +743,12 @@ test('prefetch warms a decoded frame without staging and cancels cleanly', async
h.shell.clear();
});
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],
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],
]) {
const h = harness({ product });
const pending = h.shell.setFrame(snapshot(product), times[0]);
@@ -766,10 +756,11 @@ test('infrared frames reach the shader as decoded, with the cloud key as a unifo
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, `${product}: pixels never rewritten`);
assert.equal(image.pixels !== undefined, transfer, product);
if (transfer)
assert.deepEqual([...image.pixels], [194, 0, 0, 98], 'clouds only');
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],
@@ -778,28 +769,20 @@ test('infrared frames reach the shader as decoded, with the cloud key as a unifo
}
});
test('an infrared mode change is a uniform on the same image: no fetch, no new canvas', async () => {
test('an infrared mode change restages the same time with its own cached canvas', async () => {
const h = harness({ product: 'clouds' });
assert.equal(await show(h, times[0]), true);
const image = h.material().uniforms.image;
assert.equal(h.material().uniforms.infrared, 1);
const filtered = h.material().uniforms.image;
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);
assert.equal(h.material().uniforms.image, image);
assert.equal(h.material().uniforms.infrared, 0);
const full = h.material().uniforms.image;
assert.notEqual(full, filtered);
assert.deepEqual([...full.pixels], [194, 0, 0, 200]);
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, 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);
assert.equal(h.material().uniforms.image, filtered, 'cache hit');
assert.equal(h.fetches.length, 2);
h.shell.clear();
});