Files
fpv-rid-workbench/crates/web-ui/public/map-tile-buffer.js
T
JiuContinent 7af8fb32cf feat(web-ui): 添加历史轨迹功能与地图适配
- 在 web-ui 中新增历史轨迹查询与回放功能,允许用户查看历史数据。
- 更新 map-loader.js 和 history-map-adapter.js,支持历史轨迹的地图渲染与交互。
- 修改 CSS 文件以改善历史轨迹界面的样式,确保在不同主题下的视觉一致性。
- 在 receivers.js 中更新接收机配置,支持 UID 身份隔离与状态显示优化。
- 在 map_settings.rs 中设置默认经纬度,提升地图初始化体验。
2026-11-02 15:28:01 +08:00

60 lines
4.5 KiB
JavaScript

// Shared, bounded viewport warming. Visible MapLibre requests always run first.
const pairs={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
export function attachTileBuffer(map,getKind,getRevision=()=>0){
let generation=0,closed=false,timer,retryTimer,cooldownUntil=0,controllers=new Set(),queue=[],running=0,lastSignature='',lastPrepared=0;
const warmed=new Map();
const metrics={requested:0,hits:0,cancelled:0,failed:0};
const url=(layer,z,x,y)=>`/api/maps/tile/${layer}/${z}/${x}/${y}${getRevision()?`?v=${getRevision()}`:''}`;
function cancel(){generation++;lastSignature='';clearTimeout(timer);timer=null;clearTimeout(retryTimer);retryTimer=null;queue=[];for(const c of controllers)c.abort();controllers.clear();}
function retry(){cooldownUntil=Date.now()+30000;lastSignature='';queue=[];wake(30000);}
function pump(token){
if(closed||token!==generation||Date.now()<cooldownUntil)return;
while(running<1&&queue.length){
const item=queue.shift(),controller=new AbortController();controllers.add(controller);running++;metrics.requested++;
fetch(item,{signal:controller.signal,cache:'default',headers:{'x-rid-prefetch':'1'}}).then(async response=>{
if(response.status===429){if(token===generation){queue.unshift(item);cooldownUntil=Date.now()+500;clearTimeout(retryTimer);retryTimer=setTimeout(()=>{retryTimer=null;pump(token);},550);}return;}
if(!response.ok)throw Error('tile unavailable');await response.arrayBuffer();
if(closed||token!==generation)return;
warmed.delete(item);warmed.set(item,Date.now());while(warmed.size>4096)warmed.delete(warmed.keys().next().value);
}).catch(error=>{if(error.name==='AbortError')metrics.cancelled++;else {metrics.failed++;if(!closed&&token===generation)retry();}}).finally(()=>{
controllers.delete(controller);running--;pump(generation);if(!running&&!queue.length&&!lastSignature)schedule();
});
}
}
function prepare(){
if(closed)return;
if(Date.now()<cooldownUntil){wake(cooldownUntil-Date.now());return;}
if(running||queue.length)return;
if(map.isMoving()||!map.isStyleLoaded()){schedule();return;}
const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight;
if(!w||!h){schedule();return;}
const c=map.getCenter(),signature=[c.lng,c.lat,map.getZoom(),map.getPitch(),map.getBearing(),w,h,getKind(),getRevision()].join('/');
if(signature===lastSignature&&Date.now()-lastPrepared<60000)return;
cancel();const token=generation;lastSignature=signature;lastPrepared=Date.now();
// A 256px raster source uses one level above the 512px MapLibre camera scale.
const detail=Math.min(18,Math.max(0,Math.round(map.getZoom()+1)));
const kind=getKind(),groups=[pairs[kind],pairs[kind==='road'?'imagery':'road']],unique=new Set();
// Warm the immediate parent too: raster fades can request it during a pan.
for(const layers of groups)for(const z of new Set([detail,Math.max(0,detail-1)])){
const n=2**z;
const tile=p=>{const c=map.unproject(p),lat=Math.max(-85.051128,Math.min(85.051128,c.lat))*Math.PI/180;return [(c.lng+180)/360*n,(1-Math.asinh(Math.tan(lat))/Math.PI)/2*n];};
const corners=[tile([-w,-h]),tile([2*w,-h]),tile([-w,2*h]),tile([2*w,2*h])],center=tile([w/2,h/2]);
const x0=Math.floor(Math.min(...corners.map(p=>p[0]))),x1=Math.floor(Math.max(...corners.map(p=>p[0])));
const y0=Math.max(0,Math.floor(Math.min(...corners.map(p=>p[1])))),y1=Math.min(n-1,Math.floor(Math.max(...corners.map(p=>p[1]))));
const cells=[];for(let x=x0;x<=Math.min(x1,x0+n-1);x++)for(let y=y0;y<=y1;y++)cells.push([x,y,(x-center[0])**2+(y-center[1])**2]);
cells.sort((a,b)=>a[2]-b[2]);
for(const [x,y]of cells.slice(0,32))for(const layer of layers){
const key=url(layer,z,((x%n)+n)%n,y);if(unique.has(key))continue;unique.add(key);
if(Date.now()-(warmed.get(key)||0)<240000){metrics.hits++;continue;}queue.push(key);
}
}
pump(token);
}
function wake(delay){if(closed||timer)return;timer=setTimeout(()=>{timer=null;prepare();},delay);}
const schedule=()=>wake(200);
const sourcedata=e=>{if(/^(tdt-base|tdt-labels|base|labels)$/.test(e.sourceId)&&e.isSourceLoaded&&!running&&!queue.length)schedule();};
map.on('movestart',cancel);map.on('moveend',schedule);map.on('idle',schedule);map.on('load',schedule);map.on('sourcedata',sourcedata);
schedule();
return {schedule(){cancel();cooldownUntil=0;lastSignature='';schedule();},metrics:()=>({...metrics,queued:queue.length,running,warmed:warmed.size}),destroy(){closed=true;cancel();map.off('movestart',cancel);map.off('moveend',schedule);map.off('idle',schedule);map.off('load',schedule);map.off('sourcedata',sourcedata);warmed.clear();}};
}