feat: 添加地面站实体创建逻辑,优化管理器功能
Some checks failed
/ surge (push) Successful in 2m46s
/ build-and-deploy-to-vercel (push) Successful in 2m51s
/ lint-build-and-check (push) Successful in 4m36s
/ playwright (push) Has been cancelled

This commit is contained in:
严浩
2025-04-03 15:12:11 +08:00
parent aacd168450
commit 5a69629f35
9 changed files with 183 additions and 137 deletions

View File

@ -24,7 +24,7 @@ export class SatelliteCalculator {
* @returns 解析成功返回 SatRec 对象,否则返回 null。
*/
parseTle(tle: string, satelliteId: string): null | SatRec {
const tleLines = tle.trim().split('\n');
const tleLines = tle.trim().split('\n') as [string, string, string];
if (tleLines.length < 3) {
console.error(`无效的 TLE 格式 (ID: ${satelliteId}): TLE 字符串至少需要三行`);
return null;

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import type { HCesiumManagerStationState, HCesiumManagerSatelliteState } from './useHCesiumManager.types';
import type { HCesiumManagerSatelliteState, HCesiumManagerStationState } from './useHCesiumManager.types';
import { useHCesiumManager } from './useHCesiumManager';
import { useHCesiumManagerSatellite } from './useHCesiumManager.卫星';
@ -8,8 +8,8 @@ import { useHCesiumManagerStation } from './useHCesiumManager.站点';
import 'cesium/Build/Cesium/Widgets/widgets.css';
const props = defineProps<{
groundStationState?: HCesiumManagerStationState;
satelliteState?: HCesiumManagerSatelliteState;
stationState?: HCesiumManagerStationState;
}>();
// 1. 管理 Cesium Viewer 实例生命周期
@ -19,8 +19,8 @@ const { hCesiumViewerManager } = useHCesiumManager('cesium-container'); // 获
// 将实例的 getter 和 props 的 getter 传递给组合函数
useHCesiumManagerStation(
() => hCesiumViewerManager, // 传递 Manager 实例的 getter
() => props.groundStationState?.stations, // 从新的 prop 中获取列表
() => props.groundStationState?.selectedIds, // 从新的 prop 中获取选中 ID
() => props.stationState?.stations, // 从新的 prop 中获取列表
() => props.stationState?.selectedIds, // 从新的 prop 中获取选中 ID
);
// 3. 同步卫星实体

View File

@ -25,6 +25,7 @@ export class HCesiumManager {
try {
this.viewer = new Cesium.Viewer(container, VIEWER_OPTIONS_FN());
if ($__DEV__) Object.assign(globalThis, { viewer: this.viewer });
configureTimeLine(this.viewer);

View File

@ -12,9 +12,11 @@ export interface I卫星 {
id: string; // 卫星的唯一标识符
orbitDurationSeconds?: number; // 轨道显示时长
showOrbit: boolean; // 是否显示完整轨道线
showCoverage: boolean; // 控制覆盖范围显示 (必填)
timeStepSeconds?: number; // 轨道计算步长(秒),默认为 30
tle: string; // 包含卫星名称和两行 TLE 数据的字符串,格式如下:
// NAME
// TLE1
// TLE2
showPath: boolean; // 控制是否显示路径/轨迹 (必填)
}

View File

@ -7,7 +7,7 @@ import { type OrbitCalculationResult, SatelliteCalculator } from '../calculators
interface ManagedSatelliteEntities {
coverageEntity?: Cesium.Entity;
entity: Cesium.Entity;
mainEntity: Cesium.Entity;
orbitEntity?: Cesium.Entity;
}
@ -25,29 +25,26 @@ export class HCesiumSatelliteManager {
/**
* 向视图中添加或更新卫星实体及其相关元素(轨道、覆盖范围)。
* 注意:当前实现仅添加,如果已存在则警告并返回现有实体。
* @param options - 卫星的选项参数
* @returns 添加的卫星主实体对象,如果已存在或添加失败则返回 null 或现有实体。
*/
addOrUpdateSatellite(options: I卫星): Cesium.Entity | null {
addOrUpdateSatellite(options: I卫星): undefined {
const existingEntry = this.currentSatelliteEntities.get(options.id);
const { id, tle, showOrbit, showCoverage } = options;
// --- 如果实体已存在,直接返回,不处理更新 ---
if (existingEntry) {
console.warn(`ID 为 "${options.id}" 的卫星实体已由管理器追踪,跳过添加。`);
// 未来可以扩展为更新逻辑
return existingEntry.entity;
console.warn(`ID 为 "${options.id}" 的卫星实体已存在,跳过添加。`);
return;
}
const { id, tle, showOrbit } = options;
// --- 解析 TLE 和计算轨道 ---
const satrec = this.calculator.parseTle(tle, id);
if (!satrec) {
return null; // 解析失败,已打印错误
return undefined; // 解析失败,已打印错误
}
const viewer = this.viewerManager.getViewer();
if (!viewer) {
console.error('Viewer 未初始化,无法计算轨道。');
return null;
return undefined;
}
const startTime = viewer.clock.currentTime; // 使用当前 viewer 的时间作为起点
@ -55,73 +52,32 @@ export class HCesiumSatelliteManager {
if (!orbitResult) {
console.error(`计算卫星 ${id} 的轨道失败。`);
return null;
return undefined;
}
const { sampledPositionProperty, orbitPositions } = orbitResult;
// --- 计算结束 ---
// --- 从 TLE 提取名称 ---
const tleLines = tle.trim().split('\n');
const name = tleLines.length > 0 ? tleLines[0].trim() : `Satellite ${id}`;
const tleLines = tle.trim().split('\n') as [string, string, string];
const name = tleLines[0].trim();
// --- 提取结束 ---
// --- 创建实体 ---
const randomBaseColor = Cesium.Color.fromRandom({ alpha: 1 }); // 确保 alpha 为 1
// 创建卫星实体
const satelliteEntity = new Cesium.Entity({
id,
name,
position: sampledPositionProperty, // 使用计算好的位置属性
orientation: new Cesium.VelocityOrientationProperty(sampledPositionProperty),
point: {
pixelSize: 8,
color: randomBaseColor,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 1,
},
label: {
text: name,
font: '14pt sans-serif',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -10),
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
},
// 动态轨迹路径 (Path) - 注意:这与完整轨道线 (Polyline) 不同
path: {
resolution: 1,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.15,
color: randomBaseColor,
}),
width: 2,
leadTime: (options.orbitDurationSeconds ?? 3600 * 2) / 2, // 默认1小时
trailTime: (options.orbitDurationSeconds ?? 3600 * 2) / 2, // 默认1小时
},
});
const satelliteEntity = this._createSatelliteEntity(id, name, sampledPositionProperty, randomBaseColor, options);
// 添加卫星地面覆盖范围
const coverageEntity = this.createCoverageEntity(id, name, sampledPositionProperty, randomBaseColor);
// --- 创建覆盖范围实体 (如果需要) ---
let coverageEntity: Cesium.Entity | null | undefined;
if (showCoverage) {
coverageEntity = this._createCoverageEntity(id, name, sampledPositionProperty, randomBaseColor);
}
// --- 创建结束 ---
// 添加完整轨道线(如果需要)
let orbitEntity: Cesium.Entity | undefined;
if (showOrbit && orbitPositions.length > 1) {
orbitEntity = new Cesium.Entity({
id: `${id}-orbit`,
name: `${name} 轨道`,
polyline: {
positions: orbitPositions,
width: 1,
material: new Cesium.PolylineDashMaterialProperty({
color: randomBaseColor.withAlpha(0.5),
dashLength: 16,
}),
clampToGround: false,
},
});
orbitEntity = this._createOrbitEntity(id, name, orbitPositions, randomBaseColor);
}
// --- 创建结束 ---
@ -129,7 +85,7 @@ export class HCesiumSatelliteManager {
const addedMainEntity = this.viewerManager.addEntity(satelliteEntity);
if (!addedMainEntity) {
console.error(`通过 ViewerManager 添加卫星主体 ID 为 "${id}" 的实体失败。`);
return null; // 主实体添加失败则中止
return undefined; // 主实体添加失败则中止
}
let addedCoverageEntity: Cesium.Entity | null = null;
@ -151,18 +107,63 @@ export class HCesiumSatelliteManager {
// 存储实体引用
this.currentSatelliteEntities.set(id, {
entity: addedMainEntity, // 存储实际添加成功的实体
mainEntity: addedMainEntity, // 存储实际添加成功的实体
orbitEntity: addedOrbitEntity ?? undefined,
coverageEntity: addedCoverageEntity ?? undefined,
});
}
return addedMainEntity;
/**
* 创建卫星主体实体。
*/
private _createSatelliteEntity(
id: string,
name: string,
sampledPositionProperty: Cesium.SampledPositionProperty,
randomBaseColor: Cesium.Color,
options: I卫星,
): Cesium.Entity {
// 动态轨迹路径 (Path) - 注意:这与完整轨道线 (Polyline) 不同
const path: Cesium.PathGraphics.ConstructorOptions = {
resolution: 1,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.15,
color: randomBaseColor,
}),
width: 2,
leadTime: (options.orbitDurationSeconds ?? 3600 * 2) / 2, // 默认1小时
trailTime: (options.orbitDurationSeconds ?? 3600 * 2) / 2, // 默认1小时
};
return new Cesium.Entity({
id,
name,
path: options.showPath ? path : undefined, // 根据 options.showPath 控制是否显示路径
position: sampledPositionProperty, // 使用计算好的位置属性
orientation: new Cesium.VelocityOrientationProperty(sampledPositionProperty),
point: {
pixelSize: 8,
color: randomBaseColor,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 1,
},
label: {
text: name,
font: '14pt sans-serif',
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -10),
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
},
});
}
/**
* 创建卫星覆盖范围实体。
*/
private createCoverageEntity(
private _createCoverageEntity(
satelliteId: string,
satelliteName: string,
positionProperty: Cesium.SampledPositionProperty,
@ -215,6 +216,30 @@ export class HCesiumSatelliteManager {
});
}
/**
* 创建卫星轨道实体。
*/
private _createOrbitEntity(
satelliteId: string,
satelliteName: string,
orbitPositions: Cesium.Cartesian3[],
baseColor: Cesium.Color,
): Cesium.Entity {
return new Cesium.Entity({
id: `${satelliteId}-orbit`,
name: `${satelliteName} 轨道`,
polyline: {
positions: orbitPositions,
width: 1,
material: new Cesium.PolylineDashMaterialProperty({
color: baseColor.withAlpha(0.5),
dashLength: 16,
}),
clampToGround: false, // 轨道通常不贴地
},
});
}
/**
* 从视图中移除指定的卫星实体及其相关元素 (通过 ID)。
* @param entityId - 要移除的卫星实体的 ID。
@ -230,7 +255,7 @@ export class HCesiumSatelliteManager {
let allRemoved = true;
// 移除主体
if (!this.viewerManager.removeEntity(satelliteData.entity)) {
if (!this.viewerManager.removeEntity(satelliteData.mainEntity)) {
console.warn(`尝试通过 ViewerManager 移除卫星主体 ID 为 "${entityId}" 的实体失败。`);
allRemoved = false;
}

View File

@ -18,19 +18,38 @@ export class HCesiumStationManager {
* @param options - 地面站的选项参数
* @returns 添加的实体对象,如果已存在或添加失败则返回 null 或现有实体。
*/
addOrUpdateStation(options: I站点): Cesium.Entity | null {
addOrUpdateStation(options: I站点): undefined {
const existingEntity = this.currentStationEntities.get(options.id);
if (existingEntity) {
console.warn(`ID 为 "${options.id}" 的地面站实体已由管理器追踪,跳过添加。`);
// 未来可以扩展为更新逻辑
return existingEntity;
return;
}
// 解构赋值获取站点信息
const { height = 0, id, latitude, longitude, name, pixelSize = 10 } = options;
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
const groundStationEntity = new Cesium.Entity({
const stationEntity = this._createStationEntity(id, name, position, pixelSize);
const addedEntity = this.viewerManager.addEntity(stationEntity);
if (addedEntity) {
this.currentStationEntities.set(id, addedEntity); // 添加成功后,将其存入 Map
} else {
console.error(`通过 ViewerManager 添加 ID 为 "${id}" 的地面站实体失败。`);
}
}
/**
* 创建地面站点的 Cesium 实体对象。
* 这是一个内部辅助方法,封装了实体创建的细节。
*/
private _createStationEntity(
id: string,
name: string,
position: Cesium.Cartesian3,
pixelSize: number,
): Cesium.Entity {
return new Cesium.Entity({
id, // 使用传入的 id 作为实体的唯一标识符
name,
position,
@ -49,22 +68,9 @@ export class HCesiumStationManager {
pixelOffset: new Cesium.Cartesian2(0, -12), // 标签略微偏移到点的上方
},
});
const addedEntity = this.viewerManager.addEntity(groundStationEntity);
if (addedEntity) {
// 添加成功后,将其存入 Map
this.currentStationEntities.set(id, addedEntity);
return addedEntity;
} else {
console.error(`通过 ViewerManager 添加 ID 为 "${id}" 的地面站实体失败。`);
return null;
}
}
/**
* 从视图中移除指定的地面站实体 (通过 ID)。
* @param entityId - 要移除的地面站实体的 ID。
* @returns 如果成功移除则返回 true否则返回 false。
*/
removeStation(entityId: string): boolean {
const entityToRemove = this.currentStationEntities.get(entityId);

View File

@ -1,5 +1,3 @@
// src/components/h-cesium-viewer/useHCesiumViewerClsSatellite.ts
import type { MaybeRefOrGetter } from 'vue';
import type { HCesiumManager } from './managers/HCesiumManager';

View File

@ -15,8 +15,7 @@ export function useHCesiumManagerStation(
groundStationList: MaybeRefOrGetter<Array<I站点> | undefined>,
selectedStationIds: MaybeRefOrGetter<Set<string> | undefined>,
) {
// GroundStationManager 实例引用
const groundStationManager = ref<HCesiumStationManager | null>(null);
const stationManager = ref<HCesiumStationManager | null>(null);
// 创建一个从 ID 到站点选项的映射,方便查找
const stationMap = computed(() => {
@ -37,17 +36,16 @@ export function useHCesiumManagerStation(
// 检查 Viewer Manager 和内部 Viewer 实例是否存在
if (!viewerManagerInstance || !viewerManagerInstance.getViewer()) {
// 如果 viewer manager 或 viewer 实例尚未初始化或已销毁,则清理旧 manager 并返回
groundStationManager.value?.destroy();
groundStationManager.value = null;
stationManager.value?.destroy();
stationManager.value = null;
return;
}
// 确保 GroundStationManager 实例存在且与当前的 ViewerManager 关联
if (!groundStationManager.value) {
groundStationManager.value = new HCesiumStationManager(viewerManagerInstance);
if (!stationManager.value) {
stationManager.value = new HCesiumStationManager(viewerManagerInstance);
}
const manager = groundStationManager.value; // 使用 manager 实例
const manager = stationManager.value; // 使用 manager 实例
const selectedIdsSet = toValue(selectedStationIds) ?? new Set<string>(); // 直接获取 Set如果为 undefined 则创建空 Set
const currentEntityIds = new Set(manager.getCurrentStationEntities().keys()); // 从 manager 获取当前实体 ID
@ -77,8 +75,8 @@ export function useHCesiumManagerStation(
// 组件卸载时确保最终清理
onBeforeUnmount(() => {
groundStationManager.value?.destroy();
groundStationManager.value = null; // 明确置空
stationManager.value?.destroy();
stationManager.value = null; // 明确置空
});
// 返回 stationMap 可能在某些场景下有用,例如调试或扩展

View File

@ -4,14 +4,17 @@ meta:
</route>
<script setup lang="ts">
import type { HCesiumManagerSatelliteState, HCesiumManagerStationState } from '@/components/h-cesium-viewer/useHCesiumManager.types';
import type {
HCesiumManagerSatelliteState,
HCesiumManagerStationState,
} from '@/components/h-cesium-viewer/useHCesiumManager.types';
// 地面站和选中状态
const groundStationState = reactive<HCesiumManagerStationState>({
const stationState = reactive<HCesiumManagerStationState>({
stations: [],
selectedIds: new Set<string>(),
});
groundStationState.stations = [
stationState.stations = [
{ height: 50, id: 'gs-bj', latitude: 39.9042, longitude: 116.4074, name: '北京站' },
{ height: 10, id: 'gs-sh', latitude: 31.2304, longitude: 121.4737, name: '上海站' },
{ height: 20, id: 'gs-gz', latitude: 23.1291, longitude: 113.2644, name: '广州站' },
@ -27,19 +30,31 @@ const satelliteState = reactive<HCesiumManagerSatelliteState>({
satelliteState.satellites = [
{
id: 'STARLINK-11371',
tle: `STARLINK-11371
tle: `示例-仅卫星
1 62879U 25024A 25062.93300820 .00003305 00000+0 21841-4 0 9995
2 62879 42.9977 257.3937 0001725 269.2925 90.7748 15.77864921 5143`,
showOrbit: true, // 明确显示轨道
showOrbit: false,
showCoverage: false,
showPath: false,
},
{
id: 'ISS (ZARYA)',
tle: `国际空间站
tle: `显示-path
1 25544U 98067A 25091.51178241 .00016717 00000+0 30771-3 0 9997
2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391587775`,
showOrbit: true,
showOrbit: false,
showCoverage: true,
showPath: true,
},
{
id: 'AATLAS CENTAUR 2',
tle: `显示-轨道
1 00694U 63047A 25092.72647061 .00002208 00000+0 26071-3 0 9990
2 00694 30.3579 298.5470 0554905 319.4291 36.6190 14.10324656 83424`,
showOrbit: true,
showCoverage: false,
showPath: false,
},
// 可以添加更多卫星...
];
// 计算卫星 Checkbox Group 的 options
@ -63,7 +78,7 @@ const selectedSatelliteIdsArray = computed({
// 计算 Checkbox Group 的 options
const stationCheckboxOptions = computed(() =>
groundStationState.stations.map((station) => ({ label: station.name, value: station.id })),
stationState.stations.map((station) => ({ label: station.name, value: station.id })),
);
// 添加一个随机站点
@ -72,7 +87,7 @@ const addRandomStation = () => {
const randomLon = Math.random() * 360 - 180; // -180 to 180
const randomLat = Math.random() * 180 - 90; // -90 to 90
const randomHeight = Math.random() * 1000; // 0 to 1000 meters
groundStationState.stations.push({
stationState.stations.push({
height: randomHeight,
id: randomId,
latitude: randomLat,
@ -80,37 +95,37 @@ const addRandomStation = () => {
name: `随机站 ${randomId.slice(-4)}`,
});
// 创建新的 Set 以触发响应式更新
groundStationState.selectedIds = new Set([randomId, ...groundStationState.selectedIds]); // ESLint: 调整顺序
consola.info('添加随机站点:', groundStationState.stations.at(-1)); // 使用 .at() 访问最后一个元素
stationState.selectedIds = new Set([randomId, ...stationState.selectedIds]); // ESLint: 调整顺序
consola.info('添加随机站点:', stationState.stations.at(-1)); // 使用 .at() 访问最后一个元素
};
// 移除最后一个站点
const removeLastStation = () => {
if (groundStationState.stations.length > 0) {
const removedStation = groundStationState.stations.pop();
if (stationState.stations.length > 0) {
const removedStation = stationState.stations.pop();
if (removedStation) {
consola.info('移除站点:', removedStation);
// 同时从选中项中移除
// 创建新的 Set 以触发响应式更新
const newSelectedIds = new Set(groundStationState.selectedIds);
const newSelectedIds = new Set(stationState.selectedIds);
newSelectedIds.delete(removedStation.id);
groundStationState.selectedIds = newSelectedIds;
stationState.selectedIds = newSelectedIds;
}
}
};
// 清空所有选中项
const clearAllStations = () => {
groundStationState.stations = [];
groundStationState.selectedIds = new Set(); // 创建新的空 Set 以触发响应式更新
stationState.stations = [];
stationState.selectedIds = new Set(); // 创建新的空 Set 以触发响应式更新
consola.info('清空所有站点');
};
// 为 a-checkbox-group 创建计算属性,处理 Set 和 Array 的转换
const selectedStationIdsArray = computed({
get: () => [...groundStationState.selectedIds], // 从 Set 转换为 Array
get: () => [...stationState.selectedIds], // 从 Set 转换为 Array
set: (val: string[]) => {
groundStationState.selectedIds = new Set(val); // 从 Array 转换回 Set
stationState.selectedIds = new Set(val); // 从 Array 转换回 Set
},
});
</script>
@ -122,21 +137,17 @@ const selectedStationIdsArray = computed({
<a-card title="地面站控制" size="small">
<div class="space-x-2">
<a-button size="small" type="primary" @click="addRandomStation">添加随机站点</a-button>
<a-button size="small" @click="removeLastStation" :disabled="groundStationState.stations.length === 0"
<a-button size="small" @click="removeLastStation" :disabled="stationState.stations.length === 0"
>移除最后一个</a-button
>
<a-button
size="small"
danger
@click="clearAllStations"
:disabled="groundStationState.stations.length === 0"
<a-button size="small" danger @click="clearAllStations" :disabled="stationState.stations.length === 0"
>清空所有</a-button
>
<span>当前站点数: {{ groundStationState.stations.length }}</span>
<span> | 选中站点数: {{ groundStationState.selectedIds.size }}</span>
<span>当前站点数: {{ stationState.stations.length }}</span>
<span> | 选中站点数: {{ stationState.selectedIds.size }}</span>
</div>
<!-- 站点选择 -->
<div mt-2 v-if="groundStationState.stations.length > 0">
<div mt-2 v-if="stationState.stations.length > 0">
<span class="mr-2">选择要显示的站点:</span>
<a-checkbox-group v-model:value="selectedStationIdsArray" :options="stationCheckboxOptions" />
</div>
@ -144,17 +155,22 @@ const selectedStationIdsArray = computed({
<!-- 卫星控制 -->
<a-card title="卫星控制" size="small">
<span>当前卫星数: {{ satelliteState.satellites.length }}</span>
<span> | 选中卫星数: {{ satelliteState.selectedIds.size }}</span>
<div v-if="satelliteState.satellites.length > 0" class="mt-2">
<span class="mr-2">选择要显示的卫星:</span>
<div class="flex items-center justify-between">
<div>
<span>当前卫星数: {{ satelliteState.satellites.length }}</span>
<span class="ml-2"> | 选中卫星: {{ satelliteState.selectedIds.size }}</span>
</div>
<!-- 可以添加其他全局卫星控制例如全部显示/隐藏轨道/覆盖 -->
</div>
<div v-if="satelliteState.satellites.length > 0" class="mt-2 space-y-2">
<span class="mr-2 font-medium">选择要显示的卫星:</span>
<a-checkbox-group v-model:value="selectedSatelliteIdsArray" :options="satelliteCheckboxOptions" />
</div>
</a-card>
</div>
<div class="flex-grow w-full rounded-lg border overflow-hidden">
<!-- 将地面站和卫星状态都传递给组件 -->
<h-cesium-viewer :ground-station-state :satellite-state>
<h-cesium-viewer :station-state="stationState" :satellite-state="satelliteState">
<div class="absolute top-0 left-0 z-10 p-2 bg-black/30 rounded-br-lg">
<span class="text-white text-xs">叠加 UI 示例</span>
</div>