1503 lines
46 KiB
Markdown
1503 lines
46 KiB
Markdown
# 威胁源仿真库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. 仿真管理接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 初始化威胁源仿真系统
|
||
/// </summary>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_Initialize();
|
||
|
||
/// <summary>
|
||
/// 销毁威胁源仿真系统
|
||
/// </summary>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_Shutdown();
|
||
|
||
/// <summary>
|
||
/// 创建仿真场景
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_CreateScenario(const char* scenarioId);
|
||
|
||
/// <summary>
|
||
/// 销毁仿真场景
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_DestroyScenario(const char* scenarioId);
|
||
|
||
/// <summary>
|
||
/// 开始仿真
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="timeStep">时间步长(秒)</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_StartSimulation(const char* scenarioId, double timeStep);
|
||
|
||
/// <summary>
|
||
/// 暂停仿真
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_PauseSimulation(const char* scenarioId);
|
||
|
||
/// <summary>
|
||
/// 恢复仿真
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_ResumeSimulation(const char* scenarioId);
|
||
|
||
/// <summary>
|
||
/// 停止仿真
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_StopSimulation(const char* scenarioId);
|
||
|
||
/// <summary>
|
||
/// 更新仿真
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="deltaTime">时间增量(秒)</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_UpdateSimulation(const char* scenarioId, double deltaTime);
|
||
|
||
/// <summary>
|
||
/// 获取仿真状态
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="state">输出状态 (0=停止, 1=运行, 2=暂停)</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetSimulationState(const char* scenarioId, int* state);
|
||
|
||
/// <summary>
|
||
/// 获取仿真时间
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="time">输出仿真时间</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetSimulationTime(const char* scenarioId, double* time);
|
||
|
||
// ============================================================================
|
||
// 3. 实体管理接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 创建导弹
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="missileId">导弹ID</param>
|
||
/// <param name="configPath">配置文件路径</param>
|
||
/// <param name="initialState">初始状态</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_CreateMissile(const char* scenarioId, const char* missileId,
|
||
const char* configPath, const TS_KinematicState* initialState);
|
||
|
||
/// <summary>
|
||
/// 创建目标
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="targetId">目标ID</param>
|
||
/// <param name="targetType">目标类型 (0=坦克, 1=装甲车, 2=建筑物)</param>
|
||
/// <param name="initialState">初始状态</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_CreateTarget(const char* scenarioId, const char* targetId,
|
||
int targetType, const TS_KinematicState* initialState);
|
||
|
||
/// <summary>
|
||
/// 创建指示器
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="indicatorId">指示器ID</param>
|
||
/// <param name="indicatorType">指示器类型 (0=激光指示器, 1=激光驾束仪, 2=红外测角仪)</param>
|
||
/// <param name="configPath">配置文件路径</param>
|
||
/// <param name="initialState">初始状态</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_CreateIndicator(const char* scenarioId, const char* indicatorId,
|
||
int indicatorType, const char* configPath,
|
||
const TS_KinematicState* initialState);
|
||
|
||
/// <summary>
|
||
/// 创建干扰器
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="jammerId">干扰器ID</param>
|
||
/// <param name="jammerType">干扰器类型 (0=激光干扰器, 1=红外干扰器, 2=毫米波干扰器)</param>
|
||
/// <param name="configPath">配置文件路径</param>
|
||
/// <param name="initialState">初始状态</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_CreateJammer(const char* scenarioId, const char* jammerId,
|
||
int jammerType, const char* configPath,
|
||
const TS_KinematicState* initialState);
|
||
|
||
/// <summary>
|
||
/// 销毁实体
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityId">实体ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_DestroyEntity(const char* scenarioId, const char* entityId);
|
||
|
||
/// <summary>
|
||
/// 激活实体
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityId">实体ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_ActivateEntity(const char* scenarioId, const char* entityId);
|
||
|
||
/// <summary>
|
||
/// 停用实体
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityId">实体ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_DeactivateEntity(const char* scenarioId, const char* entityId);
|
||
|
||
// ============================================================================
|
||
// 4. 实体控制接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 发射导弹
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="missileId">导弹ID</param>
|
||
/// <param name="targetId">目标ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_FireMissile(const char* scenarioId, const char* missileId, const char* targetId);
|
||
|
||
/// <summary>
|
||
/// 设置指示器目标
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="indicatorId">指示器ID</param>
|
||
/// <param name="targetId">目标ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetIndicatorTarget(const char* scenarioId, const char* indicatorId, const char* targetId);
|
||
|
||
/// <summary>
|
||
/// 启动干扰器
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="jammerId">干扰器ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_StartJammer(const char* scenarioId, const char* jammerId);
|
||
|
||
/// <summary>
|
||
/// 停止干扰器
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="jammerId">干扰器ID</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_StopJammer(const char* scenarioId, const char* jammerId);
|
||
|
||
// ============================================================================
|
||
// 5. 状态查询接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 获取实体状态
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityId">实体ID</param>
|
||
/// <param name="state">输出状态</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetEntityState(const char* scenarioId, const char* entityId, TS_KinematicState* state);
|
||
|
||
/// <summary>
|
||
/// 获取实体是否激活
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityId">实体ID</param>
|
||
/// <param name="isActive">输出是否激活</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_IsEntityActive(const char* scenarioId, const char* entityId, int* isActive);
|
||
|
||
/// <summary>
|
||
/// 获取导弹制导状态
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="missileId">导弹ID</param>
|
||
/// <param name="isGuided">输出是否制导</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetMissileGuidanceState(const char* scenarioId, const char* missileId, int* isGuided);
|
||
|
||
/// <summary>
|
||
/// 获取导弹飞行阶段
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="missileId">导弹ID</param>
|
||
/// <param name="stage">输出飞行阶段 (0=发射, 1=巡航, 2=制导, 3=终端)</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetMissileFlightStage(const char* scenarioId, const char* missileId, int* stage);
|
||
|
||
/// <summary>
|
||
/// 获取目标生命值
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="targetId">目标ID</param>
|
||
/// <param name="health">输出生命值</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetTargetHealth(const char* scenarioId, const char* targetId, double* health);
|
||
|
||
// ============================================================================
|
||
// 6. 环境控制接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 设置天气条件
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="weather">天气条件</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetWeather(const char* scenarioId, const TS_Weather* weather);
|
||
|
||
/// <summary>
|
||
/// 获取天气条件
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="weather">输出天气条件</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetWeather(const char* scenarioId, TS_Weather* weather);
|
||
|
||
// ============================================================================
|
||
// 7. 事件系统接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 注册事件回调函数
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="eventType">事件类型</param>
|
||
/// <param name="callback">回调函数指针</param>
|
||
/// <returns>错误码</returns>
|
||
typedef void (*TS_EventCallback)(const TS_Event* event);
|
||
THREATSOURCE_API int TS_RegisterEventCallback(const char* scenarioId, int eventType, TS_EventCallback callback);
|
||
|
||
/// <summary>
|
||
/// 注销事件回调函数
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="eventType">事件类型</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_UnregisterEventCallback(const char* scenarioId, int eventType);
|
||
|
||
/// <summary>
|
||
/// 轮询事件队列
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="events">输出事件数组</param>
|
||
/// <param name="maxEvents">最大事件数量</param>
|
||
/// <param name="actualEvents">实际事件数量</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_PollEvents(const char* scenarioId, TS_Event* events, int maxEvents, int* actualEvents);
|
||
|
||
/// <summary>
|
||
/// 发送外部事件
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="event">事件</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SendExternalEvent(const char* scenarioId, const TS_Event* event);
|
||
|
||
// ============================================================================
|
||
// 8. 工具函数接口
|
||
// ============================================================================
|
||
|
||
/// <summary>
|
||
/// 获取最后的错误信息
|
||
/// </summary>
|
||
/// <param name="buffer">输出缓冲区</param>
|
||
/// <param name="bufferSize">缓冲区大小</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetLastError(char* buffer, int bufferSize);
|
||
|
||
/// <summary>
|
||
/// 获取版本信息
|
||
/// </summary>
|
||
/// <param name="buffer">输出缓冲区</param>
|
||
/// <param name="bufferSize">缓冲区大小</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetVersion(char* buffer, int bufferSize);
|
||
|
||
/// <summary>
|
||
/// 获取支持的导弹类型列表
|
||
/// </summary>
|
||
/// <param name="types">输出类型数组</param>
|
||
/// <param name="maxTypes">最大类型数量</param>
|
||
/// <param name="actualTypes">实际类型数量</param>
|
||
/// <returns>错误码</returns>
|
||
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
|
||
{
|
||
/// <summary>
|
||
/// 威胁源仿真系统Unity管理器
|
||
/// </summary>
|
||
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<string, GameObject> entityObjects = new Dictionary<string, GameObject>();
|
||
|
||
// 事件回调
|
||
public event Action<string, string> OnMissileHit;
|
||
public event Action<string> OnTargetDestroyed;
|
||
public event Action<string, int> 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<MissileController>();
|
||
if (controller == null)
|
||
controller = missileObj.AddComponent<MissileController>();
|
||
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<StageChangeData>(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<EntityController>();
|
||
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
|
||
/// <summary>
|
||
/// 加载配置文件
|
||
/// </summary>
|
||
/// <param name="configPath">配置文件路径</param>
|
||
/// <param name="configData">输出配置数据JSON字符串</param>
|
||
/// <param name="bufferSize">缓冲区大小</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_LoadConfig(const char* configPath, char* configData, int bufferSize);
|
||
|
||
/// <summary>
|
||
/// 验证配置文件
|
||
/// </summary>
|
||
/// <param name="configPath">配置文件路径</param>
|
||
/// <param name="isValid">输出是否有效</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_ValidateConfig(const char* configPath, int* isValid);
|
||
|
||
/// <summary>
|
||
/// 获取默认配置
|
||
/// </summary>
|
||
/// <param name="entityType">实体类型</param>
|
||
/// <param name="configData">输出默认配置JSON字符串</param>
|
||
/// <param name="bufferSize">缓冲区大小</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetDefaultConfig(int entityType, char* configData, int bufferSize);
|
||
```
|
||
|
||
---
|
||
|
||
## 7. 性能优化建议
|
||
|
||
### 7.1 内存管理
|
||
|
||
1. **对象池模式**:为频繁创建/销毁的对象使用对象池
|
||
2. **批量操作**:批量更新多个实体状态
|
||
3. **延迟加载**:按需加载配置文件和资源
|
||
|
||
### 7.2 多线程支持
|
||
|
||
```c
|
||
/// <summary>
|
||
/// 设置仿真线程数
|
||
/// </summary>
|
||
/// <param name="threadCount">线程数量</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetThreadCount(int threadCount);
|
||
|
||
/// <summary>
|
||
/// 启用异步更新模式
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="enabled">是否启用</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetAsyncMode(const char* scenarioId, int enabled);
|
||
```
|
||
|
||
### 7.3 批量操作API
|
||
|
||
```c
|
||
/// <summary>
|
||
/// 批量获取实体状态
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityIds">实体ID数组</param>
|
||
/// <param name="entityCount">实体数量</param>
|
||
/// <param name="states">输出状态数组</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_GetEntityStatesBatch(const char* scenarioId, const char** entityIds,
|
||
int entityCount, TS_KinematicState* states);
|
||
|
||
/// <summary>
|
||
/// 批量更新实体状态
|
||
/// </summary>
|
||
/// <param name="scenarioId">场景ID</param>
|
||
/// <param name="entityIds">实体ID数组</param>
|
||
/// <param name="states">状态数组</param>
|
||
/// <param name="entityCount">实体数量</param>
|
||
/// <returns>错误码</returns>
|
||
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
|
||
/// <summary>
|
||
/// 设置日志级别
|
||
/// </summary>
|
||
/// <param name="level">日志级别 (0=关闭, 1=错误, 2=警告, 3=信息, 4=调试)</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetLogLevel(int level);
|
||
|
||
/// <summary>
|
||
/// 设置日志输出文件
|
||
/// </summary>
|
||
/// <param name="filePath">日志文件路径</param>
|
||
/// <returns>错误码</returns>
|
||
THREATSOURCE_API int TS_SetLogFile(const char* filePath);
|
||
|
||
/// <summary>
|
||
/// 注册日志回调函数
|
||
/// </summary>
|
||
/// <param name="callback">日志回调函数</param>
|
||
/// <returns>错误码</returns>
|
||
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 <stdio.h>
|
||
#include <stdlib.h>
|
||
|
||
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设计、集成方案、使用流程和示例代码。* |