Spaces:
Running

LunarVideoMap / js /main.js
AK51's picture
Upload 24 files
32db17e verified
Raw History Blame Contribute Delete
73.1 kB
import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { LOCATIONS } from './locations.js'; import { bodyToView, transpose, apply, latLonToBody, bodyToLatLon, angDist, imageDataToGray, detectDisc, matchOrientation, prepareTexture, litCentroid, sunViewVector, phaseFromLitFraction, } from './moonfit.js'; import { readMp4VideoInfo } from './mp4info.js'; import { STRINGS, FEATURE_I18N, QUICK_PICKS } from './i18n.js'; const SAMPLE_VIDEO = 'short_flash.mp4'; const SAMPLE_LONG = '2026-10-20-234910-Lunar.mp4'; const MOON_RADIUS_KM = 1737.4; const $ = (id) => document.getElementById(id); /* ===================================================================== Internationalisation (English / Simplified / Traditional Chinese) ===================================================================== */ const LANGS = ['en', 'zh-CN', 'zh-TW']; function detectLang() { const saved = localStorage.getItem('moonMapper.lang'); if (LANGS.includes(saved)) return saved; const n = (navigator.language || 'en').toLowerCase(); if (n.startsWith('zh')) return /tw|hk|mo|hant/.test(n) ? 'zh-TW' : 'zh-CN'; return 'en'; } let LANG = detectLang(); /** Translate a key, filling {placeholders}. Falls back to English, then to the key. */ function t(key, p = {}) { const s = STRINGS[LANG]?.[key] ?? STRINGS.en[key] ?? key; return s.replace(/\{(\w+)\}/g, (m, k) => (p[k] ?? m)); } const fName = (f) => FEATURE_I18N[LANG]?.[f.name]?.n ?? f.name; const fDesc = (f) => FEATURE_I18N[LANG]?.[f.name]?.d ?? f.desc; const catName = (c) => t('cat.' + c); const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); /** Error whose message is re-translated when the language changes. */ const i18nError = (key, p) => Object.assign(new Error(t(key, p)), { key, p }); const CAT_COLORS = { 'Landing & Rover Sites': '#ffcf4d', 'Maria, Oceans & Bays': '#59c3ff', 'Craters': '#c9a6ff', 'Poles & Basins': '#7dffb0', }; const CAT_DEFAULT_ON = { 'Landing & Rover Sites': true, 'Maria, Oceans & Bays': true, 'Craters': false, 'Poles & Basins': false }; /* ===================================================================== State ===================================================================== */ const S = { video: { W: 1080, H: 1920, fps: 30, name: '', src: '', loaded: false }, disc: null, // {cx, cy, r, litCx, litCy} in source px (alignment frame) fit: { theta: 0, b0: 0, l0: 0, mirror: false, s: 0 }, adj: { rad: 1, dx: 0, dy: 0 }, drift: { x: 0, y: 0 }, ref: null, // lit centroid at the alignment frame (source px) track: null, // per-frame lit centroids from a flash scan (Float32Array, x,y pairs) sunView: [0, 0, 1], prior: { b0: 0, l0: 0, phase: null, date: null }, aligned: false, views: { overlay: true, lroc: true, geo: true }, geoAmt: 0, // Shared view: Z scales the Moon's on-screen radius identically in every pane; // pan is the point at the pane centre, in Moon-disc radii (x right, y up, as seen in the video). Z: 1, pan: { x: 0, y: 0 }, fullFrame: false, grid: 0.5, gridStep: 10, gridLabels: true, color: 0, colorMode: 1, sat: 4, cats: { ...CAT_DEFAULT_ON }, focus: null, pick: null, flashes: [], flashSel: null, showFlashMarks: true, pickExtra: null, scanning: false, cancelScan: false, }; // Last-rendered status messages, kept as data so they can be re-rendered in another language. const UI = { video: null, ephem: null, align: null, flash: null, tex: null }; /* ===================================================================== Renderer & scenes ===================================================================== */ const canvas = $('gl'); const wrap = $('canvasWrap'); const video = $('video'); const renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.outputColorSpace = THREE.LinearSRGBColorSpace; // all textures are passed through raw renderer.setClearColor(0x000000, 1); const videoTex = new THREE.VideoTexture(video); videoTex.colorSpace = THREE.NoColorSpace; videoTex.minFilter = THREE.LinearFilter; videoTex.magFilter = THREE.LinearFilter; const texLoader = new THREE.TextureLoader(); function setupMap(t) { t.colorSpace = THREE.NoColorSpace; t.wrapS = THREE.RepeatWrapping; t.generateMipmaps = true; // the shader supplies seam-free gradients (textureGrad) t.minFilter = THREE.LinearMipmapLinearFilter; t.magFilter = THREE.LinearFilter; t.anisotropy = renderer.capabilities.getMaxAnisotropy(); return t; } const MAPS = { lroc: { lo: 'assets/moon_color_2k.jpg', hi: 'assets/moon_color_{R}.jpg', uni: 'uLroc', name: 'LROC' }, geo: { lo: 'assets/moon_geologic_2k.jpg', hi: 'assets/moon_geologic_{R}.jpg', uni: 'uGeo', name: 'Geologic' }, }; const lrocTex = setupMap(texLoader.load(MAPS.lroc.lo, () => loadHiRes('lroc'))); const geoTex = setupMap(texLoader.load(MAPS.geo.lo, () => loadHiRes('geo'))); const loadedRes = {}; function loadHiRes(kind) { const want = $('selRes').value; // '8k' or '16k' const px = want === '16k' ? 16384 : 8192; const res = renderer.capabilities.maxTextureSize >= px ? want : renderer.capabilities.maxTextureSize >= 8192 ? '8k' : null; const max = renderer.capabilities.maxTextureSize; if (res !== want) setTex({ k: 'tex.need', p: { want, px, max } }); if (!res || loadedRes[kind] === res) return; if (res === want) setTex({ k: 'tex.loading', p: { kind, res } }); texLoader.load(MAPS[kind].hi.replace('{R}', res), (tex) => { setupMap(tex); const old = overlayMat.uniforms[MAPS[kind].uni].value; for (const m of [overlayMat, globeMat, geoMat]) m.uniforms[MAPS[kind].uni].value = tex; if (old !== lrocTex && old !== geoTex) old.dispose(); // free the previous hi-res map's GPU memory loadedRes[kind] = res; if (res === want) setTex({ k: 'tex.loaded', p: { kind, res } }); }); } function setTex(m) { UI.tex = m; renderTex(); } function renderTex() { const m = UI.tex; $('texInfo').textContent = m ? t(m.k, { ...m.p, name: m.p.kind ? t('map.' + m.p.kind) : '' }) : ''; } $('selRes').addEventListener('change', () => { loadHiRes('lroc'); loadHiRes('geo'); }); const commonUniforms = () => ({ uLroc: { value: lrocTex }, uGeo: { value: geoTex }, uGeoAmt: { value: 0 }, uVideo: { value: videoTex }, uHasVideo: { value: 0 }, uVideoSize: { value: new THREE.Vector2(1080, 1920) }, uGrid: { value: S.grid }, uStep: { value: S.gridStep }, uColor: { value: S.color }, uMode: { value: S.colorMode }, uSat: { value: S.sat }, uShade: { value: 1 }, uSunB: { value: new THREE.Vector3(1, 0, 0) }, uM: { value: new THREE.Matrix3() }, uDisc: { value: new THREE.Vector3(540, 960, 300) }, uDrape: { value: 0 }, uAligned: { value: 0 }, }); const VERT = /* glsl */ ` varying vec3 vBody; varying vec3 vWorld; void main() { vBody = position; vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`; const FRAG = /* glsl */ ` uniform sampler2D uLroc, uVideo, uGeo; uniform float uGeoAmt; uniform float uHasVideo, uGrid, uStep, uColor, uMode, uSat, uShade, uDrape, uAligned; uniform vec2 uVideoSize; uniform vec3 uSunB, uDisc; uniform mat3 uM; varying vec3 vBody; varying vec3 vWorld; const float PI = 3.141592653589793; const float R2D = 57.29577951308232; const vec3 LW = vec3(0.299, 0.587, 0.114); // Equirectangular lookup with seam-free derivatives, so mipmaps/anisotropy stay sharp // and there is no line at the +-180 deg seam. vec3 sampleMap(sampler2D t, vec2 uv, vec2 dx, vec2 dy) { return textureGrad(t, uv, dx, dy).rgb; } void main() { vec3 p = normalize(vBody); float lat = asin(clamp(p.y, -1.0, 1.0)); float lon = atan(-p.z, p.x); vec2 tuv = vec2(lon / (2.0 * PI) + 0.5, lat / PI + 0.5); vec2 u2 = vec2(fract(tuv.x + 0.5), tuv.y); vec2 gdx = dFdx(tuv), gdy = dFdy(tuv); vec2 gdx2 = dFdx(u2), gdy2 = dFdy(u2); if (abs(gdx2.x) + abs(gdy2.x) < abs(gdx.x) + abs(gdy.x)) { gdx.x = gdx2.x; gdy.x = gdy2.x; } vec3 lroc = sampleMap(uLroc, tuv, gdx, gdy); vec3 geo = sampleMap(uGeo, tuv, gdx, gdy); float ll = max(dot(lroc, LW), 0.02); vec3 boosted = max(vec3(0.0), vec3(ll) + (lroc - vec3(ll)) * uSat); float sun = max(dot(p, uSunB), 0.0); float shade = 0.05 + 1.15 * sun; #ifdef OVERLAY vec2 vuv = vec2((vWorld.x + uVideoSize.x * 0.5) / uVideoSize.x, (vWorld.y + uVideoSize.y * 0.5) / uVideoSize.y); vec3 vid = texture2D(uVideo, vuv).rgb * uHasVideo; float vl = dot(vid, LW); vec3 colz = vl * boosted / ll; vec3 rep = boosted * shade; vec3 base = mix(vid, mix(rep, colz, uMode), uColor); base = mix(base, geo * (0.45 + 0.75 * clamp(vl * 2.5, 0.0, 1.0)), uGeoAmt); #else #ifdef GEO vec3 sim = geo * mix(1.0, 0.25 + 0.85 * sun, uShade); #else vec3 sim = boosted * mix(1.0, 0.14 + 1.05 * sun, uShade); #endif vec3 base = sim; if (uDrape > 0.5 && uHasVideo > 0.5 && uAligned > 0.5) { vec3 v = uM * p; if (v.z > 0.0) { vec2 px = vec2(uDisc.x + v.x * uDisc.z, uDisc.y - v.y * uDisc.z); vec2 vuv = vec2(px.x / uVideoSize.x, 1.0 - px.y / uVideoSize.y); if (vuv.x > 0.0 && vuv.x < 1.0 && vuv.y > 0.0 && vuv.y < 1.0) { vec3 vid = texture2D(uVideo, vuv).rgb; float vl = dot(vid, LW); vec3 vc = mix(vid, vl * boosted / ll, uColor); base = mix(sim, vc, smoothstep(0.0, 0.12, v.z)); } } } #endif // Selenographic grid (anti-aliased with screen-space derivatives). if (uGrid > 0.001) { float latD = lat * R2D; float lonD = lon * R2D; float lonD2 = atan(p.z, -p.x) * R2D; // continuous across the ±180° seam float fwLat = max(fwidth(latD), 1e-4); float fwLon = max(min(fwidth(lonD), fwidth(lonD2)), 1e-4); float dLat = abs(fract(latD / uStep + 0.5) - 0.5) * uStep / fwLat; float dLon = abs(fract(lonD / uStep + 0.5) - 0.5) * uStep / fwLon; float poleFade = 1.0 - smoothstep(76.0, 88.0, abs(latD)); float lLat = 1.0 - smoothstep(0.25, 1.1, dLat); float lLon = (1.0 - smoothstep(0.25, 1.1, dLon)) * poleFade; float eq = 1.0 - smoothstep(0.5, 1.6, abs(latD) / fwLat); float pm = (1.0 - smoothstep(0.5, 1.6, abs(lonD) / fwLon)) * poleFade; float special = max(eq, pm); float a = max(max(lLat, lLon), special) * uGrid; vec3 gcol = mix(vec3(1.0, 0.86, 0.35), vec3(1.0, 0.42, 0.2), special); base = mix(base, gcol, a); } gl_FragColor = vec4(base, 1.0); }`; // --- Overlay scene (orthographic, units = video pixels) --- // Narrow field so the 3D globes look like the near-orthographic telescope view. const GLOBE_FOV = 12; const MOON_FILL = 0.42; // at Z = 1 the Moon's radius is 42% of the pane's shorter side const overlayScene = new THREE.Scene(); const orthoCam = new THREE.OrthographicCamera(-1, 1, 1, -1, -5000, 5000); orthoCam.position.z = 1000; const videoPlane = new THREE.Mesh( new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: videoTex, toneMapped: false }) ); videoPlane.position.z = -3000; overlayScene.add(videoPlane); const overlayMat = new THREE.ShaderMaterial({ uniforms: commonUniforms(), vertexShader: VERT, fragmentShader: FRAG, defines: { OVERLAY: 1 }, }); const overlayMoon = new THREE.Mesh(new THREE.SphereGeometry(1, 160, 80), overlayMat); overlayMoon.matrixAutoUpdate = false; overlayMoon.visible = false; overlayScene.add(overlayMoon); // --- Globe scene (perspective, body frame = world frame) --- const globeScene = new THREE.Scene(); const persp = new THREE.PerspectiveCamera(GLOBE_FOV, 1, 0.01, 3000); persp.position.set(0, 0, 4); const globeMat = new THREE.ShaderMaterial({ uniforms: commonUniforms(), vertexShader: VERT, fragmentShader: FRAG }); const geoMat = new THREE.ShaderMaterial({ uniforms: commonUniforms(), vertexShader: VERT, fragmentShader: FRAG, defines: { GEO: 1 } }); const globe = new THREE.Mesh(new THREE.SphereGeometry(1, 256, 128), globeMat); globeScene.add(globe); globeScene.add(makeStars()); const controls = new OrbitControls(persp, canvas); controls.enablePan = false; controls.enableZoom = false; // zoom is shared across panes and handled in the wheel listener controls.enableDamping = true; controls.minDistance = 1.0005; controls.maxDistance = 2000; controls.rotateSpeed = 0.6; function makeStars() { const n = 2500, pos = new Float32Array(n * 3); for (let i = 0; i < n; i++) { const u = Math.random() * 2 - 1, t = Math.random() * Math.PI * 2, r = 900 + Math.random() * 300; const s = Math.sqrt(1 - u * u); pos.set([r * s * Math.cos(t), r * u, r * s * Math.sin(t)], i * 3); } const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); return new THREE.Points(g, new THREE.PointsMaterial({ color: 0x8899bb, size: 1.6, sizeAttenuation: false })); } /* ===================================================================== Geometry helpers ===================================================================== */ const curM = () => bodyToView(S.fit.theta, S.fit.b0, S.fit.l0, S.fit.mirror); function effDisc() { if (!S.disc) return null; return { cx: S.disc.cx + S.adj.dx + S.drift.x, cy: S.disc.cy + S.adj.dy + S.drift.y, r: S.disc.r * S.adj.rad, }; } /** Source-pixel position of a body point, or null when on the hidden hemisphere. */ function bodyToVideoPx(p, M = curM(), d = effDisc(), minZ = 0) { if (!d) return null; const v = apply(M, p); if (v[2] < minZ) return null; return { x: d.cx + v[0] * d.r, y: d.cy - v[1] * d.r, z: v[2] }; } function videoPxToLatLon(x, y, M = curM(), d = effDisc()) { if (!d) return null; const X = (x - d.cx) / d.r, Y = -(y - d.cy) / d.r, R2 = X * X + Y * Y; if (R2 >= 1) return null; const p = apply(transpose(M), [X, Y, Math.sqrt(1 - R2)]); return bodyToLatLon(p); } const sunBody = () => apply(transpose(curM()), S.sunView); const isLit = (p) => { const s = sunBody(); return p[0] * s[0] + p[1] * s[1] + p[2] * s[2] > 0; }; /* ===================================================================== Layout / views ===================================================================== */ let cssW = 1, cssH = 1; const VIEW_ORDER = ['overlay', 'lroc', 'geo']; const isGlobe = (k) => k === 'lroc' || k === 'geo'; function rects() { const keys = VIEW_ORDER.filter((k) => S.views[k]); const out = {}; const n = keys.length || 1; keys.forEach((k, i) => { const x0 = Math.round((i * cssW) / n), x1 = Math.round(((i + 1) * cssW) / n); out[k] = { x: x0, y: 0, w: x1 - x0, h: cssH }; }); return out; } const anyGlobe = () => S.views.lroc || S.views.geo; function whichRect(px, py) { const R = rects(); for (const k in R) { const r = R[k]; if (px >= r.x && px < r.x + r.w && py >= r.y && py < r.y + r.h) return k; } return null; } /** Moon radius in CSS px for a pane at the current shared zoom. */ const moonPx = (rect) => S.Z * MOON_FILL * Math.min(rect.w, rect.h); const moonLocked = () => S.aligned && !!S.disc && !S.fullFrame; /** Orthographic camera for the video pane: centre (world units) and half-height. */ function orthoView(rect) { if (!moonLocked()) { const a = rect.w / rect.h, va = S.video.W / S.video.H; return { cx: 0, cy: 0, hh: (a > va ? S.video.H / 2 : S.video.W / 2 / a) * 1.02 }; } const d = effDisc(), c = videoPxToWorld(d.cx, d.cy); return { cx: c.x + S.pan.x * d.r, cy: c.y + S.pan.y * d.r, hh: (d.r * rect.h) / (2 * moonPx(rect)) }; } function updateOrtho(rect) { const a = rect.w / rect.h, v = orthoView(rect); orthoCam.left = v.cx - v.hh * a; orthoCam.right = v.cx + v.hh * a; orthoCam.top = v.cy + v.hh; orthoCam.bottom = v.cy - v.hh; orthoCam.updateProjectionMatrix(); } function cssToWorld(rect, px, py) { const a = rect.w / rect.h, v = orthoView(rect); return { x: v.cx + (((px - rect.x) / rect.w) * 2 - 1) * v.hh * a, y: v.cy - (((py - rect.y) / rect.h) * 2 - 1) * v.hh, }; } function worldToCss(rect, wx, wy) { const a = rect.w / rect.h, v = orthoView(rect); return { x: rect.x + ((wx - v.cx) / (v.hh * a) + 1) * 0.5 * rect.w, y: rect.y + (1 - (wy - v.cy) / v.hh) * 0.5 * rect.h, }; } /** * Perspective camera for a globe pane, distance chosen so the Moon matches the video pane: * at low zoom the silhouette radius equals moonPx; when zoomed in, the scale at the point * being looked at matches instead (perspective would otherwise magnify the near surface more). */ function setupGlobeCam(rect) { persp.aspect = rect.w / rect.h; const tanH = Math.tan((GLOBE_FOV * Math.PI) / 360); // Keep GLOBE_FOV across the narrower side so portrait panes behave like landscape ones. persp.fov = persp.aspect >= 1 ? GLOBE_FOV : (2 * Math.atan(tanH / persp.aspect) * 180) / Math.PI; persp.updateProjectionMatrix(); const f = (Math.min(rect.w, rect.h) / 2) / tanH; // focal length in px const q = f / moonPx(rect); const dSil = Math.sqrt(1 + q * q), dCen = 1 + q; const w = Math.max(0, Math.min(1, (S.Z - 1) / 3)); const D = Math.max(1.0008, dSil + (dCen - dSil) * w); const off = persp.position.clone().sub(controls.target); if (off.lengthSq() < 1e-12) off.set(0, 0, 1); persp.position.copy(controls.target).add(off.setLength(D)); } const videoPxToWorld = (x, y) => ({ x: x - S.video.W / 2, y: S.video.H / 2 - y }); const worldToVideoPx = (wx, wy) => ({ x: wx + S.video.W / 2, y: S.video.H / 2 - wy }); function resize() { const b = wrap.getBoundingClientRect(); cssW = Math.max(1, Math.floor(b.width)); cssH = Math.max(1, Math.floor(b.height)); renderer.setSize(cssW, cssH, false); } new ResizeObserver(resize).observe(wrap); /* ===================================================================== Labels (HTML) ===================================================================== */ const labelRoot = $('labels'); const labelPool = new Map(); let labelUsed = new Set(); let placedBoxes = []; const PRIORITY = { focus: 3, flash: 3, 'flash live': 3, pick: 3 }; function putLabel(key, x, y, text, cls = '', color = null, title = '') { // Greedy decluttering: skip ordinary labels that would overlap earlier ones. const w = text.length * (cls === 'grid' ? 5.6 : 6.4) + 10, h = cls === 'grid' ? 11 : 14; const box = cls === 'grid' ? [x - w / 2, y - h / 2, x + w / 2, y + h / 2] : [x - 6, y - h / 2, x + w, y + h / 2]; if (!PRIORITY[cls]) { for (const b of placedBoxes) if (box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1]) return; } placedBoxes.push(box); let el = labelPool.get(key); if (!el) { el = document.createElement('div'); labelRoot.appendChild(el); labelPool.set(key, el); } if (el._t !== text) { el.textContent = text; el._t = text; } const c = 'lbl ' + cls; if (el.className !== c) el.className = c; if (color) el.style.setProperty('--c', color); el.title = title; el.style.left = x.toFixed(1) + 'px'; el.style.top = y.toFixed(1) + 'px'; el.style.display = ''; labelUsed.add(key); } function flushLabels() { placedBoxes = []; for (const [k, el] of labelPool) if (!labelUsed.has(k)) el.style.display = 'none'; labelUsed = new Set(); } /** Iterate items to label in a view: yields {key, p(body), text, cls, color}. */ function labelItems() { const out = []; const litOnly = $('chkLitOnly').checked && S.aligned; for (const f of LOCATIONS) { const focused = S.focus === f; if (!S.cats[f.cat] && !focused) continue; const p = latLonToBody(f.lat, f.lon); if (litOnly && !focused && !isLit(p)) continue; out.push({ key: 'f:' + f.name, p, text: fName(f), cls: focused ? 'focus' : '', color: CAT_COLORS[f.cat] }); } // A pick made by selecting a flash sits under the flash marker, so the flash label replaces it. const pickIsFlash = S.pickExtra?.k === 'pick.flash'; if (S.pick && !pickIsFlash) out.push({ key: 'pick', p: latLonToBody(S.pick.lat, S.pick.lon), text: `${fmtLat(S.pick.lat)} ${fmtLon(S.pick.lon)}`, cls: 'pick' }); if (S.showFlashMarks) { const now = video.currentTime; for (const fl of S.flashes) { if (fl.lat == null) continue; const live = Math.abs(now - fl.peakTime) < 0.4; if (S.flashSel === fl || live) out.push({ key: 'fl:' + fl.index, p: latLonToBody(fl.lat, fl.lon), text: t('flash.label', { i: fl.index }), cls: live ? 'flash live' : 'flash' }); } } // Special labels first so they win collisions, then landing sites, maria, the rest. const rank = (it) => (it.cls ? 0 : it.color === CAT_COLORS['Landing & Rover Sites'] ? 1 : it.color === CAT_COLORS['Maria, Oceans & Bays'] ? 2 : 3); return out.sort((a, b) => rank(a) - rank(b)); } function gridLabelItems(centerLon) { if (!S.gridLabels || S.grid < 0.05) return []; const step = Math.max(S.gridStep, 10); const out = []; for (let lon = -180 + step; lon < 180; lon += step) out.push({ key: 'gl:' + lon, p: latLonToBody(0, lon), text: lon === 0 ? '0°' : `${Math.abs(lon)}°${lon > 0 ? 'E' : 'W'}` }); const cl = Math.round(centerLon / step) * step; for (let lat = -80; lat <= 80; lat += step) { if (lat === 0) continue; out.push({ key: 'gp:' + lat, p: latLonToBody(lat, cl + step / 2), text: `${Math.abs(lat)}°${lat > 0 ? 'N' : 'S'}` }); } return out; } const tmpV = new THREE.Vector3(); function layoutLabels() { const R = rects(); if (R.overlay && S.aligned) { const rect = R.overlay, M = curM(), d = effDisc(); const place = (it, minZ, gridCls) => { const q = bodyToVideoPx(it.p, M, d, minZ); if (!q) return; const w = videoPxToWorld(q.x, q.y), c = worldToCss(rect, w.x, w.y); if (c.x < rect.x || c.x > rect.x + rect.w || c.y < 0 || c.y > rect.h) return; putLabel('o:' + it.key, c.x, c.y, it.text, gridCls || it.cls, it.color); }; const centre = bodyToLatLon(apply(transpose(M), [0, 0, 1])); for (const it of labelItems()) place(it, it.cls ? 0 : 0.12); for (const it of gridLabelItems(centre.lon)) place(it, 0.25, 'grid'); } for (const gk of ['lroc', 'geo']) { if (!R[gk]) continue; const rect = R[gk]; const camDir = persp.position.clone().normalize(); const place = (it, minDot, gridCls) => { tmpV.set(it.p[0], it.p[1], it.p[2]); const toCam = persp.position.clone().sub(tmpV); if (tmpV.dot(toCam) / toCam.length() < minDot) return; tmpV.project(persp); if (tmpV.z > 1) return; const x = rect.x + (tmpV.x * 0.5 + 0.5) * rect.w, y = rect.y + (0.5 - tmpV.y * 0.5) * rect.h; if (x < rect.x || x > rect.x + rect.w) return; putLabel(gk + ':' + it.key, x, y, it.text, gridCls || it.cls, it.color); }; const centre = bodyToLatLon([camDir.x, camDir.y, camDir.z]); for (const it of labelItems()) place(it, it.cls ? 0 : 0.1); for (const it of gridLabelItems(centre.lon)) place(it, 0.25, 'grid'); } updateViewTitles(R); flushLabels(); } const titleEls = {}; function updateViewTitles(R) { for (const k of VIEW_ORDER) { let el = titleEls[k]; if (!el) { el = titleEls[k] = document.createElement('div'); el.className = 'viewtitle ' + k; $('canvasWrap').appendChild(el); } const txt = t('title.' + k); if (el.textContent !== txt) el.textContent = txt; const r = R[k]; el.style.display = r ? '' : 'none'; if (r) { el.style.left = r.x + 'px'; el.style.width = r.w + 'px'; el.classList.toggle('sep', r.x > 0); } } } /* ===================================================================== Render loop ===================================================================== */ function syncUniforms() { const M = curM(), d = effDisc(); const m3 = new THREE.Matrix3().set(...M); const sb = sunBody(); for (const mat of [overlayMat, globeMat, geoMat]) { const u = mat.uniforms; u.uHasVideo.value = S.video.loaded ? 1 : 0; u.uVideoSize.value.set(S.video.W, S.video.H); u.uGrid.value = S.grid; u.uStep.value = S.gridStep; u.uColor.value = S.color; u.uMode.value = S.colorMode; u.uSat.value = S.sat; u.uShade.value = $('chkShade').checked ? 1 : 0; u.uSunB.value.set(sb[0], sb[1], sb[2]); u.uM.value.copy(m3); if (d) u.uDisc.value.set(d.cx, d.cy, d.r); u.uDrape.value = $('chkVideoOnGlobe').checked ? 1 : 0; u.uAligned.value = S.aligned ? 1 : 0; u.uGeoAmt.value = S.geoAmt; } videoPlane.scale.set(S.video.W, S.video.H, 1); overlayMoon.visible = S.aligned && !!d; if (d) { const w = videoPxToWorld(d.cx, d.cy); const m4 = new THREE.Matrix4().set( M[0] * d.r, M[1] * d.r, M[2] * d.r, w.x, M[3] * d.r, M[4] * d.r, M[5] * d.r, w.y, M[6] * d.r, M[7] * d.r, M[8] * d.r, 0, 0, 0, 0, 1); overlayMoon.matrix.copy(m4); overlayMoon.matrixWorldNeedsUpdate = true; } } function frame() { requestAnimationFrame(frame); controls.update(); syncUniforms(); const R = rects(); renderer.setScissorTest(true); renderer.clear(); for (const k in R) { const r = R[k]; const y = cssH - (r.y + r.h); renderer.setViewport(r.x, y, r.w, r.h); renderer.setScissor(r.x, y, r.w, r.h); if (k === 'overlay') { updateOrtho(r); renderer.render(overlayScene, orthoCam); } else { globe.material = k === 'geo' ? geoMat : globeMat; setupGlobeCam(r); renderer.render(globeScene, persp); } } layoutLabels(); updateTransport(); } /* ===================================================================== Video loading ===================================================================== */ function loadVideo(src, name, file = null) { S.video.loaded = false; S.aligned = false; stopReplay(); S.disc = null; S.track = null; S.flashes = []; S.flashSel = null; S.pick = null; S.pickExtra = null; UI.flash = null; UI.align = null; renderFlashList(); renderFlashInfo(); renderAlign(); updateStats(); $('flashMarksRow').classList.add('hidden'); $('pickInfo').classList.add('hidden'); if (S.video.src && S.video.src.startsWith('blob:')) URL.revokeObjectURL(S.video.src); S.video.src = src; S.video.name = name; UI.video = { name }; renderVideoName(); video.src = src; video.load(); setTimestampFromName(name); const infoP = readMp4VideoInfo(file || src); video.addEventListener('loadeddata', async () => { S.video.W = video.videoWidth; S.video.H = video.videoHeight; S.video.loaded = true; S.Z = 1; S.pan = { x: 0, y: 0 }; S.fullFrame = false; UI.video = { name, w: video.videoWidth, h: video.videoHeight, dur: video.duration.toFixed(1) }; renderVideoName(); const info = await infoP; S.video.fps = info ? info.fps : await estimateFps(); S.video.frames = info ? info.frames : null; $('fpsInput').placeholder = S.video.fps.toFixed(2); // Align on a frame a little into the clip (the first frames are often soft). await seekMain(Math.min(1, video.duration / 2)); await runAlign(); // Short clips are cheap to scan, so look for flashes straight away. if (S.video.frames && S.video.frames <= 400) scanFlashes(); }, { once: true }); } function setTimestampFromName(name) { const m = /(\d{4})-(\d{2})-(\d{2})[-_T ]?(\d{2})(\d{2})(\d{2})/.exec(name); if (m) { $('obsTime').value = `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}`; computeEphem(); } else { $('obsTime').value = ''; UI.ephem = { k: 'eph.none' }; renderEphem(); S.prior = { b0: 0, l0: 0, phase: null, date: null }; } } function renderVideoName() { const v = UI.video; $('videoName').textContent = !v ? t('vid.none') : v.w ? t('vid.info', v) : v.name; } function renderEphem() { const e = UI.ephem; $('ephemInfo').textContent = e ? t(e.k, e.p) : ''; } function computeEphem() { const v = $('obsTime').value; if (!v || typeof Astronomy === 'undefined') return; const [d, t] = v.split('T'); const [Y, Mo, D] = d.split('-').map(Number); const [h, mi, s] = (t || '0:0:0').split(':').map(Number); const off = Number($('utcOffset').value) || 0; const date = new Date(Date.UTC(Y, Mo - 1, D, h, mi, s || 0) - off * 3600e3); try { const L = Astronomy.Libration(date); const il = Astronomy.Illumination(Astronomy.Body.Moon, date); S.prior = { b0: L.elat, l0: L.elon, phase: il.phase_angle, date }; UI.ephem = { k: 'eph.info', p: { utc: date.toISOString().replace('T', ' ').slice(0, 19), b: L.elat.toFixed(2), l: L.elon.toFixed(2), phase: il.phase_angle.toFixed(1), pct: (il.phase_fraction * 100).toFixed(0), diam: (L.diam_deg * 60).toFixed(1) } }; } catch (e) { UI.ephem = { k: 'eph.err', p: { msg: e.message } }; } renderEphem(); } function estimateFps() { return new Promise((resolve) => { if (typeof video.requestVideoFrameCallback !== 'function') return resolve(30); const times = []; let done = false; const finish = () => { if (done) return; done = true; video.pause(); const d = []; for (let i = 1; i < times.length; i++) d.push(times[i] - times[i - 1]); d.sort((a, b) => a - b); const med = d[Math.floor(d.length / 2)]; resolve(med > 0.004 && med < 0.2 ? 1 / med : 30); }; const cb = (now, meta) => { times.push(meta.mediaTime); if (times.length >= 12) finish(); else video.requestVideoFrameCallback(cb); }; video.requestVideoFrameCallback(cb); video.play().catch(() => resolve(30)); setTimeout(finish, 2500); }); } function seekMain(t) { return seekVideo(video, t); } function seekVideo(v, t) { return new Promise((resolve) => { const target = Math.max(0, Math.min(t, (v.duration || 0) - 1e-3)); let settled = false; const done = () => { if (settled) return; settled = true; v.removeEventListener('seeked', done); clearTimeout(timer); resolve(); }; v.addEventListener('seeked', done); const timer = setTimeout(done, 1500); v.currentTime = Math.abs(v.currentTime - target) < 1e-4 ? target + 1e-3 : target; }); } /* ===================================================================== Frame grabbing ===================================================================== */ const grabCanvas = document.createElement('canvas'); const grabCtx = grabCanvas.getContext('2d', { willReadFrequently: true }); function grabFrame(v, targetW) { const W = v.videoWidth, H = v.videoHeight; const w = Math.max(16, Math.round(targetW)), h = Math.max(16, Math.round((targetW * H) / W)); grabCanvas.width = w; grabCanvas.height = h; grabCtx.drawImage(v, 0, 0, w, h); const img = grabCtx.getImageData(0, 0, w, h); return { img, gray: imageDataToGray(img), w, h, scale: W / w }; } /* ===================================================================== Recognition & alignment ===================================================================== */ let texPrepared = null; async function getMatchTexture() { if (texPrepared) return texPrepared; const img = await new Promise((res, rej) => { const i = new Image(); i.crossOrigin = 'anonymous'; i.onload = () => res(i); i.onerror = rej; i.src = 'assets/moon_color_2k.jpg'; }); const c = document.createElement('canvas'); c.width = 512; c.height = 256; const ctx = c.getContext('2d', { willReadFrequently: true }); ctx.drawImage(img, 0, 0, 512, 256); const g = imageDataToGray(ctx.getImageData(0, 0, 512, 256)); texPrepared = prepareTexture(g, 512, 256); return texPrepared; } function busy(key) { let el = $('busy'); if (!key) { if (el) el.remove(); return; } if (!el) { el = document.createElement('div'); el.id = 'busy'; el.innerHTML = '<div class="spinner"><div class="sp-moon"></div><div class="sp-orbit"></div></div><span></span>'; wrap.appendChild(el); } el.dataset.key = key; el.querySelector('span').textContent = t(key); } const nextPaint = () => new Promise((r) => requestAnimationFrame(() => setTimeout(r, 0))); async function runAlign() { if (!S.video.loaded) return; busy('busy.detect'); await nextPaint(); try { const tex = await getMatchTexture(); // Analysis scale: aim for a disc radius of ~130 px. let g = grabFrame(video, Math.min(640, video.videoWidth)); let disc = detectDisc(g.gray, g.w, g.h); if (!disc) throw i18nError('err.noDisc'); if (disc.r > 170 || disc.r < 90) { const target = Math.max(64, Math.min(1600, g.w * (130 / disc.r))); if (Math.abs(target - g.w) > 8 && target <= video.videoWidth) { g = grabFrame(video, target); disc = detectDisc(g.gray, g.w, g.h) || disc; } } busy('busy.match'); await nextPaint(); const t0 = performance.now(); const fit = matchOrientation(g.gray, g.w, g.h, disc, tex, { prior: { b0: S.prior.b0 || 0, l0: S.prior.l0 || 0 }, allowMirror: $('chkMirror').checked, }); if (!fit) throw i18nError('err.tooDark'); const k = g.scale; S.disc = { cx: disc.cx * k, cy: disc.cy * k, r: disc.r * k, litCx: disc.litCx * k, litCy: disc.litCy * k, litFrac: disc.litFrac }; S.fit = { theta: fit.theta, b0: fit.b0, l0: fit.l0, mirror: fit.mirror, s: fit.s }; S.adj = { rad: 1, dx: 0, dy: 0 }; const phase = S.prior.phase ?? phaseFromLitFraction(disc.litFrac); S.sunView = sunViewVector(S.disc, phase); S.phaseAngle = phase; const c = litCentroid(g.gray, g.w, g.h); S.ref = c ? { x: c.x * k, y: c.y * k, t: video.currentTime } : null; S.drift = { x: 0, y: 0 }; S.aligned = true; syncSliders(); fitOverlayToDisc(); UI.align = { limb: (disc.limbFrac * 100).toFixed(0), ms: (performance.now() - t0).toFixed(0) }; renderAlign(); updateStats(); drawThumb(); toast(t('toast.aligned', { s: fit.s.toFixed(2) }), 'ok'); if (S.flashes.length) remapFlashes(); } catch (e) { console.error(e); UI.align = { err: e.key ? { k: e.key, p: e.p } : { raw: e.message } }; renderAlign(); toast(t('toast.alignFail', { msg: alignErrText() }), 'err'); } finally { busy(null); } } const alignErrText = () => (UI.align?.err?.k ? t(UI.align.err.k, UI.align.err.p) : UI.align?.err?.raw || ''); /** Alignment report; reads the live fit so manual fine-tuning shows up too. */ function renderAlign() { const a = UI.align, el = $('alignInfo'); if (!a) { el.innerHTML = ''; return; } if (a.err) { el.innerHTML = `<span class="warn">\u26a0 ${esc(alignErrText())}</span>`; return; } const f = S.fit, d = S.disc; const q = f.s > 0.35 ? 'q.good' : f.s > 0.2 ? 'q.fair' : 'q.weak'; el.innerHTML = esc(t('align.disc', { cx: d.cx.toFixed(0), cy: d.cy.toFixed(0), r: d.r.toFixed(1), limb: a.limb })) + '<br>' + esc(t('align.orient', { theta: fmtTheta(f.theta), b: f.b0.toFixed(1), l: f.l0.toFixed(1) })) + (f.mirror ? ` \u00b7 <b>${esc(t('align.mirrored'))}</b>` : '') + '<br>' + esc(t('align.score', { s: f.s.toFixed(3), q: t(q), ms: a.ms })); } /** Reset the shared view: same-size Moon centred in every pane, globes seen from the video's viewpoint. */ function fitOverlayToDisc() { S.Z = 1; S.pan = { x: 0, y: 0 }; S.fullFrame = false; syncGlobeToOverlay(); } function fmtTheta(theta, short = false) { const cw = (360 - theta) % 360; const pre = short ? 'theta.short.' : 'theta.'; return cw <= 180 ? t(pre + 'cw', { v: cw.toFixed(1) }) : t(pre + 'ccw', { v: (360 - cw).toFixed(1) }); } /* ---- drift tracking ---- */ function updateDrift() { if (!S.aligned || !S.ref || !$('chkTrack').checked) { S.drift = { x: 0, y: 0 }; return; } const fps = getFps(); if (S.track) { const i = Math.round(video.currentTime * fps - 0.5); if (i >= 0 && i * 2 + 1 < S.track.length && !Number.isNaN(S.track[i * 2])) { S.drift = { x: S.track[i * 2] - S.ref.x, y: S.track[i * 2 + 1] - S.ref.y }; return; } } const g = grabFrame(video, 270); const c = litCentroid(g.gray, g.w, g.h); if (c) S.drift = { x: c.x * g.scale - S.ref.x, y: c.y * g.scale - S.ref.y }; } function onVideoFrame(now, meta) { updateDrift(); replayLoopCheck(meta ? meta.mediaTime : video.currentTime); video.requestVideoFrameCallback?.(onVideoFrame); } if (video.requestVideoFrameCallback) video.requestVideoFrameCallback(onVideoFrame); else video.addEventListener('timeupdate', () => { updateDrift(); replayLoopCheck(video.currentTime); }); video.addEventListener('seeked', updateDrift); /* ===================================================================== Features & picking ===================================================================== */ function fmtLat(v) { return t(v >= 0 ? 'lat.N' : 'lat.S', { v: Math.abs(v).toFixed(2) }); } function fmtLon(v) { return t(v >= 0 ? 'lon.E' : 'lon.W', { v: Math.abs(v).toFixed(2) }); } function nearest(lat, lon, n = 3) { return LOCATIONS.map((f) => ({ f, d: angDist(lat, lon, f.lat, f.lon) })).sort((a, b) => a.d - b.d).slice(0, n); } const kmOf = (deg) => (deg * Math.PI / 180) * MOON_RADIUS_KM; function visibilityNote(p) { if (!S.aligned) return t('vis.align'); const q = bodyToVideoPx(p, curM(), effDisc(), -2); if (q.z < 0) return t('vis.beyond'); const xy = { x: q.x.toFixed(0), y: q.y.toFixed(0) }; if (q.z < 0.15) return t('vis.near', xy); return t('vis.px', { ...xy, lit: t(isLit(p) ? 'vis.lit' : 'vis.dark') }); } function focusFeature(f, opts = {}) { S.focus = f; const card = $('featInfo'); if (!f) { card.classList.add('hidden'); return; } const p = latLonToBody(f.lat, f.lon); const alt = fName(f) !== f.name ? ` <span class="muted">${esc(f.name)}</span>` : ''; card.innerHTML = `<div class="fi-head" style="--c:${CAT_COLORS[f.cat]}"><span class="fi-dot"></span><b>${esc(fName(f))}</b>${alt}</div>` + `<div class="chip" style="--c:${CAT_COLORS[f.cat]}">${esc(catName(f.cat))}</div> ` + `<span class="coords">${esc(fmtLat(f.lat))}, ${esc(fmtLon(f.lon))}</span>` + `<p>${esc(fDesc(f))}</p><span class="muted">${esc(visibilityNote(p))}</span>`; card.classList.remove('hidden'); card.classList.remove('pop'); void card.offsetWidth; card.classList.add('pop'); if (opts.quiet) return; const v = S.aligned ? apply(curM(), p) : null; if (v && v[2] > 0.05 && S.Z > 1.05) { S.pan = { x: v[0], y: v[1] }; S.fullFrame = false; syncGlobeToOverlay(); } else if (anyGlobe()) flyGlobeTo(p); } /** Search English and translated names (all languages), then descriptions. */ function findFeature(q) { q = q.trim().toLowerCase(); if (!q) return null; const names = (f) => [f.name, ...LANGS.map((l) => FEATURE_I18N[l]?.[f.name]?.n).filter(Boolean)].map((s) => s.toLowerCase()); const descs = (f) => [f.desc, ...LANGS.map((l) => FEATURE_I18N[l]?.[f.name]?.d).filter(Boolean)].map((s) => s.toLowerCase()); return LOCATIONS.find((f) => names(f).includes(q)) || LOCATIONS.find((f) => names(f).some((n) => n.startsWith(q))) || LOCATIONS.find((f) => names(f).some((n) => n.includes(q))) || LOCATIONS.find((f) => descs(f).some((d) => d.includes(q))); } /** extra: optional {k, p} message key shown after the coordinates. */ function showPick(ll, extra = null) { S.pick = ll; S.pickExtra = extra; renderPick(); } function renderPick() { const ll = S.pick, el = $('pickInfo'); if (!ll) { el.classList.add('hidden'); return; } const p = latLonToBody(ll.lat, ll.lon); const nn = nearest(ll.lat, ll.lon, 4); const ex = S.pickExtra ? ` <span class="muted">${esc(t(S.pickExtra.k, S.pickExtra.p))}</span>` : ''; el.innerHTML = `<div class="fi-head"><span class="pick-dot"></span><b>${esc(t('pick.title'))}</b></div>` + `<span class="coords">${esc(fmtLat(ll.lat))}, ${esc(fmtLon(ll.lon))}</span>${ex}<br>` + `<span class="muted">${esc(visibilityNote(p))}</span><div class="nn-title">${esc(t('pick.nearest'))}</div>` + nn.map((x) => `<a href="#" class="nn" data-f="${esc(x.f.name)}" style="--c:${CAT_COLORS[x.f.cat]}">` + `<span class="fi-dot"></span>${esc(fName(x.f))}<em>${kmOf(x.d).toFixed(0)} km</em></a>`).join(''); el.classList.remove('hidden'); } $('pickInfo').addEventListener('click', (e) => { const a = e.target.closest('a[data-f]'); if (!a) return; e.preventDefault(); focusFeature(LOCATIONS.find((f) => f.name === a.dataset.f)); }); /* ---- globe camera ---- */ /** * Point the globe cameras at the same spot the video pane shows: look along the * telescope's line of sight, aimed at the pan point, with the video's "up". */ function syncGlobeToOverlay() { cancelAnimationFrame(flyAnim); const MT = transpose(bodyToView(S.fit.theta, S.fit.b0, S.fit.l0, false)); const x = S.fit.mirror ? -S.pan.x : S.pan.x; // the globe is never mirrored const tgt = apply(MT, [x, S.pan.y, 0]), dir = apply(MT, [0, 0, 1]), up = apply(MT, [0, 1, 0]); const D = Math.max(1.5, persp.position.distanceTo(controls.target)); controls.target.set(tgt[0], tgt[1], tgt[2]); persp.up.set(up[0], up[1], up[2]); persp.position.set(tgt[0] + dir[0] * D, tgt[1] + dir[1] * D, tgt[2] + dir[2] * D); persp.lookAt(controls.target); controls.update(); } function resetGlobeView() { syncGlobeToOverlay(); } let flyAnim = null; /** Rotate the globes (around their centre) to face body point p; distance stays with the shared zoom. */ function flyGlobeTo(p) { const tgt0 = controls.target.clone(); const from = persp.position.clone().sub(tgt0).normalize(); const to = new THREE.Vector3(p[0], p[1], p[2]).normalize(); const t0 = performance.now(); cancelAnimationFrame(flyAnim); const step = () => { const k = Math.min(1, (performance.now() - t0) / 900), e = k * k * (3 - 2 * k); controls.target.copy(tgt0).multiplyScalar(1 - e); const D = persp.position.distanceTo(controls.target); persp.position.copy(controls.target).add(from.clone().lerp(to, e).normalize().multiplyScalar(D)); persp.lookAt(controls.target); if (k < 1) flyAnim = requestAnimationFrame(step); }; step(); } /* ===================================================================== Pointer interaction ===================================================================== */ let drag = null; const raycaster = new THREE.Raycaster(); wrap.addEventListener('pointerdown', (e) => { if (e.target.closest?.('#replay')) return; // the replay panel handles its own input const b = wrap.getBoundingClientRect(), px = e.clientX - b.left, py = e.clientY - b.top; const r = whichRect(px, py); controls.enabled = isGlobe(r); drag = { r, px, py, sx: px, sy: py, pan: { ...S.pan }, moved: false }; if (r === 'overlay') wrap.setPointerCapture(e.pointerId); }, true); wrap.addEventListener('pointermove', (e) => { if (!drag) return; const b = wrap.getBoundingClientRect(), px = e.clientX - b.left, py = e.clientY - b.top; if (Math.hypot(px - drag.sx, py - drag.sy) > 4) drag.moved = true; if (drag.r === 'overlay' && drag.moved) { if (moonLocked()) { const R = moonPx(rects().overlay); S.pan = clampPan({ x: drag.pan.x - (px - drag.sx) / R, y: drag.pan.y + (py - drag.sy) / R }); syncGlobeToOverlay(); } } }); wrap.addEventListener('pointerup', (e) => { if (!drag || e.target.closest?.('#replay')) return; const b = wrap.getBoundingClientRect(), px = e.clientX - b.left, py = e.clientY - b.top; const d = drag; drag = null; if (d.moved || e.button !== 0) return; const R = rects(); if (d.r === 'overlay' && S.aligned) { const w = cssToWorld(R.overlay, px, py), v = worldToVideoPx(w.x, w.y); const ll = videoPxToLatLon(v.x, v.y); if (ll) showPick(ll, { k: 'pick.at', p: { x: v.x.toFixed(0), y: v.y.toFixed(0) } }); } else if (isGlobe(d.r)) { const r = R[d.r]; const ndc = new THREE.Vector2(((px - r.x) / r.w) * 2 - 1, -((py - r.y) / r.h) * 2 + 1); raycaster.setFromCamera(ndc, persp); const hit = raycaster.intersectObject(globe)[0]; if (hit) showPick(bodyToLatLon([hit.point.x, hit.point.y, hit.point.z])); } }); wrap.addEventListener('wheel', (e) => { if (e.target.closest?.('#replay')) return; // the replay panel handles its own input const b = wrap.getBoundingClientRect(), px = e.clientX - b.left, py = e.clientY - b.top; const r = whichRect(px, py); if (!r) return; e.preventDefault(); zoomAt(r, px, py, Math.exp(-e.deltaY * 0.0015)); }, { capture: true, passive: false }); const clampPan = (p) => { const L = Math.hypot(p.x, p.y); return L > 1.1 ? { x: (p.x / L) * 1.1, y: (p.y / L) * 1.1 } : p; }; /** * Change the shared zoom by `factor`. In the video pane the point under the cursor stays put * and the globes follow it; in a globe pane the zoom is about the pane centre. */ function zoomAt(paneKey, px, py, factor) { const R = rects(), rect = R[paneKey]; const Z0 = S.Z; S.Z = Math.max(0.35, Math.min(60, S.Z * factor)); if (S.Z === Z0) return; if (paneKey !== 'overlay' || !S.aligned || !S.disc) return; const wasFull = S.fullFrame; S.fullFrame = false; if (wasFull) { S.pan = { x: 0, y: 0 }; syncGlobeToOverlay(); return; } if (S.Z <= 1) { S.pan = { x: S.pan.x * S.Z, y: S.pan.y * S.Z }; syncGlobeToOverlay(); return; } const dx = px - (rect.x + rect.w / 2), dy = -(py - (rect.y + rect.h / 2)); const r0 = Z0 * MOON_FILL * Math.min(rect.w, rect.h), r1 = moonPx(rect); S.pan = clampPan({ x: S.pan.x + dx / r0 - dx / r1, y: S.pan.y + dy / r0 - dy / r1 }); syncGlobeToOverlay(); } wrap.addEventListener('mousemove', (e) => { if (e.target.closest?.('#replay')) return; // the replay panel handles its own input const b = wrap.getBoundingClientRect(), px = e.clientX - b.left, py = e.clientY - b.top; const R = rects(), r = whichRect(px, py); let ll = null; if (r === 'overlay' && S.aligned) { const w = cssToWorld(R.overlay, px, py), v = worldToVideoPx(w.x, w.y); ll = videoPxToLatLon(v.x, v.y); } else if (isGlobe(r)) { const g = R[r]; raycaster.setFromCamera(new THREE.Vector2(((px - g.x) / g.w) * 2 - 1, -((py - g.y) / g.h) * 2 + 1), persp); const hit = raycaster.intersectObject(globe)[0]; if (hit) ll = bodyToLatLon([hit.point.x, hit.point.y, hit.point.z]); } $('hud').textContent = ll ? `${fmtLat(ll.lat)} ${fmtLon(ll.lon)} \u00b7 ${t('hud.nearest', { name: fName(nearest(ll.lat, ll.lon, 1)[0].f) })}` : ''; }); /* drag & drop */ ['dragenter', 'dragover'].forEach((t) => window.addEventListener(t, (e) => { e.preventDefault(); $('dropHint').classList.remove('hidden'); })); ['dragleave', 'drop'].forEach((t) => window.addEventListener(t, (e) => { e.preventDefault(); if (t === 'drop' || !e.relatedTarget) $('dropHint').classList.add('hidden'); })); window.addEventListener('drop', (e) => { const f = e.dataTransfer?.files?.[0]; if (f) loadVideo(URL.createObjectURL(f), f.name, f); }); /* ===================================================================== Transport ===================================================================== */ const getFps = () => Number($('fpsInput').value) || S.video.fps || 30; function fmtTime(t) { const m = Math.floor(t / 60), s = t - m * 60; return `${m}:${s.toFixed(2).padStart(5, '0')}`; } let lastT = -1; function updateTransport() { const t = video.currentTime; if (t === lastT) return; lastT = t; if (!S.scanning) $('seek').value = String(video.duration ? t / video.duration : 0); $('timeLbl').textContent = `${fmtTime(t)} / ${fmtTime(video.duration || 0)} · f${Math.round(t * getFps())}`; $('btnPlay').textContent = video.paused ? '\u25b6' : '\u23f8'; } $('btnPlay').onclick = () => { if (video.paused) video.play(); else video.pause(); lastT = -1; }; $('btnPrev').onclick = () => { video.pause(); seekMain(video.currentTime - 1 / getFps()); }; $('btnNext').onclick = () => { video.pause(); seekMain(video.currentTime + 1 / getFps()); }; $('seek').addEventListener('input', () => { if (!video.duration) return; const tt = Number($('seek').value) * video.duration; if (RP.fl && (tt < RP.start || tt > RP.end)) stopReplay(); video.currentTime = tt; }); video.addEventListener('pause', () => (lastT = -1)); video.addEventListener('play', () => (lastT = -1)); window.addEventListener('keydown', (e) => { if (/INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return; if (e.key === ' ') { e.preventDefault(); $('btnPlay').click(); } if (e.key === 'Escape') stopReplay(); if (e.key === 'ArrowLeft') { e.preventDefault(); $('btnPrev').click(); } if (e.key === 'ArrowRight') { e.preventDefault(); $('btnNext').click(); } }); /* ===================================================================== Impact-flash scan ===================================================================== */ async function scanFlashes() { if (!S.video.loaded || S.scanning) return; if (typeof FlashDetector === 'undefined') { UI.flash = { err: 'err.noDetector' }; renderFlashInfo(); return; } S.scanning = true; S.cancelScan = false; $('btnFlash').disabled = true; $('btnFlashCancel').disabled = false; $('btnFlashCsv').disabled = true; $('btnFlash').classList.add('scanning'); const progWrap = $('flashProgWrap'), progBar = $('flashProgBar'); progWrap.classList.remove('hidden'); progBar.style.width = '0%'; video.pause(); const v2 = document.createElement('video'); v2.crossOrigin = 'anonymous'; v2.muted = true; v2.preload = 'auto'; v2.playsInline = true; v2.src = S.video.src; try { await new Promise((res, rej) => { v2.onloadeddata = res; v2.onerror = () => rej(i18nError('err.decode')); }); const fps = getFps(); const det = new FlashDetector({ sensitivity: Number($('selSens').value) }); det.initGeometry(v2.videoWidth, v2.videoHeight); const aw = det.analysisWidth, ah = det.analysisHeight, k = v2.videoWidth / aw; const c = document.createElement('canvas'); c.width = aw; c.height = ah; const ctx = c.getContext('2d', { willReadFrequently: true }); const total = Math.max(1, S.video.frames && !$('fpsInput').value ? S.video.frames : Math.floor(v2.duration * fps)); const track = new Float32Array(total * 2).fill(NaN); const t0 = performance.now(); let i = 0; for (; i < total && !S.cancelScan; i++) { await seekVideo(v2, (i + 0.5) / fps); ctx.drawImage(v2, 0, 0, aw, ah); const img = ctx.getImageData(0, 0, aw, ah); det.processFrame(img, i, i / fps); const cen = litCentroid(imageDataToGray(img), aw, ah); if (cen) { track[i * 2] = cen.x * k; track[i * 2 + 1] = cen.y * k; } if (i % 8 === 0) { progBar.style.width = ((100 * i) / total).toFixed(1) + '%'; const el = (performance.now() - t0) / 1000, eta = (el / (i + 1)) * (total - i - 1); UI.flash = { progress: { i: i + 1, n: total, fps: ((i + 1) / el).toFixed(1), eta: eta.toFixed(0) } }; renderFlashInfo(); await nextPaint(); } } const results = det.finalize(1 / fps); // Re-reference the track to the alignment frame so drift compensation stays consistent. if (S.ref) { const ri = Math.round(S.ref.t * fps - 0.5); if (ri >= 0 && ri < i && !Number.isNaN(track[ri * 2])) S.ref = { ...S.ref, x: track[ri * 2], y: track[ri * 2 + 1] }; } S.track = track; S.flashes = results; remapFlashes(); UI.flash = { done: { cancelled: S.cancelScan, n: i, s: ((performance.now() - t0) / 1000).toFixed(0), count: results.length } }; renderFlashInfo(); $('flashMarksRow').classList.toggle('hidden', !results.length); toast(results.length ? t('toast.found', { count: results.length }) : t('toast.none'), results.length ? 'flash' : 'info'); } catch (e) { console.error(e); UI.flash = { err: e.key || null, raw: e.message }; renderFlashInfo(); } finally { v2.removeAttribute('src'); v2.load(); S.scanning = false; progWrap.classList.add('hidden'); $('btnFlash').classList.remove('scanning'); $('btnFlash').disabled = false; $('btnFlashCancel').disabled = true; $('btnFlashCsv').disabled = !S.flashes.length; } } function renderFlashInfo() { const f = UI.flash, el = $('flashInfo'); if (!f) { el.innerHTML = ''; return; } if (f.progress) { el.textContent = t('flash.progress', f.progress); return; } if (f.err !== undefined && !f.done) { el.innerHTML = `<span class="warn">\u26a0 ${esc(f.err ? t(f.err) : f.raw)}</span>`; return; } const d = f.done; el.innerHTML = esc(t(d.cancelled ? 'flash.cancelled' : 'flash.done', d)) + ' ' + (d.count ? `<b class="flash-count">${esc(t('flash.found', d))}</b>` : esc(t('flash.none'))) + `<br><span class="small">${esc(t('flash.track'))}</span>`; } function remapFlashes() { for (const fl of S.flashes) { fl.lat = fl.lon = null; fl.nearF = null; fl.nearName = ''; fl.nearKm = null; if (!S.aligned) continue; let dx = 0, dy = 0; const i = fl.peakFrame; if (S.track && S.ref && i * 2 + 1 < S.track.length && !Number.isNaN(S.track[i * 2])) { dx = S.track[i * 2] - S.ref.x; dy = S.track[i * 2 + 1] - S.ref.y; } const d0 = effDisc(), d = { cx: d0.cx - S.drift.x + dx, cy: d0.cy - S.drift.y + dy, r: d0.r }; const ll = videoPxToLatLon(fl.x, fl.y, curM(), d); if (ll) { fl.lat = ll.lat; fl.lon = ll.lon; const n = nearest(ll.lat, ll.lon, 1)[0]; fl.nearF = n.f; fl.nearName = n.f.name; fl.nearKm = Math.round(kmOf(n.d)); fl.lit = isLit(latLonToBody(ll.lat, ll.lon)); } } renderFlashList(); } function renderFlashList() { const list = $('flashList'); list.innerHTML = ''; const maxD = Math.max(1, ...S.flashes.map((f) => f.peakDelta)); for (const fl of S.flashes) { const card = document.createElement('button'); card.className = 'flashcard' + (S.flashSel === fl ? ' on' : ''); const where = fl.lat == null ? esc(t('flash.offdisc')) : `${esc(fmtLat(fl.lat))}, ${esc(fmtLon(fl.lon))}`; const near = fl.nearF ? esc(t('flash.near', { name: fName(fl.nearF), km: fl.nearKm })) : ''; const side = fl.lat == null ? '' : `<span class="chip ${fl.lit ? 'lit' : 'night'}">${esc(t(fl.lit ? 'flash.litside' : 'flash.nightside'))}</span>`; card.innerHTML = `<span class="fc-badge">\u26a1${fl.index}</span>` + `<span class="fc-body"><span class="fc-top"><b>${fmtTime(fl.peakTime)}</b><span class="muted">f${fl.peakFrame} \u00b7 ${esc(t('flash.frames', { n: fl.frames }))}</span>${side}</span>` + `<span class="coords">${where}</span><span class="muted fc-near">${near}</span>` + `<span class="fc-bar"><i style="width:${((100 * fl.peakDelta) / maxD).toFixed(0)}%"></i><em>\u0394 ${fl.peakDelta}</em></span></span>`; card.onclick = () => selectFlash(fl); list.appendChild(card); } renderSeekMarks(); } async function selectFlash(fl) { S.flashSel = fl; renderFlashList(); if (fl.lat != null) showPick({ lat: fl.lat, lon: fl.lon }, { k: 'pick.flash', p: { i: fl.index, d: fl.peakDelta, n: fl.frames } }); await startReplay(fl); } /* ===================================================================== Flash replay: loop a short window around the flash, with slow motion and a magnified inset, because the flash lasts only a frame or two. ===================================================================== */ const REPLAY_WINDOW = 2; // seconds looped around the flash peak const RP = { fl: null, start: 0, end: 0, rate: 0.25, zoom: 4, seeking: null, frozen: false }; const rpCanvas = $('rpInset'), rpCtx = rpCanvas.getContext('2d'); async function startReplay(fl) { const dur = video.duration || 0; let start = fl.peakTime - REPLAY_WINDOW / 2, end = fl.peakTime + REPLAY_WINDOW / 2; if (start < 0) { end = Math.min(dur, end - start); start = 0; } if (end > dur) { start = Math.max(0, start - (end - dur)); end = dur; } Object.assign(RP, { fl, start, end, frozen: false }); $('replay').classList.remove('hidden'); renderReplayText(); renderReplayButtons(); video.playbackRate = RP.rate; await seekMain(start); video.play().catch(() => {}); } function stopReplay() { if (!RP.fl) return; RP.fl = null; video.playbackRate = 1; video.pause(); $('replay').classList.add('hidden'); } /** Called on every presented video frame: wrap back to the start of the window. */ function replayLoopCheck(mediaTime, force = false) { if (!RP.fl || RP.seeking || RP.frozen || (video.paused && !force)) return; const fd = 1 / getFps(); if (mediaTime >= RP.end - fd / 2 || mediaTime < RP.start - fd || video.ended) { RP.seeking = seekMain(RP.start).then(() => { RP.seeking = null; if (RP.fl && !RP.frozen) video.play().catch(() => {}); }); } } // A window that reaches the end of the clip ends the video (which pauses it), so force the wrap. video.addEventListener('ended', () => replayLoopCheck(video.duration, true)); /** Draw the magnified crop around the flash, compensating Moon drift since the peak frame. */ function drawReplayInset() { const fl = RP.fl; if (!fl || !video.videoWidth) return; const fps = getFps(); let cx = fl.x, cy = fl.y; if (S.track) { const now = Math.round(video.currentTime * fps - 0.5), pk = fl.peakFrame; const ok = (i) => i >= 0 && i * 2 + 1 < S.track.length && !Number.isNaN(S.track[i * 2]); if (ok(now) && ok(pk)) { cx += S.track[now * 2] - S.track[pk * 2]; cy += S.track[now * 2 + 1] - S.track[pk * 2 + 1]; } } const W = rpCanvas.width, crop = W / RP.zoom; rpCtx.imageSmoothingEnabled = RP.zoom < 4; // keep pixels crisp at high zoom rpCtx.fillStyle = '#000'; rpCtx.fillRect(0, 0, W, W); rpCtx.filter = $('chkRpBoost').checked ? 'brightness(1.8) contrast(1.25)' : 'none'; rpCtx.drawImage(video, cx - crop / 2, cy - crop / 2, crop, crop, 0, 0, W, W); rpCtx.filter = 'none'; const frame = Math.round(video.currentTime * fps - 0.5); const onFlash = frame >= fl.startFrame && frame <= fl.endFrame; // Reticle: open corners normally, solid pulsing ring while the flash is on screen. const r = Math.max(10, (Math.max(fl.bboxW, fl.bboxH) * RP.zoom) / 2 + 10), c = W / 2; rpCtx.lineWidth = 2; if (onFlash) { const pulse = 0.5 + 0.5 * Math.sin(performance.now() / 60); rpCtx.strokeStyle = `rgba(255, 90, 78, ${0.6 + 0.4 * pulse})`; rpCtx.lineWidth = 3; rpCtx.beginPath(); rpCtx.arc(c, c, r + 4 * pulse, 0, Math.PI * 2); rpCtx.stroke(); } else { rpCtx.strokeStyle = 'rgba(255, 211, 107, .85)'; const k = r * 0.45; for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { rpCtx.beginPath(); rpCtx.moveTo(c + sx * r, c + sy * (r - k)); rpCtx.lineTo(c + sx * r, c + sy * r); rpCtx.lineTo(c + sx * (r - k), c + sy * r); rpCtx.stroke(); } } $('replay').classList.toggle('on-flash', onFlash); $('rpBadge').classList.toggle('hidden', !onFlash); // Progress through the loop window, with the flash position marked. const span = Math.max(1e-6, RP.end - RP.start); $('rpProgBar').style.width = (100 * Math.min(1, Math.max(0, (video.currentTime - RP.start) / span))).toFixed(1) + '%'; $('rpProgMark').style.left = ((100 * (fl.peakTime - RP.start)) / span).toFixed(1) + '%'; $('rpFrame').textContent = t('rp.frame', { f: frame, peak: fl.peakFrame }); } function renderReplayText() { const fl = RP.fl; if (!fl) return; $('rpTitle').textContent = t('rp.title', { i: fl.index }); $('rpSub').textContent = t('rp.sub', { t0: fmtTime(RP.start), t1: fmtTime(RP.end), where: fl.lat == null ? t('flash.offdisc') : `${fmtLat(fl.lat)}, ${fmtLon(fl.lon)}`, }); } function renderReplayButtons() { for (const b of $('rpSpeed').children) b.classList.toggle('on', Number(b.dataset.rate) === RP.rate); for (const b of $('rpZoom').children) b.classList.toggle('on', Number(b.dataset.zoom) === RP.zoom); } $('rpSpeed').addEventListener('click', (e) => { const b = e.target.closest('button[data-rate]'); if (!b) return; RP.rate = Number(b.dataset.rate); video.playbackRate = RP.rate; renderReplayButtons(); }); $('rpZoom').addEventListener('click', (e) => { const b = e.target.closest('button[data-zoom]'); if (!b) return; RP.zoom = Number(b.dataset.zoom); renderReplayButtons(); }); $('rpPause').onclick = () => { if (video.paused) { RP.frozen = false; video.play(); } else { RP.frozen = true; video.pause(); } }; $('rpPeak').onclick = async () => { RP.frozen = true; // stop the loop from restarting playback video.pause(); if (RP.seeking) await RP.seeking; // let an in-flight wrap-around finish first await seekMain(RP.fl.peakTime + 0.5 / getFps()); }; $('rpClose').onclick = stopReplay; // Drag the replay panel by its header so it can be moved off the area you are watching. (() => { const panel = $('replay'), head = panel.querySelector('.rp-head'); let d = null; head.addEventListener('pointerdown', (e) => { if (e.target.closest('button')) return; d = { x: e.clientX - panel.offsetLeft, y: e.clientY - panel.offsetTop }; head.setPointerCapture(e.pointerId); }); head.addEventListener('pointermove', (e) => { if (!d) return; const W = wrap.clientWidth - panel.offsetWidth, H = wrap.clientHeight - panel.offsetHeight; panel.style.left = Math.max(0, Math.min(W, e.clientX - d.x)) + 'px'; panel.style.top = Math.max(0, Math.min(H, e.clientY - d.y)) + 'px'; }); head.addEventListener('pointerup', () => (d = null)); })(); function renderSeekMarks() { const box = $('seekMarks'); box.innerHTML = ''; if (!video.duration) return; for (const fl of S.flashes) { const m = document.createElement('button'); m.className = 'seekmark' + (S.flashSel === fl ? ' on' : ''); m.style.left = ((100 * fl.peakTime) / video.duration).toFixed(2) + '%'; m.title = t('flash.label', { i: fl.index }) + ' \u00b7 ' + fmtTime(fl.peakTime); m.onclick = () => selectFlash(fl); box.appendChild(m); } } function exportCsv() { const cols = ['index', 'peakTime', 'peakFrame', 'startFrame', 'endFrame', 'durationSec', 'x', 'y', 'lat', 'lon', 'peakDelta', 'peakBrightness', 'areaSrcPx', 'fill', 'aspect', 'nearName', 'nearKm', 'lit']; const rows = [cols.join(',')].concat(S.flashes.map((f) => cols.map((c) => { const v = f[c]; if (v == null || v === '') return ''; if (typeof v === 'boolean') return v ? 1 : 0; return typeof v === 'number' ? (Number.isInteger(v) ? v : v.toFixed(4)) : `"${String(v).replace(/"/g, '""')}"`; }).join(','))); const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([rows.join('\n')], { type: 'text/csv' })); a.download = (S.video.name || 'video').replace(/\.[^.]+$/, '') + '-flashes.csv'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); } /* ===================================================================== UI wiring ===================================================================== */ function bindSlider(id, outId, get, set, fmt = (v) => v.toFixed(2)) { const s = $(id), o = $(outId); s.addEventListener('input', () => { set(Number(s.value)); o.textContent = fmt(Number(s.value)); afterManualAdjust(); }); return () => { s.value = get(); o.textContent = fmt(Number(get())); }; } function afterManualAdjust() { if (S.focus) focusFeature(S.focus, { quiet: true }); if (S.flashes.length) remapFlashes(); if (S.pick) renderPick(); if (UI.align && !UI.align.err) renderAlign(); updateStats(); } const syncers = [ bindSlider('sTheta', 'oTheta', () => S.fit.theta, (v) => (S.fit.theta = v), (v) => v.toFixed(1) + '°'), bindSlider('sB0', 'oB0', () => S.fit.b0, (v) => (S.fit.b0 = v), (v) => v.toFixed(1) + '°'), bindSlider('sL0', 'oL0', () => S.fit.l0, (v) => (S.fit.l0 = v), (v) => v.toFixed(1) + '°'), bindSlider('sRad', 'oRad', () => S.adj.rad, (v) => (S.adj.rad = v), (v) => v.toFixed(3)), bindSlider('sDx', 'oDx', () => S.adj.dx, (v) => (S.adj.dx = v), (v) => v.toFixed(1)), bindSlider('sDy', 'oDy', () => S.adj.dy, (v) => (S.adj.dy = v), (v) => v.toFixed(1)), ]; function syncSliders() { syncers.forEach((f) => f()); $('chkMirrorNow').checked = S.fit.mirror; } $('chkMirrorNow').addEventListener('change', (e) => { S.fit.mirror = e.target.checked; afterManualAdjust(); }); bindSlider('sGrid', 'oGrid', () => S.grid, (v) => (S.grid = v))(); bindSlider('sColor', 'oColor', () => S.color, (v) => (S.color = v))(); bindSlider('sSat', 'oSat', () => S.sat, (v) => (S.sat = v), (v) => v.toFixed(1))(); $('selGridStep').addEventListener('change', (e) => (S.gridStep = Number(e.target.value))); $('chkGridLabels').addEventListener('change', (e) => (S.gridLabels = e.target.checked)); $('selColorMode').addEventListener('change', (e) => (S.colorMode = Number(e.target.value))); $('btnSample').onclick = () => loadVideo(SAMPLE_VIDEO, SAMPLE_VIDEO); $('btnSampleLong').onclick = () => loadVideo(SAMPLE_LONG, SAMPLE_LONG); $('fileInput').addEventListener('change', (e) => { const f = e.target.files?.[0]; if (f) loadVideo(URL.createObjectURL(f), f.name, f); e.target.value = ''; }); $('btnEphem').onclick = () => { computeEphem(); if (S.video.loaded) runAlign(); }; $('btnAlign').onclick = () => runAlign(); $('btnFlash').onclick = () => scanFlashes(); $('btnFlashCancel').onclick = () => (S.cancelScan = true); $('btnFlashCsv').onclick = exportCsv; $('btnResetView').onclick = () => fitOverlayToDisc(); $('btnFullFrame').onclick = () => { S.fullFrame = true; }; $('viewSeg').addEventListener('click', (e) => { const b = e.target.closest('button[data-view]'); if (!b) return; const k = b.dataset.view; if (k === 'all') VIEW_ORDER.forEach((v) => (S.views[v] = true)); else if (e.ctrlKey || e.shiftKey || e.metaKey) { S.views[k] = !S.views[k]; if (!VIEW_ORDER.some((v) => S.views[v])) S.views[k] = true; } else VIEW_ORDER.forEach((v) => (S.views[v] = v === k)); syncViewButtons(); }); function syncViewButtons() { const all = VIEW_ORDER.every((v) => S.views[v]); for (const b of $('viewSeg').children) { const k = b.dataset.view; b.classList.toggle('on', k === 'all' ? all : !all && S.views[k]); } } syncViewButtons(); bindSlider('sGeo', 'oGeo', () => S.geoAmt, (v) => (S.geoAmt = v))(); // Feature search & categories. function buildFeatureUi() { $('featList').innerHTML = LOCATIONS.map((f) => `<option value="${esc(fName(f))}">${fName(f) !== f.name ? esc(f.name) : ''}</option>`).join(''); $('catBoxes').innerHTML = Object.keys(CAT_COLORS).map((c) => `<label class="catchip" style="--c:${CAT_COLORS[c]}"><input type="checkbox" data-cat="${esc(c)}" ${S.cats[c] ? 'checked' : ''}/>` + `<span class="dot"></span>${esc(catName(c))}</label>`).join(''); $('quickPicks').innerHTML = QUICK_PICKS.map((n) => LOCATIONS.find((f) => f.name === n)).filter(Boolean) .map((f) => `<button class="qp" data-f="${esc(f.name)}" style="--c:${CAT_COLORS[f.cat]}">${esc(fName(f))}</button>`).join(''); } $('quickPicks').addEventListener('click', (e) => { const b = e.target.closest('button[data-f]'); if (!b) return; const f = LOCATIONS.find((x) => x.name === b.dataset.f); $('featSearch').value = fName(f); focusFeature(f); }); const doFind = () => { const f = findFeature($('featSearch').value); if (f) { $('featSearch').value = fName(f); focusFeature(f); } else { $('featInfo').innerHTML = esc(t('feat.none')); $('featInfo').classList.remove('hidden'); S.focus = null; } }; $('btnFind').onclick = doFind; $('featSearch').addEventListener('keydown', (e) => { if (e.key === 'Enter') doFind(); }); $('featSearch').addEventListener('change', doFind); $('catBoxes').addEventListener('change', (e) => { const c = e.target.dataset.cat; if (c) S.cats[c] = e.target.checked; }); $('utcOffset').value = String(-new Date().getTimezoneOffset() / 60); $('chkFlashMarks').addEventListener('change', (e) => { S.showFlashMarks = e.target.checked; }); /* ---- language switching ---- */ function applyStaticText() { document.documentElement.lang = LANG === 'en' ? 'en' : LANG === 'zh-CN' ? 'zh-Hans' : 'zh-Hant'; document.title = t('app.title'); document.querySelectorAll('[data-i18n]').forEach((el) => { el.textContent = t(el.dataset.i18n); }); document.querySelectorAll('[data-i18n-title]').forEach((el) => { el.title = t(el.dataset.i18nTitle); }); document.querySelectorAll('[data-i18n-ph]').forEach((el) => { el.placeholder = t(el.dataset.i18nPh); }); for (const b of $('langBar').children) b.classList.toggle('on', b.dataset.lang === LANG); } function setLang(l) { if (!LANGS.includes(l)) return; LANG = l; localStorage.setItem('moonMapper.lang', l); applyStaticText(); buildFeatureUi(); renderVideoName(); renderEphem(); renderAlign(); renderTex(); renderFlashInfo(); renderFlashList(); renderPick(); updateStats(); renderReplayText(); if (S.focus) focusFeature(S.focus, { quiet: true }); const b = $('busy'); if (b) b.querySelector('span').textContent = t(b.dataset.key); } $('langBar').addEventListener('click', (e) => { const b = e.target.closest('button[data-lang]'); if (b) setLang(b.dataset.lang); }); /* ===================================================================== Visual extras: stats tiles, Moon thumbnail, compass, toasts ===================================================================== */ function phaseKey() { if (S.phaseAngle == null) return null; const k = (1 + Math.cos((S.phaseAngle * Math.PI) / 180)) / 2; // illuminated fraction const sub = bodyToLatLon(sunBody()); // sub-solar point const waxing = sub.lon > 0; // sun on the eastern (Crisium) side let idx; if (k < 0.03) idx = 0; else if (k > 0.97) idx = 4; else if (Math.abs(k - 0.5) < 0.06) idx = waxing ? 2 : 6; else idx = k < 0.5 ? (waxing ? 1 : 7) : (waxing ? 3 : 5); return { idx, pct: Math.round(k * 100) }; } function updateStats() { const ok = S.aligned; const ph = ok ? phaseKey() : null; $('stPhase').innerHTML = ph ? `${esc(t('phase.' + ph.idx))}<small>${esc(t('phase.lit', { pct: ph.pct }))}</small>` : '\u2013'; $('stRot').textContent = ok ? fmtTheta(S.fit.theta, true) : '\u2013'; $('stLib').textContent = ok ? `${S.fit.b0.toFixed(1)}\u00b0, ${S.fit.l0.toFixed(1)}\u00b0` : '\u2013'; $('stScore').textContent = ok ? S.fit.s.toFixed(2) : '\u2013'; const m = $('stMeter'); m.style.setProperty('--v', ok ? Math.max(0, Math.min(1, S.fit.s)).toFixed(3) : 0); m.className = 'meter ' + (!ok ? '' : S.fit.s > 0.35 ? 'good' : S.fit.s > 0.2 ? 'fair' : 'weak'); $('hero').classList.toggle('ready', ok); } const thumb = $('moonThumb'), thumbCtx = thumb.getContext('2d'); function drawThumb() { thumbCtx.clearRect(0, 0, thumb.width, thumb.height); const d = effDisc(); if (!d || !S.video.loaded || !video.videoWidth) return; const s = d.r * 1.08, W = thumb.width; thumbCtx.save(); thumbCtx.beginPath(); thumbCtx.arc(W / 2, W / 2, W / 2 - 2, 0, Math.PI * 2); thumbCtx.clip(); thumbCtx.fillStyle = '#000'; thumbCtx.fillRect(0, 0, W, W); thumbCtx.drawImage(video, d.cx - s, d.cy - s, 2 * s, 2 * s, 0, 0, W, W); thumbCtx.restore(); } let thumbT = 0; video.addEventListener('seeked', () => drawThumb()); function compassUpdate() { const c = $('compass'), R = rects(); if (!S.aligned || !R.overlay) { c.classList.add('hidden'); return; } c.classList.remove('hidden'); const r = R.overlay; c.style.left = (r.x + r.w - 120) + 'px'; c.style.top = (r.h - 128) + 'px'; const M = curM(); const ang = (v) => (Math.atan2(v[0], v[1]) * 180) / Math.PI; // clockwise from screen-up const place = (g, txt, a, r) => { $(g).setAttribute('transform', `rotate(${a.toFixed(1)})`); // Keep the letter upright: position it outside the rotated arrow group. const rad = (a * Math.PI) / 180; $(txt).setAttribute('x', (Math.sin(rad) * r).toFixed(1)); $(txt).setAttribute('y', (-Math.cos(rad) * r + 4).toFixed(1)); }; place('cmpN', 'cmpNt', ang(apply(M, [0, 1, 0])), 56); place('cmpE', 'cmpEt', ang(apply(M, latLonToBody(0, 90))), 46); const NE = { en: ['N', 'E'], 'zh-CN': ['\u5317', '\u4e1c'], 'zh-TW': ['\u5317', '\u6771'] }[LANG]; $('cmpNt').textContent = NE[0]; $('cmpEt').textContent = NE[1]; } function toast(msg, kind = 'info') { const el = document.createElement('div'); el.className = 'toast ' + kind; el.textContent = msg; $('toasts').appendChild(el); setTimeout(() => el.classList.add('out'), 3600); setTimeout(() => el.remove(), 4200); } function visualTick(now) { compassUpdate(); if (RP.fl) drawReplayInset(); if (!video.paused && now - thumbT > 250) { thumbT = now; drawThumb(); } // Screen flash when playback passes a detected impact (only while markers are shown). const live = S.showFlashMarks && S.flashes.some((f) => f.lat != null && Math.abs(video.currentTime - f.peakTime) < 0.12); wrap.classList.toggle('impact', live && !video.paused); requestAnimationFrame(visualTick); } video.addEventListener('loadedmetadata', () => renderSeekMarks()); window.moonMapper = { S, video, runAlign, setLang }; // handy for console debugging applyStaticText(); buildFeatureUi(); renderVideoName(); updateStats(); resize(); frame(); requestAnimationFrame(visualTick); loadVideo(SAMPLE_VIDEO, SAMPLE_VIDEO);
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { LOCATIONS } from './locations.js';
import {
bodyToView, transpose, apply, latLonToBody, bodyToLatLon, angDist,
imageDataToGray, detectDisc, matchOrientation, prepareTexture, litCentroid,
sunViewVector, phaseFromLitFraction,
} from './moonfit.js';
import { readMp4VideoInfo } from './mp4info.js';
import { STRINGS, FEATURE_I18N, QUICK_PICKS } from './i18n.js';
const SAMPLE_VIDEO = 'short_flash.mp4';
const SAMPLE_LONG = '2026-10-20-234910-Lunar.mp4';
const MOON_RADIUS_KM = 1737.4;
const $ = (id) => document.getElementById(id);
/* =====================================================================
Internationalisation (English / Simplified / Traditional Chinese)
===================================================================== */
const LANGS = ['en', 'zh-CN', 'zh-TW'];
function detectLang() {
const saved = localStorage.getItem('moonMapper.lang');
if (LANGS.includes(saved)) return saved;
const n = (navigator.language || 'en').toLowerCase();
if (n.startsWith('zh')) return /tw|hk|mo|hant/.test(n) ? 'zh-TW' : 'zh-CN';
return 'en';
}
let LANG = detectLang();
/** Translate a key, filling {placeholders}. Falls back to English, then to the key. */
function t(key, p = {}) {
const s = STRINGS[LANG]?.[key] ?? STRINGS.en[key] ?? key;
return s.replace(/\{(\w+)\}/g, (m, k) => (p[k] ?? m));
}
const fName = (f) => FEATURE_I18N[LANG]?.[f.name]?.n ?? f.name;
const fDesc = (f) => FEATURE_I18N[LANG]?.[f.name]?.d ?? f.desc;
const catName = (c) => t('cat.' + c);
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
/** Error whose message is re-translated when the language changes. */
const i18nError = (key, p) => Object.assign(new Error(t(key, p)), { key, p });
const CAT_COLORS = {
'Landing & Rover Sites': '#ffcf4d',
'Maria, Oceans & Bays': '#59c3ff',
'Craters': '#c9a6ff',
'Poles & Basins': '#7dffb0',
};
const CAT_DEFAULT_ON = { 'Landing & Rover Sites': true, 'Maria, Oceans & Bays': true, 'Craters': false, 'Poles & Basins': false };
/* =====================================================================
State
===================================================================== */
const S = {
video: { W: 1080, H: 1920, fps: 30, name: '', src: '', loaded: false },
disc: null, // {cx, cy, r, litCx, litCy} in source px (alignment frame)
fit: { theta: 0, b0: 0, l0: 0, mirror: false, s: 0 },
adj: { rad: 1, dx: 0, dy: 0 },
drift: { x: 0, y: 0 },
ref: null, // lit centroid at the alignment frame (source px)
track: null, // per-frame lit centroids from a flash scan (Float32Array, x,y pairs)
sunView: [0, 0, 1],
prior: { b0: 0, l0: 0, phase: null, date: null },
aligned: false,
views: { overlay: true, lroc: true, geo: true },
geoAmt: 0,
// Shared view: Z scales the Moon's on-screen radius identically in every pane;
// pan is the point at the pane centre, in Moon-disc radii (x right, y up, as seen in the video).
Z: 1, pan: { x: 0, y: 0 }, fullFrame: false,
grid: 0.5, gridStep: 10, gridLabels: true,
color: 0, colorMode: 1, sat: 4,
cats: { ...CAT_DEFAULT_ON },
focus: null, pick: null,
flashes: [], flashSel: null, showFlashMarks: true,
pickExtra: null,
scanning: false, cancelScan: false,
};
// Last-rendered status messages, kept as data so they can be re-rendered in another language.
const UI = { video: null, ephem: null, align: null, flash: null, tex: null };
/* =====================================================================
Renderer & scenes
===================================================================== */
const canvas = $('gl');
const wrap = $('canvasWrap');
const video = $('video');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.LinearSRGBColorSpace; // all textures are passed through raw
renderer.setClearColor(0x000000, 1);
const videoTex = new THREE.VideoTexture(video);
videoTex.colorSpace = THREE.NoColorSpace;
videoTex.minFilter = THREE.LinearFilter;
videoTex.magFilter = THREE.LinearFilter;
const texLoader = new THREE.TextureLoader();
function setupMap(t) {
t.colorSpace = THREE.NoColorSpace;
t.wrapS = THREE.RepeatWrapping;
t.generateMipmaps = true; // the shader supplies seam-free gradients (textureGrad)
t.minFilter = THREE.LinearMipmapLinearFilter;