diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d760e39e..4c7acc5b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- A renderer can draw weather: the `weather` capability adds `globe.weather`, + with clouds, fog, haze, rain and snow (each 0 to 1) and the wind they drift + on. Where the renderer lists it, the view shows the conditions observed + under the camera, asked again after five minutes or 25 km of movement, and + the Display panel's Weather group can turn live weather off and set + clouds, fog, rain and snow by hand. The Cesium renderer does not draw + weather, and shows no Weather group (samehkhamis). - The globe opens at planet level, the whole Earth in view, on every renderer, instead of flying in to Austin. A shared link still flies from there to its view. An application can start somewhere else, a city for diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index b9e31b8d9..120668e21 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -138,6 +138,17 @@ The Cesium port lists `modelAtmosphere`: Cesium scatters drawn models through the atmosphere in the same stage as its distance fog, so models take it while `globe.sky`'s `fog` is on. +`weather` adds `globe.weather`: clouds, fog, haze, rain and snow drawn +around the view, each a strength from 0 to 1, with the wind they drift on. +`src/render/weather.js` keeps and clamps them alike for the renderer +(`mergeWeather`). The app's `src/viewWeather.js` sets the conditions observed +under the camera (the weather service, through +`deriveWeatherEffectProfile`), asking again after five minutes or 25 km, +and none from orbit; the Display panel's Weather group turns live off and +sets clouds, fog, rain and snow by hand, and shows only on a renderer that +lists `weather`. The Cesium port does not list it. The checks +`globe.weather` and `globe.weather.drawn` (a pixel check) pin it. + The Cesium port lists `followAutodetect`: an `autodetect` follow is Cesium's own AUTODETECT tracking frame, east-north-up on a still or slow target and an orbit frame (x along the inertial motion, z up) on a fast @@ -391,7 +402,7 @@ puts every member of `PORTS` in exactly one role. It changes no member. | `scene` | Draws the application's data as keyed, retained sets | `draw`, `drawSet` | | `view` | Places and moves the camera, hands pointer input to the application | `camera`, `flight`, `input`, `lease` | | `queries` | Picks, surface positions and heights, rays, projection, occlusion | `query` | -| `look` | Sky and atmosphere, surface shading, per-layer lighting, styles and screen effects | `effects`, `globe.sky`, `globe.setSurfaceShading`, `imageryLayer.lit` | +| `look` | Sky and atmosphere, surface shading, per-layer lighting, styles and screen effects | `effects`, `globe.sky`, `globe.weather`, `globe.setSurfaceShading`, `imageryLayer.lit` | | `host` | Canvas and life cycle, the frame loop and scene time, quality, capture, settling | `renderer`, `frame`, `quality` | An entry is a port or a `port.member` prefix; the most specific one wins, so diff --git a/src/app/controls.js b/src/app/controls.js index e7309f4d4..6a3235996 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -2,6 +2,10 @@ import { catalogControlServices } from './catalog.js'; import { StyleManager } from '../ui/composition.js'; import { applyStartView, START_VIEW } from '../camera.js'; import { initCockpitCloudEffects } from '../cockpitCloudEffects.js'; +import { createViewWeather } from '../viewWeather.js'; +import { findGlobe } from '../render/rendererOf.js'; +import { useDisplayStore } from '../ui/stores/display.js'; +import { applicationPinia } from '../ui/vueRuntime.js'; import { t } from '../i18n/index.js'; /** @@ -52,10 +56,20 @@ export function createApplicationControls({ // clouds use a separate, capped low-resolution GPU pass that never attaches // Cesium fog or post-process stages and is fully stopped in map mode. const weatherEffects = null; - const cockpitCloudEffects = initCockpitCloudEffects(viewer, { - weatherService: operations.requests.weather, - }); + // Where the renderer draws weather, it draws the cockpit's clouds too. + const cockpitCloudEffects = findGlobe(viewer)?.weather + ? null + : initCockpitCloudEffects(viewer, { + weatherService: operations.requests.weather, + }); defer(() => cockpitCloudEffects?.destroy()); + // Clouds, fog, rain and snow on a renderer that draws them: the conditions + // under the camera, or what the user sets in the Display panel. + const viewWeather = createViewWeather(viewer, { + weatherService: operations.requests.weather, + store: useDisplayStore(applicationPinia()), + }); + defer(() => viewWeather.destroy()); loaderStatus.textContent = styleManager.hasShareState ? t('Restoring shared view...') diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index ce2c3b24d..566ec9eba 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -3812,5 +3812,11 @@ "{source} imagery could not be opened": "تعذّر فتح صور {source}", "{place} has no position to look for imagery at": "لا يوجد لـ{place} موضع للبحث عن الصور فيه", "No {source} imagery near {place}": "لا توجد صور {source} قرب {place}", - "{reason} (filters on: {filters})": "{reason} (المرشحات المفعّلة: {filters})" + "{reason} (filters on: {filters})": "{reason} (المرشحات المفعّلة: {filters})", + "Clouds": "السحب", + "Fog": "الضباب", + "Rain": "المطر", + "Snow": "الثلج", + "Live weather: the conditions under the camera": "الطقس المباشر: الأحوال تحت الكاميرا", + "No weather report here": "لا يوجد تقرير طقس هنا" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 8181fa0c1..c6ba1b655 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -3488,5 +3488,11 @@ "{source} imagery could not be opened": "Bilder von {source} konnten nicht geöffnet werden", "{place} has no position to look for imagery at": "{place} hat keine Position, an der nach Bildern gesucht werden kann", "No {source} imagery near {place}": "Keine Bilder von {source} in der Nähe von {place}", - "{reason} (filters on: {filters})": "{reason} (aktive Filter: {filters})" + "{reason} (filters on: {filters})": "{reason} (aktive Filter: {filters})", + "Clouds": "Wolken", + "Fog": "Nebel", + "Rain": "Regen", + "Snow": "Schnee", + "Live weather: the conditions under the camera": "Live-Wetter: die Bedingungen unter der Kamera", + "No weather report here": "Hier gibt es keinen Wetterbericht" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 423944a33..aef09c1df 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -3569,5 +3569,11 @@ "{source} imagery could not be opened": "No se pudieron abrir las imágenes de {source}", "{place} has no position to look for imagery at": "{place} no tiene una posición donde buscar imágenes", "No {source} imagery near {place}": "No hay imágenes de {source} cerca de {place}", - "{reason} (filters on: {filters})": "{reason} (filtros activos: {filters})" + "{reason} (filters on: {filters})": "{reason} (filtros activos: {filters})", + "Clouds": "Nubes", + "Fog": "Niebla", + "Rain": "Lluvia", + "Snow": "Nieve", + "Live weather: the conditions under the camera": "Clima en directo: las condiciones bajo la cámara", + "No weather report here": "No hay parte meteorológico aquí" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 2488c8d83..06094e0ee 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -3569,5 +3569,11 @@ "{source} imagery could not be opened": "Impossible d'ouvrir les images de {source}", "{place} has no position to look for imagery at": "{place} n'a pas de position où chercher des images", "No {source} imagery near {place}": "Aucune image {source} près de {place}", - "{reason} (filters on: {filters})": "{reason} (filtres actifs : {filters})" + "{reason} (filters on: {filters})": "{reason} (filtres actifs : {filters})", + "Clouds": "Nuages", + "Fog": "Brouillard", + "Rain": "Pluie", + "Snow": "Neige", + "Live weather: the conditions under the camera": "Météo en direct : les conditions sous la caméra", + "No weather report here": "Aucun bulletin météo ici" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index b2a0e1aee..5c010baf9 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -3569,5 +3569,11 @@ "{source} imagery could not be opened": "לא ניתן היה לפתוח את הצילומים של {source}", "{place} has no position to look for imagery at": "ל-{place} אין מיקום לחיפוש צילומים", "No {source} imagery near {place}": "אין צילומים של {source} ליד {place}", - "{reason} (filters on: {filters})": "{reason} (מסננים פעילים: {filters})" + "{reason} (filters on: {filters})": "{reason} (מסננים פעילים: {filters})", + "Clouds": "עננים", + "Fog": "ערפל", + "Rain": "גשם", + "Snow": "שלג", + "Live weather: the conditions under the camera": "מזג אוויר חי: התנאים מתחת למצלמה", + "No weather report here": "אין כאן דיווח מזג אוויר" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 51b0fe4e7..f94486e65 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -3569,5 +3569,11 @@ "{source} imagery could not be opened": "Impossibile aprire le immagini di {source}", "{place} has no position to look for imagery at": "{place} non ha una posizione in cui cercare immagini", "No {source} imagery near {place}": "Nessuna immagine di {source} vicino a {place}", - "{reason} (filters on: {filters})": "{reason} (filtri attivi: {filters})" + "{reason} (filters on: {filters})": "{reason} (filtri attivi: {filters})", + "Clouds": "Nuvole", + "Fog": "Nebbia", + "Rain": "Pioggia", + "Snow": "Neve", + "Live weather: the conditions under the camera": "Meteo in diretta: le condizioni sotto la telecamera", + "No weather report here": "Nessun bollettino meteo qui" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 954b501a6..bfff96ddf 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -3407,5 +3407,11 @@ "{source} imagery could not be opened": "{source}の画像を開けませんでした", "{place} has no position to look for imagery at": "{place}には画像を探す位置がありません", "No {source} imagery near {place}": "{place}の近くに{source}の画像はありません", - "{reason} (filters on: {filters})": "{reason}(有効なフィルター: {filters})" + "{reason} (filters on: {filters})": "{reason}(有効なフィルター: {filters})", + "Clouds": "雲", + "Fog": "霧", + "Rain": "雨", + "Snow": "雪", + "Live weather: the conditions under the camera": "ライブ気象:カメラ直下の状況", + "No weather report here": "ここには気象情報がありません" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index ea730c24e..2f946be08 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -3569,5 +3569,11 @@ "{source} imagery could not be opened": "Não foi possível abrir as imagens de {source}", "{place} has no position to look for imagery at": "{place} não tem uma posição para buscar imagens", "No {source} imagery near {place}": "Nenhuma imagem de {source} perto de {place}", - "{reason} (filters on: {filters})": "{reason} (filtros ativos: {filters})" + "{reason} (filters on: {filters})": "{reason} (filtros ativos: {filters})", + "Clouds": "Nuvens", + "Fog": "Nevoeiro", + "Rain": "Chuva", + "Snow": "Neve", + "Live weather: the conditions under the camera": "Clima ao vivo: as condições sob a câmara", + "No weather report here": "Sem boletim meteorológico aqui" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index dbea59318..8b5e981b5 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -3650,5 +3650,11 @@ "{source} imagery could not be opened": "Не удалось открыть снимки {source}", "{place} has no position to look for imagery at": "У места «{place}» нет координат для поиска снимков", "No {source} imagery near {place}": "Нет снимков {source} рядом с {place}", - "{reason} (filters on: {filters})": "{reason} (включены фильтры: {filters})" + "{reason} (filters on: {filters})": "{reason} (включены фильтры: {filters})", + "Clouds": "Облака", + "Fog": "Туман", + "Rain": "Дождь", + "Snow": "Снег", + "Live weather: the conditions under the camera": "Погода сейчас: условия под камерой", + "No weather report here": "Здесь нет сводки погоды" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 2e52f4c25..04f43f2c2 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -3488,5 +3488,11 @@ "Play speed": "Uppspelningshastighet", "Scroll or pinch to zoom, drag to move along · double-click to see it all": "Scrolla eller nyp för att zooma, dra för att flytta · dubbelklicka för att se allt", "Live": "Live", - "Back to live": "Tillbaka till live" + "Back to live": "Tillbaka till live", + "Clouds": "Moln", + "Fog": "Dimma", + "Rain": "Regn", + "Snow": "Snö", + "Live weather: the conditions under the camera": "Väder live: förhållandena under kameran", + "No weather report here": "Ingen väderrapport här" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 699c6d0c0..3d861fe43 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -3650,5 +3650,11 @@ "{source} imagery could not be opened": "Не вдалося відкрити знімки {source}", "{place} has no position to look for imagery at": "Для місця «{place}» немає координат для пошуку знімків", "No {source} imagery near {place}": "Немає знімків {source} поблизу {place}", - "{reason} (filters on: {filters})": "{reason} (увімкнено фільтри: {filters})" + "{reason} (filters on: {filters})": "{reason} (увімкнено фільтри: {filters})", + "Clouds": "Хмари", + "Fog": "Туман", + "Rain": "Дощ", + "Snow": "Сніг", + "Live weather: the conditions under the camera": "Погода зараз: умови під камерою", + "No weather report here": "Тут немає зведення погоди" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index ffe3745ce..6e284f183 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -3407,5 +3407,11 @@ "{source} imagery could not be opened": "无法打开 {source} 影像", "{place} has no position to look for imagery at": "{place} 没有可查找影像的位置", "No {source} imagery near {place}": "{place} 附近没有 {source} 影像", - "{reason} (filters on: {filters})": "{reason}(已开启筛选:{filters})" + "{reason} (filters on: {filters})": "{reason}(已开启筛选:{filters})", + "Clouds": "云", + "Fog": "雾", + "Rain": "雨", + "Snow": "雪", + "Live weather: the conditions under the camera": "实时天气:相机下方的状况", + "No weather report here": "此处没有天气报告" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 6f45baaf3..d0b607ab7 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -3407,5 +3407,11 @@ "{source} imagery could not be opened": "無法打開 {source} 影像", "{place} has no position to look for imagery at": "{place} 沒有可查找影像的位置", "No {source} imagery near {place}": "{place} 附近沒有 {source} 影像", - "{reason} (filters on: {filters})": "{reason}(已開啟篩選:{filters})" + "{reason} (filters on: {filters})": "{reason}(已開啟篩選:{filters})", + "Clouds": "雲", + "Fog": "霧", + "Rain": "雨", + "Snow": "雪", + "Live weather: the conditions under the camera": "即時天氣:相機下方的狀況", + "No weather report here": "此處沒有天氣報告" } diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index d9a9e58f8..e826b0eec 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -4642,6 +4642,71 @@ export function portChecks() { }, ), + check( + 'globe.weather', + 'weather starts clear, keeps what a set leaves out, and clamps', + (h, r) => { + const first = r.globe.weather.get(); + for (const key of ['clouds', 'fog', 'haze', 'rain', 'snow']) + equal(first[key], 0, `${key} clear at first`); + equal(first.wind.speedMps, 0, 'no wind at first'); + r.globe.weather.set({ clouds: 0.6, rain: 2 }); + r.globe.weather.set({ + fog: -1, + wind: { speedMps: 8, fromDeg: -45 }, + }); + const after = r.globe.weather.get(); + near(after.clouds, 0.6, 1e-9, 'clouds kept'); + equal(after.rain, 1, 'rain clamped to 1'); + equal(after.fog, 0, 'fog clamped to 0'); + equal(after.snow, 0, 'snow untouched'); + near(after.wind.speedMps, 8, 1e-9, 'wind speed'); + near(after.wind.fromDeg, 315, 1e-9, 'wind direction wrapped'); + after.clouds = 0; + near(r.globe.weather.get().clouds, 0.6, 1e-9, 'get hands out a copy'); + }, + { capability: 'weather' }, + ), + check( + 'globe.weather.drawn', + 'clouds and fog change the drawn frame; clearing them brings it back', + async (h, r) => { + if (h.pixels === false) return { skip: 'reads pixels' }; + // Low and looking toward the horizon, where fog and a cloud layer + // both show. + r.camera.setView({ + destination: { ...AUSTIN, height: 600 }, + orientation: { heading: 0, pitch: -0.12, roll: 0 }, + }); + const frame = async () => { + await drawn(h, r, 4); + await settled(r); + r.frame.renderNow(); + return r.readPixels({ scale: 0.1 }).data; + }; + const apart = (a, b) => { + let sum = 0; + for (let i = 0; i < a.length; i += 4) + for (let c = 0; c < 3; c++) sum += Math.abs(a[i + c] - b[i + c]); + return sum / ((a.length / 4) * 3); + }; + const clear = await frame(); + r.globe.weather.set({ clouds: 1, fog: 1 }); + const weathered = await frame(); + ok( + apart(clear, weathered) > 6, + `weather changes the frame (${apart(clear, weathered).toFixed(1)})`, + ); + r.globe.weather.set({ clouds: 0, fog: 0 }); + const again = await frame(); + ok( + apart(clear, again) < 3, + `cleared, the frame is back (${apart(clear, again).toFixed(1)})`, + ); + }, + { capability: 'weather' }, + ), + // --- Effects, credits, quality --------------------------------------- check( 'effects.styles', diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts index be18fc2e9..bfd62fe3c 100644 --- a/src/render/contract/common.d.ts +++ b/src/render/contract/common.d.ts @@ -152,6 +152,8 @@ export type Capability = | 'terrain' /** Atmosphere scattering applied to drawn models. */ | 'modelAtmosphere' + /** Clouds, fog, haze, rain and snow around the view (`globe.weather`). */ + | 'weather' /** Imagery draped onto 3D tiles as well as the globe. */ | 'imageryOnTiles' /** A screen-split comparison between imagery layers. */ diff --git a/src/render/contract/contract.test.mjs b/src/render/contract/contract.test.mjs index a5d623b9b..5128847b1 100644 --- a/src/render/contract/contract.test.mjs +++ b/src/render/contract/contract.test.mjs @@ -76,20 +76,26 @@ function nestedShape(type) { return null; } -/** `[member, optional]` for every member, nested shapes dotted. */ -function members(type, prefix = '') { +/** + * `[member, optional]` for every member, nested shapes dotted; a member of + * an optional shape is as optional as the shape. + */ +function members(type, prefix = '', inOptional = false) { const out = []; for (const property of checker.getPropertiesOfType(type)) { const name = `${prefix}${property.name}`; - const optional = Boolean(property.flags & ts.SymbolFlags.Optional); + const optional = + inOptional || Boolean(property.flags & ts.SymbolFlags.Optional); out.push([name, optional]); const declaration = property.valueDeclaration ?? property.declarations?.[0]; - const propertyType = checker.getTypeOfSymbolAtLocation( - property, - declaration, - ); + const declared = checker.getTypeOfSymbolAtLocation(property, declaration); + // An optional member's shape, without the `undefined` its `?` adds. + const propertyType = + property.flags & ts.SymbolFlags.Optional + ? checker.getNonNullableType(declared) + : declared; const nested = nestedShape(propertyType); - if (nested) out.push(...members(nested, `${name}.`)); + if (nested) out.push(...members(nested, `${name}.`, optional)); } return out; } diff --git a/src/render/contract/globe.d.ts b/src/render/contract/globe.d.ts index 96fa34227..1b292d2cc 100644 --- a/src/render/contract/globe.d.ts +++ b/src/render/contract/globe.d.ts @@ -215,6 +215,36 @@ export interface SkySettings { lighting: boolean; } +/** + * `weather`: the conditions drawn around the view. Each strength is 0..1, + * 0 drawing none of it; all are 0 at first. Clouds are a layer above the + * ground that the camera can fly into and above; fog and haze thin what is + * seen with distance, fog close in, haze far off; rain and snow fall around + * the eye below the clouds and are not drawn from above them. A renderer + * fades what makes no sense at the camera's height (rain from orbit) by + * itself. None of it is picked or answers height queries. The application sets the + * conditions observed at the view, which the user can override. + */ +export interface WeatherSettings { + /** Cloud cover. */ + clouds: number; + /** Fog: 1 is about 500 m visibility or less. */ + fog: number; + /** Haze. */ + haze: number; + /** Rain. */ + rain: number; + /** Snow. */ + snow: number; + /** What the clouds and precipitation drift with. */ + wind: { + /** Metres per second. */ + speedMps: number; + /** Where the wind blows from, degrees clockwise from north. */ + fromDeg: number; + }; +} + /** * View-lit shading of the drawn terrain's own relief (the ellipsoid's * curvature where terrain has no normals); darkens only, at most @@ -295,6 +325,18 @@ export interface GlobePort { get(): SkySettings; set(settings: Partial): void; }; + /** + * `weather`. `set` keeps each strength it is not given or given as no + * number, clamps the others to 0..1, and asks for a frame. `wind` is taken + * whole: a speed below 0 or missing is 0, the direction is wrapped into + * [0, 360) and a missing one is 0. `get` answers a copy of what was set; + * at first every strength and the wind speed are 0 (`CLEAR_WEATHER` in + * `src/render/weather.js`, whose `mergeWeather` is these rules). + */ + readonly weather?: { + get(): WeatherSettings; + set(settings: Partial): void; + }; /** Whether that part of the base has finished loading what is in view. */ isSettled(kind: SettleKind): boolean; on(event: 'progress', cb: (progress: LoadProgress) => void): Off; diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 754f9ca55..700f8cf58 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -19,6 +19,7 @@ export const CAPABILITIES = Object.freeze([ 'finestHeights', 'terrain', 'modelAtmosphere', + 'weather', 'imageryOnTiles', 'splitSwipe', 'imageryFrames', @@ -147,6 +148,9 @@ export const PORTS = deepFreeze({ ['setSurfaceShading', 'surfaceShading'], ['imagery.getSplit', 'splitSwipe'], ['imagery.setSplit', 'splitSwipe'], + ['weather', 'weather'], + ['weather.get', 'weather'], + ['weather.set', 'weather'], ]), draw: Object.fromEntries([ ...required( @@ -353,6 +357,7 @@ export const ROLES = deepFreeze([ members: [ 'effects', 'globe.sky', + 'globe.weather', 'globe.setSurfaceShading', 'imageryLayer.lit', ], diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 6d0decbbb..b08849e85 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -14,6 +14,7 @@ import { alongLength } from '../../geo/polyline.js'; import { clusterScreenPoints } from '../../geo/screenCluster.js'; import { createInputRouter } from '../input/router.js'; import { cssColor } from '../color.js'; +import { CLEAR_WEATHER, mergeWeather } from '../weather.js'; import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js'; import { createStubCamera } from './camera.js'; import { motionPosition } from '../motion/iconMotion.js'; @@ -1659,6 +1660,16 @@ export function createStubRenderer(options = {}) { }; }, }; + if (capabilities.has('weather')) { + let weather = CLEAR_WEATHER; + globe.weather = { + get: () => mergeWeather(weather), + set(patch) { + weather = mergeWeather(weather, patch); + requestRender('weather'); + }, + }; + } if (capabilities.has('globeVisibility')) globe.isGlobeVisible = () => globeVisible; if (capabilities.has('surfaceIdentity')) diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index ffe951a96..2d1313253 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => { .filter((r) => r.status === 'skip') .map((r) => r.id); // It draws only models into pixels, so the sweep's, a lit shape's, a line outline's and - // the blends' (over a drawn shape) and video tiles' pixels go unread; its camera takes no user gestures: the drag and wheel scripts are for a + // the blends' (over a drawn shape), video tiles' and the weather's pixels go unread; its camera takes no user gestures: the drag and wheel scripts are for a // camera that does (a controller over it, say). assert.deepEqual(skipped, [ 'effects.screenModulation.pixels', @@ -29,6 +29,7 @@ test('the stub passes the conformance suite', async () => { 'draw.sets.blend', 'draw.models.blend', 'globe.imagery.video', + 'globe.weather.drawn', ...CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`), ]); }); diff --git a/src/render/weather.js b/src/render/weather.js new file mode 100644 index 000000000..d42bf7af2 --- /dev/null +++ b/src/render/weather.js @@ -0,0 +1,42 @@ +/** + * The weather a renderer draws (`globe.weather`, the `weather` capability): + * clear at first, and how a `set` merges into what was set. Shared by every + * renderer that lists `weather`, so they keep and clamp it alike. + */ + +/** @type {Readonly} */ +export const CLEAR_WEATHER = Object.freeze({ + clouds: 0, + fog: 0, + haze: 0, + rain: 0, + snow: 0, + wind: Object.freeze({ speedMps: 0, fromDeg: 0 }), +}); + +const STRENGTHS = ['clouds', 'fog', 'haze', 'rain', 'snow']; + +const unit = (value, fallback) => + Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : fallback; + +/** + * `current` with `patch` applied: each strength given is clamped to 0..1, + * one not given (or not a number) is kept; `wind` is taken whole, its speed + * at least 0 and its direction in [0, 360). + * @param {import('./contract/globe').WeatherSettings} current + * @param {Partial} [patch] + * @returns {import('./contract/globe').WeatherSettings} + */ +export function mergeWeather(current, patch = {}) { + const next = { ...current, wind: { ...current.wind } }; + for (const key of STRENGTHS) next[key] = unit(patch[key], current[key]); + if (patch.wind) { + const speed = Number(patch.wind.speedMps); + const from = Number(patch.wind.fromDeg); + next.wind = { + speedMps: Number.isFinite(speed) ? Math.max(0, speed) : 0, + fromDeg: Number.isFinite(from) ? ((from % 360) + 360) % 360 : 0, + }; + } + return next; +} diff --git a/src/render/weather.test.mjs b/src/render/weather.test.mjs new file mode 100644 index 000000000..143a3990d --- /dev/null +++ b/src/render/weather.test.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { CLEAR_WEATHER, mergeWeather } from './weather.js'; + +test('clear weather draws nothing', () => { + for (const key of ['clouds', 'fog', 'haze', 'rain', 'snow']) + assert.equal(CLEAR_WEATHER[key], 0, key); + assert.deepEqual(CLEAR_WEATHER.wind, { speedMps: 0, fromDeg: 0 }); +}); + +test('a set keeps what it is not given and clamps strengths', () => { + const a = mergeWeather(CLEAR_WEATHER, { clouds: 0.4, rain: 3 }); + assert.equal(a.clouds, 0.4); + assert.equal(a.rain, 1); + const b = mergeWeather(a, { fog: -1, snow: Number.NaN }); + assert.equal(b.fog, 0); + assert.equal(b.snow, 0); + assert.equal(b.clouds, 0.4, 'clouds kept'); + assert.equal(b.rain, 1, 'rain kept'); +}); + +test('wind is taken whole, its speed at least 0, its direction wrapped', () => { + const a = mergeWeather(CLEAR_WEATHER, { + wind: { speedMps: 12, fromDeg: -90 }, + }); + assert.deepEqual(a.wind, { speedMps: 12, fromDeg: 270 }); + const b = mergeWeather(a, { wind: { speedMps: -3, fromDeg: 725 } }); + assert.deepEqual(b.wind, { speedMps: 0, fromDeg: 5 }); + const c = mergeWeather(b, { clouds: 1 }); + assert.deepEqual(c.wind, b.wind, 'wind kept'); + assert.notEqual(c.wind, b.wind, 'a copy'); +}); diff --git a/src/ui/stores/display.js b/src/ui/stores/display.js index 42d5b51fa..0826c79b9 100644 --- a/src/ui/stores/display.js +++ b/src/ui/stores/display.js @@ -28,6 +28,17 @@ export const useDisplayStore = defineStore('gev-display', () => { models3d.value = markRaw(next); } + /** + * The Weather group, `{live, status, values}` (values in percent by + * condition); null where the renderer draws no weather. + */ + const weather = shallowRef(null); + + /** @param {?object} next A fresh presentation of the Weather group. */ + function publishWeather(next) { + weather.value = next && markRaw(next); + } + /** The Draw controls; null until the draw tool first renders. */ const draw = shallowRef(null); @@ -108,6 +119,8 @@ export const useDisplayStore = defineStore('gev-display', () => { publish, models3d, publishModels3d, + weather, + publishWeather, draw, publishDraw, geoImport, diff --git a/src/ui/views/panels/DisplayPanel.vue b/src/ui/views/panels/DisplayPanel.vue index 3cd202161..9e8d5e524 100644 --- a/src/ui/views/panels/DisplayPanel.vue +++ b/src/ui/views/panels/DisplayPanel.vue @@ -17,7 +17,7 @@ import { StyleParameterRows } from '../../styleParameters.js'; // and each publishes them; until they do, the panel shows its initial markup. // Draw and Import live in UTILITIES (LayerPanelsView). const display = useDisplayStore(); -const { view, models3d, parameters, cockpitPortal } = storeToRefs(display); +const { view, models3d, parameters, cockpitPortal, weather } = storeToRefs(display); // A control's change goes to its owner (DisplayBindings). const act = (name, ...args) => display.act(name, ...args); const pct = (value) => `${value}%`; @@ -35,6 +35,12 @@ const celestialTitle = computed(() => ? t('Celestial ring — available in Normal style') : t('Celestial ring — reveal the full globe'), ); +const weatherRows = computed(() => [ + { key: 'clouds', label: t('Clouds') }, + { key: 'fog', label: t('Fog') }, + { key: 'rain', label: t('Rain') }, + { key: 'snow', label: t('Snow') }, +]); const models3dOn = computed(() => models3d.value?.pressed ?? true); const modelsMode = computed(() => models3d.value?.mode ?? 'proximity'); const modelsOptions = computed(() => [ @@ -175,6 +181,22 @@ const allocationOptions = computed(() => [ {{ t('Celestial') }} + +
+ +
+ {{ t('No weather report here') }} +
+
+ {{ row.label }} + + {{ pct(weather.values[row.key] ?? 0) }} +
+