Files
fpv-rid-workbench/crates/web-ui/public/map-adapter.js
T
JiuContinent 4eaa88baeb ```
feat(protocol): Observation坐标字段可选化及协议v2扩展

- 将Observation中longitude/latitude/altitude_m/heading_deg改为Option类型,
  支持无位置信息的观测数据
- 新增DeviceTelemetry结构体承载设备遥测扩展字段(serial, mac, model, rssi,
  speed, vertical_speed, pressure_altitude, geometric_altitude, height_agl,
  pilot_position等)
- 新增LegacyObservation兼容结构体及From转换,保持旧接收器协议输入兼容
- PROTOCOL_VERSION从1升至2
- 新增coordinates()辅助方法统一提取有效坐标
- validate()适配Option类型,允许坐标字段同时缺失
- Store新增position_generation机制追踪位置可用性变化,确保合并帧间的
  位置丢失仍能正确断开轨迹
- geofence-map-adapter过滤无效坐标避免渲染异常
- 新增appearance.css外观主题系统,支持blue/graphite/white三套配色
```
2026-10-26 15:14:43 +08:00

149 lines
15 KiB
JavaScript

// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust.
import {attachTileBuffer} from './map-tile-buffer.js';
import * as maplibre from './vendor/maplibre-gl.mjs';
maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
let tileBuffer;
let map, layer, latest, ids = [], selected = '', pending = false;
let frameTimes = [], lastFrame = 0;
let marker=null, history=[], lastTrail=0, generations=null, selectedGeneration=null;
let centered=false, workerWasmBytes=0, resizeObserver;
let basemap="imagery",tileRevision=0,mapCreations=0;
const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]};
function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?v=${tileRevision}`:''}`;}
let classification=new Map(),listFilter="all";
function targetKind(id){return classification.get(id)||"unknown";}
function located(id,i=ids.indexOf(id)){return i>=0&&latest&&Number.isFinite(latest[i*4])&&Number.isFinite(latest[i*4+1]);}
function targetVisible(id,i=ids.indexOf(id)){return located(id,i)&&(listFilter==="all"||targetKind(id)===listFilter);}
function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";flush();}
let occlusion={top:0,right:0,bottom:0,left:0};
function shader(gl, type, source) {
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
}
function create(container,initialBasemap="imagery",preferences=null) {
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
tileBuffer?.destroy();
if (map) map.remove();
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
// A configured startup camera takes precedence over the legacy first-target fallback.
centered=!!(preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude));
const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):15;
map=new maplibre.Map({container,center:initialCenter,zoom:initialZoom,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,attributionControl:false,
style:{version:8,sources:{
'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'},
'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18}
},layers:[
{id:'background',type:'background',paint:{'background-color':'#060c18'}},
{id:'tdt-base',type:'raster',source:'tdt-base'},
{id:'tdt-labels',type:'raster',source:'tdt-labels'}
]}});
tileBuffer=attachTileBuffer(map,()=>basemap,()=>tileRevision);
resizeObserver?.disconnect(); resizeObserver=new ResizeObserver(()=>map?.resize());resizeObserver.observe(document.getElementById(container));
map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right');
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
onAdd(map,gl){
if (!gl.drawArraysInstanced) throw new Error('WebGL2 required');
this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat(initialCenter);
this.program=gl.createProgram();
this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
void main(){vec4 p=matrix*vec4(target.xy,0.,1.);float c=cos(target.z+bearing),s=sin(target.z+bearing);vec2 q=vec2(shape.x*c-shape.y*s,shape.x*s+shape.y*c);p.xy+=q*pixel*p.w;gl_Position=p;chosen=target.w;}`);
this.fs=shader(gl,gl.FRAGMENT_SHADER,`#version 300 es
precision highp float; in float chosen; out vec4 color; void main(){float kind=floor(chosen/2.);float picked=mod(chosen,2.);vec4 base=kind>1.5?vec4(.98,.42,.39,1.):kind>.5?vec4(.38,.82,.63,1.):vec4(.22,.74,.97,1.);color=kind<.5?mix(base,vec4(1.,.75,.15,1.),picked):mix(base,vec4(1.),picked*.25);}`);
gl.attachShader(this.program,this.vs);gl.attachShader(this.program,this.fs);gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program,gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(this.program));
this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao);
this.shape=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.shape);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([0,10,-6,-6,0,-2,0,10,0,-2,6,-6]),gl.STATIC_DRAW);
const a=gl.getAttribLocation(this.program,'shape');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);
this.instances=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.instances);gl.bufferData(gl.ARRAY_BUFFER,10000*16,gl.DYNAMIC_DRAW);
const b=gl.getAttribLocation(this.program,'target');gl.enableVertexAttribArray(b);gl.vertexAttribPointer(b,4,gl.FLOAT,false,16,0);gl.vertexAttribDivisor(b,1);
gl.bindVertexArray(null);this.count=0;this.matrix=gl.getUniformLocation(this.program,'matrix');this.pixel=gl.getUniformLocation(this.program,'pixel');this.bearing=gl.getUniformLocation(this.program,'bearing');
},
render(gl,args){
if (!this.count || !this.map.getCanvas().clientWidth || !this.map.getCanvas().clientHeight) return;
const source=args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix;
if (!source) return;
const m=new Float32Array(source);for(let r=0;r<4;r++)m[12+r]=source[r]*this.origin.x+source[4+r]*this.origin.y+source[12+r];
gl.useProgram(this.program);gl.bindVertexArray(this.vao);gl.uniformMatrix4fv(this.matrix,false,m);gl.uniform2f(this.pixel,2/this.map.getCanvas().clientWidth,2/this.map.getCanvas().clientHeight);gl.uniform1f(this.bearing,this.map.getBearing()*Math.PI/180);
gl.disable(gl.DEPTH_TEST);gl.drawArraysInstanced(gl.TRIANGLES,0,6,this.count);gl.bindVertexArray(null);
const now=performance.now();if(lastFrame)frameTimes.push(now-lastFrame);lastFrame=now;if(frameTimes.length>300)frameTimes.shift();
},
onRemove(map,gl){gl.deleteBuffer(this.shape);gl.deleteBuffer(this.instances);gl.deleteVertexArray(this.vao);gl.deleteProgram(this.program);gl.deleteShader(this.vs);gl.deleteShader(this.fs);}
};
map.on('style.load',()=>{
// Mission Control tactical radar grid & range rings
const features=[];
for(let lon=initialCenter[0]-2;lon<=initialCenter[0]+2;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,initialCenter[1]-2],[lon,initialCenter[1]+2]]},properties:{}});
for(let lat=initialCenter[1]-2;lat<=initialCenter[1]+2;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[initialCenter[0]-2,lat],[initialCenter[0]+2,lat]]},properties:{}});
// Concentric tactical range rings around default center
const center=initialCenter;
for(const radiusKm of [1, 2, 5, 10]) {
const ring=[];
for(let a=0;a<=360;a+=6){
const rad=a*Math.PI/180;
const dLat=(radiusKm/111)*Math.cos(rad);
const dLon=(radiusKm/(111*Math.cos(center[1]*Math.PI/180)))*Math.sin(rad);
ring.push([center[0]+dLon, center[1]+dLat]);
}
features.push({type:'Feature',geometry:{type:'LineString',coordinates:ring},properties:{}});
}
map.addSource('grid',{type:'geojson',data:{type:'FeatureCollection',features}});
map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}});
map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}});
map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}});
map.addLayer(layer);flush();
});
map.on('click',event=>{
if(!latest)return;let index=-1,distance=18;
for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i],i))continue;const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
if(index>=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]}));
});
map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);});
return true;
}
function flush(){
pending=false;if(!latest||!layer?.gl)return;const gl=layer.gl;
const data=new Float32Array(ids.length*4);let visible=0;for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i],i))continue;const j=visible++;const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[j*4]=p.x-layer.origin.x;data[j*4+1]=p.y-layer.origin.y;data[j*4+2]=-(Number.isFinite(latest[i*4+3])?latest[i*4+3]:0)*Math.PI/180;const kind=targetKind(ids[i]);data[j*4+3]=(kind==="black"?4:kind==="white"?2:0)+(ids[i]===selected?1:0);}
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=visible;map.triggerRepaint();
const index=ids.indexOf(selected);
if(index>=0&&targetVisible(selected)){
const coordinate=[latest[index*4],latest[index*4+1]];
if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);}
marker.getElement().textContent=selected+(targetKind(selected)==="black"?" · 黑名单":targetKind(selected)==="white"?" · 白名单":"");marker.getElement().dataset.listKind=targetKind(selected);marker.setLngLat(coordinate);
const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200);
map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});}
}else{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});}
}
function update(positions,newIds,newGenerations){latest=positions;generations=newGenerations;if(newIds)ids=Array.from(newIds);const selectedIndex=ids.indexOf(selected);const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}}
function select(id){if(selected!==id){selected=id;history=[];selectedGeneration=generations?.[ids.indexOf(id)]??null;flush();}const i=ids.indexOf(id);return located(id)?Array.from(latest.slice(i*4,i*4+4)):[];}
function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&located(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {tileBuffer:tileBuffer?.metrics(),basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").length},renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};}
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);}
function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}}
function baseReady(ready){if(map?.getLayer('grid'))map.setLayoutProperty('grid','visibility',ready?'none':'visible');}
function setOcclusion(value){
occlusion=Object.fromEntries(['top','right','bottom','left'].map(k=>[k,Number.isFinite(value?.[k])?Math.max(0,value[k]):0]));
}
function visiblePadding(){
if(!map)return {top:0,right:0,bottom:0,left:0};
const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight;
const p={...occlusion};
// Hidden mobile overlays may have just closed; measure visible panels at focus time.
const root=document.getElementById('rt-layout')?.getBoundingClientRect();
if(root){const scale=Math.max(.01,root.width/w);for(const [id,side] of [['rt-directory','left'],['rt-details','right']]){const el=document.getElementById(id);const r=el?.getBoundingClientRect();p[side]=r?.height?side==='left'?(r.right-root.left)/scale+12:(root.right-r.left)/scale+12:0;}
const manager=document.getElementById("rt-list-manager")?.getBoundingClientRect();if(manager?.height)p.right=Math.max(p.right,(root.right-manager.left)/scale+12);
const dock=document.getElementById('rt-dock')?.getBoundingClientRect();p.bottom=dock?.height?(root.bottom-dock.top)/scale+40:116;
}
if(p.left+p.right>w-80){p.left=0;p.right=0;}
if(p.top+p.bottom>h-80){p.top=0;p.bottom=0;}
return p;
}
function focusCoordinate(center,animate=true){
if(!map)return;
const p=visiblePadding();
const options={center,offset:[(p.left-p.right)/2,(p.top-p.bottom)/2]};
if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0});
}
function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);}
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];generations=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";occlusion={top:0,right:0,bottom:0,left:0};}};