import { useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import type { RocketConfig, SimulationState } from './types';
import {
boosterAngle,
engineLayout,
engineState,
separationAge,
separationTransform,
stage1EngineGroups,
stageGeometry,
type EngineGroup,
} from './sceneMath';
/*
* 运载火箭 3D 模型
*
* 几何比例、发动机数量与排布、箭体涂装与文字标识全部来自火箭配置
* (height_m / diameter_m / length_ratio / engine_count / color / name),
* 因此猎鹰 9(9 + 1 台发动机、细长箭体、大直径整流罩)与长征五号
* (10 + 2 台发动机、5m 箭体、近乎等径整流罩)在场景里一眼可辨。
*/
const SOOT = '#14171a';
const DARK = '#191d22';
const METAL = '#9aa4ad';
const COMPOSITE = '#e3e7ea';
/** 由箭体颜色推导深/浅两种涂装色,避免所有火箭长得一样。 */
function shade(hex: string, amount: number): string {
const color = new THREE.Color(hex);
const target = amount >= 0 ? new THREE.Color('#ffffff') : new THREE.Color('#0b0d10');
return color.lerp(target, Math.abs(amount)).getStyle();
}
/**
* 用 canvas 生成箭体文字标识(型号名 / 级次),让模型与火箭资料对应。
*/
function useDecalTexture(text: string, color: string, background: string) {
return useMemo(() => {
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
ctx.fillStyle = background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = color;
ctx.font = 'bold 64px "Helvetica Neue", Arial, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text.slice(0, 16), canvas.width / 2, canvas.height / 2 + 4);
const texture = new THREE.CanvasTexture(canvas);
texture.anisotropy = 4;
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}, [background, color, text]);
}
/** 一圈弧面贴片:用于把文字标识包在箭体表面。 */
function BodyDecal({
radius,
height,
y,
text,
textColor,
background,
facing = 0,
}: {
radius: number;
height: number;
y: number;
text: string;
textColor: string;
background: string;
facing?: number;
}) {
const texture = useDecalTexture(text, textColor, background);
if (!texture) return null;
return (
);
}
/** 箭体加强环:打断大面积圆柱面,让细长箭体有机械层次。 */
function StringerRings({ radius, height, baseY = 0, count = 3 }: { radius: number; height: number; baseY?: number; count?: number }) {
const ys = useMemo(
() => Array.from({ length: count }, (_, index) => baseY + height * ((index + 1) / (count + 1))),
[baseY, count, height],
);
return (
{ys.map((y) => (
))}
);
}
/** 电缆罩(贯穿箭体的走线通道),真实运载火箭的显著特征之一。 */
function Raceway({ radius, height, baseY = 0 }: { radius: number; height: number; baseY?: number }) {
return (
);
}
/** 单个喷管:收敛段 + 扩张段 + 喷管出口。 */
function Nozzle({ radius, length, color = METAL }: { radius: number; length: number; color?: string }) {
return (
);
}
/**
* 发动机舱:隔热盘 + 按配置排布的喷管 + 伺服作动器。
* 喷管数量与位置由火箭配置的 engine_count 决定。
*/
function EngineCluster({
radius,
count,
bellColor = METAL,
showActuators = true,
}: {
radius: number;
count: number;
bellColor?: string;
showActuators?: boolean;
}) {
const placements = useMemo(() => engineLayout(count, radius), [count, radius]);
return (
{/* 尾段 / 隔热盘 */}
{placements.map((placement, index) => (
{
// 外圈发动机沿径向向外偏摆(真实矢量布局)。
const angle = Math.atan2(placement.z, placement.x);
return [-Math.sin(angle) * placement.cant, 0, Math.cos(angle) * placement.cant];
})()}
>
{showActuators && placement.bellRadius > radius * 0.2 && (
)}
))}
);
}
/**
* 发动机尾焰:外层橙焰 + 内层白芯 + 马赫环。
* 整个尾焰锚定在喷管出口(局部 y = 0)向下生长,缩放时焰根始终贴合喷管。
*/
function EnginePlume({
radius,
length,
throttle,
active,
running,
nozzleY = 0,
spread = 1,
}: {
radius: number;
length: number;
throttle: number;
active: boolean;
running: boolean;
nozzleY?: number;
spread?: number;
}) {
const anchorRef = useRef(null);
const lightRef = useRef(null);
const diamondRef = useRef(null);
useFrame(({ clock }) => {
if (!anchorRef.current || !running) return;
const flicker = 0.88 + Math.sin(clock.elapsedTime * 42) * 0.08 + Math.random() * 0.05;
const stretch = flicker * (0.45 + throttle * 0.75);
anchorRef.current.scale.set(0.8 + throttle * 0.3, stretch, 0.8 + throttle * 0.3);
if (lightRef.current) lightRef.current.intensity = 6 + flicker * 4 * throttle;
if (diamondRef.current) {
diamondRef.current.children.forEach((child, index) => {
const pulse = 0.65 + Math.sin(clock.elapsedTime * 30 + index * 1.3) * 0.35;
child.scale.setScalar(0.7 + pulse * 0.5 * throttle);
});
}
});
if (!active) return null;
return (
{/* 外层燃气 */}
{/* 内层亮芯 */}
{/* 喷管根部的蓝色激波 */}
{/* 马赫环 */}
{[0.34, 0.56, 0.76].map((offset) => (
))}
);
}
interface StageProps {
radius: number;
height: number;
color: string;
}
/** 一级芯级:箭体 + 涂装 + 走线罩 + 加强环 + 尾段发动机。基座位于局部 y = 0。 */
function FirstStageBody({
radius,
height,
color,
engineCount,
label,
gridFins = false,
}: StageProps & { engineCount: number; label: string; gridFins?: boolean }) {
const accent = shade(color, -0.55);
return (
{/* 底部防热 / 烟熏段 */}
{/* 顶部深色带 */}
{gridFins && }
);
}
/** 栅格翼:细长单芯级回收构型(猎鹰 9)靠近一级顶部的四片格栅。 */
function GridFins({ radius, y, color }: { radius: number; y: number; color: string }) {
return (
{[0, 1, 2, 3].map((index) => {
const angle = (index / 4) * Math.PI * 2 + Math.PI / 4;
return (
{/* 翼盒 */}
{/* 格栅叶片 */}
{[-0.24, 0, 0.24].map((offset) => (
))}
);
})}
);
}
/**
* 捆绑助推器 / 侧芯级:并联在芯级四周,自带头锥、涂装、发动机与尾焰。
* group 是它在一级发动机分组里的那一项(stage1EngineGroups 产出),
* radius / offset 分别是它与芯级的直径比和圆心距(芯级半径的倍数),
* 两者相切布置,因此猎鹰重型能画出真实的「三根并排芯级」。
* 尾焰放在助推器节点内,分离散开时会跟着一起翻滚。
*/
function StrapOnBooster({
radius,
height,
color,
group,
throttle,
active,
running,
}: {
radius: number;
height: number;
color: string;
group: EngineGroup;
throttle: number;
active: boolean;
running: boolean;
}) {
const bodyRadius = radius * group.radius;
const offset = radius * group.offset;
const noseHeight = height * 0.22;
return (
{/* 助推器箭体 */}
{/* 头锥 */}
{/* 涂装环 */}
{/* 与芯级的连接件 */}
{/* 助推器发动机舱:只画本机自己的喷管,不借用一级总数 */}
{/* 助推器尾焰 */}
);
}
/** 级间段:深色结构段 + 分离火箭。 */
function Interstage({ radius, height }: { radius: number; height: number }) {
const motors = useMemo(() => [0, 1, 2, 3].map((index) => (index / 4) * Math.PI * 2 + Math.PI / 4), []);
return (
{motors.map((angle) => (
))}
);
}
/** 二级姿态控制推力器组(RCS)。 */
function RcsCluster({ radius, y, angle }: { radius: number; y: number; angle: number }) {
return (
{[-0.35, 0, 0.35].map((offset) => (
))}
);
}
/** 二级:箭体 + 涂装 + RCS + 发动机。基座位于局部 y = 0。 */
function SecondStageBody({
radius,
height,
color,
engineCount,
label,
}: StageProps & { engineCount: number; label: string }) {
const bodyRadius = radius * 0.97;
const accent = shade(color, -0.5);
return (
{[0, 1, 2, 3].map((index) => (
))}
);
}
/** 整流罩头锥的卵形母线,比圆锥更接近真实整流罩。 */
function ogivePoints(radius: number, height: number, segments = 14): THREE.Vector2[] {
return Array.from({ length: segments + 1 }, (_, index) => {
const t = index / segments;
const y = height * t;
const r = radius * Math.pow(1 - t, 0.62);
return new THREE.Vector2(Math.max(r, 0.0005), y);
});
}
/**
* 半瓣载荷整流罩:圆柱段 + 卵形头锥。
* 两瓣用各自的起始角直接生成几何(不做整体旋转),
* 因此外层动画无论如何变换都不会再出现「只剩半片」的情况。
*/
function FairingHalf({
radius,
barrelHeight,
coneHeight,
color,
startAngle,
}: {
radius: number;
barrelHeight: number;
coneHeight: number;
color: string;
startAngle: number;
}) {
const profile = useMemo(() => ogivePoints(radius, coneHeight), [coneHeight, radius]);
return (
{/* 对接框 */}
);
}
/**
* 无整流罩构型(星舰)的飞船头锥:与二级等直径的钝头锥。
* 这类火箭的二级本身就是飞船,整流罩的位置只剩头锥。
*/
function ShipNose({ radius, height, color }: { radius: number; height: number; color: string }) {
const coneHeight = height * 0.78;
const barrelHeight = height - coneHeight;
const profile = useMemo(() => ogivePoints(radius, coneHeight), [coneHeight, radius]);
return (
);
}
/**
* 星舰二类构型的箭体襟翼:前 2 片小襟翼 + 后 2 片大襟翼,
* 上升段收拢贴在箭体两侧,与真实飞船一眼对应。
* 以二级(飞船)顶部为原点,因此 y 为负值。
*/
function ShipFlaps({ radius, height, color }: { radius: number; height: number; color: string }) {
const flaps = [
{ y: -height * 0.12, span: radius * 0.95, chord: radius * 0.6 },
{ y: -height * 0.86, span: radius * 1.55, chord: radius * 1.1 },
];
return (
{flaps.map((flap) => (
[-1, 1].map((direction) => (
))
))}
);
}
/** 载荷适配器:二级顶部与卫星之间的锥形对接结构。 */
function PayloadAdapter({ radius, height }: { radius: number; height: number }) {
return (
);
}
/** 载荷卫星:星体 + 通信天线 + 太阳翼(部署时展开)。 */
function PayloadSatellite({ radius, panelProgress }: { radius: number; panelProgress: number }) {
const satelliteRef = useRef(null);
const eased = 1 - Math.pow(1 - panelProgress, 3);
const panelLength = radius * 3.4;
const cells = useMemo(() => Array.from({ length: 6 }, (_, index) => index), []);
useFrame((_, delta) => {
// 缓慢自转,并保持一个固定倾角,让太阳翼朝向镜头时更好辨认
if (satelliteRef.current) satelliteRef.current.rotation.y += delta * 0.08;
});
return (
{/* 星体(金色多层隔热材料) */}
{/* 抛物面天线 */}
{/* 天线阵 */}
{[-1, 1].map((direction) => (
))}
{/* 太阳翼:每侧两块板,展开时沿转轴伸出 */}
{[-1, 1].map((direction) => (
{[0, 1].map((panelIndex) => (
{cells.map((cell) => (
))}
))}
))}
);
}
interface RocketModelProps {
rocket: RocketConfig;
state: SimulationState;
}
/**
* 完整运载火箭:一级在分离后坠落,整流罩在载荷部署时两瓣分离,
* 载荷随后与二级分离并展开太阳翼。
*/
export function RocketModel({ rocket, state }: RocketModelProps) {
const geo = useMemo(() => stageGeometry(rocket), [rocket]);
const engines = engineState(state);
// 一级发动机分组:芯级与每个助推器各自的机数与平面位置
const boosterGroups = useMemo(
() => stage1EngineGroups(geo).filter((group) => group.kind === 'booster'),
[geo],
);
const age = separationAge(state);
const sep = separationTransform(age);
const deployEvent = state.events.find((event) => event.id === 'deploy');
const deployAge = deployEvent ? Math.max(0, state.time - deployEvent.time) : null;
const deployProgress = deployAge === null ? 0 : Math.min(1, deployAge / 2.6);
const fairingAge = deployAge;
const firstStageRef = useRef(null);
const boosterRef = useRef(null);
const upperStackRef = useRef(null);
const fairingRef = useRef(null);
const boosterEvent = state.events.find((event) => event.id === 'booster-sep');
const boosterAge = boosterEvent ? Math.max(0, state.time - boosterEvent.time) : null;
const upperBaseY = geo.stage1Height;
const stage2BaseY = geo.interstageHeight;
const fairingBaseY = geo.interstageHeight + geo.stage2Height;
const payloadY = fairingBaseY + geo.fairingBarrelHeight * 0.45;
const firstStageLabel = rocket.name_zh || rocket.name;
const secondStageLabel = rocket.stage_2.name;
// 整流罩是复合材料壳体:以白色为底,掺入少量箭体涂装色以便区分型号。
const fairingColor = useMemo(() => {
const base = new THREE.Color(COMPOSITE);
return base.lerp(new THREE.Color(rocket.color), 0.16).getStyle();
}, [rocket.color]);
useFrame(() => {
if (firstStageRef.current) {
if (sep) {
firstStageRef.current.position.set(sep.drift, -sep.drop, 0);
firstStageRef.current.rotation.set(sep.tumble * 0.55, sep.tumble * 0.28, sep.tumble);
firstStageRef.current.visible = sep.opacity > 0.02;
} else {
firstStageRef.current.position.set(0, 0, 0);
firstStageRef.current.rotation.set(0, 0, 0);
firstStageRef.current.visible = true;
}
}
// 助推器:分离后向四周散开、翻滚,飞出画面后隐藏
if (boosterRef.current) {
if (boosterAge === null) {
boosterRef.current.visible = true;
boosterRef.current.children.forEach((child) => {
child.position.set(0, 0, 0);
child.rotation.set(0, 0, 0);
child.visible = true;
});
} else {
const spread = geo.radius * (boosterAge * 2.2);
const visible = boosterAge < 3.2;
boosterRef.current.visible = visible;
boosterRef.current.children.forEach((child, index) => {
const angle = boosterAngle(index, boosterRef.current!.children.length);
child.position.set(
Math.cos(angle) * spread,
-0.6 * boosterAge - 0.35 * boosterAge * boosterAge,
Math.sin(angle) * spread,
);
child.rotation.set(boosterAge * 0.6, boosterAge * 0.25, boosterAge * (index % 2 === 0 ? 0.8 : -0.8));
child.visible = visible;
});
}
}
if (upperStackRef.current) {
// 无整流罩构型的二级就是飞船,入轨后继续留在画面里,不随载荷一起淡出
if (deployAge === null || !geo.fairing) {
upperStackRef.current.position.set(0, upperBaseY, 0);
upperStackRef.current.rotation.set(0, 0, 0);
upperStackRef.current.visible = true;
} else {
upperStackRef.current.position.set(-deployAge * 0.7, upperBaseY - deployAge * 0.8, deployAge * 0.16);
upperStackRef.current.rotation.set(deployAge * 0.14, deployAge * 0.07, -deployAge * 0.28);
upperStackRef.current.visible = deployAge < 5.4;
}
}
// 整流罩两瓣:向外平移 + 翻转分离后淡出。
if (fairingRef.current) {
const open = fairingAge === null ? 0 : Math.min(1, fairingAge / 2.2);
const opacity = Math.max(0, 1 - open * 1.05);
fairingRef.current.children.forEach((child, index) => {
const direction = index === 0 ? 1 : -1;
child.position.set(direction * open * geo.fairingRadius * 3.2, open * geo.fairingRadius * 0.55, 0);
child.rotation.set(0, 0, direction * open * 1.1);
child.visible = opacity > 0.02;
child.traverse((node) => {
const material = (node as THREE.Mesh).material as THREE.MeshStandardMaterial | undefined;
if (material && 'opacity' in material) material.opacity = opacity;
});
});
fairingRef.current.visible = fairingAge === null || fairingAge < 2.6;
}
});
return (
{/* 上面级:级间段 + 二级 + 整流罩 + 载荷 */}
{/* 二级尾焰:自二级喷管出口向下喷出 */}
{/* 载荷适配器 + 卫星(整流罩抛离后可见) */}
{geo.fairing && (
)}
{geo.fairing ? (
{/* 每瓣外面再包一层,动画只作用于外层,避免覆盖半瓣自身的朝向 */}
) : (
)}
{/* 载荷:部署后脱离上面级独立存在,上面级淡出后载荷仍然保留在场景中 */}
{geo.fairing && deployAge !== null && (
)}
{/* 一级:未分离时位于上面级下方,分离后翻滚坠落 */}
{/* 捆绑助推器:先于芯级分离,分离后向四周散开 */}
{boosterGroups.length > 0 && (
{boosterGroups.map((group, index) => (
))}
)}
);
}