import { I18N, LANGS } from './i18n.js';
import { MOON_I18N } from './i18n_moons.js';
import { CRAFT_I18N, CRAFT_ORDER, CRAFT_THEMES, CRAFT_INST, CRAFT_BACKDROP } from './i18n_craft.js';
import { createCraftViewer } from './craft.js';
import { createScene, PLANET_CFG, FEATURED_MOONS, moonData } from './scene.js';
import { moonFxKeys } from './moonfx.js';
// merge moon text into the main dictionary
const deepMerge = (a, b) => { for (const k in b) { if (b[k] && typeof b[k] === 'object' && !Array.isArray(b[k]) && a[k] && typeof a[k] === 'object') deepMerge(a[k], b[k]); else a[k] = b[k]; } return a; };
for (const extra of [MOON_I18N, CRAFT_I18N]) for (const l of Object.keys(extra)) deepMerge(I18N[l], extra[l]);
import { initAuroraGallery } from './aurora2d.js';
/* ------------------------------------------------------------ language */
const params = new URLSearchParams(location.search);
function detectLang() {
if (LANGS.includes(params.get('lang'))) return params.get('lang');
const saved = localStorage.getItem('mop-lang');
if (LANGS.includes(saved)) return saved;
const nav = (navigator.language || 'en').toLowerCase();
if (nav.startsWith('zh')) return /tw|hk|mo|hant/.test(nav) ? 'zh-Hant' : 'zh-Hans';
return 'en';
}
let lang = detectLang();
function t(key) {
const get = (obj) => key.split('.').reduce((o, k) => (o == null ? undefined : o[k]), obj);
const v = get(I18N[lang]);
return v === undefined ? (get(I18N.en) ?? key) : v;
}
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
/* -------------------------------------------------------------- 3D scene */
const PLANETS = ['earth', 'jupiter', 'saturn', 'uranus', 'neptune'];
let scene = null;
let selection = null; // key of the moon shown in the info panel, or null for the planet
try {
scene = createScene($('#stage'), {
t,
onPlanetChange: name => { selection = null; updateInfo(name); syncTabs(name); },
onSelect: pick => { if (pick.type === 'moon') showMoon(pick.key); else { selection = null; updateInfo(); } }
});
scene.setPlanet(PLANETS.includes(params.get('planet')) ? params.get('planet') : 'jupiter', { instant: true });
} catch (err) {
console.error(err);
$('#stage').innerHTML = '
WebGL is not available in this browser, so the 3D explorer cannot run. The rest of the page still works.
';
}
function syncTabs(name) { $$('#planetTabs button').forEach(b => b.classList.toggle('active', b.dataset.planet === name)); }
function updateInfo(name = scene?.planet || 'jupiter') {
const p = `planets.${name}.`;
$('#infoName').textContent = t(p + 'name');
$('#infoTag').textContent = t(p + 'tag');
$('#infoDesc').textContent = t(p + 'desc');
$('#infoFacts').innerHTML = ['field', 'tilt', 'mp', 'source', 'rot', 'aurora', 'visited']
.map(k => `${esc(t('info.' + k))}${esc(t(p + k))}`).join('');
const moons = PLANET_CFG[name].moons;
$('#infoMoons').innerHTML = moons.length ? `${esc(t('nav.moons'))}
${moons.map(m =>
``).join('')}
${esc(t('mn.clickHint'))}
` : '';
$$('#infoMoons [data-moon]').forEach(b => b.addEventListener('click', () => flyToMoon(b.dataset.moon, false)));
}
function moonName(key) { return I18N[lang].mo?.[key]?.full || t('moons.' + key); }
function moonFacts(key) {
const m = moonData(key), host = PLANET_CFG[m.host];
const retro = m.period < 0 ? (lang === 'en' ? ` (${t('mn.retro')})` : `(${t('mn.retro')})`) : '';
const days = Math.abs(m.period).toLocaleString('en', { maximumFractionDigits: 2 }) + ' ' + t('mn.days') + retro;
return [
['mn.host', t(`planets.${m.host}.name`)],
['mn.dia', m.dia.toLocaleString('en') + ' ' + t('mn.km')],
['mn.dist', fmtKm(Math.round(m.realDist * host.radiusKm / 100) * 100)],
['mn.period', days]
];
}
function showMoon(key) {
selection = key;
$('#infoTag').textContent = t(`mo.${key}.tag`);
$('#infoName').textContent = moonName(key);
$('#infoDesc').textContent = t(`mo.${key}.text`);
$('#infoFacts').innerHTML = moonFacts(key).map(([k, v]) => `${esc(t(k))}${esc(v)}`).join('');
const fxk = moonFxKeys(key);
$('#infoMoons').innerHTML = (fxk.length ? `${esc(t('mn.seeTitle'))}
${fxk.map(k => `${esc(t('fx.' + k))}`).join('')}
` : '') + ``;
$('#moonFly').addEventListener('click', () => scene?.focusMoon(key));
$('#moonBack').addEventListener('click', () => { selection = null; updateInfo(); scene?.view('overview'); });
document.body.classList.remove('touring');
}
function flyToMoon(key, scroll = true, instant = false) {
if (!scene) return;
const host = moonData(key).host;
endTour();
startExploring();
if (scroll) $('#explore').scrollIntoView({ behavior: 'smooth' });
if (scene.planet !== host) scene.setPlanet(host, { keepView: true });
scene.setLayer('moons', true); syncLayerBoxes();
scene.focusMoon(key, instant);
showMoon(key);
}
function syncLayerBoxes() {
if (!scene) return;
const L = scene.getLayers();
$$('[data-layer]').forEach(cb => { cb.checked = !!L[cb.dataset.layer]; });
}
$$('#planetTabs button').forEach(b => b.addEventListener('click', () => { endTour(); scene?.setPlanet(b.dataset.planet); }));
$$('[data-layer]').forEach(cb => cb.addEventListener('change', () => scene?.setLayer(cb.dataset.layer, cb.checked)));
$$('[data-view]').forEach(b => b.addEventListener('click', () => scene?.view(b.dataset.view)));
$('#speed').addEventListener('input', e => scene?.setSpeed(parseFloat(e.target.value)));
/* solar wind intensity: 1 = typical; values are relative dynamic pressure */
function windLevelKey(k) { return k < 0.7 ? 'ex.windCalm' : k < 1.5 ? 'ex.windNormal' : k < 2.6 ? 'ex.windStrong' : 'ex.windStorm'; }
function setWind(k, instant = false) {
const sl = $('#windSlider');
k = Math.min(parseFloat(sl.max), Math.max(parseFloat(sl.min), k));
sl.value = k;
scene?.setWind(k, instant);
// the stream must be visible for the slider to make sense
if (scene && !scene.getLayers().wind) { scene.setLayer('wind', true); syncLayerBoxes(); }
renderWind();
}
function renderWind() {
const k = parseFloat($('#windSlider').value);
const lvl = windLevelKey(k);
$('#windVal').textContent = `${t(lvl)} · ×${k.toFixed(1)}`;
$('#windVal').dataset.level = lvl.slice(7).toLowerCase();
$('#windCard').classList.toggle('storming', k >= 2.6);
}
/* hide / show all overlay menus so the 3D view is unobstructed (button or "H" key) */
function renderUiToggle() {
const min = document.body.classList.contains('ui-min');
$('#uiToggleTxt').textContent = t(min ? 'ex.showUi' : 'ex.hideUi');
$('#uiToggle').setAttribute('aria-pressed', String(min));
$('#uiToggle').title = t(min ? 'ex.showUi' : 'ex.hideUi') + ' (H)';
}
function toggleUi(force) {
document.body.classList.toggle('ui-min', force);
renderUiToggle();
}
$('#uiToggle').addEventListener('click', () => toggleUi());
document.addEventListener('keydown', e => {
if (e.key !== 'h' && e.key !== 'H') return;
if (e.ctrlKey || e.metaKey || e.altKey || /INPUT|TEXTAREA|SELECT/.test(document.activeElement?.tagName || '')) return;
const r = $('#explore').getBoundingClientRect();
if (r.bottom > 0 && r.top < innerHeight) toggleUi();
});
$('#windSlider').addEventListener('input', e => setWind(parseFloat(e.target.value)));
$('#windReset').addEventListener('click', () => setWind(1));
$('#cmeBtn').addEventListener('click', () => {
if (!scene) return;
if (!scene.getLayers().wind) { scene.setLayer('wind', true); syncLayerBoxes(); }
if (!scene.getLayers().mp) { scene.setLayer('mp', true); syncLayerBoxes(); }
scene.launchCME();
});
// Typical magnetopause stand-off distance in planetary radii; it scales as (pressure)^(-1/6).
const REAL_MP = { earth: 10, jupiter: 63, saturn: 22, uranus: 18, neptune: 26 };
let meterT = 0;
function updateMeters(now) {
requestAnimationFrame(updateMeters);
if (!scene || now - meterT < 150) return;
meterT = now;
const w = scene.windInfo();
const mp = (REAL_MP[scene.planet] || 10) * Math.pow(w.k, -1 / 6);
$('#mpVal').textContent = t('ex.mRadii').replace('{n}', mp >= 30 ? Math.round(mp) : mp.toFixed(1));
$('#mpBar').style.width = `${Math.min(100, 100 * Math.pow(w.k, -1 / 6) / 1.25)}%`;
$('#auVal').textContent = `×${w.boost.toFixed(1)}`;
$('#auBar').style.width = `${Math.min(100, 100 * w.boost / 2.6)}%`;
const card = $('#windCard');
card.classList.toggle('cme', w.cme && w.kick === 0);
card.classList.toggle('impact', w.kick > 0.05);
$('#cmeBtn').disabled = w.cme;
}
requestAnimationFrame(updateMeters);
function startExploring() { document.body.classList.add('exploring'); }
$('#startBtn').addEventListener('click', startExploring);
/* ----------------------------------------------------------------- tour */
const ALL_ON = { field: true, wind: true, mp: true, aurora: true, torus: true, moons: true, labels: true };
const TOUR = [
{ planet: 'jupiter', view: 'close', layers: { field: true, wind: false, mp: false, aurora: false, torus: false, moons: false, labels: true } },
{ planet: 'jupiter', view: 'overview', layers: { field: true, wind: true, mp: false, aurora: false, torus: false, moons: false, labels: true } },
{ planet: 'jupiter', view: 'overview', layers: { field: true, wind: true, mp: true, aurora: false, torus: false, moons: false, labels: true } },
{ planet: 'jupiter', view: 'mid', moon: 'io', layers: { field: true, wind: false, mp: false, aurora: true, torus: true, moons: true, labels: true } },
{ planet: 'jupiter', view: 'aurora', layers: { ...ALL_ON, wind: false, mp: false } },
{ planet: 'uranus', view: 'overview', layers: { ...ALL_ON } }
];
let tourIdx = -1;
function showStep(i) {
if (!scene) return;
tourIdx = Math.max(0, Math.min(TOUR.length - 1, i));
const s = TOUR[tourIdx];
startExploring();
document.body.classList.add('touring');
if (scene.planet !== s.planet) scene.setPlanet(s.planet, { keepView: true });
scene.setLayers(s.layers);
scene.view(s.view);
if (s.moon) scene.focusMoon(s.moon);
syncLayerBoxes();
$('#tour').hidden = false;
renderTourText();
}
function renderTourText() {
if (tourIdx < 0) return;
const step = t('how.steps')[tourIdx];
$('#tourStep').textContent = t('ex.stepFmt').replace('{i}', tourIdx + 1).replace('{n}', TOUR.length);
$('#tourTitle').textContent = step.title;
$('#tourText').textContent = step.text;
$('#tourPrev').disabled = tourIdx === 0;
$('#tourNext').disabled = tourIdx === TOUR.length - 1;
}
function endTour() {
if (tourIdx < 0) return;
tourIdx = -1;
$('#tour').hidden = true;
document.body.classList.remove('touring');
scene?.setLayers(ALL_ON);
syncLayerBoxes();
}
$('#tourBtn').addEventListener('click', () => showStep(0));
$('#tourPrev').addEventListener('click', () => showStep(tourIdx - 1));
$('#tourNext').addEventListener('click', () => showStep(tourIdx + 1));
$('#tourExit').addEventListener('click', endTour);
/* ------------------------------------------------------ dynamic sections */
const STEP_ICONS = ['🧲', '☀️', '🌊', '🌋', '🌌', '🌀'];
function renderSteps() {
$('#stepsGrid').innerHTML = t('how.steps').map((s, i) => `
${STEP_ICONS[i]}${i + 1}
${esc(s.title)}
${esc(s.text)}
`).join('');
$$('#stepsGrid [data-step]').forEach(b => b.addEventListener('click', () => {
$('#explore').scrollIntoView({ behavior: 'smooth' });
showStep(parseInt(b.dataset.step, 10));
}));
}
const SIZES = [
{ key: 'earth', km: 64000, color: '#4fa3ff' },
{ key: 'jupiter', km: 4500000, color: '#e0b27a' },
{ key: 'saturn', km: 1300000, color: '#e8d08f' },
{ key: 'uranus', km: 460000, color: '#8fe3ea' },
{ key: 'neptune', km: 600000, color: '#5d7fff' },
{ key: 'sun', km: 1392000, color: '#ffcc55' }
];
function fmtKm(km) {
if (lang === 'en') return km >= 1e6 ? `${(km / 1e6).toLocaleString('en', { maximumFractionDigits: 2 })} million km` : `${km.toLocaleString('en')} km`;
const wan = lang === 'zh-Hans' ? '万' : '萬';
return km >= 1e4 ? `${(km / 1e4).toLocaleString('en', { maximumFractionDigits: 1 })} ${wan}公里` : `${km.toLocaleString('en')} 公里`;
}
function renderBars() {
const max = Math.max(...SIZES.map(s => s.km));
$('#bars').innerHTML = SIZES.map(s => {
const name = s.key === 'sun' ? t('cmp.sun') : t(`planets.${s.key}.name`);
const w = Math.max(0.6, (s.km / max) * 100);
return `
${esc(name)}
${esc(fmtKm(s.km))}
`;
}).join('');
const io = new IntersectionObserver(es => es.forEach(e => e.isIntersecting && e.target.classList.add('grow')), { threshold: 0.3 });
io.observe($('#bars'));
}
function renderTable() {
const cols = ['field', 'tilt', 'mp', 'rot', 'source'];
$('#cmpTable').innerHTML = `| ${esc(t('cmp.planet'))} | ${cols.map(c => `${esc(t('info.' + c))} | `).join('')}
${PLANETS.map(p => `| ${esc(t(`planets.${p}.name`))} | ${cols.map(c => `${esc(t(`planets.${p}.${c}`))} | `).join('')}
`).join('')}`;
}
function renderMoons() {
$('#moonGrid').innerHTML = FEATURED_MOONS.map(k => `
${esc(t(`planets.${moonData(k).host}.name`))} · ${esc(t(`mo.${k}.tag`))}
${esc(moonName(k))}
${esc(t(`mo.${k}.text`))}
${moonFacts(k).slice(1).map(([a, v]) => `- ${esc(t(a))}
- ${esc(v)}
`).join('')}
`).join('');
$$('#moonGrid [data-fly]').forEach(b => b.addEventListener('click', () => flyToMoon(b.dataset.fly)));
}
/* ------------------------------------------------------------ spacecraft */
const craft = { key: 'juno', theme: 0, inst: null, viewer: null };
const pad2 = n => String(n).padStart(2, '0');
function craftMatches(key) { return !craft.theme || CRAFT_THEMES[key].includes(craft.theme); }
function renderThemes() {
const themes = t('themes');
$('#themeChips').innerHTML = `` +
themes.map((th, i) => ``).join('');
$('#themeDesc').textContent = craft.theme ? themes[craft.theme - 1].text : '';
$$('#themeChips [data-theme]').forEach(b => b.addEventListener('click', () => setTheme(+b.dataset.theme)));
}
function setTheme(n) {
craft.theme = n;
renderThemes();
if (!craftMatches(craft.key)) showCraft(CRAFT_ORDER.find(craftMatches));
else renderPicker();
}
function renderPicker() {
$('#craftPicker').innerHTML = CRAFT_ORDER.map(k => `
`).join('');
$$('#craftPicker [data-craft]').forEach(b => b.addEventListener('click', () => showCraft(b.dataset.craft)));
}
function renderCraftInfo() {
const k = craft.key, c = `crafts.${k}.`;
const insts = CRAFT_INST[k];
$('#craftInfo').innerHTML = `
${esc(t(c + 'agency'))}
${esc(t(c + 'name'))}
${esc(t(c + 'desc'))}
- ${esc(t('sc.years'))}
- ${esc(t(c + 'years'))}
- ${esc(t('sc.target'))}
- ${esc(t(c + 'target'))}
- ${esc(t('sc.status'))}
- ${esc(t(c + 'status'))}
${esc(t('sc.mopThemes'))}
${CRAFT_THEMES[k].map(n => ``).join('')}
${esc(t('sc.instruments'))}
${insts.map((id, i) => {
const on = craft.inst === id;
return `- ${on ? `
${esc(t(c + 'inst.' + id + '.text'))}
` : ''} `;
}).join('')}
${esc(t('sc.saw'))}
${t(c + 'saw').map(s => `- ${esc(s)}
`).join('')}
`;
$$('#craftInfo [data-inst]').forEach(b => b.addEventListener('click', () => pickInst(b.dataset.inst === craft.inst ? null : b.dataset.inst)));
$$('#craftInfo [data-theme]').forEach(b => b.addEventListener('click', () => setTheme(+b.dataset.theme)));
}
function pickInst(id) {
craft.inst = id;
craft.viewer?.select(id);
renderCraftInfo();
}
function showCraft(key) {
craft.key = key; craft.inst = null;
renderPicker(); renderCraftInfo();
craft.viewer?.show(key, CRAFT_INST[key]);
}
try {
craft.viewer = createCraftViewer($('#craftStage'), { onPick: id => pickInst(id), backdrop: k => CRAFT_BACKDROP[k] });
craft.viewer.show(craft.key, CRAFT_INST[craft.key]);
} catch (err) { console.error(err); }
function renderWhy() {
$('#whyGrid').innerHTML = t('why.cards').map(c => `
${c.icon}
${esc(c.title)}
${esc(c.text)}
`).join('');
}
function renderTimeline() {
$('#timeline').innerHTML = t('ms.items').map(m => `
${esc(m.year)}${esc(m.name)}
${esc(m.text)}
`).join('');
}
/* ----------------------------------------------------------------- quiz */
let answers = {};
function renderQuiz() {
const items = t('qz.items');
$('#quizBox').innerHTML = items.map((q, qi) => {
const done = answers[qi] !== undefined;
return `
${qi + 1}. ${esc(q.q)}
${q.options.map((o, oi) => {
let cls = '';
if (done) { if (oi === q.answer) cls = 'right'; else if (oi === answers[qi]) cls = 'wrong'; }
return ``;
}).join('')}
${done ? `
${esc(answers[qi] === q.answer ? t('qz.correct') : t('qz.wrong'))} ${esc(q.explain)}
` : ''}
`;
}).join('');
const score = Object.entries(answers).filter(([qi, o]) => items[qi].answer === o).length;
$('#quizScore').textContent = `${t('qz.score')}: ${score} / ${items.length}`;
$$('#quizBox button[data-q]').forEach(b => b.addEventListener('click', () => {
answers[+b.dataset.q] = +b.dataset.o;
renderQuiz();
}));
}
$('#quizReset').addEventListener('click', () => { answers = {}; renderQuiz(); });
/* ------------------------------------------------------------ apply lang */
function applyLang(l) {
lang = l;
localStorage.setItem('mop-lang', l);
document.documentElement.lang = l;
document.title = t('meta.title');
$$('[data-i18n]').forEach(el => { el.textContent = t(el.dataset.i18n); });
$$('.lang button').forEach(b => b.classList.toggle('active', b.dataset.lang === l));
renderSteps(); renderMoons(); renderThemes(); renderPicker(); renderCraftInfo(); renderBars(); renderTable(); renderWhy(); renderTimeline(); renderQuiz();
if (scene) { selection ? showMoon(selection) : updateInfo(); scene.refreshLabels(); }
renderTourText();
renderWind();
renderUiToggle();
}
$$('.lang button').forEach(b => b.addEventListener('click', () => applyLang(b.dataset.lang)));
$('#menuBtn').addEventListener('click', () => document.body.classList.toggle('menu-open'));
$$('#nav a').forEach(a => a.addEventListener('click', () => document.body.classList.remove('menu-open')));
applyLang(lang);
initAuroraGallery();
if (params.has('explore')) startExploring();
if (params.get('view')) scene?.view(params.get('view'), true);
if (params.has('wind')) setWind(parseFloat(params.get('wind')) || 1, true);
if (params.has('clean')) toggleUi(true);
if (params.has('cme')) scene?.launchCME(parseFloat(params.get('cme')) || 0);
if (params.has('tour')) showStep(parseInt(params.get('tour'), 10) || 0);
if (CRAFT_ORDER.includes(params.get('craft'))) showCraft(params.get('craft'));
if (params.get('moon') && moonData(params.get('moon'))) flyToMoon(params.get('moon'), false, true);