45 changed files with 4737 additions and 1226 deletions
+5
View File
@@ -16,3 +16,8 @@ zlt-web/react-web-next/public/cesium/
zlt-web/yingyan/public/cesium/ zlt-web/yingyan/public/cesium/
zlt-web/react-web-next/dist.zip
zlt-web/yingyan/dist.zip
@@ -49,7 +49,7 @@ public class BoatCommandManager {
* 发送命令 * 发送命令
* *
* @param deviceSn 设备SN * @param deviceSn 设备SN
* @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo) * @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo/flighttask_slowly)
* @param params 命令参数 * @param params 命令参数
* @return 命令ID * @return 命令ID
*/ */
@@ -187,6 +187,12 @@ public class BoatCommandManager {
} }
break; break;
case "flighttask_slowly":
// 慢速行驶
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -2,6 +2,7 @@ package com.central.device.controller;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
@@ -61,6 +62,15 @@ public class BoatCommandController {
return Result.succeed(null, "终止任务指令已下发"); return Result.succeed(null, "终止任务指令已下发");
} }
@Operation(summary = "慢速行驶")
@PostMapping("/slowly")
public Result<Void> slowly(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
@Operation(summary = "返回起点") @Operation(summary = "返回起点")
@PostMapping("/return") @PostMapping("/return")
public Result<Void> returnToStart( public Result<Void> returnToStart(
@@ -13,9 +13,19 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
/** /**
@@ -56,6 +66,21 @@ public class BoatRouteController {
return Result.succeed(detail); return Result.succeed(detail);
} }
@Operation(summary = "分页查询无人船航线列表")
@GetMapping("/page")
public Result<Page<BoatRouteListVO>> pageRoutes(
@Parameter(description = "航线名称") @RequestParam(required = false) String routeName,
@Parameter(description = "设备SN") @RequestParam(required = false) String deviceSn,
@Parameter(description = "创建开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "创建结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
Page<BoatRouteListVO> pageResult = boatRouteService.pageRoutes(routeName, deviceSn, startTime, endTime, page, size);
return Result.succeed(pageResult);
}
@Operation(summary = "获取设备绑定的航线列表") @Operation(summary = "获取设备绑定的航线列表")
@GetMapping("/list/device/{deviceSn}") @GetMapping("/list/device/{deviceSn}")
public Result<List<BoatRouteListVO>> listByDeviceSn( public Result<List<BoatRouteListVO>> listByDeviceSn(
@@ -0,0 +1,25 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* 无人船慢速行驶DTO
*
* @author Codex
* @date 2026-04-20
*/
@Data
@Schema(description = "无人船慢速行驶请求")
public class BoatSlowlyDriveDTO {
@Schema(description = "任务编码(对应 order_no)", required = true, example = "562026040600002")
@NotBlank(message = "任务编码不能为空")
private String missionCode;
@Schema(description = "慢速行驶速度", required = true, example = "30")
@NotNull(message = "速度不能为空")
private Integer speed;
}
@@ -1,6 +1,7 @@
package com.central.device.service; package com.central.device.service;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
/** /**
* 无人船控制服务接口 * 无人船控制服务接口
@@ -44,6 +45,14 @@ public interface IBoatControlService {
*/ */
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
/**
* 慢速行驶
*
* @param deviceSn 设备SN
* @param dto 慢速行驶参数
*/
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
/** /**
* 返回起点 * 返回起点
* *
@@ -9,6 +9,7 @@ import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO; import com.central.device.model.vo.BoatRouteListVO;
import com.central.device.model.vo.RouteValidateResultVO; import com.central.device.model.vo.RouteValidateResultVO;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
/** /**
@@ -69,6 +70,20 @@ public interface IBoatRouteService extends IService<BoatRoute> {
*/ */
Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size); Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size);
/**
* 分页查询无人船航线列表
*
* @param routeName 航线名称
* @param deviceSn 设备SN
* @param startTime 创建开始时间
* @param endTime 创建结束时间
* @param page 页码
* @param size 每页数量
* @return 航线分页列表
*/
Page<BoatRouteListVO> pageRoutes(String routeName, String deviceSn, LocalDateTime startTime, LocalDateTime endTime,
Integer page, Integer size);
/** /**
* 绑定航线到设备 * 绑定航线到设备
* *
@@ -6,6 +6,7 @@ import com.central.device.boat.entity.BoatRoute;
import com.central.device.boat.manager.BoatCommandManager; import com.central.device.boat.manager.BoatCommandManager;
import com.central.device.model.AgeDevice; import com.central.device.model.AgeDevice;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IAgeDeviceService; import com.central.device.service.IAgeDeviceService;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import com.central.device.service.IBoatRouteService; import com.central.device.service.IBoatRouteService;
@@ -86,6 +87,18 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
log.info("无人船慢速行驶: deviceSn={}, missionCode={}, speed={}",
deviceSn, dto.getMissionCode(), dto.getSpeed());
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
log.info("无人船返回起点: deviceSn={}", deviceSn); log.info("无人船返回起点: deviceSn={}", deviceSn);
@@ -35,6 +35,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -314,6 +315,34 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
return resultPage; return resultPage;
} }
@Override
public Page<BoatRouteListVO> pageRoutes(String routeName, String deviceSn, LocalDateTime startTime,
LocalDateTime endTime, Integer page, Integer size) {
String anchor = LoginUserContextHolder.getCurrentTenantId();
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
}
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
Page<BoatRoute> pageParam = new Page<>(page, size);
LambdaQueryWrapper<BoatRoute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(anchor != null && !anchor.isEmpty(), BoatRoute::getTenantId, anchor)
.eq(BoatRoute::getDeleted, 0)
.like(StrUtil.isNotBlank(routeName), BoatRoute::getRouteName, StrUtil.trim(routeName))
.like(StrUtil.isNotBlank(deviceSn), BoatRoute::getDeviceSn, StrUtil.trim(deviceSn))
.ge(startTime != null, BoatRoute::getCreateTime, startTime)
.le(endTime != null, BoatRoute::getCreateTime, endTime)
.orderByDesc(BoatRoute::getCreateTime);
Page<BoatRoute> routePage = this.page(pageParam, wrapper);
Page<BoatRouteListVO> resultPage = new Page<>(page, size, routePage.getTotal());
resultPage.setRecords(convertToListVO(routePage.getRecords()));
return resultPage;
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void bindToDevice(String routeId, String deviceSn) { public void bindToDevice(String routeId, String deviceSn) {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,93 @@
{
"routeId": "33415e9578a74c59a16a5d2d3fee492c",
"routeName": "Manual Test Route 2026/4/6 16:16:59",
"deviceSn": "12345678",
"deviceName": "锦鲤一号",
"scenicId": 1,
"waypointCount": 5,
"totalDistance": 320.65,
"totalDuration": 1603,
"cruiseSpeed": 0.2,
"loopEnabled": false,
"loopCount": 1,
"returnMode": "origin",
"safeDistance": 5,
"startPoint": "121.89807344122099,30.87373280450406",
"endPoint": "121.8984168707936,30.873953677640834",
"status": 1,
"statusDesc": "Local Draft",
"waypoints": [
{
"waypointId": "289feeecdd554c3989759a584c777c09",
"waypointIndex": 0,
"longitude": 121.89807344122099,
"latitude": 30.87373280450406,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "起点",
"actions": null,
"remark": null
},
{
"waypointId": "e1b7444d7d4942e2886b05f6b76f8392",
"waypointIndex": 1,
"longitude": 121.89865297403038,
"latitude": 30.874119329720497,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点1",
"actions": null,
"remark": null
},
{
"waypointId": "ab214e90d4f6495d85abfeae791a6b53",
"waypointIndex": 2,
"longitude": 121.89949003611937,
"latitude": 30.874809529580364,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点2",
"actions": null,
"remark": null
},
{
"waypointId": "e54c7b84314643538e9648d738a88ef7",
"waypointIndex": 3,
"longitude": 121.89906077613658,
"latitude": 30.874478239874847,
"speed": 2,
"stayDuration": 0,
"headingAngle": 233,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点3",
"actions": null,
"remark": null
},
{
"waypointId": "2454526441a54e989fa4739c01510c18",
"waypointIndex": 4,
"longitude": 121.8984168707936,
"latitude": 30.873953677640834,
"speed": 2,
"stayDuration": 0,
"headingAngle": null,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "终点",
"actions": null,
"remark": null
}
],
"createTime": "2026-04-06 08:16:59",
"updateTime": "2026-04-06 08:16:59"
}
@@ -78,6 +78,22 @@
} }
``` ```
### 2.5 慢速行驶(flighttask_slowly)
```json
{
"messageType": "WRITE_PROPERTY",
"deviceId": "12345678",
"properties": {
"data": {
"order_no": "562026040600002",
"speed": 30
},
"method": "flighttask_slowly"
}
}
```
## 三、架构设计原则 ## 三、架构设计原则
### 3.1 核心原则:不修改无人机代码,独立 boat 包 ### 3.1 核心原则:不修改无人机代码,独立 boat 包
@@ -169,9 +185,11 @@
| 文件 | 改动内容 | | 文件 | 改动内容 |
|------|----------| |------|----------|
| `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 | | `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask` 方法 | | `BoatCommandManager.java` | 新增 `flighttask_slowly` 指令组包逻辑,向设备透传 `order_no` 和 `speed` |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令 | | `BoatSlowlyDriveDTO.java` | 新增慢速行驶请求模型,封装 `missionCode` 和 `speed` |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo 接口 | | `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask`、`slowly` 方法 |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令;新增慢速行驶实现 |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo、slowly 接口 |
## 五、详细实现方案 ## 五、详细实现方案
@@ -279,6 +297,10 @@ public class BoatCommandManager {
case "flighttask_undo": case "flighttask_undo":
data.put("order_no", params.getString("order_no")); data.put("order_no", params.getString("order_no"));
break; break;
case "flighttask_slowly":
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -406,6 +428,7 @@ void resume(String deviceSn, String missionCode);
```java ```java
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
``` ```
--- ---
@@ -463,6 +486,14 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject()); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
@@ -512,6 +543,17 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
#### 新增慢速行驶接口
```java
@PostMapping("/slowly")
public Result<Void> slowly(@RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
```
--- ---
## 六、接口变更汇总 ## 六、接口变更汇总
@@ -521,6 +563,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 方法 | 路径 | 参数 | 说明 | | 方法 | 路径 | 参数 | 说明 |
|------|------|------|------| |------|------|------|------|
| POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 | | POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 |
| POST | `/device/boat/command/slowly` | `deviceSn` + Body(`missionCode`,`speed`) | 下发慢速行驶指令 |
### 修改接口 ### 修改接口
@@ -549,6 +592,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 | | 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 |
| 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 | | 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 |
| 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 | | 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 |
| 4 | `model/dto/BoatSlowlyDriveDTO.java` | **新建** | 无人船慢速行驶请求模型 |
## 八、修改文件清单 ## 八、修改文件清单
@@ -556,9 +600,10 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
|---|---------|----------|------| |---|---------|----------|------|
| 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) | | 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) |
| 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 | | 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| 3 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增方法 | | 3 | `boat/manager/BoatCommandManager.java` | 修改 | 新增 `flighttask_slowly` 组包逻辑 |
| 4 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发 | | 4 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增 `slowly` 方法 |
| 5 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo | | 5 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发,并新增慢速行驶实现 |
| 6 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo、slowly |
--- ---
@@ -600,10 +645,32 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
### 无人船慢速行驶指令(新增)
```json
{
"type": "sub",
"topic": "/device-message-sender/ship/{deviceSn}",
"parameter": {
"messageType": "WRITE_PROPERTY",
"properties": {
"method": "flighttask_slowly",
"data": {
"order_no": "562026040600002",
"speed": 30
}
},
"headers": { "async": false }
},
"id": "{commandId}"
}
```
**区别**: **区别**:
1. topic 路径中产品标识不同:`AutoDock3` vs `ship` 1. topic 路径中产品标识不同:`AutoDock3` vs `ship`
2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no` 2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no`
3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls` 3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls`
4. 无人船的慢速行驶指令 data 中需要携带 `order_no`、`speed`
--- ---
@@ -689,3 +756,4 @@ data: ping
2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。 2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。
3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。 3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。
4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。 4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。
5. **慢速行驶速度的单位和范围**:当前按设备协议直接透传 `speed`,示例值为 `30`。如果设备端对单位、最小值、最大值有明确限制,需要继续补充参数校验。
+4
View File
@@ -47,3 +47,7 @@ build
zlt-web/react-web-next/public/cesium/ zlt-web/react-web-next/public/cesium/
zlt-web/yingyan/public/cesium/ zlt-web/yingyan/public/cesium/
zlt-web/react-web-next/dist.zip
zlt-web/yingyan/dist.zip
+1
View File
@@ -51,6 +51,7 @@ export default [
{ {
path: '/device', path: '/device',
routes: [ routes: [
{ path: '/device/boatRoute.html', name: '无人船航线管理', component: '@/pages/device/BoatRoute' },
{ path: '/device/wayline.html', component: '@/pages/device/Wayline' }, { path: '/device/wayline.html', component: '@/pages/device/Wayline' },
{ path: '/device/device.html', component: '@/pages/device/Device' }, { path: '/device/device.html', component: '@/pages/device/Device' },
// 3D模型管理 // 3D模型管理
Binary file not shown.
+3 -3
View File
@@ -15,8 +15,8 @@
"prebuild:test:mgnt": "npm run copy:cesium", "prebuild:test:mgnt": "npm run copy:cesium",
"prebuild:pre:mgnt": "npm run copy:cesium", "prebuild:pre:mgnt": "npm run copy:cesium",
"prebuild:prod:mgnt": "npm run copy:cesium", "prebuild:prod:mgnt": "npm run copy:cesium",
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev",
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
@@ -24,7 +24,7 @@
"build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build", "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build",
"build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build",
"build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=https://test.goflytec.com umi build", "build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=https://test.goflytec.com umi build",
"build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://local.goflytec.com umi build", "build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=https://yeehaitec.com umi build",
"build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build", "build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build",
"lint": "eslint --ext .ts,.tsx src", "lint": "eslint --ext .ts,.tsx src",
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
@@ -0,0 +1,115 @@
import React, { useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { Alert, Button, Descriptions, Space, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/lib/upload/interface';
import type { BoatRoutePayload } from '@/services/boatRoute';
import { parseBoatRouteJson } from './routeJson';
interface BoatRouteCreateModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: BoatRoutePayload) => Promise<boolean>;
}
const readFileText = (file: File) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result || ''));
reader.onerror = () => reject(new Error('读取文件失败'));
reader.readAsText(file, 'utf-8');
});
const BoatRouteCreateModal: React.FC<BoatRouteCreateModalProps> = ({ visible, onVisibleChange, onFinish }) => {
const [fileList, setFileList] = useState<UploadFile[]>([]);
const [parsedPayload, setParsedPayload] = useState<BoatRoutePayload | null>(null);
const [routeName, setRouteName] = useState('');
const reset = () => {
setFileList([]);
setParsedPayload(null);
setRouteName('');
};
const handleFile = async (file: File) => {
if (!routeName.trim()) {
message.warning('请先输入航线名称');
return Upload.LIST_IGNORE;
}
try {
const text = await readFileText(file);
const payload = parseBoatRouteJson(text, routeName.trim());
setParsedPayload(payload);
setFileList([{ uid: file.name, name: file.name, status: 'done' }]);
message.success(`解析成功,共 ${payload.waypoints.length} 个航点`);
} catch (error: any) {
setParsedPayload(null);
setFileList([]);
message.error(error?.message || 'JSON 文件解析失败');
}
return false;
};
return (
<ModalForm<{ routeName: string }>
title="新增无人船航线"
visible={visible}
width={720}
modalProps={{ destroyOnClose: true }}
onVisibleChange={(nextVisible) => {
onVisibleChange(nextVisible);
if (!nextVisible) reset();
}}
onFinish={async () => {
if (!parsedPayload) {
message.warning('请上传并解析航线 JSON 文件');
return false;
}
const success = await onFinish({ ...parsedPayload, routeName: routeName.trim() });
if (success) reset();
return success;
}}
>
<ProFormText
name="routeName"
label="航线名称"
placeholder="请输入航线名称"
rules={[{ required: true, message: '请输入航线名称' }]}
fieldProps={{
value: routeName,
onChange: (event) => {
setRouteName(event.target.value);
setParsedPayload(null);
setFileList([]);
},
}}
/>
<Upload accept=".json,application/json" maxCount={1} fileList={fileList} beforeUpload={handleFile} onRemove={() => {
setParsedPayload(null);
setFileList([]);
}}>
<Button icon={<UploadOutlined />}>选择航线 JSON 文件</Button>
</Upload>
<Alert style={{ marginTop: 16 }} type="info" showIcon message="上传示例结构可参考后端 doc/waypoints.json,系统会读取 waypoints、设备 SN、巡航速度、循环设置等字段。" />
{parsedPayload && (
<Descriptions size="small" column={2} bordered style={{ marginTop: 16 }}>
<Descriptions.Item label="设备 SN">{parsedPayload.deviceSn || '--'}</Descriptions.Item>
<Descriptions.Item label="航点数量">{parsedPayload.waypoints.length}</Descriptions.Item>
<Descriptions.Item label="巡航速度">{parsedPayload.cruiseSpeed ?? '--'} m/s</Descriptions.Item>
<Descriptions.Item label="安全距离">{parsedPayload.safeDistance ?? '--'} m</Descriptions.Item>
<Descriptions.Item label="循环航行">{parsedPayload.loopEnabled ? '是' : '否'}</Descriptions.Item>
<Descriptions.Item label="结束动作">{parsedPayload.returnMode || '--'}</Descriptions.Item>
</Descriptions>
)}
<Space style={{ display: 'none' }} />
</ModalForm>
);
};
export default BoatRouteCreateModal;
@@ -0,0 +1,286 @@
import React, { useEffect, useState } from 'react';
import { ModalForm, ProFormDigit, ProFormSelect, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Button, Card, Collapse, Empty, Form, Input, InputNumber, Modal, Space, Table, Tabs, Tag, message } from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import type { BoatRouteDetail, BoatRoutePayload, BoatWaypoint } from '@/services/boatRoute';
import { boatRouteApi } from '@/services/boatRoute';
import { buildUpdatePayload, normalizeWaypoint } from './routeJson';
interface BoatRouteEditModalProps {
visible: boolean;
routeId?: string;
onVisibleChange: (visible: boolean) => void;
onFinish: (routeId: string, values: Partial<BoatRoutePayload>) => Promise<boolean>;
}
const ACTION_TYPE_OPTIONS = [
{ label: '拍照', value: 'photo' },
{ label: '开始录像', value: 'video_start' },
{ label: '停止录像', value: 'video_stop' },
{ label: '鸣笛', value: 'horn' },
{ label: '灯光控制', value: 'light' },
];
const TURN_MODE_OPTIONS = [
{ label: '平滑转弯', value: 'smooth' },
{ label: '急转弯', value: 'sharp' },
];
const RETURN_MODE_OPTIONS = [
{ label: '返回起点', value: 'return_start' },
{ label: '原地停留', value: 'stay' },
{ label: '保持原文件值', value: 'origin' },
];
const BoatRouteEditModal: React.FC<BoatRouteEditModalProps> = ({ visible, routeId, onVisibleChange, onFinish }) => {
const [form] = Form.useForm();
const [waypointForm] = Form.useForm();
const [actionForm] = Form.useForm();
const [loading, setLoading] = useState(false);
const [detail, setDetail] = useState<BoatRouteDetail | null>(null);
const [waypoints, setWaypoints] = useState<BoatWaypoint[]>([]);
const [waypointOpen, setWaypointOpen] = useState(false);
const [editingWaypointIndex, setEditingWaypointIndex] = useState<number | null>(null);
const [actionOpen, setActionOpen] = useState(false);
const [editingActionIndex, setEditingActionIndex] = useState<number | null>(null);
const loadDetail = async () => {
if (!visible || !routeId) return;
setLoading(true);
try {
const data = await boatRouteApi.detail(routeId);
setDetail(data);
setWaypoints((data.waypoints || []).map((item, index) => normalizeWaypoint(item, index)));
form.setFieldsValue({
routeName: data.routeName,
cruiseSpeed: data.cruiseSpeed,
loopEnabled: data.loopEnabled,
loopCount: data.loopCount,
returnMode: data.returnMode || 'return_start',
safeDistance: data.safeDistance,
boundaryId: data.boundaryId,
remark: data.remark,
showInModel: data.showInModel || 0,
});
} catch {
message.error('加载航线详情失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadDetail();
}, [visible, routeId]);
const closeWaypoint = () => {
setWaypointOpen(false);
setEditingWaypointIndex(null);
waypointForm.resetFields();
};
const openWaypoint = (record?: BoatWaypoint, index?: number) => {
setEditingWaypointIndex(index ?? null);
waypointForm.setFieldsValue(record || {
waypointIndex: waypoints.length,
turnMode: 'smooth',
stayDuration: 0,
isKeyPoint: false,
actions: [],
});
setWaypointOpen(true);
};
const saveWaypoint = async () => {
const values = await waypointForm.validateFields();
const normalized = normalizeWaypoint(values, editingWaypointIndex ?? waypoints.length);
setWaypoints((list) => {
if (editingWaypointIndex === null) return [...list, normalized];
return list.map((item, index) => (index === editingWaypointIndex ? { ...item, ...normalized } : item));
});
closeWaypoint();
};
const removeWaypoint = (index: number) => {
Modal.confirm({
title: `确认删除第 ${index + 1} 个航点?`,
onOk: () => setWaypoints((list) => list.filter((_, itemIndex) => itemIndex !== index)),
});
};
const currentActions = Form.useWatch('actions', waypointForm) || [];
const openAction = (record?: any, index?: number) => {
setEditingActionIndex(index ?? null);
actionForm.setFieldsValue({
actionType: record?.actionType || 'photo',
duration: record?.duration ?? 0,
paramsText: record?.params ? JSON.stringify(record.params, null, 2) : '',
});
setActionOpen(true);
};
const saveAction = async () => {
const values = await actionForm.validateFields();
let params: any = undefined;
if (values.paramsText) {
try {
params = JSON.parse(values.paramsText);
} catch {
message.error('动作参数必须是合法 JSON');
return;
}
}
const nextAction = { actionType: values.actionType, duration: values.duration, params };
const actions = [...currentActions];
if (editingActionIndex === null) actions.push(nextAction);
else actions[editingActionIndex] = nextAction;
waypointForm.setFieldsValue({ actions });
setActionOpen(false);
setEditingActionIndex(null);
actionForm.resetFields();
};
const removeAction = (index: number) => {
waypointForm.setFieldsValue({ actions: currentActions.filter((_: any, itemIndex: number) => itemIndex !== index) });
};
const waypointColumns: ColumnsType<BoatWaypoint> = [
{ title: '序号', dataIndex: 'waypointIndex', width: 80, render: (_, __, index) => index + 1 },
{ title: '航点名称', dataIndex: 'pointName', width: 140 },
{ title: '经度', dataIndex: 'longitude', width: 140 },
{ title: '纬度', dataIndex: 'latitude', width: 140 },
{ title: '速度(m/s)', dataIndex: 'speed', width: 100 },
{ title: '停留(秒)', dataIndex: 'stayDuration', width: 100 },
{ title: '动作数', dataIndex: 'actions', width: 90, render: (actions) => (actions?.length || 0) },
{
title: '操作',
width: 140,
fixed: 'right',
render: (_, record, index) => (
<Space>
<a onClick={() => openWaypoint(record, index)}><EditOutlined /> 编辑</a>
<a style={{ color: '#ff4d4f' }} onClick={() => removeWaypoint(index)}><DeleteOutlined /> 删除</a>
</Space>
),
},
];
const actionColumns: ColumnsType<any> = [
{ title: '动作类型', dataIndex: 'actionType', render: (value) => ACTION_TYPE_OPTIONS.find((item) => item.value === value)?.label || value },
{ title: '持续时间(秒)', dataIndex: 'duration', width: 120 },
{ title: '参数', dataIndex: 'params', ellipsis: true, render: (value) => value ? JSON.stringify(value) : '--' },
{
title: '操作',
width: 120,
render: (_, record, index) => (
<Space>
<a onClick={() => openAction(record, index)}>编辑</a>
<a style={{ color: '#ff4d4f' }} onClick={() => removeAction(index)}>删除</a>
</Space>
),
},
];
return (
<>
<ModalForm
form={form}
title="编辑无人船航线"
visible={visible}
width={1100}
modalProps={{ destroyOnClose: true }}
onVisibleChange={(nextVisible) => {
onVisibleChange(nextVisible);
if (!nextVisible) {
setDetail(null);
setWaypoints([]);
form.resetFields();
}
}}
onFinish={async (values) => {
if (!routeId || !detail) return false;
if (!waypoints.length) {
message.warning('航点不能为空');
return false;
}
const payload = buildUpdatePayload({ ...detail, ...values }, waypoints);
return onFinish(routeId, payload);
}}
>
<Tabs defaultActiveKey="base">
<Tabs.TabPane tab="基础信息" key="base">
{loading ? <Card loading size="small" /> : null}
<ProFormText name="routeName" label="航线名称" rules={[{ required: true, message: '请输入航线名称' }]} />
<ProFormDigit name="cruiseSpeed" label="巡航速度(m/s)" min={0.1} fieldProps={{ precision: 2 }} />
<ProFormSwitch name="loopEnabled" label="循环航行" />
<ProFormDigit name="loopCount" label="循环次数" min={-1} />
<ProFormSelect name="returnMode" label="结束动作" options={RETURN_MODE_OPTIONS} />
<ProFormDigit name="safeDistance" label="安全距离(米)" min={0} fieldProps={{ precision: 2 }} />
<ProFormSelect name="showInModel" label="模型中显示" options={[{ label: '否', value: 0 }, { label: '是', value: 1 }]} />
<ProFormText name="boundaryId" label="水域边界ID" />
<ProFormTextArea name="remark" label="备注" />
</Tabs.TabPane>
<Tabs.TabPane tab={`航点与动作(${waypoints.length})`} key="waypoints">
<Card
size="small"
title={<Space>航点列表<Tag color="blue">{waypoints.length} 个航点</Tag></Space>}
extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => openWaypoint()}>新增航点</Button>}
>
<Table
rowKey={(record, index) => record.waypointId || String(index)}
columns={waypointColumns}
dataSource={waypoints}
size="small"
scroll={{ x: 1000, y: 460 }}
pagination={{ pageSize: 10, showSizeChanger: true }}
expandable={{
expandedRowRender: (record) => (
record.actions?.length ? (
<Table rowKey={(_, index) => String(index)} columns={actionColumns.slice(0, 3)} dataSource={record.actions} pagination={false} size="small" />
) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无航点动作" />
),
}}
/>
</Card>
</Tabs.TabPane>
</Tabs>
</ModalForm>
<Modal title={editingWaypointIndex === null ? '新增航点' : '编辑航点'} visible={waypointOpen} width={820} onOk={saveWaypoint} onCancel={closeWaypoint} destroyOnClose>
<Form form={waypointForm} layout="vertical">
<Form.Item name="waypointIndex" label="航点序号"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="pointName" label="航点名称"><Input /></Form.Item>
<Form.Item name="longitude" label="经度" rules={[{ required: true, message: '请输入经度' }]}><InputNumber precision={8} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="latitude" label="纬度" rules={[{ required: true, message: '请输入纬度' }]}><InputNumber precision={8} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="speed" label="速度(m/s)"><InputNumber min={0} precision={2} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="stayDuration" label="停留时间(秒)"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="turnMode" label="转弯模式"><ProFormSelect noStyle options={TURN_MODE_OPTIONS} /></Form.Item>
<Form.Item name="isKeyPoint" label="关键点"><ProFormSwitch noStyle /></Form.Item>
<Form.Item name="remark" label="备注"><Input.TextArea rows={2} /></Form.Item>
<Form.Item name="actions" hidden><Input /></Form.Item>
<Collapse>
<Collapse.Panel header={`航点动作(${currentActions.length})`} key="actions" extra={<Button size="small" type="link" icon={<PlusOutlined />} onClick={(event) => { event.stopPropagation(); openAction(); }}>新增动作</Button>}>
<Table rowKey={(_, index) => String(index)} columns={actionColumns} dataSource={currentActions} pagination={false} size="small" />
</Collapse.Panel>
</Collapse>
</Form>
</Modal>
<Modal title={editingActionIndex === null ? '新增动作' : '编辑动作'} visible={actionOpen} onOk={saveAction} onCancel={() => setActionOpen(false)} destroyOnClose>
<Form form={actionForm} layout="vertical">
<Form.Item name="actionType" label="动作类型" rules={[{ required: true, message: '请选择动作类型' }]}>
<ProFormSelect noStyle options={ACTION_TYPE_OPTIONS} />
</Form.Item>
<Form.Item name="duration" label="持续时间(秒)"><InputNumber min={0} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="paramsText" label="动作参数(JSON)"><Input.TextArea rows={5} placeholder='例如:{"volume":80}' /></Form.Item>
</Form>
</Modal>
</>
);
};
export default BoatRouteEditModal;
@@ -0,0 +1,72 @@
import type { BoatRoutePayload, BoatWaypoint, BoatWaypointAction } from '@/services/boatRoute';
const toNumber = (value: any, fallback?: number) => {
if (value === undefined || value === null || value === '') return fallback;
const num = Number(value);
return Number.isFinite(num) ? num : fallback;
};
const normalizeAction = (action: any): BoatWaypointAction => ({
actionType: action?.actionType,
duration: toNumber(action?.duration, 0),
params: action?.params ?? undefined,
});
export const normalizeWaypoint = (waypoint: any, index: number): BoatWaypoint => ({
waypointId: waypoint?.waypointId,
waypointIndex: toNumber(waypoint?.waypointIndex, index),
longitude: toNumber(waypoint?.longitude),
latitude: toNumber(waypoint?.latitude),
speed: toNumber(waypoint?.speed),
stayDuration: toNumber(waypoint?.stayDuration, 0),
headingAngle: toNumber(waypoint?.headingAngle),
turnMode: waypoint?.turnMode || 'smooth',
isKeyPoint: Boolean(waypoint?.isKeyPoint),
pointName: waypoint?.pointName || `航点${index + 1}`,
actions: Array.isArray(waypoint?.actions) ? waypoint.actions.map(normalizeAction) : [],
remark: waypoint?.remark || undefined,
});
export const parseBoatRouteJson = (jsonText: string, routeName: string): BoatRoutePayload => {
const source = JSON.parse(jsonText);
const waypoints = Array.isArray(source?.waypoints)
? source.waypoints.map((item: any, index: number) => normalizeWaypoint(item, index))
: [];
if (!waypoints.length) {
throw new Error('JSON 文件中未找到 waypoints 数组');
}
const invalidIndex = waypoints.findIndex((item: BoatWaypoint) => item.longitude === undefined || item.latitude === undefined);
if (invalidIndex >= 0) {
throw new Error(`第 ${invalidIndex + 1} 个航点缺少经纬度`);
}
return {
routeName,
deviceSn: source?.deviceSn,
scenicId: toNumber(source?.scenicId),
cruiseSpeed: toNumber(source?.cruiseSpeed, 2),
loopEnabled: Boolean(source?.loopEnabled),
loopCount: toNumber(source?.loopCount, 1),
returnMode: source?.returnMode || 'return_start',
safeDistance: toNumber(source?.safeDistance, 5),
boundaryId: source?.boundaryId,
remark: source?.remark,
showInModel: toNumber(source?.showInModel, 0),
waypoints,
};
};
export const buildUpdatePayload = (detail: any, waypoints: BoatWaypoint[]): Partial<BoatRoutePayload> => ({
routeName: detail.routeName,
cruiseSpeed: toNumber(detail.cruiseSpeed, 2),
loopEnabled: Boolean(detail.loopEnabled),
loopCount: toNumber(detail.loopCount, 1),
returnMode: detail.returnMode || 'return_start',
safeDistance: toNumber(detail.safeDistance, 5),
boundaryId: detail.boundaryId,
remark: detail.remark,
showInModel: toNumber(detail.showInModel, 0),
waypoints: waypoints.map((item, index) => normalizeWaypoint(item, index)),
});
@@ -0,0 +1,186 @@
import React, { useRef, useState } from 'react';
import {
PageContainer,
ProFormDateTimeRangePicker,
ProFormText,
ProTable,
type ActionType,
type ProColumns,
} from '@ant-design/pro-components';
import { Modal, Space, Tag, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { boatRouteApi, type BoatRouteItem, type BoatRoutePayload } from '@/services/boatRoute';
import BoatRouteCreateModal from './components/BoatRouteCreateModal';
import BoatRouteEditModal from './components/BoatRouteEditModal';
const BoatRoutePage: React.FC = () => {
const actionRef = useRef<ActionType>();
const [query, setQuery] = useState<Record<string, any>>({});
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [currentRouteId, setCurrentRouteId] = useState<string>();
const add = async (values: BoatRoutePayload) => {
const hide = message.loading('保存中...');
try {
await boatRouteApi.create(values);
message.success('新增成功');
actionRef.current?.reload();
return true;
} catch {
message.error('新增失败');
return false;
} finally {
hide();
}
};
const edit = async (routeId: string, values: Partial<BoatRoutePayload>) => {
const hide = message.loading('保存中...');
try {
await boatRouteApi.update(routeId, values);
message.success('修改成功');
actionRef.current?.reload();
return true;
} catch {
message.error('修改失败');
return false;
} finally {
hide();
}
};
const del = (record: BoatRouteItem) => {
Modal.confirm({
title: `确认删除航线 [${record.routeName || '--'}]?`,
content: '删除后该航线及其航点数据将不可继续使用。',
onOk: async () => {
const hide = message.loading('正在删除...');
try {
await boatRouteApi.remove(record.routeId);
message.success('删除成功');
actionRef.current?.reload();
} catch {
message.error('删除失败');
} finally {
hide();
}
},
});
};
const columns: ProColumns<BoatRouteItem>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{
title: '航线名称',
dataIndex: 'routeName',
ellipsis: true,
render: (_, record) => record.routeName || '--',
},
{ title: '设备 SN', dataIndex: 'deviceSn', copyable: true, ellipsis: true },
{ title: '设备名称', dataIndex: 'deviceName', ellipsis: true },
{ title: '航点数', dataIndex: 'waypointCount', width: 90 },
{ title: '总航程(m)', dataIndex: 'totalDistance', width: 110 },
{ title: '预计时长', dataIndex: 'totalDurationStr', width: 120 },
{
title: '巡航速度',
dataIndex: 'cruiseSpeed',
width: 100,
render: (_, record) => (record.cruiseSpeed ? `${record.cruiseSpeed} m/s` : '--'),
},
{
title: '状态',
dataIndex: 'statusDesc',
width: 110,
render: (_, record) => (
<Tag color={record.status === 1 ? 'green' : 'blue'}>
{record.statusDesc || record.status || '未知'}
</Tag>
),
},
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 180 },
{
title: '操作',
key: 'action',
valueType: 'option',
width: 130,
fixed: 'right',
render: (_, record) => (
<Space>
<a
onClick={() => {
setCurrentRouteId(record.routeId);
setEditOpen(true);
}}
>
编辑
</a>
<a style={{ color: '#ff4d4f' }} onClick={() => del(record)}>
删除
</a>
</Space>
),
},
];
return (
<PageContainer header={{ title: '无人船航线管理' }}>
<SearchBarPlus
defaultCollapsed
split
span={6}
showTenant={false}
onTenantChanged={() => actionRef.current?.reload()}
onFinish={async (values) => setQuery(values)}
>
<ProFormText name="routeName" label="航线名称" />
<ProFormText name="deviceSn" label="设备 SN" />
<ProFormDateTimeRangePicker name="createTimeRange" label="创建时间" />
</SearchBarPlus>
<ActionBar
left={
<GradientButton
size="middle"
type="primary"
icon={<PlusOutlined />}
onClick={() => setCreateOpen(true)}
>
新增航线
</GradientButton>
}
/>
<GlassCard>
<ProTable<BoatRouteItem>
rowKey="routeId"
headerTitle="航线列表"
actionRef={actionRef}
request={(params) => boatRouteApi.page({ ...params, ...query })}
columns={columns}
search={false}
scroll={{ x: 1300 }}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
/>
</GlassCard>
<BoatRouteCreateModal
visible={createOpen}
onVisibleChange={setCreateOpen}
onFinish={add}
/>
<BoatRouteEditModal
visible={editOpen}
routeId={currentRouteId}
onVisibleChange={(visible) => {
setEditOpen(visible);
if (!visible) setCurrentRouteId(undefined);
}}
onFinish={edit}
/>
</PageContainer>
);
};
export default BoatRoutePage;
@@ -287,7 +287,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const unloadAllTilesets = useCallback((viewer: any) => { const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer) return; if (!viewer) return;
tilesetsRef.current.forEach((tileset, id) => { tilesetsRef.current.forEach((tileset) => {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
}); });
tilesetsRef.current.clear(); tilesetsRef.current.clear();
@@ -304,14 +304,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
if (!tileset || !viewer || !Cesium) return; if (!tileset || !viewer || !Cesium) return;
const boundingSphere = tileset.boundingSphere; const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
const radius = boundingSphere.radius; const radius = boundingSphere.radius;
// 计算合适的观察距离
const offset = new Cesium.HeadingPitchRange( const offset = new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0), // heading Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45), // pitch (45度俯视) Cesium.Math.toRadians(-45),
radius * 2.5 // 距离 radius * 2.5
); );
viewer.camera.flyToBoundingSphere(boundingSphere, { viewer.camera.flyToBoundingSphere(boundingSphere, {
@@ -337,7 +335,6 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const tileset = tilesetsRef.current.get(id); const tileset = tilesetsRef.current.get(id);
if (!tileset || !Cesium) return; if (!tileset || !Cesium) return;
// 示例: 设置建筑颜色
tileset.style = new Cesium.Cesium3DTileStyle({ tileset.style = new Cesium.Cesium3DTileStyle({
color: style.color || "color('white')", color: style.color || "color('white')",
show: style.show !== false, show: style.show !== false,
@@ -0,0 +1,134 @@
import { request } from 'umi';
export interface BoatWaypointAction {
actionType?: string;
duration?: number;
params?: any;
}
export interface BoatWaypoint {
waypointId?: string;
waypointIndex?: number;
longitude?: number;
latitude?: number;
speed?: number;
stayDuration?: number;
headingAngle?: number;
turnMode?: string;
isKeyPoint?: boolean;
pointName?: string;
actions?: BoatWaypointAction[] | null;
remark?: string;
}
export interface BoatRouteItem {
routeId: string;
routeName: string;
deviceSn?: string;
deviceName?: string;
waypointCount?: number;
totalDistance?: number;
totalDurationStr?: string;
cruiseSpeed?: number;
status?: number;
statusDesc?: string;
isTemplate?: boolean;
showInModel?: number;
boundaryId?: string;
routeFileUrl?: string;
createTime?: string;
}
export interface BoatRouteDetail extends BoatRouteItem {
scenicId?: number;
totalDuration?: number;
loopEnabled?: boolean;
loopCount?: number;
returnMode?: string;
safeDistance?: number;
startPoint?: string;
endPoint?: string;
remark?: string;
waypoints?: BoatWaypoint[];
updateTime?: string;
}
export interface BoatRoutePayload {
routeName: string;
deviceSn?: string;
scenicId?: number;
cruiseSpeed?: number;
loopEnabled?: boolean;
loopCount?: number;
returnMode?: string;
safeDistance?: number;
boundaryId?: string;
remark?: string;
showInModel?: number;
waypoints: BoatWaypoint[];
}
const unwrapData = (res: any) => res?.data ?? res;
const normalizeRouteItem = (item: any): BoatRouteItem => ({
routeId: item?.routeId ?? item?.route_id ?? '',
routeName: item?.routeName ?? item?.route_name ?? item?.name ?? '',
deviceSn: item?.deviceSn ?? item?.device_sn,
deviceName: item?.deviceName ?? item?.device_name,
waypointCount: item?.waypointCount ?? item?.waypoint_count,
totalDistance: item?.totalDistance ?? item?.total_distance,
totalDurationStr: item?.totalDurationStr ?? item?.total_duration_str,
cruiseSpeed: item?.cruiseSpeed ?? item?.cruise_speed,
status: item?.status,
statusDesc: item?.statusDesc ?? item?.status_desc,
isTemplate: item?.isTemplate ?? item?.is_template,
showInModel: item?.showInModel ?? item?.show_in_model,
boundaryId: item?.boundaryId ?? item?.boundary_id,
routeFileUrl: item?.routeFileUrl ?? item?.route_file_url,
createTime: item?.createTime ?? item?.create_time,
});
export const boatRouteApi = {
page: async (params: { current?: number; pageSize?: number; createTimeRange?: string[]; [key: string]: any }) => {
const { current, pageSize, createTimeRange, ...rest } = params || {};
const [startTime, endTime] = createTimeRange || [];
const res = await request('/api-device/device/boat/route/page', {
method: 'GET',
params: {
page: current,
size: pageSize,
startTime,
endTime,
...rest,
},
});
const pageData = unwrapData(res);
return {
data: (pageData?.records || []).map(normalizeRouteItem),
total: pageData?.total || 0,
} as { data: BoatRouteItem[]; total: number };
},
detail: async (routeId: string) => {
const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'GET' });
return {
...unwrapData(res),
...normalizeRouteItem(unwrapData(res)),
} as BoatRouteDetail;
},
create: async (data: BoatRoutePayload) => {
const res = await request('/api-device/device/boat/route/create', { method: 'POST', data });
return unwrapData(res) as string;
},
update: async (routeId: string, data: Partial<BoatRoutePayload>) => {
const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'PUT', data });
return unwrapData(res);
},
remove: async (routeId: string) => {
const res = await request(`/api-device/device/boat/route/${routeId}`, { method: 'DELETE' });
return unwrapData(res);
},
};
Binary file not shown.
+3 -3
View File
@@ -13,13 +13,13 @@
"prebuild:test": "npm run copy:cesium", "prebuild:test": "npm run copy:cesium",
"prebuild:pre": "npm run copy:cesium", "prebuild:pre": "npm run copy:cesium",
"prebuild:prod": "npm run copy:cesium", "prebuild:prod": "npm run copy:cesium",
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9900 umi dev", "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://localhost:9901 umi dev",
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=https://test.goflytec.com umi dev",
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
"build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/web API_PREFIX=https://test.goflytec.com umi build", "build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/web API_PREFIX=https://test.goflytec.com umi build",
"build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://local.goflytec.com umi build", "build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/web API_PREFIX=https://yeehaitec.com umi build",
"build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/web umi build", "build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/web umi build",
"lint": "eslint --ext .ts,.tsx src", "lint": "eslint --ext .ts,.tsx src",
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
Binary file not shown.
@@ -36,6 +36,36 @@
border: 1px solid rgba(34, 211, 238, 0.3); border: 1px solid rgba(34, 211, 238, 0.3);
} }
.viewSwitchBar {
position: absolute;
top: 18px;
right: 18px;
display: flex;
align-items: center;
gap: 10px;
z-index: 30;
}
.viewSwitchBtn {
height: 34px;
padding: 0 14px;
border: 1px solid rgba(34, 211, 238, 0.35);
border-radius: 999px;
background: rgba(8, 15, 28, 0.82);
color: #d8f6ff;
font-size: 12px;
font-weight: 600;
cursor: pointer;
backdrop-filter: blur(8px);
transition: all 0.2s ease;
&:hover {
border-color: rgba(34, 211, 238, 0.7);
color: #fff;
box-shadow: 0 0 0 1px rgba(34, 211, 238, 0.18), 0 8px 22px rgba(0, 0, 0, 0.22);
}
}
.loadingSpinner { .loadingSpinner {
width: 16px; width: 16px;
height: 16px; height: 16px;
@@ -1,15 +1,25 @@
import React, { useEffect, useRef, useState, useCallback } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { message } from 'antd'; import { App } from 'antd';
import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader'; import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader';
import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer'; import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer';
import { useRoutePreview } from '../../hooks/useRoutePreview'; import { useRoutePreview } from '../../hooks/useRoutePreview';
import { getClientModels } from '../../services/clientApi'; import { getClientModels } from '../../services/clientApi';
import { convertToTilesetConfig } from '@/services/threeDModel'; import { convertToTilesetConfig } from '@/services/threeDModel';
import { getBoatRouteDetail } from '@/services/boatRoute'; import { getBoatRouteDetail } from '@/services/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
import type { BoatRouteListVO, BoatTelemetryData, BoatWaypointDTO } from '@/types/boatRoute'; import type { BoatRouteListVO, BoatTelemetryData, BoatWaypointDTO } from '@/types/boatRoute';
import styles from './index.less'; import styles from './index.less';
let Cesium: any = null; let Cesium: any = null;
const BOAT_MODEL_URI = `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`;
const BOAT_MODEL_SCALE = 0.001;
const BOAT_MODEL_MIN_PIXEL_SIZE = 56;
const BOAT_MODEL_MAX_SCALE = 180;
const BOAT_MODEL_HEADING_OFFSET = -Math.PI / 2;
const DEFAULT_OVERVIEW_LONGITUDE = 105;
const DEFAULT_OVERVIEW_LATITUDE = 31;
const DEFAULT_OVERVIEW_HEIGHT = 18000000;
const DEFAULT_OVERVIEW_PITCH = -55;
interface CenterViewProps { interface CenterViewProps {
deviceSn: string; deviceSn: string;
@@ -25,27 +35,75 @@ interface CenterViewProps {
onPreviewChange?: (previewing: boolean) => void; onPreviewChange?: (previewing: boolean) => void;
} }
const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRouteId, boatData, onModelCenter, isSailing, sailingLoading, previewStartSignal, previewStopSignal, onStartSailing, onPreviewChange }) => { const ACTUAL_TRACK_ID = 'client-actual-track';
const toFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
const getBoatPosition = (data: BoatTelemetryData | null) => {
const validPosition = getValidCoordinate((data as any)?.longitude, (data as any)?.latitude);
if (!validPosition) return null;
const longitude = toFiniteNumber((data as any)?.longitude);
const latitude = toFiniteNumber((data as any)?.latitude);
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return null;
// 设备未上报 GPS 时常见默认值为 0,0,客户端不显示船位。
if (longitude === 0 && latitude === 0) return null;
return validPosition;
};
const CenterView: React.FC<CenterViewProps> = ({
deviceSn,
routes,
selectedRouteId,
boatData,
onModelCenter,
isSailing,
previewStartSignal,
previewStopSignal,
onPreviewChange,
}) => {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null); const viewerRef = useRef<any>(null);
const [viewerReady, setViewerReady] = useState(false);
const [modelLoading, setModelLoading] = useState(false);
const boatEntityRef = useRef<any>(null); const boatEntityRef = useRef<any>(null);
const firstTilesetRef = useRef<any>(null);
const loadedModelDeviceRef = useRef<string | null>(null);
const trackPositionsRef = useRef<any[]>([]); const trackPositionsRef = useRef<any[]>([]);
const terrainLoadedRef = useRef(false); const terrainLoadedRef = useRef(false);
const sailingCameraStateRef = useRef<any>(null); const initRetryCountRef = useRef(0);
const hasFlownToBoatRef = useRef(false);
const activeTrackRouteRef = useRef<string | null>(null);
const previousSelectedRouteRef = useRef<string | null>(selectedRouteId);
const routeDetailCacheRef = useRef<Map<string, BoatWaypointDTO[]>>(new Map());
const [viewerReady, setViewerReady] = useState(false);
const [modelLoading, setModelLoading] = useState(false);
const [hasLoadedModel, setHasLoadedModel] = useState(false);
const [modelLoadEnabled, setModelLoadEnabled] = useState(false);
const [routeRenderItems, setRouteRenderItems] = useState<any[]>([]);
const { message: messageApi } = App.useApp();
const { loadTileset, unloadAllTilesets } = useTilesetLoader(); const { loadTileset, unloadAllTilesets } = useTilesetLoader();
const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef }); const { flyToRoute: flyToRouteLibrary, getRouteSurfaceGeometry } = useCesiumRouteLibraryRenderer({
viewerRef,
routes: routeRenderItems,
});
const { isPreviewing, startPreview, stopPreview } = useRoutePreview({
viewerRef,
messageApi,
getRouteSurfaceGeometry,
});
const boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]);
const hasBoatPosition = !!boatPosition;
// 预览状态变化时通知父组件
useEffect(() => { useEffect(() => {
onPreviewChange?.(isPreviewing); onPreviewChange?.(isPreviewing);
}, [isPreviewing, onPreviewChange]); }, [isPreviewing, onPreviewChange]);
const lastPreviewStopSignalRef = useRef(previewStopSignal); const lastPreviewStopSignalRef = useRef(previewStopSignal);
// 外部停止通道:例如 HUD 点击”结束预览”时由父组件递增信号
useEffect(() => { useEffect(() => {
if (previewStopSignal == null) return; if (previewStopSignal == null) return;
if (lastPreviewStopSignalRef.current === previewStopSignal) return; if (lastPreviewStopSignalRef.current === previewStopSignal) return;
@@ -56,58 +114,142 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
} }
}, [previewStopSignal, isPreviewing, stopPreview]); }, [previewStopSignal, isPreviewing, stopPreview]);
// 外部启动预览通道:LeftPanel 点击”预览航线”时由父组件递增信号
const lastPreviewStartSignalRef = useRef(previewStartSignal); const lastPreviewStartSignalRef = useRef(previewStartSignal);
useEffect(() => { useEffect(() => {
if (previewStartSignal == null) return; if (previewStartSignal == null) return;
if (lastPreviewStartSignalRef.current === previewStartSignal) return; if (lastPreviewStartSignalRef.current === previewStartSignal) return;
lastPreviewStartSignalRef.current = previewStartSignal; lastPreviewStartSignalRef.current = previewStartSignal;
// 延迟执行,等航线航点数据加载完成
const timer = setTimeout(() => { const timer = setTimeout(() => {
const waypoints = routeDetailCacheRef.current.get(selectedRouteId || ''); const waypoints = routeDetailCacheRef.current.get(selectedRouteId || '');
if (waypoints && waypoints.length >= 2) { if (waypoints && waypoints.length >= 2) {
startPreview(waypoints, 2); startPreview(waypoints, 2, selectedRouteId || undefined);
} else { } else {
message.warning('航点数据不足或未加载,无法预览'); messageApi.warning('航点数据不足或尚未加载,无法预览航线');
} }
}, 300); }, 300);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [previewStartSignal, selectedRouteId, startPreview]); }, [previewStartSignal, selectedRouteId, startPreview, messageApi]);
// 航线渲染数据(含航点) const isContainerValid = useCallback(() => {
const [routeRenderItems, setRouteRenderItems] = useState<any[]>([]); if (!containerRef.current) return false;
// 缓存已加载的航线详情 const rect = containerRef.current.getBoundingClientRect();
const routeDetailCacheRef = useRef<Map<string, BoatWaypointDTO[]>>(new Map()); return rect.width > 0 && rect.height > 0;
}, []);
const { flyToRoute: flyToRouteLibrary } = useCesiumRouteLibraryRenderer({ const offsetPositionUp = useCallback((origin: any, upMeters: number) => {
viewerRef, if (!origin || !Cesium || !Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) {
routes: routeRenderItems, return origin;
}
try {
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
return Cesium.Matrix4.multiplyByPoint(enu, new Cesium.Cartesian3(0, 0, upMeters), new Cesium.Cartesian3());
} catch {
return origin;
}
}, []);
const resolveBoatWorldPosition = useCallback((longitude: number, latitude: number) => {
if (!Cesium) return null;
const basePosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, 0);
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.() || !viewer.scene?.clampToHeight) {
return offsetPositionUp(basePosition, 1.2);
}
try {
const excluded = boatEntityRef.current ? [boatEntityRef.current] : [];
const clamped = viewer.scene.clampToHeight(basePosition, excluded);
if (clamped) {
return offsetPositionUp(clamped, 1.2);
}
} catch {
// 忽略贴地失败,回退到基础坐标
}
return offsetPositionUp(basePosition, 1.2);
}, [offsetPositionUp]);
const flyToBoatOverview = useCallback((duration = 1.2) => {
if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return;
if (!hasBoatPosition || isPreviewing || isSailing) return;
if (!boatPosition) return;
const position = resolveBoatWorldPosition(boatPosition.longitude, boatPosition.latitude);
if (!position) return;
try {
viewerRef.current.camera.cancelFlight?.();
viewerRef.current.camera.flyToBoundingSphere(new Cesium.BoundingSphere(position, 18), {
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-54),
360,
),
duration,
}); });
hasFlownToBoatRef.current = true;
viewerRef.current.scene?.requestRender?.();
} catch {
// 忽略相机异常
}
}, [boatPosition, hasBoatPosition, isPreviewing, isSailing, resolveBoatWorldPosition]);
const flyToModelOverview = useCallback((duration = 1.2) => {
if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return;
const tileset = firstTilesetRef.current;
if (!tileset?.boundingSphere) return;
try {
viewerRef.current.camera.cancelFlight?.();
viewerRef.current.camera.flyToBoundingSphere(tileset.boundingSphere, {
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-42),
Math.max(tileset.boundingSphere.radius * 2.4, 280),
),
duration,
});
viewerRef.current.scene?.requestRender?.();
} catch {
// 忽略相机异常
}
}, []);
// 初始化 Cesium(参考鹰眼 CesiumContainer 初始化模式)
useEffect(() => { useEffect(() => {
let destroyed = false; let destroyed = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const initCesium = async () => { const initCesium = async () => {
if (!containerRef.current) return; if (!containerRef.current) return;
if (!isContainerValid()) {
if (initRetryCountRef.current < 10) {
initRetryCountRef.current += 1;
retryTimer = setTimeout(() => {
if (!destroyed) initCesium();
}, 100);
}
return;
}
if (!Cesium) { if (!Cesium) {
const cesiumModule = (window as any).Cesium || await import('cesium'); const cesiumModule = (window as any).Cesium || await import('cesium');
Cesium = cesiumModule; Cesium = cesiumModule;
(window as any).Cesium = cesiumModule; (window as any).Cesium = cesiumModule;
// 设置 Worker 基础路径,避免从 file:/// 加载
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/'; const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`); Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
// 设置 Cesium Ion Token
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN; const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
if (cesiumToken) { if (cesiumToken) {
Cesium.Ion.defaultAccessToken = cesiumToken; Cesium.Ion.defaultAccessToken = cesiumToken;
} }
// 加载 Cesium CSS
if (!document.querySelector('link[href*="cesium"]')) { if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
@@ -116,8 +258,9 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
} }
} }
if (destroyed) return; if (destroyed || !isContainerValid()) return;
try {
const viewer = new Cesium.Viewer(containerRef.current, { const viewer = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(), terrainProvider: new Cesium.EllipsoidTerrainProvider(),
scene3DOnly: false, scene3DOnly: false,
@@ -132,11 +275,10 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
navigationHelpButton: false, navigationHelpButton: false,
infoBox: false, infoBox: false,
selectionIndicator: false, selectionIndicator: false,
requestRenderMode: true, requestRenderMode: false,
maximumRenderTimeChange: Infinity, maximumRenderTimeChange: Infinity,
}); });
// 移除默认图层,添加 ArcGIS 影像
viewer.imageryLayers.remove(viewer.imageryLayers.get(0)); viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b'); viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
viewer.imageryLayers.addImageryProvider( viewer.imageryLayers.addImageryProvider(
@@ -144,38 +286,103 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0, minimumLevel: 0,
maximumLevel: 18, maximumLevel: 18,
}) }),
); );
viewer.scene.globe.enableLighting = false; viewer.scene.globe.enableLighting = false;
viewer.scene.skyAtmosphere.show = true; viewer.scene.skyAtmosphere.show = true;
viewerRef.current = viewer;
setViewerReady(true);
// 隐藏 Cesium 水印
const creditContainer = viewer.cesiumWidget?.creditContainer; const creditContainer = viewer.cesiumWidget?.creditContainer;
if (creditContainer) { if (creditContainer) {
creditContainer.style.display = 'none'; creditContainer.style.display = 'none';
} }
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(
DEFAULT_OVERVIEW_LONGITUDE,
DEFAULT_OVERVIEW_LATITUDE,
DEFAULT_OVERVIEW_HEIGHT,
),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(DEFAULT_OVERVIEW_PITCH),
roll: 0,
},
});
viewer.scene?.requestRender?.();
viewerRef.current = viewer;
setViewerReady(true);
initRetryCountRef.current = 0;
} catch (error) {
console.error('[CenterView] Cesium 初始化失败', error);
if (initRetryCountRef.current < 3) {
initRetryCountRef.current += 1;
retryTimer = setTimeout(() => {
if (!destroyed) initCesium();
}, 500);
}
}
}; };
initCesium(); initCesium();
return () => { return () => {
destroyed = true; destroyed = true;
if (retryTimer) clearTimeout(retryTimer);
if (viewerRef.current && !viewerRef.current.isDestroyed()) { if (viewerRef.current && !viewerRef.current.isDestroyed()) {
try {
unloadAllTilesets(viewerRef.current); unloadAllTilesets(viewerRef.current);
viewerRef.current.destroy(); viewerRef.current.destroy();
} catch (error) {
console.warn('[CenterView] Viewer 销毁失败', error);
}
viewerRef.current = null; viewerRef.current = null;
} }
firstTilesetRef.current = null;
loadedModelDeviceRef.current = null;
setHasLoadedModel(false);
setViewerReady(false);
}; };
}, []); }, [isContainerValid, unloadAllTilesets]);
useEffect(() => {
if (!viewerReady) return;
const viewer = viewerRef.current;
const container = containerRef.current;
if (!viewer || viewer.isDestroyed?.() || !container) return;
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
const handleResize = () => {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
const currentViewer = viewerRef.current;
if (!currentViewer || currentViewer.isDestroyed?.()) return;
try {
currentViewer.resize?.();
currentViewer.scene?.requestRender?.();
} catch {
// 忽略 resize 异常
}
}, 60);
};
const observer = typeof ResizeObserver !== 'undefined'
? new ResizeObserver(() => handleResize())
: null;
observer?.observe(container);
window.addEventListener('resize', handleResize);
handleResize();
return () => {
if (resizeTimer) clearTimeout(resizeTimer);
observer?.disconnect();
window.removeEventListener('resize', handleResize);
};
}, [viewerReady]);
/**
* 动态切换高程地形(参考鹰眼 switchToElevationTerrain)
* 根据模型配置的地形类型,优先尝试对应地形,失败后降级
*/
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => { const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
if (!viewerRef.current || !Cesium) return 'ellipsoid'; if (!viewerRef.current || !Cesium) return 'ellipsoid';
if (terrainLoadedRef.current && !preferredTerrainType) return 'loaded'; if (terrainLoadedRef.current && !preferredTerrainType) return 'loaded';
@@ -185,7 +392,7 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
if (preferredTerrainType === 'arcgis') { if (preferredTerrainType === 'arcgis') {
try { try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl( const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer' 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer',
); );
viewerRef.current.terrainProvider = terrainProvider; viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true; viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
@@ -218,7 +425,7 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
} catch { } catch {
try { try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl( const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer' 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer',
); );
viewerRef.current.terrainProvider = terrainProvider; viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true; viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
@@ -233,13 +440,16 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
return loadedTerrainType; return loadedTerrainType;
}, []); }, []);
// 加载3D模型(参考鹰眼 loadDeviceModels)
useEffect(() => { useEffect(() => {
if (!viewerReady || !deviceSn) return; if (!viewerReady || !deviceSn || !modelLoadEnabled) return;
if (loadedModelDeviceRef.current === deviceSn && firstTilesetRef.current) return;
let cancelled = false; let cancelled = false;
const loadModels = async () => { const loadModels = async () => {
setModelLoading(true); setModelLoading(true);
setHasLoadedModel(false);
firstTilesetRef.current = null;
loadedModelDeviceRef.current = null;
unloadAllTilesets(viewerRef.current); unloadAllTilesets(viewerRef.current);
try { try {
@@ -251,20 +461,17 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
} }
const configs = modelList.map((model: any) => convertToTilesetConfig(model)); const configs = modelList.map((model: any) => convertToTilesetConfig(model));
// 并行:高程地形加载 + 模型准备
const firstTerrainType = configs[0]?.position?.terrainType; const firstTerrainType = configs[0]?.position?.terrainType;
const terrainPromise = switchToElevationTerrain(firstTerrainType); const terrainPromise = switchToElevationTerrain(firstTerrainType);
const autoLoadCount = configs.length <= 2 ? configs.length : 1; const autoLoadCount = configs.length <= 2 ? configs.length : 1;
const configsToLoad = configs.slice(0, autoLoadCount); const configsToLoad = configs.slice(0, autoLoadCount);
// 等待高程加载完成
const loadedTerrainType = await terrainPromise; const loadedTerrainType = await terrainPromise;
if (cancelled) { setModelLoading(false); return; } if (cancelled) {
setModelLoading(false);
return;
}
let firstTileset: any = null; let firstTileset: any = null;
for (const config of configsToLoad) { for (const config of configsToLoad) {
if (!config.url) continue; if (!config.url) continue;
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType); const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
@@ -273,42 +480,53 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
} }
} }
// 模型加载完成后飞到模型位置 firstTilesetRef.current = firstTileset;
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) { loadedModelDeviceRef.current = firstTileset ? deviceSn : null;
try { setHasLoadedModel(!!firstTileset);
const radius = Number(firstTileset?.boundingSphere?.radius);
const range = Number.isFinite(radius) && radius > 0 ? Math.max(50, radius * 0.8) : 100; if (onModelCenter && firstTileset?.boundingSphere?.center) {
viewerRef.current.flyTo(firstTileset, {
duration: 1.5,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-50),
range
),
});
// 通知父组件模型中心位置(用于模拟数据定位)
if (onModelCenter && firstTileset.boundingSphere?.center) {
const cartographic = Cesium.Cartographic.fromCartesian(firstTileset.boundingSphere.center); const cartographic = Cesium.Cartographic.fromCartesian(firstTileset.boundingSphere.center);
onModelCenter( onModelCenter(
Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.longitude),
Cesium.Math.toDegrees(cartographic.latitude), Cesium.Math.toDegrees(cartographic.latitude),
); );
} }
} catch (e) {
console.warn('飞到模型位置失败:', e); if (
firstTileset
&& !hasBoatPosition
&& !selectedRouteId
&& !isPreviewing
&& !isSailing
) {
setTimeout(() => {
if (!cancelled) {
flyToModelOverview(1.25);
} }
}, 120);
} }
} catch (error) { } catch (error) {
console.error('加载设备模型失败:', error); console.error('加载设备模型失败', error);
} }
setModelLoading(false); setModelLoading(false);
}; };
loadModels(); loadModels();
return () => { cancelled = true; }; return () => {
}, [viewerReady, deviceSn]); cancelled = true;
};
}, [
viewerReady,
deviceSn,
modelLoadEnabled,
switchToElevationTerrain,
loadTileset,
unloadAllTilesets,
onModelCenter,
flyToModelOverview,
]);
// 选中航线时加载航点详情并渲染
useEffect(() => { useEffect(() => {
if (!viewerReady || !selectedRouteId) { if (!viewerReady || !selectedRouteId) {
setRouteRenderItems([]); setRouteRenderItems([]);
@@ -322,210 +540,250 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
try { try {
const res = await getBoatRouteDetail(selectedRouteId); const res = await getBoatRouteDetail(selectedRouteId);
if (res.resp_code === 0 && res.data?.waypoints) { if (res.resp_code === 0 && res.data?.waypoints) {
waypoints = res.data.waypoints.map((wp) => ({ waypoints = res.data.waypoints.map((waypoint) => ({
longitude: wp.longitude, longitude: waypoint.longitude,
latitude: wp.latitude, latitude: waypoint.latitude,
speed: wp.speed, speed: waypoint.speed,
stayDuration: wp.stayDuration, stayDuration: waypoint.stayDuration,
pointName: wp.pointName, pointName: waypoint.pointName,
})); }));
routeDetailCacheRef.current.set(selectedRouteId, waypoints); routeDetailCacheRef.current.set(selectedRouteId, waypoints);
} }
} catch { } catch {
message.error('线路详情加载失败'); messageApi.error('航线详情加载失败');
return; return;
} }
} }
if (waypoints && waypoints.length > 0) { if (waypoints && waypoints.length > 0) {
setRouteRenderItems([{ setRouteRenderItems([
{
routeId: selectedRouteId, routeId: selectedRouteId,
routeName: routes.find((r) => r.routeId === selectedRouteId)?.routeName || '', routeName: routes.find((route) => route.routeId === selectedRouteId)?.routeName || '',
waypoints, waypoints,
visible: true, visible: true,
highlighted: true, highlighted: true,
}]); },
// 使用 useCesiumRouteLibraryRenderer 的 flyToRoute(基于 Rectangle,视角更可靠) ]);
// 延迟一帧让 routeRenderItems 生效,entity 创建后再飞
setTimeout(() => flyToRouteLibrary(selectedRouteId), 100);
} }
}; };
loadAndRender(); loadAndRender();
}, [viewerReady, selectedRouteId]); }, [viewerReady, selectedRouteId, routes, messageApi]);
// 实时船位渲染
useEffect(() => { useEffect(() => {
if (!viewerReady || !Cesium || !boatData?.longitude || !boatData?.latitude) return; if (!viewerReady || !selectedRouteId || isPreviewing) return;
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed()) return;
const position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2); const timer = setTimeout(() => {
trackPositionsRef.current.push(position); flyToRouteLibrary(selectedRouteId);
// 限制轨迹点数 }, isSailing ? 140 : 100);
if (trackPositionsRef.current.length > 500) {
trackPositionsRef.current = trackPositionsRef.current.slice(-400); return () => clearTimeout(timer);
}, [viewerReady, selectedRouteId, isPreviewing, isSailing, flyToRouteLibrary]);
useEffect(() => {
setModelLoadEnabled(false);
hasFlownToBoatRef.current = false;
firstTilesetRef.current = null;
loadedModelDeviceRef.current = null;
setHasLoadedModel(false);
}, [deviceSn]);
useEffect(() => {
if (!viewerReady || !deviceSn) return;
if (selectedRouteId || isPreviewing || isSailing) {
setModelLoadEnabled(true);
return;
} }
// 更新/创建船位 Entity if (hasBoatPosition) {
setModelLoadEnabled(true);
return;
}
if (!hasBoatPosition) {
const timer = setTimeout(() => {
setModelLoadEnabled(true);
}, 1500);
return () => clearTimeout(timer);
}
return undefined;
}, [viewerReady, deviceSn, selectedRouteId, isPreviewing, isSailing, hasBoatPosition]);
useEffect(() => {
if (!viewerReady || !hasBoatPosition || selectedRouteId || isPreviewing || isSailing || hasFlownToBoatRef.current) {
return;
}
const timer = setTimeout(() => {
flyToBoatOverview(1.1);
}, 120);
return () => clearTimeout(timer);
}, [viewerReady, hasBoatPosition, selectedRouteId, isPreviewing, isSailing, flyToBoatOverview]);
useEffect(() => {
const previousSelectedRoute = previousSelectedRouteRef.current;
const canceledRouteSelection = !!previousSelectedRoute && !selectedRouteId;
if (viewerReady && canceledRouteSelection && hasBoatPosition && !isPreviewing && !isSailing) {
const timer = setTimeout(() => {
flyToBoatOverview(0.95);
}, 80);
previousSelectedRouteRef.current = selectedRouteId;
return () => clearTimeout(timer);
}
previousSelectedRouteRef.current = selectedRouteId;
return undefined;
}, [viewerReady, selectedRouteId, hasBoatPosition, isPreviewing, isSailing, flyToBoatOverview]);
useEffect(() => {
if (!viewerReady || !Cesium) return;
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.()) return;
if (isPreviewing) {
if (boatEntityRef.current) {
try {
viewer.entities.remove(boatEntityRef.current);
} catch {
// 忽略清理异常
}
boatEntityRef.current = null;
}
return;
}
if (!hasBoatPosition) {
if (boatEntityRef.current) {
try {
viewer.entities.remove(boatEntityRef.current);
} catch {
// 忽略清理异常
}
boatEntityRef.current = null;
}
return;
}
if (!boatPosition) return;
const liftedPosition = resolveBoatWorldPosition(boatPosition.longitude, boatPosition.latitude);
if (!liftedPosition) return;
const headingRad = Cesium.Math.toRadians(boatData?.heading || 0);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(
liftedPosition,
new Cesium.HeadingPitchRoll(headingRad + BOAT_MODEL_HEADING_OFFSET, 0, 0),
)
: undefined;
if (!boatEntityRef.current) { if (!boatEntityRef.current) {
boatEntityRef.current = viewer.entities.add({ boatEntityRef.current = viewer.entities.add({
position, position: liftedPosition,
point: { orientation,
pixelSize: 12, model: {
color: Cesium.Color.fromCssColorString('#00d4ff'), uri: BOAT_MODEL_URI,
outlineColor: Cesium.Color.WHITE, scale: BOAT_MODEL_SCALE,
outlineWidth: 2, minimumPixelSize: BOAT_MODEL_MIN_PIXEL_SIZE,
disableDepthTestDistance: Number.POSITIVE_INFINITY, maximumScale: BOAT_MODEL_MAX_SCALE,
runAnimations: true,
colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
color: Cesium.Color.WHITE,
silhouetteSize: 0,
}, },
label: { label: {
text: '当前位置', text: '无人船',
font: '12px sans-serif', font: '600 14px sans-serif',
fillColor: Cesium.Color.WHITE, fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE, style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2, outlineWidth: 2,
outlineColor: Cesium.Color.BLACK, outlineColor: Cesium.Color.BLACK,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString('#082f49').withAlpha(0.88),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM, verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -16), pixelOffset: new Cesium.Cartesian2(0, -34),
disableDepthTestDistance: Number.POSITIVE_INFINITY, disableDepthTestDistance: Number.POSITIVE_INFINITY,
}, },
}); });
} else { } else {
boatEntityRef.current.position = position; boatEntityRef.current.position = liftedPosition;
if (orientation) {
boatEntityRef.current.orientation = orientation;
}
} }
// 轨迹线 viewer.scene.requestRender?.();
if (trackPositionsRef.current.length >= 2) { }, [viewerReady, boatData?.heading, boatPosition, hasBoatPosition, isPreviewing, resolveBoatWorldPosition]);
const trackId = 'client-boat-track';
let trackEntity = viewer.entities.getById(trackId); useEffect(() => {
if (!trackEntity) { if (!viewerReady || !Cesium) return;
viewer.entities.add({ const viewer = viewerRef.current;
id: trackId, if (!viewer || viewer.isDestroyed?.()) return;
const clearTrack = () => {
trackPositionsRef.current = [];
try {
viewer.entities.removeById(ACTUAL_TRACK_ID);
} catch {
// 忽略清理异常
}
};
if (isPreviewing) {
activeTrackRouteRef.current = null;
clearTrack();
return;
}
if (activeTrackRouteRef.current !== deviceSn) {
activeTrackRouteRef.current = deviceSn;
clearTrack();
}
}, [viewerReady, deviceSn, isPreviewing]);
useEffect(() => {
if (!viewerReady || !Cesium || isPreviewing || !hasBoatPosition || !boatPosition) return;
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.()) return;
const position = Cesium.Cartesian3.fromDegrees(boatPosition.longitude, boatPosition.latitude, 0);
const lastPosition = trackPositionsRef.current[trackPositionsRef.current.length - 1];
if (!lastPosition || Cesium.Cartesian3.distance(lastPosition, position) > 0.3) {
trackPositionsRef.current.push(position);
}
if (trackPositionsRef.current.length > 600) {
trackPositionsRef.current = trackPositionsRef.current.slice(-500);
}
let trackEntity = viewer.entities.getById(ACTUAL_TRACK_ID);
if (!trackEntity && trackPositionsRef.current.length >= 2) {
trackEntity = viewer.entities.add({
id: ACTUAL_TRACK_ID,
polyline: { polyline: {
positions: new Cesium.CallbackProperty(() => trackPositionsRef.current, false), positions: new Cesium.CallbackProperty(() => trackPositionsRef.current, false),
width: 3, width: 5,
material: new Cesium.PolylineGlowMaterialProperty({ material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3, glowPower: 0.22,
color: Cesium.Color.LIME, color: Cesium.Color.fromCssColorString('#f97316').withAlpha(0.95),
}), }),
clampToGround: true, clampToGround: true,
}, },
}); });
} }
}
viewer.scene.requestRender(); viewer.scene.requestRender?.();
}, [viewerReady, boatData]); }, [viewerReady, boatPosition, hasBoatPosition, isPreviewing]);
// 执行航线时第一视角跟踪(与预览模式相同的追踪相机)
useEffect(() => {
if (!viewerReady || !Cesium) return;
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed()) return;
if (isSailing) {
// 首次进入执行模式:保存相机并定位到航线起点
if (!sailingCameraStateRef.current) {
sailingCameraStateRef.current = {
position: viewer.camera.position.clone(),
heading: viewer.camera.heading,
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
};
// 从缓存获取航线航点,定位到起点
const waypoints = routeDetailCacheRef.current.get(selectedRouteId || '');
if (waypoints && waypoints.length >= 2) {
const wp0 = waypoints[0];
const wp1 = waypoints[1];
// 计算起点到第二航点的航向
const dLon = (wp1.longitude - wp0.longitude) * Math.PI / 180;
const lat1 = wp0.latitude * Math.PI / 180;
const lat2 = wp1.latitude * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const headingRad = Math.atan2(y, x);
try {
const startPos = Cesium.Cartesian3.fromDegrees(wp0.longitude, wp0.latitude, 2);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(startPos);
const localUp = new Cesium.Cartesian3(0, 0, 0.8);
const target = Cesium.Matrix4.multiplyByPoint(enu, localUp, new Cesium.Cartesian3());
viewer.camera.lookAt(
target,
new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22),
);
viewer.scene.requestRender();
} catch { /* ignore */ }
return; // 首帧用起点位置,后续帧跟随 boatData
}
}
// 后续帧:跟随实际船位
if (boatData?.longitude && boatData?.latitude) {
try {
const headingRad = Cesium.Math.toRadians(boatData.heading || 0);
const position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const localUp = new Cesium.Cartesian3(0, 0, 0.8);
const target = Cesium.Matrix4.multiplyByPoint(enu, localUp, new Cesium.Cartesian3());
viewer.camera.lookAt(
target,
new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22),
);
viewer.scene.requestRender();
} catch {
try {
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 25),
orientation: {
heading: Cesium.Math.toRadians(boatData.heading || 0),
pitch: Cesium.Math.toRadians(-20),
roll: 0,
},
});
} catch { /* ignore */ }
}
}
}
// 退出执行模式:恢复相机
if (!isSailing && sailingCameraStateRef.current) {
try {
if (Cesium?.Matrix4) {
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
} catch { /* ignore */ }
try {
viewer.camera.setView({
destination: sailingCameraStateRef.current.position,
orientation: {
heading: sailingCameraStateRef.current.heading,
pitch: sailingCameraStateRef.current.pitch,
roll: sailingCameraStateRef.current.roll,
},
});
} catch { /* ignore */ }
sailingCameraStateRef.current = null;
}
}, [viewerReady, isSailing, boatData, selectedRouteId]);
// 预览选中航线(供外部调用,通过 ref 或直接调用)
const handlePreviewRoute = useCallback(async () => {
if (!selectedRouteId) return;
const waypoints = routeDetailCacheRef.current.get(selectedRouteId);
if (!waypoints || waypoints.length < 2) {
message.warning('航点数据不足,无法预览');
return;
}
await startPreview(waypoints, 2);
}, [selectedRouteId, startPreview]);
return ( return (
<div className={styles.wrapper}> <div className={styles.wrapper}>
<div ref={containerRef} className={styles.cesiumContainer} /> <div ref={containerRef} className={styles.cesiumContainer} />
{/* 模型加载提示 */}
{modelLoading && ( {modelLoading && (
<div className={styles.loadingTip}> <div className={styles.loadingTip}>
<div className={styles.loadingSpinner} /> <div className={styles.loadingSpinner} />
@@ -533,15 +791,44 @@ const CenterView: React.FC<CenterViewProps> = ({ deviceSn, routes, selectedRoute
</div> </div>
)} )}
{/* 地图底部信息栏 */} {(hasBoatPosition || hasLoadedModel) && (
<div className={styles.viewSwitchBar}>
{hasBoatPosition && (
<button
type="button"
className={styles.viewSwitchBtn}
onClick={() => flyToBoatOverview(0.95)}
>
无人船
</button>
)}
{hasLoadedModel && (
<button
type="button"
className={styles.viewSwitchBtn}
onClick={() => flyToModelOverview(0.95)}
>
3D模型
</button>
)}
</div>
)}
<div className={styles.mapBottomBar}> <div className={styles.mapBottomBar}>
<span className={styles.mapBottomText}> <span className={styles.mapBottomText}>
当前坐标: {boatData?.longitude ? `${boatData.longitude.toFixed(4)}°E, ${boatData.latitude.toFixed(4)}°N` : '--'} 当前坐标:
{hasBoatPosition
? ` ${boatPosition!.longitude.toFixed(4)}°E, ${boatPosition!.latitude.toFixed(4)}°N`
: ' --'}
</span> </span>
<span className={styles.mapBottomSep}>|</span> <span className={styles.mapBottomSep}>|</span>
<span className={styles.mapBottomText}>比例尺: 1:5000</span> <span className={styles.mapBottomText}>规划航线:青色航点 / 航线</span>
{isSailing && (
<>
<span className={styles.mapBottomSep}>|</span> <span className={styles.mapBottomSep}>|</span>
<span className={styles.mapBottomText}>高程: 3D模式</span> <span className={styles.mapBottomText}>实际航迹:橙色轨迹线</span>
</>
)}
</div> </div>
</div> </div>
); );
@@ -0,0 +1,395 @@
@bg-sidebar: #0f172a;
@bg-card: #1e293b;
@bg-deep: #0a0f1c;
@border-color: #1e3a5f;
@accent-cyan: #22d3ee;
@accent-orange: #f97316;
@text-primary: #ffffff;
@text-secondary: #94a3b8;
@text-dim: #64748b;
@font-mono: 'JetBrains Mono', 'Courier New', monospace;
@font-sans: 'Inter', -apple-system, sans-serif;
.panel {
width: 340px;
height: 100%;
background: @bg-sidebar;
border-left: 1px solid @border-color;
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
overflow-y: auto;
overflow-x: hidden;
flex-shrink: 0;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: rgba(34, 211, 238, 0.22);
border-radius: 999px;
}
}
.section {
background: linear-gradient(180deg, rgba(30, 41, 59, 0.92), rgba(15, 23, 42, 0.96));
border: 1px solid @border-color;
border-radius: 14px;
padding: 14px;
display: flex;
flex-direction: column;
gap: 12px;
}
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.sectionTitle {
display: inline-flex;
align-items: center;
gap: 8px;
color: @text-primary;
font-size: 13px;
font-weight: 700;
font-family: @font-sans;
}
.sectionTag {
padding: 4px 8px;
border-radius: 999px;
border: 1px solid rgba(34, 211, 238, 0.28);
background: rgba(34, 211, 238, 0.08);
color: @accent-cyan;
font-size: 10px;
font-family: @font-mono;
}
.videoCard {
border-radius: 12px;
overflow: hidden;
background: #050a14;
height: 196px;
}
.videoPlaceholder {
min-height: 196px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
color: @text-secondary;
background:
radial-gradient(circle at top, rgba(34, 211, 238, 0.10), transparent 52%),
linear-gradient(180deg, rgba(7, 11, 21, 0.96), rgba(4, 8, 15, 0.98));
}
.placeholderIcon {
font-size: 26px;
color: @accent-cyan;
}
.placeholderTitle {
font-size: 13px;
font-weight: 700;
color: @text-primary;
}
.placeholderDesc {
font-size: 11px;
color: @text-dim;
text-align: center;
}
.mockVideoCard {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
background:
radial-gradient(circle at 50% 18%, rgba(34, 211, 238, 0.24), transparent 28%),
linear-gradient(180deg, #0a1830 0%, #08111f 38%, #06111a 100%);
}
.mockVideoGlow {
position: absolute;
inset: -10% -20% auto;
height: 65%;
background: radial-gradient(circle, rgba(34, 211, 238, 0.18), transparent 60%);
pointer-events: none;
}
.mockVideoScanline {
position: absolute;
inset: 0;
background:
linear-gradient(180deg, transparent 0%, rgba(34, 211, 238, 0.1) 48%, transparent 100%),
repeating-linear-gradient(
180deg,
rgba(255, 255, 255, 0.02) 0,
rgba(255, 255, 255, 0.02) 2px,
transparent 2px,
transparent 6px
);
animation: videoSweep 4.2s linear infinite;
pointer-events: none;
}
.mockVideoHud {
position: absolute;
top: 12px;
left: 12px;
right: 12px;
display: flex;
align-items: center;
justify-content: space-between;
z-index: 2;
}
.mockVideoBadge,
.mockVideoMeta {
padding: 4px 8px;
border-radius: 999px;
background: rgba(8, 15, 28, 0.68);
border: 1px solid rgba(34, 211, 238, 0.28);
color: @accent-cyan;
font-size: 10px;
font-family: @font-mono;
}
.mockVideoScene {
position: absolute;
inset: 0;
}
.mockHorizon {
position: absolute;
left: 0;
right: 0;
top: 42%;
height: 1px;
background: rgba(255, 255, 255, 0.24);
box-shadow: 0 0 14px rgba(34, 211, 238, 0.3);
}
.mockWave {
position: absolute;
left: -12%;
right: -12%;
bottom: 18%;
height: 44%;
border-radius: 42% 58% 0 0 / 20% 24% 0 0;
background:
linear-gradient(180deg, rgba(34, 211, 238, 0.22), rgba(8, 47, 73, 0.82)),
radial-gradient(circle at 50% 0, rgba(255, 255, 255, 0.18), transparent 45%);
animation: waveFloat 6s ease-in-out infinite;
}
.mockBoatMarker {
position: absolute;
right: 18px;
bottom: 28px;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border-radius: 10px;
background: rgba(8, 15, 28, 0.72);
border: 1px solid rgba(34, 211, 238, 0.28);
color: @text-primary;
font-size: 11px;
font-weight: 600;
}
.mockBoatDot {
width: 8px;
height: 8px;
border-radius: 50%;
background: @accent-orange;
box-shadow: 0 0 0 5px rgba(249, 115, 22, 0.18);
}
.mockVideoFooter {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
display: flex;
justify-content: space-between;
gap: 8px;
color: @text-secondary;
font-size: 10px;
font-family: @font-mono;
z-index: 2;
}
.lidarCard {
display: flex;
flex-direction: column;
gap: 12px;
}
.lidarCanvas {
position: relative;
width: 100%;
height: 220px;
border-radius: 12px;
background:
radial-gradient(circle at center, rgba(34, 211, 238, 0.08), transparent 55%),
linear-gradient(180deg, rgba(6, 12, 24, 0.98), rgba(10, 15, 28, 0.98));
border: 1px solid rgba(34, 211, 238, 0.16);
overflow: hidden;
}
.lidarSvg {
width: 100%;
height: 100%;
}
.lidarRing {
fill: none;
stroke: rgba(148, 163, 184, 0.18);
stroke-width: 1;
}
.lidarAxis {
stroke: rgba(148, 163, 184, 0.14);
stroke-width: 1;
}
.lidarPoint {
fill: @accent-orange;
opacity: 0.92;
}
.lidarSweep {
stroke: rgba(34, 211, 238, 0.58);
stroke-width: 1.5;
stroke-linecap: round;
filter: drop-shadow(0 0 6px rgba(34, 211, 238, 0.45));
}
.lidarEmpty {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
color: @text-secondary;
font-size: 12px;
}
.lidarMetrics {
display: flex;
flex-direction: column;
gap: 10px;
}
.metricItem,
.metricMini {
background: rgba(10, 15, 28, 0.82);
border: 1px solid rgba(30, 58, 95, 0.7);
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 4px;
}
.metricRow {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.metricLabel {
font-size: 10px;
color: @text-dim;
font-family: @font-sans;
}
.metricValue {
font-size: 14px;
color: @text-primary;
font-family: @font-mono;
font-weight: 700;
}
.summaryGrid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.summaryCard {
min-height: 86px;
border-radius: 12px;
border: 1px solid rgba(30, 58, 95, 0.78);
background: rgba(10, 15, 28, 0.84);
padding: 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.summaryIcon {
font-size: 16px;
}
.summaryLabel {
color: @text-dim;
font-size: 10px;
font-family: @font-sans;
}
.summaryValue {
color: @text-primary;
font-size: 13px;
line-height: 1.4;
font-family: @font-mono;
font-weight: 700;
word-break: break-word;
}
@media (max-width: 1366px) {
.panel {
width: 300px;
padding: 12px;
}
.videoCard {
height: 168px;
}
.lidarCanvas {
height: 190px;
}
}
@keyframes videoSweep {
0% {
transform: translateY(-100%);
}
100% {
transform: translateY(100%);
}
}
@keyframes waveFloat {
0%, 100% {
transform: translateY(0) scaleX(1);
}
50% {
transform: translateY(5px) scaleX(1.03);
}
}
@@ -0,0 +1,302 @@
import React, { useEffect, useMemo, useState } from 'react';
import {
VideoCameraOutlined,
RadarChartOutlined,
EnvironmentOutlined,
ThunderboltOutlined,
WifiOutlined,
} from '@ant-design/icons';
import WhepPlayer from '@/pages/map3d/components/MapContainer/3d/BottomPanel/WhepPlayer';
import type { BoatRouteListVO, BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less';
interface ExecRightPanelProps {
deviceInfo: any;
boatData: BoatTelemetryData | null;
activeRouteInfo: BoatRouteListVO | null;
sseConnected: boolean;
videoStreamUrl?: string;
isPreviewing?: boolean;
}
interface LidarSample {
angle: number;
distance: number;
}
const clampNumber = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const extractLidarSamples = (deviceInfo: any, boatData: BoatTelemetryData | null): LidarSample[] => {
const raw =
(boatData as any)?.lidarSamples ||
(boatData as any)?.lidarPoints ||
(boatData as any)?.lidarDistances ||
(deviceInfo as any)?.lidarSamples ||
(deviceInfo as any)?.lidarPoints ||
(deviceInfo as any)?.lidarDistances ||
[];
if (!Array.isArray(raw) || raw.length === 0) return [];
if (typeof raw[0] === 'number') {
return raw.map((distance: number, index: number) => ({
angle: (index / raw.length) * 360,
distance: Number(distance) || 0,
}));
}
return raw
.map((item: any, index: number) => ({
angle: Number(item?.angle ?? item?.deg ?? item?.theta ?? (index / raw.length) * 360),
distance: Number(item?.distance ?? item?.range ?? item?.value ?? 0),
}))
.filter((item) => Number.isFinite(item.angle) && Number.isFinite(item.distance));
};
const createMockLidarSamples = (phase: number): LidarSample[] => (
Array.from({ length: 72 }, (_, index) => {
const angle = index * 5;
const wave = Math.sin((angle + phase * 28) * Math.PI / 180);
const ripple = Math.cos((angle * 2 + phase * 36) * Math.PI / 180);
const bump = (index % 9 === 0 ? 4.5 : 0) + (index % 13 === 0 ? 2.6 : 0);
const distance = clampNumber(16 + wave * 6 + ripple * 3 + bump, 3.6, 31);
return { angle, distance };
})
);
const ExecRightPanel: React.FC<ExecRightPanelProps> = ({
deviceInfo,
boatData,
activeRouteInfo,
sseConnected,
videoStreamUrl,
isPreviewing = false,
}) => {
const [mockPhase, setMockPhase] = useState(0);
useEffect(() => {
if (!isPreviewing) return undefined;
const timer = window.setInterval(() => {
setMockPhase((value) => (value + 1) % 360);
}, 900);
return () => window.clearInterval(timer);
}, [isPreviewing]);
const realLidarSamples = useMemo(() => extractLidarSamples(deviceInfo, boatData), [deviceInfo, boatData]);
const lidarSamples = useMemo(
() => (isPreviewing ? createMockLidarSamples(mockPhase) : realLidarSamples),
[isPreviewing, mockPhase, realLidarSamples],
);
const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
const hasBoatPosition = !!boatPosition;
const lidarMetrics = useMemo(() => {
if (!lidarSamples.length) {
return {
minDistance: null,
frontDistance: null,
leftDistance: null,
rightDistance: null,
};
}
const pickClosest = (targetAngle: number) => {
const matched = lidarSamples.reduce((best, current) => {
const delta = Math.abs((((current.angle - targetAngle) % 360) + 540) % 360 - 180);
return delta < best.delta ? { delta, distance: current.distance } : best;
}, { delta: Number.POSITIVE_INFINITY, distance: 0 });
return matched.distance;
};
return {
minDistance: Math.min(...lidarSamples.map((item) => item.distance)),
frontDistance: pickClosest(0),
leftDistance: pickClosest(270),
rightDistance: pickClosest(90),
};
}, [lidarSamples]);
const lidarPoints = useMemo(() => {
if (!lidarSamples.length) return [];
const maxDistance = Math.max(10, ...lidarSamples.map((item) => item.distance));
const radius = 88;
return lidarSamples.slice(0, 72).map((sample) => {
const normalized = clampNumber(sample.distance / maxDistance, 0.08, 1);
const actualRadius = normalized * radius;
const angleRad = (sample.angle - 90) * Math.PI / 180;
return {
x: 110 + Math.cos(angleRad) * actualRadius,
y: 110 + Math.sin(angleRad) * actualRadius,
};
});
}, [lidarSamples]);
const statusItems = [
{
label: '设备状态',
value: isPreviewing ? '模拟预览' : (sseConnected ? '在线' : '离线'),
icon: <WifiOutlined />,
accent: isPreviewing ? '#22d3ee' : (sseConnected ? '#10b981' : '#ef4444'),
},
{
label: '剩余电量',
value: `${boatData?.battery ?? (isPreviewing ? 86 : 0)}%`,
icon: <ThunderboltOutlined />,
accent: (boatData?.battery ?? 86) > 20 ? '#22d3ee' : '#f59e0b',
},
{
label: '当前位置',
value: hasBoatPosition ? `${boatData!.longitude.toFixed(4)}, ${boatData!.latitude.toFixed(4)}` : '--',
icon: <EnvironmentOutlined />,
accent: '#94a3b8',
},
];
const formatMeters = (distance: number | null) => (distance == null ? '--' : `${distance.toFixed(distance >= 10 ? 0 : 1)} m`);
return (
<div className={styles.panel}>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>
<VideoCameraOutlined />
视频回传
</span>
<span className={styles.sectionTag}>
{isPreviewing ? '模拟流' : (videoStreamUrl ? '实时流' : '未接入')}
</span>
</div>
<div className={styles.videoCard}>
{isPreviewing ? (
<div className={styles.mockVideoCard}>
<div className={styles.mockVideoGlow} />
<div className={styles.mockVideoScanline} />
<div className={styles.mockVideoHud}>
<span className={styles.mockVideoBadge}>SIM CAM</span>
<span className={styles.mockVideoMeta}>1080P / 25 FPS</span>
</div>
<div className={styles.mockVideoScene}>
<div className={styles.mockHorizon} />
<div className={styles.mockWave} />
<div className={styles.mockBoatMarker}>
<span className={styles.mockBoatDot} />
<span>航线预览目标</span>
</div>
</div>
<div className={styles.mockVideoFooter}>
<span>模拟海况:2级</span>
<span>光照:良好</span>
<span>延迟:42ms</span>
</div>
</div>
) : videoStreamUrl ? (
<WhepPlayer url={videoStreamUrl} autoPlay={true} muted={true} videoOnly={true} />
) : (
<div className={styles.videoPlaceholder}>
<VideoCameraOutlined className={styles.placeholderIcon} />
<div className={styles.placeholderTitle}>暂无视频流</div>
<div className={styles.placeholderDesc}>设备未配置 `videoStreamUrl` 或 `whepUrl`</div>
</div>
)}
</div>
</div>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>
<RadarChartOutlined />
激光雷达
</span>
<span className={styles.sectionTag}>
{isPreviewing ? `模拟 ${lidarSamples.length} 点` : (lidarSamples.length > 0 ? `${lidarSamples.length} 点` : '未接入')}
</span>
</div>
<div className={styles.lidarCard}>
<div className={styles.lidarCanvas}>
<svg viewBox="0 0 220 220" className={styles.lidarSvg}>
<circle cx="110" cy="110" r="88" className={styles.lidarRing} />
<circle cx="110" cy="110" r="58" className={styles.lidarRing} />
<circle cx="110" cy="110" r="28" className={styles.lidarRing} />
<line x1="110" y1="14" x2="110" y2="206" className={styles.lidarAxis} />
<line x1="14" y1="110" x2="206" y2="110" className={styles.lidarAxis} />
<line
x1="110"
y1="110"
x2={110 + Math.cos((mockPhase - 90) * Math.PI / 180) * 96}
y2={110 + Math.sin((mockPhase - 90) * Math.PI / 180) * 96}
className={styles.lidarSweep}
/>
{lidarPoints.map((point, index) => (
<circle key={`${point.x}-${point.y}-${index}`} cx={point.x} cy={point.y} r="2.6" className={styles.lidarPoint} />
))}
</svg>
{lidarPoints.length === 0 && (
<div className={styles.lidarEmpty}>
<RadarChartOutlined className={styles.placeholderIcon} />
<span>暂无激光雷达数据</span>
</div>
)}
</div>
<div className={styles.lidarMetrics}>
<div className={styles.metricItem}>
<span className={styles.metricLabel}>最近障碍距离</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.minDistance)}</span>
</div>
<div className={styles.metricRow}>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>前方</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.frontDistance)}</span>
</div>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>左侧</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.leftDistance)}</span>
</div>
<div className={styles.metricMini}>
<span className={styles.metricLabel}>右侧</span>
<span className={styles.metricValue}>{formatMeters(lidarMetrics.rightDistance)}</span>
</div>
</div>
</div>
</div>
</div>
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>执行摘要</span>
<span className={styles.sectionTag}>{activeRouteInfo?.routeName || '未选择航线'}</span>
</div>
<div className={styles.summaryGrid}>
{statusItems.map((item) => (
<div key={item.label} className={styles.summaryCard}>
<div className={styles.summaryIcon} style={{ color: item.accent }}>{item.icon}</div>
<div className={styles.summaryLabel}>{item.label}</div>
<div className={styles.summaryValue}>{item.value}</div>
</div>
))}
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>规划总长</div>
<div className={styles.summaryValue}>
{activeRouteInfo ? `${(activeRouteInfo.totalDistance / 1000).toFixed(2)} km` : '--'}
</div>
</div>
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>预计时长</div>
<div className={styles.summaryValue}>{activeRouteInfo?.totalDurationStr || '--'}</div>
</div>
<div className={styles.summaryCard}>
<div className={styles.summaryLabel}>航向 / 速度</div>
<div className={styles.summaryValue}>
{boatData ? `${Math.round(boatData.heading || 0)}° / ${boatData.speed?.toFixed(1) || '0.0'} m/s` : '--'}
</div>
</div>
</div>
</div>
</div>
);
};
export default ExecRightPanel;
@@ -11,6 +11,7 @@ import {
DownOutlined, DownOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import type { BoatRouteListVO, BoatWaypointVO, BoatTelemetryData } from '@/types/boatRoute'; import type { BoatRouteListVO, BoatWaypointVO, BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less'; import styles from './index.less';
interface LeftPanelProps { interface LeftPanelProps {
@@ -27,13 +28,11 @@ interface LeftPanelProps {
sailingLoading: boolean; sailingLoading: boolean;
} }
/** 格式化距离 */
const formatDistance = (meters?: number) => { const formatDistance = (meters?: number) => {
if (!meters || meters <= 0) return null; if (!meters || meters <= 0) return null;
return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`; return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`;
}; };
/** 格式化时间(秒 → "XX分钟") */
const formatDuration = (seconds?: number) => { const formatDuration = (seconds?: number) => {
if (!seconds || seconds <= 0) return null; if (!seconds || seconds <= 0) return null;
const min = Math.round(seconds / 60); const min = Math.round(seconds / 60);
@@ -55,10 +54,11 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
}) => { }) => {
const battery = boatData?.battery ?? 0; const battery = boatData?.battery ?? 0;
const isOnline = sseConnected; const isOnline = sseConnected;
const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
const hasBoatPosition = !!boatPosition;
return ( return (
<div className={styles.panel}> <div className={styles.panel}>
{/* ========== 设备状态卡片 ========== */}
<div className={`${styles.infoCard} ${styles.deviceCard}`}> <div className={`${styles.infoCard} ${styles.deviceCard}`}>
<div className={styles.cardHeader}> <div className={styles.cardHeader}>
<span className={styles.cardTitle}>设备状态</span> <span className={styles.cardTitle}>设备状态</span>
@@ -74,7 +74,7 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
GPS 信号 GPS 信号
</span> </span>
<span className={`${styles.cardValue} ${styles.cardValueGreen}`}> <span className={`${styles.cardValue} ${styles.cardValueGreen}`}>
{boatData?.longitude ? '强' : '弱'} {hasBoatPosition ? '已定位' : '未定位'}
</span> </span>
</div> </div>
@@ -84,8 +84,8 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
当前位置 当前位置
</span> </span>
<span className={`${styles.cardValue} ${styles.cardValueCyan}`}> <span className={`${styles.cardValue} ${styles.cardValueCyan}`}>
{boatData?.longitude {hasBoatPosition
? `${boatData.longitude.toFixed(2)}°E ${boatData.latitude.toFixed(2)}°N` ? `${boatPosition!.longitude.toFixed(4)}°E ${boatPosition!.latitude.toFixed(4)}°N`
: '--'} : '--'}
</span> </span>
</div> </div>
@@ -131,12 +131,10 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
</div> </div>
</div> </div>
{/* ========== 分隔线 ========== */}
<div className={styles.divider} /> <div className={styles.divider} />
{/* ========== 航线区域 ========== */}
<div className={styles.routeHeader}> <div className={styles.routeHeader}>
<span className={styles.routeHeaderTitle}>浏览线路</span> <span className={styles.routeHeaderTitle}>航线列表</span>
<span className={styles.routeCountBadge}> <span className={styles.routeCountBadge}>
{routes.length} 条航线 {routes.length} 条航线
<DownOutlined style={{ fontSize: 8 }} /> <DownOutlined style={{ fontSize: 8 }} />
@@ -172,11 +170,13 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
</div> </div>
<span className={`${styles.badge} ${styles.badgeGreen}`}>就绪</span> <span className={`${styles.badge} ${styles.badgeGreen}`}>就绪</span>
</div> </div>
<div className={styles.routeMeta}> <div className={styles.routeMeta}>
{wpCount}个航点{distance ? ` · 约${distance}` : ''}{duration ? ` · 预计${duration}` : ''} {wpCount} 个航点
{distance ? ` · 约 ${distance}` : ''}
{duration ? ` · 预计 ${duration}` : ''}
</div> </div>
{/* 选中时显示操作按钮 */}
{isSelected && ( {isSelected && (
<div className={styles.routeActions} onClick={(e) => e.stopPropagation()}> <div className={styles.routeActions} onClick={(e) => e.stopPropagation()}>
<button <button
@@ -191,7 +191,12 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
className={styles.btnExecute} className={styles.btnExecute}
disabled={sailingLoading} disabled={sailingLoading}
onClick={(e) => { e.stopPropagation(); onStartSailing(route.routeId); }} onClick={(e) => { e.stopPropagation(); onStartSailing(route.routeId); }}
onTouchEnd={(e) => { if (sailingLoading) return; e.stopPropagation(); e.preventDefault(); onStartSailing(route.routeId); }} onTouchEnd={(e) => {
if (sailingLoading) return;
e.stopPropagation();
e.preventDefault();
onStartSailing(route.routeId);
}}
> >
<PlayCircleOutlined /> <PlayCircleOutlined />
{sailingLoading ? '启动中...' : '执行航线'} {sailingLoading ? '启动中...' : '执行航线'}
@@ -203,6 +208,7 @@ const LeftPanel: React.FC<LeftPanelProps> = ({
})} })}
</div> </div>
)} )}
{routes.length > 2 && <div className={styles.scrollHint}>上下滑动查看更多航线</div>} {routes.length > 2 && <div className={styles.scrollHint}>上下滑动查看更多航线</div>}
</div> </div>
</div> </div>
@@ -15,10 +15,26 @@ interface RightPanelProps {
sseConnected: boolean; sseConnected: boolean;
} }
const toFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
const getBoatPosition = (data: BoatTelemetryData | null) => {
const longitude = toFiniteNumber((data as any)?.longitude);
const latitude = toFiniteNumber((data as any)?.latitude);
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null;
if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return null;
if (longitude === 0 && latitude === 0) return null;
return { longitude: longitude!, latitude: latitude! };
};
const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnected }) => { const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnected }) => {
const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]); const heading = useMemo(() => boatData?.heading ?? 0, [boatData?.heading]);
const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]); const speed = useMemo(() => boatData?.speed ?? 0, [boatData?.speed]);
const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]); const battery = useMemo(() => boatData?.battery ?? 0, [boatData?.battery]);
const boatPosition = useMemo(() => getBoatPosition(boatData), [boatData?.longitude, boatData?.latitude]);
const [targetSpeed, setTargetSpeed] = useState(5); const [targetSpeed, setTargetSpeed] = useState(5);
const activeCommandRef = useRef<string | null>(null); const activeCommandRef = useRef<string | null>(null);
@@ -219,8 +235,8 @@ const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnec
<div className={styles.dataRow}> <div className={styles.dataRow}>
<span className={styles.dataLabel}>GPS</span> <span className={styles.dataLabel}>GPS</span>
<span className={styles.dataValue}> <span className={styles.dataValue}>
{boatData?.longitude != null {boatPosition
? `${boatData.longitude.toFixed(4)}, ${boatData.latitude?.toFixed(4)}` ? `${boatPosition.longitude.toFixed(4)}, ${boatPosition.latitude.toFixed(4)}`
: '--'} : '--'}
</span> </span>
</div> </div>
@@ -4,9 +4,48 @@
*/ */
import { useState, useRef, useEffect, useCallback } from 'react'; import { useState, useRef, useEffect, useCallback } from 'react';
import type { BoatTelemetryData } from '@/types/boatRoute'; import type { BoatTelemetryData } from '@/types/boatRoute';
import { getValidCoordinate } from '@/utils/geo';
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
const toNumberOrZero = (value: unknown): number => {
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : 0;
};
const unusedToFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
const unusedIsValidCoordinate = (longitude?: number, latitude?: number) => {
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return false;
if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return false;
// 设备未上报 GPS 时常见默认值为 0,0,客户端不应把船显示到几内亚湾。
return !(longitude === 0 && latitude === 0);
};
const normalizeTelemetryData = (rawData: any, deviceSn: string): BoatTelemetryData => {
const position = getValidCoordinate(
rawData?.longitude ?? rawData?.lng ?? rawData?.lon ?? rawData?.gps?.longitude ?? rawData?.position?.longitude,
rawData?.latitude ?? rawData?.lat ?? rawData?.gps?.latitude ?? rawData?.position?.latitude,
);
return {
...rawData,
deviceSn: rawData?.deviceSn || deviceSn,
longitude: position?.longitude,
latitude: position?.latitude,
heading: toNumberOrZero(rawData?.heading ?? rawData?.direction ?? rawData?.yaw),
speed: toNumberOrZero(rawData?.speed),
battery: toNumberOrZero(rawData?.battery ?? rawData?.batteryPercent),
signalStrength: toNumberOrZero(rawData?.signalStrength),
status: rawData?.status ?? rawData?.deviceStatus ?? '',
recordTime: rawData?.recordTime ?? new Date().toISOString(),
} as BoatTelemetryData;
};
export interface UseClientSSEReturn { export interface UseClientSSEReturn {
boatData: BoatTelemetryData | null; boatData: BoatTelemetryData | null;
sseConnected: boolean; sseConnected: boolean;
@@ -135,12 +174,14 @@ export const useClientSSE = (): UseClientSSEReturn => {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let buffer = ''; let buffer = '';
let currentEvent = 'message';
let currentData = '';
const handleSSEEvent = (eventName: string, data: string) => { const handleSSEEvent = (eventName: string, data: string) => {
if (eventName === 'boat-telemetry') { if (eventName === 'boat-telemetry') {
try { try {
const parsed = JSON.parse(data) as BoatTelemetryData; const parsed = JSON.parse(data);
setBoatData(parsed); setBoatData(normalizeTelemetryData(parsed, deviceSn));
} catch (e) { } catch (e) {
console.warn('[ClientSSE] 解析遥测数据失败:', e); console.warn('[ClientSSE] 解析遥测数据失败:', e);
} }
@@ -164,14 +205,13 @@ export const useClientSSE = (): UseClientSSEReturn => {
const lines = buffer.split('\n'); const lines = buffer.split('\n');
buffer = lines.pop() || ''; buffer = lines.pop() || '';
let currentEvent = 'message'; for (const rawLine of lines) {
let currentData = ''; const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
for (const line of lines) {
if (line.startsWith('event:')) { if (line.startsWith('event:')) {
currentEvent = line.substring(6).trim(); currentEvent = line.substring(6).trim();
} else if (line.startsWith('data:')) { } else if (line.startsWith('data:')) {
currentData = line.substring(5).trim(); const lineData = line.substring(5).trim();
currentData = currentData ? `${currentData}\n${lineData}` : lineData;
} else if (line === '') { } else if (line === '') {
if (currentData) { if (currentData) {
handleSSEEvent(currentEvent, currentData); handleSSEEvent(currentEvent, currentData);
@@ -5,7 +5,8 @@
* 暂停/恢复/结束:调用真实无人船控制API,携带missionCode * 暂停/恢复/结束:调用真实无人船控制API,携带missionCode
*/ */
import { useState, useCallback, useRef } from 'react'; import { useState, useCallback, useRef } from 'react';
import { Modal, message } from 'antd'; import { Modal } from 'antd';
import type { MessageInstance } from 'antd/es/message/interface';
import { import {
createBoatMission, createBoatMission,
pauseBoatMission, pauseBoatMission,
@@ -46,6 +47,8 @@ export function useNavigationState(
selectedRouteId: string | null, selectedRouteId: string | null,
setSelectedRouteId: (id: string | null) => void, setSelectedRouteId: (id: string | null) => void,
routes: BoatRouteListVO[], routes: BoatRouteListVO[],
messageApi?: MessageInstance,
modalApi?: { confirm: (config: any) => void },
): UseNavigationStateReturn { ): UseNavigationStateReturn {
const [activeRoute, setActiveRoute] = useState<ActiveRouteState>({ mode: null, routeId: null }); const [activeRoute, setActiveRoute] = useState<ActiveRouteState>({ mode: null, routeId: null });
const [isPaused, setIsPaused] = useState(false); const [isPaused, setIsPaused] = useState(false);
@@ -64,12 +67,12 @@ export function useNavigationState(
const handleStartSailing = useCallback(async (routeId: string) => { const handleStartSailing = useCallback(async (routeId: string) => {
if (!deviceSn) { if (!deviceSn) {
message.error('设备SN缺失,无法开始航行'); messageApi?.error('设备SN缺失,无法开始航行');
return; return;
} }
const route = routes.find((r) => r.routeId === routeId); const route = routes.find((r) => r.routeId === routeId);
if (!route) { if (!route) {
message.error('航线信息不存在'); messageApi?.error('航线信息不存在');
return; return;
} }
@@ -88,13 +91,13 @@ export function useNavigationState(
}); });
if (res.resp_code !== 0) { if (res.resp_code !== 0) {
message.error(res.resp_msg || '创建任务失败'); messageApi?.error(res.resp_msg || '创建任务失败');
return; return;
} }
const code = res.data?.missionCode; const code = res.data?.missionCode;
if (!code) { if (!code) {
message.error('任务创建成功但未返回任务编码'); messageApi?.error('任务创建成功但未返回任务编码');
return; return;
} }
@@ -104,45 +107,45 @@ export function useNavigationState(
setSelectedRouteId(routeId); setSelectedRouteId(routeId);
setIsPaused(false); setIsPaused(false);
setCurrentWaypointIndex(0); setCurrentWaypointIndex(0);
message.success('航行任务已启动'); messageApi?.success('航行任务已启动');
} catch (e: any) { } catch (e: any) {
message.error(e?.message || '启动航行失败,请重试'); messageApi?.error(e?.message || '启动航行失败,请重试');
} finally { } finally {
setSailingLoading(false); setSailingLoading(false);
} }
}, [deviceSn, routes, activeRoute.mode, setSelectedRouteId]); }, [deviceSn, routes, activeRoute.mode, setSelectedRouteId, messageApi]);
const handlePauseSailing = useCallback(() => { const handlePauseSailing = useCallback(() => {
if (!isSailing) return; if (!isSailing) return;
const code = missionCodeRef.current; const code = missionCodeRef.current;
if (!code) { if (!code) {
message.warning('任务编码缺失,无法暂停'); messageApi?.warning('任务编码缺失,无法暂停');
return; return;
} }
setIsPaused(true); setIsPaused(true);
pauseBoatMission(deviceSn, code).catch(() => { pauseBoatMission(deviceSn, code).catch(() => {
message.error('暂停指令发送失败'); messageApi?.error('暂停指令发送失败');
setIsPaused(false); setIsPaused(false);
}); });
}, [deviceSn, isSailing]); }, [deviceSn, isSailing, messageApi]);
const handleResumeSailing = useCallback(() => { const handleResumeSailing = useCallback(() => {
if (!isSailing) return; if (!isSailing) return;
const code = missionCodeRef.current; const code = missionCodeRef.current;
if (!code) { if (!code) {
message.warning('任务编码缺失,无法恢复'); messageApi?.warning('任务编码缺失,无法恢复');
return; return;
} }
setIsPaused(false); setIsPaused(false);
resumeBoatMission(deviceSn, code).catch(() => { resumeBoatMission(deviceSn, code).catch(() => {
message.error('恢复航行指令发送失败'); messageApi?.error('恢复航行指令发送失败');
setIsPaused(true); setIsPaused(true);
}); });
}, [deviceSn, isSailing]); }, [deviceSn, isSailing, messageApi]);
const handleStopSailing = useCallback(() => { const handleStopSailing = useCallback(() => {
const code = missionCodeRef.current; const code = missionCodeRef.current;
Modal.confirm({ (modalApi || Modal).confirm({
title: '确认结束航行', title: '确认结束航行',
content: '结束后将退出导航模式,返回线路选择', content: '结束后将退出导航模式,返回线路选择',
okText: '结束航行', okText: '结束航行',
@@ -155,12 +158,12 @@ export function useNavigationState(
setMissionCode(null); setMissionCode(null);
if (code) { if (code) {
undoBoatMission(deviceSn, code).catch(() => { undoBoatMission(deviceSn, code).catch(() => {
message.warning('终止指令发送失败,但已退出导航模式'); messageApi?.warning('终止指令发送失败,但已退出导航模式');
}); });
} }
}, },
}); });
}, [deviceSn]); }, [deviceSn, modalApi, messageApi]);
const handleStopPreview = useCallback(() => { const handleStopPreview = useCallback(() => {
setPreviewStopSignal((prev) => prev + 1); setPreviewStopSignal((prev) => prev + 1);
@@ -175,11 +178,11 @@ export function useNavigationState(
setMissionCode(null); setMissionCode(null);
if (code) { if (code) {
undoBoatMission(deviceSn, code).catch(() => { undoBoatMission(deviceSn, code).catch(() => {
message.warning('紧急停靠指令发送失败'); messageApi?.warning('紧急停靠指令发送失败');
}); });
} }
message.warning('已执行紧急停靠'); messageApi?.warning('已执行紧急停靠');
}, [deviceSn]); }, [deviceSn, messageApi]);
const handlePreviewChange = useCallback((previewing: boolean) => { const handlePreviewChange = useCallback((previewing: boolean) => {
setActiveRoute((prev) => { setActiveRoute((prev) => {
@@ -1,32 +1,75 @@
/**
* 航线第一视角预览 Hook
* 从鹰眼 RouteEditor 中提取的预览动画逻辑,用于客户端页面航线预览
*/
import { useState, useRef, useCallback, useEffect } from 'react'; import { useState, useRef, useCallback, useEffect } from 'react';
import { message } from 'antd'; import type { MessageInstance } from 'antd/es/message/interface';
import type { BoatWaypointDTO } from '@/types/boatRoute'; import type { BoatWaypointDTO } from '@/types/boatRoute';
import type { RouteSurfaceGeometry } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer';
export interface UseRoutePreviewOptions { export interface UseRoutePreviewOptions {
viewerRef: React.RefObject<any>; viewerRef: React.RefObject<any>;
messageApi?: MessageInstance;
getRouteSurfaceGeometry?: (routeId: string) => RouteSurfaceGeometry | null;
} }
export interface UseRoutePreviewReturn { export interface UseRoutePreviewReturn {
isPreviewing: boolean; isPreviewing: boolean;
startPreview: (waypoints: BoatWaypointDTO[], speed?: number) => Promise<void>; startPreview: (waypoints: BoatWaypointDTO[], speed?: number, routeId?: string) => Promise<void>;
stopPreview: () => void; stopPreview: () => void;
} }
export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoutePreviewReturn { const MODEL_HEADING_OFFSET = -Math.PI / 2;
const ROUTE_HEIGHT_OFFSET = 0.8;
const BOAT_HEIGHT_OFFSET = 0.35;
const TURN_HOLD_MS = 500;
const TURN_ROTATE_MS = 650;
const TURN_ANGLE_THRESHOLD_DEG = 12;
const BOAT_MODEL_URI = `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`;
const BOAT_MODEL_SCALE = 0.001;
const BOAT_MODEL_MIN_PIXEL_SIZE = 56;
const BOAT_MODEL_MAX_SCALE = 180;
export function useRoutePreview({
viewerRef,
messageApi,
getRouteSurfaceGeometry,
}: UseRoutePreviewOptions): UseRoutePreviewReturn {
const [isPreviewing, setIsPreviewing] = useState(false); const [isPreviewing, setIsPreviewing] = useState(false);
const previewAnimationRef = useRef<number | null>(null); const previewAnimationRef = useRef<number | null>(null);
const savedCameraStateRef = useRef<any>(null); const savedCameraStateRef = useRef<any>(null);
const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null); const previewBoatEntityRef = useRef<any>(null);
const previewRouteEntityRef = useRef<any>(null); const previewEntitiesRef = useRef<any[]>([]);
const escHandlerRef = useRef<((e: KeyboardEvent) => void) | null>(null);
const getCesium = useCallback(() => (window as any).Cesium, []); const getCesium = useCallback(() => (window as any).Cesium, []);
// 计算两点间航向角 const requestRender = useCallback(() => {
const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
try {
viewer.scene?.requestRender?.();
} catch {
// ignore
}
}, [viewerRef]);
const setStaticRouteEntitiesVisible = useCallback((visible: boolean) => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !viewer.entities) return;
viewer.entities.values.forEach((entity: any) => {
const type = entity.properties?.type?.getValue?.();
if (
type === 'route-library-path'
|| type === 'route-library-point'
|| type === 'route-library-waypoint'
) {
entity.show = visible;
}
});
}, [viewerRef]);
const calculateHeading = useCallback((
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => {
const dLon = (to.longitude - from.longitude) * Math.PI / 180; const dLon = (to.longitude - from.longitude) * Math.PI / 180;
const lat1 = from.latitude * Math.PI / 180; const lat1 = from.latitude * Math.PI / 180;
const lat2 = to.latitude * Math.PI / 180; const lat2 = to.latitude * Math.PI / 180;
@@ -36,7 +79,6 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute
return (bearing + 360) % 360; return (bearing + 360) % 360;
}, []); }, []);
// 停止预览
const stopPreview = useCallback(() => { const stopPreview = useCallback(() => {
setIsPreviewing(false); setIsPreviewing(false);
@@ -44,44 +86,45 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute
cancelAnimationFrame(previewAnimationRef.current); cancelAnimationFrame(previewAnimationRef.current);
previewAnimationRef.current = null; previewAnimationRef.current = null;
} }
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler); if (escHandlerRef.current) {
(previewAnimationRef as any).escHandler = null; window.removeEventListener('keydown', escHandlerRef.current);
escHandlerRef.current = null;
} }
// 清理船只实体
if (previewBoatPartsRef.current) {
try {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) { if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
}
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
}
}
// 清理预览航线实体
if (previewRouteEntityRef.current) {
try { try {
const viewer = viewerRef?.current; if (previewBoatEntityRef.current) {
if (viewer && !viewer.isDestroyed?.()) { viewer.entities.remove(previewBoatEntityRef.current);
viewer.entities.remove(previewRouteEntityRef.current);
}
} catch { /* ignore */ } finally {
previewRouteEntityRef.current = null;
} }
} catch {
// ignore
} }
previewBoatEntityRef.current = null;
// 恢复相机 previewEntitiesRef.current.forEach((entity) => {
if (savedCameraStateRef.current && viewerRef?.current) { try {
const viewer = viewerRef.current; if (entity) viewer.entities.remove(entity);
} catch {
// ignore
}
});
previewEntitiesRef.current = [];
setStaticRouteEntitiesVisible(true);
if (savedCameraStateRef.current) {
const Cesium = getCesium(); const Cesium = getCesium();
try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ } try {
if (Cesium?.Matrix4) {
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
} catch {
// ignore
}
try {
viewer.camera.setView({ viewer.camera.setView({
destination: savedCameraStateRef.current.position, destination: savedCameraStateRef.current.position,
orientation: { orientation: {
@@ -90,98 +133,97 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute
roll: savedCameraStateRef.current.roll, roll: savedCameraStateRef.current.roll,
}, },
}); });
} catch {
// ignore
}
savedCameraStateRef.current = null; savedCameraStateRef.current = null;
} }
}, [viewerRef, getCesium]); }
// 构建预览折线(密集化 + 贴模型表面) requestRender();
const buildPreviewPolyline = useCallback(async (points: BoatWaypointDTO[]) => { }, [viewerRef, getCesium, requestRender, setStaticRouteEntitiesVisible]);
const buildPreviewWaypointPositions = useCallback(async (points: BoatWaypointDTO[]) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return []; if (!viewer || !Cesium || viewer.isDestroyed?.()) return [];
if (!Array.isArray(points) || points.length < 2) return []; if (!Array.isArray(points) || points.length === 0) return [];
const applyOffset = (cartesian: any) => { const applyOffset = (cartesian: any) => {
try { try {
const carto = Cesium.Cartographic.fromCartesian(cartesian); const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
carto.height = (Number(carto.height) || 0) + 0.05; cartographic.height = (Number(cartographic.height) || 0) + ROUTE_HEIGHT_OFFSET;
return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height); return Cesium.Cartesian3.fromRadians(
} catch { return cartesian; } cartographic.longitude,
cartographic.latitude,
cartographic.height,
);
} catch {
return cartesian;
}
}; };
// 密集化航点 const above = points.map((point) => Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 300));
const cartos: any[] = []; const ground = points.map((point) => Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 0));
let total = 0;
const maxTotal = 500;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i], b = points[i + 1];
const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 300);
const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 300);
const geodesic = new Cesium.EllipsoidGeodesic(ca, cb);
const dist = Number(geodesic.surfaceDistance) || 0;
const segments = Math.max(2, Math.min(60, Math.ceil(dist / 10)));
for (let s = 0; s <= segments; s++) {
if (i > 0 && s === 0) continue;
if (total >= maxTotal) break;
const c = geodesic.interpolateUsingFraction(segments === 0 ? 0 : s / segments);
c.height = 300;
cartos.push(c);
total++;
}
if (total >= maxTotal) break;
}
if (cartos.length < 2) {
return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset);
}
const above = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampFn = viewer.scene?.clampToHeightMostDetailed; const clampFn = viewer.scene?.clampToHeightMostDetailed;
if (typeof clampFn !== 'function') return above.map(applyOffset); if (typeof clampFn !== 'function') {
return ground.map(applyOffset).filter(Boolean);
}
try { try {
const clamped = await clampFn.call(viewer.scene, above); const clamped = await clampFn.call(viewer.scene, above);
const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]); return ground
const okCount = (clamped || []).filter(Boolean).length; .map((fallback: any, index: number) => applyOffset(clamped?.[index] || fallback))
if (okCount < 2) return above.map(applyOffset); .filter(Boolean);
return merged.map(applyOffset);
} catch { } catch {
return above.map(applyOffset); return ground.map(applyOffset).filter(Boolean);
} }
}, [viewerRef, getCesium]); }, [viewerRef, getCesium]);
// 开始预览 const startPreview = useCallback(async (waypoints: BoatWaypointDTO[], speed: number = 2, routeId?: string) => {
const startPreview = useCallback(async (waypoints: BoatWaypointDTO[], speed: number = 2) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!waypoints || waypoints.length < 2) { if (!waypoints || waypoints.length < 2) {
message.warning('至少需要2个航点才能预览'); messageApi?.warning('至少需要 2 个航点才能预览');
return; return;
} }
if (isPreviewing) stopPreview(); if (isPreviewing) {
stopPreview();
}
const polylinePositions = await buildPreviewPolyline(waypoints); const surfaceGeometry = routeId ? getRouteSurfaceGeometry?.(routeId) : null;
if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) { const fallbackWaypointPositions = await buildPreviewWaypointPositions(waypoints);
message.warning('模型瓦片加载中,请稍后再试预览'); const routePolylinePositions = Array.isArray(surfaceGeometry?.polyline) && surfaceGeometry.polyline.length >= 2
? surfaceGeometry.polyline
: fallbackWaypointPositions;
const waypointPositions = Array.isArray(surfaceGeometry?.waypointPositions)
&& surfaceGeometry.waypointPositions.length === waypoints.length
? surfaceGeometry.waypointPositions
: fallbackWaypointPositions;
if (routePolylinePositions.length < 2 || waypointPositions.length < 2) {
messageApi?.warning('模型仍在加载中,请稍后再试预览');
return; return;
} }
// 清理旧船只 const distances: number[] = [0];
if (previewBoatPartsRef.current) { for (let index = 1; index < routePolylinePositions.length; index += 1) {
try { distances[index] = distances[index - 1] + Cesium.Cartesian3.distance(
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; routePolylinePositions[index - 1],
if (hull) viewer.entities.remove(hull); routePolylinePositions[index],
if (cabin) viewer.entities.remove(cabin); );
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
} }
const totalDistance = distances[distances.length - 1] || 0;
if (totalDistance <= 1) {
setStaticRouteEntitiesVisible(true);
setIsPreviewing(false);
messageApi?.warning('航线过短,无法预览');
return;
} }
// 保存相机
savedCameraStateRef.current = { savedCameraStateRef.current = {
position: viewer.camera.position.clone(), position: viewer.camera.position.clone(),
heading: viewer.camera.heading, heading: viewer.camera.heading,
@@ -190,338 +232,364 @@ export function useRoutePreview({ viewerRef }: UseRoutePreviewOptions): UseRoute
}; };
setIsPreviewing(true); setIsPreviewing(true);
message.info('开始航线预览,按ESC退出'); setStaticRouteEntitiesVisible(false);
messageApi?.info('开始航线预览,按 ESC 可退出');
const routeMaterial = new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.35,
color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.95),
});
// 添加可见的预览航线实体(确保第一视角能看到整条航线)
try {
const routeEntity = viewer.entities.add({ const routeEntity = viewer.entities.add({
polyline: { polyline: {
positions: polylinePositions, positions: routePolylinePositions,
width: 6, width: 6,
material: new Cesium.PolylineGlowMaterialProperty({ material: routeMaterial,
glowPower: 0.4, depthFailMaterial: routeMaterial,
color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9),
}),
depthFailMaterial: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.5),
clampToGround: false, clampToGround: false,
}, },
}); });
previewRouteEntityRef.current = routeEntity;
} catch { /* ignore */ }
const chaseRange = 22; const waypointEntities = waypointPositions.map((position, index) => viewer.entities.add({
const chasePitch = -20; position,
const ellipsoid = Cesium.Ellipsoid?.WGS84; point: {
pixelSize: 12,
color: Cesium.Color.fromCssColorString('#ff4d73').withAlpha(0.95),
outlineColor: Cesium.Color.WHITE.withAlpha(0.92),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: waypoints[index]?.pointName || `航点${index + 1}`,
font: '14px bold sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 3,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -16),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}));
// 计算累积距离 previewEntitiesRef.current = [routeEntity, ...waypointEntities];
const distances: number[] = [0];
for (let i = 1; i < polylinePositions.length; i++) { const firstPosition = routePolylinePositions[0];
distances[i] = distances[i - 1] + Cesium.Cartesian3.distance(polylinePositions[i - 1], polylinePositions[i]); const initialHeadingRad = getHeadingByDistance(
Cesium,
routePolylinePositions,
distances,
calculateHeading,
0,
speed,
);
const liftedFirstPosition = offsetUp(Cesium, firstPosition, BOAT_HEIGHT_OFFSET);
previewBoatEntityRef.current = viewer.entities.add({
position: liftedFirstPosition,
orientation: Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(
liftedFirstPosition,
new Cesium.HeadingPitchRoll(initialHeadingRad + MODEL_HEADING_OFFSET, 0, 0),
)
: undefined,
model: {
uri: BOAT_MODEL_URI,
scale: BOAT_MODEL_SCALE,
minimumPixelSize: BOAT_MODEL_MIN_PIXEL_SIZE,
maximumScale: BOAT_MODEL_MAX_SCALE,
runAnimations: true,
},
});
const updateBoatState = (position: any, headingRad: number) => {
if (!previewBoatEntityRef.current) return;
const liftedPosition = offsetUp(Cesium, position, BOAT_HEIGHT_OFFSET);
previewBoatEntityRef.current.position = liftedPosition;
if (Cesium.Transforms?.headingPitchRollQuaternion) {
previewBoatEntityRef.current.orientation = Cesium.Transforms.headingPitchRollQuaternion(
liftedPosition,
new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0),
);
} }
const totalDist = distances[distances.length - 1] || 0;
if (totalDist <= 1) { try {
message.warning('航线过短,无法预览'); viewer.camera.lookAt(
setIsPreviewing(false); offsetUp(Cesium, position, 0.9),
new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22),
);
} catch {
// ignore
}
};
const cornerInfos = buildCornerInfos(Cesium, routePolylinePositions, distances, calculateHeading);
let lastTime = 0;
let traveled = 0;
let mode: 'move' | 'turn' = 'move';
let cornerPointer = 0;
let turnStartTime = 0;
let turnDistance = 0;
let turnFromHeadingDeg = 0;
let turnToHeadingDeg = 0;
const animate = (time: number) => {
const currentViewer = viewerRef?.current;
if (!currentViewer || currentViewer.isDestroyed?.()) {
stopPreview();
return; return;
} }
// Up方向偏移工具 if (!lastTime) lastTime = time;
const scratchEnu = new Cesium.Matrix4(); const deltaSeconds = Math.max(0, (time - lastTime) / 1000);
const scratchLocalOffset = new Cesium.Cartesian3(); lastTime = time;
const offsetUp = (origin: any, upMeters: number) => {
try {
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return origin;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchEnu);
scratchLocalOffset.x = 0; scratchLocalOffset.y = 0; scratchLocalOffset.z = upMeters;
return Cesium.Matrix4.multiplyByPoint(enu, scratchLocalOffset, new Cesium.Cartesian3());
} catch { return origin; }
};
// 创建船只实体
try {
const firstPos0 = polylinePositions[0];
const boatAboveRoute = 0.05;
const firstPos = offsetUp(firstPos0, boatAboveRoute);
const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0))
: undefined;
const hull = viewer.entities.add({
position: firstPos,
orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2),
material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92),
outline: true, outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const cabinOffsetFn = (basePos: any, headingRad: number) => {
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos);
const localOffset = new Cesium.Cartesian3(
Math.sin(headingRad) * 0.25, Math.cos(headingRad) * 0.25, 0.16
);
return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3());
};
const cabinPos = cabinOffsetFn(firstPos, 0);
const cabin = viewer.entities.add({
position: cabinPos, orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24),
material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95),
outline: true, outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const mast = viewer.entities.add({
position: cabinPos, orientation: initialOrientation,
cylinder: {
length: 0.38, topRadius: 0.015, bottomRadius: 0.015,
material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const markerImageUrl = typeof Cesium.buildModuleUrl === 'function'
? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png')
: '/cesium/Assets/Textures/maki/ferry.png';
const marker = viewer.entities.add({
position: offsetUp(firstPos0, boatAboveRoute + 0.12),
billboard: {
image: markerImageUrl, scale: 0.55,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6),
},
});
previewBoatPartsRef.current = { hull, cabin, mast, marker };
(previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute;
(previewBoatPartsRef.current as any).cabinOffset = cabinOffsetFn;
} catch (e) {
console.warn('创建预览船只实体失败:', e);
}
// 二分查找距离索引
const findIndexByDistance = (d: number) => {
let lo = 0, hi = distances.length - 1;
while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (distances[mid] < d) lo = mid + 1; else hi = mid; }
return Math.max(1, lo);
};
const scratchPosCur = new Cesium.Cartesian3();
const scratchPosA = new Cesium.Cartesian3();
const scratchPosB = new Cesium.Cartesian3();
const scratchCartoCur = new Cesium.Cartographic();
const scratchCartoA = new Cesium.Cartographic();
const scratchCartoB = new Cesium.Cartographic();
const fillSampleAtDistance = (d: number, outPos: any, outCarto: any) => {
const dd = Math.min(totalDist, Math.max(0, d));
const idx = findIndexByDistance(dd);
const prevD = distances[idx - 1] || 0;
const nextD = distances[idx] || prevD + 1;
const frac = Math.min(1, Math.max(0, (dd - prevD) / Math.max(1e-6, nextD - prevD)));
Cesium.Cartesian3.lerp(polylinePositions[idx - 1], polylinePositions[idx], frac, outPos);
try {
Cesium.Cartographic.fromCartesian(outPos, ellipsoid || undefined, outCarto);
} catch {
const c = Cesium.Cartographic.fromCartesian(outPos);
outCarto.longitude = c.longitude; outCarto.latitude = c.latitude; outCarto.height = c.height;
}
};
// 拐点检测
const turnAngleThresholdDeg = 12;
const turnHoldMs = 200;
const turnRotateMs = 650;
const normalizeAngleDeg = (deg: number) => ((deg % 360) + 360) % 360;
const shortestDeltaDeg = (fromDeg: number, toDeg: number) => {
let delta = normalizeAngleDeg(toDeg) - normalizeAngleDeg(fromDeg);
if (delta > 180) delta -= 360; if (delta < -180) delta += 360;
return delta;
};
const lerpHeadingDeg = (fromDeg: number, toDeg: number, f: number) => {
return normalizeAngleDeg(fromDeg + shortestDeltaDeg(fromDeg, toDeg) * Math.min(1, Math.max(0, f)));
};
const cornerInfos: Array<{ distance: number; fromHeading: number; toHeading: number }> = [];
try {
for (let i = 1; i < polylinePositions.length - 1; i++) {
const cPrev = new Cesium.Cartographic(), c = new Cesium.Cartographic(), cNext = new Cesium.Cartographic();
try {
Cesium.Cartographic.fromCartesian(polylinePositions[i - 1], ellipsoid, cPrev);
Cesium.Cartographic.fromCartesian(polylinePositions[i], ellipsoid, c);
Cesium.Cartographic.fromCartesian(polylinePositions[i + 1], ellipsoid, cNext);
} catch { continue; }
const h1 = calculateHeading(
{ longitude: Cesium.Math.toDegrees(cPrev.longitude), latitude: Cesium.Math.toDegrees(cPrev.latitude) },
{ longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) }
);
const h2 = calculateHeading(
{ longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) },
{ longitude: Cesium.Math.toDegrees(cNext.longitude), latitude: Cesium.Math.toDegrees(cNext.latitude) }
);
if (Math.abs(shortestDeltaDeg(h1, h2)) >= turnAngleThresholdDeg) {
cornerInfos.push({ distance: distances[i], fromHeading: h1, toHeading: h2 });
}
}
} catch { /* ignore */ }
let lastT = 0, traveled = 0;
let mode: 'move' | 'turn' = 'move';
let cornerPtr = 0, turnStartT = 0, turnFromHeading = 0, turnToHeading = 0, turnDistance = 0;
const animatePreview = (t: number) => {
if (!lastT) lastT = t;
const dt = Math.max(0, (t - lastT) / 1000);
lastT = t;
if (mode === 'move') { if (mode === 'move') {
traveled += dt * speed; traveled = Math.min(totalDistance, traveled + deltaSeconds * speed);
if (cornerPtr < cornerInfos.length && traveled >= cornerInfos[cornerPtr].distance) { if (cornerPointer < cornerInfos.length) {
traveled = cornerInfos[cornerPtr].distance; const nextCorner = cornerInfos[cornerPointer];
mode = 'turn'; turnStartT = t; if (traveled >= nextCorner.distance) {
turnFromHeading = cornerInfos[cornerPtr].fromHeading; traveled = nextCorner.distance;
turnToHeading = cornerInfos[cornerPtr].toHeading; mode = 'turn';
turnDistance = cornerInfos[cornerPtr].distance; cornerPointer += 1;
turnStartTime = time;
turnDistance = nextCorner.distance;
turnFromHeadingDeg = nextCorner.fromHeading;
turnToHeadingDeg = nextCorner.toHeading;
}
} }
} else { } else {
traveled = turnDistance; traveled = turnDistance;
if (t - turnStartT >= turnHoldMs + turnRotateMs) { if (time - turnStartTime >= TURN_HOLD_MS + TURN_ROTATE_MS) {
mode = 'move'; cornerPtr++; mode = 'move';
} }
} }
if (traveled >= totalDist) { if (traveled >= totalDistance) {
updateBoatState(
routePolylinePositions[routePolylinePositions.length - 1],
Cesium.Math.toRadians(turnToHeadingDeg || 0),
);
requestRender();
stopPreview(); stopPreview();
message.success('航线预览完成'); messageApi?.success('航线预览完成');
return; return;
} }
fillSampleAtDistance(traveled, scratchPosCur, scratchCartoCur); const currentPosition = samplePositionAtDistance(Cesium, routePolylinePositions, distances, traveled);
let headingDeg = getHeadingByDistance(
Cesium,
routePolylinePositions,
distances,
calculateHeading,
traveled,
speed,
);
let headingDeg = 0;
if (mode === 'turn') { if (mode === 'turn') {
const elapsed = t - turnStartT; const elapsedTurnMs = time - turnStartTime;
headingDeg = elapsed <= turnHoldMs if (elapsedTurnMs <= TURN_HOLD_MS) {
? turnFromHeading headingDeg = turnFromHeadingDeg;
: lerpHeadingDeg(turnFromHeading, turnToHeading, (elapsed - turnHoldMs) / Math.max(1, turnRotateMs));
} else { } else {
const delta = Math.max(0.6, Math.min(2.5, speed * 0.35)); headingDeg = lerpHeadingDeg(
fillSampleAtDistance(traveled - delta, scratchPosA, scratchCartoA); turnFromHeadingDeg,
fillSampleAtDistance(traveled + delta, scratchPosB, scratchCartoB); turnToHeadingDeg,
headingDeg = calculateHeading( (elapsedTurnMs - TURN_HOLD_MS) / Math.max(1, TURN_ROTATE_MS),
{ longitude: Cesium.Math.toDegrees(scratchCartoA.longitude), latitude: Cesium.Math.toDegrees(scratchCartoA.latitude) },
{ longitude: Cesium.Math.toDegrees(scratchCartoB.longitude), latitude: Cesium.Math.toDegrees(scratchCartoB.latitude) }
); );
} }
const headingRad = Cesium.Math.toRadians(headingDeg); } else {
turnToHeadingDeg = headingDeg;
// 更新船只位置
try {
if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.05;
const basePos = offsetUp(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0))
: undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current;
if (hull) { hull.position = basePos; if (orientation) hull.orientation = orientation; }
const cabinOffsetFn = (previewBoatPartsRef.current as any).cabinOffset;
const cabinPos = typeof cabinOffsetFn === 'function' ? cabinOffsetFn(basePos, headingRad) : basePos;
if (cabin) { cabin.position = cabinPos; if (orientation) cabin.orientation = orientation; }
if (mast) { mast.position = cabinPos; if (orientation) mast.orientation = orientation; }
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUp(scratchPosCur, boatAboveRoute + 0.12);
}
}
} catch { /* ignore */ }
// 追踪相机
try {
const target = offsetUp(scratchPosCur, 0.8);
viewer.camera.lookAt(target, new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(chasePitch), chaseRange));
} catch {
viewer.camera.setView({
destination: Cesium.Cartesian3.fromRadians(scratchCartoCur.longitude, scratchCartoCur.latitude, (Number(scratchCartoCur.height) || 0) + 10),
orientation: { heading: headingRad, pitch: Cesium.Math.toRadians(-10), roll: 0 },
});
} }
try { viewer.scene?.requestRender?.(); } catch { /* ignore */ } updateBoatState(currentPosition, Cesium.Math.toRadians(headingDeg));
previewAnimationRef.current = requestAnimationFrame(animatePreview); requestRender();
previewAnimationRef.current = requestAnimationFrame(animate);
}; };
// 先请求一次渲染再启动动画 const handleEsc = (event: KeyboardEvent) => {
try { viewer.scene?.requestRender?.(); } catch { /* ignore */ } if (event.key === 'Escape') {
setTimeout(() => { stopPreview();
previewAnimationRef.current = requestAnimationFrame(animatePreview); }
}, 120); };
escHandlerRef.current = handleEsc;
// ESC退出
const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') stopPreview(); };
window.addEventListener('keydown', handleEsc); window.addEventListener('keydown', handleEsc);
(previewAnimationRef as any).escHandler = handleEsc;
}, [viewerRef, getCesium, isPreviewing, stopPreview, calculateHeading, buildPreviewPolyline]);
// 组件卸载清理 requestRender();
previewAnimationRef.current = requestAnimationFrame(animate);
}, [
viewerRef,
getCesium,
isPreviewing,
stopPreview,
buildPreviewWaypointPositions,
getRouteSurfaceGeometry,
calculateHeading,
messageApi,
requestRender,
setStaticRouteEntitiesVisible,
]);
useEffect(() => { useEffect(() => {
return () => { return () => {
if (previewAnimationRef.current) cancelAnimationFrame(previewAnimationRef.current); stopPreview();
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler);
}
if (previewBoatPartsRef.current) {
try {
const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
}
} catch { /* ignore */ } finally {
previewBoatPartsRef.current = null;
}
}
if (previewRouteEntityRef.current) {
try {
const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) {
viewer.entities.remove(previewRouteEntityRef.current);
}
} catch { /* ignore */ } finally {
previewRouteEntityRef.current = null;
}
}
if (savedCameraStateRef.current && viewerRef?.current) {
const viewer = viewerRef.current;
const Cesium = (window as any).Cesium;
try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ }
try {
viewer.camera.setView({
destination: savedCameraStateRef.current.position,
orientation: {
heading: savedCameraStateRef.current.heading,
pitch: savedCameraStateRef.current.pitch,
roll: savedCameraStateRef.current.roll,
},
});
} catch { /* ignore */ } finally {
savedCameraStateRef.current = null;
}
}
}; };
}, [viewerRef]); }, [stopPreview]);
return { isPreviewing, startPreview, stopPreview }; return {
isPreviewing,
startPreview,
stopPreview,
};
}
function interpolateOnSegment(Cesium: any, start: any, end: any, fraction: number) {
return Cesium.Cartesian3.lerp(
start,
end,
Math.min(1, Math.max(0, fraction)),
new Cesium.Cartesian3(),
);
}
function samplePositionAtDistance(Cesium: any, positions: any[], distances: number[], distance: number) {
const clampedDistance = Math.max(0, Math.min(distances[distances.length - 1] || 0, distance));
const index = findIndexByDistance(distances, clampedDistance);
const previousDistance = distances[index - 1] || 0;
const nextDistance = distances[index] || previousDistance + 1;
const fraction = Math.min(
1,
Math.max(0, (clampedDistance - previousDistance) / Math.max(1e-6, nextDistance - previousDistance)),
);
return interpolateOnSegment(Cesium, positions[index - 1], positions[index], fraction);
}
function findIndexByDistance(distances: number[], distance: number) {
let low = 0;
let high = distances.length - 1;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (distances[mid] < distance) {
low = mid + 1;
} else {
high = mid;
}
}
return Math.max(1, low);
}
function getSegmentHeadingDegrees(
Cesium: any,
positions: any[],
calculateHeading: (
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => number,
segmentIndex: number,
) {
const safeIndex = Math.min(Math.max(segmentIndex, 0), positions.length - 2);
const start = positions[safeIndex];
const end = positions[safeIndex + 1];
const startCartographic = Cesium.Cartographic.fromCartesian(start);
const endCartographic = Cesium.Cartographic.fromCartesian(end);
const heading = calculateHeading(
{
longitude: Cesium.Math.toDegrees(startCartographic.longitude),
latitude: Cesium.Math.toDegrees(startCartographic.latitude),
},
{
longitude: Cesium.Math.toDegrees(endCartographic.longitude),
latitude: Cesium.Math.toDegrees(endCartographic.latitude),
},
);
return heading;
}
function getHeadingByDistance(
Cesium: any,
positions: any[],
distances: number[],
calculateHeading: (
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => number,
distance: number,
speed: number,
) {
const delta = Math.max(0.6, Math.min(2.5, speed * 0.35));
const fromPosition = samplePositionAtDistance(Cesium, positions, distances, distance - delta);
const toPosition = samplePositionAtDistance(Cesium, positions, distances, distance + delta);
const fromCartographic = Cesium.Cartographic.fromCartesian(fromPosition);
const toCartographic = Cesium.Cartographic.fromCartesian(toPosition);
return calculateHeading(
{
longitude: Cesium.Math.toDegrees(fromCartographic.longitude),
latitude: Cesium.Math.toDegrees(fromCartographic.latitude),
},
{
longitude: Cesium.Math.toDegrees(toCartographic.longitude),
latitude: Cesium.Math.toDegrees(toCartographic.latitude),
},
);
}
function buildCornerInfos(
Cesium: any,
positions: any[],
distances: number[],
calculateHeading: (
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => number,
) {
const cornerInfos: Array<{ distance: number; fromHeading: number; toHeading: number }> = [];
for (let index = 1; index < positions.length - 1; index += 1) {
const fromHeading = getSegmentHeadingDegrees(Cesium, positions, calculateHeading, index - 1);
const toHeading = getSegmentHeadingDegrees(Cesium, positions, calculateHeading, index);
const angle = Math.abs(shortestDeltaDeg(fromHeading, toHeading));
if (angle >= TURN_ANGLE_THRESHOLD_DEG) {
cornerInfos.push({
distance: distances[index],
fromHeading,
toHeading,
});
}
}
return cornerInfos;
}
function normalizeAngleDeg(degree: number) {
return ((degree % 360) + 360) % 360;
}
function shortestDeltaDeg(fromDegree: number, toDegree: number) {
let delta = normalizeAngleDeg(toDegree) - normalizeAngleDeg(fromDegree);
if (delta > 180) delta -= 360;
if (delta < -180) delta += 360;
return delta;
}
function lerpHeadingDeg(fromDegree: number, toDegree: number, fraction: number) {
return normalizeAngleDeg(
fromDegree + shortestDeltaDeg(fromDegree, toDegree) * Math.min(1, Math.max(0, fraction)),
);
}
function offsetUp(Cesium: any, origin: any, upMeters: number) {
try {
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
return Cesium.Matrix4.multiplyByPoint(enu, new Cesium.Cartesian3(0, 0, upMeters), new Cesium.Cartesian3());
} catch {
return origin;
}
} }
@@ -189,6 +189,17 @@
flex: 1; flex: 1;
height: 100%; height: 100%;
position: relative; position: relative;
min-width: 0;
}
.execRightPanel {
width: 340px;
height: 100%;
flex-shrink: 0;
@media (max-width: 1366px) {
width: 300px;
}
} }
/* ========== 沉浸模式标记 ========== */ /* ========== 沉浸模式标记 ========== */
+138 -56
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useCallback, useState, useRef, useMemo } from 'react'; import React, { useEffect, useCallback, useState, useRef, useMemo } from 'react';
import { ConfigProvider, Button, Spin } from 'antd'; import { App as AntdApp, ConfigProvider, Button, Spin, message, Modal } from 'antd';
import { import {
LogoutOutlined, LogoutOutlined,
DisconnectOutlined, DisconnectOutlined,
@@ -19,14 +19,15 @@ import LeftPanel from './components/LeftPanel';
import CenterView from './components/CenterView'; import CenterView from './components/CenterView';
import ExecLeftPanel from './components/ExecLeftPanel'; import ExecLeftPanel from './components/ExecLeftPanel';
import ExecBottomStrip from './components/ExecBottomStrip'; import ExecBottomStrip from './components/ExecBottomStrip';
import ExecRightPanel from './components/ExecRightPanel';
import { useClientAuth } from './hooks/useClientAuth'; import { useClientAuth } from './hooks/useClientAuth';
import { useClientSSE } from './hooks/useClientSSE'; import { useClientSSE } from './hooks/useClientSSE';
import { useRouteData } from './hooks/useRouteData'; import { useRouteData } from './hooks/useRouteData';
import { useNavigationState } from './hooks/useNavigationState'; import { useNavigationState } from './hooks/useNavigationState';
import { useNavigationData } from './hooks/useNavigationData'; import { useNavigationData } from './hooks/useNavigationData';
import { getValidCoordinate } from '@/utils/geo';
import styles from './index.less'; import styles from './index.less';
/** 船 Logo SVG */
const ShipLogoIcon: React.FC = () => ( const ShipLogoIcon: React.FC = () => (
<svg width="20" height="20" viewBox="0 0 36 36" fill="none"> <svg width="20" height="20" viewBox="0 0 36 36" fill="none">
<path d="M6 27L8.4 21H27.6L30 27C30 27 25.5 30 18 30C10.5 30 6 27 6 27Z" fill="white" fillOpacity="0.9" /> <path d="M6 27L8.4 21H27.6L30 27C30 27 25.5 30 18 30C10.5 30 6 27 6 27Z" fill="white" fillOpacity="0.9" />
@@ -36,7 +37,6 @@ const ShipLogoIcon: React.FC = () => (
</svg> </svg>
); );
/** 格式化秒数为 HH:MM:SS */
const formatElapsed = (totalSec: number) => { const formatElapsed = (totalSec: number) => {
const h = Math.floor(totalSec / 3600).toString().padStart(2, '0'); const h = Math.floor(totalSec / 3600).toString().padStart(2, '0');
const m = Math.floor((totalSec % 3600) / 60).toString().padStart(2, '0'); const m = Math.floor((totalSec % 3600) / 60).toString().padStart(2, '0');
@@ -44,18 +44,58 @@ const formatElapsed = (totalSec: number) => {
return `${h}:${m}:${s}`; return `${h}:${m}:${s}`;
}; };
const calculateDistanceMeters = (
from: { longitude: number; latitude: number },
to: { longitude: number; latitude: number },
) => {
const earthRadius = 6371000;
const dLat = (to.latitude - from.latitude) * Math.PI / 180;
const dLon = (to.longitude - from.longitude) * Math.PI / 180;
const lat1 = from.latitude * Math.PI / 180;
const lat2 = to.latitude * Math.PI / 180;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
return earthRadius * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
};
const ClientPage: React.FC = () => { const ClientPage: React.FC = () => {
// ── 认证 ── const [messageApi, messageContextHolder] = message.useMessage();
const { boatData: sseBoatData, sseConnected, loading: sseLoading, deviceOffline, connectSSE, disconnectSSE } = useClientSSE(); const [modalApi, modalContextHolder] = Modal.useModal();
const {
boatData: sseBoatData,
sseConnected,
loading: sseLoading,
deviceOffline,
connectSSE,
disconnectSSE,
} = useClientSSE();
const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE); const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE);
// ── 航线数据 ── const {
const { routes, routeWaypointsMap, selectedRouteId, setSelectedRouteId, routeLoading } = routes,
useRouteData(deviceSn); routeWaypointsMap,
selectedRouteId,
setSelectedRouteId,
routeLoading,
} = useRouteData(deviceSn);
const boatData = sseBoatData; const boatData = sseBoatData;
const boatPosition = useMemo(
() => getValidCoordinate(boatData?.longitude, boatData?.latitude),
[boatData?.longitude, boatData?.latitude],
);
const hasBoatPosition = !!boatPosition;
const videoStreamUrl = useMemo(() => {
const rawInfo = deviceInfo as any;
return rawInfo?.videoStreamUrl
|| rawInfo?.whepUrl
|| rawInfo?.streamUrl
|| rawInfo?.videoUrl
|| rawInfo?.liveStreamUrl
|| undefined;
}, [deviceInfo]);
// ── 沉浸模式状态机 ──
const { const {
isPaused, isPaused,
currentWaypointIndex, currentWaypointIndex,
@@ -70,43 +110,85 @@ const ClientPage: React.FC = () => {
handleResumeSailing, handleResumeSailing,
handleStopSailing, handleStopSailing,
handleStopPreview, handleStopPreview,
handleEmergencyStop,
handlePreviewChange, handlePreviewChange,
} = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes); } = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes, messageApi, modalApi);
// ── SSE 连接 ──
useEffect(() => { useEffect(() => {
if (!deviceSn) return; if (!deviceSn) return;
connectSSE(deviceSn); connectSSE(deviceSn);
return () => { disconnectSSE(); }; return () => {
}, [deviceSn]); disconnectSSE();
};
}, [deviceSn, connectSSE, disconnectSSE]);
// ── 沉浸模式计时器 ──
const [elapsed, setElapsed] = useState(0); const [elapsed, setElapsed] = useState(0);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null); const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const [previewStartSignal, setPreviewStartSignal] = useState(0); const [previewStartSignal, setPreviewStartSignal] = useState(0);
useEffect(() => { useEffect(() => {
if (isImmersive && !isPaused) { if (isImmersive && !isPaused) {
timerRef.current = setInterval(() => setElapsed((s) => s + 1), 1000); timerRef.current = setInterval(() => setElapsed((seconds) => seconds + 1), 1000);
} else if (timerRef.current) { } else if (timerRef.current) {
clearInterval(timerRef.current); clearInterval(timerRef.current);
timerRef.current = null; timerRef.current = null;
} }
if (!isImmersive) setElapsed(0);
return () => { if (timerRef.current) clearInterval(timerRef.current); }; if (!isImmersive) {
setElapsed(0);
}
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, [isImmersive, isPaused]); }, [isImmersive, isPaused]);
// ── 预览航线回调 ──
const handlePreviewRoute = useCallback((routeId: string) => { const handlePreviewRoute = useCallback((routeId: string) => {
if (routeId !== selectedRouteId) { if (routeId !== selectedRouteId) {
setSelectedRouteId(routeId); setSelectedRouteId(routeId);
} }
// 延迟递增信号,让 selectedRouteId 先生效触发航点加载 setTimeout(() => setPreviewStartSignal((signal) => signal + 1), 200);
setTimeout(() => setPreviewStartSignal((s) => s + 1), 200);
}, [selectedRouteId, setSelectedRouteId]); }, [selectedRouteId, setSelectedRouteId]);
// ── 预先计算航线基础信息(不依赖 boatData) ── const handleExecuteRoute = useCallback(async (routeId: string) => {
const firstWaypoint = routeWaypointsMap[routeId]?.[0];
if (!firstWaypoint) {
messageApi.warning('当前航线缺少起始航点,无法执行');
return;
}
if (!hasBoatPosition) {
messageApi.warning('尚未收到无人船实时位置,暂时不能执行航线');
return;
}
const distance = calculateDistanceMeters(
boatPosition!,
{ longitude: firstWaypoint.longitude, latitude: firstWaypoint.latitude },
);
if (distance > 200) {
modalApi.warning({
title: '无法执行航线',
centered: true,
width: 500,
okText: '知道了',
content: (
<div style={{ paddingTop: 8, textAlign: 'center', lineHeight: 1.9, fontSize: 16 }}>
<div>
无人船距离航线起点约
<span style={{ color: '#ff7875', fontWeight: 700, margin: '0 6px' }}>
{Math.round(distance)} 米
</span>
</div>
<div>已超过 200 米,请先将无人船驶近起点后再执行。</div>
</div>
),
});
return;
}
await handleStartSailing(routeId);
}, [routeWaypointsMap, boatPosition, hasBoatPosition, handleStartSailing, messageApi, modalApi]);
const activeWaypointsRaw = useMemo(() => { const activeWaypointsRaw = useMemo(() => {
if (!activeRouteId) return []; if (!activeRouteId) return [];
return routeWaypointsMap[activeRouteId] || []; return routeWaypointsMap[activeRouteId] || [];
@@ -114,45 +196,40 @@ const ClientPage: React.FC = () => {
const activeRouteInfoRaw = useMemo(() => { const activeRouteInfoRaw = useMemo(() => {
if (!activeRouteId) return null; if (!activeRouteId) return null;
return routes.find((r) => r.routeId === activeRouteId) || null; return routes.find((route) => route.routeId === activeRouteId) || null;
}, [activeRouteId, routes]); }, [activeRouteId, routes]);
// ── 预览模式假数据 ──
const effectiveBoatData = useMemo(() => { const effectiveBoatData = useMemo(() => {
if (!isPreviewing) return boatData; if (!isPreviewing) return boatData;
// 如果有真实 SSE 数据,优先使用 if (hasBoatPosition) return boatData;
if (boatData?.longitude) return boatData;
// 预览模式下根据航线航点和经过时间生成模拟遥测数据
if (activeWaypointsRaw.length === 0) return null; if (activeWaypointsRaw.length === 0) return null;
const previewSpeed = 2; // m/s,与预览动画速度一致 const previewSpeed = 2;
const totalDist = activeRouteInfoRaw?.totalDistance || 1000; const totalDist = activeRouteInfoRaw?.totalDistance || 1000;
const traveled = elapsed * previewSpeed; const traveled = elapsed * previewSpeed;
const fraction = Math.min(traveled / totalDist, 0.99); const fraction = Math.min(traveled / totalDist, 0.99);
const wpIdx = Math.min( const waypointIdx = Math.min(
Math.floor(fraction * (activeWaypointsRaw.length - 1)), Math.floor(fraction * (activeWaypointsRaw.length - 1)),
activeWaypointsRaw.length - 2, activeWaypointsRaw.length - 2,
); );
const wp = activeWaypointsRaw[wpIdx]; const waypoint = activeWaypointsRaw[waypointIdx];
const nextWp = activeWaypointsRaw[wpIdx + 1] || wp; const nextWaypoint = activeWaypointsRaw[waypointIdx + 1] || waypoint;
// 航段内插值 const segFraction = (fraction * (activeWaypointsRaw.length - 1)) - waypointIdx;
const segFrac = (fraction * (activeWaypointsRaw.length - 1)) - wpIdx; const longitude = waypoint.longitude + (nextWaypoint.longitude - waypoint.longitude) * segFraction;
const lon = wp.longitude + (nextWp.longitude - wp.longitude) * segFrac; const latitude = waypoint.latitude + (nextWaypoint.latitude - waypoint.latitude) * segFraction;
const lat = wp.latitude + (nextWp.latitude - wp.latitude) * segFrac;
// 计算航向 const dLon = (nextWaypoint.longitude - waypoint.longitude) * Math.PI / 180;
const dLon = (nextWp.longitude - wp.longitude) * Math.PI / 180; const lat1 = waypoint.latitude * Math.PI / 180;
const lat1 = wp.latitude * Math.PI / 180; const lat2 = nextWaypoint.latitude * Math.PI / 180;
const lat2 = nextWp.latitude * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2); const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const heading = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360; const heading = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360;
return { return {
deviceSn: deviceSn || '', deviceSn: deviceSn || '',
longitude: lon, longitude,
latitude: lat, latitude,
heading, heading,
speed: previewSpeed, speed: previewSpeed,
battery: 85, battery: 85,
@@ -160,9 +237,8 @@ const ClientPage: React.FC = () => {
status: 'preview', status: 'preview',
recordTime: new Date().toISOString(), recordTime: new Date().toISOString(),
} as import('@/types/boatRoute').BoatTelemetryData; } as import('@/types/boatRoute').BoatTelemetryData;
}, [isPreviewing, boatData, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]); }, [isPreviewing, boatData, hasBoatPosition, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]);
// ── 导航计算(使用 effectiveBoatData 以便预览模式也有数据) ──
const { const {
activeWaypoints, activeWaypoints,
activeRouteInfo, activeRouteInfo,
@@ -178,9 +254,10 @@ const ClientPage: React.FC = () => {
return ( return (
<ConfigProvider theme={darkTheme}> <ConfigProvider theme={darkTheme}>
<AntdApp>
{messageContextHolder}
{modalContextHolder}
<div className={`${styles.container} ${isImmersive ? styles.sailing : ''}`}> <div className={`${styles.container} ${isImmersive ? styles.sailing : ''}`}>
{/* ========== 普通模式 - 顶部导航栏 ========== */}
{!isImmersive && ( {!isImmersive && (
<div className={styles.navBar}> <div className={styles.navBar}>
<div className={styles.navLogo}> <div className={styles.navLogo}>
@@ -228,7 +305,6 @@ const ClientPage: React.FC = () => {
</div> </div>
)} )}
{/* ========== 沉浸模式 - 执行导航栏 ========== */}
{isImmersive && ( {isImmersive && (
<div className={styles.execNav}> <div className={styles.execNav}>
<button <button
@@ -243,7 +319,7 @@ const ClientPage: React.FC = () => {
{activeRouteInfo?.routeName || '航线'} · {modeLabel} {activeRouteInfo?.routeName || '航线'} · {modeLabel}
</div> </div>
<div className={styles.execSubtitle}> <div className={styles.execSubtitle}>
{deviceInfo.deviceName || deviceSn} · 已{isPreviewing ? '预览' : '执行'} {formatElapsed(elapsed)} {deviceInfo.deviceName || deviceSn} · {isPreviewing ? '预览' : '执行'} · {formatElapsed(elapsed)}
</div> </div>
</div> </div>
@@ -275,10 +351,7 @@ const ClientPage: React.FC = () => {
</div> </div>
)} )}
{/* ========== 主体区域 ========== */}
<div className={styles.mainBody}> <div className={styles.mainBody}>
{/* 设备离线遮罩 */}
{deviceOffline && !sseConnected && ( {deviceOffline && !sseConnected && (
<div className={styles.offlineOverlay}> <div className={styles.offlineOverlay}>
<div className={styles.offlineCard}> <div className={styles.offlineCard}>
@@ -305,7 +378,6 @@ const ClientPage: React.FC = () => {
</div> </div>
)} )}
{/* 左侧边栏 - 普通模式 */}
{!isImmersive && ( {!isImmersive && (
<div className={styles.leftPanel}> <div className={styles.leftPanel}>
<LeftPanel <LeftPanel
@@ -317,14 +389,13 @@ const ClientPage: React.FC = () => {
deviceInfo={deviceInfo} deviceInfo={deviceInfo}
boatData={boatData} boatData={boatData}
sseConnected={sseConnected} sseConnected={sseConnected}
onStartSailing={handleStartSailing} onStartSailing={handleExecuteRoute}
onPreviewRoute={handlePreviewRoute} onPreviewRoute={handlePreviewRoute}
sailingLoading={sailingLoading} sailingLoading={sailingLoading}
/> />
</div> </div>
)} )}
{/* 左侧面板 - 沉浸模式 (仪表盘 + 航点列表) */}
{isImmersive && ( {isImmersive && (
<ExecLeftPanel <ExecLeftPanel
boatData={effectiveBoatData} boatData={effectiveBoatData}
@@ -333,7 +404,6 @@ const ClientPage: React.FC = () => {
/> />
)} )}
{/* 地图区域 */}
<div className={styles.centerView}> <div className={styles.centerView}>
<CenterView <CenterView
deviceSn={deviceSn} deviceSn={deviceSn}
@@ -348,8 +418,7 @@ const ClientPage: React.FC = () => {
onPreviewChange={handlePreviewChange} onPreviewChange={handlePreviewChange}
/> />
{/* 沉浸模式 - 底部航线信息条 */} {isSailing && (
{isImmersive && (
<ExecBottomStrip <ExecBottomStrip
progress={progress} progress={progress}
currentWaypointIndex={currentWaypointIndex} currentWaypointIndex={currentWaypointIndex}
@@ -360,8 +429,21 @@ const ClientPage: React.FC = () => {
)} )}
</div> </div>
{isImmersive && (
<div className={styles.execRightPanel}>
<ExecRightPanel
deviceInfo={deviceInfo}
boatData={effectiveBoatData}
activeRouteInfo={activeRouteInfo}
sseConnected={sseConnected}
videoStreamUrl={videoStreamUrl}
isPreviewing={isPreviewing}
/>
</div>
)}
</div> </div>
</div> </div>
</AntdApp>
</ConfigProvider> </ConfigProvider>
); );
}; };
@@ -457,11 +457,11 @@ const LayerPanel: React.FC<LayerPanelProps> = ({
// 忽略 // 忽略
} }
const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)); const positions = poly.outer.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean);
if (positions.length < 3) return; if (positions.length < 3) return;
const holes = poly.holes const holes = poly.holes
.map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))) .map((ring) => ring.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).filter(Boolean))
.filter((ring) => ring.length >= 3) .filter((ring) => ring.length >= 3)
.map((ring) => new Cesium.PolygonHierarchy(ring)); .map((ring) => new Cesium.PolygonHierarchy(ring));
@@ -490,11 +490,13 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船 ? Cesium.Color.fromCssColorString('#52c41a').withAlpha(0.9) // 绿色 - 无人船
: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机 : Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9); // 蓝色 - 无人机
// 绘制航线 // 绘制航线(确保 positions 不含 undefined/null 值)
const validPolylinePositions = polylinePositions.filter(Boolean);
if (validPolylinePositions.length < 2) return;
waylineEntityRef.current = viewer.entities.add({ waylineEntityRef.current = viewer.entities.add({
name: isBoatRoute ? '无人船航线' : '无人机航线', name: isBoatRoute ? '无人船航线' : '无人机航线',
polyline: { polyline: {
positions: polylinePositions, positions: validPolylinePositions,
width: 6, width: 6,
material: routeColor, material: routeColor,
clampToGround: false, // 已经手动贴地,不需要clampToGround clampToGround: false, // 已经手动贴地,不需要clampToGround
@@ -6,6 +6,7 @@
*/ */
import { useEffect, useRef, useCallback, useMemo } from 'react'; import { useEffect, useRef, useCallback, useMemo } from 'react';
import { useBoatSSE } from './useBoatSSE'; import { useBoatSSE } from './useBoatSSE';
import { getValidCoordinate } from '@/utils/geo';
interface UseCesiumBoatTrackOptions { interface UseCesiumBoatTrackOptions {
viewerRef: React.RefObject<any>; viewerRef: React.RefObject<any>;
@@ -39,6 +40,9 @@ export function useCesiumBoatTrack({
return (window as any).Cesium; return (window as any).Cesium;
}, []); }, []);
// GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差)
const MODEL_HEADING_OFFSET = -Math.PI / 2;
/** /**
* 飞到无人船位置 * 飞到无人船位置
*/ */
@@ -46,13 +50,14 @@ export function useCesiumBoatTrack({
const viewer = viewerRef.current; const viewer = viewerRef.current;
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!boatData?.longitude || !boatData?.latitude) return; const boatPosition = getValidCoordinate(boatData?.longitude, boatData?.latitude);
if (!boatPosition) return;
try { try {
viewer.camera.flyTo({ viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees( destination: Cesium.Cartesian3.fromDegrees(
boatData.longitude, boatPosition.longitude,
boatData.latitude, boatPosition.latitude,
1000 // 视角高度1000米 1000 // 视角高度1000米
), ),
orientation: { orientation: {
@@ -119,9 +124,12 @@ export function useCesiumBoatTrack({
*/ */
const realtimePosition = useMemo(() => { const realtimePosition = useMemo(() => {
if (!boatData) return null; if (!boatData) return null;
const boatPosition = getValidCoordinate(boatData.longitude, boatData.latitude);
if (!boatPosition) return null;
return { return {
longitude: boatData.longitude, longitude: boatPosition.longitude,
latitude: boatData.latitude, latitude: boatPosition.latitude,
heading: boatData.heading ?? 0, heading: boatData.heading ?? 0,
speed: boatData.speed ?? 0, speed: boatData.speed ?? 0,
battery: boatData.battery ?? 0, battery: boatData.battery ?? 0,
@@ -138,7 +146,6 @@ export function useCesiumBoatTrack({
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!realtimePosition) return; if (!realtimePosition) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const now = Date.now(); const now = Date.now();
const currentPos = { const currentPos = {
@@ -170,6 +177,13 @@ export function useCesiumBoatTrack({
realtimePosition.latitude, realtimePosition.latitude,
0 // 无人船在水面,高度为0 0 // 无人船在水面,高度为0
); );
const headingRad = Cesium.Math.toRadians(realtimePosition.heading || 0);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(
position,
new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)
)
: undefined;
// 构建标签文本 // 构建标签文本
const labelText = [ const labelText = [
@@ -182,19 +196,26 @@ export function useCesiumBoatTrack({
// 更新或创建船位置Entity // 更新或创建船位置Entity
if (boatEntityRef.current) { if (boatEntityRef.current) {
boatEntityRef.current.position = position; boatEntityRef.current.position = position;
if (orientation) {
boatEntityRef.current.orientation = orientation;
}
if (boatEntityRef.current.label) { if (boatEntityRef.current.label) {
boatEntityRef.current.label.text = labelText; boatEntityRef.current.label.text = labelText;
} }
} else { } else {
boatEntityRef.current = viewer.entities.add({ boatEntityRef.current = viewer.entities.add({
name: '无人船实时位置', name: '无人船实时位置',
position: position, position,
point: { orientation,
pixelSize: 16, model: {
color: Cesium.Color.BLUE, uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`,
outlineColor: Cesium.Color.WHITE, scale: 0.001,
outlineWidth: 3, minimumPixelSize: 64,
disableDepthTestDistance: Number.POSITIVE_INFINITY, maximumScale: 200,
runAnimations: true,
colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
color: Cesium.Color.WHITE,
silhouetteSize: 0,
}, },
label: { label: {
text: labelText, text: labelText,
@@ -204,7 +225,7 @@ export function useCesiumBoatTrack({
outlineWidth: 2, outlineWidth: 2,
outlineColor: Cesium.Color.BLACK, outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM, verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20), pixelOffset: new Cesium.Cartesian2(0, -28),
disableDepthTestDistance: Number.POSITIVE_INFINITY, disableDepthTestDistance: Number.POSITIVE_INFINITY,
}, },
properties: { properties: {
@@ -224,21 +245,21 @@ export function useCesiumBoatTrack({
} }
// 绘制飞行轨迹(至少2个点才能绘制线) // 绘制飞行轨迹(至少2个点才能绘制线)
if (trackPositionsRef.current.length >= 2) { const validTrackPositions = trackPositionsRef.current.filter(Boolean);
if (validTrackPositions.length >= 2) {
if (trackEntityRef.current) { if (trackEntityRef.current) {
trackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; trackEntityRef.current.polyline.positions = validTrackPositions;
} else { } else {
trackEntityRef.current = viewer.entities.add({ trackEntityRef.current = viewer.entities.add({
name: '无人船航行轨迹', name: '无人船航行轨迹',
polyline: { polyline: {
positions: [...trackPositionsRef.current], positions: validTrackPositions,
width: 4, width: 4,
material: new Cesium.PolylineGlowMaterialProperty({ material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3, glowPower: 0.3,
color: Cesium.Color.BLUE, color: Cesium.Color.BLUE,
}), }),
clampToGround: true, clampToGround: true,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}, },
properties: { properties: {
type: 'boat-track', type: 'boat-track',
@@ -56,6 +56,8 @@ export interface UseTilesetLoaderResult {
export const useTilesetLoader = (): UseTilesetLoaderResult => { export const useTilesetLoader = (): UseTilesetLoaderResult => {
const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map()); const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map());
const tilesetsRef = useRef<Map<string, any>>(new Map()); const tilesetsRef = useRef<Map<string, any>>(new Map());
// 存储 loadProgress 事件移除函数,防止监听器泄漏
const progressListenersRef = useRef<Map<string, () => void>>(new Map());
/** /**
* 加载3D Tiles模型 * 加载3D Tiles模型
@@ -139,8 +141,8 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
show: config.visible !== false, show: config.visible !== false,
}); });
// 监听加载进度 // 监听加载进度(保存移除函数以便清理)
tileset.loadProgress.addEventListener((numberOfPendingRequests: number, numberOfTilesProcessing: number) => { const progressHandler = (numberOfPendingRequests: number, numberOfTilesProcessing: number) => {
const total = numberOfPendingRequests + numberOfTilesProcessing; const total = numberOfPendingRequests + numberOfTilesProcessing;
const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100; const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100;
@@ -152,7 +154,9 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
} }
return newMap; return newMap;
}); });
}); };
const removeListener = tileset.loadProgress.addEventListener(progressHandler);
progressListenersRef.current.set(config.id, removeListener);
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移 // 模型位置调整 - 根据当前地形类型选择对应的高度偏移
if (config.position) { if (config.position) {
@@ -271,6 +275,13 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
* 卸载指定模型 * 卸载指定模型
*/ */
const unloadTileset = useCallback((id: string, viewer: any) => { const unloadTileset = useCallback((id: string, viewer: any) => {
// 移除 loadProgress 监听器
const removeListener = progressListenersRef.current.get(id);
if (removeListener) {
try { removeListener(); } catch { /* ignore */ }
progressListenersRef.current.delete(id);
}
const tileset = tilesetsRef.current.get(id); const tileset = tilesetsRef.current.get(id);
if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) { if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
@@ -292,6 +303,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
const unloadAllTilesets = useCallback((viewer: any) => { const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return; if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return;
// 移除所有 loadProgress 监听器
progressListenersRef.current.forEach((removeListener) => {
try { removeListener(); } catch { /* ignore */ }
});
progressListenersRef.current.clear();
tilesetsRef.current.forEach((tileset, id) => { tilesetsRef.current.forEach((tileset, id) => {
viewer.scene.primitives.remove(tileset); viewer.scene.primitives.remove(tileset);
}); });
@@ -11,6 +11,7 @@ import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { useDroneSSE } from './3d/hooks/useDroneSSE'; import { useDroneSSE } from './3d/hooks/useDroneSSE';
import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel'; import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel';
import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel"; import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel";
import { getValidCoordinate } from '@/utils/geo';
// 动态导入Cesium // 动态导入Cesium
let Cesium: any = null; let Cesium: any = null;
@@ -95,10 +96,13 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 检查 viewer 是否已销毁 // 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return; if (viewerRef.current.isDestroyed?.()) return;
const lon = parseFloat(device.longitude); let lon = parseFloat(device.longitude);
const lat = parseFloat(device.latitude); let lat = parseFloat(device.latitude);
if (isNaN(lon) || isNaN(lat)) return; const coordinate = getValidCoordinate(lon, lat);
if (!coordinate) return;
lon = coordinate.longitude;
lat = coordinate.latitude;
viewerRef.current.camera.flyTo({ viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 10000m 高度 destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 10000m 高度
@@ -492,9 +496,12 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 计算无人机实时位置 // 计算无人机实时位置
const realtimePosition = useMemo(() => { const realtimePosition = useMemo(() => {
if (!droneData) return null; if (!droneData) return null;
const coordinate = getValidCoordinate(droneData.longitude, droneData.latitude);
if (!coordinate) return null;
return { return {
longitude: droneData.longitude, longitude: coordinate.longitude,
latitude: droneData.latitude, latitude: coordinate.latitude,
height: droneData.height, // 相对高度(相对于起飞点) height: droneData.height, // 相对高度(相对于起飞点)
elevation: droneData.elevation, // 海拔高度(椭球高度) elevation: droneData.elevation, // 海拔高度(椭球高度)
// 3D地图显示用 height(相对高度),与航线的 height 对应 // 3D地图显示用 height(相对高度),与航线的 height 对应
@@ -605,14 +612,15 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
trackPositionsRef.current.push(pos); trackPositionsRef.current.push(pos);
// 绘制飞行轨迹 // 绘制飞行轨迹
if (trackPositionsRef.current.length >= 2) { const validTrackPositions = trackPositionsRef.current.filter(Boolean);
if (validTrackPositions.length >= 2) {
if (flightTrackEntityRef.current) { if (flightTrackEntityRef.current) {
flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current]; flightTrackEntityRef.current.polyline.positions = validTrackPositions;
} else { } else {
flightTrackEntityRef.current = viewerRef.current.entities.add({ flightTrackEntityRef.current = viewerRef.current.entities.add({
name: '飞行轨迹', name: '飞行轨迹',
polyline: { polyline: {
positions: [...trackPositionsRef.current], positions: validTrackPositions,
width: 4, width: 4,
material: new Cesium.PolylineGlowMaterialProperty({ material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3, glowPower: 0.3,
@@ -823,6 +831,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
creditContainer.style.display = 'none'; creditContainer.style.display = 'none';
} }
// 捕获 Cesium 渲染循环中的错误,避免页面崩溃
viewerRef.current.scene.renderError.addEventListener((scene: any, error: any) => {
console.error('[CesiumContainer] 渲染循环错误:', error);
});
setLoading(false); setLoading(false);
setViewerReady(true); // Viewer 初始化完成 setViewerReady(true); // Viewer 初始化完成
console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true'); console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true');
@@ -861,7 +874,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const validDevices = deviceList.filter((device) => { const validDevices = deviceList.filter((device) => {
const lat = parseFloat(device.latitude); const lat = parseFloat(device.latitude);
const lng = parseFloat(device.longitude); const lng = parseFloat(device.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0; return !!getValidCoordinate(lng, lat);
}); });
if (validDevices.length === 0) return; if (validDevices.length === 0) return;
@@ -1,6 +1,6 @@
/** /**
* Cesium 已规划航线渲染 Hook * Cesium 已规划航线渲�?Hook
* 负责在 Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重) * 负责�?Cesium 地图上渲染“航线库”里勾选显示的航线(只渲染线与起终点,避免太重�?
*/ */
import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useCallback, useEffect, useMemo, useRef } from 'react';
import type { BoatWaypointDTO } from '@/types/boatRoute'; import type { BoatWaypointDTO } from '@/types/boatRoute';
@@ -18,6 +18,11 @@ interface UseCesiumRouteLibraryRendererOptions {
routes: RouteLibraryRenderItem[]; routes: RouteLibraryRenderItem[];
} }
export interface RouteSurfaceGeometry {
polyline: any[];
waypointPositions: any[];
}
export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) { export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) {
const { viewerRef, routes } = options; const { viewerRef, routes } = options;
@@ -27,8 +32,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const surfaceRetryRef = useRef<Map<string, { key: string; attempt: number; timer: any | null }>>(new Map()); const surfaceRetryRef = useRef<Map<string, { key: string; attempt: number; timer: any | null }>>(new Map());
const routesRef = useRef<RouteLibraryRenderItem[]>(routes); const routesRef = useRef<RouteLibraryRenderItem[]>(routes);
// 贴近模型表面,避免航线“悬浮” // 贴近模型表面,避免航线“悬浮�?
const ROUTE_RENDER_HEIGHT_OFFSET = 0.05; const ROUTE_RENDER_HEIGHT_OFFSET = 1.2;
const getCesium = useCallback(() => (window as any).Cesium, []); const getCesium = useCallback(() => (window as any).Cesium, []);
@@ -95,7 +100,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
return result; return result;
}, []); }, []);
const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { const clampPositionsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 2) return null; if (!Array.isArray(positions) || positions.length < 2) return null;
@@ -108,21 +113,21 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const clamped = await fn.call(scene, positions); const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
const fallbacks = groundPositions || positions;
let definedCount = 0; let definedCount = 0;
const merged = clamped.map((p: any, idx: number) => { const merged = clamped.map((p: any, idx: number) => {
if (p) definedCount++; if (p) definedCount++;
return p || positions[idx]; return p || fallbacks[idx];
}); });
if (definedCount < 2) return null; if (definedCount < 2) return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); // If barely clamped, just return what we have (mixed with fallbacks) to prevent line breaks
return merged.map((p: any) => applyHeightOffset(Cesium, p)); return merged.map((p: any) => applyHeightOffset(Cesium, p)).filter(Boolean); } catch {
} catch {
return null; return null;
} }
}, [viewerRef, applyHeightOffset]); }, [viewerRef, applyHeightOffset]);
const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[]) => { const clampWaypointsToModelSurface = useCallback(async (Cesium: any, positions: any[], groundPositions?: any[]) => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.() || !Cesium) return null; if (!viewer || viewer.isDestroyed?.() || !Cesium) return null;
if (!Array.isArray(positions) || positions.length < 1) return null; if (!Array.isArray(positions) || positions.length < 1) return null;
@@ -134,7 +139,11 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
try { try {
const clamped = await fn.call(scene, positions); const clamped = await fn.call(scene, positions);
if (!Array.isArray(clamped) || clamped.length !== positions.length) return null; if (!Array.isArray(clamped) || clamped.length !== positions.length) return null;
return clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || positions[idx])); // �?clamp 失败时,用地面位置(高度0)而非 300m 探测位置
const fallbacks = groundPositions || positions;
const result = clamped.map((p: any, idx: number) => applyHeightOffset(Cesium, p || fallbacks[idx]));
// Ensure no undefined/null values leak into position arrays
return result.every(Boolean) ? result : null;
} catch { } catch {
return null; return null;
} }
@@ -240,7 +249,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const key2 = buildWaypointsKey(cur2.waypoints); const key2 = buildWaypointsKey(cur2.waypoints);
if (key2 !== key) return; if (key2 !== key) return;
// 每次尝试前先触发一次渲染,让瓦片/深度尽量就绪 // 每次尝试前先触发一次渲染,让瓦�?深度尽量就绪
try { try {
viewer.scene?.requestRender?.(); viewer.scene?.requestRender?.();
} catch { } catch {
@@ -252,10 +261,12 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const cartos = densifyWaypoints(Cesium2, cur2.waypoints); const cartos = densifyWaypoints(Cesium2, cur2.waypoints);
const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); const densified = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampedLine = await clampPositionsToModelSurface(Cesium2, densified); const densifiedGround = cartos.map((c: any) => Cesium2.Cartesian3.fromRadians(c.longitude, c.latitude, 0));
const clampedLine = await clampPositionsToModelSurface(Cesium2, densified, densifiedGround);
const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300)); const wpAbove = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 300));
const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove); const wpGround = cur2.waypoints.map((wp) => Cesium2.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0));
const clampedWp = await clampWaypointsToModelSurface(Cesium2, wpAbove, wpGround);
if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return; if ((surfaceComputeSeqRef.current.get(routeId) || 0) !== seq) return;
if (!clampedLine || clampedLine.length < 2) { if (!clampedLine || clampedLine.length < 2) {
@@ -271,7 +282,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined, waypointPositions: Array.isArray(clampedWp) ? clampedWp : undefined,
}); });
// 触发一次增量更新(避免等下一轮effect) // 触发一次增量更新(避免等下一轮effect�?
try { try {
const pathId = `library-route-${routeId}-path`; const pathId = `library-route-${routeId}-path`;
const startId = `library-route-${routeId}-start`; const startId = `library-route-${routeId}-start`;
@@ -279,14 +290,19 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const path = viewer.entities.getById?.(pathId); const path = viewer.entities.getById?.(pathId);
if (path?.polyline) { if (path?.polyline) {
path.polyline.positions = clampedLine; const validPolyline = clampedLine.filter(Boolean);
if (validPolyline.length >= 2) {
path.polyline.positions = validPolyline;
path.polyline.clampToGround = false; path.polyline.clampToGround = false;
if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE; if (Cesium2?.ArcType) path.polyline.arcType = Cesium2.ArcType.NONE;
} }
}
const startPos = clampedLine[0];
const endPos = clampedLine[clampedLine.length - 1];
const start = viewer.entities.getById?.(startId); const start = viewer.entities.getById?.(startId);
if (start) start.position = clampedLine[0]; if (start && startPos) start.position = startPos;
const end = viewer.entities.getById?.(endId); const end = viewer.entities.getById?.(endId);
if (end) end.position = clampedLine[clampedLine.length - 1]; if (end && endPos) end.position = endPos;
if (Array.isArray(clampedWp)) { if (Array.isArray(clampedWp)) {
const total = cur2.waypoints.length; const total = cur2.waypoints.length;
@@ -295,7 +311,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
for (let i = 0; i < total; i += step) { for (let i = 0; i < total; i += step) {
const wpId = `library-route-${routeId}-wp-${i}`; const wpId = `library-route-${routeId}-wp-${i}`;
const wpEntity = viewer.entities.getById?.(wpId); const wpEntity = viewer.entities.getById?.(wpId);
if (wpEntity) wpEntity.position = clampedWp[i]; if (wpEntity && clampedWp[i]) wpEntity.position = clampedWp[i];
} }
} }
viewer.scene?.requestRender?.(); viewer.scene?.requestRender?.();
@@ -341,13 +357,14 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
color: baseColor, color: baseColor,
}) })
: baseColor; : baseColor;
const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.55) : baseColor.withAlpha(0.55); const depthFailMaterial = item.highlighted ? baseColor.withAlpha(0.65) : baseColor.withAlpha(0.65);
const cached = surfaceCacheRef.current.get(routeId); const cached = surfaceCacheRef.current.get(routeId);
const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null; const cachedPositions = cached && cached.key === waypointsKey ? cached.polyline : null;
const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)); const fallbackPositions = item.waypoints.map((wp) => Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0));
const positionsToUse = Array.isArray(cachedPositions) && cachedPositions.length >= 2 ? cachedPositions : fallbackPositions; const validCached = Array.isArray(cachedPositions) ? cachedPositions.filter(Boolean) : [];
const useClampToGround = !(Array.isArray(cachedPositions) && cachedPositions.length >= 2); const positionsToUse = validCached.length >= 2 ? validCached : fallbackPositions;
const useClampToGround = validCached.length < 2;
if (existing?.polyline) { if (existing?.polyline) {
existing.polyline.positions = positionsToUse; existing.polyline.positions = positionsToUse;
@@ -378,7 +395,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
}); });
} }
} catch (e) { } catch (e) {
console.error('渲染已规划航线失败:', e); console.error('渲染已规划航线失�?', e);
} }
// start / end // start / end
@@ -392,7 +409,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const positionFromCache = cached && cached.key === waypointsKey const positionFromCache = cached && cached.key === waypointsKey
? (id === startId ? cached.start : cached.end) ? (id === startId ? cached.start : cached.end)
: null; : null;
const position = positionFromCache || Cesium.Cartesian3.fromDegrees(lon, lat, 0); const position = (positionFromCache && typeof positionFromCache === 'object') ? positionFromCache : Cesium.Cartesian3.fromDegrees(lon, lat, 0);
if (!position) return;
if (existing) { if (existing) {
existing.position = position; existing.position = position;
existing.show = true; existing.show = true;
@@ -454,7 +472,8 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const existing = viewer.entities.getById?.(wpId); const existing = viewer.entities.getById?.(wpId);
const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null; const posFromCache = Array.isArray(cachedWp) ? cachedWp[i] : null;
const pos = posFromCache || Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0); const pos = (posFromCache && typeof posFromCache === 'object') ? posFromCache : Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0);
if (!pos) continue;
if (existing) { if (existing) {
existing.position = pos; existing.position = pos;
@@ -513,7 +532,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
entityIdsByRouteRef.current.set(routeId, ids); entityIdsByRouteRef.current.set(routeId, ids);
// 贴模型:失败则自动重试(瓦片未就绪/不在视野时容易失败) // 贴模型:失败则自动重试(瓦片未就�?不在视野时容易失败)
scheduleSurfaceCompute(routeId); scheduleSurfaceCompute(routeId);
requestRender(); requestRender();
@@ -530,7 +549,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2); return routes.filter((r) => r.visible && r.waypoints && r.waypoints.length >= 2);
}, [routes]); }, [routes]);
// 同步渲染:增量更新 + 移除未显示的航线 // 同步渲染:增量更�?+ 移除未显示的航线
useEffect(() => { useEffect(() => {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return; if (!viewer || viewer.isDestroyed?.()) return;
@@ -571,7 +590,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
const Cesium = getCesium(); const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
const item = routes.find((r) => r.routeId === routeId); const item = routesRef.current.find((r) => r.routeId === routeId);
if (!item?.waypoints || item.waypoints.length === 0) return; if (!item?.waypoints || item.waypoints.length === 0) return;
const bounds = calculateBounds(item.waypoints); const bounds = calculateBounds(item.waypoints);
try { try {
@@ -598,9 +617,20 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend
} catch { } catch {
// 忽略 // 忽略
} }
}, [viewerRef, routes, getCesium, calculateBounds]); }, [viewerRef, getCesium, calculateBounds]);
const getRouteSurfaceGeometry = useCallback((routeId: string): RouteSurfaceGeometry | null => {
const cached = surfaceCacheRef.current.get(routeId);
if (!cached) return null;
return {
polyline: Array.isArray(cached.polyline) ? cached.polyline.filter(Boolean) : [],
waypointPositions: Array.isArray(cached.waypointPositions) ? cached.waypointPositions.filter(Boolean) : [],
};
}, []);
return { return {
flyToRoute, flyToRoute,
getRouteSurfaceGeometry,
}; };
} }
@@ -511,9 +511,8 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
const entityId = `route-waypoint-${index}`; const entityId = `route-waypoint-${index}`;
const cached = surfaceCacheRef.current; const cached = surfaceCacheRef.current;
const useCached = cached?.key === waypointsKey && Array.isArray(cached?.waypointPositions) && cached!.waypointPositions.length === waypoints.length; const useCached = cached?.key === waypointsKey && Array.isArray(cached?.waypointPositions) && cached!.waypointPositions.length === waypoints.length;
const position = useCached const cachedPos = useCached ? cached!.waypointPositions[index] : null;
? cached!.waypointPositions[index] const position = (cachedPos && typeof cachedPos === 'object') ? cachedPos : getFallbackPosition(wp);
: getFallbackPosition(wp);
if (!position) return; if (!position) return;
try { try {
@@ -654,9 +653,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
if (waypoints.length < 2) return; if (waypoints.length < 2) return;
const cached = surfaceCacheRef.current; const cached = surfaceCacheRef.current;
const useCached = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) && cached!.polylinePositions.length >= 2; const cachedLine = cached?.key === waypointsKey && Array.isArray(cached?.polylinePositions) ? cached!.polylinePositions.filter(Boolean) : [];
const positions = useCached const positions = cachedLine.length >= 2
? cached!.polylinePositions ? cachedLine
: waypoints.map((wp) => getFallbackPosition(wp)).filter(Boolean); : waypoints.map((wp) => getFallbackPosition(wp)).filter(Boolean);
if (positions.length < 2) return; if (positions.length < 2) return;
@@ -675,7 +674,7 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
existing.polyline.material = material; existing.polyline.material = material;
existing.polyline.clampToGround = false; existing.polyline.clampToGround = false;
existing.polyline.arcType = Cesium.ArcType?.NONE; existing.polyline.arcType = Cesium.ArcType?.NONE;
existing.polyline.depthFailMaterial = depthFailMaterial; // removed depthFailMaterial to avoid rendering over boat model
existing.show = true; existing.show = true;
} else { } else {
viewer.entities.add({ viewer.entities.add({
@@ -686,11 +685,9 @@ export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
material, material,
clampToGround: false, clampToGround: false,
arcType: Cesium.ArcType?.NONE, arcType: Cesium.ArcType?.NONE,
depthFailMaterial,
} }
}); });
} } entityIdsRef.current.add(entityId);
entityIdsRef.current.add(entityId);
} catch (e) { } catch (e) {
console.error('添加航线polyline失败:', e); console.error('添加航线polyline失败:', e);
} }
@@ -494,9 +494,12 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const [isPreviewing, setIsPreviewing] = useState(false); const [isPreviewing, setIsPreviewing] = useState(false);
const previewAnimationRef = useRef<number | null>(null); const previewAnimationRef = useRef<number | null>(null);
const savedCameraStateRef = useRef<any>(null); const savedCameraStateRef = useRef<any>(null);
const previewBoatPartsRef = useRef<{ hull?: any; cabin?: any; mast?: any; marker?: any } | null>(null); const previewBoatPartsRef = useRef<{ boat?: any } | null>(null);
const waypointPreviewListRef = useRef<HTMLDivElement | null>(null); const waypointPreviewListRef = useRef<HTMLDivElement | null>(null);
// GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差)
const MODEL_HEADING_OFFSET = -Math.PI / 2;
// 计算两点之间的航向角(度) // 计算两点之间的航向角(度)
const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => {
const dLon = (to.longitude - from.longitude) * Math.PI / 180; const dLon = (to.longitude - from.longitude) * Math.PI / 180;
@@ -529,11 +532,8 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
try { try {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) { if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} }
} catch { } catch {
// 忽略 // 忽略
@@ -611,23 +611,26 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const densifiedCartos = densify(); const densifiedCartos = densify();
if (densifiedCartos.length < 2) { if (densifiedCartos.length < 2) {
return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset); return points
.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0))
.map(applyOffset)
.filter(Boolean);
} }
const above = densifiedCartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); const above = densifiedCartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300));
const clampFn = viewer.scene?.clampToHeightMostDetailed; const clampFn = viewer.scene?.clampToHeightMostDetailed;
if (typeof clampFn !== 'function') { if (typeof clampFn !== 'function') {
return above.map(applyOffset); return above.map(applyOffset).filter(Boolean);
} }
try { try {
const clamped = await clampFn.call(viewer.scene, above); const clamped = await clampFn.call(viewer.scene, above);
const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]); const merged = (clamped || []).map((p: any, idx: number) => p || above[idx]);
const okCount = (clamped || []).filter(Boolean).length; const okCount = (clamped || []).filter(Boolean).length;
if (okCount < 2) return above.map(applyOffset); if (okCount < 2) return above.map(applyOffset).filter(Boolean);
return merged.map(applyOffset); return merged.map(applyOffset).filter(Boolean);
} catch { } catch {
return above.map(applyOffset); return above.map(applyOffset).filter(Boolean);
} }
}, [viewerRef]); }, [viewerRef]);
@@ -635,16 +638,17 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
const Cesium = (window as any).Cesium; const Cesium = (window as any).Cesium;
if (!viewer || !Cesium || viewer.isDestroyed?.()) return; if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!Array.isArray(polylinePositions) || polylinePositions.length < 2) return; polylinePositions = Array.isArray(polylinePositions) ? polylinePositions.filter(Boolean) : [];
if (polylinePositions.length < 2) {
message.warning('模型瓦片加载中,请稍后再试预览');
return;
}
// 预览开始前,清理上一次遗留的船只实体 // 预览开始前,清理上一次遗留的船只实体
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
try { try {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} catch { } catch {
// 忽略 // 忽略
} finally { } finally {
@@ -695,92 +699,34 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
} }
}; };
// 创建预览船只实体:临时“3D船体”(用几何体拼装),后续可替换为 glb/gltf // 创建预览船只实体:使用 GLB 船模型
try { try {
const firstPos0 = polylinePositions[0]; const firstPos0 = polylinePositions[0];
// 抬高过大会产生“视差”,看起来像是偏离航线;因此尽量贴近航线,靠标记图标保证可见 // 抬高过大会产生“视差”,看起来像是偏离航线;因此尽量贴近航线,靠标记图标保证可见
const boatAboveRoute = 0.05; const boatAboveRoute = 0.5;
const firstPos = offsetUpFromCartesian(firstPos0, boatAboveRoute); const firstPos = offsetUpFromCartesian(firstPos0, boatAboveRoute);
const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(0, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const hull = viewer.entities.add({ const boat = viewer.entities.add({
position: firstPos, position: firstPos,
orientation: initialOrientation, orientation: initialOrientation,
box: { model: {
dimensions: new Cesium.Cartesian3(1.35, 0.5, 0.2), uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`,
material: Cesium.Color.fromCssColorString('#0B3D91').withAlpha(0.92), scale: 0.001,
outline: true, minimumPixelSize: 64,
outlineColor: Cesium.Color.fromCssColorString('#E6F7FF').withAlpha(0.8), maximumScale: 200,
shadows: Cesium.ShadowMode.DISABLED, runAnimations: true,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0), colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
color: Cesium.Color.WHITE,
silhouetteSize: 0,
}, },
}); });
const cabinOffset = (basePos: any, headingRad: number) => { previewBoatPartsRef.current = { boat };
if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return basePos;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(basePos);
const forwardMeters = 0.25;
const rightMeters = 0.0;
const upMeters = 0.16;
const localOffset = new Cesium.Cartesian3(
Math.sin(headingRad) * forwardMeters + Math.cos(headingRad) * rightMeters,
Math.cos(headingRad) * forwardMeters - Math.sin(headingRad) * rightMeters,
upMeters
);
return Cesium.Matrix4.multiplyByPoint(enu, localOffset, new Cesium.Cartesian3());
};
const cabinPos = cabinOffset(firstPos, 0);
const cabin = viewer.entities.add({
position: cabinPos,
orientation: initialOrientation,
box: {
dimensions: new Cesium.Cartesian3(0.55, 0.38, 0.24),
material: Cesium.Color.fromCssColorString('#F5F5F5').withAlpha(0.95),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#FA8C16').withAlpha(0.85),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
const mastPos = cabinOffset(firstPos, 0);
const mast = viewer.entities.add({
position: mastPos,
orientation: initialOrientation,
cylinder: {
length: 0.38,
topRadius: 0.015,
bottomRadius: 0.015,
material: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.9),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#FFFFFF').withAlpha(0.6),
shadows: Cesium.ShadowMode.DISABLED,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 50000.0),
},
});
// 额外加一个“标记图标”,保证在复杂模型表面也能看清船的位置
const markerImageUrl = typeof Cesium.buildModuleUrl === 'function'
? Cesium.buildModuleUrl('Assets/Textures/maki/ferry.png')
: '/cesium/Assets/Textures/maki/ferry.png';
const marker = viewer.entities.add({
position: offsetUpFromCartesian(firstPos0, boatAboveRoute + 0.12),
billboard: {
image: markerImageUrl,
scale: 0.55,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(20.0, 1.0, 200.0, 0.6),
},
});
previewBoatPartsRef.current = { hull, cabin, mast, marker };
(previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute; (previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute;
(previewBoatPartsRef.current as any).cabinOffset = cabinOffset;
} catch (e) { } catch (e) {
console.warn('创建预览船只实体失败:', e); console.warn('创建预览船只实体失败:', e);
} }
@@ -959,30 +905,16 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
// 更新船只位置与朝向(尽量贴合航线) // 更新船只位置与朝向(尽量贴合航线)
try { try {
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5;
const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) { if (boat) {
hull.position = basePos; boat.position = basePos;
if (orientation) hull.orientation = orientation; if (orientation) boat.orientation = orientation;
}
const cabinOffset = (previewBoatPartsRef.current as any).cabinOffset as ((p: any, h: number) => any) | undefined;
const cabinPos = typeof cabinOffset === 'function' ? cabinOffset(basePos, headingRad) : basePos;
if (cabin) {
cabin.position = cabinPos;
if (orientation) cabin.orientation = orientation;
}
if (mast) {
mast.position = cabinPos;
if (orientation) mast.orientation = orientation;
}
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12);
} }
} }
} catch { } catch {
@@ -1001,26 +933,15 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
// 更新船只位置(兜底) // 更新船只位置(兜底)
try { try {
if (previewBoatPartsRef.current) { if (previewBoatPartsRef.current) {
const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.14; const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || 0.5;
const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute); const basePos = offsetUpFromCartesian(scratchPosCur, boatAboveRoute);
const orientation = Cesium.Transforms?.headingPitchRollQuaternion const orientation = Cesium.Transforms?.headingPitchRollQuaternion
? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad, 0, 0)) ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0))
: undefined; : undefined;
const { hull, cabin, mast } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) { if (boat) {
hull.position = basePos; boat.position = basePos;
if (orientation) hull.orientation = orientation; if (orientation) boat.orientation = orientation;
}
if (cabin) {
cabin.position = basePos;
if (orientation) cabin.orientation = orientation;
}
if (mast) {
mast.position = basePos;
if (orientation) mast.orientation = orientation;
}
if (previewBoatPartsRef.current.marker) {
previewBoatPartsRef.current.marker.position = offsetUpFromCartesian(scratchPosCur, boatAboveRoute + 0.12);
} }
} }
} catch { } catch {
@@ -1109,11 +1030,8 @@ const RouteEditor: React.FC<RouteEditorProps> = ({
try { try {
const viewer = viewerRef?.current; const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.()) { if (viewer && !viewer.isDestroyed?.()) {
const { hull, cabin, mast, marker } = previewBoatPartsRef.current; const { boat } = previewBoatPartsRef.current;
if (hull) viewer.entities.remove(hull); if (boat) viewer.entities.remove(boat);
if (cabin) viewer.entities.remove(cabin);
if (mast) viewer.entities.remove(mast);
if (marker) viewer.entities.remove(marker);
} }
} catch { } catch {
// 忽略 // 忽略
+32
View File
@@ -0,0 +1,32 @@
export interface Coordinate {
longitude: number;
latitude: number;
}
export const toFiniteNumber = (value: unknown): number | undefined => {
if (value === null || value === undefined || value === '') return undefined;
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : undefined;
};
export const isValidCoordinate = (longitude?: number, latitude?: number): boolean => {
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return false;
if (Math.abs(longitude!) > 180 || Math.abs(latitude!) > 90) return false;
// 设备未上报定位时常见默认值是 0,0,不能当作真实位置使用。
return !(longitude === 0 && latitude === 0);
};
export const getValidCoordinate = (
longitudeValue: unknown,
latitudeValue: unknown,
): Coordinate | null => {
const longitude = toFiniteNumber(longitudeValue);
const latitude = toFiniteNumber(latitudeValue);
if (!isValidCoordinate(longitude, latitude)) return null;
return {
longitude: longitude!,
latitude: latitude!,
};
};