mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Merge branch 'sameh/renderer-fields' into sameh/renderer-seam
This commit is contained in:
commit
561cd8f1cf
28 files changed
+3460
-1773
No files matched your search
@@ -2,6 +2,14 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog`
|
||||
no longer reach Cesium: the weather shells and the wind layer's colour
|
||||
shell and flow draw through the renderer's `draw.field` (`rasterShell` and
|
||||
`windStreamlines`, which the Cesium renderer now draws), and the wind
|
||||
relief is the globe port's `hillshade` surface shading. The flow animates
|
||||
as before, and still falls back to the canvas where the renderer refuses
|
||||
it. A viewer with no renderer bound needs
|
||||
`gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis).
|
||||
- `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its
|
||||
pointer events from the renderer's input port and its picks from the query
|
||||
port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and
|
||||
|
||||
+63
-54
@@ -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 = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: ${escape(detail)}</figcaption>`;
|
||||
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 = `<img src="${objectUrl(capture)}"><figcaption>${name}: recorded</figcaption>`;
|
||||
return;
|
||||
}
|
||||
const refBlob = await reference(name);
|
||||
if (!refBlob) {
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: 'fail',
|
||||
detail: 'no reference',
|
||||
});
|
||||
figure.innerHTML = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: no reference</figcaption>`;
|
||||
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 = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: ${escape(detail)}</figcaption>`;
|
||||
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 = `<img src="${objectUrl(capture)}"><figcaption>${name}: recorded</figcaption>`;
|
||||
return;
|
||||
}
|
||||
const refBlob = await reference(name);
|
||||
if (!refBlob) {
|
||||
results.push({
|
||||
scene: scene.id,
|
||||
view: view.name,
|
||||
status: 'fail',
|
||||
detail: 'no reference',
|
||||
});
|
||||
figure.innerHTML = `<img src="${objectUrl(capture)}"><figcaption class="fail">${name}: no reference</figcaption>`;
|
||||
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 = `<div class="row"><img src="${objectUrl(capture)}" title="${which}"><img src="${objectUrl(refBlob)}" title="reference"><img src="${diffUrl}" title="difference"></div>
|
||||
<figcaption class="${outcome.match ? 'pass' : 'fail'}">${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}</figcaption>`;
|
||||
});
|
||||
} 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 = `<div class="row"><img src="${objectUrl(capture)}" title="${which}"><img src="${objectUrl(refBlob)}" title="reference"><img src="${diffUrl}" title="difference"></div>
|
||||
<figcaption class="${outcome.match ? 'pass' : 'fail'}">${name}: ${outcome.solidPixels} solid, ${outcome.mismatchedPixels} unexcused, ${(outcome.diffFraction * 100).toFixed(3)}% differ ${outcome.reason ?? ''}</figcaption>`;
|
||||
});
|
||||
}
|
||||
}
|
||||
if (record) {
|
||||
// A partial recording keeps the other scenes' entries.
|
||||
|
||||
@@ -363,9 +363,10 @@ resources and subscriptions. The globe relief helper is enabled with Wind and
|
||||
released when Wind is disabled. It uses terrain vertex normals
|
||||
for view-directed shading, falling back to global globe-curvature shading when
|
||||
normals are unavailable; the fallback does not show local hillshade. Neither mode
|
||||
adds elevation data or represents sunlight. Relief declines to replace an
|
||||
existing globe material, restores the prior empty material only while still
|
||||
owning it, and leaves later owners intact.
|
||||
adds elevation data or represents sunlight. Relief is the globe port's
|
||||
`hillshade` surface shading: the renderer never replaces a globe material
|
||||
someone else holds (it waits until that one is gone), gives the globe back
|
||||
when Wind is disabled, and leaves later owners intact.
|
||||
Source acquisition retains deadlines, body budgets, disconnect cancellation,
|
||||
per-model/field singleflight caching and one-minute failure backoff. Application
|
||||
catalog construction owns each instance.
|
||||
|
||||
@@ -65,8 +65,12 @@ optional, so a renderer written before it still conforms:
|
||||
one, and says how shells stack, blend and update. `FieldHandle.on('drawn')`
|
||||
says once per spec or `update` that it is drawn, never while hidden. These
|
||||
change `fields` itself rather than add to it, so the renderer follows
|
||||
`fields` before must follow them; only the stub lists it, and the Cesium
|
||||
adapter has no `fields` yet.
|
||||
`fields` before must follow them. The Cesium adapter lists `fields` and
|
||||
draws `rasterShell` and `windStreamlines`; it refuses `scalarRaster`. It
|
||||
draws streamlines only over the whole globe: it reads the grid's samples
|
||||
as points, the first column at `rectangle.west` and the first row at
|
||||
`rectangle.north`, rows running south, and traces paths that wrap east
|
||||
and west, so it refuses a grid short of 360° of longitude.
|
||||
- `ModulationSector` gains `radius` and `floor` and says what it modulates:
|
||||
icons, points and models dimmed toward `floor` outside the band, the map,
|
||||
lines and shapes as they are, picks unchanged. Its pass is named
|
||||
|
||||
@@ -871,6 +871,10 @@
|
||||
"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/render/cesium/drawStreamlines.js",
|
||||
"src/render/cesium/drawStreamlines.test.mjs",
|
||||
"src/layers/weather/infraredAlpha.js",
|
||||
"src/layers/weather/infraredAlpha.test.mjs",
|
||||
"src/layers/weather/infraredImage.js",
|
||||
|
||||
@@ -1070,6 +1070,10 @@
|
||||
"src/render/cesium/heights.js",
|
||||
"src/queries/heights.js",
|
||||
"src/render/cesium/draw.js",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
@@ -1854,6 +1858,10 @@
|
||||
"src/render/cesium/effects.js",
|
||||
"src/render/cesium/screenModulation.js",
|
||||
"src/render/cesium/draw.js",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
@@ -3056,6 +3064,10 @@
|
||||
"src/render/cesium/credits.js",
|
||||
"src/render/cesium/tileRequests.js",
|
||||
"src/render/cesium/draw.js",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/layers/wind/streamlines.js",
|
||||
"src/layers/wind/model.js",
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
@@ -3296,6 +3308,8 @@
|
||||
"src/render/baseTilesets.js",
|
||||
"src/render/cesium/drawHit.js",
|
||||
"src/render/cesium/draw.js",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
@@ -4308,6 +4322,8 @@
|
||||
"src/render/cesium/query.js",
|
||||
"src/render/cesium/heights.js",
|
||||
"src/render/cesium/draw.js",
|
||||
"src/render/cesium/drawFields.js",
|
||||
"src/render/cesium/drawStreamlines.js",
|
||||
"src/render/cesium/drawQuads.js",
|
||||
"src/render/cesium/drawMeshes.js",
|
||||
"src/render/cesium/drawModels.js",
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
+123
-217
@@ -1,266 +1,172 @@
|
||||
import {
|
||||
bakeWindStreamlines,
|
||||
groupWindPaths,
|
||||
WIND_DISPLAY_HEIGHT_METERS,
|
||||
WIND_PATH_LIMIT,
|
||||
WIND_NARROW_PATH_LIMIT,
|
||||
WIND_PATH_LIMIT,
|
||||
WIND_PATH_STEPS,
|
||||
} from './streamlines.js';
|
||||
import {
|
||||
canvasOf,
|
||||
findCamera,
|
||||
findDraw,
|
||||
findFrame,
|
||||
rendererOf,
|
||||
} from '../../render/rendererOf.js';
|
||||
|
||||
const WIND_FADE_LOW_METERS = 15000;
|
||||
const WIND_FADE_HIGH_METERS = 60000;
|
||||
// The streamlines' colour: the ghost and the trail; the moving tip brightens it.
|
||||
const WIND_STREAMLINE_COLOR = '#80c9e6';
|
||||
const WIND_STREAMLINE_WIDTH_PX = 2.4;
|
||||
|
||||
// Original material: a persistent fine curve plus a moving, tapered highlight.
|
||||
// The integer part of s identifies a path; its fractional part follows the wind.
|
||||
const FLOW_MATERIAL = `
|
||||
in float v_windFacing;
|
||||
czm_material czm_getMaterial(czm_materialInput materialInput)
|
||||
{
|
||||
czm_material material = czm_getDefaultMaterial(materialInput);
|
||||
float pathId = floor(materialInput.st.s);
|
||||
float along = fract(materialInput.st.s);
|
||||
float offset = fract((pathId + 1.0) * 0.61803398875);
|
||||
float behind = fract(phaseTime * 0.16 + offset - along);
|
||||
float tail = (1.0 - smoothstep(0.0, 0.32, behind));
|
||||
float tip = 1.0 - smoothstep(0.0, 0.045, behind);
|
||||
float ends = smoothstep(0.0, 0.055, along) * (1.0 - smoothstep(0.945, 1.0, along));
|
||||
float edge = 1.0 - smoothstep(0.26, 0.5, abs(materialInput.st.t - 0.5));
|
||||
float horizon = smoothstep(0.0, 0.065, v_windFacing);
|
||||
material.diffuse = mix(vec3(0.50, 0.79, 0.90), vec3(0.91, 0.99, 1.0), tip);
|
||||
material.alpha = (ghostAlpha + 0.64 * tail + 0.16 * tip) * ends * edge * horizon * heightFade;
|
||||
return material;
|
||||
}`;
|
||||
let fieldIds = 0;
|
||||
|
||||
/** Native Cesium geometry/material owner. No animation loop or DOM ownership. */
|
||||
export function createWindGpuRendering({ cesium: C, getViewer }) {
|
||||
const cells = [];
|
||||
let occluder = null;
|
||||
let collection = null;
|
||||
let material = null;
|
||||
/** The streamline fade for a camera this high: none low down, full from 60 km. */
|
||||
export function windHeightFade(height) {
|
||||
return Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
1,
|
||||
(height - WIND_FADE_LOW_METERS) /
|
||||
(WIND_FADE_HIGH_METERS - WIND_FADE_LOW_METERS),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A wind grid as the draw port's `windStreamlines` field: samples are
|
||||
* points, the first column at `lo1` and the first row at `la1`, rows
|
||||
* running south; a grid that wraps the globe spans 360° of longitude.
|
||||
*/
|
||||
export function windStreamlineSpec(field, { id, pathBudget, alpha, paused }) {
|
||||
const span = field.nx * field.dx;
|
||||
const wraps = span >= 360 - 1e-9;
|
||||
const west = field.lo1;
|
||||
const north = field.la1;
|
||||
return {
|
||||
kind: 'windStreamlines',
|
||||
id,
|
||||
u: field.u,
|
||||
v: field.v,
|
||||
width: field.nx,
|
||||
height: field.ny,
|
||||
rectangle: {
|
||||
west,
|
||||
south: north - (field.ny - 1) * field.dy,
|
||||
east: west + (wraps ? span : (field.nx - 1) * field.dx),
|
||||
north,
|
||||
},
|
||||
pathBudget,
|
||||
steps: WIND_PATH_STEPS,
|
||||
style: { color: WIND_STREAMLINE_COLOR, widthPx: WIND_STREAMLINE_WIDTH_PX },
|
||||
heightM: WIND_DISPLAY_HEIGHT_METERS,
|
||||
alpha,
|
||||
paused,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Streamlines through the draw port's `windStreamlines` field (capability
|
||||
* `fields`): the renderer traces, draws, culls and animates them; this
|
||||
* fades them by camera height and pauses them. Where the renderer has no
|
||||
* such field, or refuses this one, `setField` answers false and the layer
|
||||
* paints on its canvas instead. No animation loop or DOM ownership.
|
||||
*/
|
||||
export function createWindGpuRendering({
|
||||
getViewer,
|
||||
drawOf = findDraw,
|
||||
cameraOf = findCamera,
|
||||
frameOf = findFrame,
|
||||
} = {}) {
|
||||
let handle = null;
|
||||
let paused = false;
|
||||
let destroyed = false;
|
||||
let heightFade = 0;
|
||||
let drawn = false;
|
||||
const emptyDiagnostics = () => ({
|
||||
pathCount: 0,
|
||||
vertexCount: 0,
|
||||
buildMs: 0,
|
||||
error: null,
|
||||
cellCount: 0,
|
||||
visibleCells: 0,
|
||||
visibleVertexCount: 0,
|
||||
heightFade: 0,
|
||||
});
|
||||
let diagnostics = emptyDiagnostics();
|
||||
const viewer = () => getViewer?.() ?? null;
|
||||
|
||||
function supported() {
|
||||
const scene = getViewer?.()?.scene;
|
||||
return (
|
||||
!destroyed &&
|
||||
Boolean(
|
||||
scene?.primitives &&
|
||||
C?.Primitive &&
|
||||
C?.GeometryInstance &&
|
||||
C?.GeometryInstanceAttribute &&
|
||||
C?.ComponentDatatype?.FLOAT !== undefined &&
|
||||
C?.PolylineGeometry &&
|
||||
C?.PolylineMaterialAppearance &&
|
||||
C?.Material &&
|
||||
C?.BoundingSphere?.fromPoints &&
|
||||
C?.Occluder &&
|
||||
C?.Ellipsoid?.WGS84 &&
|
||||
C?.Intersect &&
|
||||
C?.Cartesian3?.fromDegrees,
|
||||
) &&
|
||||
(C.SceneMode?.SCENE3D === undefined ||
|
||||
scene.mode === undefined ||
|
||||
scene.mode === C.SceneMode.SCENE3D)
|
||||
);
|
||||
const host = viewer();
|
||||
if (destroyed || !host) return false;
|
||||
const capabilities = rendererOf(host)?.capabilities;
|
||||
if (capabilities && !capabilities.has('fields')) return false;
|
||||
return typeof drawOf(host)?.field === 'function';
|
||||
}
|
||||
|
||||
function clear() {
|
||||
for (const cell of cells) {
|
||||
collection?.remove(cell.primitive);
|
||||
if (!cell.primitive.isDestroyed?.()) cell.primitive.destroy?.();
|
||||
}
|
||||
cells.length = 0;
|
||||
occluder = null;
|
||||
collection = null;
|
||||
material?.destroy?.();
|
||||
material = null;
|
||||
handle?.dispose();
|
||||
handle = null;
|
||||
drawn = false;
|
||||
diagnostics = emptyDiagnostics();
|
||||
}
|
||||
|
||||
function readFade() {
|
||||
const height = cameraOf(viewer())?.pose?.().height;
|
||||
return Number.isFinite(height) ? windHeightFade(height) : heightFade;
|
||||
}
|
||||
|
||||
function setField(field) {
|
||||
clear();
|
||||
if (!supported() || !field) return false;
|
||||
const started = globalThis.performance?.now?.() ?? Date.now();
|
||||
const width = canvasOf(viewer())?.clientWidth;
|
||||
const pathBudget =
|
||||
width > 0 && width < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT;
|
||||
heightFade = readFade();
|
||||
try {
|
||||
const width = getViewer().scene.canvas?.clientWidth;
|
||||
const budget =
|
||||
width > 0 && width < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT;
|
||||
const paths = bakeWindStreamlines(field, { count: budget });
|
||||
if (!paths.length) return false;
|
||||
let vertexCount = 0;
|
||||
material = new C.Material({
|
||||
fabric: {
|
||||
type: 'GevWindStreamline',
|
||||
uniforms: {
|
||||
phaseTime: 0,
|
||||
ghostAlpha: paused ? 0.34 : 0.25,
|
||||
heightFade: 0,
|
||||
},
|
||||
source: FLOW_MATERIAL,
|
||||
},
|
||||
translucent: () => true,
|
||||
});
|
||||
const base = new C.PolylineMaterialAppearance({ material });
|
||||
// Extend the public default shader rather than duplicate Cesium's polyline
|
||||
// expansion/precision code. Explicit facing also masks the far hemisphere
|
||||
// when a scene chooses not to preserve globe depth for translucent objects.
|
||||
const source = base.vertexShaderSource;
|
||||
if (
|
||||
!/void\s+main\s*\(\s*\)/.test(source) ||
|
||||
!/v_st\.s\s*=\s*st\.s\s*;/.test(source)
|
||||
)
|
||||
throw new Error('Wind polyline shader entry unavailable');
|
||||
const seededSource = source.replace(
|
||||
/v_st\.s\s*=\s*st\.s\s*;/,
|
||||
'v_st.s = st.s * 0.999 + czm_batchTable_windSeed(batchId);',
|
||||
handle = drawOf(viewer()).field(
|
||||
windStreamlineSpec(field, {
|
||||
id: `wind-streamlines:${(fieldIds += 1)}`,
|
||||
pathBudget,
|
||||
alpha: heightFade,
|
||||
paused,
|
||||
}),
|
||||
);
|
||||
const vertexShaderSource =
|
||||
`out float v_windFacing;\n${seededSource}`.replace(
|
||||
/void\s+main\s*\(\s*\)\s*\{/,
|
||||
`void main() {\nvec3 windWorld = (czm_model * vec4(position3DHigh + position3DLow, 1.0)).xyz;\nv_windFacing = dot(normalize(windWorld), normalize(czm_viewerPositionWC - windWorld));\n`,
|
||||
);
|
||||
const scene = getViewer().scene;
|
||||
collection = scene.primitives;
|
||||
// EllipsoidalOccluder only tests points. Use Cesium's sphere occluder
|
||||
// with an inscribed Earth sphere, independent of scene.globe.show.
|
||||
occluder = new C.Occluder(
|
||||
new C.BoundingSphere(
|
||||
C.Cartesian3.ZERO,
|
||||
C.Ellipsoid.WGS84.minimumRadius,
|
||||
),
|
||||
scene.camera.positionWC,
|
||||
);
|
||||
for (const group of groupWindPaths(paths)) {
|
||||
const cellPositions = [];
|
||||
let cellVertexCount = 0;
|
||||
const instances = group.paths.map((path) => {
|
||||
const positions = path.coordinates.map(([lon, lat]) =>
|
||||
C.Cartesian3.fromDegrees(lon, lat, WIND_DISPLAY_HEIGHT_METERS),
|
||||
);
|
||||
// Pass the native description to Cesium's worker. Per-instance seed
|
||||
// attributes avoid touching the expanded vertex buffer on the UI thread.
|
||||
const geometry = new C.PolylineGeometry({
|
||||
positions,
|
||||
width: 2.4,
|
||||
arcType: C.ArcType?.NONE,
|
||||
vertexFormat: C.PolylineMaterialAppearance.VERTEX_FORMAT,
|
||||
});
|
||||
cellPositions.push(...positions);
|
||||
cellVertexCount += positions.length * 4 - 4;
|
||||
return new C.GeometryInstance({
|
||||
geometry,
|
||||
attributes: {
|
||||
windSeed: new C.GeometryInstanceAttribute({
|
||||
componentDatatype: C.ComponentDatatype.FLOAT,
|
||||
componentsPerAttribute: 1,
|
||||
value: [path.seed],
|
||||
}),
|
||||
},
|
||||
});
|
||||
});
|
||||
const appearance = new C.PolylineMaterialAppearance({
|
||||
material,
|
||||
vertexShaderSource,
|
||||
translucent: true,
|
||||
renderState: { depthTest: { enabled: true }, depthMask: false },
|
||||
});
|
||||
const primitive = new C.Primitive({
|
||||
show: false,
|
||||
geometryInstances: instances,
|
||||
appearance,
|
||||
asynchronous: true,
|
||||
allowPicking: false,
|
||||
releaseGeometryInstances: true,
|
||||
compressVertices: false,
|
||||
});
|
||||
const cell = {
|
||||
primitive,
|
||||
sphere: C.BoundingSphere.fromPoints(cellPositions),
|
||||
vertexCount: cellVertexCount,
|
||||
};
|
||||
cells.push(cell);
|
||||
collection.add(primitive);
|
||||
vertexCount += cellVertexCount;
|
||||
}
|
||||
diagnostics = {
|
||||
...emptyDiagnostics(),
|
||||
cellCount: cells.length,
|
||||
pathCount: paths.length,
|
||||
vertexCount,
|
||||
buildMs: (globalThis.performance?.now?.() ?? Date.now()) - started,
|
||||
error: null,
|
||||
};
|
||||
return true;
|
||||
} catch (error) {
|
||||
clear();
|
||||
handle = null;
|
||||
diagnostics.error =
|
||||
// i18n-ignore: GPU diagnostics only; the panel never shows this field
|
||||
error instanceof Error ? error.message : 'Wind geometry unavailable';
|
||||
return false;
|
||||
}
|
||||
handle.on('drawn', () => {
|
||||
drawn = true;
|
||||
// One more frame, so a still scene shows the layer ready.
|
||||
frameOf(viewer())?.requestRender?.('wind');
|
||||
});
|
||||
diagnostics = {
|
||||
...emptyDiagnostics(),
|
||||
pathCount: pathBudget,
|
||||
buildMs: (globalThis.performance?.now?.() ?? Date.now()) - started,
|
||||
heightFade,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
// Cesium reuses its frustum culling volume and the occluder's scratch vectors.
|
||||
// This loop creates no positions, spheres, appearances or per-cell temporaries.
|
||||
function updateVisibility(camera) {
|
||||
const height = camera.positionCartographic.height;
|
||||
const heightFade = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
1,
|
||||
(height - WIND_FADE_LOW_METERS) /
|
||||
(WIND_FADE_HIGH_METERS - WIND_FADE_LOW_METERS),
|
||||
),
|
||||
);
|
||||
diagnostics.heightFade = heightFade;
|
||||
if (material) material.uniforms.heightFade = heightFade;
|
||||
diagnostics.visibleCells = 0;
|
||||
diagnostics.visibleVertexCount = 0;
|
||||
let volume;
|
||||
if (heightFade > 0 && cells.length) {
|
||||
occluder.cameraPosition = camera.positionWC;
|
||||
volume = camera.frustum.computeCullingVolume(
|
||||
camera.positionWC,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < cells.length; i++) {
|
||||
const cell = cells[i];
|
||||
cell.primitive.show =
|
||||
heightFade > 0 &&
|
||||
occluder.isBoundingSphereVisible(cell.sphere) &&
|
||||
volume.computeVisibility(cell.sphere) !== C.Intersect.OUTSIDE;
|
||||
if (cell.primitive.show) {
|
||||
diagnostics.visibleCells++;
|
||||
diagnostics.visibleVertexCount += cell.vertexCount;
|
||||
}
|
||||
}
|
||||
return diagnostics.visibleCells > 0 && heightFade > 0;
|
||||
/** Fade by camera height; whether anything can draw. */
|
||||
function updateVisibility() {
|
||||
const fade = readFade();
|
||||
diagnostics.heightFade = fade;
|
||||
if (handle && fade !== heightFade) handle.update({ alpha: fade });
|
||||
heightFade = fade;
|
||||
return Boolean(handle) && fade > 0;
|
||||
}
|
||||
|
||||
return {
|
||||
supported,
|
||||
setField,
|
||||
updateVisibility,
|
||||
tick(elapsedSeconds) {
|
||||
if (material && !paused && Number.isFinite(elapsedSeconds))
|
||||
material.uniforms.phaseTime = Math.max(0, elapsedSeconds) % 10000;
|
||||
},
|
||||
setOptions(options = {}) {
|
||||
if (typeof options.paused === 'boolean') paused = options.paused;
|
||||
if (material) material.uniforms.ghostAlpha = paused ? 0.34 : 0.25;
|
||||
if (typeof options.paused !== 'boolean' || options.paused === paused)
|
||||
return;
|
||||
paused = options.paused;
|
||||
handle?.update({ paused });
|
||||
},
|
||||
clear,
|
||||
destroy() {
|
||||
@@ -270,7 +176,7 @@ export function createWindGpuRendering({ cesium: C, getViewer }) {
|
||||
getParticleCount: () => diagnostics.pathCount,
|
||||
getDiagnostics: () => ({
|
||||
...diagnostics,
|
||||
ready: cells.length > 0 && cells.every((cell) => cell.primitive.ready),
|
||||
ready: Boolean(handle) && drawn,
|
||||
mode: 'gpu-streamlines',
|
||||
displayHeightMeters: WIND_DISPLAY_HEIGHT_METERS,
|
||||
}),
|
||||
|
||||
@@ -1,147 +1,18 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createWindGpuRendering } from './gpuRendering.js';
|
||||
import {
|
||||
BoundingSphere,
|
||||
Cartesian3,
|
||||
Ellipsoid,
|
||||
Intersect,
|
||||
Occluder,
|
||||
PerspectiveFrustum,
|
||||
} from 'cesium';
|
||||
import { bakeWindStreamlines } from './streamlines.js';
|
||||
createWindGpuRendering,
|
||||
windHeightFade,
|
||||
windStreamlineSpec,
|
||||
} from './gpuRendering.js';
|
||||
import {
|
||||
WIND_DISPLAY_HEIGHT_METERS,
|
||||
WIND_NARROW_PATH_LIMIT,
|
||||
WIND_PATH_LIMIT,
|
||||
WIND_PATH_STEPS,
|
||||
} from './streamlines.js';
|
||||
|
||||
function harness({ width = 1000 } = {}) {
|
||||
const members = new Set();
|
||||
let geometryBuilds = 0;
|
||||
const spheres = [];
|
||||
const visibility = {
|
||||
horizon: () => true,
|
||||
frustum: () => Intersect.INSIDE,
|
||||
horizonTests: 0,
|
||||
frustumTests: 0,
|
||||
};
|
||||
let occluderBuilds = 0;
|
||||
class Material {
|
||||
constructor(options) {
|
||||
this.uniforms = options.fabric.uniforms;
|
||||
this.source = options.fabric.source;
|
||||
}
|
||||
destroy() {
|
||||
assert.ok(!this.destroyed, 'owned resource destroyed once');
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
class Appearance {
|
||||
static VERTEX_FORMAT = {};
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.vertexShaderSource ??=
|
||||
'in vec3 position3DHigh; in vec3 position3DLow; void main() { gl_Position = vec4(0.0); v_st.s = st.s; }';
|
||||
}
|
||||
}
|
||||
class Polyline {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
static createGeometry(options) {
|
||||
geometryBuilds++;
|
||||
const st = new Float32Array(options.positions.length * 2);
|
||||
for (let i = 0; i < options.positions.length; i++)
|
||||
st[i * 2] = i / (options.positions.length - 1);
|
||||
return { attributes: { st: { values: st } } };
|
||||
}
|
||||
}
|
||||
class Primitive {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.ready = true;
|
||||
}
|
||||
destroy() {
|
||||
assert.ok(!this.destroyed, 'owned resource destroyed once');
|
||||
this.destroyed = true;
|
||||
}
|
||||
isDestroyed() {
|
||||
return Boolean(this.destroyed);
|
||||
}
|
||||
}
|
||||
const C = {
|
||||
ComponentDatatype: { FLOAT: 5126 },
|
||||
GeometryInstanceAttribute: class {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
},
|
||||
Material,
|
||||
PolylineMaterialAppearance: Appearance,
|
||||
PolylineGeometry: Polyline,
|
||||
Primitive,
|
||||
GeometryInstance: class {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
},
|
||||
Cartesian3,
|
||||
Ellipsoid,
|
||||
Intersect,
|
||||
BoundingSphere: class extends BoundingSphere {
|
||||
static fromPoints(points) {
|
||||
const sphere = BoundingSphere.fromPoints(points);
|
||||
spheres.push({ sphere, points });
|
||||
return sphere;
|
||||
}
|
||||
},
|
||||
Occluder: class {
|
||||
constructor(sphere, cameraPosition) {
|
||||
occluderBuilds++;
|
||||
this.cameraPosition = cameraPosition;
|
||||
}
|
||||
isBoundingSphereVisible(sphere) {
|
||||
visibility.horizonTests++;
|
||||
return visibility.horizon(sphere, this.cameraPosition);
|
||||
}
|
||||
},
|
||||
ArcType: { NONE: 0 },
|
||||
};
|
||||
const volume = {
|
||||
computeVisibility(sphere) {
|
||||
visibility.frustumTests++;
|
||||
return visibility.frustum(sphere);
|
||||
},
|
||||
};
|
||||
const scene = {
|
||||
globe: { show: false },
|
||||
camera: {
|
||||
positionWC: Cartesian3.fromDegrees(0, 0, 1e7),
|
||||
positionCartographic: { height: 1e7 },
|
||||
directionWC: new Cartesian3(-1, 0, 0),
|
||||
upWC: new Cartesian3(0, 0, 1),
|
||||
frustum: { computeCullingVolume: () => volume },
|
||||
},
|
||||
canvas: { clientWidth: width },
|
||||
primitives: {
|
||||
add(item) {
|
||||
members.add(item);
|
||||
},
|
||||
remove(item) {
|
||||
const removed = members.delete(item);
|
||||
if (removed) item.destroy();
|
||||
return removed;
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
C,
|
||||
scene,
|
||||
members,
|
||||
builds: () => geometryBuilds,
|
||||
spheres,
|
||||
visibility,
|
||||
occluderBuilds: () => occluderBuilds,
|
||||
owner: createWindGpuRendering({ cesium: C, getViewer: () => ({ scene }) }),
|
||||
};
|
||||
}
|
||||
const field = () => ({
|
||||
const wind = () => ({
|
||||
nx: 4,
|
||||
ny: 3,
|
||||
lo1: -180,
|
||||
@@ -152,248 +23,152 @@ const field = () => ({
|
||||
v: new Float32Array(12),
|
||||
});
|
||||
|
||||
test('GPU owner builds regional native batches; ticks update uniforms without rebuilding geometry', () => {
|
||||
const h = harness();
|
||||
assert.equal(h.owner.setField(field()), true);
|
||||
assert.equal(h.members.size, 72);
|
||||
const batch = [...h.members][0];
|
||||
assert.equal(batch.allowPicking, false);
|
||||
assert.equal(batch.asynchronous, true);
|
||||
assert.ok(batch.appearance.vertexShaderSource.includes('v_windFacing = dot'));
|
||||
assert.ok(
|
||||
batch.appearance.material.source.includes(
|
||||
'smoothstep(0.0, 0.065, v_windFacing)',
|
||||
),
|
||||
);
|
||||
const builds = h.builds();
|
||||
assert.equal(builds, 0, 'expanded geometry is deferred to Cesium workers');
|
||||
assert.ok(
|
||||
batch.appearance.vertexShaderSource.includes(
|
||||
'czm_batchTable_windSeed(batchId)',
|
||||
),
|
||||
);
|
||||
h.owner.tick(3);
|
||||
assert.equal(batch.appearance.material.uniforms.phaseTime, 3);
|
||||
h.owner.setOptions({ paused: true });
|
||||
h.owner.tick(8);
|
||||
assert.equal(batch.appearance.material.uniforms.phaseTime, 3);
|
||||
h.owner.setOptions({ paused: false });
|
||||
h.owner.tick(9);
|
||||
assert.equal(batch.appearance.material.uniforms.phaseTime, 9);
|
||||
assert.equal(h.builds(), builds);
|
||||
const diagnostics = h.owner.getDiagnostics();
|
||||
assert.ok(diagnostics.pathCount <= 7200);
|
||||
assert.ok(
|
||||
diagnostics.pathCount > 7000,
|
||||
'desktop retains the requested doubled global density',
|
||||
);
|
||||
assert.ok(diagnostics.vertexCount > 0);
|
||||
assert.ok(
|
||||
diagnostics.vertexCount <= 7200 * 128,
|
||||
'expanded geometry remains bounded',
|
||||
);
|
||||
assert.equal(diagnostics.ready, true);
|
||||
assert.equal(diagnostics.displayHeightMeters, 12000);
|
||||
assert.equal(diagnostics.cellCount, 72);
|
||||
assert.equal(h.spheres.length, 72);
|
||||
assert.equal(new Set([...h.members].map((p) => p.appearance)).size, 72);
|
||||
for (const cell of h.members) {
|
||||
assert.equal(cell.appearance.material, batch.appearance.material);
|
||||
assert.equal(cell.appearance.material.uniforms.phaseTime, 9);
|
||||
assert.equal(cell.appearance.material.uniforms.ghostAlpha, 0.25);
|
||||
assert.equal(cell.compressVertices, false);
|
||||
assert.equal(cell.releaseGeometryInstances, true);
|
||||
}
|
||||
batch.ready = false;
|
||||
assert.equal(
|
||||
h.owner.getDiagnostics().ready,
|
||||
false,
|
||||
'every cell must be ready',
|
||||
);
|
||||
batch.ready = true;
|
||||
const instances = [...h.members].flatMap((p) => p.geometryInstances);
|
||||
const baked = bakeWindStreamlines(field());
|
||||
assert.equal(instances.length, baked.length);
|
||||
const bySeed = new Map(
|
||||
instances.map((i) => [i.attributes.windSeed.value[0], i]),
|
||||
);
|
||||
for (const path of baked) {
|
||||
assert.deepEqual(
|
||||
bySeed.get(path.seed).geometry.positions,
|
||||
path.coordinates.map(([lon, lat]) =>
|
||||
Cartesian3.fromDegrees(lon, lat, 12000),
|
||||
),
|
||||
);
|
||||
}
|
||||
for (const { sphere, points } of h.spheres) {
|
||||
assert.deepEqual(sphere, BoundingSphere.fromPoints(points));
|
||||
for (const point of points)
|
||||
assert.ok(
|
||||
Cartesian3.distance(point, sphere.center) <= sphere.radius + 1e-6,
|
||||
);
|
||||
}
|
||||
for (const instance of instances) {
|
||||
assert.ok(instance.geometry instanceof h.C.PolylineGeometry);
|
||||
assert.equal(instance.geometry.width, 2.4);
|
||||
assert.equal(instance.attributes.windSeed.componentsPerAttribute, 1);
|
||||
assert.ok(Number.isInteger(instance.attributes.windSeed.value[0]));
|
||||
}
|
||||
// A draw port whose fields record what they were asked, a camera at
|
||||
// `height` and a canvas `width` wide.
|
||||
function harness({ width = 1000, height = 2_000_000, refuse = null } = {}) {
|
||||
const fields = [];
|
||||
const camera = { height };
|
||||
const viewer = { canvas: { clientWidth: width } };
|
||||
const draw = {
|
||||
field(spec) {
|
||||
if (refuse) throw refuse;
|
||||
const listeners = [];
|
||||
const handle = {
|
||||
spec,
|
||||
updates: [],
|
||||
disposed: false,
|
||||
show: true,
|
||||
update(patch) {
|
||||
this.updates.push(patch);
|
||||
},
|
||||
on(event, cb) {
|
||||
assert.equal(event, 'drawn');
|
||||
listeners.push(cb);
|
||||
return () => {};
|
||||
},
|
||||
dispose() {
|
||||
assert.equal(this.disposed, false, 'disposed once');
|
||||
this.disposed = true;
|
||||
},
|
||||
tell: () => listeners.forEach((cb) => cb()),
|
||||
};
|
||||
fields.push(handle);
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
const frames = [];
|
||||
const owner = createWindGpuRendering({
|
||||
getViewer: () => viewer,
|
||||
drawOf: () => draw,
|
||||
cameraOf: () => ({ pose: () => ({ height: camera.height }) }),
|
||||
frameOf: () => ({ requestRender: (reason) => frames.push(reason) }),
|
||||
});
|
||||
return { owner, fields, camera, viewer, draw, frames };
|
||||
}
|
||||
|
||||
test('the fade by camera height is none below 15 km and full from 60 km', () => {
|
||||
assert.equal(windHeightFade(10_000), 0);
|
||||
assert.equal(windHeightFade(15_000), 0);
|
||||
assert.equal(windHeightFade(37_500), 0.5);
|
||||
assert.equal(windHeightFade(60_000), 1);
|
||||
assert.equal(windHeightFade(2e7), 1);
|
||||
});
|
||||
|
||||
test('replacement, clear and destroy dispose every owned cell and the shared material', () => {
|
||||
const h = harness();
|
||||
const assertDisposed = (batches) => {
|
||||
assert.equal(batches.length, 72);
|
||||
for (const batch of batches) {
|
||||
assert.equal(batch.destroyed, true);
|
||||
assert.equal(batch.appearance.material.destroyed, true);
|
||||
}
|
||||
};
|
||||
h.owner.setField(field());
|
||||
const first = [...h.members];
|
||||
h.owner.setField(field());
|
||||
assertDisposed(first);
|
||||
const second = [...h.members];
|
||||
test('a wind grid becomes a windStreamlines spec over the rectangle its samples span', () => {
|
||||
const field = wind();
|
||||
const spec = windStreamlineSpec(field, {
|
||||
id: 'w',
|
||||
pathBudget: 100,
|
||||
alpha: 0.5,
|
||||
paused: true,
|
||||
});
|
||||
assert.equal(spec.kind, 'windStreamlines');
|
||||
assert.deepEqual(spec.rectangle, {
|
||||
west: -180,
|
||||
south: -90,
|
||||
east: 180,
|
||||
north: 90,
|
||||
});
|
||||
assert.equal(spec.width, 4);
|
||||
assert.equal(spec.height, 3);
|
||||
assert.equal(spec.steps, WIND_PATH_STEPS);
|
||||
assert.equal(spec.heightM, WIND_DISPLAY_HEIGHT_METERS);
|
||||
assert.equal(spec.alpha, 0.5);
|
||||
assert.equal(spec.paused, true);
|
||||
assert.equal(spec.u, field.u);
|
||||
assert.equal(spec.v, field.v);
|
||||
const regional = windStreamlineSpec(
|
||||
{ ...field, nx: 4, ny: 4, lo1: -100, la1: 50, dx: 10, dy: 10 },
|
||||
{ id: 'r', pathBudget: 1 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
regional.rectangle,
|
||||
{ west: -100, south: 20, east: -70, north: 50 },
|
||||
'a regional grid spans its samples and does not wrap',
|
||||
);
|
||||
});
|
||||
|
||||
test('streamlines draw through the port, faded by height, paused and ready once drawn', () => {
|
||||
const h = harness({ height: 37_500 });
|
||||
assert.equal(h.owner.supported(), true);
|
||||
assert.equal(h.owner.setField(wind()), true);
|
||||
const [field] = h.fields;
|
||||
assert.equal(field.spec.pathBudget, WIND_PATH_LIMIT);
|
||||
assert.equal(field.spec.alpha, 0.5);
|
||||
assert.equal(field.spec.paused, false);
|
||||
assert.equal(h.owner.getDiagnostics().ready, false);
|
||||
assert.equal(h.owner.getDiagnostics().mode, 'gpu-streamlines');
|
||||
assert.equal(h.owner.getParticleCount(), WIND_PATH_LIMIT);
|
||||
field.tell();
|
||||
assert.equal(h.owner.getDiagnostics().ready, true);
|
||||
assert.deepEqual(h.frames, ['wind'], 'a still scene draws the ready state');
|
||||
assert.equal(h.owner.updateVisibility(), true);
|
||||
assert.deepEqual(field.updates, [], 'an unchanged fade asks nothing');
|
||||
h.camera.height = 10_000;
|
||||
assert.equal(h.owner.updateVisibility(), false, 'nothing draws low down');
|
||||
assert.deepEqual(field.updates, [{ alpha: 0 }]);
|
||||
assert.equal(h.owner.getDiagnostics().heightFade, 0);
|
||||
h.camera.height = 100_000;
|
||||
assert.equal(h.owner.updateVisibility(), true);
|
||||
h.owner.setOptions({ paused: true });
|
||||
h.owner.setOptions({ paused: true });
|
||||
h.owner.setOptions({ overlay: 'speed' });
|
||||
assert.deepEqual(field.updates, [
|
||||
{ alpha: 0 },
|
||||
{ alpha: 1 },
|
||||
{ paused: true },
|
||||
]);
|
||||
h.owner.setField(wind());
|
||||
assert.equal(field.disposed, true, 'a new grid replaces the field');
|
||||
assert.equal(h.fields[1].spec.paused, true, 'and keeps the pause');
|
||||
assert.notEqual(h.fields[1].spec.id, field.spec.id);
|
||||
h.owner.clear();
|
||||
assertDisposed(second);
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.equal(h.fields[1].disposed, true);
|
||||
assert.equal(h.owner.getParticleCount(), 0);
|
||||
assert.equal(h.owner.getDiagnostics().ready, false);
|
||||
h.owner.setField(field());
|
||||
const third = [...h.members];
|
||||
h.owner.destroy();
|
||||
assertDisposed(third);
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.equal(h.owner.supported(), false);
|
||||
assert.equal(h.owner.setField(field()), false);
|
||||
});
|
||||
|
||||
test('unsupported or failed geometry cleanly requests the existing fallback', () => {
|
||||
const missing = createWindGpuRendering({
|
||||
cesium: {},
|
||||
getViewer: () => ({ scene: {} }),
|
||||
});
|
||||
assert.equal(missing.setField(field()), false);
|
||||
const h = harness();
|
||||
h.C.PolylineGeometry = class {
|
||||
constructor() {
|
||||
throw new Error('test build failure');
|
||||
}
|
||||
};
|
||||
assert.equal(h.owner.setField(field()), false);
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.match(h.owner.getDiagnostics().error, /test build failure/);
|
||||
assert.equal(h.owner.setField(wind()), false);
|
||||
});
|
||||
|
||||
test('narrow canvases use a lower bounded path budget', () => {
|
||||
const h = harness({ width: 390 });
|
||||
assert.equal(h.owner.setField(field()), true);
|
||||
assert.ok(h.owner.getParticleCount() <= 1200);
|
||||
assert.ok(h.owner.getParticleCount() > 1000);
|
||||
const h = harness({ width: 600 });
|
||||
assert.equal(h.owner.setField(wind()), true);
|
||||
assert.equal(h.fields[0].spec.pathBudget, WIND_NARROW_PATH_LIMIT);
|
||||
});
|
||||
|
||||
test('cell visibility combines horizon, frustum and height with shared fade uniforms', () => {
|
||||
const h = harness();
|
||||
h.owner.setField(field());
|
||||
const batches = [...h.members];
|
||||
const camera = h.scene.camera;
|
||||
h.visibility.horizon = (sphere) =>
|
||||
h.spheres.findIndex((s) => s.sphere === sphere) % 2 === 0;
|
||||
h.visibility.frustum = (sphere) =>
|
||||
h.spheres.findIndex((s) => s.sphere === sphere) % 3 === 0
|
||||
? Intersect.INTERSECTING
|
||||
: Intersect.OUTSIDE;
|
||||
assert.equal(h.owner.updateVisibility(camera), true);
|
||||
assert.equal(h.owner.getDiagnostics().visibleCells, 12);
|
||||
let vertices = 0;
|
||||
for (let i = 0; i < batches.length; i++) {
|
||||
assert.equal(batches[i].show, i % 6 === 0);
|
||||
if (batches[i].show)
|
||||
vertices += batches[i].geometryInstances.reduce(
|
||||
(sum, p) => sum + p.geometry.positions.length * 4 - 4,
|
||||
0,
|
||||
);
|
||||
}
|
||||
assert.equal(h.owner.getDiagnostics().visibleVertexCount, vertices);
|
||||
assert.equal(h.visibility.horizonTests, 72);
|
||||
assert.equal(h.visibility.frustumTests, 36);
|
||||
for (const [height, fade] of [
|
||||
[60000, 1],
|
||||
[37500, 0.5],
|
||||
[15000, 0],
|
||||
[1200, 0],
|
||||
]) {
|
||||
camera.positionCartographic.height = height;
|
||||
assert.equal(h.owner.updateVisibility(camera), fade > 0);
|
||||
assert.equal(h.owner.getDiagnostics().heightFade, fade);
|
||||
for (const batch of batches) {
|
||||
assert.equal(batch.appearance.material.uniforms.heightFade, fade);
|
||||
assert.match(batch.appearance.material.source, /horizon \* heightFade/);
|
||||
if (!fade) assert.equal(batch.show, false);
|
||||
}
|
||||
}
|
||||
assert.equal(h.owner.getDiagnostics().visibleVertexCount, 0);
|
||||
assert.equal(h.owner.getDiagnostics().visibleCells, 0);
|
||||
assert.equal(
|
||||
h.visibility.horizonTests,
|
||||
216,
|
||||
'zero fade skips all sphere tests',
|
||||
);
|
||||
assert.equal(h.visibility.frustumTests, 108);
|
||||
assert.equal(
|
||||
h.occluderBuilds(),
|
||||
1,
|
||||
'occluder is reused across camera updates',
|
||||
);
|
||||
});
|
||||
|
||||
test('real Cesium sphere culling hides far hemisphere with globe hidden and rejects a sky-facing view', () => {
|
||||
const h = harness();
|
||||
h.C.Occluder = Occluder;
|
||||
h.owner.setField(field());
|
||||
const camera = h.scene.camera;
|
||||
camera.frustum = new PerspectiveFrustum({
|
||||
fov: Math.PI / 3,
|
||||
aspectRatio: 1.5,
|
||||
near: 1,
|
||||
far: 5e7,
|
||||
test('a refused or missing field falls back to the canvas', () => {
|
||||
const refused = harness({ refuse: new TypeError('no streamlines here') });
|
||||
assert.equal(refused.owner.setField(wind()), false);
|
||||
assert.equal(refused.owner.getDiagnostics().error, 'no streamlines here');
|
||||
assert.equal(refused.owner.getParticleCount(), 0);
|
||||
const none = createWindGpuRendering({
|
||||
getViewer: () => ({}),
|
||||
drawOf: () => ({}),
|
||||
cameraOf: () => null,
|
||||
});
|
||||
assert.equal(h.owner.updateVisibility(camera), true);
|
||||
const facingEarth = h.owner.getDiagnostics();
|
||||
assert.ok(facingEarth.visibleCells > 0 && facingEarth.visibleCells < 72);
|
||||
for (let i = 0; i < h.spheres.length; i++) {
|
||||
const sphere = h.spheres[i].sphere;
|
||||
if (sphere.center.x < -5e6) assert.equal([...h.members][i].show, false);
|
||||
}
|
||||
camera.directionWC.x = 1;
|
||||
assert.equal(h.owner.updateVisibility(camera), false);
|
||||
assert.equal(h.owner.getDiagnostics().visibleCells, 0);
|
||||
camera.positionWC = Cartesian3.fromDegrees(180, 0, 1e7);
|
||||
assert.equal(
|
||||
h.owner.updateVisibility(camera),
|
||||
true,
|
||||
'camera position updates the owned horizon test',
|
||||
);
|
||||
h.owner.destroy();
|
||||
});
|
||||
|
||||
test('a failed later cell build releases already installed cells and shared material', () => {
|
||||
const h = harness();
|
||||
const NativePrimitive = h.C.Primitive;
|
||||
const built = [];
|
||||
h.C.Primitive = class extends NativePrimitive {
|
||||
constructor(options) {
|
||||
if (built.length === 2) throw new Error('later cell failed');
|
||||
super(options);
|
||||
built.push(this);
|
||||
}
|
||||
};
|
||||
assert.equal(h.owner.setField(field()), false);
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.equal(built.length, 2);
|
||||
for (const batch of built) {
|
||||
assert.equal(batch.destroyed, true);
|
||||
assert.equal(batch.appearance.material.destroyed, true);
|
||||
}
|
||||
assert.match(h.owner.getDiagnostics().error, /later cell failed/);
|
||||
assert.equal(none.supported(), false);
|
||||
assert.equal(none.setField(wind()), false);
|
||||
const absent = createWindGpuRendering({ getViewer: () => null });
|
||||
assert.equal(absent.supported(), false);
|
||||
});
|
||||
+40
-75
@@ -1,98 +1,63 @@
|
||||
// View-directed display lighting over existing terrain normals. This does not
|
||||
// represent the Sun, change terrain geometry, or supply missing elevation data.
|
||||
function reliefSource(terrainNormals) {
|
||||
const normal = terrainNormals
|
||||
? 'vec3 normal = normalize(materialInput.normalEC);'
|
||||
: `vec3 worldPosition = (czm_inverseView * vec4(-materialInput.positionToEyeEC, 1.0)).xyz;
|
||||
vec3 geodeticNormal = normalize(worldPosition * czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii);
|
||||
vec3 normal = normalize(czm_viewRotation * geodeticNormal);`;
|
||||
return `
|
||||
czm_material czm_getMaterial(czm_materialInput materialInput)
|
||||
{
|
||||
czm_material material = czm_getDefaultMaterial(materialInput);
|
||||
${normal}
|
||||
vec3 displayLight = normalize(vec3(-0.45, 0.55, 0.8));
|
||||
float shade = clamp((1.0 - dot(normal, displayLight)) * 0.32, 0.0, 0.28);
|
||||
material.diffuse = vec3(0.0);
|
||||
material.alpha = shade;
|
||||
return material;
|
||||
}
|
||||
`;
|
||||
}
|
||||
import { findGlobe } from '../../render/rendererOf.js';
|
||||
|
||||
/** Optional, exclusive globe-material owner; no animation or source acquisition. */
|
||||
export function createWindRelief({ cesium, getViewer } = {}) {
|
||||
/** The darkest the relief shading gets, as an opacity. */
|
||||
export const WIND_RELIEF_STRENGTH = 0.28;
|
||||
|
||||
/**
|
||||
* View-directed display shading of the globe's relief while the wind layer
|
||||
* shows: the globe port's `hillshade` surface shading (capability
|
||||
* `surfaceShading`), over the terrain's own normals or, without them, the
|
||||
* ellipsoid's curvature. It stands for no sun, changes no geometry and asks
|
||||
* for no data. The renderer owns the material: it never takes one someone
|
||||
* else holds, and gives it back when cleared. No animation or source
|
||||
* acquisition.
|
||||
*/
|
||||
export function createWindRelief({ getViewer, globeOf = findGlobe } = {}) {
|
||||
// The globe port shading for this layer, and the viewer it belongs to.
|
||||
let globe = null;
|
||||
let scene = null;
|
||||
let owned = null;
|
||||
let previous = undefined;
|
||||
let viewer = null;
|
||||
let destroyed = false;
|
||||
let reason = 'Not attached';
|
||||
let mode = null;
|
||||
const alive = (value) => value && !value.isDestroyed?.();
|
||||
const active = () =>
|
||||
Boolean(owned && alive(globe) && globe.material === owned);
|
||||
|
||||
function clear() {
|
||||
const changed = active();
|
||||
if (changed) globe.material = previous;
|
||||
if (owned && !owned.isDestroyed?.()) owned.destroy?.();
|
||||
if (changed && alive(scene)) scene.requestRender?.();
|
||||
owned = null;
|
||||
mode = null;
|
||||
if (globe && alive(viewer)) globe.setSurfaceShading(null);
|
||||
globe = null;
|
||||
scene = null;
|
||||
previous = undefined;
|
||||
viewer = null;
|
||||
reason = destroyed ? 'Destroyed' : 'Not attached';
|
||||
}
|
||||
|
||||
return {
|
||||
attach() {
|
||||
if (destroyed) return false;
|
||||
const viewer = getViewer?.();
|
||||
const nextScene = alive(viewer) ? viewer.scene : null;
|
||||
const nextGlobe = nextScene?.globe;
|
||||
const nextMode =
|
||||
nextGlobe?.terrainProvider?.hasVertexNormals === true
|
||||
? 'terrain relief'
|
||||
: 'globe curvature';
|
||||
if (active() && globe === nextGlobe && mode === nextMode) return true;
|
||||
const next = getViewer?.();
|
||||
const port = alive(next) ? globeOf(next) : null;
|
||||
if (globe && globe === port) return true;
|
||||
clear();
|
||||
if (!alive(nextGlobe) || typeof cesium?.Material !== 'function') {
|
||||
if (typeof port?.setSurfaceShading !== 'function') {
|
||||
reason = 'Globe material unavailable';
|
||||
return false;
|
||||
}
|
||||
if (nextGlobe.material != null) {
|
||||
reason = 'Globe material already owned';
|
||||
return false;
|
||||
}
|
||||
// Cesium excludes normal-dependent materials without terrain normals.
|
||||
// The fallback uses existing position/ellipsoid uniforms: curvature only,
|
||||
// never an invented terrain normal or an additional provider request.
|
||||
try {
|
||||
owned = new cesium.Material({
|
||||
fabric: {
|
||||
type:
|
||||
nextMode === 'terrain relief'
|
||||
? 'GEVWindTerrainRelief'
|
||||
: 'GEVWindGlobeCurvature',
|
||||
source: reliefSource(nextMode === 'terrain relief'),
|
||||
},
|
||||
translucent: true,
|
||||
port.setSurfaceShading({
|
||||
kind: 'hillshade',
|
||||
strength: WIND_RELIEF_STRENGTH,
|
||||
});
|
||||
mode = nextMode;
|
||||
globe = nextGlobe;
|
||||
scene = nextScene;
|
||||
previous = globe.material;
|
||||
globe.material = owned;
|
||||
scene.requestRender?.();
|
||||
reason = null;
|
||||
return true;
|
||||
} catch {
|
||||
clear();
|
||||
// The port may hold the request even though it could not draw it;
|
||||
// take it back so it never shows up later, after Wind is off.
|
||||
try {
|
||||
port.setSurfaceShading(null);
|
||||
} catch {
|
||||
// Nothing was kept.
|
||||
}
|
||||
reason = 'Relief material unavailable';
|
||||
return false;
|
||||
}
|
||||
globe = port;
|
||||
viewer = next;
|
||||
reason = null;
|
||||
return true;
|
||||
},
|
||||
clear,
|
||||
destroy() {
|
||||
@@ -102,11 +67,11 @@ export function createWindRelief({ cesium, getViewer } = {}) {
|
||||
},
|
||||
getDiagnostics() {
|
||||
return {
|
||||
active: active(),
|
||||
reason: owned && !active() ? 'Globe material replaced' : reason,
|
||||
active: globe !== null,
|
||||
reason,
|
||||
lighting: 'View-directed display shading',
|
||||
mode: active() ? mode : null,
|
||||
maxOpacity: 0.28,
|
||||
mode: globe ? 'hillshade' : null,
|
||||
maxOpacity: WIND_RELIEF_STRENGTH,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,101 +1,103 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createWindRelief } from './relief.js';
|
||||
import { createWindRelief, WIND_RELIEF_STRENGTH } from './relief.js';
|
||||
|
||||
function fixture({ material = undefined, normals = true } = {}) {
|
||||
const materials = [];
|
||||
class Material {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.destroyed = false;
|
||||
materials.push(this);
|
||||
}
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
destroy() {
|
||||
assert.equal(this.destroyed, false);
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
let renders = 0;
|
||||
const globe = { material, terrainProvider: { hasVertexNormals: normals } };
|
||||
const scene = { globe, requestRender: () => renders++ };
|
||||
const viewer = { scene };
|
||||
const relief = createWindRelief({
|
||||
cesium: { Material },
|
||||
getViewer: () => viewer,
|
||||
// A viewer whose globe port records the shading it is asked for.
|
||||
function fixture({ shading = true } = {}) {
|
||||
const calls = [];
|
||||
const port = (name) => ({
|
||||
name,
|
||||
...(shading
|
||||
? {
|
||||
setSurfaceShading(next) {
|
||||
calls.push([name, next]);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
return { relief, globe, scene, viewer, materials, renders: () => renders };
|
||||
const ports = new Map();
|
||||
const viewer = { isDestroyed: () => false };
|
||||
ports.set(viewer, port('first'));
|
||||
let current = viewer;
|
||||
const relief = createWindRelief({
|
||||
getViewer: () => current,
|
||||
globeOf: (given) => ports.get(given) ?? null,
|
||||
});
|
||||
return {
|
||||
relief,
|
||||
calls,
|
||||
viewer,
|
||||
ports,
|
||||
port,
|
||||
use: (next) => (current = next),
|
||||
};
|
||||
}
|
||||
|
||||
test('relief acquires once and restores the exact prior empty material on clear', () => {
|
||||
for (const material of [null, undefined]) {
|
||||
const f = fixture({ material });
|
||||
f.globe.material = material;
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.equal(f.materials.length, 1);
|
||||
assert.equal(f.globe.material, f.materials[0]);
|
||||
assert.equal(f.relief.getDiagnostics().active, true);
|
||||
f.relief.clear();
|
||||
assert.equal(f.globe.material, material);
|
||||
assert.equal(f.materials[0].destroyed, true);
|
||||
assert.equal(f.renders(), 2);
|
||||
f.relief.clear();
|
||||
assert.equal(f.renders(), 2);
|
||||
assert.equal(f.relief.attach(), true);
|
||||
f.relief.destroy();
|
||||
assert.equal(f.materials[1].destroyed, true);
|
||||
assert.equal(f.relief.attach(), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('pre-existing and replacement material owners are never overwritten', () => {
|
||||
const other = { name: 'other-owner' };
|
||||
const f = fixture({ material: other });
|
||||
assert.equal(f.relief.attach(), false);
|
||||
assert.equal(f.globe.material, other);
|
||||
assert.equal(f.materials.length, 0);
|
||||
f.globe.material = undefined;
|
||||
test('relief asks the globe port for hillshade once and gives it back on clear', () => {
|
||||
const f = fixture();
|
||||
assert.equal(f.relief.attach(), true);
|
||||
f.globe.material = other;
|
||||
assert.equal(f.relief.getDiagnostics().reason, 'Globe material replaced');
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.deepEqual(f.calls, [
|
||||
['first', { kind: 'hillshade', strength: WIND_RELIEF_STRENGTH }],
|
||||
]);
|
||||
assert.equal(WIND_RELIEF_STRENGTH, 0.28);
|
||||
assert.equal(f.relief.getDiagnostics().active, true);
|
||||
assert.equal(f.relief.getDiagnostics().maxOpacity, 0.28);
|
||||
f.relief.clear();
|
||||
assert.equal(f.globe.material, other);
|
||||
assert.equal(f.materials[0].destroyed, true);
|
||||
assert.deepEqual(f.calls.at(-1), ['first', null]);
|
||||
f.relief.clear();
|
||||
assert.equal(f.calls.length, 2, 'a second clear asks nothing');
|
||||
assert.equal(f.relief.getDiagnostics().active, false);
|
||||
assert.equal(f.relief.attach(), true);
|
||||
f.relief.destroy();
|
||||
assert.deepEqual(f.calls.at(-1), ['first', null]);
|
||||
assert.equal(f.relief.attach(), false);
|
||||
f.relief.destroy();
|
||||
assert.equal(f.globe.material, other);
|
||||
assert.equal(f.relief.getDiagnostics().reason, 'Destroyed');
|
||||
});
|
||||
|
||||
test('missing terrain normals uses curvature only and upgrades when normals exist', () => {
|
||||
const f = fixture({ normals: false });
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.equal(f.relief.getDiagnostics().mode, 'globe curvature');
|
||||
const source = f.materials[0].options.fabric.source;
|
||||
assert.doesNotMatch(source, /normalEC|slope/);
|
||||
assert.match(source, /materialInput.positionToEyeEC/);
|
||||
assert.match(source, /czm_ellipsoidInverseRadii/);
|
||||
f.globe.terrainProvider.hasVertexNormals = true;
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.equal(f.materials[0].destroyed, true);
|
||||
assert.equal(f.relief.getDiagnostics().mode, 'terrain relief');
|
||||
assert.match(f.materials[1].options.fabric.source, /materialInput.normalEC/);
|
||||
f.relief.destroy();
|
||||
assert.equal(f.globe.material, undefined);
|
||||
test('a globe with no surface shading, or one that refuses it, is reported', () => {
|
||||
const f = fixture({ shading: false });
|
||||
assert.equal(f.relief.attach(), false);
|
||||
assert.equal(f.relief.getDiagnostics().reason, 'Globe material unavailable');
|
||||
const refusing = fixture();
|
||||
const asked = [];
|
||||
refusing.ports.get(refusing.viewer).setSurfaceShading = (next) => {
|
||||
asked.push(next);
|
||||
if (next) throw new TypeError('no hillshade');
|
||||
};
|
||||
assert.equal(refusing.relief.attach(), false);
|
||||
assert.equal(
|
||||
refusing.relief.getDiagnostics().reason,
|
||||
'Relief material unavailable',
|
||||
);
|
||||
assert.equal(refusing.relief.getDiagnostics().active, false);
|
||||
assert.deepEqual(
|
||||
asked.at(-1),
|
||||
null,
|
||||
'a refused request is taken back so it never shows later',
|
||||
);
|
||||
});
|
||||
|
||||
test('moving to a new viewer releases the old globe and owns only the new one', () => {
|
||||
test('moving to a new viewer releases the old globe and shades only the new one', () => {
|
||||
const f = fixture();
|
||||
f.relief.attach();
|
||||
const old = f.globe;
|
||||
const next = { material: null, terrainProvider: { hasVertexNormals: true } };
|
||||
f.viewer.scene = { globe: next, requestRender() {} };
|
||||
const next = { isDestroyed: () => false };
|
||||
f.ports.set(next, f.port('second'));
|
||||
f.use(next);
|
||||
assert.equal(f.relief.attach(), true);
|
||||
assert.equal(old.material, undefined);
|
||||
assert.equal(f.materials[0].destroyed, true);
|
||||
assert.equal(next.material, f.materials[1]);
|
||||
assert.deepEqual(f.calls, [
|
||||
['first', { kind: 'hillshade', strength: 0.28 }],
|
||||
['first', null],
|
||||
['second', { kind: 'hillshade', strength: 0.28 }],
|
||||
]);
|
||||
f.relief.destroy();
|
||||
assert.equal(next.material, null);
|
||||
assert.deepEqual(f.calls.at(-1), ['second', null]);
|
||||
});
|
||||
|
||||
test('a destroyed viewer is never asked to give the shading back', () => {
|
||||
const f = fixture();
|
||||
f.relief.attach();
|
||||
f.viewer.isDestroyed = () => true;
|
||||
f.relief.clear();
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
+165
-161
@@ -1,16 +1,19 @@
|
||||
import * as Cesium from 'cesium';
|
||||
// The renderer drapes through `findGlobe`, and the layer's inspection marker
|
||||
// reads `findQuery` and `findFrame`; a viewer with no renderer bound gets
|
||||
// those ports from the factories these modules provide.
|
||||
import '../../render/cesium/globe.js';
|
||||
import '../../render/cesium/camera.js';
|
||||
import {
|
||||
createShellSurface,
|
||||
followShellLift,
|
||||
globeImageryHost,
|
||||
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 {
|
||||
canvasOf,
|
||||
findCamera,
|
||||
findDraw,
|
||||
findFrame,
|
||||
findGlobe,
|
||||
findQuery,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { fromDegreesInto } from '../../geo/ellipsoid.js';
|
||||
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
import { createWindGpuRendering } from './gpuRendering.js';
|
||||
@@ -63,25 +66,79 @@ 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, ports) {
|
||||
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 });
|
||||
},
|
||||
ports,
|
||||
);
|
||||
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({
|
||||
cesium = Cesium,
|
||||
container,
|
||||
getViewer,
|
||||
getHost: hostOf,
|
||||
eventTarget = globalThis.window,
|
||||
createGpuRendering = createWindGpuRendering,
|
||||
globeOf = findGlobe,
|
||||
drawOf = findDraw,
|
||||
cameraOf = findCamera,
|
||||
frameOf = findFrame,
|
||||
queryOf = findQuery,
|
||||
onStatusChange,
|
||||
} = {}) {
|
||||
// The host the shell names, else the viewer's globe imagery.
|
||||
const getHost = () =>
|
||||
hostOf?.() ?? {
|
||||
collection:
|
||||
getViewer?.()?.imageryLayers ?? getViewer?.()?.scene?.imageryLayers,
|
||||
kind: 'globe',
|
||||
};
|
||||
const getHost = () => hostOf?.() ?? globeImageryHost(getViewer?.());
|
||||
let canvas = null;
|
||||
let context = null;
|
||||
let snapshot = null;
|
||||
@@ -106,22 +163,15 @@ export function createWindRendering({
|
||||
let bounds = null;
|
||||
let cameraChanged = true;
|
||||
let painted = 0;
|
||||
const gpu = createGpuRendering({ cesium, getViewer });
|
||||
const gpu = createGpuRendering({ getViewer, drawOf });
|
||||
let gpuActive = false;
|
||||
let gpuVisible = false;
|
||||
let reportedGpuReady = null;
|
||||
let gpuNarrow = false;
|
||||
let flowTime = 0;
|
||||
const relief = createWindRelief({ cesium, getViewer });
|
||||
const relief = createWindRelief({ getViewer, globeOf });
|
||||
const signature = Array(8).fill(null);
|
||||
const wind = { u: 0, v: 0 };
|
||||
const before = { lon: 0, lat: 0 };
|
||||
const world =
|
||||
typeof cesium.Cartesian3 === 'function' ? new cesium.Cartesian3() : {};
|
||||
const screenA =
|
||||
typeof cesium.Cartesian2 === 'function' ? new cesium.Cartesian2() : {};
|
||||
const screenB =
|
||||
typeof cesium.Cartesian2 === 'function' ? new cesium.Cartesian2() : {};
|
||||
const world = { x: 0, y: 0, z: 0 };
|
||||
const degree = Math.PI / 180;
|
||||
const hidden = () => globalThis.document?.hidden === true;
|
||||
const still = () => paused || reducedMotion;
|
||||
@@ -137,6 +187,19 @@ export function createWindRendering({
|
||||
const viewer = getViewer?.();
|
||||
return viewer && !viewer.isDestroyed?.() ? viewer : null;
|
||||
};
|
||||
const poseOf = (viewer) => cameraOf(viewer)?.pose?.() ?? null;
|
||||
// The camera's height, or undefined where there is none (or the eye sits
|
||||
// at the earth's centre and it is not a number).
|
||||
const heightOf = (viewer) => {
|
||||
const height = viewer ? poseOf(viewer)?.height : undefined;
|
||||
return Number.isFinite(height) ? height : undefined;
|
||||
};
|
||||
const requestRender = (viewer) => frameOf(viewer)?.requestRender?.('wind');
|
||||
// What a paint projects with: the query port and the eye's position.
|
||||
const viewOf = (viewer) => ({
|
||||
query: queryOf(viewer),
|
||||
eye: poseOf(viewer)?.position ?? null,
|
||||
});
|
||||
|
||||
function cancel() {
|
||||
if (frame !== null) globalThis.cancelAnimationFrame(frame);
|
||||
@@ -149,7 +212,7 @@ export function createWindRendering({
|
||||
canvas &&
|
||||
!hidden() &&
|
||||
!still() &&
|
||||
(!gpuActive || gpuVisible) &&
|
||||
!gpuActive &&
|
||||
frame === null
|
||||
)
|
||||
frame = globalThis.requestAnimationFrame(draw);
|
||||
@@ -160,10 +223,9 @@ export function createWindRendering({
|
||||
|
||||
function resize(viewer) {
|
||||
const ratio = Math.min(2, globalThis.devicePixelRatio || 1);
|
||||
cssWidth =
|
||||
viewer?.scene?.canvas?.clientWidth || container?.clientWidth || 1;
|
||||
cssHeight =
|
||||
viewer?.scene?.canvas?.clientHeight || container?.clientHeight || 1;
|
||||
const surface = canvasOf(viewer);
|
||||
cssWidth = surface?.clientWidth || container?.clientWidth || 1;
|
||||
cssHeight = surface?.clientHeight || container?.clientHeight || 1;
|
||||
const width = Math.max(1, Math.floor(cssWidth * ratio));
|
||||
const height = Math.max(1, Math.floor(cssHeight * ratio));
|
||||
// Assigning even unchanged dimensions erases a real canvas.
|
||||
@@ -176,16 +238,16 @@ export function createWindRendering({
|
||||
return true;
|
||||
}
|
||||
|
||||
function checkCamera(scene) {
|
||||
const camera = scene.camera;
|
||||
const position = camera?.positionWC;
|
||||
function checkCamera(viewer) {
|
||||
const pose = poseOf(viewer);
|
||||
const position = pose?.position;
|
||||
const values = [
|
||||
position?.x,
|
||||
position?.y,
|
||||
position?.z,
|
||||
camera?.heading,
|
||||
camera?.pitch,
|
||||
camera?.roll,
|
||||
pose?.heading,
|
||||
pose?.pitch,
|
||||
pose?.roll,
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
];
|
||||
@@ -197,16 +259,17 @@ export function createWindRendering({
|
||||
return changed;
|
||||
}
|
||||
|
||||
function updateBounds(scene) {
|
||||
function updateBounds(viewer) {
|
||||
bounds = null;
|
||||
if (!scene.camera?.computeViewRectangle || !cesium.Ellipsoid) return;
|
||||
const camera = cameraOf(viewer);
|
||||
if (!camera?.viewRectangle) return;
|
||||
try {
|
||||
const rect = scene.camera.computeViewRectangle(cesium.Ellipsoid.WGS84);
|
||||
const rect = camera.viewRectangle();
|
||||
if (!rect) return;
|
||||
const west = rect.west / degree;
|
||||
let east = rect.east / degree;
|
||||
const south = Math.max(-89, rect.south / degree);
|
||||
const north = Math.min(89, rect.north / degree);
|
||||
const west = rect.west;
|
||||
let east = rect.east;
|
||||
const south = Math.max(-89, rect.south);
|
||||
const north = Math.min(89, rect.north);
|
||||
if (east < west) east += 360;
|
||||
if (
|
||||
[west, east, south, north].every(Number.isFinite) &&
|
||||
@@ -224,34 +287,12 @@ export function createWindRendering({
|
||||
}
|
||||
}
|
||||
|
||||
function makeOccluder(scene) {
|
||||
if (
|
||||
!cesium.EllipsoidalOccluder ||
|
||||
!cesium.Ellipsoid ||
|
||||
!scene.camera?.positionWC
|
||||
)
|
||||
function project(view, lon, lat) {
|
||||
if (!Number.isFinite(lon) || !Number.isFinite(lat) || !view.query)
|
||||
return null;
|
||||
return new cesium.EllipsoidalOccluder(
|
||||
cesium.Ellipsoid.WGS84,
|
||||
scene.camera.positionWC,
|
||||
);
|
||||
}
|
||||
|
||||
function project(scene, occluder, lon, lat, result) {
|
||||
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
|
||||
const point = cesium.Cartesian3.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
0,
|
||||
cesium.Ellipsoid?.WGS84,
|
||||
world,
|
||||
);
|
||||
if (occluder && !occluder.isPointVisible(point)) return null;
|
||||
const projected = cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
point,
|
||||
result,
|
||||
);
|
||||
const point = fromDegreesInto(lon, lat, 0, world);
|
||||
if (view.eye && view.query.isOccluded?.(point)) return null;
|
||||
const projected = view.query.project(point);
|
||||
if (
|
||||
!projected ||
|
||||
!Number.isFinite(projected.x) ||
|
||||
@@ -259,7 +300,7 @@ export function createWindRendering({
|
||||
)
|
||||
return null;
|
||||
// A perspective surface normal dims the limb instead of accumulating a bright rim.
|
||||
const camera = scene.camera?.positionWC;
|
||||
const camera = view.eye;
|
||||
const dx = camera?.x - point.x;
|
||||
const dy = camera?.y - point.y;
|
||||
const dz = camera?.z - point.z;
|
||||
@@ -281,7 +322,7 @@ export function createWindRendering({
|
||||
point.x <= cssWidth &&
|
||||
point.y <= cssHeight;
|
||||
|
||||
function spawn(particle, scene, occluder) {
|
||||
function spawn(particle, view) {
|
||||
for (let attempt = 0; attempt < 6; attempt++) {
|
||||
const west = bounds?.west ?? -180;
|
||||
const east = bounds?.east ?? 180;
|
||||
@@ -291,17 +332,16 @@ export function createWindRendering({
|
||||
particle.lat = Math.asin(low + Math.random() * (high - low)) / degree;
|
||||
particle.age = 1 + Math.random() * 7;
|
||||
particle.life = 8 + Math.random() * 4;
|
||||
if (inView(project(scene, occluder, particle.lon, particle.lat, screenA)))
|
||||
return;
|
||||
if (inView(project(view, particle.lon, particle.lat))) return;
|
||||
}
|
||||
}
|
||||
function seed(scene, occluder) {
|
||||
function seed(viewer, view = viewOf(viewer)) {
|
||||
const count = budget();
|
||||
if (particles.length > count) particles.length = count;
|
||||
while (particles.length < count)
|
||||
particles.push({ lon: 0, lat: 0, age: 0, life: 10 });
|
||||
updateBounds(scene);
|
||||
for (const particle of particles) spawn(particle, scene, occluder);
|
||||
updateBounds(viewer);
|
||||
for (const particle of particles) spawn(particle, view);
|
||||
}
|
||||
|
||||
function removeImagery() {
|
||||
@@ -313,16 +353,15 @@ export function createWindRendering({
|
||||
shell = null;
|
||||
imageryKind = null;
|
||||
}
|
||||
function updateImageryFade(camera, settled = false) {
|
||||
function updateImageryFade(height, settled = false) {
|
||||
// The tileset shell keeps the quantised move-end fade; globe imagery keeps
|
||||
// its smooth per-frame fade.
|
||||
if (
|
||||
(!imagery && !shell) ||
|
||||
!camera?.positionCartographic ||
|
||||
!Number.isFinite(height) ||
|
||||
(imageryKind === 'tileset' && !settled)
|
||||
)
|
||||
return;
|
||||
const height = camera.positionCartographic.height;
|
||||
const fade = !gpuActive
|
||||
? 1
|
||||
: height <= WIND_FIELD_FADE_LOW_METERS
|
||||
@@ -362,7 +401,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,17 +415,16 @@ 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,
|
||||
{ cameraOf, frameOf },
|
||||
);
|
||||
imageryKind = kind;
|
||||
shell.setAlpha(overlay === 'temperature' ? 1 : 0.85);
|
||||
updateImageryFade(viewer.scene.camera, true);
|
||||
viewer.scene?.requestRender?.();
|
||||
updateImageryFade(heightOf(viewer), true);
|
||||
requestRender(viewer);
|
||||
return;
|
||||
}
|
||||
imagery = globe.imagery.add({
|
||||
@@ -399,11 +438,11 @@ export function createWindRendering({
|
||||
// Temperature colors carry quantitative meaning; double transparency
|
||||
// blends orange heat into blue ocean and obscures useful gradients.
|
||||
imagery.alpha = overlay === 'temperature' ? 1 : 0.85;
|
||||
if (gpuActive) updateImageryFade(viewer.scene.camera, true);
|
||||
if (gpuActive) updateImageryFade(heightOf(viewer), true);
|
||||
imageryErrorRemove = imagery.on('tileError', () => {
|
||||
imageryError = msg('Globe field image unavailable');
|
||||
});
|
||||
viewer.scene?.requestRender?.();
|
||||
requestRender(viewer);
|
||||
} catch {
|
||||
removeImagery();
|
||||
imageryError = msg('Globe field image unavailable');
|
||||
@@ -426,10 +465,10 @@ export function createWindRendering({
|
||||
const show = kind !== 'none' && imagery?.alpha > 0;
|
||||
if (imagery && imagery.show !== show) {
|
||||
imagery.show = show;
|
||||
viewerReady()?.scene?.requestRender?.();
|
||||
requestRender(viewerReady());
|
||||
}
|
||||
if ((gpuActive || kind === 'tileset') && kind !== 'none')
|
||||
updateImageryFade(viewerReady()?.scene?.camera, true);
|
||||
updateImageryFade(heightOf(viewerReady()), true);
|
||||
if (kind === 'none') imageryError = NO_IMAGERY_HOST;
|
||||
else if (wasHidden) {
|
||||
imageryError = null;
|
||||
@@ -442,39 +481,33 @@ export function createWindRendering({
|
||||
function viewChanged() {
|
||||
if (gpuActive) {
|
||||
const viewer = viewerReady();
|
||||
if (viewer) updateImageryFade(viewer.scene.camera);
|
||||
const narrow = (viewer?.scene?.canvas?.clientWidth || 800) < 700;
|
||||
if (viewer) updateImageryFade(heightOf(viewer));
|
||||
const narrow = (canvasOf(viewer)?.clientWidth || 800) < 700;
|
||||
let visibilityUpdated = false;
|
||||
if (running && field && !hidden() && narrow !== gpuNarrow) {
|
||||
gpuNarrow = narrow;
|
||||
gpuActive = gpu.setField(field);
|
||||
if (!gpuActive && viewer) {
|
||||
resize(viewer);
|
||||
seed(viewer.scene, makeOccluder(viewer.scene));
|
||||
seed(viewer);
|
||||
}
|
||||
motionChanged();
|
||||
visibilityUpdated = true;
|
||||
}
|
||||
if (gpuActive && viewer && !visibilityUpdated) {
|
||||
gpuVisible = gpu.updateVisibility(viewer.scene.camera);
|
||||
if (gpuVisible) schedule();
|
||||
else {
|
||||
cancel();
|
||||
lastTime = null;
|
||||
}
|
||||
}
|
||||
// The renderer culls and animates the streamlines; this fades them.
|
||||
if (gpuActive && viewer && !visibilityUpdated) gpu.updateVisibility();
|
||||
const ready = gpuActive ? gpu.getDiagnostics().ready : null;
|
||||
if (ready !== reportedGpuReady) {
|
||||
reportedGpuReady = ready;
|
||||
onStatusChange?.();
|
||||
}
|
||||
return; // Cesium projects persistent curves; only a responsive budget change rebuilds them.
|
||||
return; // The renderer projects persistent curves; only a responsive budget change rebuilds them.
|
||||
}
|
||||
if (!running || !field || hidden() || !canvas) return;
|
||||
const viewer = viewerReady();
|
||||
if (!viewer) return;
|
||||
const resized = resize(viewer);
|
||||
if (resized || checkCamera(viewer.scene)) {
|
||||
if (resized || checkCamera(viewer)) {
|
||||
cameraChanged = true;
|
||||
if (still()) paint(viewer, 0, true);
|
||||
else schedule();
|
||||
@@ -489,13 +522,8 @@ export function createWindRendering({
|
||||
if (!running || !field || hidden()) return;
|
||||
const viewer = viewerReady();
|
||||
if (gpuActive) {
|
||||
if (viewer) updateImageryFade(viewer.scene.camera);
|
||||
gpuVisible = viewer ? gpu.updateVisibility(viewer.scene.camera) : false;
|
||||
if (gpuVisible) {
|
||||
gpu.tick(flowTime);
|
||||
viewer.scene.requestRender();
|
||||
schedule();
|
||||
}
|
||||
if (viewer) updateImageryFade(heightOf(viewer));
|
||||
if (viewer) gpu.updateVisibility();
|
||||
return;
|
||||
}
|
||||
if (still() && viewer) paint(viewer, 0, true);
|
||||
@@ -508,23 +536,18 @@ export function createWindRendering({
|
||||
}
|
||||
function cameraSettled() {
|
||||
if (gpuActive || imageryKind === 'tileset')
|
||||
updateImageryFade(viewerReady()?.scene?.camera, true);
|
||||
updateImageryFade(heightOf(viewerReady()), true);
|
||||
cameraMoved();
|
||||
}
|
||||
function cameraMoved() {
|
||||
viewChanged();
|
||||
// A parked request-render scene may never run preRender until we wake it.
|
||||
if (gpuActive && running && field && !hidden())
|
||||
viewerReady()?.scene?.requestRender?.();
|
||||
requestRender(viewerReady());
|
||||
}
|
||||
function listenScene(event, callback) {
|
||||
if (!event?.addEventListener) return;
|
||||
const remove = event.addEventListener(callback);
|
||||
removers.push(
|
||||
typeof remove === 'function'
|
||||
? remove
|
||||
: () => event.removeEventListener(callback),
|
||||
);
|
||||
function listenPort(port, event, callback) {
|
||||
const off = port?.on?.(event, () => callback());
|
||||
if (typeof off === 'function') removers.push(off);
|
||||
}
|
||||
function attachListeners() {
|
||||
if (removers.length) return;
|
||||
@@ -535,9 +558,9 @@ export function createWindRendering({
|
||||
listen(globalThis, 'resize', cameraMoved);
|
||||
listen(eventTarget, 'gev:map-stack-changed', rehome);
|
||||
const viewer = viewerReady();
|
||||
const camera = viewer?.scene?.camera;
|
||||
listenScene(viewer?.scene?.preRender, viewChanged);
|
||||
listenScene(camera?.moveEnd, cameraSettled);
|
||||
if (!viewer) return;
|
||||
listenPort(frameOf(viewer), 'preRender', viewChanged);
|
||||
listenPort(cameraOf(viewer), 'moveEnd', cameraSettled);
|
||||
}
|
||||
function detachListeners() {
|
||||
for (const remove of removers) remove();
|
||||
@@ -546,16 +569,15 @@ export function createWindRendering({
|
||||
}
|
||||
|
||||
function paint(viewer, dt, staticFrame, fadeSeconds = dt) {
|
||||
const scene = viewer.scene;
|
||||
const resized = resize(viewer);
|
||||
const changed = checkCamera(scene) || cameraChanged || resized;
|
||||
const occluder = makeOccluder(scene);
|
||||
const changed = checkCamera(viewer) || cameraChanged || resized;
|
||||
const view = viewOf(viewer);
|
||||
if (changed) {
|
||||
clearPixels();
|
||||
updateBounds(scene);
|
||||
updateBounds(viewer);
|
||||
cameraChanged = false;
|
||||
}
|
||||
if (particles.length !== budget()) seed(scene, occluder);
|
||||
if (particles.length !== budget()) seed(viewer, view);
|
||||
if (staticFrame) clearPixels();
|
||||
context.globalAlpha = 1;
|
||||
context.globalCompositeOperation = 'destination-out';
|
||||
@@ -563,7 +585,7 @@ export function createWindRendering({
|
||||
context.fillRect(0, 0, cssWidth, cssHeight);
|
||||
context.globalCompositeOperation = 'source-over';
|
||||
context.lineCap = 'round';
|
||||
const cameraHeight = scene.camera?.positionCartographic?.height ?? 1e6;
|
||||
const cameraHeight = heightOf(viewer) ?? 1e6;
|
||||
const speedScale = Math.max(0.002, Math.min(4000, cameraHeight / 400));
|
||||
const advection = { speedScale };
|
||||
// Stroke length is a display sample of the local field, not frame travel.
|
||||
@@ -577,27 +599,21 @@ export function createWindRendering({
|
||||
advectParticle(particle, wind, dt, advection);
|
||||
particle.age += dt;
|
||||
}
|
||||
let point = project(scene, occluder, particle.lon, particle.lat, screenB);
|
||||
let point = project(view, particle.lon, particle.lat);
|
||||
if (changed && !inView(point)) {
|
||||
// Refill newly exposed regions while retaining world anchors still in view.
|
||||
spawn(particle, scene, occluder);
|
||||
spawn(particle, view);
|
||||
sampleWind(field, particle.lon, particle.lat, wind);
|
||||
point = project(scene, occluder, particle.lon, particle.lat, screenB);
|
||||
point = project(view, particle.lon, particle.lat);
|
||||
}
|
||||
if (particle.age > particle.life || !inView(point)) {
|
||||
spawn(particle, scene, occluder);
|
||||
spawn(particle, view);
|
||||
continue;
|
||||
}
|
||||
before.lon = particle.lon;
|
||||
before.lat = particle.lat;
|
||||
advectParticle(before, wind, -strokeSeconds, advection);
|
||||
const previous = project(
|
||||
scene,
|
||||
occluder,
|
||||
before.lon,
|
||||
before.lat,
|
||||
screenA,
|
||||
);
|
||||
const previous = project(view, before.lon, before.lat);
|
||||
if (!inView(previous)) continue;
|
||||
const startX = previous.x;
|
||||
const startY = previous.y;
|
||||
@@ -653,26 +669,17 @@ export function createWindRendering({
|
||||
|
||||
function draw(time) {
|
||||
frame = null;
|
||||
if (!running || !field || hidden() || still()) return;
|
||||
if (gpuActive && !gpuVisible) {
|
||||
lastTime = null;
|
||||
return;
|
||||
}
|
||||
if (!running || !field || hidden() || still() || gpuActive) return;
|
||||
const viewer = viewerReady();
|
||||
if (!viewer) return;
|
||||
try {
|
||||
const resized = !gpuActive && resize(viewer);
|
||||
const resized = resize(viewer);
|
||||
if (resized) cameraChanged = true;
|
||||
const elapsed =
|
||||
lastTime === null ? 1 / 60 : Math.max(0, (time - lastTime) / 1000);
|
||||
// Limit full particle paints to 30 Hz while preserving elapsed-time motion/fading.
|
||||
if (lastTime === null || elapsed >= 0.032 || cameraChanged) {
|
||||
if (gpuActive) {
|
||||
flowTime += elapsed;
|
||||
gpu.tick(flowTime);
|
||||
viewer.scene.requestRender();
|
||||
cameraChanged = false;
|
||||
} else paint(viewer, Math.min(0.1, elapsed), false, elapsed);
|
||||
paint(viewer, Math.min(0.1, elapsed), false, elapsed);
|
||||
lastTime = time;
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -705,7 +712,7 @@ export function createWindRendering({
|
||||
? { ...next.grid, u: next.u, v: next.v }
|
||||
: next;
|
||||
const viewer = viewerReady();
|
||||
const nextNarrow = (viewer?.scene?.canvas?.clientWidth || 800) < 700;
|
||||
const nextNarrow = (canvasOf(viewer)?.clientWidth || 800) < 700;
|
||||
const reuseGeometry =
|
||||
gpuActive &&
|
||||
gpuNarrow === nextNarrow &&
|
||||
@@ -721,13 +728,12 @@ export function createWindRendering({
|
||||
if (!reuseGeometry) {
|
||||
gpuActive = gpu.supported() && gpu.setField(field);
|
||||
reportedGpuReady = gpuActive ? gpu.getDiagnostics().ready : null;
|
||||
flowTime = 0;
|
||||
}
|
||||
clearPixels();
|
||||
particles = [];
|
||||
if (viewer && !gpuActive) {
|
||||
resize(viewer);
|
||||
seed(viewer.scene, makeOccluder(viewer.scene));
|
||||
seed(viewer);
|
||||
}
|
||||
installImagery();
|
||||
relief.attach();
|
||||
@@ -775,9 +781,7 @@ export function createWindRendering({
|
||||
gpu.clear();
|
||||
relief.clear();
|
||||
gpuActive = false;
|
||||
gpuVisible = false;
|
||||
reportedGpuReady = null;
|
||||
flowTime = 0;
|
||||
removeImagery();
|
||||
imageryError = null;
|
||||
clearPixels();
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
import { createWindRendering } from './rendering.js';
|
||||
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
|
||||
import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js';
|
||||
import {
|
||||
createShellCesium,
|
||||
createShellScene,
|
||||
renderShells,
|
||||
} from '../weather/shellFixture.mjs';
|
||||
import { createCesiumFields } from '../../render/cesium/drawFields.js';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
|
||||
function event() {
|
||||
const listeners = new Set();
|
||||
@@ -177,6 +178,7 @@ function harness({
|
||||
const viewer = {
|
||||
container,
|
||||
imageryLayers,
|
||||
canvas,
|
||||
scene: {
|
||||
canvas,
|
||||
camera: {
|
||||
@@ -197,34 +199,49 @@ function harness({
|
||||
},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
const cesium = {
|
||||
...(shell ? createShellCesium() : {}),
|
||||
GeographicTilingScheme: Cesium.GeographicTilingScheme,
|
||||
Credit: Cesium.Credit,
|
||||
Event: Cesium.Event,
|
||||
Cartesian3: { fromDegrees: (lon, lat) => ({ lon, lat }) },
|
||||
Ellipsoid: { WGS84: {} },
|
||||
Rectangle: { MAX_VALUE: {} },
|
||||
EllipsoidalOccluder: class {
|
||||
isPointVisible() {
|
||||
return !occluded;
|
||||
}
|
||||
},
|
||||
SceneTransforms: {
|
||||
worldToWindowCoordinates: projected ?? (() => ({ x: 100, y: 100 })),
|
||||
},
|
||||
SingleTileImageryProvider: class {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.errorEvent = event();
|
||||
}
|
||||
const shellCesium = shell ? createShellCesium() : null;
|
||||
// The camera, frame and query ports over the doubles above, read live.
|
||||
const cameraPort = {
|
||||
pose() {
|
||||
const camera = viewer.scene.camera;
|
||||
return {
|
||||
position: camera.positionWC,
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
height: camera.positionCartographic?.height,
|
||||
};
|
||||
},
|
||||
viewRectangle: () => viewer.scene.camera.viewRectangle?.() ?? null,
|
||||
on: (name, cb) =>
|
||||
name === 'moveEnd'
|
||||
? viewer.scene.camera.moveEnd.addEventListener(cb)
|
||||
: () => {},
|
||||
};
|
||||
const framePort = {
|
||||
on: (name, cb) =>
|
||||
name === 'preRender' ? preRender.addEventListener(cb) : () => {},
|
||||
requestRender: () => viewer.scene.requestRender(),
|
||||
};
|
||||
// Projections see the point as degrees, as the doubles above were written.
|
||||
const project = projected ?? (() => ({ x: 100, y: 100 }));
|
||||
const queryPort = {
|
||||
isOccluded: () => occluded,
|
||||
project: (point) => project(viewer.scene, toLonLatH(point)),
|
||||
};
|
||||
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),
|
||||
cameraOf: (given) => (given === viewer ? cameraPort : null),
|
||||
frameOf: (given) => (given === viewer ? framePort : null),
|
||||
queryOf: (given) => (given === viewer ? queryPort : null),
|
||||
createGpuRendering,
|
||||
onStatusChange,
|
||||
getHost,
|
||||
@@ -245,7 +262,7 @@ function harness({
|
||||
motion,
|
||||
preRender,
|
||||
viewer,
|
||||
cesium,
|
||||
cesium: shellCesium,
|
||||
imagery,
|
||||
removed,
|
||||
primitives: () => shellScene?.primitives.items ?? [],
|
||||
@@ -444,11 +461,11 @@ test('scalar imagery builds once, survives pause, replaces cleanly, and releases
|
||||
|
||||
for (const overlay of ['speed', 'pressure', 'temperature']) {
|
||||
test(`${overlay} imagery fades with log camera height and resumes from idle`, () => {
|
||||
let camera = null;
|
||||
const gpu = {
|
||||
supported: () => true,
|
||||
setField: () => true,
|
||||
updateVisibility: (camera) => camera.positionCartographic.height > 15000,
|
||||
tick() {},
|
||||
updateVisibility: () => camera.positionCartographic.height > 15000,
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
@@ -456,7 +473,7 @@ for (const overlay of ['speed', 'pressure', 'temperature']) {
|
||||
getDiagnostics: () => ({ ready: true }),
|
||||
};
|
||||
const h = harness({ createGpuRendering: () => gpu });
|
||||
const camera = h.viewer.scene.camera;
|
||||
camera = h.viewer.scene.camera;
|
||||
const baseAlpha = overlay === 'temperature' ? 1 : 0.85;
|
||||
const snapshot = {
|
||||
grid: FIELD,
|
||||
@@ -586,11 +603,11 @@ test('a large camera move immediately refills the newly visible region', () => {
|
||||
y: 300 + point.lat * 20,
|
||||
}),
|
||||
});
|
||||
h.viewer.scene.camera.computeViewRectangle = () => ({
|
||||
west: ((center - 10) * Math.PI) / 180,
|
||||
east: ((center + 10) * Math.PI) / 180,
|
||||
south: (-10 * Math.PI) / 180,
|
||||
north: (10 * Math.PI) / 180,
|
||||
h.viewer.scene.camera.viewRectangle = () => ({
|
||||
west: center - 10,
|
||||
east: center + 10,
|
||||
south: -10,
|
||||
north: 10,
|
||||
});
|
||||
h.rendering.attach();
|
||||
h.rendering.setField(FIELD);
|
||||
@@ -615,11 +632,11 @@ test('world-anchored wind glyphs remain readable at low FPS without accelerating
|
||||
y: 300 + point.lat * 20,
|
||||
}),
|
||||
});
|
||||
h.viewer.scene.camera.computeViewRectangle = () => ({
|
||||
west: (-5 * Math.PI) / 180,
|
||||
east: (5 * Math.PI) / 180,
|
||||
south: (-0.001 * Math.PI) / 180,
|
||||
north: (0.001 * Math.PI) / 180,
|
||||
h.viewer.scene.camera.viewRectangle = () => ({
|
||||
west: -5,
|
||||
east: 5,
|
||||
south: -0.001,
|
||||
north: 0.001,
|
||||
});
|
||||
h.rendering.attach();
|
||||
h.rendering.setField(FIELD);
|
||||
@@ -664,11 +681,11 @@ test('world-anchored wind glyphs remain readable at low FPS without accelerating
|
||||
h.rendering.destroy();
|
||||
});
|
||||
|
||||
test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pauses cleanly', () => {
|
||||
test('GPU flow leaves animation to the renderer, rebuilds only across viewport budgets, and pauses cleanly', () => {
|
||||
let builds = 0,
|
||||
ticks = 0,
|
||||
cleared = 0,
|
||||
destroyed = 0;
|
||||
const options = [];
|
||||
const gpu = {
|
||||
supported: () => true,
|
||||
updateVisibility: () => true,
|
||||
@@ -677,10 +694,9 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa
|
||||
builds++;
|
||||
return true;
|
||||
},
|
||||
tick() {
|
||||
ticks++;
|
||||
setOptions(value) {
|
||||
options.push(value.paused);
|
||||
},
|
||||
setOptions() {},
|
||||
clear() {
|
||||
cleared++;
|
||||
},
|
||||
@@ -691,16 +707,12 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa
|
||||
getDiagnostics: () => ({ ready: true, pathCount: 1 }),
|
||||
};
|
||||
const h = harness({ createGpuRendering: () => gpu });
|
||||
let renders = 0;
|
||||
h.viewer.scene.requestRender = () => {
|
||||
renders++;
|
||||
};
|
||||
h.rendering.attach();
|
||||
h.rendering.setField({ grid: FIELD, u: FIELD.u, v: FIELD.v });
|
||||
h.rendering.start();
|
||||
h.callbacks.shift()(16);
|
||||
assert.equal(h.rendering.getDiagnostics().renderMode, 'gpu-streamlines');
|
||||
assert.ok(ticks > 0 && renders > 0);
|
||||
assert.equal(h.pending.size, 0, 'the renderer moves the highlight');
|
||||
assert.equal(options.at(-1), false);
|
||||
assert.equal(h.strokes.length, 0);
|
||||
h.viewer.scene.camera.positionWC.x = 10;
|
||||
h.preRender.emit();
|
||||
@@ -710,7 +722,7 @@ test('GPU flow uses one scheduler, rebuilds only across viewport budgets, and pa
|
||||
'camera changes project geometry without rebuilding paths',
|
||||
);
|
||||
h.rendering.setOptions({ paused: true });
|
||||
assert.equal(h.pending.size, 0);
|
||||
assert.equal(options.at(-1), true, 'the pause reaches the renderer');
|
||||
h.canvas.clientWidth = 390;
|
||||
h.preRender.emit();
|
||||
assert.equal(builds, 2, 'crossing the narrow viewport boundary rebakes once');
|
||||
@@ -735,7 +747,6 @@ for (const paused of [false, true]) {
|
||||
ready = false;
|
||||
return true;
|
||||
},
|
||||
tick() {},
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
@@ -787,9 +798,8 @@ for (const paused of [false, true]) {
|
||||
});
|
||||
}
|
||||
|
||||
test('scalar snapshots retain identical GPU wind geometry and animation phase', () => {
|
||||
test('scalar snapshots retain identical GPU wind geometry, and so its animation phase', () => {
|
||||
let builds = 0;
|
||||
const times = [];
|
||||
const gpu = {
|
||||
supported: () => true,
|
||||
updateVisibility: () => true,
|
||||
@@ -797,9 +807,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase',
|
||||
builds++;
|
||||
return true;
|
||||
},
|
||||
tick(time) {
|
||||
times.push(time);
|
||||
},
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
@@ -824,9 +831,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase',
|
||||
h.rendering.attach();
|
||||
h.rendering.setField(snapshot());
|
||||
h.rendering.start();
|
||||
h.callbacks.shift()(16);
|
||||
h.callbacks.shift()(1016);
|
||||
const phase = times.at(-1);
|
||||
h.rendering.setOptions({ overlay: 'temperature' });
|
||||
h.rendering.setField(
|
||||
snapshot({
|
||||
@@ -843,11 +847,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase',
|
||||
'freshly decoded equal arrays reuse the worker-built primitive',
|
||||
);
|
||||
assert.equal(h.imagery.length, 1, 'new scalar field is still installed');
|
||||
h.callbacks.shift()(1032);
|
||||
assert.ok(
|
||||
times.at(-1) >= phase,
|
||||
'scalar acquisition does not reset travelling highlights',
|
||||
);
|
||||
h.rendering.setField(
|
||||
snapshot({
|
||||
scalar: {
|
||||
@@ -890,7 +889,6 @@ for (const [label, change] of Object.entries({
|
||||
builds++;
|
||||
return true;
|
||||
},
|
||||
tick() {},
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
@@ -918,25 +916,25 @@ for (const [label, change] of Object.entries({
|
||||
}
|
||||
|
||||
for (const eventName of ['preRender', 'moveEnd']) {
|
||||
test(`GPU height suspension resumes from camera ${eventName} without preRender`, () => {
|
||||
const times = [];
|
||||
test(`GPU height fade follows camera ${eventName} with no frames of its own`, () => {
|
||||
let visible = false;
|
||||
let inFrustum = true;
|
||||
let fades = 0;
|
||||
const options = [];
|
||||
const gpu = {
|
||||
supported: () => true,
|
||||
setField: () => true,
|
||||
updateVisibility(camera) {
|
||||
visible = camera.positionCartographic.height > 15000 && inFrustum;
|
||||
updateVisibility() {
|
||||
fades++;
|
||||
visible = camera.positionCartographic.height > 15000;
|
||||
return visible;
|
||||
},
|
||||
tick(time) {
|
||||
times.push(time);
|
||||
setOptions(value) {
|
||||
options.push(value.paused);
|
||||
},
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
getParticleCount: () => 1,
|
||||
getDiagnostics: () => ({ ready: true, visibleCells: Number(visible) }),
|
||||
getDiagnostics: () => ({ ready: true }),
|
||||
};
|
||||
const h = harness({ createGpuRendering: () => gpu });
|
||||
const camera = h.viewer.scene.camera;
|
||||
@@ -949,52 +947,27 @@ for (const eventName of ['preRender', 'moveEnd']) {
|
||||
h.preRender.emit();
|
||||
assert.equal(h.pending.size, 0);
|
||||
assert.equal(renders, 0);
|
||||
assert.equal(times.length, 0);
|
||||
assert.equal(visible, false);
|
||||
assert.equal(camera.percentageChanged, 0.5);
|
||||
assert.equal(camera.changed.size, 0);
|
||||
|
||||
camera.positionCartographic.height = 60000;
|
||||
const before = fades;
|
||||
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
|
||||
assert.ok(fades > before, 'the fade follows the camera');
|
||||
assert.equal(visible, true);
|
||||
assert.equal(
|
||||
renders,
|
||||
eventName === 'preRender' ? 0 : 1,
|
||||
'moveEnd wakes the parked scene',
|
||||
);
|
||||
assert.equal(h.pending.size, 1);
|
||||
h.callbacks.shift()(16);
|
||||
assert.equal(times.length, 1);
|
||||
const phase = times.at(-1);
|
||||
const queued = h.callbacks.shift();
|
||||
camera.positionCartographic.height = 15000;
|
||||
h.preRender.emit();
|
||||
const parkedRenders = renders;
|
||||
queued(100000);
|
||||
assert.equal(h.pending.size, 0);
|
||||
assert.equal(renders, parkedRenders);
|
||||
assert.equal(times.length, 1, 'parked draw cannot tick or advance phase');
|
||||
|
||||
camera.positionCartographic.height = 60000;
|
||||
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
|
||||
h.callbacks.shift()(200000);
|
||||
assert.ok(
|
||||
times.at(-1) - phase < 0.1,
|
||||
'idle time does not jump animation phase',
|
||||
);
|
||||
inFrustum = false;
|
||||
h.preRender.emit();
|
||||
assert.equal(h.pending.size, 0, 'frustum-hidden cells also park');
|
||||
inFrustum = true;
|
||||
assert.equal(h.pending.size, 0, 'the renderer animates, not the layer');
|
||||
h.rendering.setOptions({ paused: true });
|
||||
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
|
||||
assert.equal(h.pending.size, 0, 'camera events respect pause');
|
||||
assert.equal(options.at(-1), true);
|
||||
h.rendering.setOptions({ paused: false });
|
||||
globalThis.document.hidden = true;
|
||||
h.visibility.emit();
|
||||
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
|
||||
assert.equal(h.pending.size, 0, 'camera events respect hidden documents');
|
||||
globalThis.document.hidden = false;
|
||||
h.visibility.emit();
|
||||
assert.equal(h.pending.size, 1);
|
||||
assert.equal(options.at(-1), false);
|
||||
h.rendering.stop();
|
||||
assert.equal(options.at(-1), true, 'a stopped layer holds the flow still');
|
||||
h.rendering.destroy();
|
||||
assert.equal(h.pending.size, 0);
|
||||
assert.equal(camera.changed.size, 0);
|
||||
@@ -1028,10 +1001,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]);
|
||||
@@ -1094,7 +1071,6 @@ for (const overlay of ['speed', 'temperature', 'pressure']) {
|
||||
supported: () => true,
|
||||
setField: () => true,
|
||||
updateVisibility: () => true,
|
||||
tick() {},
|
||||
setOptions() {},
|
||||
clear() {},
|
||||
destroy() {},
|
||||
@@ -1121,6 +1097,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 +1162,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;
|
||||
|
||||
@@ -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()),
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
/**
|
||||
* @module render/cesium/drawFields
|
||||
* @description The Cesium draw port's `field` handles. It draws two kinds:
|
||||
* `windStreamlines` (drawStreamlines.js) and `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 (`scalarRaster`) 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';
|
||||
import { createWindStreamlines } from './drawStreamlines.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);
|
||||
if (spec?.kind === 'windStreamlines') {
|
||||
const handle = createWindStreamlines({
|
||||
scene,
|
||||
spec,
|
||||
report,
|
||||
cesium,
|
||||
onDispose: () => {
|
||||
if (fields.get(spec.id) === handle) fields.delete(spec.id);
|
||||
},
|
||||
});
|
||||
fields.set(spec.id, handle);
|
||||
return handle;
|
||||
}
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
@@ -0,0 +1,469 @@
|
||||
/**
|
||||
* @module render/cesium/drawStreamlines
|
||||
* @description The Cesium draw port's `windStreamlines` fields: paths
|
||||
* traced once through the wind grid (`bakeWindStreamlines`), drawn as
|
||||
* polylines at `heightM` in 30° cells, each a primitive of its own. A
|
||||
* highlight moves along each path in the wind's direction; a faint ghost
|
||||
* of the whole path stays. Cells the eye cannot see (behind the Earth or
|
||||
* outside the view) are not drawn, and nothing animates while no cell is.
|
||||
*
|
||||
* Choices the contract leaves open, taken conservatively:
|
||||
* - The grid's samples are points: the first column at `rectangle.west`
|
||||
* and the first row at `rectangle.north`, rows running south. A grid
|
||||
* whose rectangle spans 360° of longitude wraps (`width` columns over
|
||||
* the whole circle); any other is `width - 1` steps from west to east.
|
||||
* - `style.color` is the ghost's and the trail's colour; the moving tip
|
||||
* brightens it towards white. `speedFactor` scales how fast the tip
|
||||
* moves (1 by default).
|
||||
* - The highlight moves on the page's own clock, at most 30 times a
|
||||
* second, asking for the frames it needs; `paused` holds it where it is
|
||||
* and raises the ghost. `alpha` scales everything, and 0 draws nothing.
|
||||
* - Without `heightM` the paths are drawn at the ellipsoid's surface.
|
||||
* - Any change but `alpha`, `paused` and `style` traces the paths again.
|
||||
* - Scenes not in 3D refuse the field, as does a grid no path runs through.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
bakeWindStreamlines,
|
||||
groupWindPaths,
|
||||
} from '../../layers/wind/streamlines.js';
|
||||
import { listenerList, uncaught } from './common.js';
|
||||
|
||||
// How fast the highlight runs along a path, in path lengths per second.
|
||||
const TIP_SPEED = 0.16;
|
||||
const GHOST_ALPHA = 0.25;
|
||||
const GHOST_ALPHA_PAUSED = 0.34;
|
||||
// The highlight moves at most this often (seconds between frames).
|
||||
const STEP_SECONDS = 0.032;
|
||||
|
||||
// A persistent fine curve plus a moving, tapered highlight. The integer part
|
||||
// of s identifies a path; its fractional part follows the wind.
|
||||
const FLOW_MATERIAL = `
|
||||
in float v_windFacing;
|
||||
czm_material czm_getMaterial(czm_materialInput materialInput)
|
||||
{
|
||||
czm_material material = czm_getDefaultMaterial(materialInput);
|
||||
float pathId = floor(materialInput.st.s);
|
||||
float along = fract(materialInput.st.s);
|
||||
float offset = fract((pathId + 1.0) * 0.61803398875);
|
||||
float behind = fract(phaseTime * tipSpeed + offset - along);
|
||||
float tail = (1.0 - smoothstep(0.0, 0.32, behind));
|
||||
float tip = 1.0 - smoothstep(0.0, 0.045, behind);
|
||||
float ends = smoothstep(0.0, 0.055, along) * (1.0 - smoothstep(0.945, 1.0, along));
|
||||
float edge = 1.0 - smoothstep(0.26, 0.5, abs(materialInput.st.t - 0.5));
|
||||
float horizon = smoothstep(0.0, 0.065, v_windFacing);
|
||||
material.diffuse = mix(baseColor.rgb, vec3(0.91, 0.99, 1.0), tip);
|
||||
material.alpha = (ghostAlpha + 0.64 * tail + 0.16 * tip) * ends * edge * horizon * heightFade;
|
||||
return material;
|
||||
}`;
|
||||
|
||||
const DEFAULT_COLOR = '#80c9e6';
|
||||
|
||||
/** A contract colour as Cesium's; one Cesium cannot read is the default. */
|
||||
function toColor(C, color) {
|
||||
const Color = C.Color ?? Cesium.Color;
|
||||
if (Array.isArray(color))
|
||||
return new Color(color[0], color[1], color[2], color[3] ?? 1);
|
||||
return (
|
||||
Color.fromCssColorString(String(color ?? DEFAULT_COLOR)) ??
|
||||
Color.fromCssColorString(DEFAULT_COLOR)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The spec's grid as the wind sampler reads it. A rectangle across the
|
||||
* antimeridian (west east of east) runs east past 180°.
|
||||
*/
|
||||
export function windGridOf(spec) {
|
||||
const { west, south, north } = spec.rectangle;
|
||||
let { east } = spec.rectangle;
|
||||
if (east < west) east += 360;
|
||||
const span = east - west;
|
||||
const wraps = span >= 360 - 1e-9;
|
||||
return {
|
||||
u: spec.u,
|
||||
v: spec.v,
|
||||
nx: spec.width,
|
||||
ny: spec.height,
|
||||
lo1: west,
|
||||
la1: north,
|
||||
dx: span / (wraps ? spec.width : spec.width - 1),
|
||||
dy: (north - south) / (spec.height - 1),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One `windStreamlines` field over `scene`.
|
||||
* @param {{scene: object, spec: object, report?: (error: unknown) => void,
|
||||
* cesium?: object,
|
||||
* requestFrame?: (cb: (time: number) => void) => number,
|
||||
* cancelFrame?: (id: number) => void, onDispose?: () => void}} options
|
||||
*/
|
||||
export function createWindStreamlines({
|
||||
scene,
|
||||
spec,
|
||||
report = uncaught,
|
||||
cesium: C = Cesium,
|
||||
requestFrame = (cb) => globalThis.requestAnimationFrame(cb),
|
||||
cancelFrame = (id) => globalThis.cancelAnimationFrame(id),
|
||||
onDispose = () => {},
|
||||
}) {
|
||||
if (
|
||||
C.SceneMode?.SCENE3D !== undefined &&
|
||||
scene.mode !== undefined &&
|
||||
scene.mode !== C.SceneMode.SCENE3D
|
||||
)
|
||||
throw new TypeError(
|
||||
'the Cesium renderer draws wind streamlines in 3D only',
|
||||
);
|
||||
|
||||
const live = () => !scene.isDestroyed?.();
|
||||
const requestRender = () => {
|
||||
if (live()) scene.requestRender();
|
||||
};
|
||||
let current = { ...spec, style: { ...spec.style } };
|
||||
let alpha = spec.alpha ?? 1;
|
||||
let paused = spec.paused === true;
|
||||
let shown = true;
|
||||
let disposed = false;
|
||||
const cells = [];
|
||||
let material = null;
|
||||
let occluder = null;
|
||||
let phaseTime = 0;
|
||||
let visibleCells = 0;
|
||||
let diagnostics = { pathCount: 0, vertexCount: 0, buildMs: 0, cellCount: 0 };
|
||||
// The animation frame asked for, and when the highlight last moved.
|
||||
let frameId = null;
|
||||
let lastTime = null;
|
||||
// 'drawn' is owed for the latest change, made at `changedAt`.
|
||||
let owed = true;
|
||||
let renders = 0;
|
||||
let changedAt = 0;
|
||||
const frameNumber = () => scene.frameState?.frameNumber ?? renders;
|
||||
const drawnListeners = listenerList(report);
|
||||
|
||||
function clear() {
|
||||
for (const cell of cells) {
|
||||
if (live() && scene.primitives && !scene.primitives.isDestroyed?.())
|
||||
scene.primitives.remove(cell.primitive);
|
||||
if (!cell.primitive.isDestroyed?.()) cell.primitive.destroy?.();
|
||||
}
|
||||
cells.length = 0;
|
||||
if (material && !material.isDestroyed?.()) material.destroy?.();
|
||||
material = null;
|
||||
occluder = null;
|
||||
visibleCells = 0;
|
||||
}
|
||||
|
||||
function styleUniforms() {
|
||||
if (!material) return;
|
||||
const color = toColor(C, current.style?.color);
|
||||
material.uniforms.baseColor = color;
|
||||
material.uniforms.tipSpeed = TIP_SPEED * (current.style?.speedFactor ?? 1);
|
||||
material.uniforms.ghostAlpha = paused ? GHOST_ALPHA_PAUSED : GHOST_ALPHA;
|
||||
material.uniforms.heightFade = alpha;
|
||||
}
|
||||
|
||||
/** Trace and build; a failure leaves nothing built and throws. */
|
||||
function build() {
|
||||
try {
|
||||
buildCells();
|
||||
} catch (error) {
|
||||
clear();
|
||||
diagnostics = { pathCount: 0, vertexCount: 0, buildMs: 0, cellCount: 0 };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function buildCells() {
|
||||
clear();
|
||||
const started = performance.now();
|
||||
// The paths are traced round the whole globe, the wind wrapping east and
|
||||
// west: a grid that does not span it is refused, not drawn wrapped.
|
||||
const grid = windGridOf(current);
|
||||
const { west, east } = current.rectangle;
|
||||
if ((east < west ? east + 360 : east) - west < 360 - 1e-9)
|
||||
throw new RangeError(
|
||||
'the Cesium renderer draws wind streamlines over the whole globe only',
|
||||
);
|
||||
const paths = bakeWindStreamlines(grid, {
|
||||
count: current.pathBudget,
|
||||
steps: current.steps,
|
||||
});
|
||||
// A grid no path runs through is refused, so its caller can draw it
|
||||
// some other way.
|
||||
if (!paths.length)
|
||||
throw new RangeError('no wind streamlines run through this grid');
|
||||
let vertexCount = 0;
|
||||
material = new C.Material({
|
||||
fabric: {
|
||||
type: 'DrawWindStreamline',
|
||||
uniforms: {
|
||||
phaseTime,
|
||||
ghostAlpha: GHOST_ALPHA,
|
||||
heightFade: 0,
|
||||
tipSpeed: TIP_SPEED,
|
||||
baseColor: toColor(C, DEFAULT_COLOR),
|
||||
},
|
||||
source: FLOW_MATERIAL,
|
||||
},
|
||||
translucent: () => true,
|
||||
});
|
||||
styleUniforms();
|
||||
const base = new C.PolylineMaterialAppearance({ material });
|
||||
// Extend Cesium's own polyline shader rather than duplicate its
|
||||
// expansion and precision code. Explicit facing also masks the far
|
||||
// hemisphere when a scene keeps no globe depth for translucent objects.
|
||||
const source = base.vertexShaderSource;
|
||||
if (
|
||||
!/void\s+main\s*\(\s*\)/.test(source) ||
|
||||
!/v_st\.s\s*=\s*st\.s\s*;/.test(source)
|
||||
)
|
||||
throw new Error('Wind polyline shader entry unavailable');
|
||||
const seededSource = source.replace(
|
||||
/v_st\.s\s*=\s*st\.s\s*;/,
|
||||
'v_st.s = st.s * 0.999 + czm_batchTable_windSeed(batchId);',
|
||||
);
|
||||
const vertexShaderSource =
|
||||
`out float v_windFacing;\n${seededSource}`.replace(
|
||||
/void\s+main\s*\(\s*\)\s*\{/,
|
||||
`void main() {\nvec3 windWorld = (czm_model * vec4(position3DHigh + position3DLow, 1.0)).xyz;\nv_windFacing = dot(normalize(windWorld), normalize(czm_viewerPositionWC - windWorld));\n`,
|
||||
);
|
||||
// EllipsoidalOccluder only tests points: a sphere occluder with an
|
||||
// inscribed Earth sphere, whether or not the globe shows.
|
||||
occluder = new C.Occluder(
|
||||
new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius),
|
||||
scene.camera.positionWC,
|
||||
);
|
||||
const height = Number(current.heightM) || 0;
|
||||
const width = current.style?.widthPx ?? 2.4;
|
||||
for (const group of groupWindPaths(paths)) {
|
||||
const cellPositions = [];
|
||||
let cellVertexCount = 0;
|
||||
const instances = group.paths.map((path) => {
|
||||
const positions = path.coordinates.map(([lon, lat]) =>
|
||||
C.Cartesian3.fromDegrees(lon, lat, height),
|
||||
);
|
||||
// Cesium's worker expands the lines; per-instance seeds keep the
|
||||
// expanded vertex buffer off the main thread.
|
||||
const geometry = new C.PolylineGeometry({
|
||||
positions,
|
||||
width,
|
||||
arcType: C.ArcType?.NONE,
|
||||
vertexFormat: C.PolylineMaterialAppearance.VERTEX_FORMAT,
|
||||
});
|
||||
cellPositions.push(...positions);
|
||||
cellVertexCount += positions.length * 4 - 4;
|
||||
return new C.GeometryInstance({
|
||||
geometry,
|
||||
attributes: {
|
||||
windSeed: new C.GeometryInstanceAttribute({
|
||||
componentDatatype: C.ComponentDatatype.FLOAT,
|
||||
componentsPerAttribute: 1,
|
||||
value: [path.seed],
|
||||
}),
|
||||
},
|
||||
});
|
||||
});
|
||||
const appearance = new C.PolylineMaterialAppearance({
|
||||
material,
|
||||
vertexShaderSource,
|
||||
translucent: true,
|
||||
renderState: { depthTest: { enabled: true }, depthMask: false },
|
||||
});
|
||||
const primitive = new C.Primitive({
|
||||
show: false,
|
||||
geometryInstances: instances,
|
||||
appearance,
|
||||
asynchronous: true,
|
||||
allowPicking: false,
|
||||
releaseGeometryInstances: true,
|
||||
compressVertices: false,
|
||||
});
|
||||
cells.push({
|
||||
primitive,
|
||||
sphere: C.BoundingSphere.fromPoints(cellPositions),
|
||||
vertexCount: cellVertexCount,
|
||||
});
|
||||
scene.primitives.add(primitive);
|
||||
vertexCount += cellVertexCount;
|
||||
}
|
||||
diagnostics = {
|
||||
pathCount: paths.length,
|
||||
vertexCount,
|
||||
buildMs: performance.now() - started,
|
||||
cellCount: cells.length,
|
||||
};
|
||||
}
|
||||
|
||||
// Which cells the eye can see, before each frame draws.
|
||||
function cull() {
|
||||
visibleCells = 0;
|
||||
const camera = scene.camera;
|
||||
const draws = shown && alpha > 0 && cells.length > 0 && camera;
|
||||
let volume;
|
||||
if (draws) {
|
||||
occluder.cameraPosition = camera.positionWC;
|
||||
volume = camera.frustum.computeCullingVolume(
|
||||
camera.positionWC,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
);
|
||||
}
|
||||
for (const cell of cells) {
|
||||
cell.primitive.show = Boolean(
|
||||
draws &&
|
||||
occluder.isBoundingSphereVisible(cell.sphere) &&
|
||||
volume.computeVisibility(cell.sphere) !== C.Intersect.OUTSIDE,
|
||||
);
|
||||
if (cell.primitive.show) visibleCells += 1;
|
||||
}
|
||||
}
|
||||
const page = globalThis.document;
|
||||
const animating = () =>
|
||||
!disposed &&
|
||||
shown &&
|
||||
!paused &&
|
||||
alpha > 0 &&
|
||||
visibleCells > 0 &&
|
||||
page?.hidden !== true;
|
||||
function step(time) {
|
||||
frameId = null;
|
||||
if (!animating()) {
|
||||
lastTime = null;
|
||||
return;
|
||||
}
|
||||
const elapsed = lastTime === null ? null : (time - lastTime) / 1000;
|
||||
// A first frame (after a pause, a hidden page or nothing in view) moves
|
||||
// one tick; otherwise the highlight moves by the time passed, and a frame
|
||||
// is drawn, at most every STEP_SECONDS.
|
||||
let moved = true;
|
||||
if (elapsed === null) phaseTime += 1 / 60;
|
||||
else if (elapsed >= STEP_SECONDS) phaseTime += elapsed;
|
||||
else moved = false;
|
||||
if (moved) {
|
||||
lastTime = time;
|
||||
if (material) material.uniforms.phaseTime = phaseTime % 10000;
|
||||
requestRender();
|
||||
}
|
||||
frameId = requestFrame(step);
|
||||
}
|
||||
function animate() {
|
||||
if (animating()) frameId ??= requestFrame(step);
|
||||
else if (frameId !== null) {
|
||||
cancelFrame(frameId);
|
||||
frameId = null;
|
||||
lastTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
const ready = () => cells.every((cell) => cell.primitive.ready);
|
||||
function changed() {
|
||||
owed = true;
|
||||
changedAt = frameNumber();
|
||||
requestRender();
|
||||
}
|
||||
// A field that cannot be built is refused, holding nothing.
|
||||
build();
|
||||
const offPreRender = scene.preRender.addEventListener(() => {
|
||||
cull();
|
||||
animate();
|
||||
});
|
||||
// A hidden page stops the highlight; shown again, it starts afresh rather
|
||||
// than jumping by the time it was hidden.
|
||||
const onVisibility = () => {
|
||||
lastTime = null;
|
||||
animate();
|
||||
};
|
||||
page?.addEventListener?.('visibilitychange', onVisibility);
|
||||
const offPostRender = scene.postRender.addEventListener(() => {
|
||||
renders += 1;
|
||||
// Nothing built (a rebuild failed) is never told drawn.
|
||||
if (!owed || !shown || disposed || !cells.length) return;
|
||||
if (!ready() || frameNumber() <= changedAt) {
|
||||
requestRender();
|
||||
return;
|
||||
}
|
||||
owed = false;
|
||||
drawnListeners.fire();
|
||||
});
|
||||
|
||||
changed();
|
||||
|
||||
return {
|
||||
id: spec.id,
|
||||
get show() {
|
||||
return shown;
|
||||
},
|
||||
set show(value) {
|
||||
const next = Boolean(value);
|
||||
if (disposed || next === shown) return;
|
||||
shown = next;
|
||||
if (!shown) {
|
||||
for (const cell of cells) cell.primitive.show = false;
|
||||
visibleCells = 0;
|
||||
animate();
|
||||
}
|
||||
changedAt = frameNumber();
|
||||
requestRender();
|
||||
},
|
||||
update(patch = {}) {
|
||||
if (disposed) return;
|
||||
if (patch.kind !== undefined && patch.kind !== 'windStreamlines')
|
||||
throw new TypeError('a field keeps its kind');
|
||||
const retrace =
|
||||
['u', 'v', 'width', 'height', 'pathBudget', 'steps', 'heightM'].some(
|
||||
(key) => key in patch && patch[key] !== current[key],
|
||||
) ||
|
||||
(patch.rectangle !== undefined &&
|
||||
['west', 'south', 'east', 'north'].some(
|
||||
(edge) => patch.rectangle[edge] !== current.rectangle?.[edge],
|
||||
));
|
||||
const restroke =
|
||||
patch.style?.widthPx !== undefined &&
|
||||
patch.style.widthPx !== current.style?.widthPx;
|
||||
current = {
|
||||
...current,
|
||||
...patch,
|
||||
style: { ...current.style, ...patch.style },
|
||||
};
|
||||
if ('alpha' in patch) alpha = patch.alpha ?? 1;
|
||||
if ('paused' in patch) paused = patch.paused === true;
|
||||
if (retrace || restroke)
|
||||
try {
|
||||
build();
|
||||
} catch (error) {
|
||||
// It draws nothing until a change builds again.
|
||||
report(error);
|
||||
}
|
||||
else styleUniforms();
|
||||
cull();
|
||||
animate();
|
||||
changed();
|
||||
},
|
||||
on(event, cb) {
|
||||
if (event !== 'drawn') return () => {};
|
||||
return drawnListeners.on(cb);
|
||||
},
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (frameId !== null) cancelFrame(frameId);
|
||||
frameId = null;
|
||||
offPreRender();
|
||||
offPostRender();
|
||||
page?.removeEventListener?.('visibilitychange', onVisibility);
|
||||
drawnListeners.clear();
|
||||
clear();
|
||||
requestRender();
|
||||
onDispose();
|
||||
},
|
||||
/** For tests and diagnostics: what it built and draws. */
|
||||
diagnostics: () => ({
|
||||
...diagnostics,
|
||||
visibleCells,
|
||||
ready: ready(),
|
||||
animating: frameId !== null,
|
||||
phaseTime,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
BoundingSphere,
|
||||
Cartesian3,
|
||||
Ellipsoid,
|
||||
Event,
|
||||
Intersect,
|
||||
Occluder,
|
||||
PerspectiveFrustum,
|
||||
} from 'cesium';
|
||||
import { createWindStreamlines, windGridOf } from './drawStreamlines.js';
|
||||
import { createCesiumFields } from './drawFields.js';
|
||||
import { bakeWindStreamlines } from '../../layers/wind/streamlines.js';
|
||||
|
||||
const grid = () => ({
|
||||
nx: 4,
|
||||
ny: 3,
|
||||
lo1: -180,
|
||||
la1: 90,
|
||||
dx: 90,
|
||||
dy: 90,
|
||||
u: new Float32Array(12).fill(15),
|
||||
v: new Float32Array(12),
|
||||
});
|
||||
// The grid above as a field spec: 4 columns wrapping the globe, 3 rows.
|
||||
const SPEC = Object.freeze({
|
||||
kind: 'windStreamlines',
|
||||
id: 'wind',
|
||||
u: new Float32Array(12).fill(15),
|
||||
v: new Float32Array(12),
|
||||
width: 4,
|
||||
height: 3,
|
||||
rectangle: { west: -180, south: -90, east: 180, north: 90 },
|
||||
pathBudget: 7200,
|
||||
steps: 16,
|
||||
style: { color: '#80c9e6', widthPx: 2.4 },
|
||||
heightM: 12000,
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const members = new Set();
|
||||
let geometryBuilds = 0;
|
||||
const spheres = [];
|
||||
const visibility = {
|
||||
horizon: () => true,
|
||||
frustum: () => Intersect.INSIDE,
|
||||
horizonTests: 0,
|
||||
frustumTests: 0,
|
||||
};
|
||||
let occluderBuilds = 0;
|
||||
class Material {
|
||||
constructor(options) {
|
||||
this.uniforms = options.fabric.uniforms;
|
||||
this.source = options.fabric.source;
|
||||
}
|
||||
destroy() {
|
||||
assert.ok(!this.destroyed, 'owned resource destroyed once');
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
class Appearance {
|
||||
static VERTEX_FORMAT = {};
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.vertexShaderSource ??=
|
||||
'in vec3 position3DHigh; in vec3 position3DLow; void main() { gl_Position = vec4(0.0); v_st.s = st.s; }';
|
||||
}
|
||||
}
|
||||
class Polyline {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
static createGeometry(options) {
|
||||
geometryBuilds++;
|
||||
const st = new Float32Array(options.positions.length * 2);
|
||||
for (let i = 0; i < options.positions.length; i++)
|
||||
st[i * 2] = i / (options.positions.length - 1);
|
||||
return { attributes: { st: { values: st } } };
|
||||
}
|
||||
}
|
||||
class Primitive {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.ready = true;
|
||||
}
|
||||
destroy() {
|
||||
assert.ok(!this.destroyed, 'owned resource destroyed once');
|
||||
this.destroyed = true;
|
||||
}
|
||||
isDestroyed() {
|
||||
return Boolean(this.destroyed);
|
||||
}
|
||||
}
|
||||
const C = {
|
||||
ComponentDatatype: { FLOAT: 5126 },
|
||||
GeometryInstanceAttribute: class {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
},
|
||||
Material,
|
||||
PolylineMaterialAppearance: Appearance,
|
||||
PolylineGeometry: Polyline,
|
||||
Primitive,
|
||||
GeometryInstance: class {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
}
|
||||
},
|
||||
Cartesian3,
|
||||
Ellipsoid,
|
||||
Intersect,
|
||||
BoundingSphere: class extends BoundingSphere {
|
||||
static fromPoints(points) {
|
||||
const sphere = BoundingSphere.fromPoints(points);
|
||||
spheres.push({ sphere, points });
|
||||
return sphere;
|
||||
}
|
||||
},
|
||||
Occluder: class {
|
||||
constructor(sphere, cameraPosition) {
|
||||
occluderBuilds++;
|
||||
this.cameraPosition = cameraPosition;
|
||||
}
|
||||
isBoundingSphereVisible(sphere) {
|
||||
visibility.horizonTests++;
|
||||
return visibility.horizon(sphere, this.cameraPosition);
|
||||
}
|
||||
},
|
||||
ArcType: { NONE: 0 },
|
||||
};
|
||||
const volume = {
|
||||
computeVisibility(sphere) {
|
||||
visibility.frustumTests++;
|
||||
return visibility.frustum(sphere);
|
||||
},
|
||||
};
|
||||
const frames = [];
|
||||
const preRender = new Event();
|
||||
const postRender = new Event();
|
||||
let renders = 0;
|
||||
const scene = {
|
||||
preRender,
|
||||
postRender,
|
||||
requestRender() {
|
||||
renders += 1;
|
||||
},
|
||||
get renders() {
|
||||
return renders;
|
||||
},
|
||||
globe: { show: false },
|
||||
camera: {
|
||||
positionWC: Cartesian3.fromDegrees(0, 0, 1e7),
|
||||
positionCartographic: { height: 1e7 },
|
||||
directionWC: new Cartesian3(-1, 0, 0),
|
||||
upWC: new Cartesian3(0, 0, 1),
|
||||
frustum: { computeCullingVolume: () => volume },
|
||||
},
|
||||
primitives: {
|
||||
add(item) {
|
||||
members.add(item);
|
||||
},
|
||||
remove(item) {
|
||||
const removed = members.delete(item);
|
||||
if (removed) item.destroy();
|
||||
return removed;
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
C,
|
||||
scene,
|
||||
members,
|
||||
builds: () => geometryBuilds,
|
||||
spheres,
|
||||
visibility,
|
||||
occluderBuilds: () => occluderBuilds,
|
||||
frames,
|
||||
make: (patch = {}) =>
|
||||
createWindStreamlines({
|
||||
scene,
|
||||
cesium: C,
|
||||
spec: { ...SPEC, ...patch },
|
||||
requestFrame: (cb) => {
|
||||
frames.push(cb);
|
||||
return frames.length;
|
||||
},
|
||||
cancelFrame: (id) => {
|
||||
frames[id - 1] = null;
|
||||
},
|
||||
}),
|
||||
/** One render: the frame events around it. */
|
||||
render() {
|
||||
preRender.raiseEvent();
|
||||
postRender.raiseEvent();
|
||||
},
|
||||
};
|
||||
}
|
||||
const field = () => ({
|
||||
nx: 4,
|
||||
ny: 3,
|
||||
lo1: -180,
|
||||
la1: 90,
|
||||
dx: 90,
|
||||
dy: 90,
|
||||
u: new Float32Array(12).fill(15),
|
||||
v: new Float32Array(12),
|
||||
});
|
||||
|
||||
test('the spec reads back as the wind grid it came from', () => {
|
||||
const { u, v, ...rest } = windGridOf(SPEC);
|
||||
const { u: gu, v: gv, ...want } = grid();
|
||||
assert.deepEqual(rest, want);
|
||||
assert.deepEqual([...u], [...gu]);
|
||||
const regional = windGridOf({
|
||||
...SPEC,
|
||||
rectangle: { west: -100, south: 20, east: -70, north: 50 },
|
||||
});
|
||||
assert.equal(regional.dx, 10, 'a regional grid does not wrap');
|
||||
assert.equal(regional.dy, 15);
|
||||
const across = windGridOf({
|
||||
...SPEC,
|
||||
rectangle: { west: 170, south: 20, east: -170, north: 50 },
|
||||
});
|
||||
assert.equal(across.lo1, 170);
|
||||
assert.equal(across.dx, 20 / 3, 'across the antimeridian it runs east');
|
||||
});
|
||||
|
||||
test('streamlines build native cells; the highlight moves without rebuilding', () => {
|
||||
const h = harness();
|
||||
const field = h.make();
|
||||
assert.equal(h.members.size, 72);
|
||||
const batch = [...h.members][0];
|
||||
assert.equal(batch.allowPicking, false);
|
||||
assert.equal(batch.asynchronous, true);
|
||||
assert.ok(batch.appearance.vertexShaderSource.includes('v_windFacing = dot'));
|
||||
assert.ok(
|
||||
batch.appearance.vertexShaderSource.includes(
|
||||
'czm_batchTable_windSeed(batchId)',
|
||||
),
|
||||
);
|
||||
const { uniforms, source } = batch.appearance.material;
|
||||
assert.ok(source.includes('smoothstep(0.0, 0.065, v_windFacing)'));
|
||||
assert.ok(source.includes('mix(baseColor.rgb'));
|
||||
assert.equal(
|
||||
h.builds(),
|
||||
0,
|
||||
'expanded geometry is deferred to Cesium workers',
|
||||
);
|
||||
const diagnostics = field.diagnostics();
|
||||
assert.ok(diagnostics.pathCount > 7000 && diagnostics.pathCount <= 7200);
|
||||
assert.ok(diagnostics.vertexCount > 0);
|
||||
assert.equal(diagnostics.cellCount, 72);
|
||||
const instances = [...h.members].flatMap((p) => p.geometryInstances);
|
||||
const baked = bakeWindStreamlines(grid());
|
||||
assert.equal(instances.length, baked.length);
|
||||
const bySeed = new Map(
|
||||
instances.map((i) => [i.attributes.windSeed.value[0], i]),
|
||||
);
|
||||
for (const path of baked)
|
||||
assert.deepEqual(
|
||||
bySeed.get(path.seed).geometry.positions,
|
||||
path.coordinates.map(([lon, lat]) =>
|
||||
Cartesian3.fromDegrees(lon, lat, 12000),
|
||||
),
|
||||
);
|
||||
for (const instance of instances) assert.equal(instance.geometry.width, 2.4);
|
||||
for (const cell of h.members) {
|
||||
assert.equal(cell.appearance.material, batch.appearance.material);
|
||||
assert.equal(cell.compressVertices, false);
|
||||
assert.equal(cell.releaseGeometryInstances, true);
|
||||
}
|
||||
assert.equal(uniforms.ghostAlpha, 0.25);
|
||||
assert.equal(uniforms.heightFade, 1);
|
||||
assert.ok(Math.abs(uniforms.tipSpeed - 0.16) < 1e-12);
|
||||
// A render culls the cells and starts the highlight on the page's frames.
|
||||
h.render();
|
||||
assert.equal(h.frames.length, 1);
|
||||
h.frames.at(-1)(1000);
|
||||
const first = uniforms.phaseTime;
|
||||
assert.ok(first > 0);
|
||||
const asked = h.scene.renders;
|
||||
h.frames.at(-1)(1010);
|
||||
assert.equal(uniforms.phaseTime, first, 'at most 30 steps a second');
|
||||
assert.equal(h.scene.renders, asked, 'and no frame drawn between them');
|
||||
h.frames.at(-1)(1040);
|
||||
assert.ok(Math.abs(uniforms.phaseTime - first - 0.04) < 1e-9);
|
||||
assert.equal(h.scene.renders, asked + 1);
|
||||
field.update({ paused: true });
|
||||
assert.equal(uniforms.ghostAlpha, 0.34, 'paused raises the ghost');
|
||||
const held = uniforms.phaseTime;
|
||||
assert.equal(h.frames.at(-1), null, 'paused stops the frames');
|
||||
field.update({ paused: false, alpha: 0.5, style: { speedFactor: 2 } });
|
||||
assert.equal(uniforms.heightFade, 0.5);
|
||||
assert.ok(Math.abs(uniforms.tipSpeed - 0.32) < 1e-12);
|
||||
assert.equal(uniforms.phaseTime, held);
|
||||
assert.equal(h.members.size, 72, 'style, alpha and pause never rebuild');
|
||||
field.dispose();
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.equal(h.scene.preRender.numberOfListeners, 0);
|
||||
assert.equal(h.scene.postRender.numberOfListeners, 0);
|
||||
});
|
||||
|
||||
test("streamlines tell 'drawn' once every cell is ready, never while hidden", () => {
|
||||
const h = harness();
|
||||
const field = h.make();
|
||||
let drawn = 0;
|
||||
field.on('drawn', () => (drawn += 1));
|
||||
const [batch] = h.members;
|
||||
batch.ready = false;
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 0, 'every cell must be ready');
|
||||
batch.ready = true;
|
||||
h.render();
|
||||
assert.equal(drawn, 1);
|
||||
h.render();
|
||||
assert.equal(drawn, 1);
|
||||
field.show = false;
|
||||
field.update({ alpha: 0.4 });
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 1, 'never while hidden');
|
||||
assert.equal(batch.show, false);
|
||||
field.show = true;
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 2, 'told once shown');
|
||||
field.update({ u: new Float32Array(12).fill(10) });
|
||||
assert.equal(batch.destroyed, true, 'a new grid traces again');
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 3);
|
||||
field.dispose();
|
||||
});
|
||||
|
||||
test('a failed build is refused, holding nothing', () => {
|
||||
const h = harness();
|
||||
const NativePrimitive = h.C.Primitive;
|
||||
const built = [];
|
||||
h.C.Primitive = class extends NativePrimitive {
|
||||
constructor(options) {
|
||||
if (built.length === 2) throw new Error('later cell failed');
|
||||
super(options);
|
||||
built.push(this);
|
||||
}
|
||||
};
|
||||
assert.throws(() => h.make(), /later cell failed/);
|
||||
assert.equal(h.members.size, 0);
|
||||
for (const batch of built) {
|
||||
assert.equal(batch.destroyed, true);
|
||||
assert.equal(batch.appearance.material.destroyed, true);
|
||||
}
|
||||
assert.equal(h.scene.preRender.numberOfListeners, 0);
|
||||
});
|
||||
|
||||
test('a grid no path runs through is refused, holding nothing', () => {
|
||||
const h = harness();
|
||||
assert.throws(
|
||||
() => h.make({ u: new Float32Array(12), v: new Float32Array(12) }),
|
||||
/no wind streamlines/,
|
||||
);
|
||||
assert.equal(h.members.size, 0);
|
||||
assert.equal(h.scene.preRender.numberOfListeners, 0);
|
||||
});
|
||||
|
||||
test('the Cesium fields draw wind streamlines under their id until disposed', () => {
|
||||
const h = harness();
|
||||
const fields = createCesiumFields({ scene: h.scene, cesium: h.C });
|
||||
const field = fields.field({ ...SPEC });
|
||||
assert.ok(h.members.size > 0);
|
||||
assert.equal(fields.has('wind'), true);
|
||||
assert.throws(() => fields.field({ ...SPEC }), /is live/);
|
||||
field.dispose();
|
||||
assert.equal(fields.has('wind'), false);
|
||||
assert.equal(h.members.size, 0);
|
||||
fields.field({ ...SPEC });
|
||||
fields.dispose();
|
||||
assert.equal(fields.has('wind'), false);
|
||||
assert.equal(h.members.size, 0);
|
||||
});
|
||||
|
||||
test('a grid short of the whole globe is refused, not drawn wrapped', () => {
|
||||
const h = harness();
|
||||
for (const rectangle of [
|
||||
{ west: -100, south: -90, east: 80, north: 90 },
|
||||
// Four columns over 300°: its samples nearly span the globe; it does not.
|
||||
{ west: -150, south: -90, east: 150, north: 90 },
|
||||
])
|
||||
assert.throws(() => h.make({ rectangle }), /whole globe only/);
|
||||
assert.equal(h.members.size, 0);
|
||||
const across = h.make({
|
||||
rectangle: { west: 0, south: -90, east: -0.000000000001, north: 90 },
|
||||
});
|
||||
assert.ok(h.members.size > 0, 'a rectangle across the antimeridian wraps');
|
||||
across.dispose();
|
||||
});
|
||||
|
||||
test('a rebuild that fails draws nothing and is never told drawn', () => {
|
||||
const reported = [];
|
||||
const h = harness();
|
||||
const field = createWindStreamlines({
|
||||
scene: h.scene,
|
||||
cesium: h.C,
|
||||
spec: { ...SPEC },
|
||||
report: (error) => reported.push(error),
|
||||
requestFrame: () => 1,
|
||||
cancelFrame() {},
|
||||
});
|
||||
let drawn = 0;
|
||||
field.on('drawn', () => (drawn += 1));
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 1);
|
||||
const asked = h.scene.renders;
|
||||
field.update({ u: new Float32Array(12), v: new Float32Array(12) });
|
||||
assert.equal(reported.length, 1);
|
||||
assert.equal(h.members.size, 0);
|
||||
h.render();
|
||||
h.render();
|
||||
assert.equal(drawn, 1, 'nothing drawn is never told');
|
||||
assert.ok(h.scene.renders - asked <= 1, 'and asks no frames for it');
|
||||
field.dispose();
|
||||
});
|
||||
|
||||
test('the highlight stops when hidden, transparent or out of view, and starts again', () => {
|
||||
const h = harness();
|
||||
const field = h.make();
|
||||
const live = () => h.frames.filter(Boolean).length;
|
||||
h.render();
|
||||
assert.equal(live(), 1);
|
||||
field.show = false;
|
||||
assert.equal(live(), 0, 'hidden');
|
||||
field.show = true;
|
||||
h.render();
|
||||
assert.equal(live(), 1);
|
||||
field.update({ alpha: 0 });
|
||||
assert.equal(live(), 0, 'transparent');
|
||||
field.update({ alpha: 1 });
|
||||
h.render();
|
||||
assert.equal(live(), 1);
|
||||
h.visibility.horizon = () => false;
|
||||
h.render();
|
||||
assert.equal(live(), 0, 'every cell behind the Earth');
|
||||
h.visibility.horizon = () => true;
|
||||
h.render();
|
||||
assert.equal(live(), 1, 'the next render in view starts it');
|
||||
field.dispose();
|
||||
assert.equal(live(), 0, 'dispose cancels the frame it asked for');
|
||||
});
|
||||
|
||||
test('a hidden page stops the highlight; shown again, it starts afresh', () => {
|
||||
const listeners = new Set();
|
||||
const document = globalThis.document;
|
||||
const page = {
|
||||
hidden: false,
|
||||
addEventListener: (type, cb) => listeners.add(cb),
|
||||
removeEventListener: (type, cb) => listeners.delete(cb),
|
||||
};
|
||||
globalThis.document = page;
|
||||
try {
|
||||
const h = harness();
|
||||
const field = h.make();
|
||||
// Whether the frame asked for last is still pending.
|
||||
const pending = () => h.frames.at(-1) !== null;
|
||||
const { uniforms } = [...h.members][0].appearance.material;
|
||||
h.render();
|
||||
h.frames.at(-1)(1000);
|
||||
h.frames.at(-1)(1100);
|
||||
const before = uniforms.phaseTime;
|
||||
assert.ok(Math.abs(before - 1 / 60 - 0.1) < 1e-9, 'time passed moves it');
|
||||
h.frames.at(-1)(1400);
|
||||
assert.ok(
|
||||
Math.abs(uniforms.phaseTime - before - 0.3) < 1e-9,
|
||||
'a stall still moves it by the time passed',
|
||||
);
|
||||
page.hidden = true;
|
||||
for (const cb of listeners) cb();
|
||||
assert.equal(pending(), false, 'a hidden page asks no frames');
|
||||
page.hidden = false;
|
||||
for (const cb of listeners) cb();
|
||||
assert.equal(pending(), true);
|
||||
const shown = uniforms.phaseTime;
|
||||
h.frames.at(-1)(60_000);
|
||||
assert.ok(Math.abs(uniforms.phaseTime - shown - 1 / 60) < 1e-9);
|
||||
field.dispose();
|
||||
assert.equal(listeners.size, 0);
|
||||
} finally {
|
||||
globalThis.document = document;
|
||||
}
|
||||
});
|
||||
|
||||
test('a scene not in 3D refuses streamlines', () => {
|
||||
const h = harness();
|
||||
h.C.SceneMode = { SCENE3D: 3 };
|
||||
h.scene.mode = 2;
|
||||
assert.throws(() => h.make(), /3D only/);
|
||||
});
|
||||
|
||||
test('cell visibility combines horizon, frustum and alpha', () => {
|
||||
const h = harness();
|
||||
const field = h.make();
|
||||
const batches = [...h.members];
|
||||
h.visibility.horizon = (sphere) =>
|
||||
h.spheres.findIndex((s) => s.sphere === sphere) % 2 === 0;
|
||||
h.visibility.frustum = (sphere) =>
|
||||
h.spheres.findIndex((s) => s.sphere === sphere) % 3 === 0
|
||||
? Intersect.INTERSECTING
|
||||
: Intersect.OUTSIDE;
|
||||
h.render();
|
||||
assert.equal(field.diagnostics().visibleCells, 12);
|
||||
for (let i = 0; i < batches.length; i++)
|
||||
assert.equal(batches[i].show, i % 6 === 0);
|
||||
assert.equal(h.visibility.horizonTests, 72);
|
||||
assert.equal(h.visibility.frustumTests, 36);
|
||||
field.update({ alpha: 0 });
|
||||
h.render();
|
||||
assert.equal(field.diagnostics().visibleCells, 0);
|
||||
for (const batch of batches) assert.equal(batch.show, false);
|
||||
assert.equal(h.visibility.horizonTests, 72, 'alpha 0 tests nothing');
|
||||
assert.equal(h.occluderBuilds(), 1, 'the occluder is reused');
|
||||
field.dispose();
|
||||
});
|
||||
|
||||
test('real Cesium sphere culling hides the far hemisphere and a sky-facing view', () => {
|
||||
const h = harness();
|
||||
h.C.Occluder = Occluder;
|
||||
const field = h.make();
|
||||
const camera = h.scene.camera;
|
||||
camera.frustum = new PerspectiveFrustum({
|
||||
fov: Math.PI / 3,
|
||||
aspectRatio: 1.5,
|
||||
near: 1,
|
||||
far: 5e7,
|
||||
});
|
||||
h.render();
|
||||
const facing = field.diagnostics().visibleCells;
|
||||
assert.ok(facing > 0 && facing < 72);
|
||||
for (let i = 0; i < h.spheres.length; i++)
|
||||
if (h.spheres[i].sphere.center.x < -5e6)
|
||||
assert.equal([...h.members][i].show, false);
|
||||
camera.directionWC.x = 1;
|
||||
h.render();
|
||||
assert.equal(field.diagnostics().visibleCells, 0);
|
||||
field.dispose();
|
||||
});
|
||||
@@ -639,6 +639,8 @@ provideUnboundGlobe((viewer) => {
|
||||
]);
|
||||
if (typeof viewer.scene.globe?.show === 'boolean')
|
||||
capabilities.add('globeVisibility');
|
||||
// The globe's surface shading needs a globe to shade.
|
||||
if (viewer.scene.globe) capabilities.add('surfaceShading');
|
||||
const { port, dispose } = createCesiumGlobe(viewer, {
|
||||
capabilities,
|
||||
requestRender: () => viewer.scene.requestRender?.(),
|
||||
|
||||
@@ -40,6 +40,8 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.columns.shown',
|
||||
'draw.drawOrder',
|
||||
'draw.drillPick',
|
||||
'draw.field.rasterShell',
|
||||
'draw.field.windStreamlines',
|
||||
'draw.icons.distance',
|
||||
'draw.icons.update',
|
||||
'draw.lines.depthFailDash',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }), [
|
||||
|
||||
@@ -5,10 +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",
|
||||
"src/maps/catalog.js",
|
||||
"src/maps/controller.js",
|
||||
"src/maps/google3d.js",
|
||||
|
||||
@@ -786,6 +786,64 @@ export function portChecks() {
|
||||
},
|
||||
{ capability: 'fields' },
|
||||
),
|
||||
check(
|
||||
'draw.field.windStreamlines',
|
||||
"streamlines' 'drawn' comes once per change, never while hidden",
|
||||
async (h, r) => {
|
||||
await overAustin(h, r, 2000000);
|
||||
const width = 8;
|
||||
const height = 5;
|
||||
const errors = [];
|
||||
const offError = r.on('error', (e) => errors.push(e));
|
||||
const field = r.draw.field({
|
||||
kind: 'windStreamlines',
|
||||
id: 'conf:wind',
|
||||
u: new Float32Array(width * height).fill(12),
|
||||
v: new Float32Array(width * height).fill(4),
|
||||
width,
|
||||
height,
|
||||
rectangle: { west: -180, south: -80, east: 180, north: 80 },
|
||||
pathBudget: 200,
|
||||
steps: 8,
|
||||
style: { color: '#80c9e6', widthPx: 2 },
|
||||
heightM: 12000,
|
||||
alpha: 1,
|
||||
});
|
||||
let drawnCount = 0;
|
||||
const off = field.on('drawn', () => (drawnCount += 1));
|
||||
// Frames until 'drawn' has come `want` times, for at most 20 s.
|
||||
const until = async (want) => {
|
||||
const deadline = Date.now() + 20000;
|
||||
while (drawnCount < want && Date.now() < deadline)
|
||||
await drawn(h, r, 1);
|
||||
};
|
||||
try {
|
||||
await until(1);
|
||||
equal(drawnCount, 1, 'drawn once made');
|
||||
await drawn(h, r, 4);
|
||||
equal(drawnCount, 1, 'not again while nothing changes');
|
||||
field.update({ alpha: 0.5 });
|
||||
await until(2);
|
||||
equal(drawnCount, 2, 'drawn after a new alpha');
|
||||
field.update({ paused: true });
|
||||
await until(3);
|
||||
equal(drawnCount, 3, 'drawn once paused');
|
||||
field.show = false;
|
||||
field.update({ alpha: 0.4 });
|
||||
await drawn(h, r, 6);
|
||||
equal(drawnCount, 3, 'never while hidden');
|
||||
field.show = true;
|
||||
await until(4);
|
||||
equal(drawnCount, 4, 'drawn once shown again');
|
||||
deepEqual(errors, [], 'no errors');
|
||||
} finally {
|
||||
off();
|
||||
offError();
|
||||
field.dispose();
|
||||
}
|
||||
},
|
||||
{ capability: 'fields' },
|
||||
),
|
||||
check(
|
||||
'draw.drawOrder',
|
||||
'of sets drawn over depth, the higher draw order is on top and picked',
|
||||
|
||||
@@ -133,6 +133,11 @@ const DRAW_FROM_CALLER = new Set([
|
||||
// It configures the sources of layers, the traffic layer's among them,
|
||||
// that draw and read the surface through the ports alone.
|
||||
'./application/sources',
|
||||
// The layer catalog and the standalone catalog over it: their layers, the
|
||||
// weather shells and the wind flow and relief among them, draw, read the
|
||||
// eye and shade the globe through the ports alone.
|
||||
'./application/layers',
|
||||
'./standalone/catalog',
|
||||
]);
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user