Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
|
||||
import { urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||
@@ -24,6 +26,11 @@ export class AiEditorRuntime {
|
||||
private preferences = DEFAULT_PLANNER_PREFERENCES;
|
||||
private selected: string|null = null;
|
||||
private terrain = new EditorTerrain();
|
||||
private urbanLayer: EditorUrbanMapLayer | null = null;
|
||||
private experienceLayer: EditorUrbanMapLayer | null = null;
|
||||
private experiencePoints: number[][] = [];
|
||||
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
|
||||
private urbanMap: UrbanMap | null = null;
|
||||
private collisionLayer: EditorCollisionLayer | null = null;
|
||||
private resize: ResizeObserver;
|
||||
private abort = new AbortController();
|
||||
@@ -70,6 +77,7 @@ export class AiEditorRuntime {
|
||||
const matrix = this.camera.getWorldTransform().data.join(",");
|
||||
if (matrix !== this.previous || this.dirty) {
|
||||
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
|
||||
this.onExperienceProject(this.experiencePoints.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
||||
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
|
||||
this.onProject(this.points.map((p) => {
|
||||
const [x,y,z] = toEditor(p.position);
|
||||
@@ -106,13 +114,28 @@ export class AiEditorRuntime {
|
||||
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
|
||||
this.setClip(Infinity); this.dirty = true;
|
||||
}
|
||||
setViewMode(mode: SimulationViewMode) {
|
||||
if (mode !== "visual" && !this.collisionLayer) {
|
||||
setExperience(document: UrbanMap, points: number[][], callback: (p: ScreenPoint[])=>void) {
|
||||
this.experienceLayer?.dispose();this.experienceLayer=new EditorUrbanMapLayer(this.app,this.camera,document);
|
||||
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip);this.dirty=true;
|
||||
}
|
||||
showExperience(visible: boolean) {this.experienceLayer?.setVisible(visible);this.dirty=true;}
|
||||
clearExperience() {this.experienceLayer?.dispose();this.experienceLayer=null;this.experiencePoints=[];this.onExperienceProject=()=>undefined;this.dirty=true;}
|
||||
setUrbanMap(document: UrbanMap) {
|
||||
this.urbanLayer?.dispose(); this.urbanMap=document;
|
||||
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip);this.dirty=true;
|
||||
}
|
||||
showUrbanMap(visible: boolean) { this.urbanLayer?.setVisible(visible);this.dirty=true; }
|
||||
focusUrbanMap() {
|
||||
const points=this.urbanMap?.features.flatMap(f=>urbanPaths(f).flat()).map(toEditor)??[];
|
||||
if(points.length)this.controls.top(points);this.syncCamera();this.dirty=true;
|
||||
}
|
||||
setViewMode(mode: SimulationViewMode|"map") {
|
||||
if (mode !== "visual" && mode !== "map" && !this.collisionLayer) {
|
||||
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
|
||||
this.collisionLayer.setClip(this.clip);
|
||||
}
|
||||
this.scan.enabled = mode !== "collision";
|
||||
this.collisionLayer?.setMode(mode);
|
||||
this.scan.enabled = mode === "visual" || mode === "combined";
|
||||
this.collisionLayer?.setMode(mode === "map" ? "visual" : mode);
|
||||
this.dirty = true;
|
||||
}
|
||||
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
|
||||
@@ -133,6 +156,7 @@ export class AiEditorRuntime {
|
||||
setClip(height: number) {
|
||||
this.clip = height;
|
||||
this.collisionLayer?.setClip(height);
|
||||
this.urbanLayer?.setClip(height);this.experienceLayer?.setClip(height);
|
||||
if (this.scan.gsplat) {
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
|
||||
@@ -189,6 +213,7 @@ export class AiEditorRuntime {
|
||||
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
|
||||
this.annotations.dispose();
|
||||
this.collisionLayer?.dispose();
|
||||
this.urbanLayer?.dispose();this.clearExperience();
|
||||
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { PlannerExperience } from "./PlannerExperience";
|
||||
import { loadUrbanMap, URBAN_COLORS, URBAN_LABELS, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
import type { SimulationViewMode } from "./PlayCanvasRuntime";
|
||||
import type { PreparedRoute } from "../../core/simulation/routePreparation";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
@@ -31,7 +33,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
const {points,selected,sequence} = editing;
|
||||
const press=useRef<{id:number;x:number;y:number}|null>(null);
|
||||
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
|
||||
const [layerMode,setLayerMode]=useState<SimulationViewMode>("visual");
|
||||
const [layerMode,setLayerMode]=useState<SimulationViewMode|"map">("visual");
|
||||
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||
const [urbanVisible,setUrbanVisible]=useState(false);
|
||||
const [urbanError,setUrbanError]=useState<string|null>(null);
|
||||
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
@@ -42,14 +47,21 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
useEffect(() => {
|
||||
if (cache?.status !== "ready" || !canvas.current) return;
|
||||
let active = true;
|
||||
const abort=new AbortController();
|
||||
setUrbanMap(null);setUrbanVisible(false);setUrbanError(null);
|
||||
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
|
||||
let view: AiEditorRuntime;
|
||||
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
|
||||
catch (e) { setError((e as Error).message); return; }
|
||||
runtime.current = view;
|
||||
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
|
||||
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
|
||||
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
|
||||
void view.load().then(() => { if (active) {
|
||||
setReady(true);
|
||||
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
|
||||
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
|
||||
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
|
||||
} }).catch((e: Error) => { if (active) setError(e.message); });
|
||||
return () => { active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
|
||||
}, [cache?.key,cache?.status,retry]);
|
||||
useEffect(() => {
|
||||
runtime.current?.setPoints(points);
|
||||
@@ -86,7 +98,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
|
||||
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
|
||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
|
||||
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
|
||||
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>
|
||||
{urbanVisible && urbanMap ? <p>Генплан · {urbanMap.coverage.kind === "objects-only" ? `участок · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
|
||||
</div>
|
||||
{urbanVisible?<span className="ai-inference-preview__legend" aria-label="Классы инфраструктуры">
|
||||
{Object.keys(URBAN_LABELS).filter(id=>urbanMap?.features.some(f=>f.properties.class===id)).map(id=>
|
||||
<span key={id}><i style={{background:`rgb(${URBAN_COLORS[id].join(',')})`}}/>{URBAN_LABELS[id]}</span>)}
|
||||
</span>:null}
|
||||
<div className="ai-polygon__viewer">
|
||||
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
|
||||
onKeyDown={(e)=>{
|
||||
@@ -99,11 +117,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
|
||||
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
|
||||
}}><Icon name="trash"/></IconButton>:null}
|
||||
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!} runtime={runtime.current} viewport={viewport.current}/> : null}
|
||||
<SegmentedControl label="Слои сцены" value={layerMode}
|
||||
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"}]}
|
||||
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);setError(null);}
|
||||
items={[{value:"visual",label:"Gaussian"},{value:"collision",label:"Коллизии"},{value:"combined",label:"Вместе"},...(urbanMap?[{value:"map" as const,label:"Генплан"}]:[])]}
|
||||
onChange={v=>{try {runtime.current?.setViewMode(v);setLayerMode(v);if(v==="map"){setUrbanVisible(true);runtime.current?.showUrbanMap(true);runtime.current?.focusUrbanMap();setViewMode("top");}setError(null);}
|
||||
catch (e) {setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}/>
|
||||
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
|
||||
<IconButton label={urbanError??(urbanMap?"Карта дорожной инфраструктуры":"Карта инфраструктуры ещё не подготовлена")}
|
||||
disabled={!urbanMap || layerMode==="map"} aria-pressed={urbanVisible} onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}><Icon name="layers"/></IconButton>
|
||||
{urbanVisible?<IconButton label="Показать участок карты" onClick={()=>{runtime.current?.focusUrbanMap();setViewMode("top");}}><Icon name="plan"/></IconButton>:null}
|
||||
{preparedRoute||urbanMap?<SegmentedControl label="Ракурс" value={viewMode}
|
||||
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
|
||||
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
|
||||
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Application, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
|
||||
import { toEditor } from "../../core/simulation/aiEditor";
|
||||
import { URBAN_COLORS, urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
|
||||
|
||||
/** Read-only contours. This layer never enters terrain picking, collision or routing. */
|
||||
export class EditorUrbanMapLayer {
|
||||
private entity: Entity;
|
||||
private mesh: Mesh;
|
||||
private material: ShaderMaterial;
|
||||
private layer = new Layer({ name: "Urban infrastructure observations" });
|
||||
constructor(private app: Application, private camera: Entity, document: UrbanMap) {
|
||||
app.scene.layers.insert(this.layer, app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1);
|
||||
camera.camera!.layers = [...camera.camera!.layers, this.layer.id];
|
||||
this.material = new ShaderMaterial({ uniqueName: "urban-map-contours", attributes: { vertex_position: SEMANTIC_POSITION, vertex_color: SEMANTIC_COLOR },
|
||||
vertexGLSL: `attribute vec3 vertex_position; attribute vec4 vertex_color;
|
||||
uniform mat4 matrix_model; uniform mat4 matrix_viewProjection;
|
||||
varying vec4 mapColor; varying float mapHeight;
|
||||
void main(void) { vec4 p=matrix_model*vec4(vertex_position,1.0); mapColor=vertex_color; mapHeight=p.y; gl_Position=matrix_viewProjection*p; }`,
|
||||
fragmentGLSL: `precision highp float; varying vec4 mapColor; varying float mapHeight; uniform float mapClip;
|
||||
void main(void) { if(mapHeight>mapClip) discard; gl_FragColor=mapColor; }` });
|
||||
this.material.depthTest = false; this.material.depthWrite = false;
|
||||
const positions: number[] = [], colors: number[] = [];
|
||||
for (const feature of document.features) {
|
||||
const color = URBAN_COLORS[feature.properties.class]; if (!color) continue;
|
||||
for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
|
||||
positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
|
||||
colors.push(...color,255,...color,255);
|
||||
}
|
||||
}
|
||||
this.mesh = new Mesh(app.graphicsDevice); this.mesh.setPositions(positions); this.mesh.setColors32(colors); this.mesh.update(PRIMITIVE_LINES);
|
||||
this.entity = new Entity("Urban infrastructure",app);
|
||||
this.entity.addComponent("render", { meshInstances: [new MeshInstance(this.mesh,this.material)], layers: [this.layer.id] });
|
||||
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
|
||||
}
|
||||
setVisible(visible: boolean) { this.entity.enabled=visible; }
|
||||
setClip(height: number) { this.material.setParameter("mapClip",Number.isFinite(height)?height:1e9); }
|
||||
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id); this.app.scene.layers.remove(this.layer); this.entity.destroy();this.mesh.destroy();this.material.destroy(); }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Icon, IconButton } from "@nodedc/ui-react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import type { AiEditorRuntime } from "./AiEditorRuntime";
|
||||
import { URBAN_COLORS } from "../../core/simulation/urbanMap";
|
||||
|
||||
export function PlannerExperience({worldId,worldSha,runtime,viewport}: {
|
||||
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;
|
||||
}) {
|
||||
const [memory,setMemory]=useState<SpatialExperience|null>(null),[visible,setVisible]=useState(false);
|
||||
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const refresh=async()=>{
|
||||
try {const value=await loadExperience(worldId,worldSha,abort.signal);
|
||||
if(abort.signal.aborted)return;setMemory(value);setError(null);
|
||||
if(value)runtime.setExperience(experienceMap(value),value.attempts.map(a=>a.xyz),setProjected);
|
||||
} catch(e) {if(!abort.signal.aborted)setError((e as Error).message);}
|
||||
if(!abort.signal.aborted)timer=setTimeout(refresh,5000);
|
||||
};
|
||||
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
|
||||
},[worldId,worldSha,runtime]);
|
||||
useEffect(()=>runtime.showExperience(visible),[runtime,visible,memory]);
|
||||
return <>
|
||||
<IconButton label={error??(memory?`Память локации · посещено ${memory.visits.length} участков · ${memory.attempts.length} попыток`:"В этой локации ещё нет сохранённого опыта")}
|
||||
disabled={!memory} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}><Icon name="database"/></IconButton>
|
||||
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
|
||||
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
|
||||
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
|
||||
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||
</g>;
|
||||
})}
|
||||
</svg>,viewport):null}
|
||||
</>;
|
||||
}
|
||||
Reference in New Issue
Block a user