diff --git a/dev/conformance/main.js b/dev/conformance/main.js
index 2d32b806c..f577614c5 100644
--- a/dev/conformance/main.js
+++ b/dev/conformance/main.js
@@ -137,67 +137,76 @@ async function runScenes({ record = false, only } = {}) {
continue;
}
status(`${scene.id}…`);
- await drawScene(renderer, scene, ctx, async (view, capture, settle) => {
- const name = referenceName(scene.id, view.name);
- const figure = document.createElement('figure');
- $('views').append(figure);
- if (settle.state !== 'settled') {
- const detail = `${settle.state}: ${settle.blockers.join(', ')}`;
+ // A scene the renderer refuses fails alone; the others still draw.
+ try {
+ await drawScene(renderer, scene, ctx, async (view, capture, settle) => {
+ const name = referenceName(scene.id, view.name);
+ const figure = document.createElement('figure');
+ $('views').append(figure);
+ if (settle.state !== 'settled') {
+ const detail = `${settle.state}: ${settle.blockers.join(', ')}`;
+ results.push({
+ scene: scene.id,
+ view: view.name,
+ status: 'fail',
+ detail,
+ });
+ figure.innerHTML = `
${name}: ${escape(detail)}`;
+ return;
+ }
+ if (record) {
+ const res = await fetch(SAVE + name, {
+ method: 'PUT',
+ body: capture,
+ });
+ results.push({
+ scene: scene.id,
+ view: view.name,
+ status: res.ok ? 'recorded' : 'fail',
+ detail: res.ok ? undefined : `save ${res.status}`,
+ });
+ figure.innerHTML = `
${name}: recorded`;
+ return;
+ }
+ const refBlob = await reference(name);
+ if (!refBlob) {
+ results.push({
+ scene: scene.id,
+ view: view.name,
+ status: 'fail',
+ detail: 'no reference',
+ });
+ figure.innerHTML = `
${name}: no reference`;
+ return;
+ }
+ const [actual, expected] = await Promise.all([
+ pixels(capture),
+ pixels(refBlob),
+ ]);
+ const diff = new Uint8ClampedArray(actual.data.length);
+ const outcome = compareImages(actual, expected, { diff });
results.push({
scene: scene.id,
view: view.name,
- status: 'fail',
- detail,
+ status: outcome.match ? 'pass' : 'fail',
+ diffFraction: outcome.diffFraction,
+ solidPixels: outcome.solidPixels,
+ mismatchedPixels: outcome.mismatchedPixels,
+ ...(outcome.reason ? { detail: outcome.reason } : {}),
});
- figure.innerHTML = `
${name}: ${escape(detail)}`;
- return;
- }
- if (record) {
- const res = await fetch(SAVE + name, {
- method: 'PUT',
- body: capture,
- });
- results.push({
- scene: scene.id,
- view: view.name,
- status: res.ok ? 'recorded' : 'fail',
- detail: res.ok ? undefined : `save ${res.status}`,
- });
- figure.innerHTML = `
${name}: recorded`;
- return;
- }
- const refBlob = await reference(name);
- if (!refBlob) {
- results.push({
- scene: scene.id,
- view: view.name,
- status: 'fail',
- detail: 'no reference',
- });
- figure.innerHTML = `
${name}: no reference`;
- return;
- }
- const [actual, expected] = await Promise.all([
- pixels(capture),
- pixels(refBlob),
- ]);
- const diff = new Uint8ClampedArray(actual.data.length);
- const outcome = compareImages(actual, expected, { diff });
+ const diffUrl = outcome.reason
+ ? ''
+ : await toUrl(new ImageData(diff, actual.width, actual.height));
+ figure.innerHTML = `
+ ${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}`;
+ });
+ } catch (error) {
results.push({
scene: scene.id,
- view: view.name,
- status: outcome.match ? 'pass' : 'fail',
- diffFraction: outcome.diffFraction,
- solidPixels: outcome.solidPixels,
- mismatchedPixels: outcome.mismatchedPixels,
- ...(outcome.reason ? { detail: outcome.reason } : {}),
+ status: 'fail',
+ detail: String(error?.message ?? error),
});
- const diffUrl = outcome.reason
- ? ''
- : await toUrl(new ImageData(diff, actual.width, actual.height));
- figure.innerHTML = `
- ${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}`;
- });
+ }
}
if (record) {
// A partial recording keeps the other scenes' entries.
diff --git a/scripts/format-scope.json b/scripts/format-scope.json
index b7ca37fd3..07f8d9110 100644
--- a/scripts/format-scope.json
+++ b/scripts/format-scope.json
@@ -871,6 +871,8 @@
"src/layers/weather/rendering.js",
"src/layers/weather/shellRendering.js",
"src/layers/weather/shellRendering.test.mjs",
+ "src/render/cesium/drawFields.js",
+ "src/render/cesium/drawFields.test.mjs",
"src/layers/weather/infraredAlpha.js",
"src/layers/weather/infraredAlpha.test.mjs",
"src/layers/weather/infraredImage.js",
diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json
index 08a5326bf..5b9bbd12a 100644
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@ -1070,6 +1070,7 @@
"src/render/cesium/heights.js",
"src/queries/heights.js",
"src/render/cesium/draw.js",
+ "src/render/cesium/drawFields.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js",
@@ -1854,6 +1855,7 @@
"src/render/cesium/effects.js",
"src/render/cesium/screenModulation.js",
"src/render/cesium/draw.js",
+ "src/render/cesium/drawFields.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js",
@@ -3056,6 +3058,7 @@
"src/render/cesium/credits.js",
"src/render/cesium/tileRequests.js",
"src/render/cesium/draw.js",
+ "src/render/cesium/drawFields.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js",
@@ -3296,6 +3299,7 @@
"src/render/baseTilesets.js",
"src/render/cesium/drawHit.js",
"src/render/cesium/draw.js",
+ "src/render/cesium/drawFields.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawModels.js",
@@ -4308,6 +4312,7 @@
"src/render/cesium/query.js",
"src/render/cesium/heights.js",
"src/render/cesium/draw.js",
+ "src/render/cesium/drawFields.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js",
diff --git a/src/layers/weather/shellFixture.mjs b/src/layers/weather/shellFixture.mjs
index 18e5de788..6cbe9e3a8 100644
--- a/src/layers/weather/shellFixture.mjs
+++ b/src/layers/weather/shellFixture.mjs
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
+import { createCesiumFields } from '../../render/cesium/drawFields.js';
+import { bindRenderer } from '../../render/rendererOf.js';
/** Test double for the Cesium classes a weather shell constructs. */
export function createShellCesium({ maximumTextureSize = 0 } = {}) {
@@ -154,3 +156,45 @@ export function renderShells(cesium, scene, count = 4) {
scene.postRender.emit();
}
}
+
+/**
+ * Bind to `viewer` a renderer whose draw port draws raster-shell fields
+ * with the Cesium adapter's code over these doubles, whose camera port reads
+ * the viewer's Cesium-shaped camera double (its view rectangle, `moveEnd`
+ * and height) and whose frame port runs on the scene's own events.
+ * @returns {{fields: object, unbind: () => void}}
+ */
+export function bindShellFields(viewer, cesium) {
+ const scene = viewer.scene;
+ const fields = createCesiumFields({ scene, cesium });
+ const camera = () => viewer.camera ?? scene.camera;
+ const deg = 180 / Math.PI;
+ const unbind = bindRenderer(viewer, {
+ draw: { field: (spec) => fields.field(spec) },
+ camera: {
+ pose: () => ({ height: camera()?.positionCartographic?.height }),
+ viewRectangle() {
+ const rect = camera()?.computeViewRectangle?.();
+ return rect
+ ? {
+ west: rect.west * deg,
+ south: rect.south * deg,
+ east: rect.east * deg,
+ north: rect.north * deg,
+ }
+ : null;
+ },
+ on(event, cb) {
+ if (event !== 'moveEnd') return () => {};
+ return camera()?.moveEnd?.addEventListener(cb) ?? (() => {});
+ },
+ },
+ frame: {
+ on(phase, cb) {
+ return scene[phase]?.addEventListener?.(cb) ?? (() => {});
+ },
+ requestRender: () => scene.requestRender(),
+ },
+ });
+ return { fields, unbind };
+}
diff --git a/src/layers/weather/shellRendering.js b/src/layers/weather/shellRendering.js
index 71ad2fca7..2031e88c4 100644
--- a/src/layers/weather/shellRendering.js
+++ b/src/layers/weather/shellRendering.js
@@ -1,9 +1,12 @@
-import * as Cesium from 'cesium';
-// The weather layers fly through `cameraOf`, drape through `findGlobe` and
-// read `findCamera` and `findQuery`; this module is their Cesium side, so it
-// brings the factories a viewer with no renderer bound gets those ports from.
-import '../../render/cesium/camera.js';
-import '../../render/cesium/globe.js';
+// The shell draws through the draw port's raster-shell field; its detail
+// window follows the camera port and its lift the frame port.
+import {
+ findCamera,
+ findDraw,
+ findFrame,
+ findGlobe,
+ rendererOf,
+} from '../../render/rendererOf.js';
import { acquireWeatherImage } from './infraredImage.js';
import { imageryHostStatus } from './imageryHost.js';
import { WEATHER_DETAIL_SIZE, WEATHER_IMAGE_SIZES } from './source.js';
@@ -11,12 +14,13 @@ import { msg } from '../../i18n/index.js';
/**
* The viewer's own globe imagery, as a weather imagery host: where a layer
- * drapes when the application shell names no host of its own.
- * @param {object|null|undefined} viewer A Cesium viewer.
- * @returns {{collection: object|undefined, kind: 'globe'}}
+ * drapes when the application shell names no host of its own. Its globe
+ * port's imagery stands for it, one object per port.
+ * @param {object|null|undefined} viewer The scene object the layer holds.
+ * @returns {{collection: object|null, kind: 'globe'}}
*/
export function globeImageryHost(viewer) {
- return { collection: viewer?.imageryLayers, kind: 'globe' };
+ return { collection: findGlobe(viewer)?.imagery ?? null, kind: 'globe' };
}
/** Metres above the ellipsoid. Lower shells draw first, so lightning draws last. */
@@ -29,64 +33,19 @@ export const WEATHER_SHELL_HEIGHTS = Object.freeze({
});
// Decoded canvases per renderer, full-extent and detail images alike: the shown
// frame and the warmed next frame, each full-extent and detail (four 4096×2048
-// canvases); nothing older survives them. Cesium holds the shown canvases
-// through the material uniforms in any case.
+// canvases); nothing older survives them. The renderer holds the shown
+// canvases in any case.
export const WEATHER_SHELL_CACHE_BYTES = 128 * 1024 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
-const MATERIAL_TYPE = 'WeatherFrame';
-// Renders after an image swap: one queues the upload, one uploads and draws, one spare.
-const UPLOAD_FRAMES = 3;
-// An empty detail window: the full-extent image shows everywhere.
-const NO_WINDOW = Object.freeze({ west: 0, south: 0, east: -1, north: -1 });
// Detail windows, in degrees.
const DETAIL_MIN_WIDTH = 6;
const DETAIL_GRID = 0.5;
-const shellHeights = new WeakMap();
// From far away Google's coarse 3D tiles rise tens of kilometres above the
// ground and hide the shells, so the shells rise with the camera: 4 m per
// kilometre of camera height, at most 60 km, in 500 m steps.
const LIFT_PER_METRE = 0.004;
const MAX_LIFT = 60_000;
const LIFT_STEP = 500;
-// Cesium binds a 1×1 white texture to an image uniform until its first upload:
-// 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.
-const MATERIAL_SOURCE = `czm_material czm_getMaterial(czm_materialInput materialInput)
-{
- czm_material material = czm_getDefaultMaterial(materialInput);
- vec2 st = materialInput.st;
- vec4 coarse = texture(image, st);
- vec2 dst = (st - window.xy) / max(window.zw - window.xy, vec2(1e-6));
- float inside = float(all(greaterThanEqual(st, window.xy)) && all(lessThanEqual(st, window.zw)));
- 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));
- return material;
-}
-`;
-
-function registerMaterial(cesium) {
- const cache = cesium.Material._materialCache;
- if (cache.getMaterial(MATERIAL_TYPE)) return;
- // A plain template: building the first material from a fabric would make that
- // instance Cesium's shared template and keep its last image alive.
- cache.addMaterial(MATERIAL_TYPE, {
- fabric: {
- type: MATERIAL_TYPE,
- uniforms: {
- image: cesium.Material.DefaultImageId,
- detail: cesium.Material.DefaultImageId,
- alpha: 1,
- window: { type: 'vec4', x: 0, y: 0, z: -1, w: -1 },
- },
- // Diffuse and alpha share these samples, so one source, not components.
- source: MATERIAL_SOURCE,
- },
- translucent: false,
- });
-}
const sameEdges = (a, b) =>
a.west === b.west &&
@@ -101,239 +60,31 @@ export function shellLift(cameraHeight) {
return Math.round(lift / LIFT_STEP) * LIFT_STEP;
}
-/** Keep weather shells first in the primitive collection, in ascending height:
- * higher shells draw over lower ones and other opaque content draws over both. */
-export function orderWeatherShells(primitives, primitive, height) {
- shellHeights.set(primitive, height);
- if (typeof primitives.lowerToBottom !== 'function') return;
- const shells = [];
- for (let i = 0; i < primitives.length; i++) {
- const item = primitives.get(i);
- if (shellHeights.has(item)) shells.push(item);
- }
- const ordered = [...shells].sort(
- (a, b) => shellHeights.get(a) - shellHeights.get(b),
- );
- if (ordered.every((item, i) => primitives.get(i) === item)) return;
- for (const item of ordered.reverse()) primitives.lowerToBottom(item);
-}
-
-/** One raised rectangle drawing one full-extent image and, inside a window of
- * it, an optional detail image. The owner calls destroy(). */
-export function createShellSurface({
+/**
+ * Tell `apply` the shell lift for the camera's height now and, each frame
+ * before it draws, whenever it changes.
+ * @param {object} viewer
+ * @param {(liftM: number) => void} apply
+ * @param {{cameraOf?: Function, frameOf?: Function}} [ports]
+ * @returns {() => void} Stops.
+ */
+export function followShellLift(
viewer,
- cesium,
- rectangle,
- height,
- onSettled = () => {},
-}) {
- registerMaterial(cesium);
- const scene = viewer.scene;
- const primitives = scene.primitives;
- const material = new cesium.Material({
- fabric: { type: MATERIAL_TYPE },
- translucent: false,
- });
- // Flat shading keeps the product colours independent of the viewing angle.
- const appearance = new cesium.EllipsoidSurfaceAppearance({
- aboveGround: true,
- flat: true,
- translucent: false,
- material,
- });
- // Cesium orders its translucent pass itself (weighted OIT or distance), which
- // cannot honour stacked heights. Draw in the opaque pass in scene.primitives
- // order, alpha-blended and without depth writes, so higher shells draw over
- // lower ones and nothing is hidden or picked through a shell.
- appearance.getRenderState = () => ({
- depthTest: { enabled: true },
- depthMask: false,
- blending: cesium.BlendingState.ALPHA_BLEND,
- });
- const primitive = new cesium.Primitive({
- geometryInstances: new cesium.GeometryInstance({
- geometry: new cesium.RectangleGeometry({
- rectangle,
- height,
- granularity: cesium.Math.toRadians(0.5),
- vertexFormat: cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
- }),
- }),
- appearance,
- asynchronous: true,
- allowPicking: false,
- });
- primitives.add(primitive);
- orderWeatherShells(primitives, primitive, height);
- // A uniform scale about the Earth's centre lifts every shell alike and keeps
- // their order.
- let lift = 0;
- const offLift = scene.preRender?.addEventListener(() => {
- const next = shellLift(scene.camera?.positionCartographic?.height);
+ apply,
+ { cameraOf = findCamera, frameOf = findFrame } = {},
+) {
+ let lift = null;
+ const read = () => {
+ const next = shellLift(cameraOf(viewer)?.pose?.().height);
if (next === lift) return;
lift = next;
- primitive.modelMatrix = cesium.Matrix4.fromUniformScale(
- 1 + lift / cesium.Ellipsoid.WGS84.maximumRadius,
- );
- });
- let image = null;
- let frames = 0;
- // The detail image, its own upload count and a window waiting for it to draw.
- let detail = null;
- let detailFrames = 0;
- let pendingWindow = null;
- let offRender = null;
- let destroyed = false;
-
- const fits = (size, value) =>
- !size || (size.x === value.width && size.y === value.height);
- const uploaded = () =>
- image !== null && fits(material.uniforms.imageDimensions, image);
- const detailDrawn = () =>
- detail !== null &&
- detailFrames === 0 &&
- fits(material.uniforms.detailDimensions, detail);
- const drawn = () =>
- primitive.ready &&
- uploaded() &&
- frames === 0 &&
- (detail === null || (detailDrawn() && pendingWindow === null));
- function appliedWindow() {
- const { x, y, z, w } = material.uniforms.window;
- return z < x ? null : { west: x, south: y, east: z, north: w };
- }
- function setWindow(rect) {
- const next = rect ?? NO_WINDOW;
- const { x, y, z, w } = material.uniforms.window;
- if (
- x === next.west &&
- y === next.south &&
- z === next.east &&
- w === next.north
- )
- return;
- material.uniforms.window = new cesium.Cartesian4(
- next.west,
- next.south,
- next.east,
- next.north,
- );
- scene.requestRender();
- }
- // The render governor may idle the scene; request frames only until the
- // asynchronous geometry is ready and the latest images have been drawn.
- function tick() {
- // Cesium updates a material only while its primitive is shown, so hidden
- // frames upload nothing and count for nothing.
- if (primitive.ready && primitive.show) {
- if (frames > 0) frames--;
- if (detailFrames > 0) detailFrames--;
- // A texture is never shown at another window's place.
- if (pendingWindow && detailDrawn()) {
- setWindow(pendingWindow);
- pendingWindow = null;
- }
- }
- if (primitive.show && !drawn()) {
- scene.requestRender();
- return;
- }
- offRender?.();
- offRender = null;
- if (drawn()) onSettled();
- }
- function wake() {
- if (destroyed || !primitive.show || image === null || drawn()) return;
- offRender ??= scene.postRender.addEventListener(tick);
- scene.requestRender();
- }
-
- return {
- setImage(next) {
- if (destroyed || next === image) return;
- image = next;
- material.uniforms.image = next;
- frames = UPLOAD_FRAMES;
- wake();
- },
- setAlpha(value) {
- if (destroyed || material.uniforms.alpha === value) return;
- material.uniforms.alpha = 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
- * this one is uploaded. A different window applies once its image has
- * drawn; until then the full-extent image covers it. */
- setDetail(next, rect) {
- if (destroyed) return;
- if (!next) {
- if (detail === null) return;
- detail = null;
- detailFrames = 0;
- pendingWindow = null;
- material.uniforms.detail = cesium.Material.DefaultImageId;
- setWindow(null);
- scene.requestRender();
- return;
- }
- if (next !== detail) {
- detail = next;
- material.uniforms.detail = next;
- detailFrames = UPLOAD_FRAMES;
- }
- const applied = appliedWindow();
- if (applied && sameEdges(applied, rect)) {
- pendingWindow = null;
- } else {
- setWindow(null);
- pendingWindow = rect;
- }
- wake();
- },
- /** Returns whether visibility changed. */
- setShow(value) {
- const show = Boolean(value);
- if (destroyed || primitive.show === show) return false;
- primitive.show = show;
- wake();
- scene.requestRender();
- return true;
- },
- destroy() {
- if (destroyed) return;
- destroyed = true;
- offRender?.();
- offRender = null;
- offLift?.();
- if (!primitives.isDestroyed?.() && primitives.contains(primitive))
- primitives.remove(primitive);
- if (!primitive.isDestroyed()) primitive.destroy();
- // Primitive.destroy leaves the material and its texture alive.
- if (!material.isDestroyed()) material.destroy();
- image = null;
- detail = null;
- pendingWindow = null;
- scene.requestRender();
- },
- getDiagnostics() {
- return {
- height,
- ready: Boolean(primitive.ready),
- uploaded: uploaded(),
- show: primitive.show,
- alpha: material.uniforms.alpha,
- rendering: offRender !== null,
- // `uploaded` once the detail image has drawn; the window applies after.
- detail: { uploaded: detailDrawn(), window: appliedWindow() },
- };
- },
+ apply(next);
};
+ read();
+ return frameOf(viewer)?.on('preRender', read) ?? (() => {});
}
-function fitTexture(cesium, { width, height }) {
- const limit = cesium.ContextLimits?.maximumTextureSize;
+function fitTexture({ width, height }, limit) {
// Halve, down to 1024 px wide, on devices with a smaller texture limit.
while (limit > 0 && width > limit && width > 1024) {
width /= 2;
@@ -404,13 +155,14 @@ export function detailWindow(footprint, bounds, previous = null) {
return previous && sameEdges(previous, next) ? previous : next;
}
+let weatherShells = 0;
+
/** Observed weather on 3D Tiles: one raised shell per product and one
* full-extent image per frame. The previous image stays until the next is ready.
* Inside a window around the view the same surface samples a sharper image of
* that area, so the two images share one mesh and never blend. */
export function createWeatherShell({
viewer,
- cesium = Cesium,
product,
height = WEATHER_SHELL_HEIGHTS[product],
getHost = () => ({ collection: null, kind: 'tileset' }),
@@ -421,17 +173,35 @@ export function createWeatherShell({
decodeImage,
createCanvas = () => document.createElement('canvas'),
cacheBytes = WEATHER_SHELL_CACHE_BYTES,
+ drawOf = findDraw,
+ cameraOf = findCamera,
+ frameOf = findFrame,
+ maxTextureSize = rendererOf(viewer)?.quality?.device?.().maxTextureSize ?? 0,
}) {
if (!Object.hasOwn(WEATHER_IMAGE_SIZES, product))
throw new TypeError('Unknown weather product');
- const scene = viewer.scene;
- const size = fitTexture(cesium, WEATHER_IMAGE_SIZES[product]);
- const detailSize = fitTexture(cesium, WEATHER_DETAIL_SIZE);
+ const size = fitTexture(WEATHER_IMAGE_SIZES[product], maxTextureSize);
+ const detailSize = fitTexture(WEATHER_DETAIL_SIZE, maxTextureSize);
const infrared = product === 'clouds' || product === 'clouds-regional';
// Global infrared contrast depends on the requested extent, so a window would
// not match the image around it; the globe host also shows one mosaic.
const detailed = product !== 'clouds';
- let surface = null;
+ const requestRender = () => frameOf(viewer)?.requestRender('weather');
+ // The shell's field, and what it was last given: the committed frame's
+ // bounds and image, and the detail.
+ let field = null;
+ let offLift = null;
+ let fieldBounds = null;
+ let fieldImage = null;
+ let fieldRect = null;
+ let fieldDetail = null;
+ let fieldAlpha = 0;
+ // What its 'drawn' has told: anything yet, the image and the detail it
+ // was last given, and whether a change waits for it.
+ let everDrawn = false;
+ let imageDrawn = false;
+ let detailDrawn = false;
+ let owed = false;
let current = null;
let incoming = null;
let alpha = 0.7;
@@ -456,6 +226,72 @@ export function createWeatherShell({
`${time}|${infrared ? mode : 'none'}${box ? `|${boundsKey(box)}` : ''}`;
const wantedDetail = () =>
current && view ? cacheKey(current.time, current.infrared, view) : null;
+ const imageRef = (canvas, key) => ({ canvas, key });
+
+ function update(patch) {
+ owed = true;
+ field.update(patch);
+ }
+ function onDrawn() {
+ owed = false;
+ everDrawn = true;
+ imageDrawn = true;
+ detailDrawn = fieldDetail !== null;
+ if (incoming?.staged) commit(incoming);
+ }
+ function makeField(rectangle, image) {
+ field = drawOf(viewer).field({
+ kind: 'rasterShell',
+ id: `weather-shell:${product}:${(weatherShells += 1)}`,
+ image,
+ rectangle,
+ heightM: height,
+ alpha,
+ detail: null,
+ });
+ fieldAlpha = alpha;
+ owed = true;
+ field.on('drawn', onDrawn);
+ offLift = followShellLift(viewer, (liftM) => update({ liftM }), {
+ cameraOf,
+ frameOf,
+ });
+ }
+ function dropField() {
+ offLift?.();
+ offLift = null;
+ field?.dispose();
+ field = null;
+ fieldBounds = null;
+ fieldImage = null;
+ fieldRect = null;
+ fieldDetail = null;
+ everDrawn = false;
+ imageDrawn = false;
+ detailDrawn = false;
+ owed = false;
+ }
+ /** Give the field `next` for its detail, unless it has it already. */
+ function giveDetail(next) {
+ if (!field) return;
+ const given = incoming?.staged ? incoming.keptDetail : fieldDetail;
+ const same =
+ next === given ||
+ (next &&
+ given &&
+ next.image.canvas === given.image.canvas &&
+ sameEdges(next.rectangle, given.rectangle));
+ if (same) return;
+ // A frame being staged takes its detail once it is committed; until
+ // then the detail is what the field goes back to if it is given up.
+ if (incoming?.staged) {
+ incoming.keptDetail = next;
+ return;
+ }
+ fieldDetail = next;
+ detailDrawn = false;
+ update({ detail: next });
+ }
function evict(keep = []) {
const kept = new Set([...keep, current?.key, detail?.key]);
@@ -517,11 +353,19 @@ export function createWeatherShell({
};
}
function syncDetail() {
- if (detail && current) surface?.setDetail(detail.image, detailRect());
- else surface?.setDetail(null);
+ if (detail && current)
+ giveDetail({
+ image: imageRef(detail.image, detail.key),
+ rectangle: { ...detail.box },
+ });
+ else giveDetail(null);
}
function applyVisibility() {
- return surface?.setShow(visible()) ?? false;
+ if (!field) return false;
+ const show = visible();
+ if (field.show === show) return false;
+ field.show = show;
+ return true;
}
function cancelDetail() {
clearTimeout(detailJob?.timeout);
@@ -531,7 +375,7 @@ export function createWeatherShell({
function dropDetail() {
detail = null;
// The full-extent image covers the window in the same turn.
- surface?.setDetail(null);
+ giveDetail(null);
}
function installDetail(job, image) {
if (detailJob !== job) return;
@@ -540,14 +384,14 @@ export function createWeatherShell({
detail = { box: job.box, key: job.key, image, stale: false };
syncDetail();
evict();
- scene.requestRender();
+ requestRender();
}
function failDetail(job) {
if (detailJob !== job) return;
clearTimeout(job.timeout);
detailJob = null;
if (detail?.stale) dropDetail();
- scene.requestRender();
+ requestRender();
}
/** Bring the detail to the shown frame and window. The previous detail image
* stays until the next is decoded unless the window itself moved, and over at
@@ -585,16 +429,9 @@ export function createWeatherShell({
}
/** Recompute the window from the camera's ground footprint; returns whether it changed. */
function computeView() {
- const rectangle = detailed
- ? viewer.camera?.computeViewRectangle?.(scene.globe?.ellipsoid)
+ const footprint = detailed
+ ? (cameraOf(viewer)?.viewRectangle?.() ?? null)
: null;
- const degrees = cesium.Math.toDegrees;
- const footprint = rectangle && {
- west: degrees(rectangle.west),
- south: degrees(rectangle.south),
- east: degrees(rectangle.east),
- north: degrees(rectangle.north),
- };
const next = detailWindow(
footprint,
current.extent,
@@ -608,7 +445,7 @@ export function createWeatherShell({
function watchCamera() {
if (offCamera || !detailed) return;
offCamera =
- viewer.camera?.moveEnd?.addEventListener(() => {
+ cameraOf(viewer)?.on?.('moveEnd', () => {
if (current && computeView()) refreshDetail();
}) ?? null;
}
@@ -623,18 +460,30 @@ export function createWeatherShell({
frame.owned = true;
const abort = () => {
if (incoming === frame) cancelIncoming();
- scene.requestRender();
+ requestRender();
};
signal.addEventListener('abort', abort, { once: true });
frame.offAbort = () => signal.removeEventListener('abort', abort);
}
+ /** A staged frame given up: the field goes back to what it drew. */
+ function unstage(frame) {
+ if (!frame.staged) return;
+ frame.staged = false;
+ if (fieldBounds === null) {
+ dropField();
+ return;
+ }
+ fieldDetail = frame.keptDetail ?? null;
+ detailDrawn = false;
+ imageDrawn = false;
+ update({ image: fieldImage, rectangle: fieldRect, detail: fieldDetail });
+ }
function close(frame) {
frame.closed = true;
frame.controller.abort();
clearTimeout(frame.timeout);
frame.offAbort?.();
- frame.surface?.destroy();
- frame.surface = null;
+ unstage(frame);
}
function cancelIncoming() {
if (!incoming) return;
@@ -649,7 +498,7 @@ export function createWeatherShell({
close(frame);
lastError = msg('Weather tiles unavailable · previous frame retained');
frame.resolve(false);
- scene.requestRender();
+ requestRender();
onChange();
}
function commit(frame) {
@@ -657,12 +506,13 @@ export function createWeatherShell({
incoming = null;
clearTimeout(frame.timeout);
frame.offAbort?.();
- if (frame.surface) {
- surface?.destroy();
- surface = frame.surface;
- frame.surface = null;
- }
const { west, south, east, north } = frame.snapshot.bounds;
+ if (frame.staged) {
+ frame.staged = false;
+ fieldBounds = frame.bounds;
+ fieldRect = { west, south, east, north };
+ }
+ fieldImage = frame.image;
current = {
time: frame.time,
product: frame.product,
@@ -673,7 +523,10 @@ export function createWeatherShell({
mosaic: frame.mosaic,
loadMs: now() - frame.startedAt,
};
- surface.setAlpha(alpha);
+ if (fieldAlpha !== alpha) {
+ fieldAlpha = alpha;
+ update({ alpha });
+ }
applyVisibility();
lastError = null;
evict();
@@ -684,31 +537,35 @@ export function createWeatherShell({
if (detail?.stale && detail.key !== wantedDetail()) dropDetail();
refreshDetail();
frame.resolve(true);
- scene.requestRender();
+ requestRender();
onChange();
}
- function install(frame, image) {
+ function install(frame, texture) {
if (frame.closed || incoming !== frame) return;
- if (surface?.bounds === frame.bounds) {
- // Cesium keeps drawing the previous texture until this one is uploaded.
- surface.setImage(image);
+ frame.image = imageRef(texture, frame.key);
+ if (field && fieldBounds === frame.bounds) {
+ // The renderer keeps drawing the previous image until this one is drawn.
+ imageDrawn = false;
+ update({ image: frame.image });
commit(frame);
return;
}
- // First frame or a new extent: stage an invisible surface and keep the
- // previous one until the new geometry and texture are drawable.
+ // First frame or a new extent: the field keeps what it draws until the
+ // new rectangle and image can be drawn, then the frame commits.
const { west, south, east, north } = frame.snapshot.bounds;
- const next = createShellSurface({
- viewer,
- cesium,
- height,
- rectangle: cesium.Rectangle.fromDegrees(west, south, east, north),
- onSettled: () => commit(frame),
- });
- next.bounds = frame.bounds;
- frame.surface = next;
- next.setAlpha(0);
- next.setImage(image);
+ const rectangle = { west, south, east, north };
+ frame.staged = true;
+ imageDrawn = false;
+ if (!field) makeField(rectangle, frame.image);
+ else {
+ frame.keptDetail = fieldDetail;
+ fieldDetail = null;
+ detailDrawn = false;
+ update({ image: frame.image, rectangle, detail: null });
+ }
+ // A hidden field tells nothing drawn: the renderer readies the new
+ // content unseen and shows it, not the old, once the field shows.
+ if (!visible()) commit(frame);
}
return {
@@ -724,7 +581,7 @@ export function createWeatherShell({
computeView();
refreshDetail();
}
- if (changed) scene.requestRender();
+ if (changed) requestRender();
return changed;
},
cancelPrefetch,
@@ -799,7 +656,9 @@ export function createWeatherShell({
mosaic: { fetched: false, decodeMs: null, cached: false },
controller: new AbortController(),
startedAt: now(),
- surface: null,
+ image: null,
+ staged: false,
+ keptDetail: null,
owned: false,
closed: false,
resolve: null,
@@ -821,7 +680,7 @@ export function createWeatherShell({
install(frame, texture);
})
.catch(() => fail(frame));
- scene.requestRender();
+ requestRender();
onChange();
return frame.result;
},
@@ -834,12 +693,15 @@ export function createWeatherShell({
}
applyVisibility();
if (!hidden) refreshDetail();
- scene.requestRender();
+ requestRender();
},
setAlpha(value) {
alpha = value;
- surface?.setAlpha(alpha);
- scene.requestRender();
+ if (field && fieldAlpha !== alpha) {
+ fieldAlpha = alpha;
+ update({ alpha });
+ }
+ requestRender();
},
clear() {
cancelPrefetch();
@@ -848,8 +710,7 @@ export function createWeatherShell({
offCamera?.();
offCamera = null;
dropDetail();
- surface?.destroy();
- surface = null;
+ dropField();
current = null;
view = null;
viewBounds = null;
@@ -857,11 +718,21 @@ export function createWeatherShell({
lastError = null;
images.clear();
imageBytes = 0;
- scene.requestRender();
+ requestRender();
},
getDiagnostics() {
- const drawn = surface?.getDiagnostics();
- const applied = drawn?.detail.window;
+ // The detail is drawn once its image has drawn in its window.
+ const window =
+ current && detail && detailDrawn && fieldDetail ? detailRect() : null;
+ const drawn = field && {
+ height,
+ ready: everDrawn,
+ uploaded: imageDrawn,
+ show: field.show,
+ alpha: fieldAlpha,
+ rendering: owed && field.show,
+ detail: { uploaded: detailDrawn, window },
+ };
return {
host: 'shell',
height,
@@ -882,8 +753,8 @@ export function createWeatherShell({
drawn.ready &&
drawn.show &&
drawn.detail.uploaded &&
- applied &&
- sameEdges(applied, detailRect()),
+ window &&
+ !owed,
),
enabled: view !== null,
},
@@ -894,7 +765,7 @@ export function createWeatherShell({
bytes: imageBytes,
prefetching: !!prefetchJob,
},
- imageryCount: Number(!!surface) + Number(!!incoming?.surface),
+ imageryCount: Number(fieldBounds !== null) + Number(!!incoming?.staged),
mosaic: (incoming || current)?.mosaic,
infrared: (incoming || current)?.infrared ?? 'filtered',
loading: !!incoming,
diff --git a/src/layers/weather/shellRendering.test.mjs b/src/layers/weather/shellRendering.test.mjs
index ad65dcef2..f1f755f1c 100644
--- a/src/layers/weather/shellRendering.test.mjs
+++ b/src/layers/weather/shellRendering.test.mjs
@@ -2,16 +2,16 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
- createShellSurface,
createWeatherShell,
detailWindow,
- orderWeatherShells,
+ followShellLift,
shellLift,
WEATHER_SHELL_CACHE_BYTES,
WEATHER_SHELL_HEIGHTS,
} from './shellRendering.js';
import { NO_IMAGERY_HOST } from './imageryHost.js';
import {
+ bindShellFields,
createShellCesium,
createShellScene,
renderShells,
@@ -72,10 +72,12 @@ function harness({ product = 'radar', camera, ...options } = {}) {
const fetches = [];
const decoded = [];
let host = { collection: null, kind: 'tileset' };
+ const viewer = { scene, camera };
+ bindShellFields(viewer, cesium);
const shell = createWeatherShell({
- viewer: { scene, camera },
- cesium,
+ viewer,
product,
+ maxTextureSize: cesium.ContextLimits.maximumTextureSize,
getHost: () => host,
fetchImpl: async (url, init) => {
fetches.push({ url, signal: init.signal });
@@ -131,317 +133,36 @@ test('shell heights stack every product with lightning highest', () => {
assert.equal(WEATHER_SHELL_CACHE_BYTES, 128 * 1024 * 1024);
});
-test('surface builds a flat raised rectangle drawn in primitive order without depth writes', () => {
- const cesium = createShellCesium();
- const scene = createShellScene();
- const rectangle = Cesium.Rectangle.fromDegrees(-130, 20, -60, 55);
- const surface = createShellSurface({
- viewer: { scene },
- cesium,
- rectangle,
- height: 6_200,
- });
- const template = cesium.templates.get('WeatherFrame');
- assert.ok(!(template instanceof cesium.Material), 'plain template');
- assert.deepEqual(template.fabric.uniforms, {
- image: Cesium.Material.DefaultImageId,
- detail: Cesium.Material.DefaultImageId,
- alpha: 1,
- 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\)\);/,
- 'nothing draws before the full-extent image',
- );
- assert.match(
- source,
- /float useDetail = inside \* step\(1\.5, float\(detailDimensions\.x\)\);/,
- 'the detail image is sampled only once it has arrived',
- );
- assert.match(
- source,
- /all\(greaterThanEqual\(st, window\.xy\)\) && all\(lessThanEqual\(st, window\.zw\)\)/,
- );
- assert.match(
- source,
- /mix\(coarse, texture\(detail, clamp\(dst, 0\.0, 1\.0\)\), useDetail\)/,
- );
- assert.match(source, /material\.diffuse = czm_gammaCorrect\(c\.rgb\);/);
- const [primitive] = scene.primitives.items;
- const appearance = primitive.appearance;
- assert.equal(appearance.material.options.translucent, false);
- assert.deepEqual(
- { ...appearance.options, material: undefined },
- {
- aboveGround: true,
- flat: true,
- translucent: false,
- material: undefined,
- },
- );
- assert.deepEqual(appearance.getRenderState(), {
- depthTest: { enabled: true },
- depthMask: false,
- blending: Cesium.BlendingState.ALPHA_BLEND,
- });
- const geometry = primitive.options.geometryInstances.geometry.options;
- assert.equal(geometry.rectangle, rectangle);
- assert.equal(geometry.height, 6_200);
- assert.equal(geometry.granularity, Cesium.Math.toRadians(0.5));
- assert.equal(
- geometry.vertexFormat,
- Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
- );
- assert.equal(primitive.options.asynchronous, true);
- assert.equal(primitive.options.allowPicking, false);
- const lower = createShellSurface({
- viewer: { scene },
- cesium,
- rectangle,
- height: 5_000,
- });
- assert.equal(cesium.templates.size, 1, 'the template registers once');
- assert.deepEqual(
- scene.primitives.items.map(
- (item) => item.options.geometryInstances.geometry.options.height,
- ),
- [5_000, 6_200],
- );
- lower.destroy();
- surface.destroy();
-});
-
-test('a surface applies a new detail window only once its image has drawn; the same window swaps only the image', () => {
- const cesium = createShellCesium();
- const scene = createShellScene();
- const surface = createShellSurface({
- viewer: { scene },
- cesium,
- rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
- height: 6_200,
- });
- const [primitive] = scene.primitives.items;
- const { uniforms } = primitive.appearance.material;
- const render = (count) => renderShells(cesium, scene, count);
- const image = () => ({ width: 4096, height: 2048 });
- surface.setImage(image());
- render();
- assert.deepEqual(surface.getDiagnostics().detail, {
- uploaded: false,
- window: null,
- });
- const a = { west: 0.25, south: 0.5, east: 0.5, north: 0.75 };
- const first = image();
- surface.setDetail(first, a);
- assert.equal(uniforms.detail, first);
- assert.deepEqual(windowOf(primitive), NONE, 'the full-extent image covers');
- assert.equal(scene.postRender.size, 1, 'renders until the detail has drawn');
- render(2);
- assert.deepEqual(windowOf(primitive), NONE);
- render(1);
- assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
- assert.ok(uniforms.window instanceof Cesium.Cartesian4);
- assert.deepEqual(surface.getDiagnostics().detail, {
- uploaded: true,
- window: a,
- });
- assert.equal(scene.postRender.size, 0);
-
- // A time change in the same window: Cesium keeps drawing the previous
- // texture until the new one is uploaded, so the window stays.
- const applied = uniforms.window;
- const second = image();
- surface.setDetail(second, { ...a });
- assert.equal(uniforms.detail, second);
- assert.equal(uniforms.window, applied, 'only the image is written');
- assert.equal(surface.getDiagnostics().detail.uploaded, false);
- render();
- assert.equal(surface.getDiagnostics().detail.uploaded, true);
- assert.equal(uniforms.window, applied);
- const renders = scene.renders;
- surface.setDetail(second, { ...a });
- assert.equal(scene.renders, renders, 'an unchanged detail costs nothing');
- assert.equal(scene.postRender.size, 0);
-
- // A different window empties at once and applies once its image has drawn.
- const b = { west: 0.5, south: 0.25, east: 0.75, north: 0.5 };
- surface.setDetail(image(), b);
- assert.deepEqual(windowOf(primitive), NONE);
- render(2);
- assert.deepEqual(windowOf(primitive), NONE);
- render(1);
- assert.deepEqual(windowOf(primitive), { x: 0.5, y: 0.25, z: 0.75, w: 0.5 });
-
- surface.setDetail(null);
- assert.equal(uniforms.detail, Cesium.Material.DefaultImageId);
- assert.deepEqual(windowOf(primitive), NONE);
- assert.deepEqual(surface.getDiagnostics().detail, {
- uploaded: false,
- window: null,
- });
- render();
- assert.deepEqual(
- { ...uniforms.detailDimensions },
- { type: 'ivec3', x: 1, y: 1 },
- );
- // Counted renders alone are not enough: the bound texture must be this image.
- surface.setDetail(image(), a);
- for (let i = 0; i < 4; i++) scene.postRender.emit();
- assert.deepEqual(windowOf(primitive), NONE, 'still the 1×1 default');
- render(1);
- assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
- surface.destroy();
- surface.setDetail(image(), b);
- assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
- assert.equal(scene.postRender.size, 0);
-});
-
test('shells rise with the camera over coarse 3D tiles, in steps, up to 60 km', () => {
assert.equal(shellLift(undefined), 0);
assert.equal(shellLift(1_200), 0, 'city views keep the shell heights');
assert.equal(shellLift(3_000_000), 12_000);
assert.equal(shellLift(8_000_000), 32_000);
assert.equal(shellLift(18_500_000), 60_000);
- const camera = { positionCartographic: { height: 1_200 } };
- const scene = {
- primitives: new Cesium.PrimitiveCollection(),
- preRender: new Cesium.Event(),
- postRender: new Cesium.Event(),
- camera,
- requestRender() {},
- };
- const surface = createShellSurface({
- viewer: { scene },
- cesium: Cesium,
- rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
- height: 5_800,
+ let height = 1_200;
+ const preRender = new Set();
+ const lifts = [];
+ const off = followShellLift({}, (lift) => lifts.push(lift), {
+ cameraOf: () => ({ pose: () => ({ height }) }),
+ frameOf: () => ({
+ on(phase, cb) {
+ assert.equal(phase, 'preRender');
+ preRender.add(cb);
+ return () => preRender.delete(cb);
+ },
+ }),
});
- const primitive = scene.primitives.get(0);
- const identity = primitive.modelMatrix;
- scene.preRender.raiseEvent();
- assert.equal(primitive.modelMatrix, identity, 'no lift, no new matrix');
- camera.positionCartographic.height = 8_000_000;
- scene.preRender.raiseEvent();
- const radius = Cesium.Ellipsoid.WGS84.maximumRadius;
- assert.ok(
- Math.abs(primitive.modelMatrix[0] * radius - (radius + 32_000)) < 1e-3,
- );
- const lifted = primitive.modelMatrix;
- camera.positionCartographic.height = 8_010_000;
- scene.preRender.raiseEvent();
- assert.equal(primitive.modelMatrix, lifted, 'the same step keeps the matrix');
- surface.destroy();
- assert.equal(scene.preRender.numberOfListeners, 0);
-});
-
-test('real Cesium builds the two-texture material, the opaque-pass appearance and the rectangle primitive', () => {
- const scene = {
- primitives: new Cesium.PrimitiveCollection(),
- postRender: new Cesium.Event(),
- requestRender() {},
- };
- const surface = createShellSurface({
- viewer: { scene },
- cesium: Cesium,
- rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
- height: 6_600,
- });
- const cached = Cesium.Material._materialCache.getMaterial('WeatherFrame');
- assert.ok(cached && !(cached instanceof Cesium.Material));
- const primitive = scene.primitives.get(0);
- const material = primitive.appearance.material;
- assert.ok(primitive instanceof Cesium.Primitive);
- assert.equal(material.type, 'WeatherFrame');
- assert.equal(material.isTranslucent(), false);
- assert.equal(primitive.appearance.isTranslucent(), false, 'opaque pass');
- assert.equal(primitive.appearance.getRenderState().depthMask, false);
- assert.equal(
- Cesium.Appearance.prototype.getRenderState.call(primitive.appearance)
- .depthMask,
- true,
- 'the default opaque render state would write depth',
- );
- assert.deepEqual(
- [material.uniforms.imageDimensions.x, material.uniforms.detailDimensions.x],
- [1, 1],
- 'Cesium tracks both bound texture sizes',
- );
- const shader = material.shaderSource;
- for (const declaration of [
- /uniform sampler2D image_\d+;/,
- /uniform sampler2D detail_\d+;/,
- /uniform float alpha_\d+;/,
- /uniform vec4 window_\d+;/,
- /uniform ivec3 imageDimensions_\d+;/,
- /uniform ivec3 detailDimensions_\d+;/,
- ])
- assert.match(shader, declaration);
- assert.match(shader, /texture\(image_\d+, st\)/);
- assert.match(shader, /texture\(detail_\d+, clamp\(dst, 0\.0, 1\.0\)\)/);
- assert.match(shader, /lessThanEqual\(st, window_\d+\.zw\)/);
- 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\)\);/,
- 'the uniform is renamed, the material field is not',
- );
- 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 });
- assert.equal(material.uniforms.detail, detail);
- assert.deepEqual(
- [material.uniforms.window.z, material.uniforms.window.w],
- [-1, -1],
- 'no window before the image has drawn',
- );
- surface.setDetail(null);
- assert.equal(material.uniforms.detail, Cesium.Material.DefaultImageId);
- surface.setAlpha(0.4);
- assert.equal(material.uniforms.alpha, 0.4);
- surface.destroy();
- assert.equal(scene.primitives.length, 0);
- assert.equal(primitive.isDestroyed(), true);
- assert.equal(material.isDestroyed(), true);
- assert.equal(scene.postRender.numberOfListeners, 0);
-});
-
-test('shells draw first, in height order, regardless of add order', () => {
- const scene = createShellScene();
- const other = { name: 'other' };
- scene.primitives.add(other);
- const add = (name, height) => {
- const primitive = { name };
- scene.primitives.add(primitive);
- orderWeatherShells(scene.primitives, primitive, height);
- return primitive;
- };
- add('lightning', 6_600);
- add('radar', 6_200);
- add('wind', 5_000);
- const later = { name: 'later' };
- scene.primitives.add(later);
- add('regional', 5_800);
- assert.deepEqual(
- scene.primitives.items.map(({ name }) => name),
- ['wind', 'regional', 'radar', 'lightning', 'other', 'later'],
- );
- const primitives = new Cesium.PrimitiveCollection({
- destroyPrimitives: false,
- });
- const real = (name) => ({ name, update() {}, isDestroyed: () => false });
- const tileset = primitives.add(real('tileset'));
- const lightning = primitives.add(real('lightning'));
- orderWeatherShells(primitives, lightning, 6_600);
- const radar = primitives.add(real('radar'));
- orderWeatherShells(primitives, radar, 6_200);
- assert.deepEqual(
- [0, 1, 2].map((i) => primitives.get(i).name),
- ['radar', 'lightning', 'tileset'],
- 'real Cesium collection order',
- );
- assert.equal(tileset.name, 'tileset');
+ const frame = () => [...preRender].forEach((cb) => cb());
+ assert.deepEqual(lifts, [0], 'told at once');
+ frame();
+ assert.deepEqual(lifts, [0], 'no change, nothing told');
+ height = 8_000_000;
+ frame();
+ height = 8_010_000;
+ frame();
+ assert.deepEqual(lifts, [0, 32_000], 'the same step is told once');
+ off();
+ assert.equal(preRender.size, 0);
});
test('first frame stages invisibly, requests renders until drawable and then commits', async () => {
@@ -871,40 +592,6 @@ test('an unowned restage is joined by the next request for the same frame', asyn
const footprint = (west, south, east, north) => ({ west, south, east, north });
const box = (west, south, east, north) => ({ west, south, east, north });
-test('hidden frames do not count towards a pending detail window', () => {
- const cesium = createShellCesium();
- const scene = createShellScene();
- const surface = createShellSurface({
- viewer: { scene },
- cesium,
- rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
- height: 6_200,
- });
- const [primitive] = scene.primitives.items;
- const render = (count) => renderShells(cesium, scene, count);
- const image = () => ({ width: 4096, height: 2048 });
- surface.setImage(image());
- const a = { west: 0.25, south: 0.5, east: 0.5, north: 0.75 };
- surface.setDetail(image(), a);
- render();
- assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
- // A different window with a same-sized image: the dimensions alone cannot
- // tell the textures apart, so only shown frames may count.
- const b = { west: 0.5, south: 0.25, east: 0.75, north: 0.5 };
- surface.setDetail(image(), b);
- assert.deepEqual(windowOf(primitive), NONE);
- for (let i = 0; i < 3; i++) {
- surface.setShow(false);
- scene.postRender.emit();
- surface.setShow(true);
- }
- assert.deepEqual(windowOf(primitive), NONE, 'hidden frames counted nothing');
- render(2);
- assert.deepEqual(windowOf(primitive), NONE);
- render(1);
- assert.deepEqual(windowOf(primitive), { x: 0.5, y: 0.25, z: 0.75, w: 0.5 });
-});
-
test('detail windows are sized from the footprint, snapped to 0.5° and clamped inside the product', () => {
// max(2 × the longitude span, 6°) wide, half as tall.
assert.deepEqual(
diff --git a/src/layers/weather/weather.test.mjs b/src/layers/weather/weather.test.mjs
index d4a2a726d..cf341f31f 100644
--- a/src/layers/weather/weather.test.mjs
+++ b/src/layers/weather/weather.test.mjs
@@ -7,6 +7,7 @@ import * as Cesium from 'cesium';
import { Color, ImageryLayerCollection, GeographicTilingScheme } from 'cesium';
import { NO_IMAGERY_HOST } from './imageryHost.js';
import { createWeatherShell } from './shellRendering.js';
+import { createCesiumFields } from '../../render/cesium/drawFields.js';
import { WEATHER_IMAGERY_Z } from './imageryOrder.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { fakeSceneFrame } from '../../testSupport/fakeCesiumScene.mjs';
@@ -222,6 +223,9 @@ function renderingHarness(options = {}) {
Credit: Cesium.Credit,
Rectangle: Cesium.Rectangle,
};
+ // The Cesium draw port's raster shells, over the doubles.
+ const fields = createCesiumFields({ scene: viewer.scene, cesium });
+ const draw = { field: (spec) => fields.field(spec) };
const rendering = createWeatherRendering({
viewer,
globeOf: () => globe,
@@ -230,7 +234,12 @@ function renderingHarness(options = {}) {
frameOf: () => frame,
toBitmap: (canvas) => canvas,
createShell: (shellOptions) =>
- createWeatherShell({ ...shellOptions, cesium }),
+ createWeatherShell({
+ ...shellOptions,
+ drawOf: () => draw,
+ cameraOf: cameraOver,
+ frameOf: () => frame,
+ }),
fetchImpl: async () => mockResponse(),
decodeImage: async () => ({ width: 2048, height: 1024, close() {} }),
createCanvas,
diff --git a/src/layers/wind/rendering.js b/src/layers/wind/rendering.js
index 21735a93e..cfcf324dc 100644
--- a/src/layers/wind/rendering.js
+++ b/src/layers/wind/rendering.js
@@ -5,12 +5,12 @@ import * as Cesium from 'cesium';
import '../../render/cesium/globe.js';
import '../../render/cesium/camera.js';
import {
- createShellSurface,
+ followShellLift,
WEATHER_SHELL_HEIGHTS,
} from '../weather/shellRendering.js';
import { createWindRelief } from './relief.js';
import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js';
-import { findGlobe } from '../../render/rendererOf.js';
+import { findDraw, findGlobe } from '../../render/rendererOf.js';
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
import { msg } from '../../i18n/index.js';
import { createWindGpuRendering } from './gpuRendering.js';
@@ -63,6 +63,58 @@ function sameWind(previous, next, previousField, nextField) {
return true;
}
+let windShells = 0;
+
+/** The colour field as a raised shell over the whole globe, through the
+ * draw port's raster-shell field; it rises with the camera. */
+function createWindShell(viewer, draw, texture, alpha) {
+ const seq = (windShells += 1);
+ const height = WEATHER_SHELL_HEIGHTS.wind;
+ const field = draw.field({
+ kind: 'rasterShell',
+ id: `wind-shell:${seq}`,
+ image: { canvas: texture, key: `wind-shell:${seq}` },
+ rectangle: { west: -180, south: -90, east: 180, north: 90 },
+ heightM: height,
+ alpha,
+ });
+ let shownAlpha = alpha;
+ let drawn = false;
+ let owed = true;
+ field.on('drawn', () => {
+ drawn = true;
+ owed = false;
+ });
+ const offLift = followShellLift(viewer, (liftM) => {
+ owed = true;
+ field.update({ liftM });
+ });
+ return {
+ setAlpha(value) {
+ if (value === shownAlpha) return;
+ shownAlpha = value;
+ owed = true;
+ field.update({ alpha: value });
+ },
+ setShow(value) {
+ field.show = Boolean(value);
+ },
+ destroy() {
+ offLift();
+ field.dispose();
+ },
+ getDiagnostics: () => ({
+ height,
+ ready: drawn,
+ uploaded: drawn,
+ show: field.show,
+ alpha: shownAlpha,
+ rendering: owed && field.show,
+ detail: { uploaded: false, window: null },
+ }),
+ };
+}
+
/** Globe-projected surface flow plus one owned, static colour field: globe
* imagery on the globe host, a raised shell on the 3D Tiles host. */
export function createWindRendering({
@@ -73,6 +125,7 @@ export function createWindRendering({
eventTarget = globalThis.window,
createGpuRendering = createWindGpuRendering,
globeOf = findGlobe,
+ drawOf = findDraw,
onStatusChange,
} = {}) {
// The host the shell names, else the viewer's globe imagery.
@@ -362,7 +415,8 @@ export function createWindRendering({
imageryError = fieldUnavailableText(overlay);
return;
}
- if (kind === 'tileset' ? !cesium.Primitive : !globe) {
+ const draw = kind === 'tileset' ? drawOf(viewer) : null;
+ if (kind === 'tileset' ? !draw?.field : !globe) {
imageryError = msg('Globe imagery unavailable');
return;
}
@@ -375,15 +429,13 @@ export function createWindRendering({
pixels.data.set(raster.rgba);
ctx.putImageData(pixels, 0, 0);
if (kind === 'tileset') {
- shell = createShellSurface({
+ shell = createWindShell(
viewer,
- cesium,
- rectangle: cesium.Rectangle.MAX_VALUE,
- height: WEATHER_SHELL_HEIGHTS.wind,
- });
- shell.setImage(texture);
+ draw,
+ texture,
+ overlay === 'temperature' ? 1 : 0.85,
+ );
imageryKind = kind;
- shell.setAlpha(overlay === 'temperature' ? 1 : 0.85);
updateImageryFade(viewer.scene.camera, true);
viewer.scene?.requestRender?.();
return;
diff --git a/src/layers/wind/rendering.test.mjs b/src/layers/wind/rendering.test.mjs
index f34825527..815f8c90a 100644
--- a/src/layers/wind/rendering.test.mjs
+++ b/src/layers/wind/rendering.test.mjs
@@ -8,7 +8,9 @@ import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js';
import {
createShellCesium,
createShellScene,
+ renderShells,
} from '../weather/shellFixture.mjs';
+import { createCesiumFields } from '../../render/cesium/drawFields.js';
function event() {
const listeners = new Set();
@@ -197,8 +199,9 @@ function harness({
},
isDestroyed: () => false,
};
+ const shellCesium = shell ? createShellCesium() : null;
const cesium = {
- ...(shell ? createShellCesium() : {}),
+ ...(shellCesium ?? {}),
GeographicTilingScheme: Cesium.GeographicTilingScheme,
Credit: Cesium.Credit,
Event: Cesium.Event,
@@ -220,11 +223,17 @@ function harness({
}
},
};
+ const fields = shellCesium
+ ? createCesiumFields({ scene: viewer.scene, cesium: shellCesium })
+ : null;
+ const draw = fields && { field: (spec) => fields.field(spec) };
const rendering = createWindRendering({
cesium,
container,
getViewer: () => viewer,
globeOf: (given) => (given === viewer ? globe : null),
+ // The Cesium draw port's raster shells, over the doubles.
+ drawOf: (given) => (given === viewer ? draw : null),
createGpuRendering,
onStatusChange,
getHost,
@@ -245,7 +254,7 @@ function harness({
motion,
preRender,
viewer,
- cesium,
+ cesium: shellCesium ?? cesium,
imagery,
removed,
primitives: () => shellScene?.primitives.items ?? [],
@@ -1028,10 +1037,14 @@ test('scalar field becomes a raised shell on 3D Tiles and survives no-host event
eventTarget.dispatchEvent(new Event('gev:map-stack-changed'));
assert.equal(h.imagery.length, 0);
assert.equal(h.removed[0].destroy, true);
+ // It shows once its geometry and image are ready.
+ renderShells(h.cesium, h.viewer.scene);
const [primitive] = h.primitives();
const geometry = primitive.options.geometryInstances.geometry.options;
assert.equal(geometry.height, 5_000);
- assert.equal(geometry.rectangle, h.cesium.Rectangle.MAX_VALUE);
+ assert.ok(
+ h.cesium.Rectangle.equals(geometry.rectangle, h.cesium.Rectangle.MAX_VALUE),
+ );
const material = primitive.appearance.material;
assert.equal(h.textures.length, 2);
assert.equal(material.uniforms.image, h.textures[1]);
@@ -1121,6 +1134,7 @@ for (const overlay of ['speed', 'temperature', 'pressure']) {
h.rendering.setOptions({ overlay });
h.rendering.setField(field);
h.rendering.start();
+ renderShells(h.cesium, h.viewer.scene);
assert.equal(h.imagery.length, 0);
const [primitive] = h.primitives();
const { uniforms } = primitive.appearance.material;
@@ -1185,6 +1199,7 @@ for (const overlay of ['speed', 'temperature', 'pressure']) {
},
});
h.rendering.start();
+ renderShells(h.cesium, h.viewer.scene);
const [primitive] = h.primitives();
const textures = h.textures.length;
const baseAlpha = overlay === 'temperature' ? 1 : 0.85;
diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js
index 43b008259..1f9e63ad2 100644
--- a/src/render/cesium/draw.js
+++ b/src/render/cesium/draw.js
@@ -40,6 +40,7 @@ import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createModelSets } from './drawModels.js';
import { createMeshSets } from './drawMeshes.js';
import { createQuadSets } from './drawQuads.js';
+import { createCesiumFields } from './drawFields.js';
/** The contract's colour as Cesium's. */
export function toColor(color, alpha = 1) {
@@ -358,6 +359,8 @@ export function createCesiumDraw({
requestRender: requestFrame = null,
}) {
const sets = new Map();
+ // Fields share the sets' ids.
+ const fieldPart = createCesiumFields({ scene, report });
let setSeq = 0;
// Bumped whenever what height queries see through may have changed: a
// set made, rebuilt, restyled or gone, or items added or removed (icons
@@ -371,7 +374,8 @@ export function createCesiumDraw({
};
function makeSet(kind, spec, build) {
- if (sets.has(spec.id)) throw new Error(`a set with id ${spec.id} is live`);
+ if (sets.has(spec.id) || fieldPart.has(spec.id))
+ throw new Error(`a set with id ${spec.id} is live`);
const items = new Map();
const listeners = {
ready: listenerList(report),
@@ -3868,6 +3872,15 @@ export function createCesiumDraw({
makeSet('quads', { ...spec }, (record) => quadSets.build(record)),
meshes: (spec) =>
makeSet('meshes', { ...spec }, (record) => meshSets.build(record)),
+ ...(capabilities.has('fields')
+ ? {
+ field(spec) {
+ if (sets.has(spec?.id))
+ throw new Error(`a set with id ${spec.id} is live`);
+ return fieldPart.field(spec);
+ },
+ }
+ : {}),
clampState,
on(event, cb) {
if (event !== 'clampState') return () => {};
@@ -3950,6 +3963,8 @@ export function createCesiumDraw({
*/
dispose({ removeHosts = false } = {}) {
clampListeners.clear();
+ // Fields go with the port, and their frame listeners with them.
+ fieldPart.dispose();
// Late model loads find no host and destroy themselves.
for (const record of sets.values()) {
if (removeHosts && !scene.isDestroyed?.()) {
@@ -3989,7 +4004,11 @@ provideUnboundDraw((viewer) => {
typeof scene.requestRender !== 'function'
)
return null;
- const part = createCesiumDraw({ scene, report: uncaught });
+ const part = createCesiumDraw({
+ scene,
+ report: uncaught,
+ capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields']),
+ });
unboundParts.set(part.port, part);
const offs = [
scene.preRender?.addEventListener?.(() => part.beforeRender()),
diff --git a/src/render/cesium/drawFields.js b/src/render/cesium/drawFields.js
new file mode 100644
index 000000000..4d95244b4
--- /dev/null
+++ b/src/render/cesium/drawFields.js
@@ -0,0 +1,644 @@
+/**
+ * @module render/cesium/drawFields
+ * @description The Cesium draw port's `field` handles. It draws one kind:
+ * `rasterShell`, a raster on a rectangle raised above the ellipsoid, drawn
+ * flat in the opaque pass in the scene's primitive order (ascending height),
+ * alpha-blended, without depth writes and never picked. Other kinds are
+ * refused loudly.
+ *
+ * Choices the contract leaves open, taken conservatively:
+ * - An image is read when it is first named, as a Cesium material reads
+ * one: to show new pixels, name another canvas. URL, SVG and blob images
+ * are decoded before they are handed over, so the frame they replace
+ * stays until they can be drawn; atlas slots are refused.
+ * - An `update` of `image` alone, inside the same rectangle and height,
+ * swaps the texture on the drawn surface: Cesium keeps drawing the old
+ * one until the new one is uploaded. A new `rectangle` or `heightM` is
+ * built as a second surface, drawn invisibly until its geometry and
+ * images are ready, and then takes the first one's place in one frame.
+ * - A `detail` in a new rectangle shows the full image there until the
+ * detail image has drawn, never the old detail at the new place; one in
+ * the same rectangle swaps only the image, the old one drawing until the
+ * new is uploaded.
+ * - `liftM` scales the shell about the Earth's centre, so every shell
+ * rises alike and keeps its order.
+ */
+import * as Cesium from 'cesium';
+import { listenerList, uncaught } from './common.js';
+
+const MATERIAL_TYPE = 'DrawRasterShell';
+// Renders after an image swap: one queues the upload, one uploads and draws, one spare.
+const UPLOAD_FRAMES = 3;
+// An empty detail window: the full-extent image shows everywhere.
+const NO_WINDOW = Object.freeze({ west: 0, south: 0, east: -1, north: -1 });
+const shellHeights = new WeakMap();
+// Cesium binds a 1×1 white texture to an image uniform until its first upload:
+// 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.
+const MATERIAL_SOURCE = `czm_material czm_getMaterial(czm_materialInput materialInput)
+{
+ czm_material material = czm_getDefaultMaterial(materialInput);
+ vec2 st = materialInput.st;
+ vec4 coarse = texture(image, st);
+ vec2 dst = (st - window.xy) / max(window.zw - window.xy, vec2(1e-6));
+ float inside = float(all(greaterThanEqual(st, window.xy)) && all(lessThanEqual(st, window.zw)));
+ 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));
+ return material;
+}
+`;
+
+function registerMaterial(cesium) {
+ const cache = cesium.Material._materialCache;
+ if (cache.getMaterial(MATERIAL_TYPE)) return;
+ // A plain template: building the first material from a fabric would make that
+ // instance Cesium's shared template and keep its last image alive.
+ cache.addMaterial(MATERIAL_TYPE, {
+ fabric: {
+ type: MATERIAL_TYPE,
+ uniforms: {
+ image: cesium.Material.DefaultImageId,
+ detail: cesium.Material.DefaultImageId,
+ alpha: 1,
+ window: { type: 'vec4', x: 0, y: 0, z: -1, w: -1 },
+ },
+ // Diffuse and alpha share these samples, so one source, not components.
+ source: MATERIAL_SOURCE,
+ },
+ translucent: false,
+ });
+}
+
+const sameEdges = (a, b) =>
+ a.west === b.west &&
+ a.south === b.south &&
+ a.east === b.east &&
+ a.north === b.north;
+
+/** Keep raster shells first in the primitive collection, in ascending height:
+ * higher shells draw over lower ones and other opaque content draws over both. */
+export function orderShells(primitives, primitive, height) {
+ shellHeights.set(primitive, height);
+ if (typeof primitives.lowerToBottom !== 'function') return;
+ const shells = [];
+ for (let i = 0; i < primitives.length; i++) {
+ const item = primitives.get(i);
+ if (shellHeights.has(item)) shells.push(item);
+ }
+ const ordered = [...shells].sort(
+ (a, b) => shellHeights.get(a) - shellHeights.get(b),
+ );
+ if (ordered.every((item, i) => primitives.get(i) === item)) return;
+ for (const item of ordered.reverse()) primitives.lowerToBottom(item);
+}
+
+/** One raised rectangle drawing one full-extent image and, inside a window of
+ * it, an optional detail image. The owner calls destroy(). `onSettled` is
+ * told each time what it was last given has drawn. With `onWake` its owner
+ * runs its frames: it is told when the surface needs them, and calls
+ * `tick()` after each render while `awake()`; without, it listens itself. */
+export function createShellSurface({
+ scene,
+ cesium = Cesium,
+ rectangle,
+ height,
+ onSettled = () => {},
+ onWake = null,
+}) {
+ registerMaterial(cesium);
+ const primitives = scene.primitives;
+ // A scene destroyed under it asks for nothing.
+ const ask = () => {
+ if (!scene.isDestroyed?.()) scene.requestRender();
+ };
+ const material = new cesium.Material({
+ fabric: { type: MATERIAL_TYPE },
+ translucent: false,
+ });
+ // Flat shading keeps the product colours independent of the viewing angle.
+ const appearance = new cesium.EllipsoidSurfaceAppearance({
+ aboveGround: true,
+ flat: true,
+ translucent: false,
+ material,
+ });
+ // Cesium orders its translucent pass itself (weighted OIT or distance), which
+ // cannot honour stacked heights. Draw in the opaque pass in scene.primitives
+ // order, alpha-blended and without depth writes, so higher shells draw over
+ // lower ones and nothing is hidden or picked through a shell.
+ appearance.getRenderState = () => ({
+ depthTest: { enabled: true },
+ depthMask: false,
+ blending: cesium.BlendingState.ALPHA_BLEND,
+ });
+ const primitive = new cesium.Primitive({
+ geometryInstances: new cesium.GeometryInstance({
+ geometry: new cesium.RectangleGeometry({
+ rectangle,
+ height,
+ granularity: cesium.Math.toRadians(0.5),
+ vertexFormat: cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
+ }),
+ }),
+ appearance,
+ asynchronous: true,
+ allowPicking: false,
+ });
+ primitives.add(primitive);
+ orderShells(primitives, primitive, height);
+ let lift = 0;
+ let image = null;
+ let frames = 0;
+ // The detail image, its own upload count and a window waiting for it to draw.
+ let detail = null;
+ let detailFrames = 0;
+ let pendingWindow = null;
+ let offRender = null;
+ let awake = false;
+ let destroyed = false;
+
+ const fits = (size, value) =>
+ !size || (size.x === value.width && size.y === value.height);
+ const uploaded = () =>
+ image !== null && fits(material.uniforms.imageDimensions, image);
+ const detailDrawn = () =>
+ detail !== null &&
+ detailFrames === 0 &&
+ fits(material.uniforms.detailDimensions, detail);
+ const drawn = () =>
+ primitive.ready &&
+ uploaded() &&
+ frames === 0 &&
+ (detail === null || (detailDrawn() && pendingWindow === null));
+ function appliedWindow() {
+ const { x, y, z, w } = material.uniforms.window;
+ return z < x ? null : { west: x, south: y, east: z, north: w };
+ }
+ function setWindow(rect) {
+ const next = rect ?? NO_WINDOW;
+ const { x, y, z, w } = material.uniforms.window;
+ if (
+ x === next.west &&
+ y === next.south &&
+ z === next.east &&
+ w === next.north
+ )
+ return;
+ material.uniforms.window = new cesium.Cartesian4(
+ next.west,
+ next.south,
+ next.east,
+ next.north,
+ );
+ ask();
+ }
+ // The render governor may idle the scene; request frames only until the
+ // asynchronous geometry is ready and the latest images have been drawn.
+ function tick() {
+ // Cesium updates a material only while its primitive is shown, so hidden
+ // frames upload nothing and count for nothing.
+ if (primitive.ready && primitive.show) {
+ if (frames > 0) frames--;
+ if (detailFrames > 0) detailFrames--;
+ // A texture is never shown at another window's place.
+ if (pendingWindow && detailDrawn()) {
+ setWindow(pendingWindow);
+ pendingWindow = null;
+ }
+ }
+ if (primitive.show && !drawn()) {
+ ask();
+ return;
+ }
+ awake = false;
+ offRender?.();
+ offRender = null;
+ if (drawn()) onSettled();
+ }
+ function wake() {
+ if (destroyed || !primitive.show || image === null || drawn()) return;
+ awake = true;
+ if (onWake) onWake();
+ else offRender ??= scene.postRender.addEventListener(tick);
+ ask();
+ }
+
+ return {
+ setImage(next) {
+ if (destroyed || next === image) return;
+ image = next;
+ material.uniforms.image = next;
+ frames = UPLOAD_FRAMES;
+ wake();
+ },
+ setAlpha(value) {
+ if (destroyed || material.uniforms.alpha === value) return;
+ material.uniforms.alpha = value;
+ ask();
+ },
+ /** Metres the surface rises, by a uniform scale about the Earth's centre. */
+ setLift(value) {
+ const next = Number(value) || 0;
+ if (destroyed || next === lift) return;
+ lift = next;
+ primitive.modelMatrix = cesium.Matrix4.fromUniformScale(
+ 1 + lift / cesium.Ellipsoid.WGS84.maximumRadius,
+ );
+ ask();
+ },
+ /** 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
+ * this one is uploaded. A different window applies once its image has
+ * drawn; until then the full-extent image covers it. */
+ setDetail(next, rect) {
+ if (destroyed) return;
+ if (!next) {
+ if (detail === null) return;
+ detail = null;
+ detailFrames = 0;
+ pendingWindow = null;
+ material.uniforms.detail = cesium.Material.DefaultImageId;
+ setWindow(null);
+ ask();
+ return;
+ }
+ if (next !== detail) {
+ detail = next;
+ material.uniforms.detail = next;
+ detailFrames = UPLOAD_FRAMES;
+ }
+ const applied = appliedWindow();
+ if (applied && sameEdges(applied, rect)) {
+ pendingWindow = null;
+ } else {
+ setWindow(null);
+ pendingWindow = rect;
+ }
+ wake();
+ },
+ /** Returns whether visibility changed. */
+ setShow(value) {
+ const show = Boolean(value);
+ if (destroyed || primitive.show === show) return false;
+ primitive.show = show;
+ wake();
+ ask();
+ return true;
+ },
+ /** Whether what it was last given has drawn. */
+ isDrawn: () => !destroyed && drawn(),
+ /** Whether it needs frames until what it was given has drawn. */
+ awake: () => awake && !destroyed,
+ tick,
+ getDiagnostics() {
+ return {
+ height,
+ lift,
+ ready: Boolean(primitive.ready),
+ uploaded: uploaded(),
+ show: primitive.show,
+ alpha: material.uniforms.alpha,
+ rendering: awake,
+ // `uploaded` once the detail image has drawn; the window applies after.
+ detail: { uploaded: detailDrawn(), window: appliedWindow() },
+ };
+ },
+ destroy() {
+ if (destroyed) return;
+ destroyed = true;
+ awake = false;
+ offRender?.();
+ offRender = null;
+ if (!primitives.isDestroyed?.() && primitives.contains(primitive))
+ primitives.remove(primitive);
+ if (!primitive.isDestroyed()) primitive.destroy();
+ // Primitive.destroy leaves the material and its texture alive.
+ if (!material.isDestroyed()) material.destroy();
+ image = null;
+ detail = null;
+ pendingWindow = null;
+ ask();
+ },
+ };
+}
+
+/** A rectangle's place inside another, in the outer one's texture coordinates. */
+function placeIn(outer, inner) {
+ const x = outer.east - outer.west;
+ const y = outer.north - outer.south;
+ return {
+ west: (inner.west - outer.west) / x,
+ south: (inner.south - outer.south) / y,
+ east: (inner.east - outer.west) / x,
+ north: (inner.north - outer.south) / y,
+ };
+}
+
+/** Whether `ref` is drawn as it is, with no decode first. */
+const immediate = (ref) => Boolean(ref?.canvas);
+
+/** An image reference decoded into something a material uploads. */
+async function decode(ref) {
+ if (ref?.atlas) throw new TypeError('a raster shell takes no atlas images');
+ const url = ref?.blob
+ ? URL.createObjectURL(ref.blob)
+ : ref?.svg
+ ? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(ref.svg)}`
+ : String(ref);
+ try {
+ const image = new Image();
+ image.crossOrigin = 'anonymous';
+ image.src = url;
+ await image.decode();
+ return image;
+ } finally {
+ if (ref?.blob) URL.revokeObjectURL(url);
+ }
+}
+
+/**
+ * The fields part of a Cesium draw port.
+ * @param {{scene: object, report?: (error: unknown) => void,
+ * cesium?: object}} options `cesium` is for test doubles.
+ * @returns {{field: (spec: object) => object, has: (id: string) => boolean,
+ * dispose: () => void}}
+ */
+export function createCesiumFields({
+ scene,
+ report = uncaught,
+ cesium = Cesium,
+}) {
+ const fields = new Map();
+ const live = () => !scene.isDestroyed?.();
+ const requestRender = () => {
+ if (live()) scene.requestRender();
+ };
+ function rasterShell(spec) {
+ const id = spec.id;
+ // The frame a change was put on the surface, so 'drawn' waits for the
+ // render after it. Scenes without a frame state count this field's
+ // renders.
+ let renders = 0;
+ const frameNumber = () => scene.frameState?.frameNumber ?? renders;
+ let content = {
+ image: spec.image,
+ rectangle: { ...spec.rectangle },
+ heightM: Number(spec.heightM) || 0,
+ detail: spec.detail ? { ...spec.detail } : null,
+ };
+ let liftM = Number(spec.liftM) || 0;
+ let alpha = spec.alpha ?? 1;
+ let shown = true;
+ let disposed = false;
+ // The surface drawn, and one being built for a new rectangle or height.
+ let drawing = null;
+ let staged = null;
+ // Each content change, so a late decode of an older one is dropped.
+ let contentSeq = 0;
+ let placedSeq = -1;
+ // 'drawn' is owed for the latest change, put on the surface at `placedAt`.
+ let owed = true;
+ let placedAt = Infinity;
+ let offRender = null;
+ const drawnListeners = listenerList(report);
+
+ const keyOf = (c) =>
+ `${c.rectangle.west},${c.rectangle.south},${c.rectangle.east},${c.rectangle.north}|${c.heightM}`;
+
+ function make(c) {
+ const entry = { key: keyOf(c), rectangle: c.rectangle, surface: null };
+ const { west, south, east, north } = c.rectangle;
+ entry.surface = createShellSurface({
+ scene,
+ cesium,
+ rectangle: cesium.Rectangle.fromDegrees(west, south, east, north),
+ height: c.heightM,
+ onSettled: () => settled(entry),
+ onWake: () => watch(),
+ });
+ entry.surface.setLift(liftM);
+ // Staged surfaces draw, invisibly, even while the field is hidden, so
+ // the new content is ready when it shows.
+ return entry;
+ }
+ function drop(entry) {
+ entry?.surface.destroy();
+ return null;
+ }
+ // A staged surface takes the drawn one's place once it has drawn.
+ function settled(entry) {
+ if (disposed) return;
+ if (entry === staged) {
+ drop(drawing);
+ drawing = staged;
+ staged = null;
+ drawing.surface.setAlpha(alpha);
+ drawing.surface.setShow(shown);
+ // It has drawn already, invisibly, so it shows from the next frame on,
+ // the frame the one it replaces stops: told now, so nothing comes
+ // between the swap and 'drawn'.
+ if (owed && shown && placedSeq === contentSeq) {
+ owed = false;
+ drawnListeners.fire();
+ return;
+ }
+ placed();
+ return;
+ }
+ // What it last applied (a detail window, say) draws in the next frame.
+ if (entry === drawing) placed();
+ else watch();
+ }
+ function placed() {
+ placedAt = frameNumber();
+ watch();
+ }
+ function put(entry, c, image, detailImage) {
+ entry.surface.setImage(image);
+ if (c.detail && detailImage)
+ entry.surface.setDetail(
+ detailImage,
+ placeIn(entry.rectangle, c.detail.rectangle),
+ );
+ else entry.surface.setDetail(null);
+ }
+ /** Draw `c` with its images decoded. */
+ function place(c, image, detailImage) {
+ const key = keyOf(c);
+ if (drawing?.key === key) {
+ staged = drop(staged);
+ put(drawing, c, image, detailImage);
+ placed();
+ return;
+ }
+ if (staged?.key !== key) {
+ staged = drop(staged);
+ staged = make(c);
+ // Invisible until it takes the drawn one's place.
+ staged.surface.setAlpha(0);
+ }
+ put(staged, c, image, detailImage);
+ // Its own settling promotes it.
+ watch();
+ }
+ function load(c) {
+ const seq = (contentSeq += 1);
+ const refs = [c.image, c.detail?.image];
+ if (refs.every((ref) => ref == null || immediate(ref))) {
+ placedSeq = seq;
+ place(c, c.image.canvas, c.detail?.image.canvas ?? null);
+ return;
+ }
+ // A stage of older content must not take the drawn one's place while
+ // this decodes.
+ staged = drop(staged);
+ Promise.all(
+ refs.map((ref) =>
+ ref == null ? null : immediate(ref) ? ref.canvas : decode(ref),
+ ),
+ ).then(
+ ([image, detailImage]) => {
+ if (disposed || seq !== contentSeq || !live()) return;
+ placedSeq = seq;
+ place(c, image, detailImage);
+ },
+ (error) => {
+ // What it drew stays.
+ if (disposed || seq !== contentSeq) return;
+ report(error);
+ if (!busy()) unwatch();
+ },
+ );
+ }
+
+ // One listener runs the surfaces' frames and tells 'drawn'.
+ const busy = () =>
+ Boolean(drawing?.surface.awake() || staged?.surface.awake());
+ function notify() {
+ if (!owed || !shown || staged || placedSeq !== contentSeq || !drawing)
+ return;
+ if (!drawing.surface.isDrawn()) return;
+ // A frame number that has moved on (it wraps) has drawn the change.
+ if (frameNumber() === placedAt) {
+ requestRender();
+ return;
+ }
+ owed = false;
+ drawnListeners.fire();
+ }
+ function tick() {
+ renders += 1;
+ for (const entry of [drawing, staged])
+ if (entry?.surface.awake()) entry.surface.tick();
+ if (!disposed) notify();
+ if (disposed || (!busy() && !(owed && shown))) unwatch();
+ }
+ function watch() {
+ if (disposed || (!(owed && shown) && !busy())) return;
+ offRender ??= scene.postRender.addEventListener(tick);
+ requestRender();
+ }
+ function unwatch() {
+ offRender?.();
+ offRender = null;
+ }
+
+ const handle = {
+ id,
+ get show() {
+ return shown;
+ },
+ set show(value) {
+ const next = Boolean(value);
+ if (disposed || next === shown) return;
+ shown = next;
+ drawing?.surface.setShow(shown);
+ // A stage in progress keeps building, so it is ready when shown.
+ if (shown) watch();
+ else if (!busy()) unwatch();
+ requestRender();
+ },
+ update(patch = {}) {
+ if (disposed) return;
+ if (patch.kind !== undefined && patch.kind !== 'rasterShell')
+ throw new TypeError('a field keeps its kind');
+ const next = { ...content };
+ let reload = false;
+ if ('image' in patch && patch.image !== content.image) {
+ next.image = patch.image;
+ reload = true;
+ }
+ if (patch.rectangle && !sameEdges(patch.rectangle, content.rectangle)) {
+ next.rectangle = { ...patch.rectangle };
+ reload = true;
+ }
+ if ('heightM' in patch && Number(patch.heightM) !== content.heightM) {
+ next.heightM = Number(patch.heightM) || 0;
+ reload = true;
+ }
+ if ('detail' in patch) {
+ const was = content.detail;
+ const now = patch.detail ? { ...patch.detail } : null;
+ if (
+ (was === null) !== (now === null) ||
+ (now &&
+ (now.image !== was.image ||
+ !sameEdges(now.rectangle, was.rectangle)))
+ ) {
+ next.detail = now;
+ reload = true;
+ }
+ }
+ if ('liftM' in patch) {
+ liftM = Number(patch.liftM) || 0;
+ drawing?.surface.setLift(liftM);
+ staged?.surface.setLift(liftM);
+ }
+ if ('alpha' in patch) {
+ alpha = patch.alpha ?? 1;
+ drawing?.surface.setAlpha(alpha);
+ }
+ owed = true;
+ content = next;
+ if (reload) load(content);
+ else placed();
+ requestRender();
+ },
+ on(event, cb) {
+ if (event !== 'drawn') return () => {};
+ return drawnListeners.on(cb);
+ },
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ unwatch();
+ drawnListeners.clear();
+ drawing = drop(drawing);
+ staged = drop(staged);
+ if (fields.get(id) === handle) fields.delete(id);
+ },
+ };
+ fields.set(id, handle);
+ load(content);
+ return handle;
+ }
+
+ return {
+ field(spec) {
+ if (fields.has(spec?.id))
+ throw new Error(`a field with id ${spec.id} is live`);
+ if (spec?.kind === 'rasterShell') return rasterShell(spec);
+ throw new TypeError(
+ `the Cesium renderer draws no ${spec?.kind} fields yet`,
+ );
+ },
+ has: (id) => fields.has(id),
+ dispose() {
+ for (const handle of [...fields.values()]) handle.dispose();
+ },
+ };
+}
diff --git a/src/render/cesium/drawFields.test.mjs b/src/render/cesium/drawFields.test.mjs
new file mode 100644
index 000000000..ededeaacd
--- /dev/null
+++ b/src/render/cesium/drawFields.test.mjs
@@ -0,0 +1,645 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as Cesium from 'cesium';
+import {
+ createCesiumFields,
+ createShellSurface,
+ orderShells,
+} from './drawFields.js';
+import {
+ createShellCesium,
+ createShellScene,
+ renderShells,
+} from '../../layers/weather/shellFixture.mjs';
+
+// The detail window uniform; NONE is the empty window.
+const NONE = { x: 0, y: 0, z: -1, w: -1 };
+const windowOf = (primitive) => {
+ const { x, y, z, w } = primitive.appearance.material.uniforms.window;
+ return { x, y, z, w };
+};
+
+test('surface builds a flat raised rectangle drawn in primitive order without depth writes', () => {
+ const cesium = createShellCesium();
+ const scene = createShellScene();
+ const rectangle = Cesium.Rectangle.fromDegrees(-130, 20, -60, 55);
+ const surface = createShellSurface({
+ scene,
+ cesium,
+ rectangle,
+ height: 6_200,
+ });
+ const template = cesium.templates.get('DrawRasterShell');
+ assert.ok(!(template instanceof cesium.Material), 'plain template');
+ assert.deepEqual(template.fabric.uniforms, {
+ image: Cesium.Material.DefaultImageId,
+ detail: Cesium.Material.DefaultImageId,
+ alpha: 1,
+ 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\)\);/,
+ 'nothing draws before the full-extent image',
+ );
+ assert.match(
+ source,
+ /float useDetail = inside \* step\(1\.5, float\(detailDimensions\.x\)\);/,
+ 'the detail image is sampled only once it has arrived',
+ );
+ assert.match(
+ source,
+ /all\(greaterThanEqual\(st, window\.xy\)\) && all\(lessThanEqual\(st, window\.zw\)\)/,
+ );
+ assert.match(
+ source,
+ /mix\(coarse, texture\(detail, clamp\(dst, 0\.0, 1\.0\)\), useDetail\)/,
+ );
+ assert.match(source, /material\.diffuse = czm_gammaCorrect\(c\.rgb\);/);
+ const [primitive] = scene.primitives.items;
+ const appearance = primitive.appearance;
+ assert.equal(appearance.material.options.translucent, false);
+ assert.deepEqual(
+ { ...appearance.options, material: undefined },
+ {
+ aboveGround: true,
+ flat: true,
+ translucent: false,
+ material: undefined,
+ },
+ );
+ assert.deepEqual(appearance.getRenderState(), {
+ depthTest: { enabled: true },
+ depthMask: false,
+ blending: Cesium.BlendingState.ALPHA_BLEND,
+ });
+ const geometry = primitive.options.geometryInstances.geometry.options;
+ assert.equal(geometry.rectangle, rectangle);
+ assert.equal(geometry.height, 6_200);
+ assert.equal(geometry.granularity, Cesium.Math.toRadians(0.5));
+ assert.equal(
+ geometry.vertexFormat,
+ Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
+ );
+ assert.equal(primitive.options.asynchronous, true);
+ assert.equal(primitive.options.allowPicking, false);
+ const lower = createShellSurface({
+ scene,
+ cesium,
+ rectangle,
+ height: 5_000,
+ });
+ assert.equal(cesium.templates.size, 1, 'the template registers once');
+ assert.deepEqual(
+ scene.primitives.items.map(
+ (item) => item.options.geometryInstances.geometry.options.height,
+ ),
+ [5_000, 6_200],
+ );
+ lower.destroy();
+ surface.destroy();
+});
+
+test('a surface applies a new detail window only once its image has drawn; the same window swaps only the image', () => {
+ const cesium = createShellCesium();
+ const scene = createShellScene();
+ const surface = createShellSurface({
+ scene,
+ cesium,
+ rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
+ height: 6_200,
+ });
+ const [primitive] = scene.primitives.items;
+ const { uniforms } = primitive.appearance.material;
+ const render = (count) => renderShells(cesium, scene, count);
+ const image = () => ({ width: 4096, height: 2048 });
+ surface.setImage(image());
+ render();
+ assert.deepEqual(surface.getDiagnostics().detail, {
+ uploaded: false,
+ window: null,
+ });
+ const a = { west: 0.25, south: 0.5, east: 0.5, north: 0.75 };
+ const first = image();
+ surface.setDetail(first, a);
+ assert.equal(uniforms.detail, first);
+ assert.deepEqual(windowOf(primitive), NONE, 'the full-extent image covers');
+ assert.equal(scene.postRender.size, 1, 'renders until the detail has drawn');
+ render(2);
+ assert.deepEqual(windowOf(primitive), NONE);
+ render(1);
+ assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
+ assert.ok(uniforms.window instanceof Cesium.Cartesian4);
+ assert.deepEqual(surface.getDiagnostics().detail, {
+ uploaded: true,
+ window: a,
+ });
+ assert.equal(scene.postRender.size, 0);
+
+ // A time change in the same window: Cesium keeps drawing the previous
+ // texture until the new one is uploaded, so the window stays.
+ const applied = uniforms.window;
+ const second = image();
+ surface.setDetail(second, { ...a });
+ assert.equal(uniforms.detail, second);
+ assert.equal(uniforms.window, applied, 'only the image is written');
+ assert.equal(surface.getDiagnostics().detail.uploaded, false);
+ render();
+ assert.equal(surface.getDiagnostics().detail.uploaded, true);
+ assert.equal(uniforms.window, applied);
+ const renders = scene.renders;
+ surface.setDetail(second, { ...a });
+ assert.equal(scene.renders, renders, 'an unchanged detail costs nothing');
+ assert.equal(scene.postRender.size, 0);
+
+ // A different window empties at once and applies once its image has drawn.
+ const b = { west: 0.5, south: 0.25, east: 0.75, north: 0.5 };
+ surface.setDetail(image(), b);
+ assert.deepEqual(windowOf(primitive), NONE);
+ render(2);
+ assert.deepEqual(windowOf(primitive), NONE);
+ render(1);
+ assert.deepEqual(windowOf(primitive), { x: 0.5, y: 0.25, z: 0.75, w: 0.5 });
+
+ surface.setDetail(null);
+ assert.equal(uniforms.detail, Cesium.Material.DefaultImageId);
+ assert.deepEqual(windowOf(primitive), NONE);
+ assert.deepEqual(surface.getDiagnostics().detail, {
+ uploaded: false,
+ window: null,
+ });
+ render();
+ assert.deepEqual(
+ { ...uniforms.detailDimensions },
+ { type: 'ivec3', x: 1, y: 1 },
+ );
+ // Counted renders alone are not enough: the bound texture must be this image.
+ surface.setDetail(image(), a);
+ for (let i = 0; i < 4; i++) scene.postRender.emit();
+ assert.deepEqual(windowOf(primitive), NONE, 'still the 1×1 default');
+ render(1);
+ assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
+ surface.destroy();
+ surface.setDetail(image(), b);
+ assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
+ assert.equal(scene.postRender.size, 0);
+});
+
+test("a surface rises by a uniform scale about the Earth's centre", () => {
+ const scene = {
+ primitives: new Cesium.PrimitiveCollection(),
+ postRender: new Cesium.Event(),
+ requestRender() {},
+ };
+ const surface = createShellSurface({
+ scene,
+ cesium: Cesium,
+ rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
+ height: 5_800,
+ });
+ const primitive = scene.primitives.get(0);
+ const identity = primitive.modelMatrix;
+ surface.setLift(0);
+ assert.equal(primitive.modelMatrix, identity, 'no lift, no new matrix');
+ surface.setLift(32_000);
+ const radius = Cesium.Ellipsoid.WGS84.maximumRadius;
+ assert.ok(
+ Math.abs(primitive.modelMatrix[0] * radius - (radius + 32_000)) < 1e-3,
+ );
+ const lifted = primitive.modelMatrix;
+ surface.setLift(32_000);
+ assert.equal(primitive.modelMatrix, lifted, 'the same lift keeps the matrix');
+ surface.destroy();
+});
+
+test('real Cesium builds the two-texture material, the opaque-pass appearance and the rectangle primitive', () => {
+ const scene = {
+ primitives: new Cesium.PrimitiveCollection(),
+ postRender: new Cesium.Event(),
+ requestRender() {},
+ };
+ const surface = createShellSurface({
+ scene,
+ cesium: Cesium,
+ rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
+ height: 6_600,
+ });
+ const cached = Cesium.Material._materialCache.getMaterial('DrawRasterShell');
+ assert.ok(cached && !(cached instanceof Cesium.Material));
+ const primitive = scene.primitives.get(0);
+ const material = primitive.appearance.material;
+ assert.ok(primitive instanceof Cesium.Primitive);
+ assert.equal(material.type, 'DrawRasterShell');
+ assert.equal(material.isTranslucent(), false);
+ assert.equal(primitive.appearance.isTranslucent(), false, 'opaque pass');
+ assert.equal(primitive.appearance.getRenderState().depthMask, false);
+ assert.equal(
+ Cesium.Appearance.prototype.getRenderState.call(primitive.appearance)
+ .depthMask,
+ true,
+ 'the default opaque render state would write depth',
+ );
+ assert.deepEqual(
+ [material.uniforms.imageDimensions.x, material.uniforms.detailDimensions.x],
+ [1, 1],
+ 'Cesium tracks both bound texture sizes',
+ );
+ const shader = material.shaderSource;
+ for (const declaration of [
+ /uniform sampler2D image_\d+;/,
+ /uniform sampler2D detail_\d+;/,
+ /uniform float alpha_\d+;/,
+ /uniform vec4 window_\d+;/,
+ /uniform ivec3 imageDimensions_\d+;/,
+ /uniform ivec3 detailDimensions_\d+;/,
+ ])
+ assert.match(shader, declaration);
+ assert.match(shader, /texture\(image_\d+, st\)/);
+ assert.match(shader, /texture\(detail_\d+, clamp\(dst, 0\.0, 1\.0\)\)/);
+ assert.match(shader, /lessThanEqual\(st, window_\d+\.zw\)/);
+ 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\)\);/,
+ 'the uniform is renamed, the material field is not',
+ );
+ 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 });
+ assert.equal(material.uniforms.detail, detail);
+ assert.deepEqual(
+ [material.uniforms.window.z, material.uniforms.window.w],
+ [-1, -1],
+ 'no window before the image has drawn',
+ );
+ surface.setDetail(null);
+ assert.equal(material.uniforms.detail, Cesium.Material.DefaultImageId);
+ surface.setAlpha(0.4);
+ assert.equal(material.uniforms.alpha, 0.4);
+ surface.destroy();
+ assert.equal(scene.primitives.length, 0);
+ assert.equal(primitive.isDestroyed(), true);
+ assert.equal(material.isDestroyed(), true);
+ assert.equal(scene.postRender.numberOfListeners, 0);
+});
+
+test('shells draw first, in height order, regardless of add order', () => {
+ const scene = createShellScene();
+ const other = { name: 'other' };
+ scene.primitives.add(other);
+ const add = (name, height) => {
+ const primitive = { name };
+ scene.primitives.add(primitive);
+ orderShells(scene.primitives, primitive, height);
+ return primitive;
+ };
+ add('lightning', 6_600);
+ add('radar', 6_200);
+ add('wind', 5_000);
+ const later = { name: 'later' };
+ scene.primitives.add(later);
+ add('regional', 5_800);
+ assert.deepEqual(
+ scene.primitives.items.map(({ name }) => name),
+ ['wind', 'regional', 'radar', 'lightning', 'other', 'later'],
+ );
+ const primitives = new Cesium.PrimitiveCollection({
+ destroyPrimitives: false,
+ });
+ const real = (name) => ({ name, update() {}, isDestroyed: () => false });
+ const tileset = primitives.add(real('tileset'));
+ const lightning = primitives.add(real('lightning'));
+ orderShells(primitives, lightning, 6_600);
+ const radar = primitives.add(real('radar'));
+ orderShells(primitives, radar, 6_200);
+ assert.deepEqual(
+ [0, 1, 2].map((i) => primitives.get(i).name),
+ ['radar', 'lightning', 'tileset'],
+ 'real Cesium collection order',
+ );
+ assert.equal(tileset.name, 'tileset');
+});
+
+test('hidden frames do not count towards a pending detail window', () => {
+ const cesium = createShellCesium();
+ const scene = createShellScene();
+ const surface = createShellSurface({
+ scene,
+ cesium,
+ rectangle: Cesium.Rectangle.fromDegrees(-130, 20, -60, 55),
+ height: 6_200,
+ });
+ const [primitive] = scene.primitives.items;
+ const render = (count) => renderShells(cesium, scene, count);
+ const image = () => ({ width: 4096, height: 2048 });
+ surface.setImage(image());
+ const a = { west: 0.25, south: 0.5, east: 0.5, north: 0.75 };
+ surface.setDetail(image(), a);
+ render();
+ assert.deepEqual(windowOf(primitive), { x: 0.25, y: 0.5, z: 0.5, w: 0.75 });
+ // A different window with a same-sized image: the dimensions alone cannot
+ // tell the textures apart, so only shown frames may count.
+ const b = { west: 0.5, south: 0.25, east: 0.75, north: 0.5 };
+ surface.setDetail(image(), b);
+ assert.deepEqual(windowOf(primitive), NONE);
+ for (let i = 0; i < 3; i++) {
+ surface.setShow(false);
+ scene.postRender.emit();
+ surface.setShow(true);
+ }
+ assert.deepEqual(windowOf(primitive), NONE, 'hidden frames counted nothing');
+ render(2);
+ assert.deepEqual(windowOf(primitive), NONE);
+ render(1);
+ assert.deepEqual(windowOf(primitive), { x: 0.5, y: 0.25, z: 0.75, w: 0.5 });
+});
+
+function fieldHarness() {
+ const cesium = createShellCesium();
+ const scene = createShellScene();
+ const fields = createCesiumFields({ scene, cesium });
+ const image = () => ({ canvas: { width: 64, height: 32 }, key: 'k' });
+ const render = (count = 4) => renderShells(cesium, scene, count);
+ const live = () => scene.primitives.items.filter((p) => !p.destroyed);
+ return { cesium, scene, fields, image, render, live };
+}
+const RECT = { west: -100, south: 20, east: -60, north: 40 };
+
+test("a raster shell tells 'drawn' once its content is drawn, once per change", () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ alpha: 0.5,
+ });
+ let drawn = 0;
+ field.on('drawn', () => (drawn += 1));
+ const [primitive] = h.live();
+ const { uniforms } = primitive.appearance.material;
+ assert.equal(uniforms.alpha, 0, 'invisible until drawable');
+ h.render();
+ assert.equal(drawn, 1);
+ assert.equal(uniforms.alpha, 0.5);
+ assert.equal(h.scene.postRender.size, 0, 'no frames once drawn');
+ field.update({ alpha: 0.3, liftM: 1_000 });
+ assert.equal(uniforms.alpha, 0.3);
+ assert.notEqual(primitive.modelMatrix, undefined, 'lifted');
+ assert.deepEqual(h.live(), [primitive], 'alpha and lift never rebuild');
+ h.render();
+ assert.equal(drawn, 2);
+ field.show = false;
+ field.update({ alpha: 0.4 });
+ h.render();
+ assert.equal(drawn, 2, 'never while hidden');
+ field.show = true;
+ h.render();
+ assert.equal(drawn, 3, 'told once shown');
+ h.render();
+ assert.equal(drawn, 3);
+ field.dispose();
+ assert.equal(h.live().length, 0);
+ assert.equal(h.scene.postRender.size, 0);
+});
+
+test('a raster shell keeps drawing its rectangle until a new one is drawn whole', () => {
+ const h = fieldHarness();
+ const first = h.image();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: first,
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ let drawn = 0;
+ field.on('drawn', () => (drawn += 1));
+ h.render();
+ const [old] = h.live();
+ const second = h.image();
+ field.update({
+ image: second,
+ rectangle: { west: -120, south: 10, east: -50, north: 50 },
+ });
+ const [, staged] = h.live();
+ assert.equal(old.appearance.material.uniforms.alpha, 1, 'the old one draws');
+ assert.equal(staged.appearance.material.uniforms.alpha, 0);
+ assert.equal(staged.appearance.material.uniforms.image, second.canvas);
+ h.render();
+ assert.equal(old.destroyed, true, 'swapped in one frame');
+ assert.deepEqual(h.live(), [staged]);
+ assert.equal(staged.appearance.material.uniforms.alpha, 1);
+ assert.equal(drawn, 2);
+ // Back to the drawn rectangle before a staged one is drawn: it goes.
+ field.update({ rectangle: RECT });
+ assert.equal(h.live().length, 2);
+ field.update({ rectangle: { west: -120, south: 10, east: -50, north: 50 } });
+ assert.deepEqual(h.live(), [staged]);
+ field.dispose();
+});
+
+test('a raster shell draws its detail in its own rectangle, in texture coordinates', () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ h.render();
+ const [primitive] = h.live();
+ const detail = h.image();
+ field.update({
+ detail: {
+ image: detail,
+ rectangle: { west: -90, south: 25, east: -80, north: 30 },
+ },
+ });
+ assert.deepEqual(windowOf(primitive), NONE, 'the full image covers it');
+ h.render();
+ assert.equal(primitive.appearance.material.uniforms.detail, detail.canvas);
+ assert.deepEqual(windowOf(primitive), {
+ x: 0.25,
+ y: 0.25,
+ z: 0.5,
+ w: 0.5,
+ });
+ field.update({ detail: null });
+ assert.deepEqual(windowOf(primitive), NONE);
+ field.dispose();
+});
+
+test('a raster shell hidden while a new rectangle stages still swaps it in', () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ let drawn = 0;
+ field.on('drawn', () => (drawn += 1));
+ h.render();
+ const [old] = h.live();
+ field.show = false;
+ field.update({
+ image: h.image(),
+ rectangle: { west: -120, south: 10, east: -50, north: 50 },
+ });
+ h.render();
+ const [staged] = h.live();
+ assert.equal(old.destroyed, true, 'drawn invisibly and swapped in');
+ assert.notEqual(staged, old);
+ assert.equal(staged.show, false, 'and kept hidden');
+ assert.equal(drawn, 1, 'never told while hidden');
+ field.show = true;
+ h.render();
+ assert.equal(staged.show, true);
+ assert.equal(drawn, 2);
+ field.dispose();
+});
+
+test("a raster shell tells 'drawn' for a detail only once its window is placed", () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ h.render();
+ const [primitive] = h.live();
+ const windows = [];
+ field.on('drawn', () => windows.push(windowOf(primitive)));
+ field.update({
+ detail: {
+ image: h.image(),
+ rectangle: { west: -90, south: 25, east: -80, north: 30 },
+ },
+ });
+ h.render();
+ assert.deepEqual(windows, [{ x: 0.25, y: 0.25, z: 0.5, w: 0.5 }]);
+ field.dispose();
+});
+
+test("a raster shell tells 'drawn' in the frame its new rectangle replaces the old", () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ h.render();
+ const [old] = h.live();
+ let drawnAt = null;
+ let render = 0;
+ field.on('drawn', () => (drawnAt = render));
+ field.update({ rectangle: { west: -120, south: 10, east: -50, north: 50 } });
+ let swappedAt = null;
+ for (render = 1; render <= 6; render++) {
+ h.render(1);
+ if (old.destroyed && swappedAt === null) swappedAt = render;
+ }
+ assert.ok(swappedAt > 1, 'staged while uploading');
+ assert.equal(drawnAt, swappedAt, 'nothing comes between the swap and drawn');
+ field.dispose();
+});
+
+test('a raster shell hidden after a new rectangle stages still builds and swaps it', () => {
+ const h = fieldHarness();
+ const field = h.fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ let drawn = 0;
+ field.on('drawn', () => (drawn += 1));
+ h.render();
+ const [old] = h.live();
+ field.update({ rectangle: { west: -120, south: 10, east: -50, north: 50 } });
+ field.show = false;
+ h.render();
+ const [staged] = h.live();
+ assert.equal(old.destroyed, true);
+ assert.notEqual(staged, old);
+ assert.equal(staged.show, false);
+ assert.equal(h.scene.postRender.size, 0, 'no frames once built');
+ assert.equal(drawn, 1);
+ field.show = true;
+ h.render();
+ assert.equal(drawn, 2);
+ field.dispose();
+});
+
+test('a raster shell never swaps in a stage superseded by content still decoding', async (t) => {
+ const pending = [];
+ const Image = globalThis.Image;
+ globalThis.Image = class {
+ decode() {
+ return new Promise((resolve, reject) =>
+ pending.push({ resolve, reject }),
+ );
+ }
+ };
+ t.after(() => (globalThis.Image = Image));
+ const reported = [];
+ const cesium = createShellCesium();
+ const scene = createShellScene();
+ const fields = createCesiumFields({
+ scene,
+ cesium,
+ report: (error) => reported.push(error),
+ });
+ const live = () => scene.primitives.items.filter((p) => !p.destroyed);
+ const field = fields.field({
+ kind: 'rasterShell',
+ id: 'shell',
+ image: { canvas: { width: 64, height: 32 } },
+ rectangle: RECT,
+ heightM: 6_000,
+ });
+ renderShells(cesium, scene);
+ const [old] = live();
+ field.update({
+ image: { canvas: { width: 64, height: 32 } },
+ rectangle: { west: -120, south: 10, east: -50, north: 50 },
+ });
+ assert.equal(live().length, 2);
+ field.update({ image: 'https://example.test/next.png' });
+ assert.deepEqual(live(), [old], 'the superseded stage goes');
+ pending[0].reject(new Error('no image'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ renderShells(cesium, scene);
+ assert.deepEqual(live(), [old], 'what it drew stays');
+ assert.equal(reported.length, 1);
+ field.dispose();
+});
+
+test('the Cesium fields refuse kinds they cannot draw and live ids', () => {
+ const h = fieldHarness();
+ assert.throws(
+ () => h.fields.field({ kind: 'scalarRaster', id: 'x' }),
+ /no scalarRaster fields/,
+ );
+ const spec = {
+ kind: 'rasterShell',
+ id: 'shell',
+ image: h.image(),
+ rectangle: RECT,
+ heightM: 1,
+ };
+ const field = h.fields.field(spec);
+ assert.throws(() => h.fields.field(spec), /is live/);
+ field.dispose();
+ h.fields.field(spec).dispose();
+});
diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js
index dedc020e7..53ded5cff 100644
--- a/src/render/cesium/harness.js
+++ b/src/render/cesium/harness.js
@@ -40,6 +40,7 @@ export const CESIUM_CHECKS = new Set([
'draw.columns.shown',
'draw.drawOrder',
'draw.drillPick',
+ 'draw.field.rasterShell',
'draw.icons.distance',
'draw.icons.update',
'draw.lines.depthFailDash',
diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js
index 2a115b3f7..1747fb371 100644
--- a/src/render/cesium/ports.js
+++ b/src/render/cesium/ports.js
@@ -66,6 +66,8 @@ export function cesiumCapabilities(scene, only) {
'models',
'quads',
'meshes',
+ // Raster shells; other field kinds are refused.
+ 'fields',
'followFrame',
'cameraChangeThreshold',
...GPU_ICON_CAPABILITIES,
diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs
index 722b96208..6a8b3d995 100644
--- a/src/render/cesium/ports.test.mjs
+++ b/src/render/cesium/ports.test.mjs
@@ -29,7 +29,7 @@ test('capabilities follow what the scene supports', () => {
'surfaceShading',
];
const globe = { show: true };
- const draw = ['models', 'quads', 'meshes'];
+ const draw = ['models', 'quads', 'meshes', 'fields'];
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
// A scene with a globe reads its visibility back.
assert.deepEqual(cesiumCapabilities({ globe }), [
diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json
index 6198d24d7..5b7efdead 100644
--- a/src/render/cesiumAllowList.json
+++ b/src/render/cesiumAllowList.json
@@ -5,7 +5,6 @@
"src/app/scene.js",
"src/app/viewer.js",
"src/data/geoImportPins.js",
- "src/layers/weather/shellRendering.js",
"src/layers/wind/gpuRendering.js",
"src/layers/wind/relief.js",
"src/layers/wind/rendering.js",