diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f1d1211e..7bca0a38e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index c4476d2bd..f765849d7 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -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. diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 5cbaf5e09..2b8fee12b 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -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 diff --git a/src/layers/wind/relief.js b/src/layers/wind/relief.js index 5d80e3b8d..3ef1cf721 100644 --- a/src/layers/wind/relief.js +++ b/src/layers/wind/relief.js @@ -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, }; }, }; diff --git a/src/layers/wind/relief.test.mjs b/src/layers/wind/relief.test.mjs index 9e1b94b33..448aee21a 100644 --- a/src/layers/wind/relief.test.mjs +++ b/src/layers/wind/relief.test.mjs @@ -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); }); diff --git a/src/layers/wind/rendering.js b/src/layers/wind/rendering.js index 050bbf362..c18f931c4 100644 --- a/src/layers/wind/rendering.js +++ b/src/layers/wind/rendering.js @@ -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 { followShellLift, + globeImageryHost, WEATHER_SHELL_HEIGHTS, } from '../weather/shellRendering.js'; import { createWindRelief } from './relief.js'; import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js'; -import { findDraw, 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'; @@ -67,7 +70,7 @@ 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) { +function createWindShell(viewer, draw, texture, alpha, ports) { const seq = (windShells += 1); const height = WEATHER_SHELL_HEIGHTS.wind; const field = draw.field({ @@ -85,10 +88,14 @@ function createWindShell(viewer, draw, texture, alpha) { drawn = true; owed = false; }); - const offLift = followShellLift(viewer, (liftM) => { - owed = true; - field.update({ liftM }); - }); + const offLift = followShellLift( + viewer, + (liftM) => { + owed = true; + field.update({ liftM }); + }, + ports, + ); return { setAlpha(value) { if (value === shownAlpha) return; @@ -118,7 +125,6 @@ function createWindShell(viewer, draw, texture, alpha) { /** 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, @@ -126,15 +132,13 @@ export function createWindRendering({ 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; @@ -163,16 +167,11 @@ export function createWindRendering({ let gpuActive = false; let reportedGpuReady = null; let gpuNarrow = false; - 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; @@ -188,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); @@ -211,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. @@ -227,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, ]; @@ -248,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) && @@ -275,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) || @@ -310,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; @@ -332,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; @@ -342,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() { @@ -364,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 @@ -432,10 +420,11 @@ export function createWindRendering({ draw, texture, overlay === 'temperature' ? 1 : 0.85, + { cameraOf, frameOf }, ); imageryKind = kind; - updateImageryFade(viewer.scene.camera, true); - viewer.scene?.requestRender?.(); + updateImageryFade(heightOf(viewer), true); + requestRender(viewer); return; } imagery = globe.imagery.add({ @@ -449,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'); @@ -476,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; @@ -492,15 +481,15 @@ 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; @@ -512,13 +501,13 @@ export function createWindRendering({ 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(); @@ -533,7 +522,7 @@ export function createWindRendering({ if (!running || !field || hidden()) return; const viewer = viewerReady(); if (gpuActive) { - if (viewer) updateImageryFade(viewer.scene.camera); + if (viewer) updateImageryFade(heightOf(viewer)); if (viewer) gpu.updateVisibility(); return; } @@ -547,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; @@ -574,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(); @@ -585,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'; @@ -602,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. @@ -616,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; @@ -735,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 && @@ -756,7 +733,7 @@ export function createWindRendering({ particles = []; if (viewer && !gpuActive) { resize(viewer); - seed(viewer.scene, makeOccluder(viewer.scene)); + seed(viewer); } installImagery(); relief.attach(); diff --git a/src/layers/wind/rendering.test.mjs b/src/layers/wind/rendering.test.mjs index 2006cecbc..0976da15e 100644 --- a/src/layers/wind/rendering.test.mjs +++ b/src/layers/wind/rendering.test.mjs @@ -1,7 +1,5 @@ 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'; @@ -11,6 +9,7 @@ import { renderShells, } from '../weather/shellFixture.mjs'; import { createCesiumFields } from '../../render/cesium/drawFields.js'; +import { toLonLatH } from '../../geo/ellipsoid.js'; function event() { const listeners = new Set(); @@ -179,6 +178,7 @@ function harness({ const viewer = { container, imageryLayers, + canvas, scene: { canvas, camera: { @@ -200,40 +200,48 @@ function harness({ isDestroyed: () => false, }; const shellCesium = shell ? createShellCesium() : null; - const cesium = { - ...(shellCesium ?? {}), - 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(); - } + // 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, @@ -254,7 +262,7 @@ function harness({ motion, preRender, viewer, - cesium: shellCesium ?? cesium, + cesium: shellCesium, imagery, removed, primitives: () => shellScene?.primitives.items ?? [], @@ -595,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); @@ -624,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); diff --git a/src/render/cesium/globe.js b/src/render/cesium/globe.js index 8f59ccd12..00ef48dd7 100644 --- a/src/render/cesium/globe.js +++ b/src/render/cesium/globe.js @@ -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?.(), diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 0473f91a3..3a7a147d0 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -5,8 +5,6 @@ "src/app/scene.js", "src/app/viewer.js", "src/data/geoImportPins.js", - "src/layers/wind/relief.js", - "src/layers/wind/rendering.js", "src/maps/catalog.js", "src/maps/controller.js", "src/maps/google3d.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 808235462..67a73aaf7 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -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', ]); /**