CounterDroneBackend/docs/对接文档_Unity前端.md

256 lines
8.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 后端对接文档Unity 前端)
> **版本**V1.5
> **日期**2026-06-17
> **Unity 版本**2022.3.62f3c1
---
## 一、交付物
从仓库取以下内容,拖入 Unity 项目:
```
src/Unity/Assets/Plugins/ ← DLLCore + sqlite + JSON
src/Unity/Assets/Scripts/Managers/ ← 桥接脚本
将以下文件放到 Unity 项目 Assets/StreamingAssets/ 目录下:
data/defaults.json ← 默认数据(首次运行自动复制到 persistentDataPath
data/planner_config.json ← 规划器配置(同上)
```
---
## 二、快速开始
1.`defaults.json``planner_config.json` 放到 `Assets/StreamingAssets/`
2. 创建空 GameObject`SimulationBootstrap`
3. 运行 — 自动种子数据库,选一个 `[Demo]` 想定,启动仿真
> `SimulationBootstrap` 是前端开发的参考模板,展示预设模式(一行代码)和自定义模式两种路径。
---
## 三、完整工作流5 步)
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌──────────┐ ┌──────────┐
│ 基础数据 CRUD │ → │ 创建想定 │ → │ 运行仿真 │ → │ 生成报告 │ → │ 回放 │
│ DataService │ │ ScenarioMgr │ │ SimRunner │ │ ReportMgr │ │ Replay │
└─────────────┘ └─────────────┘ └─────────────┘ └──────────┘ └──────────┘
```
### 3.1 步骤 1管理基础数据
```csharp
var mgr = GetComponent<ScenarioManager>();
var ds = mgr.DataService;
// 列出所有
var drones = ds.GetAllDrones();
var ammo = ds.GetAllAmmo();
var units = ds.GetAllFireUnits();
// 新增
ds.SaveDrone(new DroneSpec { Id = "custom", Name = "自定义", TypicalSpeed = 100, ... });
// 删除
ds.DeleteDrone("custom");
// 7 类全覆盖DroneSpec / FireUnitSpec / SensorSpec / EnvironmentSpec
// FormationTemplate / RouteTemplate / AmmunitionSpec
```
### 3.2 步骤 2创建想定
```csharp
var scenario = GetComponent<ScenarioManager>();
// 方式 A预设想定最快
var demos = scenario.Search("Demo", null, null, 1, 100);
var taskId = demos.Items[0].Id;
// 方式 B自定义
var task = scenario.CreateTask("我的想定", "");
scenario.SaveScene(task.Id, new CombatScene { WindSpeed = 5, WindDirection = (int)WindDirection.E });
scenario.SaveTarget(task.Id, new TargetConfig { WaveId = "w1", Quantity = 1, TypicalSpeed = 200, TypicalAltitude = 500 });
scenario.SaveRoute(task.Id, "w1", new RoutePlan(), new List<Waypoint> {
new() { PosX = 0, PosY = 500, PosZ = 0, Speed = 200 },
new() { PosX = 10000, PosY = 500, PosZ = 0, Speed = 200 }
});
scenario.SaveDeployment(task.Id, new List<EquipmentDeployment> {
new() { EquipmentRole = 1, PlatformType = 1, Quantity = 1, PositionX = 5000, AerosolType = 0, MunitionCount = 8 }
});
scenario.SaveCloud(task.Id, new CloudDispersal { AerosolType = 0, DisperseHeight = 500 });
scenario.UpdateStep(task.Id, 5);
```
### 3.3 步骤 3运行仿真
```csharp
var runner = GetComponent<SimulationRunner>();
runner.LoadAndStart(taskId);
runner.Engine.TimeScale = 4f;
// 事件
runner.Engine.OnMunitionLaunched += m => { };
runner.Engine.OnCloudGenerated += c => { };
runner.Engine.OnDroneDestroyed += d => { };
runner.Engine.OnSimulationEnded += () => { };
// 逐帧
void Update() {
var result = runner.Engine.Tick(Time.deltaTime);
foreach (var snap in result.EntitySnapshots) {
// snap.EntityType, PosX/Y/Z, VelX/Y/Z, Hp, CloudRadius...
}
}
```
### 3.4 步骤 4生成报告
```csharp
var rm = GetComponent<ReportManager>();
var detail = scenario.GetDetail(taskId);
var report = rm.Generate(taskId, detail, runner.Engine.Events.ToList(),
runner.Engine.Drones[0].Status.ToString(), runner.Engine.SimulationTime);
string path = rm.Export(report.Id);
```
### 3.5 步骤 5回放
```csharp
var replay = GetComponent<ReplayController>();
replay.LoadReplay(taskId);
for (int i = 0; i < replay.TotalFrames; i++) {
var frame = replay.GetFrame(i);
// frame.SimulationTime, frame.EntitySnapshots...
}
```
---
## 四、Manager API 速查
### ScenarioManager — 基础数据 + 想定
```csharp
var mgr = GetComponent<ScenarioManager>();
// 基础数据 CRUD7 类)
mgr.DataService.GetAllAmmo() / SaveAmmo() / DeleteAmmo()
mgr.DataService.GetAllFireUnits() / GetAllDrones() / GetAllSensors()
mgr.DataService.GetAllEnvironments() / GetAllFormations() / GetAllRoutes()
// 想定 CRUD
mgr.CreateTask(name, "") / mgr.DeleteTask(id) / mgr.Search(kw, from, to, page, size)
mgr.SaveScene / SaveTarget / SaveDeployment / SaveCloud / SaveRoute / UpdateStep
mgr.GetDetail(id) TaskFullConfig
```
### SimulationRunner — 仿真执行
```csharp
var runner = GetComponent<SimulationRunner>();
runner.LoadAndStart(taskId);
runner.Engine.TimeScale = 4f;
runner.Engine.State / Drones / Clouds / Munitions / Platforms / DetectionEntities / Events
runner.Engine.Tick(dt) SimulationFrameResult { EntitySnapshots, NewEvents }
runner.Engine.OnMunitionLaunched / OnCloudGenerated / OnDroneDestroyed / ...
runner.Stop();
```
### ReportManager — 报告
```csharp
var rm = GetComponent<ReportManager>();
rm.Generate(taskId, detail, events, status, duration) SimulationReport
rm.Export(reportId) 文件路径
```
### ReplayController — 回放
```csharp
var replay = GetComponent<ReplayController>();
replay.LoadReplay(taskId);
replay.TotalFrames / replay.GetFrame(index)
```
---
## 五、EntitySnapshot每帧推送
| 字段 | 类型 | 说明 |
|------|------|------|
| `EntityId` | string | 实体唯一 ID |
| `EntityType` | enum | Drone / Platform / Munition / Cloud / DetectionEquip |
| `PosX/Y/Z` | float | 三维位置 |
| `VelX/Y/Z` | float | 瞬时速度 (m/s) |
| `Hp` | float | 无人机血量 (0~1) |
| `DamageStage` | int | 损伤阶段 |
| `PlatformStateStr` | string | Idle / FlyingToTarget / ReadyToRelease |
| `CloudRadius` | float | 云团有效半径 |
| `CloudOpacity` | float | 不透明度 (0~1) |
| `CloudPhase` | int | 扩散阶段 (1/2/3) |
| `CloudElapsed` | float | 已存在时间 (s) |
---
## 六、实体属性速查
| 实体 | 关键属性 |
|------|------|
| **DroneEntity** | Id, PosX/Y/Z, Hp, Status, Type, Wingspan, CruiseSpeed, Route, TraveledArc, TotalArc, Progress |
| **CloudEntity** | Id, PosX/Y/Z, Radius, Density, Phase, Elapsed, IsDissipated |
| **MunitionEntity** | Id, PosX/Y/Z, Velocity, Start, LaunchTime, ElapsedTime, LaunchAngle, Azimuth, MuzzleVelocity, FlightDuration, Target, HasArrived |
| **PlatformEntity** | Id, PosX/Y/Z, CurrentVelocity, State, MunitionCount, Cooldown, MuzzleVelocity, CruiseSpeed, ReleaseAltitude, Target, FlightDistance |
| **DetectionEntity** | Id, PosX/Y/Z, Source, IsInRange(), IsDetected() |
---
## 七、规格类命名对照
| 旧名 | 新名 | SQLite 表 |
|------|------|------|
| `TargetPreset` | `DroneSpec` | `DroneSpec` |
| `DetectionPreset` | `SensorSpec` | `SensorSpec` |
| `WeatherPreset` | `EnvironmentSpec` | `EnvironmentSpec` |
| `FireUnitTemplate` | `FireUnitSpec` | `FireUnitSpec` |
| `RoutePreset` | `RouteTemplate` | `RouteTemplate` |
| `FormationTemplate` | 不变 | `FormationTemplate` |
| `AmmunitionSpec` | 不变 | `AmmunitionSpec` |
---
## 八、默认数据
首次运行自动种子,含 6 个 `[Demo]` 预设想定:
| 类别 | 示例 ID |
|------|------|
| 弹药 | `inert` / `active` / `fuel` |
| 编队 | `single` / `line-3` / `swarm-10` |
| 航线 | `5km-h500` / `10km-h500` / `20km-h500` |
| 火力单元 | `ground-light` / `air-standard` |
| 无人机 | `shahed` / `quadcopter` / `cruise-missile` |
| 传感器 | `radar-mr` / `eo-station` |
| 环境 | `sunny-calm` / `fog` / `night` |
---
## 九、更新后端
```bash
cd src/CounterDrone.Core
dotnet publish -c Release -o ../../unity_plugins
```
---
## 十、参考
| 文档 | 位置 |
|------|------|
| 架构设计 | `docs/design/architecture/总体架构设计.md` |
| 实体事件映射 | `docs/design/technical/仿真器实体与事件映射.md` |
| 测试状态 | **243 测试11 秒(全部通过)** |