import { useEffect, useMemo, useState, type CSSProperties } from 'react'; import { ArrowLeft, Camera, ChevronDown, ChevronLeft, ChevronRight, Clock3, Orbit, Pause, Play, RotateCcw, Rocket, ZoomIn, ZoomOut } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; import { fetchRocketConfigs } from '../features/rocket-simulator/api'; import { PHASE_LABELS, type FlightEvent, type FlightPhase, type RocketConfig } from '../features/rocket-simulator/types'; import { useRocketSimulation } from '../features/rocket-simulator/useRocketSimulation'; import { RocketFlightScene, type CameraMode } from '../features/rocket-simulator/RocketFlightScene'; import { TelemetryChart } from '../features/rocket-simulator/TelemetryChart'; import { engineLayout, FOLLOW_VIEW_YAW, layoutForRocket, stage1EngineGroups, stageGeometry, type EngineGroup, } from '../features/rocket-simulator/sceneMath'; import '../features/rocket-simulator/rocket-simulator.css'; import { resolveStage1 } from '../features/rocket-simulator/stageSplit'; /** * Canonical flight milestones, in order. Each maps to an event id emitted by * the physics loop. This single list is the SOLE source of truth for both the * mission profile timeline and the phase status readout, so they can never * disagree. */ const MILESTONES: Array<{ id: string; code: string; label: string }> = [ { id: 'liftoff', code: 'LIFTOFF', label: '点火起飞' }, { id: 'maxq', code: 'MAX-Q', label: '最大动压' }, { id: 'booster-sep', code: 'BS', label: '助推器分离' }, { id: 'meco', code: 'MECO', label: '一级关机' }, { id: 'separation', code: 'SEP', label: '级间分离' }, { id: 'ses1', code: 'SES-1', label: '二级点火' }, { id: 'seco', code: 'SECO-1', label: '二级关机' }, { id: 'orbit', code: 'ORBIT', label: '轨道注入' }, { id: 'deploy', code: 'PAYLOAD', label: '载荷部署' }, ]; /** * 里程碑清单:只有捆绑助推器的火箭(长征五号一类)才显示助推器分离节点; * 没有整流罩的火箭(星舰)末端节点是飞船入轨,而不是载荷分离。 */ function milestonesFor(rocket: RocketConfig) { const hasBoosters = layoutForRocket(rocket).layout === 'boosters'; const list = hasBoosters ? MILESTONES : MILESTONES.filter((item) => item.id !== 'booster-sep'); if (rocket.appearance?.fairing === false) { return list.map((item) => (item.id === 'deploy' ? { ...item, code: 'SHIP', label: '飞船入轨' } : item)); } return list; } function formatTime(seconds: number) { const sign = seconds < 0 ? '-' : '+'; const abs = Math.abs(Math.floor(seconds)); const h = Math.floor(abs / 3600); const m = Math.floor((abs % 3600) / 60); const s = abs % 60; const pad = (n: number) => String(n).padStart(2, '0'); return `T${sign}${h > 0 ? `${pad(h)}:` : ''}${pad(m)}:${pad(s)}`; } /* ------------------------------------------------------------------ */ /* Vehicle stack: the dashboard shows exactly what the 3D scene shows — */ /* full rocket → second stage after separation → payload at deploy. */ /* ------------------------------------------------------------------ */ type StackMode = 'full' | 'stage2' | 'payload'; function stackModeFor(phase: FlightPhase): StackMode { if (phase === 'ready' || phase === 'stage1_burn' || phase === 'stage1_cutoff') return 'full'; if (phase === 'payload_deploy' || phase === 'mission_complete') return 'payload'; return 'stage2'; } const STACK_MODE_LABEL: Record = { full: { code: 'FULL STACK', zh: '全箭组合体', detail: 'S1 + S2 + PAYLOAD · 待命' }, stage2: { code: 'STAGE 2', zh: '二级飞行', detail: 'S2 + PAYLOAD · 一级已分离' }, payload: { code: 'PAYLOAD', zh: '载荷部署', detail: '载荷分离 · 太阳翼展开' }, }; /** 无整流罩构型(星舰)的二级本身就是飞船,末端状态是飞船入轨。 */ const SHIP_MODE_LABEL: { code: string; zh: string; detail: string } = { code: 'SPACECRAFT', zh: '飞船入轨', detail: '二级即飞船 · 无载荷分离', }; /** * Vertical schematic of the launch vehicle. Height proportions come from the * real config (stageGeometry) — 箭体粗细、整流罩形状与发动机数量都与 3D 场景 * 使用同一套数据推导,因此示意图与真实火箭信息、三维模型三者始终一致。 * 图形状态由模式类(full / stage2 / payload)驱动,CSS 负责分离动画。 */ function StackDiagram({ rocket }: { rocket: RocketConfig }) { const geo = useMemo(() => stageGeometry(rocket), [rocket]); const TOP = 16; const BOTTOM = 212; const CX = 58; const scale = (BOTTOM - TOP) / geo.totalHeight; const r1 = Math.max(8, geo.radius * scale); const r2 = r1 * 0.97; // 无整流罩构型的头锥与二级等直径,不会比箭体更细 const rf = geo.fairing ? Math.max(r1 + 1.5, geo.fairingRadius * scale) : r2; const fairingH = geo.fairingHeight * scale; const coneH = geo.fairingConeHeight * scale; const s2H = geo.stage2Height * scale; const interH = Math.max(geo.interstageHeight * scale, 4); const s1H = geo.stage1Height * scale; const fairingBottom = TOP + fairingH; const coneTop = TOP; const barrelTop = TOP + coneH; const s2Top = fairingBottom; const interTop = s2Top + s2H; const s1Top = interTop + interH; const engineY = s1Top + s1H; const padY = engineY + 14; const metal = '#aeb7bd'; /** 侧视图中的发动机:把发动机舱布局投影到水平方向,按位置去重后绘制。 */ const engineBells = (count: number, radius: number, baseY: number) => { const drawn: Array<{ x: number; width: number }> = []; engineLayout(count, radius).forEach((placement) => { const x = CX + placement.x * scale; if (drawn.some((item) => Math.abs(item.x - x) < placement.bellRadius * scale * 0.9)) return; drawn.push({ x, width: Math.max(2.6, placement.bellRadius * 2 * scale) }); }); return drawn.map((bell, index) => ( )); }; return ( {/* measurement rail */} {rocket.height_m.toFixed(1)} M Ø {rocket.diameter_m.toFixed(1)} M {/* 助推器 / 侧芯级:按登记的直径比例画在芯级两侧(与芯级相切) */} {geo.layout === 'boosters' && [-1, 1].map((direction) => { // 长度按登记的长度比,底面与芯级一级底面齐平(与 3D 模型同一口径) const boosterH = s1H * geo.boosterLengthRatio; const boosterTop = s1Top + s1H - boosterH; const br = r1 * geo.boosterDiameterRatio; const bx = CX + direction * (r1 + br); return ( {/* 栅格翼:助推器自己可回收才画,贴在顶部两侧 */} {geo.boosterRecoverable && [-1, 1].map((side) => { const w = Math.max(3, br * 1.2); const h = Math.max(2, br * 0.8); return ( ); })} {engineBells(geo.enginesPerBooster, geo.radius * geo.boosterDiameterRatio * 1.08, boosterTop + boosterH)} ); })} {/* Stage 1 — drops away after separation */} {/* 栅格翼:一级登记为可回收才画 */} {geo.coreRecoverable && [-1, 1].map((direction) => { const x = CX + direction * r1; const y = s1Top + s1H * 0.06; return ( {[3.5, 7].map((offset) => ( ))} ); })} {engineBells(geo.layout === 'boosters' ? geo.coreEngines : geo.stage1Engines, geo.radius, engineY + 5)} {/* Upper stack (interstage + S2) */} {engineBells(geo.stage2Engines, geo.radius * 0.97, s2Top + s2H + 3.4)} {/* 头锥 / 整流罩:有整流罩时为两瓣卵形罩,载荷部署时分离;无整流罩时为飞船头锥 */} {geo.fairing ? ( ) : ( {/* 前 / 后襟翼 */} {[-1, 1].map((direction) => ( ))} )} {/* Payload satellite — revealed at deploy */} {geo.fairing && ( )} ); } function VehiclePanel({ rocket, mode, stage1FuelPct, stage2FuelPct }: { rocket: RocketConfig; mode: StackMode; stage1FuelPct: number; stage2FuelPct: number }) { const meta = mode === 'payload' && rocket.appearance?.fairing === false ? SHIP_MODE_LABEL : STACK_MODE_LABEL[mode]; const layout = layoutForRocket(rocket); // 芯级与助推器各自登记自己的机数,规格里分开写清各是几台 const stage1Engines = layout.layout === 'boosters' ? `${layout.coreEngines}+${layout.boosterCount}×${layout.enginesPerBooster}` : `${layout.coreEngines}`; // 只登记了构型的助推器不参与物理,起飞推力仍按一级整段计 const split = resolveStage1(rocket); const totalThrustMN = (split.coreThrustN + (split.boosters?.thrustN ?? 0)) / 1e6; return (
VEHICLE运载器状态
{meta.code} {meta.zh} {meta.detail}
一级{rocket.stage_1.name}{stage1FuelPct.toFixed(0)}%
二级{rocket.stage_2.name}{stage2FuelPct.toFixed(0)}%
箭体尺寸{rocket.height_m.toFixed(1)} × Ø{rocket.diameter_m.toFixed(1)} m
发动机{stage1Engines} + {rocket.stage_2.engine_count} 台
起飞推力{totalThrustMN.toFixed(2)} MN
二级推力{(rocket.stage_2.max_thrust_n / 1e6).toFixed(2)} MN
载荷{(rocket.payload_mass_kg / 1000).toFixed(1)} t
目标轨道{rocket.target_orbit_km} km
{rocket.manufacturer ? (
制造方{rocket.manufacturer}
) : null}
); } /* ------------------------------------------------------------------ */ /* Mission timeline: the mission clock progress bar IS the mission */ /* profile — every phase sits on the bar at its own node, so the */ /* progress readout and the phase list can never drift apart. */ /* ------------------------------------------------------------------ */ function MissionTimeline({ events, next, running, milestones, progress, }: { events: FlightEvent[]; next?: { id: string; code: string; label: string }; running: boolean; milestones: Array<{ id: string; code: string; label: string }>; progress: number; }) { const eventTime = (id: string) => events.find((event) => event.id === id)?.time ?? null; return (
{milestones.map((m, index) => { const time = eventTime(m.id); const reached = time !== null; const isNext = next?.id === m.id && running; const at = `${((index + 0.5) / milestones.length) * 100}%`; return ( {m.code} {m.label} ); })}
{progress.toFixed(0)}%
); } /* ------------------------------------------------------------------ */ /* Flight data panel (big green monospace numbers) */ /* ------------------------------------------------------------------ */ function FlightData({ state, history, totalFuelPct, stage1FuelPct, stage2FuelPct }: { state: ReturnType['state']; history: ReturnType['state']['history']; totalFuelPct: number; stage1FuelPct: number; stage2FuelPct: number; }) { return (
FLIGHT DATA飞行遥测
ALTITUDE
{(state.altitude / 1000).toFixed(1)}KM
VELOCITY
{(state.velocity * 3.6).toFixed(0)}KM/H
ACCELERATION
{(state.acceleration / 9.80665).toFixed(2)}G
DYNAMIC PRESS
{(state.dynamicPressure / 1000).toFixed(1)}KPA
DOWNRANGE
{(state.downrange / 1000).toFixed(1)}KM
PITCH
{state.pitch.toFixed(0)}°
ALT / VEL TRACE高度 · 速度
推进剂余量 / PROPELLANT{totalFuelPct.toFixed(0)}%
S1
{stage1FuelPct.toFixed(0)}%
S2
{stage2FuelPct.toFixed(0)}%
总推进剂{totalFuelPct.toFixed(0)}%
); } /* ------------------------------------------------------------------ */ /* Small mission-control widgets */ /* ------------------------------------------------------------------ */ /** 底栏左侧留给发动机示意图的显示预算:宽 380、高 104(与中间计时器那一列同高,不会把底栏顶高) */ const BANK_WIDTH = 380; const BANK_HEIGHT = 104; /** * 留空系数:真实位置是紧挨着的(同圈相邻喷管几乎相切、助推器舱与芯级舱相切), * 照原样画圆与圆就粘在一起,所以整体按同一系数缩小,间隙出现、圆之间的大小比例不变。 */ const DOT_GAP = 0.78; const BAY_GAP = 0.94; /** * 发动机仪表组:按俯视平面布置画芯级与每个助推器的发动机舱,芯级大圆在正中, * 助推器小圆贴在左右两侧(每侧两枚就是上下堆叠、相邻相切), * 圆的直径按「助推器直径 / 芯级直径」等比缩放(diameter_ratio)。 * 舱内点位取自 engineLayout:位置是真实的舱内平面位置, * 直径就是该规格发动机喷管出口的真实直径,于是「机少的火箭是大发动机、 * 星舰二级外圈 3 台大机 + 内圈 3 台小机」在示意图上和箭体完全一致。 * 分组与位置取自 stage1EngineGroups,与 3D 模型的喷管/尾焰同源。 */ function EngineBank({ label, groups, lit, boostersLit = lit, }: { label: string; groups: EngineGroup[]; lit: boolean; /** 助推器在一级飞行中段先分离,分离后其发动机不再点火 */ boostersLit?: boolean; }) { const isLit = (group: EngineGroup) => (group.kind === 'core' ? lit : boostersLit); const total = groups.reduce((sum, group) => sum + group.engines, 0); const firing = groups.filter(isLit).reduce((sum, group) => sum + group.engines, 0); // 舱心位置以「芯级半径」为单位。3D 机位相对箭体有固定方位角(FOLLOW_VIEW_YAW), // 俯视图里把它减掉,左右两组助推器才对称。 const cells = groups.map((group) => ({ group, x: Math.cos(group.angle + FOLLOW_VIEW_YAW) * group.offset, y: Math.sin(group.angle + FOLLOW_VIEW_YAW) * group.offset, })); const edges = cells.reduce((box, cell) => ({ left: Math.min(box.left, cell.x - cell.group.radius), right: Math.max(box.right, cell.x + cell.group.radius), top: Math.min(box.top, cell.y - cell.group.radius), bottom: Math.max(box.bottom, cell.y + cell.group.radius), }), { left: -1, right: 1, top: -1, bottom: 1 }); // base 是一个芯级半径对应的像素数:整组按包围盒缩放到预算内最大的尺寸 const base = Math.min( BANK_WIDTH / (edges.right - edges.left), BANK_HEIGHT / (edges.bottom - edges.top), ); return (
{cells.map(({ group, x, y }, index) => { const unit = base * 2 * group.radius * BAY_GAP; // engineLayout 的归一化坐标与喷管半径都以「舱半径 = 1」为单位, // 圆环内壁正好就是一个舱半径,所以点位按内壁半径等比换算即可, // 发动机再多也只会挤到圆环内壁上,不会画到舱外。 const inner = unit / 2 - 2; const placements = engineLayout(group.engines, 1); return (
{placements.map((placement, dotIndex) => ( ))}
); })}
); } function AttitudeGauge({ pitch }: { pitch: number }) { const vehicleRotation = 45 - pitch; return (
PITCH {pitch.toFixed(0)}°
); } /* ------------------------------------------------------------------ */ /* Page */ /* ------------------------------------------------------------------ */ function RocketMission({ rockets }: { rockets: RocketConfig[] }) { const navigate = useNavigate(); const [selectedCode, setSelectedCode] = useState(rockets[0].code); const [cameraMode, setCameraMode] = useState('follow'); const [viewScale, setViewScale] = useState(100); const [viewScaleResetTrigger, setViewScaleResetTrigger] = useState(0); const rocket = rockets.find((item) => item.code === selectedCode) || rockets[0]; const { state, toggle, reset, speed, setSpeed } = useRocketSimulation(rocket); // 一级推进剂的起点是「芯级 + 助推器」的合计(与 initialState 同一口径), // 助推器烧完先分离,余量也随之归零,因此 S1% 会在那一刻下一个台阶 const stage1FuelKg = rocket.stage_1.fuel_mass_kg + (resolveStage1(rocket).boosters?.fuelKg ?? 0); const totalFuel = stage1FuelKg + rocket.stage_2.fuel_mass_kg; const remainingFuel = state.stage1Fuel + state.stage2Fuel; const stage1FuelPct = Math.max(0, state.stage1Fuel / stage1FuelKg * 100); const stage2FuelPct = Math.max(0, state.stage2Fuel / rocket.stage_2.fuel_mass_kg * 100); const totalFuelPct = Math.max(0, remainingFuel / totalFuel * 100); const eventTime = (id: string) => state.events.find((event) => event.id === id)?.time ?? null; const milestones = useMemo(() => milestonesFor(rocket), [rocket]); const reachedCount = milestones.filter((m) => eventTime(m.id) !== null).length; const progress = reachedCount / milestones.length * 100; const nextMilestone = milestones.find((m) => eventTime(m.id) === null); const stackMode = stackModeFor(state.phase); // 仪表盘发动机示意:一级按芯级 + 助推器分组,二级只有芯级一组 const stage1Groups = useMemo(() => stage1EngineGroups(layoutForRocket(rocket)), [rocket]); const stage2Groups: EngineGroup[] = [ { kind: 'core', engines: Math.max(1, Math.round(rocket.stage_2.engine_count)), radius: 1, offset: 0, angle: 0 }, ]; const stage: 1 | 2 = ['separating', 'stage2_ignition', 'stage2_burn', 'orbit', 'payload_deploy', 'mission_complete'].includes(state.phase) ? 2 : 1; const stageFiring = stage === 1 ? state.phase === 'stage1_burn' : state.phase === 'stage2_ignition' || state.phase === 'stage2_burn'; const launchLabel = state.phase === 'mission_complete' ? '重新模拟' : state.isRunning ? '暂停' : state.phase === 'ready' ? '执行点火' : '继续'; const clockText = state.phase === 'ready' && !state.isRunning ? 'T-00:00:00' : formatTime(state.time); /* * 左右两块面板:离地升空后自动收起,把画面让给箭体。 * 手动开合记成 override,没动过把手就完全交给「是否已升空」决定, * 于是自动收起之后手动展开不会被再次收起,按重置回到发射台又会展开。 * 两块面板共用一个开关:窄屏下左侧面板整块隐藏,分开记状态可能出现 * 「收起之后没有把手能打开」。 */ const [panelsOverride, setPanelsOverride] = useState(null); const panelsOpen = panelsOverride ?? state.altitude <= 0; const togglePanels = () => setPanelsOverride(!panelsOpen); return (
{/* Top bar: brand + mission status + vehicle selector + view controls */}
COSMO LAUNCH{rocket.name_zh || rocket.name} · {rocket.name}
MISSION STATUS{PHASE_LABELS[state.phase as FlightPhase]}
{/* 完整任务约 9 分钟,提供三段倍速开关便于观察分离、入轨与载荷部署 */}
{/* Left: mission profile + vehicle stack */} {/* Right: flight telemetry */} {/* 收起后贴在屏幕边缘的把手:点一下展开,再点一下收起 */} {/* Bottom: engine bank + mission clock + progress + attitude + controls */}
{clockText}
MISSION TIME · REAL TIME
); } export function RocketSimulator() { const [rockets, setRockets] = useState([]); const [error, setError] = useState(''); useEffect(() => { fetchRocketConfigs().then(setRockets).catch(() => setError('火箭配置加载失败,请确认数据库升级脚本已执行。')); }, []); // 管理端改完参数、后端启动补完助推器口径之后,本页不会自己发现数据变了: // 箭体外形与仪表圈都按打开页面时取到的直径比绘制,于是管理端明明填了 1, // 这里还按旧值画。切回本页时静默重取一次,取到空列表则维持原状。 useEffect(() => { const refetch = () => { if (document.visibilityState !== 'visible') return; fetchRocketConfigs() .then((next) => { if (next.length > 0) setRockets(next); }) .catch(() => undefined); }; document.addEventListener('visibilitychange', refetch); return () => document.removeEventListener('visibilitychange', refetch); }, []); if (error) return ; if (rockets.length === 0) return
正在载入发射任务
; return ; }