feat: 3d模型

This commit is contained in:
2025-12-09 17:13:20 +08:00
parent 5f603bc69d
commit 358639a8ac
492 changed files with 74670 additions and 190 deletions
@@ -0,0 +1,227 @@
@import '~antd/lib/style/themes/default.less';
@cyan: #00f0ff;
@bg-dark: rgba(10, 20, 30, 0.95);
@border-color: rgba(0, 240, 255, 0.3);
.leftPanel {
position: absolute;
top: 64px;
left: 0;
bottom: 0;
width: 400px;
background: @bg-dark;
backdrop-filter: blur(20px);
border-right: 1px solid @border-color;
display: flex;
flex-direction: column;
transform: translateX(-100%);
transition: transform 0.4s cubic-bezier(0.2, 0.8, 0.2, 1);
z-index: 900;
box-shadow: 10px 0 30px rgba(0, 0, 0, 0.5);
&.visible {
transform: translateX(0);
}
&::after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 1px;
background: linear-gradient(180deg, transparent, @cyan, transparent);
box-shadow: 0 0 10px @cyan;
}
.header {
padding: 16px 20px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 240, 255, 0.05);
.title {
font-size: 16px;
font-weight: 700;
color: #fff;
display: flex;
align-items: center;
gap: 8px;
.liveTag {
font-size: 10px;
background: #ff4d4f;
padding: 1px 6px;
border-radius: 2px;
animation: blink 2s infinite;
}
}
.closeBtn {
background: none;
border: 1px solid rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.6);
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.3s;
&:hover { border-color: #ff4d4f; color: #ff4d4f; }
}
}
.videoContainer {
width: 100%;
aspect-ratio: 16/9;
background: #000;
position: relative;
border-bottom: 1px solid @border-color;
overflow: hidden;
.videoPlaceholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: rgba(0, 240, 255, 0.5);
background: radial-gradient(circle at center, rgba(0, 40, 60, 0.5) 0%, #000 100%);
background-image: linear-gradient(rgba(0, 240, 255, 0.1) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 240, 255, 0.1) 1px, transparent 1px);
background-size: 20px 20px;
.icon { font-size: 48px; margin-bottom: 12px; filter: drop-shadow(0 0 10px @cyan); }
}
.hudOverlay {
position: absolute;
top: 10px; left: 10px; right: 10px; bottom: 10px;
pointer-events: none;
border: 1px solid rgba(0, 240, 255, 0.3);
.crosshair {
position: absolute;
top: 50%; left: 50%; width: 20px; height: 20px;
border: 1px solid rgba(0, 255, 0, 0.5);
transform: translate(-50%, -50%);
&::before { content: ''; position: absolute; top: 9px; left: 0; width: 100%; height: 1px; background: rgba(0, 255, 0, 0.8); }
&::after { content: ''; position: absolute; left: 9px; top: 0; height: 100%; width: 1px; background: rgba(0, 255, 0, 0.8); }
}
}
}
// 飞行仪表盘
.flightDashboard {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
padding: 16px 20px;
background: rgba(0,0,0,0.2);
border-bottom: 1px solid rgba(255,255,255,0.05);
.dashItem {
background: rgba(255,255,255,0.05);
padding: 8px;
border-radius: 4px;
text-align: center;
.dashLabel { font-size: 10px; color: rgba(255,255,255,0.4); margin-bottom: 2px; }
.dashValue { font-size: 14px; font-weight: bold; color: #fff; font-family: 'Consolas', monospace; }
}
}
.controlsContent {
flex: 1;
overflow-y: auto;
padding: 20px;
.controlGroup {
margin-bottom: 24px;
.groupTitle {
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
margin-bottom: 12px;
display: flex;
align-items: center;
&::after { content: ''; flex: 1; height: 1px; background: rgba(255, 255, 255, 0.1); margin-left: 8px; }
}
.flightActions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
button {
height: 36px;
background: rgba(0, 240, 255, 0.1);
border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan;
cursor: pointer;
&:hover { background: rgba(0, 240, 255, 0.2); }
}
}
.joystickArea {
display: flex;
justify-content: space-between;
gap: 12px;
.joystickGroup {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
background: rgba(0,0,0,0.3);
padding: 12px 8px;
border-radius: 8px;
border: 1px solid rgba(255,255,255,0.05);
.joystickLabel {
font-size: 10px;
color: rgba(255,255,255,0.4);
margin-bottom: 8px;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 32px);
grid-template-rows: repeat(3, 32px);
gap: 4px;
button {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
color: #fff;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
&:hover { background: @cyan; color: #000; box-shadow: 0 0 10px @cyan; }
&:active { transform: scale(0.95); }
&.up { grid-column: 2; grid-row: 1; }
&.left { grid-column: 1; grid-row: 2; }
&.right { grid-column: 3; grid-row: 2; }
&.down { grid-column: 2; grid-row: 3; }
}
}
}
}
}
}
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
@@ -0,0 +1,196 @@
import React from 'react';
import {
CloseOutlined,
RocketOutlined,
VideoCameraOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
ArrowLeftOutlined,
ArrowRightOutlined,
StopOutlined,
HomeOutlined,
CameraOutlined,
RotateLeftOutlined,
RotateRightOutlined,
VerticalAlignTopOutlined,
VerticalAlignBottomOutlined,
DashboardOutlined,
CompassOutlined
} from '@ant-design/icons';
import { message } from 'antd';
import styles from './LeftControlPanel.less';
interface LeftControlPanelProps {
visible: boolean;
onClose: () => void;
device: any;
realtimeData: any;
}
const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
visible,
onClose,
device,
realtimeData
}) => {
const dockData = realtimeData?.rawData?.dockData;
// 模拟详细飞行数据 (Placeholder Data)
const flightData = {
pitch: -2.5,
roll: 0.1,
yaw: 125.4,
hSpeed: 0.0,
vSpeed: 0.0,
altitude: realtimeData?.gps?.altitude?.toFixed(1) || '0.0',
distance: 12.5, // 离家距离
homeAlt: 0,
satellites: dockData?.position_state?.gps_number || 12,
rtkStatus: 'FIX',
signal: 95,
rcSignal: 100
};
const handleControl = (action: string) => {
message.info(`发送指令: ${action}`);
};
return (
<div className={`${styles.leftPanel} ${visible ? styles.visible : ''}`}>
<div className={styles.header}>
<div className={styles.title}>
<VideoCameraOutlined />
<span>实时监控 / LIVE VIEW</span>
<span className={styles.liveTag}>LIVE</span>
</div>
<button className={styles.closeBtn} onClick={onClose}>
<CloseOutlined />
</button>
</div>
<div className={styles.videoContainer}>
<div className={styles.videoPlaceholder}>
<VideoCameraOutlined className={styles.icon} />
<span>等待图传信号...</span>
<span style={{fontSize: 12, marginTop: 8}}>{device?.deviceSn || '未选择设备'}</span>
</div>
<div className={styles.hudOverlay}>
<div className={styles.crosshair} />
<div style={{position: 'absolute', top: 10, left: 10, color: '#0f0', fontSize: 12, fontFamily: 'monospace'}}>
CAM: Main<br/>ISO: Auto<br/>EXP: 0.0
</div>
{/* HUD底部状态条 */}
<div style={{
position: 'absolute', bottom: 10, left: 10, right: 10,
display: 'flex', justifyContent: 'space-between',
color: '#fff', fontSize: 12, textShadow: '0 0 2px #000'
}}>
<span>H: {flightData.altitude}m</span>
<span>D: {flightData.distance}m</span>
<span>H.S: {flightData.hSpeed}m/s</span>
<span>V.S: {flightData.vSpeed}m/s</span>
</div>
</div>
</div>
{/* 飞行仪表盘区域 */}
<div className={styles.flightDashboard}>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
<div className={styles.dashValue}>{flightData.pitch}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
<div className={styles.dashValue}>{flightData.roll}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
<div className={styles.dashValue}>{flightData.yaw}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>RTK</div>
<div className={styles.dashValue} style={{color: '#00ff88'}}>{flightData.rtkStatus}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>SAT</div>
<div className={styles.dashValue}>{flightData.satellites}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>LINK</div>
<div className={styles.dashValue}>{flightData.signal}%</div>
</div>
</div>
<div className={styles.controlsContent}>
{/* 主要动作 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>快捷指令 / ACTIONS</div>
<div className={styles.flightActions}>
<button
onClick={() => handleControl('一键起飞')}
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
>
<RocketOutlined /> 一键起飞
</button>
<button onClick={() => handleControl('一键返航')}>
<HomeOutlined /> 一键返航
</button>
<button className={styles.danger} onClick={() => handleControl('紧急悬停')}>
<StopOutlined /> 紧急悬停
</button>
<button onClick={() => handleControl('拍照')}>
<CameraOutlined /> 拍照
</button>
</div>
</div>
{/* 飞行姿态控制 (模拟双摇杆) */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>姿态控制 / ATTITUDE CONTROL</div>
<div className={styles.joystickArea}>
{/* 左手:升降 + 转向 */}
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>升降 & 偏航 (Left)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('上升')} title="上升"><VerticalAlignTopOutlined /></button>
<button className={styles.left} onClick={() => handleControl('左转')} title="左转"><RotateLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('右转')} title="右转"><RotateRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('下降')} title="下降"><VerticalAlignBottomOutlined /></button>
</div>
</div>
{/* 右手:前后 + 左右 */}
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>水平移动 (Right)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('前进')} title="前进"><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('向左飞')} title="向左"><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('向右飞')} title="向右"><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('后退')} title="后退"><ArrowDownOutlined /></button>
</div>
</div>
</div>
</div>
{/* 云台控制 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>云台控制 / GIMBAL</div>
<div className={styles.joystickArea}>
<div className={styles.joystickGroup} style={{flex: 1}}>
<div className={styles.joystickLabel}>云台方向</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('云台向上')}><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('云台向左')}><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('云台向右')}><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('云台向下')}><ArrowDownOutlined /></button>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default LeftControlPanel;
@@ -0,0 +1,296 @@
@import '~antd/lib/style/themes/default.less';
@cyan: #00f0ff;
@neon-green: #00ff88;
@neon-orange: #ffaa00;
@neon-red: #ff4d4f;
@bg-dark: rgba(10, 20, 30, 0.95);
@border-color: rgba(0, 240, 255, 0.3);
.rightPanel {
position: absolute;
top: 64px;
right: 0;
bottom: 0;
width: 420px; // 稍微加宽一点
background: linear-gradient(
135deg,
rgba(6, 12, 20, 0.98) 0%,
rgba(10, 25, 40, 0.95) 100%
);
backdrop-filter: blur(10px);
z-index: 1000;
display: flex;
flex-direction: column;
transform: translateX(100%);
transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
border-left: 1px solid @border-color;
box-shadow: -10px 0 30px rgba(0, 0, 0, 0.5);
&.visible {
transform: translateX(0);
}
.header {
flex-shrink: 0;
padding: 20px 24px 16px;
border-bottom: 1px solid rgba(0, 240, 255, 0.1);
background: rgba(0, 20, 40, 0.3);
.titleRow {
display: flex;
justify-content: space-between;
align-items: flex-start;
.titleInfo {
flex: 1;
.mainTitle {
font-size: 20px;
font-weight: 700;
color: #fff;
text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 4px;
.icon { color: @cyan; }
}
.subTitle {
font-size: 12px;
color: rgba(0, 240, 255, 0.6);
font-family: 'Consolas', monospace;
}
}
.closeBtn {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.6);
cursor: pointer;
transition: all 0.3s;
&:hover {
background: rgba(255, 50, 50, 0.2);
border-color: rgba(255, 50, 50, 0.5);
color: @neon-red;
}
}
}
}
.deviceList {
flex-shrink: 0;
padding: 12px 24px;
background: rgba(0, 10, 20, 0.3);
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
.scrollContainer {
display: flex;
gap: 12px;
overflow-x: auto;
padding-bottom: 8px;
&::-webkit-scrollbar { height: 4px; }
&::-webkit-scrollbar-thumb { background: rgba(0, 240, 255, 0.2); border-radius: 2px; }
.deviceItem {
flex-shrink: 0;
width: 140px;
padding: 10px;
background: rgba(0, 240, 255, 0.05);
border: 1px solid rgba(0, 240, 255, 0.1);
cursor: pointer;
transition: all 0.3s;
position: relative;
&:hover { background: rgba(0, 240, 255, 0.1); }
&.active {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.15), rgba(0, 100, 255, 0.1));
border-color: @cyan;
box-shadow: 0 0 15px rgba(0, 240, 255, 0.1);
.name { color: @cyan; font-weight: 600; }
}
.iconWrapper {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
.icon { font-size: 16px; color: rgba(255, 255, 255, 0.6); }
.statusDot {
width: 8px; height: 8px; border-radius: 50%; background: #444;
&.online { background: @neon-green; box-shadow: 0 0 8px @neon-green; }
}
}
.name {
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
}
.content {
flex: 1;
overflow-y: auto;
.customTabs {
color: #fff;
:global {
.ant-tabs-nav {
margin-bottom: 0;
padding: 0 24px;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
.ant-tabs-tab {
color: rgba(255, 255, 255, 0.4);
padding: 16px 0;
margin-right: 24px;
transition: all 0.3s;
&:hover { color: @cyan; }
}
.ant-tabs-tab-active .ant-tabs-tab-btn {
color: @cyan;
font-weight: 600;
text-shadow: none !important;
}
.ant-tabs-ink-bar {
background: @cyan;
height: 3px;
box-shadow: 0 0 10px @cyan;
}
}
.ant-tabs-content-holder {
padding: 24px;
}
}
}
.detailContainer {
// 核心状态卡片
.statusCard {
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.1);
padding: 16px;
border-radius: 4px;
margin-bottom: 24px;
.statusHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
.statusTitle { color: rgba(255,255,255,0.6); font-size: 12px; letter-spacing: 1px; }
.statusTag {
font-size: 12px; font-weight: bold; padding: 2px 8px; border-radius: 2px;
&.success { background: rgba(0,255,136,0.2); color: @neon-green; }
&.error { background: rgba(255,77,79,0.2); color: @neon-red; }
}
}
.mainStatusGrid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
.mainStatusItem {
.label { font-size: 12px; color: rgba(255,255,255,0.4); margin-bottom: 4px; }
.value { font-size: 18px; color: #fff; font-weight: bold; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; }
:global(.ant-progress-inner) { background-color: rgba(255,255,255,0.1); }
}
}
}
.section {
margin-bottom: 24px;
.sectionHeader {
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
margin-bottom: 12px;
padding-left: 8px;
border-left: 2px solid @cyan;
text-transform: uppercase;
letter-spacing: 1px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.hudItem {
background: rgba(255, 255, 255, 0.03);
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.05);
display: flex;
flex-direction: column;
justify-content: center;
.label { font-size: 12px; color: rgba(255, 255, 255, 0.4); margin-bottom: 2px; }
.value {
font-size: 14px;
color: rgba(255, 255, 255, 0.9);
font-family: 'Consolas', monospace;
font-weight: 500;
.unit { font-size: 12px; color: rgba(255, 255, 255, 0.3); margin-left: 4px; }
&.warning { color: @neon-orange; }
&.error { color: @neon-red; }
&.success { color: @neon-green; }
}
}
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 32px;
button {
padding: 12px;
background: rgba(0, 240, 255, 0.1);
border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
&:hover:not(:disabled) {
background: rgba(0, 240, 255, 0.2);
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
transform: translateY(-2px);
}
&:disabled { opacity: 0.5; cursor: not-allowed; filter: grayscale(1); }
&.primary {
background: rgba(0, 240, 255, 0.2);
border-color: @cyan;
color: #fff;
text-shadow: none;
&:hover:not(:disabled) { background: rgba(0, 240, 255, 0.4); }
}
}
}
}
}
}
@@ -0,0 +1,255 @@
import React, { useState, useEffect } from 'react';
import { Spin, Empty, message, Tooltip, Tabs, Progress } from 'antd';
import {
CloseOutlined,
EnvironmentOutlined,
RocketOutlined,
VideoCameraOutlined,
HomeOutlined,
ThunderboltOutlined,
DashboardOutlined,
SignalFilled,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders';
import useDeviceSSE from '../hooks/useDeviceSSE';
import styles from './RightPanel.less';
const { TabPane } = Tabs;
interface RightPanelProps {
visible: boolean;
tourism: any;
onClose: () => void;
onControlClick: (device: any, realtimeData: any) => void;
}
const RightPanel: React.FC<RightPanelProps> = ({
visible,
tourism,
onClose,
onControlClick
}) => {
const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
const [loading, setLoading] = useState(false);
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
const fetchDeviceList = async (tourismId: number) => {
setLoading(true);
try {
const deviceSns = await ordersApi.getDeviceSnsByTourismId(tourismId);
if (!deviceSns || deviceSns.length === 0) {
setDeviceList([]);
return;
}
const promises = deviceSns.map((sn: string) =>
deviceApi.deviceList({ page: 1, limit: 1, deviceSn: sn })
);
const results = await Promise.all(promises);
const devices = results
.map((res: any) => (res.data && res.data.length > 0 ? res.data[0] : null))
.filter((device: any) => device !== null);
setDeviceList(devices);
if (devices.length > 0) setSelectedDeviceSn(devices[0].deviceSn || '');
} catch (error) {
console.error(error);
message.error('获取设备列表失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible && tourism?.id) fetchDeviceList(tourism.id);
else { setDeviceList([]); setSelectedDeviceSn(''); }
}, [visible, tourism?.id]);
useEffect(() => {
if (selectedDeviceSn && visible) connectSSE(selectedDeviceSn);
return () => { if (selectedDeviceSn) disconnectSSE(selectedDeviceSn); };
}, [selectedDeviceSn, visible]);
useEffect(() => {
if (!visible && selectedDeviceSn) disconnectSSE(selectedDeviceSn);
}, [visible]);
const handleDeviceSelect = (deviceSn: string) => {
if (deviceSn !== selectedDeviceSn) setSelectedDeviceSn(deviceSn);
};
const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn);
const dockData = realtimeData?.rawData?.dockData;
const battery = realtimeData?.battery ?? 0;
const formatValue = (val: any, unit: string = '') => (val !== undefined && val !== null ? `${val}${unit}` : '-');
const renderItem = (label: string, value: any, unit: string = '', status: 'normal'|'warning'|'error'|'success' = 'normal') => (
<div className={styles.hudItem}>
<div className={styles.label}>{label}</div>
<div className={`${styles.value} ${styles[status]}`}>
{value !== undefined && value !== null ? value : '-'}
<span className={styles.unit}>{unit}</span>
</div>
</div>
);
return (
<div className={`${styles.rightPanel} ${visible ? styles.visible : ''}`}>
<div className={styles.header}>
<div className={styles.titleRow}>
<div className={styles.titleInfo}>
<div className={styles.mainTitle}>
<EnvironmentOutlined className={styles.icon} />
{tourism?.tourismName || '景区详情'}
</div>
<div className={styles.subTitle}>{deviceList.length} DEVICES ONLINE</div>
</div>
<button className={styles.closeBtn} onClick={onClose}><CloseOutlined /></button>
</div>
</div>
{deviceList.length > 0 && (
<div className={styles.deviceList}>
<div className={styles.scrollContainer}>
{deviceList.map((device) => {
const isSelected = device.deviceSn === selectedDeviceSn;
const isDeviceOnline = realtimeData?.deviceSn === device.deviceSn && realtimeData?.online;
return (
<div
key={device.deviceSn}
className={`${styles.deviceItem} ${isSelected ? styles.active : ''}`}
onClick={() => handleDeviceSelect(device.deviceSn)}
>
<div className={styles.iconWrapper}>
<HomeOutlined className={styles.icon} />
<Tooltip title={isDeviceOnline ? '在线' : '离线'}>
<div className={`${styles.statusDot} ${isDeviceOnline ? styles.online : ''}`} />
</Tooltip>
</div>
<div className={styles.name}>{device.deviceName || device.deviceSn}</div>
</div>
);
})}
</div>
</div>
)}
<div className={styles.content}>
<Spin spinning={loading}>
{!selectedDevice ? (
<Empty description="暂无设备数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<Tabs defaultActiveKey="1" className={styles.customTabs}>
{/* Tab 1: 综合状态 (对齐2D: 机库信息 + 无人机信息) */}
<TabPane tab={<span><DashboardOutlined />综合状态</span>} key="1">
<div className={styles.detailContainer}>
{/* Block A: 机库信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>机库信息 / DOCK INFO</div>
{/* 状态卡片 */}
<div className={styles.statusCard}>
<div className={styles.statusHeader}>
<span className={styles.statusTitle}>{selectedDevice?.deviceName || selectedDevice?.deviceSn}</span>
<span className={`${styles.statusTag} ${realtimeData?.online ? styles.success : styles.error}`}>
{realtimeData?.online ? '在线' : '离线'}
</span>
</div>
<div className={styles.grid}>
{renderItem('机库SN', selectedDevice?.deviceSn)}
{renderItem('运行模式', dockData?.mode_code === 1 ? '工作' : '待机', '', dockData?.mode_code === 1 ? 'warning' : 'success')}
{renderItem('舱门', dockData?.cover_state === 1 ? '开启' : '关闭')}
{renderItem('告警', dockData?.alarm_state === 1 ? '告警' : '正常', '', dockData?.alarm_state === 1 ? 'error' : 'success')}
{renderItem('急停', dockData?.emergency_stop_state === 1 ? '触发' : '正常', '', dockData?.emergency_stop_state === 1 ? 'error' : 'success')}
{renderItem('推杆', dockData?.putter_state === 1 ? '展开' : '收起')}
</div>
</div>
</div>
{/* Block B: 无人机信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>无人机信息 / DRONE INFO</div>
<div className={styles.grid}>
{renderItem('无人机SN', dockData?.sub_device?.device_sn || '--')}
{renderItem('连接状态', dockData?.sub_device?.device_online_status === 1 ? '在线' : '离线', '', dockData?.sub_device?.device_online_status === 1 ? 'success' : 'normal')}
{renderItem('在库状态', dockData?.drone_in_dock === 1 ? '在库' : '外出', '', dockData?.drone_in_dock === 1 ? 'success' : 'warning')}
{renderItem('对频状态', dockData?.sub_device?.device_paired === 1 ? '已对频' : '未对频')}
{renderItem('RTK卫星', dockData?.position_state?.rtk_number, '颗')}
{renderItem('定位状态', dockData?.position_state?.is_fixed === 2 ? '固定解' : '非固定', '', dockData?.position_state?.is_fixed === 2 ? 'success' : 'warning')}
{renderItem('网络信号', dockData?.network_state?.type === 2 ? '4G' : 'WiFi')}
{renderItem('网络质量', dockData?.network_state?.quality, '/5')}
</div>
</div>
{/* 操作区 */}
<div className={styles.actions}>
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
<VideoCameraOutlined /> 进入操控台
</button>
<button disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1} onClick={() => message.info('一键起飞指令发送')}>
<RocketOutlined /> 一键起飞
</button>
</div>
</div>
</TabPane>
{/* Tab 2: 详细状态 (对齐2D: 机库环境电气 + 无人机详细状态) */}
<TabPane tab={<span><ThunderboltOutlined />详细状态</span>} key="2">
<div className={styles.detailContainer}>
{/* Block A: 机库环境与电气 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>机库环境与电气 / DOCK ENV & POWER</div>
<div className={styles.grid}>
{renderItem('环境温度', dockData?.environment_temperature, '°C')}
{renderItem('机库温度', dockData?.temperature, '°C')}
{renderItem('环境湿度', dockData?.humidity, '%')}
{renderItem('风速', dockData?.wind_speed, 'm/s')}
{renderItem('降雨量', dockData?.rainfall, 'mm')}
{renderItem('累计运行', formatValue(Math.floor((dockData?.acc_time ?? 0) / 3600), 'h'))}
{renderItem('供电电压', dockData?.electric_supply_voltage, 'V')}
{renderItem('输入功率', formatValue(dockData?.acdc_power_input, 'W'))}
{renderItem('工作电流', formatValue((dockData?.working_current ?? 0) / 1000, 'A'))}
{renderItem('备电电压', formatValue((dockData?.backup_battery?.voltage ?? 0) / 1000, 'V'))}
</div>
</div>
{/* Block B: 无人机详细状态 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>无人机详细状态 / DRONE DETAIL</div>
{/* 电池大图标 */}
<div style={{display:'flex', alignItems:'center', marginBottom: 16, background:'rgba(255,255,255,0.05)', padding:12, borderRadius:4}}>
<div style={{marginRight:16}}>
<div style={{fontSize:12, color:'rgba(255,255,255,0.6)'}}>BATTERY</div>
<div style={{fontSize:24, fontWeight:'bold', color:battery<20?'#ff4d4f':'#00ff88'}}>{battery}%</div>
</div>
<div style={{flex:1}}>
<Progress percent={battery} showInfo={false} strokeColor={battery<20?'#ff4d4f':'#00ff88'} trailColor="rgba(255,255,255,0.1)" />
</div>
</div>
<div className={styles.grid}>
{renderItem('电池电压', formatValue((dockData?.drone_battery_maintenance_info?.batteries?.[0]?.voltage ?? 0) / 1000, 'V'))}
{renderItem('电池温度', realtimeData?.temperature, '°C')}
{renderItem('充电状态', dockData?.drone_charge_state?.state === 1 ? '充电中' : '未充电')}
{renderItem('加热状态', dockData?.drone_battery_maintenance_info?.heat_state === 1 ? '加热中' : '未加热')}
{renderItem('维护状态', dockData?.drone_battery_maintenance_info?.maintenance_state === 1 ? '维护中' : '正常')}
{renderItem('存储模式', dockData?.battery_store_mode === 1 ? '计划模式' : '普通')}
</div>
</div>
</div>
</TabPane>
</Tabs>
)}
</Spin>
</div>
</div>
);
};
export default RightPanel;
@@ -0,0 +1,275 @@
// 3D科技风格底部面板
.bottomPanel {
position: absolute;
left: 20px;
right: 20px;
bottom: 20px;
background: linear-gradient(
135deg,
rgba(10, 20, 40, 0.92) 0%,
rgba(20, 40, 70, 0.88) 50%,
rgba(10, 30, 50, 0.92) 100%
);
backdrop-filter: blur(20px);
border: 1px solid rgba(0, 200, 255, 0.3);
border-radius: 16px;
box-shadow:
0 0 30px rgba(0, 150, 255, 0.2),
0 0 60px rgba(0, 100, 200, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.1);
z-index: 1000;
transform: translateY(calc(100% + 40px));
opacity: 0;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
max-height: 280px;
overflow: hidden;
// 顶部发光线条
&::before {
content: '';
position: absolute;
top: 0;
left: 20px;
right: 20px;
height: 2px;
background: linear-gradient(
90deg,
transparent 0%,
rgba(0, 200, 255, 0.8) 20%,
rgba(100, 220, 255, 1) 50%,
rgba(0, 200, 255, 0.8) 80%,
transparent 100%
);
border-radius: 2px;
box-shadow: 0 0 10px rgba(0, 200, 255, 0.8);
}
&.visible {
transform: translateY(0);
opacity: 1;
}
&.expanded {
max-height: 500px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px 12px;
border-bottom: 1px solid rgba(0, 200, 255, 0.15);
.headerLeft {
display: flex;
align-items: center;
gap: 12px;
.tourismIcon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.3), rgba(0, 200, 255, 0.1));
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 10px;
color: #00d4ff;
font-size: 18px;
box-shadow: 0 0 15px rgba(0, 200, 255, 0.3);
}
.tourismInfo {
.tourismName {
font-size: 16px;
font-weight: 600;
color: #fff;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
letter-spacing: 1px;
}
.deviceCount {
font-size: 12px;
color: rgba(0, 200, 255, 0.8);
margin-top: 2px;
}
}
}
.headerRight {
display: flex;
align-items: center;
gap: 8px;
.iconBtn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: 1px solid rgba(0, 200, 255, 0.3);
background: rgba(0, 150, 255, 0.1);
border-radius: 8px;
cursor: pointer;
color: #00d4ff;
transition: all 0.3s;
&:hover {
background: rgba(0, 200, 255, 0.2);
border-color: rgba(0, 200, 255, 0.6);
box-shadow: 0 0 15px rgba(0, 200, 255, 0.4);
transform: scale(1.05);
}
&.closeBtn:hover {
background: rgba(255, 80, 80, 0.2);
border-color: rgba(255, 80, 80, 0.6);
color: #ff6b6b;
box-shadow: 0 0 15px rgba(255, 80, 80, 0.4);
}
}
}
}
.deviceTabs {
display: flex;
gap: 10px;
padding: 12px 20px;
overflow-x: auto;
border-bottom: 1px solid rgba(0, 200, 255, 0.1);
&::-webkit-scrollbar {
height: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(0, 100, 150, 0.2);
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 200, 255, 0.4);
border-radius: 2px;
}
.deviceTab {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: rgba(0, 100, 150, 0.2);
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 25px;
cursor: pointer;
white-space: nowrap;
transition: all 0.3s;
&:hover {
background: rgba(0, 150, 200, 0.3);
border-color: rgba(0, 200, 255, 0.4);
}
&.selected {
background: linear-gradient(135deg, rgba(0, 150, 255, 0.4), rgba(0, 200, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow:
0 0 20px rgba(0, 200, 255, 0.3),
inset 0 0 10px rgba(0, 200, 255, 0.1);
}
.statusDot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #666;
transition: all 0.3s;
box-shadow: 0 0 5px rgba(100, 100, 100, 0.5);
&.online {
background: #00ff88;
box-shadow: 0 0 10px rgba(0, 255, 136, 0.8);
animation: pulse 2s infinite;
}
}
.deviceName {
font-size: 13px;
color: #e0f0ff;
font-weight: 500;
}
}
}
.content {
padding: 16px 20px;
overflow-y: auto;
max-height: calc(100% - 130px);
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(0, 100, 150, 0.2);
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 200, 255, 0.4);
border-radius: 2px;
}
:global(.ant-empty-description) {
color: rgba(255, 255, 255, 0.5);
}
:global(.ant-spin-dot-item) {
background-color: #00d4ff;
}
}
}
// 脉冲动画
@keyframes pulse {
0% {
box-shadow: 0 0 5px rgba(0, 255, 136, 0.8);
}
50% {
box-shadow: 0 0 15px rgba(0, 255, 136, 1), 0 0 25px rgba(0, 255, 136, 0.5);
}
100% {
box-shadow: 0 0 5px rgba(0, 255, 136, 0.8);
}
}
// 响应式
@media (max-width: 768px) {
.bottomPanel {
left: 10px;
right: 10px;
bottom: 10px;
border-radius: 12px;
.header {
padding: 12px 16px 10px;
.tourismIcon {
width: 36px;
height: 36px;
font-size: 16px;
}
.tourismName {
font-size: 14px;
}
}
.deviceTabs {
padding: 10px 16px;
}
.content {
padding: 12px 16px;
}
}
}
@@ -0,0 +1,231 @@
import React, { useState, useEffect } from 'react';
import { Spin, Empty, message, Modal } from 'antd';
import {
CloseOutlined,
ExpandAltOutlined,
CompressOutlined,
EnvironmentOutlined,
RocketOutlined,
VideoCameraOutlined,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders';
import useDeviceSSE from '../hooks/useDeviceSSE';
import DeviceInfo from '../DeviceInfo';
import styles from './index.less';
interface BottomPanelProps {
visible: boolean;
tourism: any;
onClose: () => void;
}
const BottomPanel: React.FC<BottomPanelProps> = ({ visible, tourism, onClose }) => {
const [expanded, setExpanded] = useState(false);
const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
const [loading, setLoading] = useState(false);
const [droneControlVisible, setDroneControlVisible] = useState(false);
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
// 获取设备列表
const fetchDeviceList = async (tourismId: number) => {
setLoading(true);
try {
// 获取设备SN列表
const deviceSns = await ordersApi.getDeviceSnsByTourismId(tourismId);
if (!deviceSns || deviceSns.length === 0) {
setDeviceList([]);
return;
}
// 批量查询设备详情
const promises = deviceSns.map((sn: string) =>
deviceApi.deviceList({ page: 1, limit: 1, deviceSn: sn })
);
const results = await Promise.all(promises);
const devices = results
.map((res: any) => (res.data && res.data.length > 0 ? res.data[0] : null))
.filter((device: any) => device !== null);
setDeviceList(devices);
// 默认选中第一个设备
if (devices.length > 0) {
setSelectedDeviceSn(devices[0].deviceSn || '');
}
} catch (error) {
console.error('获取设备列表失败:', error);
message.error('获取设备列表失败');
} finally {
setLoading(false);
}
};
// 景区变化时,重新获取设备列表
useEffect(() => {
if (visible && tourism?.id) {
fetchDeviceList(tourism.id);
} else {
setDeviceList([]);
setSelectedDeviceSn('');
setExpanded(false);
}
}, [visible, tourism?.id]);
// 选中设备变化时,连接SSE
useEffect(() => {
if (selectedDeviceSn && visible) {
connectSSE(selectedDeviceSn);
}
return () => {
if (selectedDeviceSn) {
disconnectSSE(selectedDeviceSn);
}
};
}, [selectedDeviceSn, visible]);
// 面板关闭时断开SSE
useEffect(() => {
if (!visible && selectedDeviceSn) {
disconnectSSE(selectedDeviceSn);
}
}, [visible]);
// 处理设备选择
const handleDeviceSelect = (deviceSn: string) => {
if (deviceSn !== selectedDeviceSn) {
setSelectedDeviceSn(deviceSn);
}
};
// 处理一键起飞
const handleTakeoff = () => {
const dockData = realtimeData?.rawData?.dockData;
if (dockData?.mode_code === 1) {
message.warning('机库正在执行任务,无法起飞');
return;
}
if (dockData?.drone_in_dock !== 1) {
message.warning('无人机不在库,无法起飞');
return;
}
message.info('一键起飞功能开发中');
};
// 获取选中设备
const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn);
return (
<>
<div className={`${styles.bottomPanel} ${visible ? styles.visible : ''} ${expanded ? styles.expanded : ''}`}>
{/* 头部 */}
<div className={styles.header}>
<div className={styles.headerLeft}>
<div className={styles.tourismIcon}>
<EnvironmentOutlined />
</div>
<div className={styles.tourismInfo}>
<div className={styles.tourismName}>{tourism?.tourismName || '景区'}</div>
<div className={styles.deviceCount}>{deviceList.length} 个设备在线</div>
</div>
</div>
<div className={styles.headerRight}>
<button
className={styles.iconBtn}
onClick={() => setExpanded(!expanded)}
title={expanded ? '收起' : '展开'}
>
{expanded ? <CompressOutlined /> : <ExpandAltOutlined />}
</button>
<button
className={`${styles.iconBtn} ${styles.closeBtn}`}
onClick={onClose}
title="关闭"
>
<CloseOutlined />
</button>
</div>
</div>
{/* 设备列表 */}
<div className={styles.deviceTabs}>
{deviceList.length === 0 && !loading && (
<div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 13 }}>暂无设备</div>
)}
{deviceList.map((device) => {
const isSelected = device.deviceSn === selectedDeviceSn;
const isOnline = realtimeData?.deviceSn === device.deviceSn && realtimeData?.online;
return (
<div
key={device.deviceSn}
className={`${styles.deviceTab} ${isSelected ? styles.selected : ''}`}
onClick={() => handleDeviceSelect(device.deviceSn)}
>
<span className={`${styles.statusDot} ${isOnline ? styles.online : ''}`} />
<span className={styles.deviceName}>{device.deviceName || device.deviceSn}</span>
</div>
);
})}
</div>
{/* 内容区 */}
<div className={styles.content}>
<Spin spinning={loading}>
{deviceList.length === 0 ? (
<Empty
description="该景区暂无设备"
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
) : selectedDevice ? (
<DeviceInfo
device={selectedDevice}
realtimeData={realtimeData}
sseConnected={sseConnected}
expanded={expanded}
onTakeoff={handleTakeoff}
onControl={() => setDroneControlVisible(true)}
/>
) : null}
</Spin>
</div>
</div>
{/* 无人机操控弹窗 */}
<Modal
title={
<span style={{ color: '#00d4ff' }}>
<RocketOutlined style={{ marginRight: 8 }} />
无人机操控台 - {realtimeData?.rawData?.dockData?.sub_device?.device_sn || '--'}
</span>
}
open={droneControlVisible}
onCancel={() => setDroneControlVisible(false)}
width={1000}
footer={null}
destroyOnClose
styles={{
content: {
background: 'linear-gradient(135deg, rgba(10, 20, 40, 0.98), rgba(20, 40, 70, 0.95))',
border: '1px solid rgba(0, 200, 255, 0.3)',
},
header: {
background: 'transparent',
borderBottom: '1px solid rgba(0, 200, 255, 0.2)',
},
}}
>
<div style={{ textAlign: 'center', padding: '60px 0' }}>
<VideoCameraOutlined style={{ fontSize: 64, color: 'rgba(0, 200, 255, 0.5)' }} />
<p style={{ marginTop: 16, color: 'rgba(255, 255, 255, 0.6)' }}>无人机操控功能开发中...</p>
</div>
</Modal>
</>
);
};
export default BottomPanel;
@@ -0,0 +1,331 @@
// 3D科技风格设备信息
.compactView {
.statusRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
.statusGroup {
display: flex;
align-items: center;
gap: 20px;
flex-wrap: wrap;
}
.statusItem {
display: flex;
align-items: center;
gap: 8px;
.statusIcon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 150, 255, 0.15);
border: 1px solid rgba(0, 200, 255, 0.3);
border-radius: 8px;
color: #00d4ff;
font-size: 14px;
}
.statusInfo {
.statusLabel {
font-size: 11px;
color: rgba(255, 255, 255, 0.5);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.statusValue {
font-size: 14px;
font-weight: 600;
color: #fff;
&.online {
color: #00ff88;
text-shadow: 0 0 8px rgba(0, 255, 136, 0.5);
}
&.offline {
color: #888;
}
&.warning {
color: #ffaa00;
text-shadow: 0 0 8px rgba(255, 170, 0, 0.5);
}
}
}
}
.batteryItem {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 16px;
background: linear-gradient(135deg, rgba(0, 100, 50, 0.3), rgba(0, 150, 100, 0.15));
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 20px;
.batteryIcon {
font-size: 18px;
}
.batteryText {
font-size: 16px;
font-weight: bold;
font-family: 'Courier New', monospace;
}
&.high {
border-color: rgba(0, 255, 136, 0.5);
.batteryIcon, .batteryText {
color: #00ff88;
text-shadow: 0 0 10px rgba(0, 255, 136, 0.6);
}
}
&.medium {
background: linear-gradient(135deg, rgba(100, 80, 0, 0.3), rgba(150, 120, 0, 0.15));
border-color: rgba(255, 200, 0, 0.5);
.batteryIcon, .batteryText {
color: #ffcc00;
text-shadow: 0 0 10px rgba(255, 200, 0, 0.6);
}
}
&.low {
background: linear-gradient(135deg, rgba(100, 30, 30, 0.3), rgba(150, 50, 50, 0.15));
border-color: rgba(255, 80, 80, 0.5);
.batteryIcon, .batteryText {
color: #ff5555;
text-shadow: 0 0 10px rgba(255, 80, 80, 0.6);
}
}
}
.actionButtons {
display: flex;
gap: 10px;
.actionBtn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 20px;
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 20px;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.2), rgba(0, 100, 200, 0.1));
color: #00d4ff;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 200, 255, 0.4), rgba(0, 150, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow: 0 0 20px rgba(0, 200, 255, 0.4);
transform: translateY(-2px);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
&.primary {
background: linear-gradient(135deg, rgba(0, 200, 100, 0.3), rgba(0, 150, 80, 0.2));
border-color: rgba(0, 255, 136, 0.5);
color: #00ff88;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 255, 136, 0.4), rgba(0, 200, 100, 0.3));
border-color: rgba(0, 255, 136, 0.8);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.4);
}
}
}
}
}
}
.expandedView {
.dataGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
margin-bottom: 16px;
@media (max-width: 900px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 600px) {
grid-template-columns: 1fr;
}
}
.dataCard {
background: linear-gradient(135deg, rgba(0, 100, 150, 0.2), rgba(0, 80, 120, 0.1));
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 12px;
padding: 14px;
transition: all 0.3s;
&:hover {
border-color: rgba(0, 200, 255, 0.4);
box-shadow: 0 0 15px rgba(0, 200, 255, 0.15);
}
.cardHeader {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid rgba(0, 200, 255, 0.15);
.cardIcon {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 200, 255, 0.15);
border-radius: 6px;
color: #00d4ff;
font-size: 14px;
}
.cardTitle {
font-size: 13px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
letter-spacing: 0.5px;
}
}
.cardContent {
.dataRow {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 0;
&:not(:last-child) {
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.dataLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.5);
}
.dataValue {
font-size: 13px;
color: #fff;
font-weight: 500;
font-family: 'Courier New', monospace;
&.success {
color: #00ff88;
}
&.warning {
color: #ffcc00;
}
&.error {
color: #ff5555;
}
}
}
}
}
.actionBar {
display: flex;
justify-content: space-between;
align-items: center;
padding-top: 16px;
border-top: 1px solid rgba(0, 200, 255, 0.15);
.actionButtons {
display: flex;
gap: 12px;
.actionBtn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 24px;
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 25px;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.2), rgba(0, 100, 200, 0.1));
color: #00d4ff;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 200, 255, 0.4), rgba(0, 150, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow: 0 0 25px rgba(0, 200, 255, 0.4);
transform: translateY(-2px);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
&.primary {
background: linear-gradient(135deg, rgba(0, 200, 100, 0.3), rgba(0, 150, 80, 0.2));
border-color: rgba(0, 255, 136, 0.5);
color: #00ff88;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 255, 136, 0.4), rgba(0, 200, 100, 0.3));
border-color: rgba(0, 255, 136, 0.8);
box-shadow: 0 0 25px rgba(0, 255, 136, 0.4);
}
}
&.danger {
background: linear-gradient(135deg, rgba(200, 50, 50, 0.3), rgba(150, 30, 30, 0.2));
border-color: rgba(255, 80, 80, 0.5);
color: #ff6b6b;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(255, 80, 80, 0.4), rgba(200, 50, 50, 0.3));
border-color: rgba(255, 80, 80, 0.8);
box-shadow: 0 0 25px rgba(255, 80, 80, 0.4);
}
}
}
}
.gpsInfo {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: rgba(0, 100, 150, 0.2);
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 20px;
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
font-family: 'Courier New', monospace;
.gpsIcon {
color: #00d4ff;
}
}
}
}
@@ -0,0 +1,288 @@
import React from 'react';
import {
ThunderboltOutlined,
RocketOutlined,
HomeOutlined,
AlertOutlined,
CloudOutlined,
EnvironmentOutlined,
WifiOutlined,
SettingOutlined,
} from '@ant-design/icons';
import type { RealtimeData } from '../hooks/useDeviceSSE';
import styles from './index.less';
interface DeviceInfoProps {
device: any;
realtimeData: RealtimeData | null;
sseConnected: boolean;
expanded: boolean;
onTakeoff?: () => void;
onControl?: () => void;
}
// 精简视图
export const CompactView: React.FC<DeviceInfoProps> = ({
device,
realtimeData,
sseConnected,
onTakeoff,
onControl,
}) => {
const isOnline = realtimeData?.online;
const battery = realtimeData?.battery ?? 0;
const droneOnline = realtimeData?.rawData?.dockData?.sub_device?.device_online_status === 1;
const droneInDock = realtimeData?.rawData?.dockData?.drone_in_dock === 1;
const modeCode = realtimeData?.rawData?.dockData?.mode_code;
const getBatteryClass = () => {
if (battery > 50) return styles.high;
if (battery > 20) return styles.medium;
return styles.low;
};
return (
<div className={styles.compactView}>
<div className={styles.statusRow}>
<div className={styles.statusGroup}>
{/* 机库状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<HomeOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>机库</div>
<div className={`${styles.statusValue} ${isOnline ? styles.online : styles.offline}`}>
{isOnline ? '在线' : '离线'}
</div>
</div>
</div>
{/* 无人机状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<RocketOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>无人机</div>
<div className={`${styles.statusValue} ${droneOnline ? styles.warning : styles.offline}`}>
{droneOnline ? '已开机' : '未开机'}
</div>
</div>
</div>
{/* 在库状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<SettingOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>状态</div>
<div className={`${styles.statusValue} ${droneInDock ? styles.online : styles.warning}`}>
{droneInDock ? '在库' : '外出'}
</div>
</div>
</div>
{/* 电池电量 */}
<div className={`${styles.batteryItem} ${getBatteryClass()}`}>
<ThunderboltOutlined className={styles.batteryIcon} />
<span className={styles.batteryText}>{battery}%</span>
</div>
</div>
{/* 操作按钮 */}
<div className={styles.actionButtons}>
<button
className={`${styles.actionBtn} ${styles.primary}`}
onClick={onTakeoff}
disabled={modeCode === 1 || !droneInDock}
>
<RocketOutlined />
一键起飞
</button>
<button className={styles.actionBtn} onClick={onControl}>
<WifiOutlined />
操控
</button>
</div>
</div>
</div>
);
};
// 完整视图
export const ExpandedView: React.FC<DeviceInfoProps> = ({
device,
realtimeData,
sseConnected,
onTakeoff,
onControl,
}) => {
const dockData = realtimeData?.rawData?.dockData;
const isOnline = realtimeData?.online;
const battery = realtimeData?.battery ?? 0;
const getModeText = (code?: number) => {
if (code === 0) return '待机';
if (code === 1) return '工作中';
return '未知';
};
const getCoverText = (state?: number) => {
if (state === 0) return '关闭';
if (state === 1) return '打开';
return '等待';
};
return (
<div className={styles.expandedView}>
<div className={styles.dataGrid}>
{/* 机库信息 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<HomeOutlined />
</div>
<span className={styles.cardTitle}>机库状态</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>名称</span>
<span className={styles.dataValue}>{device?.deviceName || '-'}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>状态</span>
<span className={`${styles.dataValue} ${dockData?.mode_code === 0 ? styles.success : styles.warning}`}>
{getModeText(dockData?.mode_code)}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>舱门</span>
<span className={`${styles.dataValue} ${dockData?.cover_state === 0 ? styles.success : styles.warning}`}>
{getCoverText(dockData?.cover_state)}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>告警</span>
<span className={`${styles.dataValue} ${dockData?.alarm_state === 0 ? styles.success : styles.error}`}>
{dockData?.alarm_state === 0 ? '正常' : '有告警'}
</span>
</div>
</div>
</div>
{/* 无人机信息 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<RocketOutlined />
</div>
<span className={styles.cardTitle}>无人机状态</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>SN</span>
<span className={styles.dataValue}>{dockData?.sub_device?.device_sn || '--'}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>开机</span>
<span className={`${styles.dataValue} ${dockData?.sub_device?.device_online_status === 1 ? styles.success : ''}`}>
{dockData?.sub_device?.device_online_status === 1 ? '已开机' : '未开机'}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>电量</span>
<span className={`${styles.dataValue} ${battery > 50 ? styles.success : battery > 20 ? styles.warning : styles.error}`}>
{battery}%
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>温度</span>
<span className={styles.dataValue}>{realtimeData?.temperature ?? 0}°C</span>
</div>
</div>
</div>
{/* 环境数据 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<CloudOutlined />
</div>
<span className={styles.cardTitle}>环境数据</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>温度</span>
<span className={styles.dataValue}>
{dockData?.environment_temperature ?? dockData?.temperature ?? 0}°C
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>湿度</span>
<span className={styles.dataValue}>{dockData?.humidity ?? 0}%</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>风速</span>
<span className={styles.dataValue}>{dockData?.wind_speed ?? 0} m/s</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>降雨</span>
<span className={styles.dataValue}>{dockData?.rainfall ?? 0} mm</span>
</div>
</div>
</div>
</div>
{/* 底部操作栏 */}
<div className={styles.actionBar}>
<div className={styles.actionButtons}>
<button
className={`${styles.actionBtn} ${styles.primary}`}
onClick={onTakeoff}
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
>
<RocketOutlined />
一键起飞
</button>
<button className={styles.actionBtn} onClick={onControl}>
<WifiOutlined />
操控无人机
</button>
<button className={styles.actionBtn} disabled>
<HomeOutlined />
一键返航
</button>
<button className={`${styles.actionBtn} ${styles.danger}`} disabled>
<AlertOutlined />
紧急悬停
</button>
</div>
{/* GPS信息 */}
<div className={styles.gpsInfo}>
<EnvironmentOutlined className={styles.gpsIcon} />
<span>
{(realtimeData?.gps?.latitude ?? 0).toFixed(6)}°,{' '}
{(realtimeData?.gps?.longitude ?? 0).toFixed(6)}°,{' '}
{(realtimeData?.gps?.altitude ?? 0).toFixed(1)}m
</span>
</div>
</div>
</div>
);
};
// 主组件
const DeviceInfo: React.FC<DeviceInfoProps> = (props) => {
const { expanded, ...rest } = props;
if (expanded) {
return <ExpandedView {...props} />;
}
return <CompactView {...props} />;
};
export default DeviceInfo;
@@ -0,0 +1,454 @@
# 大疆建图模型加载指南
## 一、模型处理流程
### 1. 大疆建图输出格式
大疆 Terra 建图软件输出的主要格式:
| 格式 | 说明 | Cesium支持 |
|------|------|-----------|
| **OSGB** | 倾斜摄影标准格式 | ❌ 需转换 |
| **3D Tiles** | Cesium原生格式 | ✅ 直接使用 |
| **OBJ** | 通用3D格式 | ⚠️ 需转换 |
| **PLY** | 点云格式 | ⚠️ 需转换 |
**推荐**: 直接在大疆Terra导出时选择 **3D Tiles** 格式
### 2. 模型转换(如果输出OSGB)
#### 方式一: Cesium Ion (推荐)
```bash
# 1. 注册 Cesium Ion 账号 https://cesium.com/ion/
# 2. 上传OSGB文件夹
# 3. 选择 "3D Capture" 或 "3D Model"
# 4. 等待处理完成,获取 Asset ID
```
#### 方式二: 开源工具转换
```bash
# 使用 cesiumlab 或 obj23dtiles
npm install -g 3d-tiles-tools
# OSGB转3D Tiles (需要osgb23dtiles工具)
osgb23dtiles -i ./osgb_folder -o ./3dtiles_output
```
#### 方式三: FME (企业级)
- 使用 Safe Software FME
- 支持批量转换和自动化流程
### 3. 模型存储方案
#### 方案A: 对象存储 + CDN (推荐)
```
OSS/MinIO/S3
├── scenic-models/
│ ├── {tourismId}/
│ │ ├── tileset.json # 入口文件
│ │ ├── data/
│ │ │ ├── L0/ # LOD层级
│ │ │ ├── L1/
│ │ │ └── ...
│ │ └── textures/ # 纹理文件
```
**优势**:
- 支持CDN加速
- 按需加载,节省带宽
- 支持断点续传
#### 方案B: Cesium Ion 托管
```typescript
// 使用 Asset ID 加载
const tileset = await Cesium.Cesium3DTileset.fromIonAssetId(YOUR_ASSET_ID, {
// 配置选项
});
```
#### 方案C: 本地服务器
```
nginx静态资源服务
├── /models/
│ ├── scenic_001/tileset.json
│ └── scenic_002/tileset.json
```
---
## 二、前端使用方式
### 1. 基础配置
```tsx
import CesiumContainer from './components/MapContainer/CesiumContainer';
// 定义模型配置
const tilesetConfigs = [
{
id: 'scenic_huangshan',
name: '黄山景区3D模型',
url: 'https://your-cdn.com/models/huangshan/tileset.json',
tourismId: 101,
position: {
longitude: 0, // 经度微调
latitude: 0, // 纬度微调
height: 0, // 高度偏移
},
style: {
maximumScreenSpaceError: 16, // LOD精度
maximumMemoryUsage: 512, // 最大内存MB
},
visible: true,
},
];
// 使用组件
<CesiumContainer
tourismList={tourismList}
tilesetConfigs={tilesetConfigs}
/>
```
### 2. 动态加载景区模型
```tsx
// 从后端API获取模型配置
const fetchTilesetConfigs = async (tourismId: number) => {
const response = await fetch(`/api/tourism/${tourismId}/3d-model`);
const data = await response.json();
return {
id: `tileset_${tourismId}`,
name: data.name,
url: data.tilesetUrl,
tourismId,
position: data.position,
style: data.style,
};
};
```
### 3. 性能优化配置
```typescript
// 低端设备配置
const lowEndConfig = {
maximumScreenSpaceError: 32, // 降低LOD精度
maximumMemoryUsage: 256, // 限制内存
skipLevelOfDetail: true,
preferLeaves: true,
progressiveResolutionHeightFraction: 0.5,
};
// 高端设备配置
const highEndConfig = {
maximumScreenSpaceError: 8, // 高精度LOD
maximumMemoryUsage: 1024, // 更多内存
skipLevelOfDetail: false,
preferLeaves: false,
};
```
---
## 三、后端API设计
### 1. 模型管理接口
```java
// 景区3D模型Controller
@RestController
@RequestMapping("/api/tourism")
public class Tourism3DModelController {
// 获取景区的3D模型配置
@GetMapping("/{tourismId}/3d-model")
public Result<TilesetConfigVO> getTilesetConfig(@PathVariable Long tourismId) {
return Result.succeed(tourismService.getTilesetConfig(tourismId));
}
// 上传模型(获取上传凭证)
@PostMapping("/{tourismId}/3d-model/upload-token")
public Result<UploadTokenVO> getUploadToken(@PathVariable Long tourismId) {
return Result.succeed(ossService.generateUploadToken(tourismId));
}
// 更新模型配置
@PutMapping("/{tourismId}/3d-model")
public Result<Void> updateTilesetConfig(
@PathVariable Long tourismId,
@RequestBody TilesetConfigDTO dto
) {
tourismService.updateTilesetConfig(tourismId, dto);
return Result.succeed();
}
}
```
### 2. 数据库设计
```sql
-- 景区3D模型表
CREATE TABLE tourism_3d_model (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
tourism_id BIGINT NOT NULL COMMENT '关联景区ID',
model_name VARCHAR(100) NOT NULL COMMENT '模型名称',
tileset_url VARCHAR(500) NOT NULL COMMENT 'tileset.json URL',
-- 位置调整
offset_longitude DECIMAL(10,7) DEFAULT 0 COMMENT '经度偏移',
offset_latitude DECIMAL(10,7) DEFAULT 0 COMMENT '纬度偏移',
offset_height DECIMAL(10,2) DEFAULT 0 COMMENT '高度偏移',
-- 变换参数
scale DECIMAL(5,3) DEFAULT 1.0 COMMENT '缩放比例',
rotation_x DECIMAL(6,4) DEFAULT 0 COMMENT 'X轴旋转(弧度)',
rotation_y DECIMAL(6,4) DEFAULT 0 COMMENT 'Y轴旋转',
rotation_z DECIMAL(6,4) DEFAULT 0 COMMENT 'Z轴旋转',
-- 渲染配置
max_screen_space_error INT DEFAULT 16 COMMENT 'LOD精度',
max_memory_usage INT DEFAULT 512 COMMENT '最大内存(MB)',
-- 元数据
file_size BIGINT COMMENT '文件大小(bytes)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
status TINYINT DEFAULT 1 COMMENT '1-正常 0-禁用',
INDEX idx_tourism_id (tourism_id),
UNIQUE KEY uk_tourism (tourism_id)
) COMMENT='景区3D模型配置';
```
### 3. VO/DTO定义
```java
@Data
public class TilesetConfigVO {
private String id;
private String name;
private String url;
private Long tourismId;
private PositionConfig position;
private TransformConfig transform;
private StyleConfig style;
private Boolean visible;
}
@Data
public class PositionConfig {
private Double longitude;
private Double latitude;
private Double height;
}
@Data
public class StyleConfig {
private Integer maximumScreenSpaceError = 16;
private Integer maximumMemoryUsage = 512;
private Boolean skipLevelOfDetail = true;
private Boolean preferLeaves = true;
}
```
---
## 四、完整业务流程
### 流程图
```
┌─────────────────────────────────────────────────────────────────────┐
│ 大疆建图模型上线流程 │
└─────────────────────────────────────────────────────────────────────┘
1. 模型采集
┌──────────────┐
│ 无人机航拍 │ ──→ 大疆Terra建图 ──→ 输出3D Tiles
└──────────────┘
2. 模型上传
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 获取上传凭证 │ ──→ │ 分片上传OSS │ ──→ │ CDN预热 │
└──────────────┘ └──────────────┘ └──────────────┘
3. 配置关联
┌──────────────┐ ┌──────────────┐
│ 保存模型配置 │ ──→ │ 关联景区ID │
└──────────────┘ └──────────────┘
4. 前端加载
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 查询模型配置 │ ──→ │ Cesium加载 │ ──→ │ 渐进式渲染 │
└──────────────┘ └──────────────┘ └──────────────┘
```
### 详细步骤
#### Step 1: 模型采集与处理
1. 使用大疆无人机对景区进行航拍
2. 将航拍数据导入大疆Terra
3. 选择"重建"任务,输出格式选择 **3D Tiles**
4. 等待处理完成,检查模型质量
#### Step 2: 模型上传
```typescript
// 前端上传流程
const uploadModel = async (tourismId: number, files: FileList) => {
// 1. 获取上传凭证
const { uploadUrl, ossPath } = await api.getUploadToken(tourismId);
// 2. 分片上传大文件
for (const file of files) {
await uploadToOSS(uploadUrl, ossPath, file);
}
// 3. 通知后端上传完成
await api.notifyUploadComplete(tourismId, ossPath);
};
```
#### Step 3: 模型配置
```typescript
// 管理后台配置模型参数
const saveModelConfig = async (tourismId: number, config: ModelConfig) => {
await api.updateTilesetConfig(tourismId, {
name: config.name,
tilesetUrl: `https://cdn.example.com/models/${tourismId}/tileset.json`,
position: {
longitude: config.offsetLng,
latitude: config.offsetLat,
height: config.offsetHeight,
},
style: {
maximumScreenSpaceError: config.lodQuality,
maximumMemoryUsage: config.memoryLimit,
},
});
};
```
#### Step 4: 前端展示
```typescript
// 地图仪表盘自动加载关联模型
useEffect(() => {
if (selectedTourism && selectedTourism.has3DModel) {
loadTourismModel(selectedTourism.id);
}
}, [selectedTourism]);
const loadTourismModel = async (tourismId: number) => {
const config = await api.getTilesetConfig(tourismId);
await handleLoadTileset(config);
handleFlyToTileset(config.id);
};
```
---
## 五、性能优化最佳实践
### 1. LOD (Level of Detail) 策略
```typescript
// 根据设备性能动态调整
const getOptimalConfig = () => {
const memory = navigator.deviceMemory || 4; // GB
const cores = navigator.hardwareConcurrency || 4;
if (memory >= 8 && cores >= 8) {
return { maximumScreenSpaceError: 8, maximumMemoryUsage: 1024 };
} else if (memory >= 4) {
return { maximumScreenSpaceError: 16, maximumMemoryUsage: 512 };
} else {
return { maximumScreenSpaceError: 32, maximumMemoryUsage: 256 };
}
};
```
### 2. 视锥裁剪
```typescript
// 启用视锥裁剪优化
const tilesetConfig = {
cullWithChildrenBounds: true, // 子节点包围盒裁剪
cullRequestsWhileMoving: true, // 移动时暂停请求
cullRequestsWhileMovingMultiplier: 60.0,
};
```
### 3. 预加载策略
```typescript
// 预加载飞行目的地
const tilesetConfig = {
preloadWhenHidden: true, // 隐藏时也预加载
preloadFlightDestinations: true, // 预加载飞行目标
};
```
### 4. 内存管理
```typescript
// 监控内存使用
viewer.scene.postRender.addEventListener(() => {
const statistics = tileset.statistics;
console.log('已加载Tiles:', statistics.numberOfTilesLoaded);
console.log('内存使用:', statistics.totalMemoryUsageInBytes / 1024 / 1024, 'MB');
});
// 当内存超限时降级
if (statistics.totalMemoryUsageInBytes > MAX_MEMORY) {
tileset.maximumScreenSpaceError *= 2; // 降低精度
}
```
### 5. 网络优化
```nginx
# Nginx配置 - 启用gzip和缓存
location /models/ {
gzip on;
gzip_types application/json application/octet-stream;
# 长期缓存静态资源
add_header Cache-Control "public, max-age=31536000, immutable";
# CORS支持
add_header Access-Control-Allow-Origin *;
}
```
---
## 六、常见问题
### Q1: 模型位置偏移怎么调整?
```typescript
// 使用position配置微调
const config = {
position: {
longitude: 0.0001, // 向东偏移约10米
latitude: -0.0001, // 向南偏移约10米
height: 5, // 抬高5米
}
};
```
### Q2: 模型加载太慢?
1. 检查CDN是否生效
2. 降低 `maximumScreenSpaceError` 值
3. 启用 `skipLevelOfDetail`
4. 检查模型文件大小,考虑简化
### Q3: 模型显示不完整?
1. 检查 `tileset.json` 路径是否正确
2. 确认所有子文件都已上传
3. 检查浏览器控制台的网络请求
### Q4: 内存占用过高?
1. 降低 `maximumMemoryUsage`
2. 增大 `maximumScreenSpaceError`
3. 启用 `cullRequestsWhileMoving`
@@ -0,0 +1,153 @@
.tilesetPanel {
position: absolute;
top: 10px;
right: 440px; // 放在 RightPanel (420px) 左边,不遮挡 Home 按钮
width: 320px;
max-height: calc(100vh - 100px);
z-index: 1100; // 高于 RightPanel 的 z-index (1000)
animation: slideInRight 0.3s ease-out;
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.panelCard {
background: rgba(10, 20, 40, 0.95);
border: 1px solid rgba(0, 240, 255, 0.3);
border-radius: 8px;
backdrop-filter: blur(10px);
:global {
.ant-card-head {
background: rgba(0, 240, 255, 0.1);
border-bottom: 1px solid rgba(0, 240, 255, 0.2);
color: #fff;
padding: 8px 12px;
min-height: auto;
.ant-card-head-title {
padding: 4px 0;
font-size: 14px;
}
.ant-card-extra {
padding: 0;
.ant-btn {
color: rgba(255, 255, 255, 0.6);
&:hover {
color: #fff;
}
}
}
}
.ant-card-body {
padding: 8px;
max-height: 400px;
overflow-y: auto;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 240, 255, 0.3);
border-radius: 2px;
}
}
.ant-list-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
padding: 8px 0;
}
.ant-empty-description {
color: rgba(255, 255, 255, 0.5);
}
}
}
.listItem {
display: block;
}
.itemContent {
width: 100%;
}
.itemHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.itemName {
color: #fff;
font-size: 13px;
font-weight: 500;
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress {
margin-bottom: 8px;
:global {
.ant-progress-text {
color: rgba(255, 255, 255, 0.8);
font-size: 11px;
}
}
}
.errorMsg {
color: #ff4d4f;
font-size: 11px;
margin-bottom: 8px;
padding: 4px 8px;
background: rgba(255, 77, 79, 0.1);
border-radius: 4px;
}
.itemActions {
display: flex;
justify-content: flex-end;
gap: 8px;
:global {
.ant-btn {
font-size: 12px;
}
.ant-switch {
background: rgba(255, 255, 255, 0.2);
&.ant-switch-checked {
background: #00f0ff;
}
}
}
}
}
// 暗色模式兼容
@media (prefers-color-scheme: dark) {
.tilesetPanel {
.panelCard {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
}
}
@@ -0,0 +1,202 @@
/**
* 3D Tiles 模型管理面板
* 用于显示和管理景区倾斜摄影模型
*/
import React from 'react';
import { Card, List, Progress, Button, Switch, Space, Tag, Tooltip, Empty } from 'antd';
import {
EyeOutlined,
EyeInvisibleOutlined,
AimOutlined,
DeleteOutlined,
ReloadOutlined,
CloudDownloadOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
LoadingOutlined,
} from '@ant-design/icons';
import type { TilesetConfig, TilesetState } from '../hooks/useTilesetLoader';
import styles from './index.less';
interface TilesetPanelProps {
visible: boolean;
tilesets: Map<string, TilesetState>;
configs: TilesetConfig[];
onLoad: (config: TilesetConfig) => void;
onUnload: (id: string) => void;
onFlyTo: (id: string) => void;
onToggleVisible: (id: string, visible: boolean) => void;
onClose: () => void;
}
const TilesetPanel: React.FC<TilesetPanelProps> = ({
visible,
tilesets,
configs,
onLoad,
onUnload,
onFlyTo,
onToggleVisible,
onClose,
}) => {
if (!visible) return null;
// 获取状态图标
const getStatusIcon = (state?: TilesetState) => {
if (!state) return <CloudDownloadOutlined style={{ color: '#999' }} />;
switch (state.status) {
case 'loading':
return <LoadingOutlined style={{ color: '#1890ff' }} spin />;
case 'loaded':
return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
case 'error':
return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
default:
return <CloudDownloadOutlined style={{ color: '#999' }} />;
}
};
// 获取状态标签
const getStatusTag = (state?: TilesetState) => {
if (!state) return <Tag>未加载</Tag>;
switch (state.status) {
case 'loading':
return <Tag color="processing">加载中 {state.progress}%</Tag>;
case 'loaded':
return <Tag color="success">已加载</Tag>;
case 'error':
return <Tag color="error">加载失败</Tag>;
default:
return <Tag>未加载</Tag>;
}
};
return (
<div className={styles.tilesetPanel}>
<Card
title={
<Space>
<span>3D模型管理</span>
<Tag color="cyan">{configs.length} 个模型</Tag>
</Space>
}
extra={
<Button type="text" size="small" onClick={onClose}>
关闭
</Button>
}
size="small"
className={styles.panelCard}
>
{configs.length === 0 ? (
<Empty description="暂无3D模型" image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<List
dataSource={configs}
renderItem={(config) => {
const state = tilesets.get(config.id);
const isLoaded = state?.status === 'loaded';
const isLoading = state?.status === 'loading';
return (
<List.Item className={styles.listItem}>
<div className={styles.itemContent}>
<div className={styles.itemHeader}>
<Space>
{getStatusIcon(state)}
<span className={styles.itemName}>{config.name}</span>
</Space>
{getStatusTag(state)}
</div>
{/* 加载进度 */}
{isLoading && (
<Progress
percent={state?.progress || 0}
size="small"
strokeColor="#00f0ff"
trailColor="rgba(255,255,255,0.1)"
className={styles.progress}
/>
)}
{/* 错误信息 */}
{state?.status === 'error' && (
<div className={styles.errorMsg}>
{state.error || '加载失败,请重试'}
</div>
)}
{/* 操作按钮 */}
<div className={styles.itemActions}>
{!isLoaded && !isLoading && (
<Tooltip title="加载模型">
<Button
type="primary"
size="small"
icon={<CloudDownloadOutlined />}
onClick={() => onLoad(config)}
>
加载
</Button>
</Tooltip>
)}
{isLoaded && (
<Space size="small">
<Tooltip title="飞往模型">
<Button
type="default"
size="small"
icon={<AimOutlined />}
onClick={() => onFlyTo(config.id)}
/>
</Tooltip>
<Tooltip title={config.visible !== false ? '隐藏' : '显示'}>
<Switch
size="small"
checked={config.visible !== false}
onChange={(checked) => onToggleVisible(config.id, checked)}
checkedChildren={<EyeOutlined />}
unCheckedChildren={<EyeInvisibleOutlined />}
/>
</Tooltip>
<Tooltip title="卸载模型">
<Button
type="text"
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => onUnload(config.id)}
/>
</Tooltip>
</Space>
)}
{state?.status === 'error' && (
<Tooltip title="重新加载">
<Button
type="default"
size="small"
icon={<ReloadOutlined />}
onClick={() => onLoad(config)}
>
重试
</Button>
</Tooltip>
)}
</div>
</div>
</List.Item>
);
}}
/>
)}
</Card>
</div>
);
};
export default TilesetPanel;
@@ -0,0 +1,240 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { message } from 'antd';
// GPS信息
interface GpsData {
latitude: number;
longitude: number;
altitude: number;
}
// 机库数据接口定义 (省略部分详细字段以节省空间,保持原有定义)
export interface DockData {
// ... (保持原有字段定义不变,此处省略展示)
[key: string]: any;
}
// 实时数据
export interface RealtimeData {
deviceSn: string;
online: boolean;
battery?: number;
temperature?: number;
humidity?: number;
gps?: GpsData;
flightMode?: string;
flightStatus?: string;
timestamp?: number;
rawData?: {
dockData?: any;
[key: string]: any;
};
}
interface UseDeviceSSEResult {
realtimeData: RealtimeData | null;
sseConnected: boolean;
connectSSE: (deviceSn: string) => Promise<void>;
disconnectSSE: (deviceSn?: string) => Promise<void>;
}
export function useDeviceSSE(): UseDeviceSSEResult {
const [realtimeData, setRealtimeData] = useState<RealtimeData | null>(null);
const [sseConnected, setSSEConnected] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const currentDeviceSnRef = useRef<string>('');
const clientSessionIdRef = useRef<string>(
`client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
);
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return;
// 尝试使用 fetch keepalive
fetch(`/api-device/sse/device-status/${deviceSn}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId,
},
keepalive: true,
}).catch(err => console.error('Disconnect fetch failed:', err));
// 备用方案:如果支持 Beacon 且后端允许 POST 处理断开 (通常 API 设计为 DELETE,Beacon 不适用,故仅作备注)
// navigator.sendBeacon(...) 仅支持 POST
};
// 断开SSE连接
const disconnectSSE = useCallback(async (deviceSn?: string) => {
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
// 1. 取消当前的 fetch 连接 (客户端主动断开)
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
// 2. 发送请求通知后端 (服务端清理资源)
if (snToDisconnect) {
const token = sessionStorage.getItem('access_token');
performDisconnect(snToDisconnect, clientSessionIdRef.current, token);
}
setSSEConnected(false);
currentDeviceSnRef.current = '';
console.log('SSE连接已断开');
}, []);
// 处理SSE事件
const handleSSEEvent = useCallback((eventName: string, data: string) => {
try {
if (eventName === 'connected') {
console.log('SSE连接确认:', data);
} else if (eventName === 'device-data-update') {
const parsedData = JSON.parse(data);
setRealtimeData(parsedData);
} else if (eventName === 'heartbeat') {
// 心跳
}
} catch (error) {
console.error('解析SSE数据失败:', error);
}
}, []);
// 连接SSE
const connectSSE = useCallback(async (deviceSn: string) => {
// 如果已经连接了同一个设备,先不断开,或者视需求而定。
// 这里采取策略:如果 ID 变了,先断开旧的。
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
await disconnectSSE(currentDeviceSnRef.current);
}
if (!deviceSn) return;
currentDeviceSnRef.current = deviceSn;
try {
const token = sessionStorage.getItem('access_token');
const url = `/api-device/sse/device-status/${deviceSn}`;
const abortController = new AbortController();
abortControllerRef.current = abortController;
console.log('正在建立SSE连接:', deviceSn);
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': clientSessionIdRef.current,
},
cache: 'no-store',
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`SSE连接失败: ${response.status}`);
}
setSSEConnected(true);
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('无法读取响应流');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('SSE连接已关闭');
setSSEConnected(false);
break;
}
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let currentEvent = '';
let currentData = '';
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine === '') {
if (currentEvent && currentData) {
handleSSEEvent(currentEvent, currentData);
}
currentEvent = '';
currentData = '';
} else if (line.startsWith('event:')) {
currentEvent = line.substring(6).trim();
} else if (line.startsWith('data:')) {
currentData = line.substring(5).trim();
}
}
}
} catch (error: any) {
if (error.name === 'AbortError') {
return;
}
console.error('SSE连接错误:', error);
setSSEConnected(false);
// message.error('连接实时数据失败'); // 避免频繁报错
// 简单重连逻辑
setTimeout(() => {
if (currentDeviceSnRef.current === deviceSn && !abortControllerRef.current) {
// 只有在没有活跃连接时才重连
// connectSSE(deviceSn); // 慎用自动重连,可能导致死循环
}
}, 5000);
}
}, [disconnectSSE, handleSSEEvent]);
// 监听浏览器刷新/关闭事件 (beforeunload)
useEffect(() => {
const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// 组件卸载清理 (React Unmount)
useEffect(() => {
return () => {
// 在组件卸载时,也尝试发送断开请求
if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
return {
realtimeData,
sseConnected,
connectSSE,
disconnectSSE,
};
}
export default useDeviceSSE;
@@ -0,0 +1,330 @@
/**
* 3D Tiles 倾斜摄影模型加载器 Hook
* 用于加载大疆建图等工具生成的3D Tiles模型
*/
import { useState, useCallback, useRef } from 'react';
// 模型配置接口
export interface TilesetConfig {
id: string; // 模型唯一标识
name: string; // 模型名称
url: string; // tileset.json 的URL地址
tourismId?: number; // 关联的景区ID
position?: { // 模型位置调整
longitude?: number; // 经度偏移
latitude?: number; // 纬度偏移
height?: number; // 高度偏移
};
transform?: { // 模型变换
scale?: number; // 缩放比例
rotationX?: number; // X轴旋转(弧度)
rotationY?: number; // Y轴旋转
rotationZ?: number; // Z轴旋转
};
style?: { // 渲染样式
maximumScreenSpaceError?: number; // LOD精度控制(默认16)
maximumMemoryUsage?: number; // 最大内存使用(MB)
skipLevelOfDetail?: boolean; // 是否跳过LOD
preferLeaves?: boolean; // 优先加载叶子节点
};
visible?: boolean; // 是否可见
}
// 模型加载状态
export interface TilesetState {
id: string;
status: 'pending' | 'loading' | 'loaded' | 'error';
progress: number; // 加载进度 0-100
error?: string;
tileset?: any; // Cesium3DTileset 实例
}
// Hook返回类型
export interface UseTilesetLoaderResult {
tilesets: Map<string, TilesetState>;
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any) => Promise<any>;
unloadTileset: (id: string, viewer: any) => void;
unloadAllTilesets: (viewer: any) => void;
flyToTileset: (id: string, viewer: any, Cesium: any) => void;
setTilesetVisible: (id: string, visible: boolean) => void;
updateTilesetStyle: (id: string, style: any, Cesium: any) => void;
}
export const useTilesetLoader = (): UseTilesetLoaderResult => {
const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map());
const tilesetsRef = useRef<Map<string, any>>(new Map());
/**
* 加载3D Tiles模型
*/
const loadTileset = useCallback(async (
config: TilesetConfig,
viewer: any,
Cesium: any
): Promise<any> => {
if (!viewer || !Cesium) {
console.error('Viewer或Cesium未初始化');
return null;
}
// 如果已经加载,直接返回
if (tilesetsRef.current.has(config.id)) {
console.log(`模型 ${config.id} 已加载,跳过`);
return tilesetsRef.current.get(config.id);
}
// 更新状态为loading
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'loading',
progress: 0,
});
return newMap;
});
try {
// 创建3DTileset - 高清晰度渲染配置
const tileset = await Cesium.Cesium3DTileset.fromUrl(config.url, {
// 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2)
maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1,
maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片
// 禁用LOD跳跃以获得更好的清晰度
skipLevelOfDetail: config.style?.skipLevelOfDetail ?? false,
preferLeaves: config.style?.preferLeaves ?? true,
// 动态调度 - 关闭以保持一致的高清晰度
dynamicScreenSpaceError: false,
// 预加载配置 - 积极预加载
preloadWhenHidden: true,
preloadFlightDestinations: true,
// 渐进式加载 - 减少模糊过渡
progressiveResolutionHeightFraction: 0.5,
// 焦点区域优化
foveatedScreenSpaceError: true,
foveatedConeSize: 0.1,
foveatedMinimumScreenSpaceErrorRelaxation: 0.0,
// 裁剪优化 - 减少移动时的清晰度降低
cullWithChildrenBounds: true,
cullRequestsWhileMoving: false, // 禁用移动时的请求裁剪
cullRequestsWhileMovingMultiplier: 1.0,
// 缓存策略 - 立即加载高精度
immediatelyLoadDesiredLevelOfDetail: true,
loadSiblings: true, // 加载相邻瓦片以减少边缘模糊
// 显示设置
show: config.visible !== false,
});
// 监听加载进度
tileset.loadProgress.addEventListener((numberOfPendingRequests: number, numberOfTilesProcessing: number) => {
const total = numberOfPendingRequests + numberOfTilesProcessing;
const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100;
setTilesets(prev => {
const newMap = new Map(prev);
const state = newMap.get(config.id);
if (state) {
newMap.set(config.id, { ...state, progress });
}
return newMap;
});
});
// 模型位置调整 - 只有当位置偏移不为0时才调整
if (config.position) {
const { longitude = 0, latitude = 0, height = 0 } = config.position;
// 只有当有非零偏移时才应用位置调整
if (longitude !== 0 || latitude !== 0 || height !== 0) {
const boundingSphere = tileset.boundingSphere;
const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
const newLon = cartographic.longitude + Cesium.Math.toRadians(longitude);
const newLat = cartographic.latitude + Cesium.Math.toRadians(latitude);
const newHeight = cartographic.height + height;
const newCenter = Cesium.Cartesian3.fromRadians(newLon, newLat, newHeight);
const translation = Cesium.Cartesian3.subtract(newCenter, boundingSphere.center, new Cesium.Cartesian3());
tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
}
}
// 模型变换(缩放/旋转) - 只有当有非默认值时才应用
if (config.transform) {
const { scale = 1, rotationX = 0, rotationY = 0, rotationZ = 0 } = config.transform;
// 只有当缩放不为1或有旋转时才应用变换
const needsTransform = scale !== 1 || rotationX !== 0 || rotationY !== 0 || rotationZ !== 0;
if (needsTransform) {
const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
// 创建变换矩阵
const transformMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
// 应用旋转
if (rotationX !== 0 || rotationY !== 0 || rotationZ !== 0) {
const rotationMatrix = Cesium.Matrix3.fromHeadingPitchRoll(
new Cesium.HeadingPitchRoll(rotationZ, rotationX, rotationY)
);
const rotation4 = Cesium.Matrix4.fromRotationTranslation(rotationMatrix);
Cesium.Matrix4.multiply(transformMatrix, rotation4, transformMatrix);
}
// 应用缩放
if (scale !== 1) {
const scaleMatrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(scale, scale, scale));
Cesium.Matrix4.multiply(transformMatrix, scaleMatrix, transformMatrix);
}
tileset.modelMatrix = Cesium.Matrix4.multiply(
tileset.modelMatrix || Cesium.Matrix4.IDENTITY,
transformMatrix,
new Cesium.Matrix4()
);
}
}
// 添加到场景
viewer.scene.primitives.add(tileset);
// 存储引用
tilesetsRef.current.set(config.id, tileset);
// 更新状态为loaded
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'loaded',
progress: 100,
tileset,
});
return newMap;
});
console.log(`3D Tiles模型 [${config.name}] 加载成功`);
return tileset;
} catch (error: any) {
console.error(`3D Tiles模型 [${config.name}] 加载失败:`, error);
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'error',
progress: 0,
error: error.message || '加载失败',
});
return newMap;
});
return null;
}
}, []);
/**
* 卸载指定模型
*/
const unloadTileset = useCallback((id: string, viewer: any) => {
const tileset = tilesetsRef.current.get(id);
if (tileset && viewer) {
viewer.scene.primitives.remove(tileset);
tilesetsRef.current.delete(id);
setTilesets(prev => {
const newMap = new Map(prev);
newMap.delete(id);
return newMap;
});
console.log(`模型 ${id} 已卸载`);
}
}, []);
/**
* 卸载所有模型
*/
const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer) return;
tilesetsRef.current.forEach((tileset, id) => {
viewer.scene.primitives.remove(tileset);
});
tilesetsRef.current.clear();
setTilesets(new Map());
console.log('所有3D Tiles模型已卸载');
}, []);
/**
* 飞行到指定模型
*/
const flyToTileset = useCallback((id: string, viewer: any, Cesium: any) => {
const tileset = tilesetsRef.current.get(id);
if (!tileset || !viewer || !Cesium) return;
const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
const radius = boundingSphere.radius;
// 计算合适的观察距离
const offset = new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0), // heading
Cesium.Math.toRadians(-45), // pitch (45度俯视)
radius * 2.5 // 距离
);
viewer.camera.flyToBoundingSphere(boundingSphere, {
offset,
duration: 2.0,
});
}, []);
/**
* 设置模型可见性
*/
const setTilesetVisible = useCallback((id: string, visible: boolean) => {
const tileset = tilesetsRef.current.get(id);
if (tileset) {
tileset.show = visible;
}
}, []);
/**
* 更新模型样式(着色/高亮等)
*/
const updateTilesetStyle = useCallback((id: string, style: any, Cesium: any) => {
const tileset = tilesetsRef.current.get(id);
if (!tileset || !Cesium) return;
// 示例: 设置建筑颜色
tileset.style = new Cesium.Cesium3DTileStyle({
color: style.color || "color('white')",
show: style.show !== false,
pointSize: style.pointSize || 5,
});
}, []);
return {
tilesets,
loadTileset,
unloadTileset,
unloadAllTilesets,
flyToTileset,
setTilesetVisible,
updateTilesetStyle,
};
};
export default useTilesetLoader;
@@ -18,6 +18,7 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
const mapRef = useRef<HTMLDivElement>(null);
const mapInstanceRef = useRef<any>(null);
const markersRef = useRef<Map<string, any>>(new Map());
const [mapReady, setMapReady] = React.useState(false); // 新增状态
// 初始化地图
useEffect(() => {
@@ -44,6 +45,9 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
resizeEnable: true,
});
// 标记地图已就绪
setMapReady(true);
console.log('地图初始化成功,开始加载控件插件...');
// 添加地图控件 - 使用 AMap.plugin 异步加载
window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
@@ -169,7 +173,7 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
marker.setMap(mapInstanceRef.current);
markersRef.current.set(`tourism_${tourism.id}`, marker);
});
}, [tourismList, onTourismClick]);
}, [tourismList, onTourismClick, mapReady]);
return <div ref={mapRef} style={{ width: '100%', height: '100%' }} />;
};
@@ -1,82 +1,304 @@
import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined } from '@ant-design/icons';
import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TilesetPanel from './3d/TilesetPanel';
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel';
// 动态导入Cesium
let Cesium: any = null;
interface CesiumContainerProps {
tourismList: any[];
onTourismClick: (tourism: any) => void;
externalSelectedTourism?: any; // 接收外部选择的景区
}
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const { tourismList, onTourismClick } = props;
const { tourismList, externalSelectedTourism } = props;
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const [loading, setLoading] = useState(true);
// 3D 模式专属状态
const [selectedTourism, setSelectedTourism] = useState<any>(null);
const [rightPanelVisible, setRightPanelVisible] = useState(false);
const [leftPanelVisible, setLeftPanelVisible] = useState(false);
// 传递给 LeftControlPanel 的数据
const [controlDevice, setControlDevice] = useState<any>(null);
const [controlRealtimeData, setControlRealtimeData] = useState<any>(null);
// 3D Tiles 模型管理
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的模型
const [modelLoading, setModelLoading] = useState(false);
const {
tilesets,
loadTileset,
unloadTileset,
unloadAllTilesets,
flyToTileset,
setTilesetVisible,
} = useTilesetLoader();
// 相机飞到景区
const flyToTourism = useCallback((tourism: any) => {
if (!viewerRef.current || !Cesium) return;
const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
if (isNaN(lon) || isNaN(lat)) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 5000km 高度
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
roll: 0,
},
duration: 1.5,
});
}, []);
// 相机飞回全球视角
const flyToGlobal = useCallback(() => {
if (!viewerRef.current || !Cesium) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
}, []);
// 加载景区绑定的模型,返回是否有模型
const loadTourismModels = useCallback(async (tourismId: number): Promise<boolean> => {
if (!viewerRef.current || !Cesium) {
console.log('Viewer或Cesium未准备好');
return false;
}
console.log('开始查询景区模型, tourismId:', tourismId);
setModelLoading(true);
// 先卸载之前的模型
unloadAllTilesets(viewerRef.current);
setCurrentTourismModels([]);
try {
const res = await getModelsByTourismId(tourismId);
console.log('查询景区模型结果:', res);
const modelList = res.datas || res.data; // 兼容两种返回格式
if (res.resp_code === 0 && modelList && modelList.length > 0) {
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
console.log('转换后的模型配置:', configs);
setCurrentTourismModels(configs);
let loadedCount = 0;
// 加载所有模型
for (const config of configs) {
console.log('准备加载模型:', config.name, 'URL:', config.url);
if (config.url) {
const tileset = await loadTileset(config, viewerRef.current, Cesium);
if (tileset) {
loadedCount++;
message.success(`模型 [${config.name}] 加载成功`);
// 加载成功后飞到第一个模型位置
if (loadedCount === 1) {
// 使用 viewer.flyTo 自动飞到模型
try {
await viewerRef.current.flyTo(tileset, {
duration: 2.0,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (e) {
console.warn('flyTo 失败,尝试 zoomTo:', e);
await viewerRef.current.zoomTo(tileset);
}
}
}
} else {
console.warn('模型URL为空,跳过加载:', config.name);
}
}
setModelLoading(false);
return loadedCount > 0;
} else {
console.log('该景区没有绑定模型或查询结果为空');
setModelLoading(false);
return false;
}
} catch (error) {
console.error('加载景区模型失败:', error);
setModelLoading(false);
return false;
}
}, [loadTileset, unloadAllTilesets]);
// 处理景区点击
const handleTourismSelect = useCallback((tourism: any) => {
setSelectedTourism(tourism);
setRightPanelVisible(true);
// 切换景区时,关闭左侧操控台
setLeftPanelVisible(false);
// 查询并加载该景区绑定的3D模型
// 如果有模型会自动飞到模型位置,没有模型才飞到景区位置
if (tourism.id) {
loadTourismModels(tourism.id).then((hasModel) => {
if (!hasModel) {
flyToTourism(tourism);
}
});
} else {
flyToTourism(tourism);
}
}, [flyToTourism, loadTourismModels]);
// 处理外部选择变化
useEffect(() => {
if (externalSelectedTourism && !loading) {
handleTourismSelect(externalSelectedTourism);
}
}, [externalSelectedTourism, loading, handleTourismSelect]);
// 处理从右侧面板点击“操控”
const handleOpenControl = useCallback((device: any, realtimeData: any) => {
setControlDevice(device);
setControlRealtimeData(realtimeData);
setLeftPanelVisible(true);
}, []);
// 关闭右侧面板
const handleRightPanelClose = useCallback(() => {
setRightPanelVisible(false);
setSelectedTourism(null);
setLeftPanelVisible(false); // 同时也关闭左侧
flyToGlobal();
}, [flyToGlobal]);
// ========== 3D Tiles 模型管理方法 ==========
// 加载模型
const handleLoadTileset = useCallback(async (config: TilesetConfig) => {
if (!viewerRef.current || !Cesium) {
message.warning('请等待地图加载完成');
return;
}
const tileset = await loadTileset(config, viewerRef.current, Cesium);
if (tileset) {
message.success(`模型 [${config.name}] 加载成功`);
}
}, [loadTileset]);
// 卸载模型
const handleUnloadTileset = useCallback((id: string) => {
unloadTileset(id, viewerRef.current);
message.info('模型已卸载');
}, [unloadTileset]);
// 飞往模型
const handleFlyToTileset = useCallback((id: string) => {
flyToTileset(id, viewerRef.current, Cesium);
}, [flyToTileset]);
// 切换模型可见性
const handleToggleTilesetVisible = useCallback((id: string, visible: boolean) => {
setTilesetVisible(id, visible);
// 更新当前景区模型配置状态
setCurrentTourismModels(prev =>
prev.map(c => c.id === id ? { ...c, visible } : c)
);
}, [setTilesetVisible]);
// 初始化Cesium
useEffect(() => {
const initCesium = async () => {
try {
// 动态导入Cesium
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
// 动态加载Cesium样式(使用CDN,稳定可靠)
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/cesium@1.110.0/Build/Cesium/Widgets/widgets.css';
link.href = `${cesiumBaseUrl}cesium/Widgets/widgets.css`;
document.head.appendChild(link);
}
}
if (!containerRef.current) return;
// 配置Cesium Ion Token(使用默认的,或配置自己的)
// Cesium.Ion.defaultAccessToken = process.env.REACT_APP_CESIUM_TOKEN || '';
// 创建Viewer
viewerRef.current = new Cesium.Viewer(containerRef.current, {
// 使用天地图或高德作为底图(国内访问)
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
minimumLevel: 3,
maximumLevel: 18,
}),
// 地形设置 - 使用默认地形(平坦)
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
// UI组件配置
animation: false, // 不显示动画控件
timeline: false, // 不显示时间轴
fullscreenButton: false, // 不显示全屏按钮
geocoder: false, // 不显示地理位置搜索
homeButton: true, // 显示主页按钮
sceneModePicker: true, // 显示2D/3D切换
baseLayerPicker: false, // 不显示底图选择器
navigationHelpButton: false,// 不显示帮助按钮
// 性能优化
requestRenderMode: true, // 请求渲染模式
scene3DOnly: false,
shouldAnimate: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: true,
sceneModePicker: true,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
});
// 设置初始视角(中国中心,可以看到全国范围)
viewerRef.current.imageryLayers.remove(viewerRef.current.imageryLayers.get(0));
viewerRef.current.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
});
viewerRef.current.imageryLayers.addImageryProvider(arcgisImagery);
viewerRef.current.scene.globe.enableLighting = false;
viewerRef.current.scene.globe.show = true;
viewerRef.current.scene.skyAtmosphere.show = true;
viewerRef.current.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 5000000), // 提高高度到5000km
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-60), // 俯视角度
roll: 0.0,
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
});
// 移除Cesium Logo和版权信息的点击事件
// 重写 Home 按钮行为
viewerRef.current.homeButton.viewModel.command.beforeExecute.addEventListener((e: any) => {
e.cancel = true; // 取消默认行为
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
});
const creditContainer = viewerRef.current.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
@@ -94,7 +316,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
initCesium();
return () => {
// 清理
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.destroy();
}
@@ -103,11 +324,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 更新景区标记
useEffect(() => {
if (!viewerRef.current || !Cesium || !tourismList.length) return;
if (loading || !viewerRef.current || !Cesium || !tourismList.length) return;
const viewer = viewerRef.current;
// 清除旧标记
entitiesRef.current.forEach((entity, key) => {
if (key.startsWith('tourism_')) {
viewer.entities.remove(entity);
@@ -115,36 +335,22 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
}
});
// 验证并过滤有效的景区坐标(只显示有经纬度的景区)
const validTourisms = tourismList.filter((tourism) => {
const lat = parseFloat(tourism.latitude);
const lng = parseFloat(tourism.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});
// 如果没有有效景区,不进行后续操作
if (validTourisms.length === 0) {
return;
}
// 添加景区标记
const positions: any[] = [];
if (validTourisms.length === 0) return;
validTourisms.forEach((tourism) => {
const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
// 根据 status 状态设置颜色:1=绿色(启用),0=红色(禁用)
const pointColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
positions.push(Cesium.Cartesian3.fromDegrees(lon, lat));
// 创建实体标记
const entity = viewer.entities.add({
id: `tourism_${tourism.id}`,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
// 点标记
point: {
pixelSize: 20,
color: Cesium.Color.fromCssColorString(pointColor),
@@ -152,8 +358,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
// 标签
label: {
text: tourism.tourismName || '景区',
font: '14px sans-serif',
@@ -166,8 +370,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
// 存储景区数据
properties: {
tourismData: tourism,
},
@@ -175,39 +377,34 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
entitiesRef.current.set(`tourism_${tourism.id}`, entity);
});
}, [tourismList]);
}, [tourismList, loading]);
// 点击事件
useEffect(() => {
if (!viewerRef.current || !Cesium) return;
if (loading || !viewerRef.current || !Cesium) return;
const viewer = viewerRef.current;
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// 左键点击
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const tourismData = entity.properties?.tourismData?.getValue();
if (tourismData) {
onTourismClick(tourismData);
handleTourismSelect(tourismData);
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 鼠标移动悬停效果
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.endPosition);
if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.point) {
// 鼠标悬停时放大点
pickedObject.id.point.pixelSize = 25;
document.body.style.cursor = 'pointer';
} else {
// 恢复所有点的大小
entitiesRef.current.forEach((entity) => {
if (entity.point) {
entity.point.pixelSize = 20;
@@ -221,11 +418,12 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
handler.destroy();
document.body.style.cursor = 'default';
};
}, [onTourismClick]);
}, [loading, handleTourismSelect]);
return (
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
{loading && (
<div
style={{
@@ -243,8 +441,75 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
加载3D地图中...
</div>
)}
{/* 模型加载中提示 */}
{modelLoading && (
<div
style={{
position: 'absolute',
top: 60,
left: '50%',
transform: 'translateX(-50%)',
color: '#fff',
fontSize: 14,
background: 'rgba(0,0,0,0.7)',
padding: '8px 16px',
borderRadius: 4,
zIndex: 800,
}}
>
正在加载3D模型...
</div>
)}
{/* 3D模型管理按钮 - 当景区有绑定模型时显示 */}
{!loading && currentTourismModels.length > 0 && (
<Tooltip title="3D模型管理">
<Button
type="primary"
icon={<AppstoreOutlined />}
onClick={() => setTilesetPanelVisible(!tilesetPanelVisible)}
style={{
position: 'absolute',
top: 10,
right: 180,
zIndex: 700,
background: tilesetPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 3D Tiles模型管理面板 */}
<TilesetPanel
visible={tilesetPanelVisible}
tilesets={tilesets}
configs={currentTourismModels}
onLoad={handleLoadTileset}
onUnload={handleUnloadTileset}
onFlyTo={handleFlyToTileset}
onToggleVisible={handleToggleTilesetVisible}
onClose={() => setTilesetPanelVisible(false)}
/>
{/* 左侧操控台 */}
<LeftControlPanel
visible={leftPanelVisible}
onClose={() => setLeftPanelVisible(false)}
device={controlDevice}
realtimeData={controlRealtimeData}
/>
{/* 右侧数据面板 */}
<RightPanel
visible={rightPanelVisible}
tourism={selectedTourism}
onClose={handleRightPanelClose}
onControlClick={handleOpenControl}
/>
</div>
);
};
export default CesiumContainer;
export default CesiumContainer;
@@ -7,20 +7,28 @@ interface MapContainerProps {
mode: '2d' | '3d';
tourismList: any[];
onTourismClick: (tourism: any) => void;
selectedTourism?: any;
}
const MapContainer: React.FC<MapContainerProps> = (props) => {
const { mode, ...otherProps } = props;
const { mode, tourismList, onTourismClick, selectedTourism } = props;
return (
<div className={styles.mapContainer}>
{/* 2D地图 - 高德 */}
{mode === '2d' && <AmapContainer {...otherProps} />}
{mode === '2d' && (
<AmapContainer tourismList={tourismList} onTourismClick={onTourismClick} />
)}
{/* 3D地图 - Cesium */}
{mode === '3d' && <CesiumContainer {...otherProps} />}
{/* 3D地图 - Cesium(内部处理点击,显示底部面板) */}
{mode === '3d' && (
<CesiumContainer
tourismList={tourismList}
externalSelectedTourism={selectedTourism}
/>
)}
</div>
);
};
export default MapContainer;
export default MapContainer;