From 982ceffb73540eefa899855d46b91bef01c67cec Mon Sep 17 00:00:00 2001 From: Tian jianyong <11429339@qq.com> Date: Mon, 26 May 2025 18:47:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E5=AF=BC=E5=BC=B9?= =?UTF-8?q?=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E7=9A=84=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E5=92=8C=E5=88=B6=E5=AF=BC=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=EF=BC=8C=E5=AE=8C=E5=96=84=E4=BA=86=E9=9B=86=E6=88=90=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=9A=84=E8=8F=9C=E5=8D=95=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E5=B9=B2=E6=89=B0=E5=99=A8=E6=AD=A3=E5=B8=B8=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 9 + ...MillimeterWaveGuidanceSnrAveragingTests.cs | 24 +- .../src/Sensor/QuadrantDetectorTests.cs | 2 +- ThreatSource/src/MIssile/BaseMissile.cs | 126 +- ThreatSource/src/MIssile/IMissile.cs | 10 - .../src/Simulation/SimulationEvents.cs | 121 ++ VERSION | 2 +- docs/project/cpp_compatibility_analysis.md | 323 ++++ docs/project/dll_implementation_analysis.md | 701 ++++++++ docs/project/dll_integration_guide.md | 1503 +++++++++++++++++ docs/project/simulation_events_checklist.md | 289 ++++ tools/ComprehensiveMissileSimulator.cs | 29 +- tools/Program.cs | 28 +- 13 files changed, 3132 insertions(+), 35 deletions(-) create mode 100644 docs/project/cpp_compatibility_analysis.md create mode 100644 docs/project/dll_implementation_analysis.md create mode 100644 docs/project/dll_integration_guide.md create mode 100644 docs/project/simulation_events_checklist.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 808571f..a9b85da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ - 实现实时仿真数据同步 - 处理不同时间步长的协调 - 命中概率和系统随机噪声 +- dll 库的接口有效性验证 +- 所有威胁源的参数规范化,增加默认参数配置 +- 同步 dll 库的文档,api 文档、使用说明、工作原理 +- 规范第三方仿真环境使用 dll 库的场景和事件类型 + +## [1.1.22] - 2025-05-26 +- 完善了集成测试的菜单逻辑,干扰器正常工作了 +- 增加了导弹生命周期的状态事件和制导事件 ## [1.1.21] - 2025-05-24 - 增加了升力加速度的计算 @@ -20,6 +28,7 @@ - 将毫米波制导的扫描阶段改为螺旋扫描,并调整了参数 - 完善了集成测试的菜单逻辑,可以反复运行了 - 给导弹增加了巡航攻角、制导下视角参数,完善了三个阶段的朝向逻辑 +- 增加了激光/红外复合制导导弹 ## [1.1.20] - 2025-05-19 - 增加了SwerlingRCS回波模型 diff --git a/ThreatSource.Tests/src/Guidance/MillimeterWaveGuidanceSnrAveragingTests.cs b/ThreatSource.Tests/src/Guidance/MillimeterWaveGuidanceSnrAveragingTests.cs index 4fc8640..51e9617 100644 --- a/ThreatSource.Tests/src/Guidance/MillimeterWaveGuidanceSnrAveragingTests.cs +++ b/ThreatSource.Tests/src/Guidance/MillimeterWaveGuidanceSnrAveragingTests.cs @@ -61,7 +61,7 @@ namespace ThreatSource.Tests.Guidance var initialKState = new KinematicState { - Position = new Vector3D(1000, 0, 0), // 1000米距离 + Position = new Vector3D(300, 0, 0), // 300米距离 Velocity = new Vector3D(0, 0, 0), Orientation = new Orientation(0, 0, 0), Speed = 0 @@ -73,6 +73,12 @@ namespace ThreatSource.Tests.Guidance target.Activate(); guidanceSystem.Activate(); + // 直接设置制导系统的运动状态,模拟导弹的位置和前进方向 + guidanceSystem.KState.Position = new Vector3D(0, 0, 0); // 制导系统位置在原点 + guidanceSystem.KState.Velocity = new Vector3D(100, 0, 0); // 向X轴正方向前进 + guidanceSystem.KState.Orientation = new Orientation(0, 0, 0); // 朝向X轴正方向 + guidanceSystem.KState.Speed = 100; // 前进速度100m/s + // 注册到仿真管理器 simulationManager.RegisterEntity("test_tank", target); } @@ -93,9 +99,11 @@ namespace ThreatSource.Tests.Guidance // 模拟从Search -> Track -> Lock的过程 // 1. 首先进入Track模式(模拟已经找到目标) - guidanceSystem.GetType() - .GetMethod("SwitchToTrackMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) - ?.Invoke(guidanceSystem, null); + Assert.IsNotNull(guidanceSystem, "Guidance system should be initialized"); + var switchToTrackMethod = guidanceSystem.GetType() + .GetMethod("SwitchToTrackMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + Assert.IsNotNull(switchToTrackMethod, "SwitchToTrackMode method should exist"); + switchToTrackMethod.Invoke(guidanceSystem, null); // 2. 更新几次以稳定Track模式 for (int i = 0; i < 10; i++) @@ -104,9 +112,10 @@ namespace ThreatSource.Tests.Guidance } // 3. 切换到Lock模式 - guidanceSystem.GetType() - .GetMethod("SwitchToLockMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) - ?.Invoke(guidanceSystem, null); + var switchToLockMethod = guidanceSystem.GetType() + .GetMethod("SwitchToLockMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + Assert.IsNotNull(switchToLockMethod, "SwitchToLockMode method should exist"); + switchToLockMethod.Invoke(guidanceSystem, null); // 4. 验证Lock模式下的SNR平均化 int lockSuccessCount = 0; @@ -141,6 +150,7 @@ namespace ThreatSource.Tests.Guidance public void TestNewSnrThreshold_IsApplied() { // 验证新的SNR阈值已经应用 + Assert.IsNotNull(guidanceSystem, "Guidance system should be initialized"); var config = guidanceSystem.GetType() .GetField("config", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) ?.GetValue(guidanceSystem) as MillimeterWaveGuidanceConfig; diff --git a/ThreatSource.Tests/src/Sensor/QuadrantDetectorTests.cs b/ThreatSource.Tests/src/Sensor/QuadrantDetectorTests.cs index 26d8536..5959c97 100644 --- a/ThreatSource.Tests/src/Sensor/QuadrantDetectorTests.cs +++ b/ThreatSource.Tests/src/Sensor/QuadrantDetectorTests.cs @@ -194,7 +194,7 @@ namespace ThreatSource.Tests.Sensor // Assert Assert.Contains($"锁定=True", status); - Assert.Contains($"总功率={receivedPower:E}", status); + Assert.Contains($"总功率={receivedPower:E2}", status); Assert.Contains("水平误差=", status); Assert.Contains("垂直误差=", status); Assert.Contains("象限信号=", status); diff --git a/ThreatSource/src/MIssile/BaseMissile.cs b/ThreatSource/src/MIssile/BaseMissile.cs index 717ba0c..233b36d 100644 --- a/ThreatSource/src/MIssile/BaseMissile.cs +++ b/ThreatSource/src/MIssile/BaseMissile.cs @@ -61,14 +61,14 @@ namespace ThreatSource.Missile public bool IsGuidance { get; protected set; } /// - /// 获取或设置导弹失去制导的持续时间 + /// 获取或设置前一个制导状态 /// - /// 失去制导的时间,单位:秒 + /// 上一个时间步的制导状态 /// - /// 用于判断是否需要触发自毁 - /// 超过阈值时可能导致导弹自毁 + /// 用于检测制导状态变化 + /// 当IsGuidance与此值不同时,表示制导状态发生了变化 /// - protected double LostGuidanceTime { get; set; } = 0; + protected bool PreviousIsGuidance { get; set; } = false; /// /// 获取或设置导弹的最后已知速度向量 @@ -238,6 +238,9 @@ namespace ThreatSource.Missile { SelfDestruct(); } + + // 检测制导状态变化并发布相应事件 + CheckGuidanceStatusChange(); } /// @@ -489,6 +492,16 @@ namespace ThreatSource.Missile /// protected virtual void OnExplode() { + // 发布导弹爆炸事件 + var explodeEvent = new MissileExplodeEvent + { + SenderId = Id, + Position = KState.Position, + ExplosionRadius = Properties.ExplosionRadius, + TargetId = null // 这里可以根据需要设置目标ID,通常在子类中重写 + }; + SimulationManager.PublishEvent(explodeEvent); + // 子类可以重写此方法来处理爆炸时的特殊逻辑 } @@ -527,6 +540,16 @@ namespace ThreatSource.Missile } Trace.TraceInformation($"导弹 {Id} 自毁。原因: {reason}"); + + // 发布导弹自毁事件 + var selfDestructEvent = new MissileSelfDestructEvent + { + SenderId = Id, + Reason = reason, + Position = KState.Position + }; + SimulationManager.PublishEvent(selfDestructEvent); + OnSelfDestruct(); Deactivate(); } @@ -619,10 +642,101 @@ namespace ThreatSource.Missile statusInfo.ExtendedProperties["EngineBurnTime"] = EngineBurnTime; statusInfo.ExtendedProperties["CurrentStage"] = currentStage.ToString(); statusInfo.ExtendedProperties["IsGuidance"] = IsGuidance; - statusInfo.ExtendedProperties["LostGuidanceTime"] = LostGuidanceTime; statusInfo.ExtendedProperties["GuidanceAcceleration"] = GuidanceAcceleration; return statusInfo; } + + /// + /// 检测制导状态变化并发布相应事件 + /// + /// + /// 检测过程: + /// - 比较当前制导状态与前一个状态 + /// - 如果状态发生变化,发布相应的制导获得或失去事件 + /// - 更新前一个状态记录 + /// + protected virtual void CheckGuidanceStatusChange() + { + if (IsGuidance != PreviousIsGuidance) + { + if (IsGuidance) + { + // 获得制导 + var guidanceAcquiredEvent = new MissileGuidanceAcquiredEvent + { + SenderId = Id, + GuidanceType = GetCurrentGuidanceType(), + GuidanceSystemId = GetCurrentGuidanceSystemId() + }; + SimulationManager.PublishEvent(guidanceAcquiredEvent); + + Trace.TraceInformation($"导弹 {Id} 获得制导"); + } + else + { + // 失去制导 + var guidanceLostEvent = new MissileGuidanceLostEvent + { + SenderId = Id, + Reason = GetGuidanceLostReason(), + GuidanceType = GetCurrentGuidanceType(), + }; + SimulationManager.PublishEvent(guidanceLostEvent); + + Trace.TraceInformation($"导弹 {Id} 失去制导,原因: {guidanceLostEvent.Reason}"); + } + + // 更新前一个状态 + PreviousIsGuidance = IsGuidance; + } + } + + /// + /// 获取当前制导类型描述 + /// + /// 制导类型字符串 + /// + /// 子类可以重写此方法以提供更具体的制导类型信息 + /// 基类默认根据导弹类型返回通用描述 + /// + protected virtual string GetCurrentGuidanceType() + { + return Properties.Type switch + { + MissileType.LaserSemiActiveGuidance => "激光半主动制导", + MissileType.LaserBeamRiderGuidance => "激光驾束制导", + MissileType.InfraredImagingTerminalGuidance => "红外成像制导", + MissileType.InfraredCommandGuidance => "红外指令制导", + MissileType.MillimeterWaveTerminalGuidance => "毫米波制导", + MissileType.CompositeGuidance => "复合制导", + _ => "未知制导类型" + }; + } + + /// + /// 获取当前制导系统ID + /// + /// 制导系统ID,基类返回null + /// + /// 子类可以重写此方法以提供具体的制导系统ID + /// + protected virtual string? GetCurrentGuidanceSystemId() + { + return null; + } + + /// + /// 获取失去制导的原因 + /// + /// 失去制导的原因描述 + /// + /// 子类可以重写此方法以提供更具体的失去制导原因 + /// 基类默认返回通用描述 + /// + protected virtual string GetGuidanceLostReason() + { + return "制导系统失效或信号中断"; + } } } diff --git a/ThreatSource/src/MIssile/IMissile.cs b/ThreatSource/src/MIssile/IMissile.cs index e256882..214f0a7 100644 --- a/ThreatSource/src/MIssile/IMissile.cs +++ b/ThreatSource/src/MIssile/IMissile.cs @@ -111,16 +111,6 @@ namespace ThreatSource.Missile /// public bool IsGuidance { get; set; } - /// - /// 获取或设置导弹失去制导的持续时间 - /// - /// - /// 单位:秒 - /// 记录导弹处于非制导状态的累计时间 - /// 用于判断是否需要触发自毁 - /// - public double LostGuidanceTime { get; set; } - /// /// 获取或设置发动机的当前燃烧时间 /// diff --git a/ThreatSource/src/Simulation/SimulationEvents.cs b/ThreatSource/src/Simulation/SimulationEvents.cs index e000eae..3a7be89 100644 --- a/ThreatSource/src/Simulation/SimulationEvents.cs +++ b/ThreatSource/src/Simulation/SimulationEvents.cs @@ -487,6 +487,127 @@ namespace ThreatSource.Simulation public LaserCodeConfig? ReceivedCodeConfig { get; set; } } + /// + /// 导弹自毁事件,表示导弹执行自毁程序 + /// + /// + /// 用于通知系统导弹已执行自毁 + /// 触发时机:导弹调用SelfDestruct()方法时 + /// + public class MissileSelfDestructEvent : SimulationEvent + { + /// + /// 获取或设置自毁原因 + /// + /// + /// 描述导致导弹自毁的具体原因 + /// 如:超出最大飞行时间、超出最大飞行距离、失去制导等 + /// + public string? Reason { get; set; } + + /// + /// 获取或设置自毁时的位置 + /// + /// + /// 导弹执行自毁时的三维位置坐标 + /// 用于记录自毁发生的位置 + /// + public Vector3D Position { get; set; } = Vector3D.Zero; + } + + /// + /// 导弹爆炸事件,表示导弹发生爆炸 + /// + /// + /// 用于通知系统导弹已爆炸 + /// 触发时机:导弹调用Explode()方法时,通常在命中目标后 + /// + public class MissileExplodeEvent : SimulationEvent + { + /// + /// 获取或设置爆炸位置 + /// + /// + /// 导弹爆炸时的三维位置坐标 + /// 用于计算爆炸伤害范围和效果 + /// + public Vector3D Position { get; set; } = Vector3D.Zero; + + /// + /// 获取或设置爆炸半径 + /// + /// + /// 爆炸效果的有效作用范围,单位:米 + /// 用于计算对周围目标的伤害 + /// + public double ExplosionRadius { get; set; } + + /// + /// 获取或设置目标ID(如果有) + /// + /// + /// 如果是命中目标后爆炸,记录目标的ID + /// 可以为null,表示非命中目标的爆炸 + /// + public string? TargetId { get; set; } + } + + /// + /// 导弹获得制导事件,表示导弹制导系统获得有效制导信号 + /// + /// + /// 用于通知系统导弹已获得制导能力 + /// 触发时机:导弹IsGuidance状态从false变为true时 + /// + public class MissileGuidanceAcquiredEvent : SimulationEvent + { + /// + /// 获取或设置制导类型 + /// + /// + /// 标识获得的制导方式类型 + /// 如:激光制导、红外制导、毫米波制导等 + /// + public string? GuidanceType { get; set; } + + /// + /// 获取或设置制导系统ID + /// + /// + /// 提供制导信号的制导系统标识 + /// 可以为null,表示未知或内置制导系统 + /// + public string? GuidanceSystemId { get; set; } + } + + /// + /// 导弹失去制导事件,表示导弹制导系统失去制导信号 + /// + /// + /// 用于通知系统导弹已失去制导能力 + /// 触发时机:导弹IsGuidance状态从true变为false时 + /// + public class MissileGuidanceLostEvent : SimulationEvent + { + /// + /// 获取或设置失去制导的原因 + /// + /// + /// 描述导致失去制导的具体原因 + /// 如:干扰、信号丢失、制导系统故障等 + /// + public string? Reason { get; set; } + + /// + /// 获取或设置制导类型 + /// + /// + /// 标识失去的制导方式类型 + /// 如:激光制导、红外制导、毫米波制导等 + /// + public string? GuidanceType { get; set; } + } + // --- General Jamming Events --- /// diff --git a/VERSION b/VERSION index a2a8e42..2ac1f8d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.21 \ No newline at end of file +1.1.22 \ No newline at end of file diff --git a/docs/project/cpp_compatibility_analysis.md b/docs/project/cpp_compatibility_analysis.md new file mode 100644 index 0000000..d993227 --- /dev/null +++ b/docs/project/cpp_compatibility_analysis.md @@ -0,0 +1,323 @@ +# 威胁源仿真库C++兼容性分析 + +## 文档概述 + +本文档分析威胁源仿真库当前DLL的C++兼容性问题,并提供详细的解决方案和实施建议。 + +**版本**: 1.0 +**创建日期**: 2024年12月 +**问题等级**: 🔴 高优先级架构问题 + +--- + +## 1. 问题分析 + +### 1.1 🔴 核心问题:当前DLL不是真正的原生C++ DLL + +#### 问题表现 +```cpp +// 当前实现使用C++/CLI,不是原生C++ +#include // ❌ 需要.NET CLR支持 +#include // ❌ 需要托管运行时 +using namespace System; // ❌ .NET命名空间 +``` + +#### 项目配置问题 +```xml + +true // ❌ 生成托管DLL,不是原生DLL +``` + +#### 运行时依赖 +- ✅ C#/.NET程序:可以直接调用 +- ❌ 纯C++程序:需要.NET运行时,实际上是托管调用 +- ❌ C程序:无法直接调用 +- ❌ 其他语言:兼容性有限 + +### 1.2 具体技术问题 + +#### 1.2.1 DLL类型错误识别 +```cpp +// 开发者可能认为这是原生DLL,实际是托管DLL +THREATSOURCE_API int TS_CreateMissile(...) { + // 内部使用托管对象 + auto missile = gcnew TerminalSensitiveMissile(...); // ❌ 这是托管代码 +} +``` + +#### 1.2.2 部署复杂性 +当前部署需要: +- ✅ ThreatSourceNative.dll +- ✅ ThreatSource.dll +- ✅ ThreatSource.deps.json +- ❌ **缺失**: .NET 8.0运行时安装要求的明确说明 +- ❌ **缺失**: 运行时配置文件 + +#### 1.2.3 跨平台限制 +- Windows:理论可行(需要.NET运行时) +- Linux:需要Mono或.NET Core,复杂 +- macOS:需要.NET运行时,兼容性问题 +- 嵌入式系统:几乎不可行 + +--- + +## 2. 解决方案对比 + +### 2.1 方案矩阵 + +| 方案 | 开发周期 | C++兼容性 | 性能 | 部署复杂度 | 维护成本 | +|------|---------|-----------|------|-----------|----------| +| **当前方案改进** | 2-3周 | ⚠️ 限制 | 中等 | 中等 | 低 | +| **原生C++重写** | 3-6个月 | ✅ 完美 | 高 | 低 | 高 | +| **进程间通信** | 1-2个月 | ✅ 完美 | 低 | 高 | 中等 | +| **混合架构** | 4-8个月 | ✅ 完美 | 高 | 中等 | 高 | + +### 2.2 详细方案分析 + +#### 方案A:当前架构优化(短期解决) + +**实施策略**: +```cpp +// 1. 改进C API设计 +extern "C" { + // 添加初始化函数,明确.NET依赖 + THREATSOURCE_API int TS_InitializeWithDotNet(const char* runtimePath); + THREATSOURCE_API int TS_CheckDotNetAvailability(); + + // 改进错误报告 + THREATSOURCE_API const char* TS_GetSystemRequirements(); +} +``` + +**部署改进**: +```bash +# 创建智能部署脚本 +check_dotnet_runtime.ps1 +deploy_with_runtime.bat +``` + +**文档改进**: +```markdown +## ⚠️ 重要声明 +当前DLL虽然提供C接口,但内部依赖.NET运行时。 +这意味着您的C++程序实际上在调用托管代码。 + +### 系统要求 +- Windows x64 (其他平台需要额外配置) +- .NET 8.0 Desktop Runtime +- 所有依赖DLL必须在同一目录 +``` + +#### 方案B:原生C++引擎(长期解决) + +**架构设计**: +```cpp +// 完全原生的C++实现 +namespace ThreatSource { +namespace Native { + +class IMissileGuidance { +public: + virtual ~IMissileGuidance() = default; + virtual void Update(double deltaTime) = 0; + virtual bool IsTargetAcquired() const = 0; +}; + +class IRImagingGuidance : public IMissileGuidance { +private: + // 原生C++算法实现 + std::vector targetSignature; + double searchRange; + double detectionThreshold; + +public: + void Update(double deltaTime) override; + bool IsTargetAcquired() const override; +}; + +class NativeMissile { +private: + std::unique_ptr guidance; + Vector3D position; + Vector3D velocity; + +public: + void Fire(); + void Update(double deltaTime); + bool IsActive() const; +}; + +}} +``` + +**核心库依赖**: +```cpp +// 高性能C++库选择 +#include // 线性代数 +#include // 可选:REST API +#include // 配置解析 +#include // 日志系统 +#include // JSON处理 +``` + +#### 方案C:混合架构(推荐) + +**设计思路**:同时维护两套实现 +```cpp +// 统一接口层 +extern "C" { + enum TS_BackendType { + TS_BACKEND_AUTO, // 自动选择 + TS_BACKEND_NATIVE, // 原生C++实现 + TS_BACKEND_DOTNET // .NET实现 + }; + + THREATSOURCE_API int TS_Initialize(TS_BackendType backend); + THREATSOURCE_API int TS_GetAvailableBackends(TS_BackendType* backends, int* count); +} +``` + +**实现策略**: +```cpp +// 后端适配器模式 +class ISimulationBackend { +public: + virtual int CreateMissile(const char* id, const MissileConfig& config) = 0; + virtual int UpdateSimulation(double deltaTime) = 0; + virtual ~ISimulationBackend() = default; +}; + +class NativeBackend : public ISimulationBackend { + // 原生C++实现 +}; + +class DotNetBackend : public ISimulationBackend { + // 当前C++/CLI实现 +}; +``` + +--- + +## 3. 立即行动计划 + +### 3.1 第一步:诚实的文档(本周完成) + +```markdown +# 重要说明:当前C++兼容性限制 + +## 当前状况 +- ✅ 提供C风格API接口 +- ❌ 但内部依赖.NET运行时 +- ❌ 不是真正的原生C++ DLL + +## 使用限制 +1. 目标系统必须安装.NET 8.0运行时 +2. 所有依赖DLL必须正确部署 +3. 跨平台支持有限 + +## 计划改进 +我们正在开发真正的原生C++ DLL,预计6个月内发布。 +``` + +### 3.2 第二步:改进当前实现(2-3周) + +```cpp +// 添加运行时检测 +THREATSOURCE_API int TS_CheckSystemCompatibility() { + try { + // 检测.NET运行时 + // 检测依赖库 + return TS_SUCCESS; + } catch (...) { + return TS_ERROR_RUNTIME_NOT_AVAILABLE; + } +} + +// 添加详细错误信息 +THREATSOURCE_API const char* TS_GetLastDetailedError() { + static std::string detailedError; + // 返回包含解决建议的详细错误信息 + return detailedError.c_str(); +} +``` + +### 3.3 第三步:原生引擎规划(长期) + +**里程碑计划**: +``` +月份1-2: 核心数学库和数据结构 +月份3-4: 制导算法移植 +月份5-6: 仿真控制和API层 +月份7-8: 测试和优化 +``` + +**技术栈选择**: +```cpp +// 建议的技术栈 +- 数学计算: Eigen3 +- 配置解析: toml++ +- 日志系统: spdlog +- 测试框架: Google Test +- 构建系统: CMake +- 包管理: vcpkg +``` + +--- + +## 4. 风险评估 + +### 4.1 当前方案风险 + +| 风险 | 概率 | 影响 | 缓解措施 | +|------|------|------|----------| +| C++用户期望原生DLL | 高 | 高 | 立即更新文档说明 | +| 部署失败 | 中 | 高 | 提供部署检测工具 | +| 性能不满足要求 | 中 | 中 | 性能基准测试 | +| 跨平台问题 | 高 | 中 | 明确平台支持范围 | + +### 4.2 原生重写风险 + +| 风险 | 概率 | 影响 | 缓解措施 | +|------|------|------|----------| +| 开发周期延长 | 中 | 高 | 分阶段交付 | +| 算法移植错误 | 中 | 高 | 全面测试对比 | +| 维护成本增加 | 高 | 中 | 自动化测试 | +| 功能不完整 | 低 | 中 | 渐进式移植 | + +--- + +## 5. 建议决策 + +### 5.1 立即执行(本周) +1. **更新所有文档**,明确当前DLL的.NET依赖 +2. **创建兼容性检测工具** +3. **提供详细的部署指南** + +### 5.2 短期计划(1个月内) +1. **改进当前C++/CLI实现**,增强错误处理 +2. **创建自动化部署脚本** +3. **建立性能基准测试** + +### 5.3 长期规划(6个月内) +1. **启动原生C++引擎项目** +2. **建立双重维护流程** +3. **逐步迁移用户到原生版本** + +### 5.4 推荐策略 +**混合方案**: +- 保持当前实现为"快速原型"版本 +- 并行开发原生版本作为"生产"版本 +- 提供统一的API接口层 +- 让用户根据需求选择后端 + +--- + +## 6. 结论 + +当前的"C++ DLL"实际上是托管DLL,这个问题需要诚实面对并积极解决。建议: + +1. **短期**:改进当前实现,明确说明限制 +2. **中期**:开发原生C++版本 +3. **长期**:提供混合架构,满足不同需求 + +这种分阶段方案既能解决当前问题,又能为未来建立强大的技术基础。 \ No newline at end of file diff --git a/docs/project/dll_implementation_analysis.md b/docs/project/dll_implementation_analysis.md new file mode 100644 index 0000000..66b3c43 --- /dev/null +++ b/docs/project/dll_implementation_analysis.md @@ -0,0 +1,701 @@ +# 威胁源仿真库DLL对接方案实现状况分析 + +## 文档概述 + +本文档详细分析了威胁源仿真库DLL对接方案的当前实现状况,对比理想方案识别缺失功能和问题,并提供具体的改进建议和实施路线图。 + +**版本**: 1.0 +**创建日期**: 2024年12月 +**分析基准**: [DLL对接指南v1.0](dll_integration_guide.md) + +--- + +## 1. 实现状况总览 + +### 1.1 整体完成度评估 + +| 功能模块 | 建议方案 | 当前实现 | 完成度 | 优先级 | +|---------|---------|---------|--------|--------| +| 场景管理 | 完整API (10个接口) | 缺失 | **0%** | 🔴 高 | +| 实体管理 | 40+ API | 8个基础API | **20%** | 🔴 高 | +| 状态查询 | 15+ API | 0个 | **0%** | 🟡 中 | +| 事件系统 | 完整对接 (5个接口) | 缺失 | **0%** | 🔴 高 | +| 环境控制 | 天气系统 (2个接口) | 缺失 | **0%** | 🟢 低 | +| Unity集成 | 完整包 | 缺失 | **0%** | 🟡 中 | +| 配置管理 | 完整API (3个接口) | 缺失 | **0%** | 🟡 中 | +| 错误处理 | 详细错误码 | 基础实现 | **30%** | 🟢 低 | + +**总体完成度:约15%** + +### 1.2 当前架构状况 + +``` +当前实现架构: +外部系统 + ↕ (P/Invoke) +ThreatSourceNative.dll (C++/CLI) + ↕ (直接调用) +ThreatSource.dll (.NET核心库) + +问题: +❌ 单例设计,无法支持多场景 +❌ 硬编码实体类型 +❌ 缺乏标准化数据结构 +❌ 事件系统未对接 +``` + +--- + +## 2. 已实现功能分析 + +### 2.1 ✅ 基础C++/CLI包装层 + +**文件位置**: `ThreatSourceNative/` + +**已实现接口**: +```c +// 仿真管理 (2/10) +THREATSOURCE_API int TS_CreateSimulation(); +THREATSOURCE_API int TS_DestroySimulation(); + +// 导弹管理 (4/15) +THREATSOURCE_API int TS_CreateMissile(...); +THREATSOURCE_API int TS_ActivateMissile(const char* id); +THREATSOURCE_API int TS_DeactivateMissile(const char* id); +THREATSOURCE_API int TS_FireMissile(const char* id); + +// 目标管理 (1/10) +THREATSOURCE_API int TS_CreateTarget(...); + +// 仿真控制 (1/5) +THREATSOURCE_API int TS_UpdateSimulation(double deltaTime); + +// 错误处理 (1/3) +THREATSOURCE_API int TS_GetLastError(char* buffer, int buffer_size); +``` + +**优点**: +- 基本的C++/CLI互操作已建立 +- 错误处理机制存在 +- 能够创建和控制基础实体 + +**问题**: +- API设计不符合建议方案 +- 缺乏场景管理概念 +- 数据结构不标准化 + +### 2.2 ✅ .NET核心库完备性 + +**文件位置**: `ThreatSource/src/` + +**已实现功能**: +- ✅ 完整的仿真管理器 (`SimulationManager`) +- ✅ 多种导弹类型和制导系统 +- ✅ 目标、指示器、干扰器实体 +- ✅ 事件发布/订阅系统 +- ✅ 配置文件支持 (TOML) +- ✅ 大气传输模型集成 + +**核心优势**: +- 仿真核心功能完整且稳定 +- 支持复杂的制导和干扰场景 +- 事件系统设计良好 + +--- + +## 3. 缺失功能详细清单 + +### 3.1 🔴 高优先级缺失 (阻塞性问题) + +#### 3.1.1 场景管理系统 (0% 完成) + +**缺失接口**: +```c +// 完全缺失的场景管理API +THREATSOURCE_API int TS_Initialize(); +THREATSOURCE_API int TS_Shutdown(); +THREATSOURCE_API int TS_CreateScenario(const char* scenarioId); +THREATSOURCE_API int TS_DestroyScenario(const char* scenarioId); +THREATSOURCE_API int TS_StartSimulation(const char* scenarioId, double timeStep); +THREATSOURCE_API int TS_PauseSimulation(const char* scenarioId); +THREATSOURCE_API int TS_ResumeSimulation(const char* scenarioId); +THREATSOURCE_API int TS_StopSimulation(const char* scenarioId); +THREATSOURCE_API int TS_GetSimulationState(const char* scenarioId, int* state); +THREATSOURCE_API int TS_GetSimulationTime(const char* scenarioId, double* time); +``` + +**影响**: 无法支持多个独立仿真实例,限制了系统的可扩展性。 + +#### 3.1.2 标准化数据结构 (0% 完成) + +**缺失结构体**: +```c +// 完全缺失的核心数据结构 +typedef struct { + double x, y, z; +} TS_Vector3D; + +typedef struct { + double yaw, pitch, roll; +} TS_Orientation; + +typedef struct { + TS_Vector3D position; + TS_Vector3D velocity; + TS_Orientation orientation; +} TS_KinematicState; + +typedef struct { + int type; + double temperature; + double humidity; + double visibility; + double precipitation; + double windSpeed; + double windDirection; +} TS_Weather; + +typedef struct { + char senderId[64]; + char targetId[64]; + double timestamp; + int eventType; + char data[256]; +} TS_Event; +``` + +**影响**: 数据交换不标准化,难以与外部系统集成。 + +#### 3.1.3 事件系统对接 (0% 完成) + +**缺失接口**: +```c +// 事件系统完全未对接 +typedef void (*TS_EventCallback)(const TS_Event* event); +THREATSOURCE_API int TS_RegisterEventCallback(const char* scenarioId, int eventType, TS_EventCallback callback); +THREATSOURCE_API int TS_UnregisterEventCallback(const char* scenarioId, int eventType); +THREATSOURCE_API int TS_PollEvents(const char* scenarioId, TS_Event* events, int maxEvents, int* actualEvents); +THREATSOURCE_API int TS_SendExternalEvent(const char* scenarioId, const TS_Event* event); +``` + +**影响**: 无法与外部系统进行实时事件交互,严重限制集成能力。 + +### 3.2 🟡 中优先级缺失 + +#### 3.2.1 完整实体管理 (20% 完成) + +**缺失接口**: +```c +// 指示器管理 - 完全缺失 +THREATSOURCE_API int TS_CreateIndicator(const char* scenarioId, const char* indicatorId, + int indicatorType, const char* configPath, + const TS_KinematicState* initialState); +THREATSOURCE_API int TS_SetIndicatorTarget(const char* scenarioId, const char* indicatorId, const char* targetId); + +// 干扰器管理 - 完全缺失 +THREATSOURCE_API int TS_CreateJammer(const char* scenarioId, const char* jammerId, + int jammerType, const char* configPath, + const TS_KinematicState* initialState); +THREATSOURCE_API int TS_StartJammer(const char* scenarioId, const char* jammerId); +THREATSOURCE_API int TS_StopJammer(const char* scenarioId, const char* jammerId); + +// 通用实体管理 - 完全缺失 +THREATSOURCE_API int TS_DestroyEntity(const char* scenarioId, const char* entityId); +THREATSOURCE_API int TS_ActivateEntity(const char* scenarioId, const char* entityId); +THREATSOURCE_API int TS_DeactivateEntity(const char* scenarioId, const char* entityId); +``` + +#### 3.2.2 状态查询系统 (0% 完成) + +**缺失接口**: +```c +// 状态查询完全缺失 +THREATSOURCE_API int TS_GetEntityState(const char* scenarioId, const char* entityId, TS_KinematicState* state); +THREATSOURCE_API int TS_IsEntityActive(const char* scenarioId, const char* entityId, int* isActive); +THREATSOURCE_API int TS_GetMissileGuidanceState(const char* scenarioId, const char* missileId, int* isGuided); +THREATSOURCE_API int TS_GetMissileFlightStage(const char* scenarioId, const char* missileId, int* stage); +THREATSOURCE_API int TS_GetTargetHealth(const char* scenarioId, const char* targetId, double* health); +``` + +#### 3.2.3 Unity集成包 (0% 完成) + +**缺失组件**: +``` +ThreatSourceUnity/ - 完全缺失 +├── Runtime/ +│ ├── Scripts/ +│ │ ├── Core/ +│ │ │ ├── ThreatSourceManager.cs +│ │ │ ├── SimulationScenario.cs +│ │ │ └── EntityManager.cs +│ │ ├── Entities/ +│ │ │ ├── MissileController.cs +│ │ │ ├── TargetController.cs +│ │ │ ├── IndicatorController.cs +│ │ │ └── JammerController.cs +│ │ └── Utils/ +│ │ ├── NativeInterop.cs +│ │ └── ConfigLoader.cs +│ └── Prefabs/ +└── Editor/ +``` + +### 3.3 🟢 低优先级缺失 + +#### 3.3.1 环境控制 (0% 完成) + +**缺失接口**: +```c +THREATSOURCE_API int TS_SetWeather(const char* scenarioId, const TS_Weather* weather); +THREATSOURCE_API int TS_GetWeather(const char* scenarioId, TS_Weather* weather); +``` + +#### 3.3.2 配置管理 (0% 完成) + +**缺失接口**: +```c +THREATSOURCE_API int TS_LoadConfig(const char* configPath, char* configData, int bufferSize); +THREATSOURCE_API int TS_ValidateConfig(const char* configPath, int* isValid); +THREATSOURCE_API int TS_GetDefaultConfig(int entityType, char* configData, int bufferSize); +``` + +#### 3.3.3 性能优化接口 (0% 完成) + +**缺失接口**: +```c +THREATSOURCE_API int TS_SetThreadCount(int threadCount); +THREATSOURCE_API int TS_SetAsyncMode(const char* scenarioId, int enabled); +THREATSOURCE_API int TS_GetEntityStatesBatch(...); +THREATSOURCE_API int TS_SetEntityStatesBatch(...); +``` + +--- + +## 4. 关键问题分析 + +### 4.1 架构设计问题 + +#### 4.1.1 🔴 单例模式限制 + +**当前实现**: +```cpp +// ThreatSourceNative/src/threat_source.cpp +static msclr::auto_gcroot g_manager; +static std::unordered_map> g_missiles; +static std::unordered_map> g_targets; +``` + +**问题**: +- 全局单例设计无法支持多个独立仿真实例 +- 不同场景之间会相互干扰 +- 无法并行运行多个仿真 + +**解决方案**: +```cpp +// 建议的多场景架构 +class ScenarioManager { + std::unordered_map> scenarios; +}; + +struct SimulationInstance { + msclr::auto_gcroot manager; + std::unordered_map> entities; + SimulationState state; + double currentTime; +}; +``` + +#### 4.1.2 🔴 硬编码实体类型 + +**当前实现**: +```cpp +// 只支持TerminalSensitiveMissile +auto missile = gcnew TerminalSensitiveMissile(managedId, properties, g_manager); +``` + +**问题**: +- 无法根据配置创建不同类型的导弹 +- 不支持指示器和干扰器创建 +- 扩展性差 + +**解决方案**: +```cpp +// 建议的工厂模式 +class EntityFactory { +public: + static ISimulationElement^ CreateMissile(const std::string& type, const std::string& configPath, ...); + static ISimulationElement^ CreateIndicator(const std::string& type, const std::string& configPath, ...); + static ISimulationElement^ CreateJammer(const std::string& type, const std::string& configPath, ...); +}; +``` + +### 4.2 接口设计问题 + +#### 4.2.1 🔴 缺乏类型安全 + +**当前实现**: +```c +THREATSOURCE_API int TS_CreateTarget( + const char* id, + double x, double y, double z, + double orientation // 应该使用结构体 +); +``` + +**问题**: +- 参数过多,容易出错 +- 缺乏类型检查 +- 不符合C API最佳实践 + +**解决方案**: +```c +// 使用标准化结构体 +THREATSOURCE_API int TS_CreateTarget( + const char* scenarioId, + const char* targetId, + int targetType, + const TS_KinematicState* initialState +); +``` + +#### 4.2.2 🔴 错误处理不完善 + +**当前实现**: +```c +#define THREATSOURCE_SUCCESS 0 +#define THREATSOURCE_ERROR_INVALID_PARAM -1 +#define THREATSOURCE_ERROR_INIT_FAILED -2 +#define THREATSOURCE_ERROR_SIMULATION_FAILED -3 +``` + +**问题**: +- 错误码过于简单 +- 缺乏详细的错误分类 +- 调试信息不足 + +**解决方案**: +```c +// 详细错误码系统 +#define TS_SUCCESS 0 +#define TS_ERROR_INVALID_PARAM -1 +#define TS_ERROR_INIT_FAILED -2 +#define TS_ERROR_SIMULATION_FAILED -3 +#define TS_ERROR_ENTITY_NOT_FOUND -4 +#define TS_ERROR_BUFFER_TOO_SMALL -5 +#define TS_ERROR_CONFIG_INVALID -6 +#define TS_ERROR_SCENARIO_NOT_FOUND -7 +#define TS_ERROR_ENTITY_ALREADY_EXISTS -8 +#define TS_ERROR_SIMULATION_NOT_RUNNING -9 +#define TS_ERROR_THREAD_FAILED -10 +#define TS_ERROR_MEMORY_ALLOCATION -11 +#define TS_ERROR_FILE_NOT_FOUND -12 +#define TS_ERROR_PERMISSION_DENIED -13 +``` + +### 4.3 集成问题 + +#### 4.3.1 🔴 事件系统断层 + +**问题**: +- .NET事件系统与C API完全隔离 +- 外部系统无法接收仿真事件 +- 无法实现双向事件通信 + +**影响**: +- Unity等外部系统无法响应导弹命中、目标摧毁等关键事件 +- 无法实现实时的状态同步 +- 集成体验差 + +#### 4.3.2 🟡 配置系统缺失 + +**问题**: +- 当前API不支持配置文件路径参数 +- 无法验证配置文件有效性 +- 缺乏默认配置获取机制 + +**影响**: +- 外部系统难以管理复杂的实体配置 +- 无法实现配置的标准化和复用 + +--- + +## 5. 改进建议和实施路线图 + +### 5.1 第一阶段:核心架构重构 (高优先级) + +#### 5.1.1 实施场景管理系统 + +**目标**: 支持多场景独立仿真 + +**任务清单**: +- [ ] 设计`ScenarioManager`类 +- [ ] 实现场景生命周期管理 +- [ ] 重构全局变量为场景级别 +- [ ] 实现场景隔离机制 + +**预估工期**: 2-3周 + +**关键文件**: +``` +ThreatSourceNative/ +├── include/ +│ ├── threat_source.h (更新) +│ └── scenario_manager.h (新增) +├── src/ +│ ├── threat_source.cpp (重构) +│ ├── scenario_manager.cpp (新增) +│ └── simulation_instance.cpp (新增) +``` + +#### 5.1.2 标准化数据结构 + +**目标**: 建立统一的数据交换格式 + +**任务清单**: +- [ ] 定义核心数据结构 (`TS_Vector3D`, `TS_KinematicState`等) +- [ ] 实现.NET到C结构体的转换 +- [ ] 更新所有API接口使用标准结构 +- [ ] 添加数据验证机制 + +**预估工期**: 1-2周 + +#### 5.1.3 事件系统桥接 + +**目标**: 连接.NET事件系统与C API + +**任务清单**: +- [ ] 设计事件类型枚举 +- [ ] 实现事件回调机制 +- [ ] 建立事件队列系统 +- [ ] 实现事件序列化/反序列化 + +**预估工期**: 2-3周 + +**关键实现**: +```cpp +// 事件桥接类 +class EventBridge { +private: + std::queue eventQueue; + std::unordered_map> callbacks; + +public: + void RegisterCallback(int eventType, TS_EventCallback callback); + void PublishEvent(const TS_Event& event); + int PollEvents(TS_Event* events, int maxEvents); +}; +``` + +### 5.2 第二阶段:功能完善 (中优先级) + +#### 5.2.1 完整实体管理 + +**目标**: 支持所有实体类型的创建和管理 + +**任务清单**: +- [ ] 实现指示器管理API +- [ ] 实现干扰器管理API +- [ ] 实现通用实体管理API +- [ ] 添加实体工厂模式 + +**预估工期**: 3-4周 + +#### 5.2.2 状态查询系统 + +**目标**: 提供完整的状态查询能力 + +**任务清单**: +- [ ] 实现实体状态查询 +- [ ] 实现导弹制导状态查询 +- [ ] 实现目标健康状态查询 +- [ ] 添加批量查询支持 + +**预估工期**: 1-2周 + +#### 5.2.3 Unity集成包 + +**目标**: 提供开箱即用的Unity集成方案 + +**任务清单**: +- [ ] 创建Unity Package结构 +- [ ] 实现核心管理脚本 +- [ ] 创建实体控制器组件 +- [ ] 实现坐标系转换工具 +- [ ] 创建示例场景和预制件 + +**预估工期**: 4-5周 + +### 5.3 第三阶段:优化和扩展 (低优先级) + +#### 5.3.1 环境控制系统 + +**任务清单**: +- [ ] 实现天气系统API +- [ ] 添加环境参数配置 +- [ ] 实现大气条件控制 + +**预估工期**: 1-2周 + +#### 5.3.2 配置管理系统 + +**任务清单**: +- [ ] 实现配置文件加载API +- [ ] 添加配置验证机制 +- [ ] 实现默认配置生成 + +**预估工期**: 1-2周 + +#### 5.3.3 性能优化 + +**任务清单**: +- [ ] 实现多线程支持 +- [ ] 添加批量操作API +- [ ] 实现异步更新模式 +- [ ] 添加性能监控接口 + +**预估工期**: 2-3周 + +### 5.4 总体时间规划 + +``` +阶段一 (核心架构重构): 5-8周 +├── 场景管理系统: 2-3周 +├── 数据结构标准化: 1-2周 +└── 事件系统桥接: 2-3周 + +阶段二 (功能完善): 8-11周 +├── 完整实体管理: 3-4周 +├── 状态查询系统: 1-2周 +└── Unity集成包: 4-5周 + +阶段三 (优化扩展): 4-7周 +├── 环境控制: 1-2周 +├── 配置管理: 1-2周 +└── 性能优化: 2-3周 + +总计: 17-26周 (约4-6个月) +``` + +--- + +## 6. 风险评估和缓解策略 + +### 6.1 技术风险 + +#### 6.1.1 🔴 高风险:C++/CLI互操作复杂性 + +**风险描述**: +- .NET对象生命周期管理复杂 +- 跨边界异常处理困难 +- 内存泄漏风险 + +**缓解策略**: +- 建立严格的对象生命周期管理规范 +- 实现全面的异常捕获和转换 +- 添加内存泄漏检测工具 +- 建立完整的单元测试覆盖 + +#### 6.1.2 🟡 中风险:多场景并发安全 + +**风险描述**: +- 多个场景同时运行可能产生竞态条件 +- 共享资源访问冲突 + +**缓解策略**: +- 实现场景级别的资源隔离 +- 使用线程安全的数据结构 +- 添加并发测试用例 + +### 6.2 项目风险 + +#### 6.2.1 🟡 中风险:开发周期较长 + +**风险描述**: +- 完整实现需要4-6个月 +- 可能影响其他项目进度 + +**缓解策略**: +- 采用分阶段交付模式 +- 优先实现核心功能 +- 建立里程碑检查点 + +#### 6.2.2 🟢 低风险:向后兼容性 + +**风险描述**: +- 新API可能与现有代码不兼容 + +**缓解策略**: +- 保留现有API作为过渡 +- 提供迁移指南和工具 +- 建立版本管理策略 + +--- + +## 7. 成功标准和验收条件 + +### 7.1 功能完整性标准 + +- [ ] **场景管理**: 支持创建、销毁、启停多个独立场景 +- [ ] **实体管理**: 支持所有实体类型的完整生命周期管理 +- [ ] **事件系统**: 实现双向事件通信,支持回调和轮询模式 +- [ ] **状态查询**: 提供实时的实体状态查询能力 +- [ ] **Unity集成**: 提供开箱即用的Unity集成包 + +### 7.2 性能标准 + +- [ ] **响应时间**: API调用响应时间 < 1ms (95%分位) +- [ ] **并发支持**: 支持至少4个并发场景 +- [ ] **内存使用**: 内存泄漏率 < 0.1%/小时 +- [ ] **稳定性**: 连续运行24小时无崩溃 + +### 7.3 集成标准 + +- [ ] **Unity兼容**: 支持Unity 2021.3 LTS及以上版本 +- [ ] **平台支持**: 支持Windows x64, Linux x64, macOS x64 +- [ ] **文档完整**: 提供完整的API文档和集成指南 +- [ ] **示例丰富**: 提供C、C#、Unity三种语言的完整示例 + +--- + +## 8. 结论和建议 + +### 8.1 当前状况总结 + +威胁源仿真库的.NET核心功能已经非常完善,但DLL对接层的实现严重不足,仅完成了约15%的建议功能。主要问题集中在: + +1. **架构设计缺陷**: 单例模式限制了多场景支持 +2. **接口不完整**: 缺失85%的建议API +3. **事件系统断层**: 无法与外部系统进行事件交互 +4. **集成支持缺失**: 没有Unity等外部系统的集成方案 + +### 8.2 优先级建议 + +**立即开始** (阻塞性问题): +1. 场景管理系统重构 +2. 标准化数据结构定义 +3. 事件系统桥接实现 + +**第二优先级** (功能完善): +1. 完整实体管理API +2. 状态查询系统 +3. Unity集成包开发 + +**第三优先级** (优化扩展): +1. 环境控制系统 +2. 配置管理优化 +3. 性能优化功能 + +### 8.3 投资回报分析 + +**投入**: 4-6个月开发时间 +**收益**: +- 支持Unity、UE4等主流游戏引擎集成 +- 提供标准化的外部系统对接能力 +- 大幅提升产品的市场竞争力和应用范围 +- 建立完整的生态系统基础 + +**建议**: 考虑到威胁源仿真库的核心价值和市场潜力,建议投入资源完成完整的DLL对接方案实现。 + +--- + +**文档维护**: 本文档应随着实现进度定期更新,建议每月更新一次完成状况和风险评估。 \ No newline at end of file diff --git a/docs/project/dll_integration_guide.md b/docs/project/dll_integration_guide.md new file mode 100644 index 0000000..7d8e1ca --- /dev/null +++ b/docs/project/dll_integration_guide.md @@ -0,0 +1,1503 @@ +# 威胁源仿真库DLL对接指南 + +## 文档概述 + +本文档详细说明了如何将威胁源仿真库作为DLL库集成到外部仿真系统(如Unity、UE4、自定义仿真平台等)中。 + +**版本**: 1.0 +**创建日期**: 2024年12月 +**最后更新**: 2024年12月 + +--- + +## 1. 架构概览 + +### 1.1 整体架构 + +``` +外部仿真系统 (Unity/UE4/自定义) + ↕ (P/Invoke 或 COM) +威胁源仿真库 DLL (ThreatSource.dll) + ↕ (内部调用) +C++/CLI 包装层 (ThreatSourceNative.dll) + ↕ (托管/非托管互操作) +.NET 核心库 (ThreatSource.dll) + ↕ (依赖) +大气传输库 (AirTransmission.dll) +``` + +### 1.2 接口层次 + +1. **C API层**:提供标准C接口,支持所有外部系统 +2. **C# Wrapper层**:提供.NET友好的接口 +3. **Unity Package层**:专门为Unity优化的包装 +4. **通用适配器层**:支持自定义仿真系统 + +--- + +## 2. C API接口设计 + +### 2.1 核心API结构 + +```c +// ============================================================================ +// 威胁源仿真库 C API 接口 +// ============================================================================ + +#ifndef THREATSOURCE_API_H +#define THREATSOURCE_API_H + +#ifdef _WIN32 + #ifdef THREATSOURCE_EXPORTS + #define THREATSOURCE_API __declspec(dllexport) + #else + #define THREATSOURCE_API __declspec(dllimport) + #endif +#else + #define THREATSOURCE_API +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// 1. 基础类型定义 +// ============================================================================ + +typedef struct { + double x, y, z; +} TS_Vector3D; + +typedef struct { + double yaw, pitch, roll; // 弧度 +} TS_Orientation; + +typedef struct { + TS_Vector3D position; + TS_Vector3D velocity; + TS_Orientation orientation; +} TS_KinematicState; + +typedef struct { + int type; // 0=晴朗, 1=雨天, 2=雪天, 3=雾天, 4=沙尘 + double temperature; // 摄氏度 + double humidity; // 相对湿度 (0-1) + double visibility; // 能见度 (km) + double precipitation; // 降水量 (mm/h) + double windSpeed; // 风速 (m/s) + double windDirection; // 风向 (度) +} TS_Weather; + +typedef struct { + char senderId[64]; + char targetId[64]; + double timestamp; + int eventType; // 事件类型枚举 + char data[256]; // 事件数据JSON字符串 +} TS_Event; + +// 错误码定义 +#define TS_SUCCESS 0 +#define TS_ERROR_INVALID_PARAM -1 +#define TS_ERROR_INIT_FAILED -2 +#define TS_ERROR_SIMULATION_FAILED -3 +#define TS_ERROR_ENTITY_NOT_FOUND -4 +#define TS_ERROR_BUFFER_TOO_SMALL -5 + +// ============================================================================ +// 2. 仿真管理接口 +// ============================================================================ + +/// +/// 初始化威胁源仿真系统 +/// +/// 错误码 +THREATSOURCE_API int TS_Initialize(); + +/// +/// 销毁威胁源仿真系统 +/// +/// 错误码 +THREATSOURCE_API int TS_Shutdown(); + +/// +/// 创建仿真场景 +/// +/// 场景ID +/// 错误码 +THREATSOURCE_API int TS_CreateScenario(const char* scenarioId); + +/// +/// 销毁仿真场景 +/// +/// 场景ID +/// 错误码 +THREATSOURCE_API int TS_DestroyScenario(const char* scenarioId); + +/// +/// 开始仿真 +/// +/// 场景ID +/// 时间步长(秒) +/// 错误码 +THREATSOURCE_API int TS_StartSimulation(const char* scenarioId, double timeStep); + +/// +/// 暂停仿真 +/// +/// 场景ID +/// 错误码 +THREATSOURCE_API int TS_PauseSimulation(const char* scenarioId); + +/// +/// 恢复仿真 +/// +/// 场景ID +/// 错误码 +THREATSOURCE_API int TS_ResumeSimulation(const char* scenarioId); + +/// +/// 停止仿真 +/// +/// 场景ID +/// 错误码 +THREATSOURCE_API int TS_StopSimulation(const char* scenarioId); + +/// +/// 更新仿真 +/// +/// 场景ID +/// 时间增量(秒) +/// 错误码 +THREATSOURCE_API int TS_UpdateSimulation(const char* scenarioId, double deltaTime); + +/// +/// 获取仿真状态 +/// +/// 场景ID +/// 输出状态 (0=停止, 1=运行, 2=暂停) +/// 错误码 +THREATSOURCE_API int TS_GetSimulationState(const char* scenarioId, int* state); + +/// +/// 获取仿真时间 +/// +/// 场景ID +/// 输出仿真时间 +/// 错误码 +THREATSOURCE_API int TS_GetSimulationTime(const char* scenarioId, double* time); + +// ============================================================================ +// 3. 实体管理接口 +// ============================================================================ + +/// +/// 创建导弹 +/// +/// 场景ID +/// 导弹ID +/// 配置文件路径 +/// 初始状态 +/// 错误码 +THREATSOURCE_API int TS_CreateMissile(const char* scenarioId, const char* missileId, + const char* configPath, const TS_KinematicState* initialState); + +/// +/// 创建目标 +/// +/// 场景ID +/// 目标ID +/// 目标类型 (0=坦克, 1=装甲车, 2=建筑物) +/// 初始状态 +/// 错误码 +THREATSOURCE_API int TS_CreateTarget(const char* scenarioId, const char* targetId, + int targetType, const TS_KinematicState* initialState); + +/// +/// 创建指示器 +/// +/// 场景ID +/// 指示器ID +/// 指示器类型 (0=激光指示器, 1=激光驾束仪, 2=红外测角仪) +/// 配置文件路径 +/// 初始状态 +/// 错误码 +THREATSOURCE_API int TS_CreateIndicator(const char* scenarioId, const char* indicatorId, + int indicatorType, const char* configPath, + const TS_KinematicState* initialState); + +/// +/// 创建干扰器 +/// +/// 场景ID +/// 干扰器ID +/// 干扰器类型 (0=激光干扰器, 1=红外干扰器, 2=毫米波干扰器) +/// 配置文件路径 +/// 初始状态 +/// 错误码 +THREATSOURCE_API int TS_CreateJammer(const char* scenarioId, const char* jammerId, + int jammerType, const char* configPath, + const TS_KinematicState* initialState); + +/// +/// 销毁实体 +/// +/// 场景ID +/// 实体ID +/// 错误码 +THREATSOURCE_API int TS_DestroyEntity(const char* scenarioId, const char* entityId); + +/// +/// 激活实体 +/// +/// 场景ID +/// 实体ID +/// 错误码 +THREATSOURCE_API int TS_ActivateEntity(const char* scenarioId, const char* entityId); + +/// +/// 停用实体 +/// +/// 场景ID +/// 实体ID +/// 错误码 +THREATSOURCE_API int TS_DeactivateEntity(const char* scenarioId, const char* entityId); + +// ============================================================================ +// 4. 实体控制接口 +// ============================================================================ + +/// +/// 发射导弹 +/// +/// 场景ID +/// 导弹ID +/// 目标ID +/// 错误码 +THREATSOURCE_API int TS_FireMissile(const char* scenarioId, const char* missileId, const char* targetId); + +/// +/// 设置指示器目标 +/// +/// 场景ID +/// 指示器ID +/// 目标ID +/// 错误码 +THREATSOURCE_API int TS_SetIndicatorTarget(const char* scenarioId, const char* indicatorId, const char* targetId); + +/// +/// 启动干扰器 +/// +/// 场景ID +/// 干扰器ID +/// 错误码 +THREATSOURCE_API int TS_StartJammer(const char* scenarioId, const char* jammerId); + +/// +/// 停止干扰器 +/// +/// 场景ID +/// 干扰器ID +/// 错误码 +THREATSOURCE_API int TS_StopJammer(const char* scenarioId, const char* jammerId); + +// ============================================================================ +// 5. 状态查询接口 +// ============================================================================ + +/// +/// 获取实体状态 +/// +/// 场景ID +/// 实体ID +/// 输出状态 +/// 错误码 +THREATSOURCE_API int TS_GetEntityState(const char* scenarioId, const char* entityId, TS_KinematicState* state); + +/// +/// 获取实体是否激活 +/// +/// 场景ID +/// 实体ID +/// 输出是否激活 +/// 错误码 +THREATSOURCE_API int TS_IsEntityActive(const char* scenarioId, const char* entityId, int* isActive); + +/// +/// 获取导弹制导状态 +/// +/// 场景ID +/// 导弹ID +/// 输出是否制导 +/// 错误码 +THREATSOURCE_API int TS_GetMissileGuidanceState(const char* scenarioId, const char* missileId, int* isGuided); + +/// +/// 获取导弹飞行阶段 +/// +/// 场景ID +/// 导弹ID +/// 输出飞行阶段 (0=发射, 1=巡航, 2=制导, 3=终端) +/// 错误码 +THREATSOURCE_API int TS_GetMissileFlightStage(const char* scenarioId, const char* missileId, int* stage); + +/// +/// 获取目标生命值 +/// +/// 场景ID +/// 目标ID +/// 输出生命值 +/// 错误码 +THREATSOURCE_API int TS_GetTargetHealth(const char* scenarioId, const char* targetId, double* health); + +// ============================================================================ +// 6. 环境控制接口 +// ============================================================================ + +/// +/// 设置天气条件 +/// +/// 场景ID +/// 天气条件 +/// 错误码 +THREATSOURCE_API int TS_SetWeather(const char* scenarioId, const TS_Weather* weather); + +/// +/// 获取天气条件 +/// +/// 场景ID +/// 输出天气条件 +/// 错误码 +THREATSOURCE_API int TS_GetWeather(const char* scenarioId, TS_Weather* weather); + +// ============================================================================ +// 7. 事件系统接口 +// ============================================================================ + +/// +/// 注册事件回调函数 +/// +/// 场景ID +/// 事件类型 +/// 回调函数指针 +/// 错误码 +typedef void (*TS_EventCallback)(const TS_Event* event); +THREATSOURCE_API int TS_RegisterEventCallback(const char* scenarioId, int eventType, TS_EventCallback callback); + +/// +/// 注销事件回调函数 +/// +/// 场景ID +/// 事件类型 +/// 错误码 +THREATSOURCE_API int TS_UnregisterEventCallback(const char* scenarioId, int eventType); + +/// +/// 轮询事件队列 +/// +/// 场景ID +/// 输出事件数组 +/// 最大事件数量 +/// 实际事件数量 +/// 错误码 +THREATSOURCE_API int TS_PollEvents(const char* scenarioId, TS_Event* events, int maxEvents, int* actualEvents); + +/// +/// 发送外部事件 +/// +/// 场景ID +/// 事件 +/// 错误码 +THREATSOURCE_API int TS_SendExternalEvent(const char* scenarioId, const TS_Event* event); + +// ============================================================================ +// 8. 工具函数接口 +// ============================================================================ + +/// +/// 获取最后的错误信息 +/// +/// 输出缓冲区 +/// 缓冲区大小 +/// 错误码 +THREATSOURCE_API int TS_GetLastError(char* buffer, int bufferSize); + +/// +/// 获取版本信息 +/// +/// 输出缓冲区 +/// 缓冲区大小 +/// 错误码 +THREATSOURCE_API int TS_GetVersion(char* buffer, int bufferSize); + +/// +/// 获取支持的导弹类型列表 +/// +/// 输出类型数组 +/// 最大类型数量 +/// 实际类型数量 +/// 错误码 +THREATSOURCE_API int TS_GetSupportedMissileTypes(char types[][64], int maxTypes, int* actualTypes); + +#ifdef __cplusplus +} +#endif + +#endif // THREATSOURCE_API_H +``` + +--- + +## 3. Unity集成方案 + +### 3.1 Unity Package结构 + +``` +ThreatSourceUnity/ +├── Runtime/ +│ ├── Scripts/ +│ │ ├── Core/ +│ │ │ ├── ThreatSourceManager.cs +│ │ │ ├── SimulationScenario.cs +│ │ │ └── EntityManager.cs +│ │ ├── Entities/ +│ │ │ ├── MissileController.cs +│ │ │ ├── TargetController.cs +│ │ │ ├── IndicatorController.cs +│ │ │ └── JammerController.cs +│ │ ├── Events/ +│ │ │ ├── EventManager.cs +│ │ │ └── EventTypes.cs +│ │ └── Utils/ +│ │ ├── NativeInterop.cs +│ │ └── ConfigLoader.cs +│ ├── Plugins/ +│ │ ├── x86_64/ +│ │ │ ├── ThreatSource.dll +│ │ │ ├── ThreatSourceNative.dll +│ │ │ └── AirTransmission.dll +│ │ └── x86/ +│ │ └── (32位版本) +│ └── Prefabs/ +│ ├── Missile.prefab +│ ├── Target.prefab +│ ├── Indicator.prefab +│ └── Jammer.prefab +├── Editor/ +│ ├── ThreatSourceEditor.cs +│ └── ScenarioBuilder.cs +└── Documentation~/ + ├── manual.md + └── api.md +``` + +### 3.2 Unity核心脚本 + +```csharp +// ThreatSourceManager.cs - Unity主管理器 +using UnityEngine; +using System; +using System.Runtime.InteropServices; +using System.Collections.Generic; + +namespace ThreatSource.Unity +{ + /// + /// 威胁源仿真系统Unity管理器 + /// + public class ThreatSourceManager : MonoBehaviour + { + [Header("仿真设置")] + public string scenarioId = "DefaultScenario"; + public double timeStep = 0.02; // 50Hz + public bool autoStart = true; + + [Header("天气设置")] + public WeatherSettings weather = new WeatherSettings(); + + private bool isInitialized = false; + private Dictionary entityObjects = new Dictionary(); + + // 事件回调 + public event Action OnMissileHit; + public event Action OnTargetDestroyed; + public event Action OnMissileStageChanged; + + void Start() + { + InitializeSimulation(); + if (autoStart) + { + StartSimulation(); + } + } + + void Update() + { + if (isInitialized) + { + // 更新仿真 + int result = NativeInterop.TS_UpdateSimulation(scenarioId, Time.deltaTime); + if (result != 0) + { + Debug.LogError($"仿真更新失败: {NativeInterop.GetLastError()}"); + } + + // 轮询事件 + PollEvents(); + + // 同步实体状态 + SynchronizeEntityStates(); + } + } + + void OnDestroy() + { + ShutdownSimulation(); + } + + private void InitializeSimulation() + { + // 初始化威胁源系统 + int result = NativeInterop.TS_Initialize(); + if (result != 0) + { + Debug.LogError($"威胁源系统初始化失败: {NativeInterop.GetLastError()}"); + return; + } + + // 创建场景 + result = NativeInterop.TS_CreateScenario(scenarioId); + if (result != 0) + { + Debug.LogError($"场景创建失败: {NativeInterop.GetLastError()}"); + return; + } + + // 设置天气 + SetWeather(weather); + + isInitialized = true; + Debug.Log("威胁源仿真系统初始化成功"); + } + + public void StartSimulation() + { + if (!isInitialized) return; + + int result = NativeInterop.TS_StartSimulation(scenarioId, timeStep); + if (result != 0) + { + Debug.LogError($"仿真启动失败: {NativeInterop.GetLastError()}"); + } + else + { + Debug.Log("仿真已启动"); + } + } + + public void StopSimulation() + { + if (!isInitialized) return; + + int result = NativeInterop.TS_StopSimulation(scenarioId); + if (result != 0) + { + Debug.LogError($"仿真停止失败: {NativeInterop.GetLastError()}"); + } + else + { + Debug.Log("仿真已停止"); + } + } + + private void ShutdownSimulation() + { + if (isInitialized) + { + NativeInterop.TS_DestroyScenario(scenarioId); + NativeInterop.TS_Shutdown(); + isInitialized = false; + } + } + + // 创建实体的公共方法 + public GameObject CreateMissile(string missileId, string configPath, Vector3 position, Vector3 rotation) + { + // 转换Unity坐标到仿真坐标 + var state = UnityToSimulationState(position, rotation); + + // 在仿真中创建导弹 + int result = NativeInterop.TS_CreateMissile(scenarioId, missileId, configPath, ref state); + if (result != 0) + { + Debug.LogError($"导弹创建失败: {NativeInterop.GetLastError()}"); + return null; + } + + // 在Unity中创建GameObject + GameObject missileObj = Instantiate(missilePrefab, position, Quaternion.Euler(rotation)); + missileObj.name = missileId; + + // 添加控制器组件 + var controller = missileObj.GetComponent(); + if (controller == null) + controller = missileObj.AddComponent(); + controller.Initialize(missileId, this); + + entityObjects[missileId] = missileObj; + return missileObj; + } + + // 其他实体创建方法... + + private void PollEvents() + { + const int maxEvents = 32; + var events = new NativeInterop.TS_Event[maxEvents]; + int actualEvents; + + int result = NativeInterop.TS_PollEvents(scenarioId, events, maxEvents, out actualEvents); + if (result == 0) + { + for (int i = 0; i < actualEvents; i++) + { + ProcessEvent(events[i]); + } + } + } + + private void ProcessEvent(NativeInterop.TS_Event evt) + { + switch (evt.eventType) + { + case (int)EventType.MissileHit: + OnMissileHit?.Invoke(evt.senderId, evt.targetId); + break; + case (int)EventType.TargetDestroyed: + OnTargetDestroyed?.Invoke(evt.targetId); + break; + case (int)EventType.MissileStageChanged: + // 解析事件数据获取新阶段 + var stageData = JsonUtility.FromJson(evt.data); + OnMissileStageChanged?.Invoke(evt.senderId, stageData.newStage); + break; + } + } + + private void SynchronizeEntityStates() + { + foreach (var kvp in entityObjects) + { + string entityId = kvp.Key; + GameObject obj = kvp.Value; + + // 获取仿真状态 + NativeInterop.TS_KinematicState state; + int result = NativeInterop.TS_GetEntityState(scenarioId, entityId, out state); + if (result == 0) + { + // 同步到Unity对象 + obj.transform.position = SimulationToUnityPosition(state.position); + obj.transform.rotation = SimulationToUnityRotation(state.orientation); + + // 通知控制器组件 + var controller = obj.GetComponent(); + controller?.OnStateUpdated(state); + } + } + } + + // 坐标系转换方法 + private NativeInterop.TS_KinematicState UnityToSimulationState(Vector3 position, Vector3 rotation) + { + return new NativeInterop.TS_KinematicState + { + position = new NativeInterop.TS_Vector3D { x = position.x, y = position.y, z = position.z }, + velocity = new NativeInterop.TS_Vector3D { x = 0, y = 0, z = 0 }, + orientation = new NativeInterop.TS_Orientation + { + yaw = rotation.y * Mathf.Deg2Rad, + pitch = rotation.x * Mathf.Deg2Rad, + roll = rotation.z * Mathf.Deg2Rad + } + }; + } + + private Vector3 SimulationToUnityPosition(NativeInterop.TS_Vector3D pos) + { + return new Vector3((float)pos.x, (float)pos.y, (float)pos.z); + } + + private Quaternion SimulationToUnityRotation(NativeInterop.TS_Orientation orient) + { + return Quaternion.Euler( + (float)(orient.pitch * Mathf.Rad2Deg), + (float)(orient.yaw * Mathf.Rad2Deg), + (float)(orient.roll * Mathf.Rad2Deg) + ); + } + } + + [Serializable] + public class WeatherSettings + { + public WeatherType type = WeatherType.Clear; + public float temperature = 20f; + public float humidity = 0.5f; + public float visibility = 10f; + public float precipitation = 0f; + public float windSpeed = 5f; + public float windDirection = 0f; + } + + public enum WeatherType + { + Clear = 0, + Rain = 1, + Snow = 2, + Fog = 3, + Dust = 4 + } + + public enum EventType + { + MissileHit = 1, + TargetDestroyed = 2, + MissileStageChanged = 3, + // 其他事件类型... + } + + [Serializable] + public class StageChangeData + { + public int oldStage; + public int newStage; + } +} +``` + +--- + +## 4. 使用流程 + +### 4.1 初始化流程 + +```csharp +// 1. 初始化威胁源系统 +int result = TS_Initialize(); + +// 2. 创建仿真场景 +result = TS_CreateScenario("MyScenario"); + +// 3. 设置环境条件 +TS_Weather weather = { + .type = 0, // 晴朗 + .temperature = 25.0, // 25°C + .humidity = 0.6, // 60%湿度 + .visibility = 15.0, // 15km能见度 + .precipitation = 0.0, + .windSpeed = 3.0, + .windDirection = 45.0 +}; +result = TS_SetWeather("MyScenario", &weather); + +// 4. 注册事件回调 +result = TS_RegisterEventCallback("MyScenario", EVENT_MISSILE_HIT, OnMissileHitCallback); +result = TS_RegisterEventCallback("MyScenario", EVENT_TARGET_DESTROYED, OnTargetDestroyedCallback); +``` + +### 4.2 实体创建流程 + +```csharp +// 1. 创建目标 +TS_KinematicState targetState = { + .position = {1000.0, 0.0, 0.0}, + .velocity = {0.0, 0.0, 0.0}, + .orientation = {0.0, 0.0, 0.0} +}; +result = TS_CreateTarget("MyScenario", "Tank_01", TARGET_TYPE_TANK, &targetState); + +// 2. 创建导弹 +TS_KinematicState missileState = { + .position = {0.0, 0.0, 0.0}, + .velocity = {0.0, 0.0, 0.0}, + .orientation = {0.0, 0.0, 0.0} +}; +result = TS_CreateMissile("MyScenario", "Missile_01", "configs/ir_imaging.toml", &missileState); + +// 3. 创建指示器(如果需要) +TS_KinematicState indicatorState = { + .position = {-100.0, 0.0, 10.0}, + .velocity = {0.0, 0.0, 0.0}, + .orientation = {0.0, 0.0, 0.0} +}; +result = TS_CreateIndicator("MyScenario", "Laser_01", INDICATOR_TYPE_LASER_DESIGNATOR, + "configs/laser_designator.toml", &indicatorState); +``` + +### 4.3 仿真运行流程 + +```csharp +// 1. 激活实体 +result = TS_ActivateEntity("MyScenario", "Tank_01"); +result = TS_ActivateEntity("MyScenario", "Missile_01"); +result = TS_ActivateEntity("MyScenario", "Laser_01"); + +// 2. 设置指示器目标(如果需要) +result = TS_SetIndicatorTarget("MyScenario", "Laser_01", "Tank_01"); + +// 3. 开始仿真 +result = TS_StartSimulation("MyScenario", 0.02); // 50Hz + +// 4. 发射导弹 +result = TS_FireMissile("MyScenario", "Missile_01", "Tank_01"); + +// 5. 仿真循环 +while (simulationRunning) { + // 更新仿真 + result = TS_UpdateSimulation("MyScenario", deltaTime); + + // 轮询事件 + TS_Event events[32]; + int eventCount; + result = TS_PollEvents("MyScenario", events, 32, &eventCount); + + for (int i = 0; i < eventCount; i++) { + ProcessEvent(&events[i]); + } + + // 获取实体状态进行可视化更新 + TS_KinematicState missileState; + result = TS_GetEntityState("MyScenario", "Missile_01", &missileState); + UpdateVisualObject("Missile_01", &missileState); + + Sleep(20); // 50Hz +} +``` + +### 4.4 清理流程 + +```csharp +// 1. 停止仿真 +result = TS_StopSimulation("MyScenario"); + +// 2. 销毁实体 +result = TS_DestroyEntity("MyScenario", "Missile_01"); +result = TS_DestroyEntity("MyScenario", "Tank_01"); +result = TS_DestroyEntity("MyScenario", "Laser_01"); + +// 3. 销毁场景 +result = TS_DestroyScenario("MyScenario"); + +// 4. 关闭系统 +result = TS_Shutdown(); +``` + +--- + +## 5. 事件系统对接 + +### 5.1 事件类型定义 + +```c +// 事件类型枚举 +typedef enum { + // 导弹事件 + EVENT_MISSILE_FIRED = 1, + EVENT_MISSILE_HIT = 2, + EVENT_MISSILE_STAGE_CHANGED = 3, + EVENT_MISSILE_GUIDANCE_ACQUIRED = 4, + EVENT_MISSILE_GUIDANCE_LOST = 5, + + // 目标事件 + EVENT_TARGET_HIT = 10, + EVENT_TARGET_DESTROYED = 11, + EVENT_TARGET_DAMAGED = 12, + + // 指示器事件 + EVENT_LASER_ILLUMINATION_START = 20, + EVENT_LASER_ILLUMINATION_STOP = 21, + EVENT_INFRARED_GUIDANCE_COMMAND = 22, + + // 干扰器事件 + EVENT_JAMMING_START = 30, + EVENT_JAMMING_STOP = 31, + + // 告警器事件 + EVENT_LASER_WARNING = 40, + EVENT_INFRARED_WARNING = 41, + EVENT_MILLIMETER_WAVE_WARNING = 42, + + // 系统事件 + EVENT_SIMULATION_START = 50, + EVENT_SIMULATION_STOP = 51, + EVENT_SIMULATION_PAUSE = 52, + EVENT_SIMULATION_RESUME = 53 +} TS_EventType; +``` + +### 5.2 事件回调示例 + +```c +// 导弹命中事件回调 +void OnMissileHitCallback(const TS_Event* event) { + printf("导弹 %s 命中目标 %s\n", event->senderId, event->targetId); + + // 解析事件数据 + // event->data 包含JSON格式的详细信息 + // 例如: {"hitPosition": {"x": 1000, "y": 0, "z": 0}, "damage": 100} + + // 通知外部系统 + NotifyExternalSystem(EVENT_MISSILE_HIT, event); +} + +// 目标被摧毁事件回调 +void OnTargetDestroyedCallback(const TS_Event* event) { + printf("目标 %s 被摧毁\n", event->targetId); + + // 在外部系统中移除目标的可视化表示 + RemoveVisualObject(event->targetId); +} +``` + +--- + +## 6. 配置文件管理 + +### 6.1 配置文件结构 + +``` +configs/ +├── missiles/ +│ ├── ir_imaging/ +│ │ └── itg_001.toml +│ ├── ir_command/ +│ │ └── irc_001.toml +│ ├── laser_beam_rider/ +│ │ └── lbr_001.toml +│ └── laser_semi_active/ +│ └── lsg_001.toml +├── indicators/ +│ ├── laser_designators/ +│ │ └── ld_001.toml +│ ├── laser_beam_riders/ +│ │ └── lbr_001.toml +│ └── ir_trackers/ +│ └── it_001.toml +├── jammers/ +│ ├── laser_jammers/ +│ │ └── lj_001.toml +│ ├── ir_jammers/ +│ │ └── ij_001.toml +│ └── mmw_jammers/ +│ └── mj_001.toml +└── scenarios/ + ├── basic_test.toml + └── complex_scenario.toml +``` + +### 6.2 配置加载API + +```c +/// +/// 加载配置文件 +/// +/// 配置文件路径 +/// 输出配置数据JSON字符串 +/// 缓冲区大小 +/// 错误码 +THREATSOURCE_API int TS_LoadConfig(const char* configPath, char* configData, int bufferSize); + +/// +/// 验证配置文件 +/// +/// 配置文件路径 +/// 输出是否有效 +/// 错误码 +THREATSOURCE_API int TS_ValidateConfig(const char* configPath, int* isValid); + +/// +/// 获取默认配置 +/// +/// 实体类型 +/// 输出默认配置JSON字符串 +/// 缓冲区大小 +/// 错误码 +THREATSOURCE_API int TS_GetDefaultConfig(int entityType, char* configData, int bufferSize); +``` + +--- + +## 7. 性能优化建议 + +### 7.1 内存管理 + +1. **对象池模式**:为频繁创建/销毁的对象使用对象池 +2. **批量操作**:批量更新多个实体状态 +3. **延迟加载**:按需加载配置文件和资源 + +### 7.2 多线程支持 + +```c +/// +/// 设置仿真线程数 +/// +/// 线程数量 +/// 错误码 +THREATSOURCE_API int TS_SetThreadCount(int threadCount); + +/// +/// 启用异步更新模式 +/// +/// 场景ID +/// 是否启用 +/// 错误码 +THREATSOURCE_API int TS_SetAsyncMode(const char* scenarioId, int enabled); +``` + +### 7.3 批量操作API + +```c +/// +/// 批量获取实体状态 +/// +/// 场景ID +/// 实体ID数组 +/// 实体数量 +/// 输出状态数组 +/// 错误码 +THREATSOURCE_API int TS_GetEntityStatesBatch(const char* scenarioId, const char** entityIds, + int entityCount, TS_KinematicState* states); + +/// +/// 批量更新实体状态 +/// +/// 场景ID +/// 实体ID数组 +/// 状态数组 +/// 实体数量 +/// 错误码 +THREATSOURCE_API int TS_SetEntityStatesBatch(const char* scenarioId, const char** entityIds, + const TS_KinematicState* states, int entityCount); +``` + +--- + +## 8. 错误处理和调试 + +### 8.1 错误码系统 + +```c +// 详细错误码定义 +#define TS_SUCCESS 0 +#define TS_ERROR_INVALID_PARAM -1 +#define TS_ERROR_INIT_FAILED -2 +#define TS_ERROR_SIMULATION_FAILED -3 +#define TS_ERROR_ENTITY_NOT_FOUND -4 +#define TS_ERROR_BUFFER_TOO_SMALL -5 +#define TS_ERROR_CONFIG_INVALID -6 +#define TS_ERROR_SCENARIO_NOT_FOUND -7 +#define TS_ERROR_ENTITY_ALREADY_EXISTS -8 +#define TS_ERROR_SIMULATION_NOT_RUNNING -9 +#define TS_ERROR_THREAD_FAILED -10 +#define TS_ERROR_MEMORY_ALLOCATION -11 +#define TS_ERROR_FILE_NOT_FOUND -12 +#define TS_ERROR_PERMISSION_DENIED -13 +``` + +### 8.2 日志系统 + +```c +/// +/// 设置日志级别 +/// +/// 日志级别 (0=关闭, 1=错误, 2=警告, 3=信息, 4=调试) +/// 错误码 +THREATSOURCE_API int TS_SetLogLevel(int level); + +/// +/// 设置日志输出文件 +/// +/// 日志文件路径 +/// 错误码 +THREATSOURCE_API int TS_SetLogFile(const char* filePath); + +/// +/// 注册日志回调函数 +/// +/// 日志回调函数 +/// 错误码 +typedef void (*TS_LogCallback)(int level, const char* message); +THREATSOURCE_API int TS_RegisterLogCallback(TS_LogCallback callback); +``` + +--- + +## 9. 部署和分发 + +### 9.1 文件结构 + +``` +ThreatSourceSDK/ +├── bin/ +│ ├── x64/ +│ │ ├── ThreatSource.dll +│ │ ├── ThreatSourceNative.dll +│ │ ├── AirTransmission.dll +│ │ └── msvcr140.dll (运行时依赖) +│ └── x86/ +│ └── (32位版本) +├── include/ +│ ├── threat_source.h +│ └── threat_source_types.h +├── lib/ +│ ├── x64/ +│ │ └── ThreatSourceNative.lib +│ └── x86/ +│ └── ThreatSourceNative.lib +├── configs/ +│ └── (配置文件) +├── docs/ +│ ├── api_reference.html +│ ├── integration_guide.pdf +│ └── examples/ +└── samples/ + ├── c_sample/ + ├── cpp_sample/ + ├── csharp_sample/ + └── unity_sample/ +``` + +### 9.2 系统要求 + +- **操作系统**: Windows 10/11 (x64), Linux (x64), macOS (x64) +- **.NET Runtime**: .NET 8.0 或更高版本 +- **Visual C++ Redistributable**: 2019或更高版本 +- **内存**: 最少512MB,推荐2GB +- **存储**: 最少100MB可用空间 + +--- + +## 10. 示例代码 + +### 10.1 C语言示例 + +```c +#include "threat_source.h" +#include +#include + +int main() { + // 初始化系统 + int result = TS_Initialize(); + if (result != TS_SUCCESS) { + printf("初始化失败: %d\n", result); + return -1; + } + + // 创建场景 + const char* scenarioId = "TestScenario"; + result = TS_CreateScenario(scenarioId); + if (result != TS_SUCCESS) { + printf("场景创建失败: %d\n", result); + TS_Shutdown(); + return -1; + } + + // 创建目标 + TS_KinematicState targetState = { + .position = {1000.0, 0.0, 0.0}, + .velocity = {0.0, 0.0, 0.0}, + .orientation = {0.0, 0.0, 0.0} + }; + result = TS_CreateTarget(scenarioId, "Target_01", 0, &targetState); + + // 创建导弹 + TS_KinematicState missileState = { + .position = {0.0, 0.0, 0.0}, + .velocity = {0.0, 0.0, 0.0}, + .orientation = {0.0, 0.0, 0.0} + }; + result = TS_CreateMissile(scenarioId, "Missile_01", "configs/ir_imaging.toml", &missileState); + + // 激活实体 + TS_ActivateEntity(scenarioId, "Target_01"); + TS_ActivateEntity(scenarioId, "Missile_01"); + + // 开始仿真 + result = TS_StartSimulation(scenarioId, 0.02); + + // 发射导弹 + TS_FireMissile(scenarioId, "Missile_01", "Target_01"); + + // 仿真循环 + for (int i = 0; i < 1000; i++) { + result = TS_UpdateSimulation(scenarioId, 0.02); + + // 检查仿真状态 + int state; + TS_GetSimulationState(scenarioId, &state); + if (state == 0) { // 仿真已停止 + break; + } + + // 获取导弹状态 + TS_KinematicState currentState; + result = TS_GetEntityState(scenarioId, "Missile_01", ¤tState); + if (result == TS_SUCCESS) { + printf("导弹位置: (%.2f, %.2f, %.2f)\n", + currentState.position.x, + currentState.position.y, + currentState.position.z); + } + + // 模拟20ms延迟 + #ifdef _WIN32 + Sleep(20); + #else + usleep(20000); + #endif + } + + // 清理 + TS_StopSimulation(scenarioId); + TS_DestroyScenario(scenarioId); + TS_Shutdown(); + + return 0; +} +``` + +### 10.2 C#语言示例 + +```csharp +using System; +using System.Runtime.InteropServices; +using System.Threading; + +class Program +{ + static void Main() + { + var simulator = new ThreatSourceSimulator(); + simulator.RunSimulation(); + } +} + +public class ThreatSourceSimulator +{ + public void RunSimulation() + { + // 初始化系统 + int result = NativeAPI.TS_Initialize(); + if (result != 0) + { + Console.WriteLine($"初始化失败: {result}"); + return; + } + + string scenarioId = "TestScenario"; + + try + { + // 创建场景 + result = NativeAPI.TS_CreateScenario(scenarioId); + CheckResult(result, "场景创建"); + + // 设置天气 + var weather = new NativeAPI.TS_Weather + { + type = 0, // 晴朗 + temperature = 25.0, + humidity = 0.6, + visibility = 15.0, + precipitation = 0.0, + windSpeed = 3.0, + windDirection = 45.0 + }; + result = NativeAPI.TS_SetWeather(scenarioId, ref weather); + CheckResult(result, "天气设置"); + + // 创建实体 + CreateEntities(scenarioId); + + // 开始仿真 + result = NativeAPI.TS_StartSimulation(scenarioId, 0.02); + CheckResult(result, "仿真启动"); + + // 发射导弹 + result = NativeAPI.TS_FireMissile(scenarioId, "Missile_01", "Target_01"); + CheckResult(result, "导弹发射"); + + // 仿真循环 + RunSimulationLoop(scenarioId); + } + finally + { + // 清理资源 + NativeAPI.TS_StopSimulation(scenarioId); + NativeAPI.TS_DestroyScenario(scenarioId); + NativeAPI.TS_Shutdown(); + } + } + + private void CreateEntities(string scenarioId) + { + // 创建目标 + var targetState = new NativeAPI.TS_KinematicState + { + position = new NativeAPI.TS_Vector3D { x = 1000.0, y = 0.0, z = 0.0 }, + velocity = new NativeAPI.TS_Vector3D { x = 0.0, y = 0.0, z = 0.0 }, + orientation = new NativeAPI.TS_Orientation { yaw = 0.0, pitch = 0.0, roll = 0.0 } + }; + int result = NativeAPI.TS_CreateTarget(scenarioId, "Target_01", 0, ref targetState); + CheckResult(result, "目标创建"); + + // 创建导弹 + var missileState = new NativeAPI.TS_KinematicState + { + position = new NativeAPI.TS_Vector3D { x = 0.0, y = 0.0, z = 0.0 }, + velocity = new NativeAPI.TS_Vector3D { x = 0.0, y = 0.0, z = 0.0 }, + orientation = new NativeAPI.TS_Orientation { yaw = 0.0, pitch = 0.0, roll = 0.0 } + }; + result = NativeAPI.TS_CreateMissile(scenarioId, "Missile_01", "configs/ir_imaging.toml", ref missileState); + CheckResult(result, "导弹创建"); + + // 激活实体 + NativeAPI.TS_ActivateEntity(scenarioId, "Target_01"); + NativeAPI.TS_ActivateEntity(scenarioId, "Missile_01"); + } + + private void RunSimulationLoop(string scenarioId) + { + for (int i = 0; i < 1000; i++) + { + // 更新仿真 + int result = NativeAPI.TS_UpdateSimulation(scenarioId, 0.02); + if (result != 0) break; + + // 检查仿真状态 + int state; + NativeAPI.TS_GetSimulationState(scenarioId, out state); + if (state == 0) break; // 仿真已停止 + + // 获取导弹状态 + NativeAPI.TS_KinematicState currentState; + result = NativeAPI.TS_GetEntityState(scenarioId, "Missile_01", out currentState); + if (result == 0) + { + Console.WriteLine($"导弹位置: ({currentState.position.x:F2}, {currentState.position.y:F2}, {currentState.position.z:F2})"); + } + + Thread.Sleep(20); // 20ms延迟 + } + } + + private void CheckResult(int result, string operation) + { + if (result != 0) + { + string error = NativeAPI.GetLastError(); + throw new Exception($"{operation}失败: {result}, {error}"); + } + } +} + +// P/Invoke声明 +public static class NativeAPI +{ + const string DllName = "ThreatSourceNative.dll"; + + [StructLayout(LayoutKind.Sequential)] + public struct TS_Vector3D + { + public double x, y, z; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TS_Orientation + { + public double yaw, pitch, roll; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TS_KinematicState + { + public TS_Vector3D position; + public TS_Vector3D velocity; + public TS_Orientation orientation; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TS_Weather + { + public int type; + public double temperature; + public double humidity; + public double visibility; + public double precipitation; + public double windSpeed; + public double windDirection; + } + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] + public static extern int TS_Initialize(); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] + public static extern int TS_Shutdown(); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_CreateScenario(string scenarioId); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_DestroyScenario(string scenarioId); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_StartSimulation(string scenarioId, double timeStep); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_StopSimulation(string scenarioId); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_UpdateSimulation(string scenarioId, double deltaTime); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_CreateTarget(string scenarioId, string targetId, int targetType, ref TS_KinematicState initialState); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_CreateMissile(string scenarioId, string missileId, string configPath, ref TS_KinematicState initialState); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_ActivateEntity(string scenarioId, string entityId); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_FireMissile(string scenarioId, string missileId, string targetId); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_GetEntityState(string scenarioId, string entityId, out TS_KinematicState state); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_GetSimulationState(string scenarioId, out int state); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_SetWeather(string scenarioId, ref TS_Weather weather); + + [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + public static extern int TS_GetLastError(StringBuilder buffer, int bufferSize); + + public static string GetLastError() + { + var buffer = new StringBuilder(256); + TS_GetLastError(buffer, buffer.Capacity); + return buffer.ToString(); + } +} +``` + +--- + +**文档结束** + +*此文档提供了威胁源仿真库DLL对接的完整指南,包括API设计、集成方案、使用流程和示例代码。* \ No newline at end of file diff --git a/docs/project/simulation_events_checklist.md b/docs/project/simulation_events_checklist.md new file mode 100644 index 0000000..6e66a26 --- /dev/null +++ b/docs/project/simulation_events_checklist.md @@ -0,0 +1,289 @@ +# 威胁源仿真系统事件清单 + +## 文档概述 + +本文档整理了威胁源仿真系统中所有实体的生命周期事件和交互事件,用于查漏补缺和系统完整性验证。 + +**版本**: 1.0 +**创建日期**: 2024年12月 +**最后更新**: 2024年12月 + +--- + +## 1. 导弹生命周期事件 + +### 1.1 导弹状态事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 导弹发射 | `MissileFireEvent` | 导弹Fire()方法调用时 | SenderId, TargetId | 仿真管理器, 外部系统 | +| 导弹激活 | *(缺失)* | 导弹Activate()时 | SenderId | - | +| 导弹停用 | *(缺失)* | 导弹Deactivate()时 | SenderId | - | +| 导弹自毁 | *(缺失)* | 导弹SelfDestruct()时 | SenderId, 原因 | - | +| 导弹爆炸 | *(缺失)* | 导弹Explode()时 | SenderId, 位置 | - | +| 导弹阶段切换 | *(缺失)* | 飞行阶段变化时 | SenderId, 旧阶段, 新阶段 | - | + +### 1.2 导弹运动事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 发动机启动 | *(缺失)* | 推力开始时 | SenderId, 推力值 | - | +| 发动机关闭 | *(缺失)* | 推力结束时 | SenderId, 关闭原因 | - | +| 速度限制触发 | *(缺失)* | 达到最大速度时 | SenderId, 当前速度 | - | + +### 1.3 导弹制导事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 制导获得 | *(缺失)* | IsGuidance变为true时 | SenderId, 制导类型 | - | +| 制导丢失 | *(缺失)* | IsGuidance变为false时 | SenderId, 丢失原因 | - | +| 制导指令更新 | *(缺失)* | GuidanceAcceleration更新时 | SenderId, 制导加速度 | - | + +--- + +## 2. 目标/装备生命周期事件 + +### 2.1 目标状态事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 目标被击中 | `TargetHitEvent` | 导弹命中目标时 | TargetId, MissileId | 仿真管理器 | +| 目标被摧毁 | `TargetDestroyedEvent` | 目标生命值≤0时 | TargetId, MissileId | 仿真管理器 | +| 目标激活 | *(缺失)* | 目标Activate()时 | SenderId | - | +| 目标停用 | *(缺失)* | 目标Deactivate()时 | SenderId | - | +| 目标受损 | *(缺失)* | TakeDamage()调用时 | SenderId, 伤害值, 剩余生命值 | - | + +### 2.2 目标运动事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 目标位置更新 | *(缺失)* | 位置显著变化时 | SenderId, 新位置, 速度 | - | +| 目标停止 | *(缺失)* | 速度降为0时 | SenderId, 停止位置 | - | + +--- + +## 3. 指示器生命周期事件 + +### 3.1 激光指示器事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 激光照射开始 | `LaserIlluminationEvent` | 开始照射目标时 | LaserDesignatorId, TargetId, SpotPosition, LaserCodeConfig | 激光制导导弹 | +| 激光照射停止 | `LaserIlluminationStopEvent` | 停止照射时 | LaserDesignatorId, TargetId | 激光制导导弹 | +| 激光编码不匹配 | `LaserCodeMismatchEvent` | 编码验证失败时 | MissileId, DesignatorId, ExpectedCodeConfig, ReceivedCodeConfig | 导弹制导系统 | + +### 3.2 激光驾束仪事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 激光波束开始 | `LaserBeamEvent` | 开始发射波束时 | LaserBeamRiderId, BeamPower, LaserCodeConfig | 激光驾束导弹 | +| 激光波束停止 | `LaserBeamStopEvent` | 停止发射波束时 | LaserBeamRiderId | 激光驾束导弹 | + +### 3.3 红外测角仪事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 红外制导指令 | `InfraredGuidanceCommandEvent` | 发送制导指令时 | TargetMissileId, TrackerToTargetVector, TrackerToMissileVector | 红外指令导弹 | +| 导弹红外热源点亮 | `InfraredGuidanceMissileLightEvent` | 导弹发动机点火时 | SenderId, RadiationPower | 红外测角仪 | +| 导弹红外热源熄灭 | `InfraredGuidanceMissileLightOffEvent` | 导弹发动机关闭时 | SenderId | 红外测角仪 | + +### 3.4 指示器状态事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 指示器激活 | *(缺失)* | 指示器Activate()时 | SenderId, 指示器类型 | - | +| 指示器停用 | *(缺失)* | 指示器Deactivate()时 | SenderId, 指示器类型 | - | +| 目标锁定 | *(缺失)* | 成功锁定目标时 | SenderId, TargetId | - | +| 目标丢失 | *(缺失)* | 失去目标时 | SenderId, TargetId, 丢失原因 | - | + +--- + +## 4. 告警器事件 + +### 4.1 激光告警器事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 激光告警开始 | `LaserWarnerAlarmEvent` | 检测到激光照射时 | SenderId, TargetId | 目标防护系统 | +| 激光告警停止 | `LaserWarnerAlarmStopEvent` | 激光照射结束时 | SenderId, TargetId | 目标防护系统 | + +### 4.2 红外告警器事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 红外探测 | `InfraredDetectionEvent` | 检测到红外辐射时 | SenderId, TargetId, Intensity | - | +| 红外告警开始 | `InfraredWarnerAlarmEvent` | 红外威胁告警时 | SenderId, TargetId | 目标防护系统 | +| 红外告警停止 | `InfraredWarnerAlarmStopEvent` | 红外威胁消失时 | SenderId, TargetId | 目标防护系统 | + +### 4.3 紫外告警器事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 紫外探测 | `UltravioletDetectionEvent` | 检测到紫外辐射时 | SenderId, TargetId, Intensity | - | +| 紫外告警开始 | `UltravioletWarnerAlarmEvent` | 紫外威胁告警时 | SenderId, TargetId | 目标防护系统 | +| 紫外告警停止 | `UltravioletWarnerAlarmStopEvent` | 紫外威胁消失时 | SenderId, TargetId | 目标防护系统 | + +### 4.4 毫米波告警器事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 毫米波探测 | `MillimeterWaveDetectionEvent` | 检测到毫米波辐射时 | SenderId, TargetId, Intensity, Frequency | - | +| 毫米波告警开始 | `MillimeterWaveWarnerAlarmEvent` | 毫米波威胁告警时 | SenderId, TargetId, DetectedFrequency | 目标防护系统 | +| 毫米波告警停止 | `MillimeterWaveWarnerAlarmStopEvent` | 毫米波威胁消失时 | SenderId, TargetId | 目标防护系统 | + +--- + +## 5. 干扰器事件 + +### 5.1 通用干扰事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 干扰开始 | `JammingEvent` | 干扰器开始工作时 | SenderId, Parameters(功率、波长、位置、方向等) | 所有可干扰设备 | +| 干扰停止 | `JammingStoppedEvent` | 干扰器停止工作时 | SenderId, Parameters | 所有可干扰设备 | + +### 5.2 干扰器状态事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 干扰器激活 | *(缺失)* | 干扰器Activate()时 | SenderId, 干扰类型 | - | +| 干扰器停用 | *(缺失)* | 干扰器Deactivate()时 | SenderId, 干扰类型 | - | +| 干扰器故障 | *(缺失)* | 状态变为Fault时 | SenderId, 故障原因 | - | +| 干扰器冷却 | *(缺失)* | 状态变为Cooling时 | SenderId, 冷却时间 | - | + +--- + +## 6. 系统级事件 + +### 6.1 仿真控制事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 仿真开始 | *(缺失)* | StartSimulation()时 | 时间步长 | 所有实体 | +| 仿真暂停 | *(缺失)* | PauseSimulation()时 | 暂停时间 | 所有实体 | +| 仿真恢复 | *(缺失)* | ResumeSimulation()时 | 恢复时间 | 所有实体 | +| 仿真停止 | *(缺失)* | StopSimulation()时 | 停止时间 | 所有实体 | + +### 6.2 实体管理事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 实体注册 | *(缺失)* | RegisterEntity()时 | EntityId, EntityType | 仿真管理器 | +| 实体注销 | *(缺失)* | UnregisterEntity()时 | EntityId, EntityType | 仿真管理器 | +| 实体销毁 | `EntityDestroyedEvent` | 实体被销毁时 | DestroyedEntityId | 仿真管理器 | + +### 6.3 环境事件 +| 事件名称 | 事件类 | 触发时机 | 包含信息 | 订阅者 | +|---------|--------|----------|----------|--------| +| 天气变化 | *(缺失)* | SetWeather()时 | 新天气条件 | 所有实体 | +| 时间同步 | *(缺失)* | 时间步进时 | 当前仿真时间 | 外部系统 | + +--- + +## 7. 交互事件矩阵 + +### 7.1 导弹-目标交互 +| 发送者 | 接收者 | 事件 | 触发条件 | +|--------|--------|------|----------| +| 导弹 | 目标 | TargetHitEvent | 导弹命中目标 | +| 目标 | 系统 | TargetDestroyedEvent | 目标生命值耗尽 | + +### 7.2 指示器-导弹交互 +| 发送者 | 接收者 | 事件 | 触发条件 | +|--------|--------|------|----------| +| 激光指示器 | 激光制导导弹 | LaserIlluminationEvent | 照射目标 | +| 激光驾束仪 | 激光驾束导弹 | LaserBeamEvent | 发射波束 | +| 红外测角仪 | 红外指令导弹 | InfraredGuidanceCommandEvent | 发送制导指令 | +| 导弹 | 红外测角仪 | InfraredGuidanceMissileLightEvent | 发动机点火 | + +### 7.3 干扰器-设备交互 +| 发送者 | 接收者 | 事件 | 触发条件 | +|--------|--------|------|----------| +| 干扰器 | 所有可干扰设备 | JammingEvent | 开始干扰 | +| 干扰器 | 所有可干扰设备 | JammingStoppedEvent | 停止干扰 | + +### 7.4 告警器-目标交互 +| 发送者 | 接收者 | 事件 | 触发条件 | +|--------|--------|------|----------| +| 告警器 | 目标 | *WarnerAlarmEvent | 检测到威胁 | +| 告警器 | 目标 | *WarnerAlarmStopEvent | 威胁消失 | + +--- + +## 8. 缺失事件分析 + +### 8.1 高优先级缺失事件 +1. **导弹状态变化事件**: 激活、停用、自毁、爆炸、阶段切换 +2. **制导状态事件**: 制导获得、制导丢失、制导指令更新 +3. **发动机事件**: 启动、关闭、推力变化 +4. **仿真控制事件**: 开始、暂停、恢复、停止 +5. **实体管理事件**: 注册、注销 + +### 8.2 中优先级缺失事件 +1. **目标状态事件**: 激活、停用、受损、位置更新 +2. **指示器状态事件**: 激活、停用、目标锁定、目标丢失 +3. **干扰器状态事件**: 激活、停用、故障、冷却 +4. **环境事件**: 天气变化、时间同步 + +### 8.3 低优先级缺失事件 +1. **性能监控事件**: CPU使用率、内存使用率、帧率 +2. **调试事件**: 断点触发、变量变化、异常捕获 +3. **统计事件**: 命中率统计、干扰效果统计 + +--- + +## 9. 事件订阅关系图 + +``` +仿真管理器 +├── 订阅所有实体的生命周期事件 +├── 发布系统级事件 +└── 转发事件到外部系统 + +导弹 +├── 订阅: TargetHitEvent, JammingEvent, LaserIlluminationEvent等 +├── 发布: MissileFireEvent, InfraredGuidanceMissileLightEvent等 +└── 响应: 制导指令、干扰信号 + +目标/装备 +├── 订阅: *WarnerAlarmEvent, JammingEvent +├── 发布: TargetHitEvent, TargetDestroyedEvent +└── 响应: 告警信号、干扰信号 + +指示器 +├── 订阅: JammingEvent, InfraredGuidanceMissileLightEvent +├── 发布: LaserIlluminationEvent, InfraredGuidanceCommandEvent等 +└── 响应: 干扰信号、导弹状态 + +干扰器 +├── 订阅: 无(主动发射) +├── 发布: JammingEvent, JammingStoppedEvent +└── 响应: 控制指令 + +告警器 +├── 订阅: 辐射探测信号 +├── 发布: *WarnerAlarmEvent, *DetectionEvent +└── 响应: 威胁信号 +``` + +--- + +## 10. 改进建议 + +### 10.1 立即实施 +1. **添加导弹生命周期事件**: 激活、停用、自毁、爆炸事件 +2. **添加制导状态事件**: 制导获得、丢失事件 +3. **添加仿真控制事件**: 开始、停止、暂停、恢复事件 + +### 10.2 短期实施 +1. **完善实体管理事件**: 注册、注销事件 +2. **添加发动机事件**: 启动、关闭事件 +3. **添加环境事件**: 天气变化事件 + +### 10.3 长期实施 +1. **性能监控事件系统** +2. **调试事件系统** +3. **统计分析事件系统** + +--- + +## 11. 事件命名规范 + +### 11.1 命名约定 +- **状态变化事件**: `[Entity][State]Event` (如: `MissileActivatedEvent`) +- **动作事件**: `[Entity][Action]Event` (如: `MissileFiredEvent`) +- **交互事件**: `[Source]To[Target][Action]Event` (如: `LaserToMissileIlluminationEvent`) + +### 11.2 属性约定 +- **必需属性**: `SenderId`, `Timestamp` +- **标识属性**: `TargetId`, `EntityId`等 +- **数据属性**: 具体的状态或参数信息 + +--- + +**文档结束** + +*此文档将随着系统发展持续更新,请定期检查事件完整性。* \ No newline at end of file diff --git a/tools/ComprehensiveMissileSimulator.cs b/tools/ComprehensiveMissileSimulator.cs index c2b8454..efad49e 100644 --- a/tools/ComprehensiveMissileSimulator.cs +++ b/tools/ComprehensiveMissileSimulator.cs @@ -1073,8 +1073,9 @@ namespace ThreatSource.Tools.MissileSimulation { Console.WriteLine("检测到现有实体,销毁并重新创建..."); - // 保存当前选中的导弹ID,避免在销毁时被清空 + // 保存当前选中的导弹ID和激活的干扰器列表,避免在销毁时被清空 string currentSelectedMissileId = SelectedMissileId; + var savedActiveJammings = activeJammings.ToList(); // 保存当前激活的干扰器列表 DestroyAllEntities(); @@ -1082,6 +1083,22 @@ namespace ThreatSource.Tools.MissileSimulation if (!string.IsNullOrEmpty(currentSelectedMissileId)) { CreateMissileAndRelatedEntities(currentSelectedMissileId); + + // 恢复用户选择的干扰器配置 + if (savedActiveJammings.Count > 0) + { + Console.WriteLine($"恢复用户选择的 {savedActiveJammings.Count} 个干扰器配置..."); + foreach (var jammingConfig in savedActiveJammings) + { + // 检查干扰器是否已创建 + if (jammers.ContainsKey(jammingConfig.JammerId)) + { + // 重新应用干扰配置 + ApplyJamming(jammingConfig.Type, jammingConfig.DisplayName, jammingConfig.JammerId, jammingConfig.Mode, jammingConfig.Target); + Console.WriteLine($"已激活干扰器: {jammingConfig.DisplayName}"); + } + } + } } else { @@ -1382,7 +1399,15 @@ namespace ThreatSource.Tools.MissileSimulation { return "(无干扰)"; } - return $"(已激活: {activeJammings.First().DisplayName})"; + + if (activeJammings.Count == 1) + { + return $"(已激活: {activeJammings.First().DisplayName})"; + } + else + { + return $"(已激活: {activeJammings.Count}个干扰器)"; + } } public List<(JammingType Type, string DisplayName, string JammerId, string Mode, string Target)> GetCurrentlyActiveJammings() diff --git a/tools/Program.cs b/tools/Program.cs index 45e3e09..51384b3 100644 --- a/tools/Program.cs +++ b/tools/Program.cs @@ -285,7 +285,8 @@ namespace ThreatSource.Tools.MissileSimulation } } - while (true) + bool backToMainMenu = false; + while (!backToMainMenu) { Console.WriteLine("\n--- 选择干扰方式 ---"); Console.WriteLine($"当前导弹: {simulator.SelectedMissileDisplayName}"); @@ -293,6 +294,7 @@ namespace ThreatSource.Tools.MissileSimulation if (availableJammingOptions.Length == 0) { Console.WriteLine("当前导弹类型没有可选择的干扰方式。"); + return; } else { @@ -305,14 +307,17 @@ namespace ThreatSource.Tools.MissileSimulation } } - Console.WriteLine(" 0. 返回主菜单"); - Console.Write("请选择切换状态的干扰项,或返回: "); + Console.WriteLine(" 0. 确认并返回主菜单"); + Console.Write("请选择干扰方式,或输入0确认并返回: "); string input = Console.ReadLine()?.ToLower() ?? string.Empty; + if (input == "0") - return; - - if (int.TryParse(input, out int choice)) + { + Console.WriteLine("干扰配置已确认,返回主菜单。"); + backToMainMenu = true; + } + else if (int.TryParse(input, out int choice)) { if (choice >= 1 && choice <= availableJammingOptions.Length) { @@ -320,11 +325,18 @@ namespace ThreatSource.Tools.MissileSimulation jammingStatus[choice - 1] = !jammingStatus[choice - 1]; // Toggle local status for display if (jammingStatus[choice - 1]) + { simulator.ApplyJamming(option.Type, option.DisplayName, option.JammerId, option.Mode, option.Target); + Console.WriteLine($"已激活: {option.DisplayName}"); + } else + { simulator.ClearJamming(option.Type, option.DisplayName, option.JammerId); + Console.WriteLine($"已停用: {option.DisplayName}"); + } - return; + // 更新当前状态显示(获取最新激活状态) + currentlyActiveJammingsFromSimulator = simulator.GetCurrentlyActiveJammings(); } else { @@ -333,7 +345,7 @@ namespace ThreatSource.Tools.MissileSimulation } else { - Console.WriteLine("无效输入,请输入数字。"); + Console.WriteLine("无效输入,请输入数字或'0'返回。"); } } }