// cloud-map.js - Live satellite cloud map controller, dual-frame crossfade, and O(1) cloud sampling import * as THREE from "three"; import { CLOUD_LAYER_CONFIG } from "./constants.js"; import { configureColorTexture } from "./texture-colors.js"; import { earthTextureImages } from "./earth-texture-image.js"; const CLOUD_META_ENDPOINT = "/api/v1/earth/clouds/meta"; const CLOUD_BROADCAST_CHANNEL = "planet-earth-cloud-map"; const META_TIMEOUT_MS = 3500; const CROSSFADE_DURATION_MS = 1800; const TIMELAPSE_STEP_MS = 2800; const SAMPLER_WIDTH = 360; const SAMPLER_HEIGHT = 180; let _mode = "realtime"; // "realtime" | "static" let _timelapseEnabled = false; let _lastMeta = null; let _activeVersion = null; let _activeImageUrl = CLOUD_LAYER_CONFIG.textureUrl; let _samplerPixels = null; let _blendRaf = 0; let _timelapseTimer = null; let _timelapseIndex = 0; let _broadcastChannel = null; let _visibilityBound = false; let _inFlightSync = null; let _applyTextureCallback = null; let _getMaterialsCallback = null; function buildCloudStatusEventDetail() { return { mode: _mode, backendMode: _lastMeta?.mode || "static", degraded: Boolean(_lastMeta?.degraded), source: _lastMeta?.source || "static", capturedAt: _lastMeta?.captured_at || null, version: _activeVersion, timelapseEnabled: _timelapseEnabled, timelapseAvailable: Boolean(_lastMeta?.timelapse_enabled && (_lastMeta?.frames?.length || 0) > 1), frameCount: _lastMeta?.frames?.length || 0, globalCloudCoverPct: _lastMeta?.summary?.global_cloud_cover_pct ?? null, convectiveClusterCount: _lastMeta?.summary?.convective_cluster_count ?? 0, }; } function emitCloudMapStatus() { if (typeof window === "undefined") return; window.dispatchEvent( new CustomEvent("earth:cloud-map-status", { detail: buildCloudStatusEventDetail() }), ); } function updateSamplerFromImage(image) { if (typeof document === "undefined" || !image) { _samplerPixels = null; return; } try { const canvas = document.createElement("canvas"); canvas.width = SAMPLER_WIDTH; canvas.height = SAMPLER_HEIGHT; const ctx = canvas.getContext("2d", { willReadFrequently: true }); if (!ctx) return; // Note: ImageBitmap decoded with imageOrientation: "flipY" is already bottom-up for WebGL, // so drawing onto 2D canvas without flipping places -90..+90 or +90..-90 depending on source. // We detect ImageBitmap (closeable) vs HTMLImageElement and keep north-at-row-0 consistently. const isFlippedBitmap = typeof image.close === "function"; ctx.save(); if (isFlippedBitmap) { ctx.translate(0, SAMPLER_HEIGHT); ctx.scale(1, -1); } ctx.drawImage(image, 0, 0, SAMPLER_WIDTH, SAMPLER_HEIGHT); ctx.restore(); _samplerPixels = ctx.getImageData(0, 0, SAMPLER_WIDTH, SAMPLER_HEIGHT).data; } catch { _samplerPixels = null; } } export function sampleCloudCoverAtLatLon(lat, lon) { if (!_samplerPixels || !Number.isFinite(lat) || !Number.isFinite(lon)) return null; const clampedLat = Math.max(-89.99, Math.min(89.99, lat)); const wrappedLon = (((lon + 180) % 360) + 360) % 360 - 180; const col = Math.max(0, Math.min(SAMPLER_WIDTH - 1, Math.floor(((wrappedLon + 180) / 360) * SAMPLER_WIDTH))); const row = Math.max(0, Math.min(SAMPLER_HEIGHT - 1, Math.floor(((90 - clampedLat) / 180) * SAMPLER_HEIGHT))); const idx = (row * SAMPLER_WIDTH + col) * 4; const rgbAvg = (_samplerPixels[idx] + _samplerPixels[idx + 1] + _samplerPixels[idx + 2]) / 3; const alpha = _samplerPixels[idx + 3]; const density = Math.min(rgbAvg, alpha) / 255; return Math.round(Math.max(0, Math.min(1, density)) * 100); } async function decodeCloudTexture(url) { const image = await earthTextureImages.load(url); const texture = new THREE.Texture(image); if (typeof image.close === "function") { texture.flipY = false; texture.addEventListener("dispose", () => image.close()); } // Cloud density RGBA channels store linear weights [0..1], not sRGB gamma values. if ("NoColorSpace" in THREE) { texture.colorSpace = THREE.NoColorSpace; } texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.ClampToEdgeWrapping; texture.anisotropy = 16; texture.generateMipmaps = true; texture.minFilter = THREE.LinearMipmapLinearFilter; texture.magFilter = THREE.LinearFilter; texture.needsUpdate = true; updateSamplerFromImage(image); return texture; } let _visualUrl = null; let _flowUrl = null; let _visualTexture = null; let _flowTexture = null; let _pendingVisualTexture = null; let _pendingFlowTexture = null; let _pendingFlowMaxUv = 0; function disposeExtraTexture(refName) { if (refName === "visual" && _visualTexture) { _visualTexture.dispose?.(); _visualTexture = null; } if (refName === "flow" && _flowTexture) { _flowTexture.dispose?.(); _flowTexture = null; } } function applyAuxCloudUniforms({ visualTexture = _visualTexture, flowTexture = _flowTexture, flowMaxUv = 0, meta = _lastMeta, } = {}) { for (const mat of _getMaterialsCallback?.() || []) { if (!mat?.uniforms) continue; if (mat.uniforms.uCloudVisualMap) { mat.uniforms.uCloudVisualMap.value = visualTexture || null; } if (mat.uniforms.uCloudVisualEnabled) { mat.uniforms.uCloudVisualEnabled.value = meta?.geocolor_enabled !== false && visualTexture ? 1.0 : 0.0; } if (mat.uniforms.uCloudFlowMap) { mat.uniforms.uCloudFlowMap.value = flowTexture || null; } if (mat.uniforms.uCloudFlowEnabled) { mat.uniforms.uCloudFlowEnabled.value = meta?.optical_flow_enabled !== false && flowTexture && flowMaxUv > 0 ? 1.0 : 0.0; } if (mat.uniforms.uCloudFlowMaxUv) { mat.uniforms.uCloudFlowMaxUv.value = Number.isFinite(Number(flowMaxUv)) ? Number(flowMaxUv) : 0.0; } if (mat.uniforms.uReliefStrength && meta && meta.relief_shading_strength !== undefined) { const val = Number(meta.relief_shading_strength); if (Number.isFinite(val)) { mat.uniforms.uReliefStrength.value = val; } } } } async function decodeAuxTexture(url, { srgb = false } = {}) { if (!url) return null; try { const image = await earthTextureImages.load(url); const texture = new THREE.Texture(image); if (typeof image.close === "function") { texture.flipY = false; texture.addEventListener("dispose", () => image.close()); } if (srgb) { configureColorTexture(texture); } else if ("NoColorSpace" in THREE) { texture.colorSpace = THREE.NoColorSpace; } texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.ClampToEdgeWrapping; texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.LinearFilter; texture.needsUpdate = true; return texture; } catch { return null; } } function stopBlendAnimation(commitNext = true) { if (_blendRaf) { cancelAnimationFrame(_blendRaf); _blendRaf = 0; } const mats = _getMaterialsCallback?.() || []; const primaryMat = mats[0]; if (!primaryMat?.uniforms) return; const current = primaryMat.uniforms.uCloudMap?.value; const next = primaryMat.uniforms.uCloudMapNext?.value; if (commitNext && next) { if (_pendingVisualTexture && _pendingVisualTexture !== _visualTexture) { disposeExtraTexture("visual"); _visualTexture = _pendingVisualTexture; } _pendingVisualTexture = null; if (_pendingFlowTexture && _pendingFlowTexture !== _flowTexture) { disposeExtraTexture("flow"); _flowTexture = _pendingFlowTexture; } _pendingFlowTexture = null; _pendingFlowMaxUv = 0; for (const mat of mats) { if (!mat?.uniforms) continue; mat.uniforms.uCloudMap.value = next; if (mat.uniforms.uCloudMapNext) mat.uniforms.uCloudMapNext.value = null; if (mat.uniforms.uCloudHasNext) mat.uniforms.uCloudHasNext.value = 0; if (mat.uniforms.uCloudBlend) mat.uniforms.uCloudBlend.value = 0; if (mat.uniforms.uCloudVisualMap) mat.uniforms.uCloudVisualMap.value = _visualTexture || null; if (mat.uniforms.uCloudVisualEnabled) { mat.uniforms.uCloudVisualEnabled.value = _lastMeta?.geocolor_enabled !== false && _visualTexture ? 1.0 : 0.0; } if (mat.uniforms.uCloudFlowEnabled) mat.uniforms.uCloudFlowEnabled.value = 0.0; } if (current && current !== next) { current.dispose?.(); } } else if (next && next !== current) { for (const mat of mats) { if (!mat?.uniforms) continue; if (mat.uniforms.uCloudMapNext) mat.uniforms.uCloudMapNext.value = null; if (mat.uniforms.uCloudHasNext) mat.uniforms.uCloudHasNext.value = 0; if (mat.uniforms.uCloudBlend) mat.uniforms.uCloudBlend.value = 0; if (mat.uniforms.uCloudFlowEnabled) mat.uniforms.uCloudFlowEnabled.value = 0.0; } if (_pendingVisualTexture && _pendingVisualTexture !== _visualTexture) { _pendingVisualTexture.dispose?.(); } if (_pendingFlowTexture && _pendingFlowTexture !== _flowTexture) { _pendingFlowTexture.dispose?.(); } _pendingVisualTexture = null; _pendingFlowTexture = null; _pendingFlowMaxUv = 0; next.dispose?.(); } } export function transitionCloudTexture( nextTexture, { crossFadeMs = CROSSFADE_DURATION_MS, visualTexture = null, flowTexture = null, flowMaxUv = 0 } = {}, ) { const mats = _getMaterialsCallback?.() || []; const primaryMat = mats[0]; if (!primaryMat?.uniforms) return; const existing = primaryMat.uniforms.uCloudMap?.value; if (!existing || existing === nextTexture || crossFadeMs <= 0 || typeof requestAnimationFrame !== "function") { stopBlendAnimation(false); if (visualTexture !== _visualTexture) { disposeExtraTexture("visual"); _visualTexture = visualTexture || null; } if (flowTexture !== _flowTexture) { disposeExtraTexture("flow"); _flowTexture = flowTexture || null; } for (const mat of mats) { if (!mat?.uniforms) continue; mat.uniforms.uCloudMap.value = nextTexture; if (mat.uniforms.uCloudMapNext) mat.uniforms.uCloudMapNext.value = null; if (mat.uniforms.uCloudHasNext) mat.uniforms.uCloudHasNext.value = 0; if (mat.uniforms.uCloudBlend) mat.uniforms.uCloudBlend.value = 0; mat.needsUpdate = true; } applyAuxCloudUniforms({ visualTexture: _visualTexture, flowTexture: _flowTexture, flowMaxUv: 0, meta: _lastMeta, }); if (existing && existing !== nextTexture) { existing.dispose?.(); } _applyTextureCallback?.(nextTexture); return; } stopBlendAnimation(true); const previous = primaryMat.uniforms.uCloudMap?.value; if (previous === nextTexture) return; _pendingVisualTexture = visualTexture || null; _pendingFlowTexture = flowTexture || null; _pendingFlowMaxUv = Number(flowMaxUv || 0); if (_pendingVisualTexture) { disposeExtraTexture("visual"); _visualTexture = _pendingVisualTexture; _pendingVisualTexture = null; } for (const mat of mats) { if (!mat?.uniforms) continue; if (mat.uniforms.uCloudMapNext) mat.uniforms.uCloudMapNext.value = nextTexture; if (mat.uniforms.uCloudHasNext) mat.uniforms.uCloudHasNext.value = 1; if (mat.uniforms.uCloudBlend) mat.uniforms.uCloudBlend.value = 0; } applyAuxCloudUniforms({ visualTexture: _visualTexture, flowTexture: _pendingFlowTexture, flowMaxUv: _pendingFlowMaxUv, meta: _lastMeta, }); _applyTextureCallback?.(nextTexture); const startedAt = performance.now(); const step = (now) => { const progress = Math.min(1, (now - startedAt) / crossFadeMs); for (const mat of _getMaterialsCallback?.() || []) { if (mat?.uniforms?.uCloudBlend) { mat.uniforms.uCloudBlend.value = progress; } } if (progress < 1) { _blendRaf = requestAnimationFrame(step); } else { _blendRaf = 0; stopBlendAnimation(true); } }; _blendRaf = requestAnimationFrame(step); } async function fetchCloudMetaSafe() { if (typeof fetch !== "function") return null; const controller = typeof AbortController === "function" ? new AbortController() : null; const timer = controller ? setTimeout(() => controller.abort(), META_TIMEOUT_MS) : null; try { const response = await fetch(CLOUD_META_ENDPOINT, { cache: "no-store", signal: controller?.signal, }); if (!response.ok) return null; return await response.json(); } catch { return null; } finally { if (timer) clearTimeout(timer); } } function syncTimelapseLoop() { if (_timelapseTimer) { clearInterval(_timelapseTimer); _timelapseTimer = null; } if (_mode !== "realtime" || !_timelapseEnabled) return; const frames = _lastMeta?.frames; if (!_lastMeta?.timelapse_enabled || !Array.isArray(frames) || frames.length < 2) return; // Ordered oldest -> newest for chronological evolution const chronological = [...frames].reverse(); _timelapseIndex = chronological.length - 1; _timelapseTimer = setInterval(async () => { if (typeof document !== "undefined" && document.visibilityState === "hidden") return; const prevFrame = chronological[_timelapseIndex]; _timelapseIndex = (_timelapseIndex + 1) % chronological.length; const frame = chronological[_timelapseIndex]; if (!frame?.image_url) return; try { const useFlow = _lastMeta?.optical_flow_enabled !== false && frame.flow_url && frame.flow_prev_version === prevFrame?.version; const [texture, visTex, flowTex] = await Promise.all([ decodeCloudTexture(frame.image_url), _lastMeta?.geocolor_enabled !== false && frame.visual_url ? decodeAuxTexture(frame.visual_url, { srgb: false }) : Promise.resolve(null), useFlow ? decodeAuxTexture(frame.flow_url, { srgb: false }) : Promise.resolve(null), ]); _activeVersion = frame.version; _activeImageUrl = frame.image_url; transitionCloudTexture(texture, { crossFadeMs: 900, visualTexture: visTex, flowTexture: flowTex, flowMaxUv: useFlow ? Number(frame.flow_max_uv || 0) : 0, }); emitCloudMapStatus(); } catch { // Keep active texture on transient frame decode failure. } }, TIMELAPSE_STEP_MS); } export function bindCloudMaterialAccessors({ getMaterials, onTextureApplied }) { _getMaterialsCallback = getMaterials; _applyTextureCallback = onTextureApplied; } export function getCloudMapState() { return buildCloudStatusEventDetail(); } export function setCloudMapMode(nextMode) { const normalized = nextMode === "static" ? "static" : "realtime"; if (normalized === _mode) return; _mode = normalized; emitCloudMapStatus(); void refreshLiveCloudMap({ forceReload: true }); } export function setCloudTimelapseEnabled(enabled) { const next = Boolean(enabled); if (next === _timelapseEnabled) return; _timelapseEnabled = next; syncTimelapseLoop(); emitCloudMapStatus(); } export async function refreshLiveCloudMap({ forceReload = false } = {}) { if (_inFlightSync) return _inFlightSync; _inFlightSync = (async () => { let targetUrl = CLOUD_LAYER_CONFIG.textureUrl; let nextVersion = "static"; let nextVisualUrl = null; let nextFlowUrl = null; let nextFlowMaxUv = 0; const isFirstLoad = !(_getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value); if (_mode === "realtime") { const meta = await fetchCloudMetaSafe(); if (meta) { _lastMeta = meta; for (const mat of _getMaterialsCallback?.() || []) { if (mat?.uniforms?.uOpacity && Number.isFinite(Number(meta.default_opacity))) { const nextOpacity = Number(meta.default_opacity); mat.userData.baseOpacity = nextOpacity; mat.uniforms.uOpacity.value = nextOpacity; } } if (meta.enabled && meta.mode === "realtime" && meta.image_url) { targetUrl = meta.image_url; nextVersion = meta.version || targetUrl; nextVisualUrl = meta.geocolor_enabled !== false ? meta.visual_url || null : null; nextFlowUrl = meta.optical_flow_enabled !== false ? meta.flow_url || null : null; nextFlowMaxUv = Number(meta.flow_max_uv || 0); } } } if ( !forceReload && !isFirstLoad && nextVersion === _activeVersion && targetUrl === _activeImageUrl && nextVisualUrl === _visualUrl && nextFlowUrl === _flowUrl ) { applyAuxCloudUniforms({ meta: _lastMeta }); syncTimelapseLoop(); emitCloudMapStatus(); return _getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value || null; } let texture = null; let visualTex = null; let flowTex = null; try { [texture, visualTex, flowTex] = await Promise.all([ decodeCloudTexture(targetUrl), nextVisualUrl ? decodeAuxTexture(nextVisualUrl, { srgb: false }) : Promise.resolve(null), !isFirstLoad && nextFlowUrl ? decodeAuxTexture(nextFlowUrl, { srgb: false }) : Promise.resolve(null), ]); _activeVersion = nextVersion; _activeImageUrl = targetUrl; _visualUrl = nextVisualUrl; _flowUrl = nextFlowUrl; } catch { if (targetUrl !== CLOUD_LAYER_CONFIG.textureUrl) { texture = await decodeCloudTexture(CLOUD_LAYER_CONFIG.textureUrl); _activeVersion = "static"; _activeImageUrl = CLOUD_LAYER_CONFIG.textureUrl; _visualUrl = null; _flowUrl = null; } else { throw new Error("Cloud map texture load failed"); } } transitionCloudTexture(texture, { crossFadeMs: isFirstLoad ? 0 : CROSSFADE_DURATION_MS, visualTexture: visualTex, flowTexture: flowTex, flowMaxUv: nextFlowMaxUv, }); syncTimelapseLoop(); emitCloudMapStatus(); return texture; })().finally(() => { _inFlightSync = null; }); return _inFlightSync; } export function initCloudMapSync() { if (typeof BroadcastChannel === "function" && !_broadcastChannel) { try { _broadcastChannel = new BroadcastChannel(CLOUD_BROADCAST_CHANNEL); _broadcastChannel.onmessage = () => { void refreshLiveCloudMap({ forceReload: true }); }; } catch { _broadcastChannel = null; } } if (typeof document?.addEventListener === "function" && !_visibilityBound) { _visibilityBound = true; document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && _mode === "realtime") { void refreshLiveCloudMap(); } }); } } export function disposeCloudMapSync() { stopBlendAnimation(false); if (_timelapseTimer) { clearInterval(_timelapseTimer); _timelapseTimer = null; } if (_broadcastChannel) { _broadcastChannel.close(); _broadcastChannel = null; } _samplerPixels = null; }