feat(simulation): integrate infrastructure jobs and semantic scene editing

Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent 25dc0a1b44
commit f48411f8fe
116 changed files with 10690 additions and 263 deletions
+26
View File
@@ -19,6 +19,7 @@
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1",
@@ -1757,6 +1758,16 @@
"node": ">=18.3.0"
}
},
"node_modules/polygon-clipping": {
"version": "0.15.7",
"resolved": "https://registry.npmjs.org/polygon-clipping/-/polygon-clipping-0.15.7.tgz",
"integrity": "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==",
"license": "MIT",
"dependencies": {
"robust-predicates": "^3.0.2",
"splaytree": "^3.1.0"
}
},
"node_modules/postcss": {
"version": "8.5.19",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
@@ -1817,6 +1828,12 @@
"node": ">=0.10.0"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rollup": {
"version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1888,6 +1905,15 @@
"node": ">=0.10.0"
}
},
"node_modules/splaytree": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/splaytree/-/splaytree-3.2.3.tgz",
"integrity": "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==",
"license": "MIT",
"engines": {
"node": ">=18.20 || >=20"
}
},
"node_modules/three": {
"version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
+2 -1
View File
@@ -9,7 +9,7 @@
"prebuild": "node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:unit": "node --test test/*.test.mjs",
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false"
},
"dependencies": {
@@ -23,6 +23,7 @@
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1",
@@ -1,17 +1,20 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
import { sceneClipBounds } from "../../core/simulation/sceneClip";
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
import { urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
import { EditorCollisionLayer } from "./EditorCollisionLayer";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, Color, Entity, FILLMODE_NONE, Mat4, Quat, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
@@ -22,15 +25,21 @@ export class AiEditorRuntime {
private scan: Entity;
private asset: Asset | null = null;
private controls: EditorCamera;
private surfacePicker: EditorSurfacePicker;
private collisionVisible = false;
private annotations: PlannerMarkers;
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private urbanLayer: EditorUrbanMapLayer | null = null;
private urbanBounds:number[][]=[];
private cameraProject: ((q:[number,number,number,number])=>void)|null=null;
private semanticProject: (()=>void)|null = null;
private visualBounds:number[][]=[];
private urbanVisible=false;
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();
@@ -40,6 +49,7 @@ export class AiEditorRuntime {
private points: AiWaypoint[] = [];
private route: number[][] = [];
clip = Infinity;
clipFloor = -Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void,
@@ -54,10 +64,19 @@ export class AiEditorRuntime {
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
this.controls = new EditorCamera(canvas.parentElement!, canvas);
this.surfacePicker = new EditorSurfacePicker(app, this.camera, canvas);
app.root.addChild(this.camera);
app.root.addChild(this.scan);
this.annotations = new PlannerMarkers(app,this.camera,canvas);
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
this.controls.pickSurface = async (x,y) => {
this.syncCamera();
if(this.scan.enabled && this.scan.gsplat) return this.surfacePicker.pick(x,y);
if(!this.collisionVisible)return null;
const from=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,2000);
return this.terrain.pickSurface([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,false,this.clipFloor)?.toArray()??null;
};
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
this.scan.setPosition(transform.getTranslation());
this.scan.setRotation(new Quat().setFromMat4(transform));
@@ -74,9 +93,10 @@ export class AiEditorRuntime {
this.controls.update(dt); this.syncCamera();
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
if (this.annotations.update(dt)) app.renderNextFrame = true;
const matrix = this.camera.getWorldTransform().data.join(",");
const matrix = this.camera.getWorldTransform().data.join(",")+this.controls.camera.projectionMatrix.elements.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.semanticProject?.();this.cameraProject?.(this.controls.camera.quaternion.toArray());
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) => {
@@ -90,10 +110,9 @@ export class AiEditorRuntime {
}
async load() {
const scene = localScene(this.cache);
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
if (scene.collision.available && scene.collision.meshUrl)
await this.terrain.load(scene.collision.meshUrl, this.abort.signal, scene.transforms.worldFromCollision);
if (this.disposed) return;
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
this.asset = asset;
await new Promise<void>((resolve,reject) => {
@@ -102,44 +121,100 @@ export class AiEditorRuntime {
});
if (this.disposed) { asset.unload(); return; }
this.scan.addComponent("gsplat", { asset, unified: true });
const bounds = new BoundingBox();
bounds.setFromTransformedAabb(this.scan.gsplat!.customAabb!, this.scan.getWorldTransform());
const low=bounds.getMin(),high=bounds.getMax();
this.visualBounds=[...Array(8)].map((_,i)=>[i&1?high.x:low.x,i&2?high.y:low.y,i&4?high.z:low.z]);
const terrain=this.terrain.bounds;
this.height = sceneClipBounds([low.y, high.y], terrain.isEmpty() ? null : [terrain.min.y, terrain.max.y]);
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
uniform float editorFloor;
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip) color.a = 0.0;
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
}` });
this.setPreferences(this.preferences);
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
else this.controls.sceneCenter = terrain.getCenter(this.controls.sceneCenter);
if (!scene.collision.available) { this.controls.top(this.visualBounds); this.syncCamera(); }
this.setClip(Infinity); this.dirty = true;
}
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;
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip,this.clipFloor);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;
this.urbanBounds=urbanExtent(document);
this.urbanLayer?.dispose();
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);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;
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;}
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
watchSemantic(callback:(()=>void)|null) { this.semanticProject=callback;this.dirty=true; }
projectSemantic(point:number[]): ScreenPoint {
if(point[2]<this.clipFloor||point[2]>this.clip)return null;
return this.project(...toEditor(point) as [number,number,number]);
}
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);
semanticSegmentParameter(a:number[],b:number[],u:number) {
if(isOrthographic(this.controls.camera))return u;
const depth=(p:number[])=>new Vec3(...toEditor(p)).sub(this.camera.getPosition()).dot(this.camera.forward);
const za=depth(a),zb=depth(b);
return u*za/((1-u)*zb+u*za);
}
/** Explicit planar edit: preserve source elevation, never pretend a ray hit ground. */
moveSemantic(point:number[],x:number,y:number,axis:import("../../core/simulation/semanticVector").SemanticAxis="xy") {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const origin=toMission([from.x,from.y,from.z]),direction=toMission([to.x-from.x,to.y-from.y,to.z-from.z]);
let result:number[]|null;
if(axis.length===1)result=dragWaypoint(origin,direction,point,axis as "x"|"y"|"z");
else {
const normal=[0,1,2].find(k=>!axis.includes("xyz"[k]))!;
if(Math.abs(direction[normal])<1e-8)return null;
const t=(point[normal]-origin[normal])/direction[normal];if(t<0)return null;
result=point.map((v,k)=>k===normal?v:origin[k]+t*direction[k]);
}
this.scan.enabled = mode === "visual" || mode === "combined";
this.collisionLayer?.setMode(mode === "map" ? "visual" : mode);
if(!result)return null;
return result[2]>=this.clipFloor&&result[2]<=this.clip?result:null;
}
semanticGizmo(point:number[]) {
const depth=new Vec3(...toEditor(point)).sub(this.camera.getPosition()).dot(this.camera.forward);
const length=screenSpan(this.controls.camera,depth)*this.preferences.pivot.pixels*.7/Math.max(1,this.canvas.clientHeight);
return {length,colors:this.preferences.pivot,base:this.projectSemantic(point),
x:this.projectSemantic([point[0]+length,point[1],point[2]]),
y:this.projectSemantic([point[0],point[1]+length,point[2]]),
z:this.projectSemantic([point[0],point[1],point[2]+length])};
}
async pickSemanticSurface(x:number,y:number) {
if(!this.scan.enabled||!this.scan.gsplat)return null;
this.syncCamera();
const hit=await this.surfacePicker.pick(x,y);
if(!hit)return null;
const q=toMission(hit);
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
}
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; }
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
this.collisionLayer.setClip(this.clip,this.clipFloor);
}
this.scan.enabled = gaussian;
this.collisionLayer?.setMode(collision ? (gaussian ? "combined" : "collision") : "visual");
this.dirty = true;
}
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
top() {this.controls.top((this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor));this.syncCamera();this.dirty=true;}
top() {const points=(this.urbanVisible&&this.urbanBounds.length?this.urbanBounds:this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor);this.controls.top(points.length?points:this.visualBounds);this.syncCamera();this.dirty=true;}
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
setPreferences(preferences: PlannerPreferences) {
@@ -153,12 +228,14 @@ export class AiEditorRuntime {
}
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number) {
this.clip = height;
this.collisionLayer?.setClip(height);
this.urbanLayer?.setClip(height);this.experienceLayer?.setClip(height);
setClip(height: number, floor = -Infinity) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();
this.clip = height; this.clipFloor = floor;
this.collisionLayer?.setClip(height,floor);
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
this.dirty = true;
@@ -166,9 +243,13 @@ export class AiEditorRuntime {
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
}
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
private syncCamera() {
const { position:p, quaternion:q } = this.controls.camera;
const c=this.controls.camera;
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
const { position:p, quaternion:q } = c;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
}
home() {
@@ -179,7 +260,7 @@ export class AiEditorRuntime {
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,this.clipFloor);
return hit ? toMission(hit.toArray()) : null;
}
pickWaypoint(x:number,y:number) {
@@ -200,16 +281,17 @@ export class AiEditorRuntime {
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
if (!hit) return null;
if (axis !== "xz") return toMission(hit);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip,this.clipFloor);
return ground ? toMission(ground.toArray()) : null;
}
private project(x:number,y:number,z:number): ScreenPoint {
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
return new Vec3(x,y,z).sub(this.camera.getPosition()).dot(this.camera.forward) > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
}
dispose() {
this.disposed = true;
this.controls.dispose();
this.surfacePicker.dispose();
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.collisionLayer?.dispose();
@@ -1,6 +1,11 @@
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
import {PlannerCameraTools} from "./PlannerCameraTools";
import { heightSlice } from "../../core/heightSlice";
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
import { PlannerLegend } from "./PlannerLegend";
import { SemanticEditor } from "./SemanticEditor";
import { PlannerExperience } from "./PlannerExperience";
import { loadUrbanMap, URBAN_COLORS, URBAN_LABELS, type UrbanMap } from "../../core/simulation/urbanMap";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
@@ -8,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, RangeControl, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
@@ -17,10 +22,14 @@ import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false, preparedRoute=null }: {
export type LocationMode = "view" | "semantic" | "planning";
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
}) {
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
@@ -33,44 +42,62 @@ 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|"map">("visual");
const [layout,updateLayout]=useSimulationLayout();
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
const [urbanVisible,setUrbanVisible]=useState(false);
const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
const [memoryVisible,setMemoryVisible]=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");
const [clip,setClip] = useState(Infinity);
const [clip,setClip] = useState<[number,number]|null>(null);
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
const callback = useRef(onDraft); callback.current = onDraft;
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true;
let active = true, loaded=false;
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
const abort=new AbortController();
setUrbanMap(null);setUrbanVisible(false);setUrbanError(null);
setReady(false); setError(null); setClip(Infinity); setLayerMode("visual");
setUrbanMap(null);setUrbanError(null);
setReady(false); setError(null); setClip(null);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
catch (e) { setError((e as Error).message); return; }
catch (e) { clearInterval(timer);window.removeEventListener("pagehide",remember);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);
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
loaded=true;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); };
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
useEffect(() => {
runtime.current?.setPoints(points);
runtime.current?.setPoints(planning?points:[]);
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence]);
}, [points,cache,ready,sequence,planning]);
useEffect(()=>{
runtime.current?.setRoute(preparedRoute?.preview_xyz??[]);
if(preparedRoute && ready){runtime.current?.top();setViewMode("top");}
},[preparedRoute?.sha256,ready]);
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
},[semantic,urbanMap,urbanVisible,urbanClasses]);
useEffect(()=>{
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
},[preparedRoute?.sha256,ready,planning]);
useEffect(()=>{
setMode("view");press.current=null;runtime.current?.setAddMode(false);
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
},[sceneMode,ready]);
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
@@ -94,47 +121,60 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null;
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
{expanded ? <>
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
</> : <>
{actionsHost ? createPortal(header,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>
{urbanVisible && urbanMap ? <p>Генплан · {urbanMap.coverage.kind === "objects-only" ? `участок · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null}
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${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)=>{
if(!planning)return;
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
const action=waypointShortcut(e,editable);
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
}}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning routeEditing={planning} semantic={semantic}>
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
{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:"Вместе"},...(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:"Не удалось показать слой коллизий.");}}}/>
<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");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
<div className="ai-local-editor__tool-row">
{runtime.current&&viewport.current?<PlannerCameraTools runtime={runtime.current} viewport={viewport.current} semantic={semantic} disabled={busy}/>:null} {planning?<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>:null}
{planning&&points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
</div>
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
active={urbanVisible} aria-pressed={urbanVisible}
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
</SegmentedGroup>
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} active={semantic} busy={busy} source={urbanMap} headerHost={semanticHeader}/>:null}
{semantic&&!urbanMap?<StatusBadge tone="neutral">Рассчитайте инфраструктуру для редактирования</StatusBadge>:null}
</div>:null}
</SimulationViewTools>
<div className="ai-local-editor__surface"
onPointerDownCapture={(e)=>{
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
if(!planning || e.target!==canvas.current || e.button!==0 || busy || !ready)return;
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
if(!id)return;
e.preventDefault();e.stopPropagation();press.current=null;
@@ -145,14 +185,14 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
}}
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerDown={(e)=>{if(planning&&e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerCancel={()=>{press.current=null;}}
onPointerUp={(e)=>{
const start=press.current;press.current=null;
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(!planning||!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
<svg ref={markerSvg} style={!planning?{display:"none"}:undefined} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
onPointerMove={(e)=>{
if (!drag.current) return;
const d=drag.current, [x,y]=position(e);
@@ -183,11 +223,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={Number.isFinite(clip)?clip:runtime.current!.height[1]}
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
onChange={(v)=>{const next=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div>
@@ -0,0 +1,74 @@
import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
}) {
const queue=useInfrastructureQueue();
const [editing, setEditing] = useState<AiWorld | null>(null);
const [name, setName] = useState("");
const [confirming, setConfirming] = useState(false);
const [showRemoved, setShowRemoved] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const update = async (world: AiWorld, changes: {display_name?:string;removed?:boolean}) => {
if (busy) return;
setBusy(world.world_id); setError(null);
try {
await updateAiWorld(world.world_id, changes);
await onChanged();
setConfirming(false); setEditing(null);
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось сохранить изменения.");
} finally { setBusy(null); }
};
return <>
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
actions={<>
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
<IconButton label={`Настройки ${world.name}`} onClick={() => {
setEditing(world); setName(world.name); setConfirming(false); setError(null);
}}><Icon name="settings"/></IconButton>
</>}/>
</li>;})}</ResourceList>
{removedWorlds.length ? <>
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
Удалённые локации · {removedWorlds.length}</Button>
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
<Button disabled={busy !== null} loading={busy === world.world_id}
onClick={() => void update(world, {removed:false})}>Восстановить</Button>}/>
</li>)}</ResourceList> : null}
</> : null}
<Window open={!!editing && !confirming} title="Настройки локации" size="sm"
onClose={() => {if (!busy) setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
onClick={() => setConfirming(true)}>Удалить локацию</Button>
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
</WindowFooterActions>}>
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
</Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
Восстановить её можно в списке удалённых локаций.</>}
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
onDismiss={() => setError(null)}/> : null}
</>;
}
@@ -126,7 +126,7 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
}} />
</div> : null}
{editing ? <div className="ai-route__tools">
{editing ? <div className="ai-route__tools nodedc-viewport-controls">
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
@@ -1,24 +1,31 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
import { zoomDisplacement } from "../../core/simulation/editorZoom";
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
import { PerspectiveCamera, Vector3 } from "three";
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
/** Input/math only: PlayCanvas remains the sole renderer. */
export class EditorCamera {
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
camera:ProjectionCamera = new PerspectiveCamera(60, 1, .05, 3000);
private aspect=1;
get projection():EditorProjection {return isOrthographic(this.camera)?"orthographic":"perspective";}
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private topPoints:number[][]|null=null;
private addMode=false;
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
semanticSelection=false;
private gesture: {id:number;x:number;y:number;nextX:number;nextY:number;anchor:Vector3;depth:number;distance:number;pan:boolean;pending:boolean}|null=null;
private lastAnchor: Vector3|null = null;
private forward = new Vector3();
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
pick: ((x:number,y:number)=>number[]|null)|null = null;
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
surface.addEventListener("wheel",this.zoom,{passive:false});
surface.addEventListener("pointerdown",this.pointerDown);
@@ -34,68 +41,122 @@ export class EditorCamera {
private anchor(x:number,y:number) {
const hit=this.pick?.(x,y);
if(hit)return new Vector3(...hit);
// Empty sky has no surface; retain useful scale relative to the scene.
return this.camera.getWorldDirection(new Vector3())
.multiplyScalar(Math.max(2,this.camera.position.distanceTo(this.sceneCenter))).add(this.camera.position);
// Empty sky: retain useful depth, but keep the pivot on the clicked ray.
const depth=this.lastAnchor?navigationDepth(this.camera,this.lastAnchor):Math.max(2,this.camera.position.distanceTo(this.sceneCenter));
const forward=this.camera.getWorldDirection(new Vector3());
const ray=cameraRay(this.camera,x,y);
return ray.at((depth-ray.origin.clone().sub(this.camera.position).dot(forward))/Math.max(.01,ray.direction.dot(forward)),new Vector3());
}
private pointerDown=(e:PointerEvent)=>{
const editOrbit=this.semanticSelection&&e.ctrlKey&&[0,2].includes(e.button);
// Ctrl-drag may start on a semantic gizmo as well as the underlying canvas.
if(e.target!==this.canvas&&!(editOrbit&&(e.target as Element).closest("[data-semantic-axis],[data-semantic-handle]")))return;
this.canvas.focus({preventScroll:true});
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
if(e.button===0 && this.addMode)return;
const rect=this.canvas.getBoundingClientRect();
const anchor=this.anchor((e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height);
this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0};
if(e.button===0&&(this.semanticSelection&&!editOrbit||this.addMode&&!editOrbit))return;
if(editOrbit)e.preventDefault();
this.cancelGesture();
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const anchor=this.anchor(x,y);this.lastAnchor=anchor.clone();
const g=this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,nextX:e.clientX,nextY:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0&&!editOrbit,pending:!!this.pickSurface};
this.surface.setPointerCapture(e.pointerId);
if(this.pickSurface)void this.pickSurface(x,y).catch(()=>null).then(hit=>{
if(this.gesture!==g)return; // Released pointer, new gesture, resize or view change.
if(hit?.length===3&&hit.every(Number.isFinite)){g.anchor.set(...hit as [number,number,number]);this.lastAnchor=g.anchor.clone();}
g.depth=navigationDepth(this.camera,g.anchor);g.distance=this.camera.position.distanceTo(g.anchor);g.pending=false;
this.moveGesture(g.nextX,g.nextY);
});
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
this.topPoints=null;
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
g.nextX=e.clientX;g.nextY=e.clientY;
if(!g.pending)this.moveGesture(e.clientX,e.clientY);
};
private moveGesture(x:number,y:number){
const g=this.gesture;if(!g)return;
const dx=x-g.x,dy=y-g.y;g.x=x;g.y=y;
if(!dx&&!dy)return;
this.topPoints=null;
if(g.pan){const before=this.camera.position.clone();panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);this.lastAnchor?.add(this.camera.position.clone().sub(before));}
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
}
private pointerEnd=(e:PointerEvent)=>{
if(this.gesture?.id!==e.pointerId)return;
this.gesture=null;
if(this.surface.hasPointerCapture(e.pointerId))this.surface.releasePointerCapture(e.pointerId);
this.cancelGesture();
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled)return;
if(!this.enabled||e.target!==this.canvas)return;
this.cancelGesture();
this.topPoints=null;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
const depth=this.camera.position.distanceTo(this.anchor(x,y));
const anchor=this.anchor(x,y),ray=cameraRay(this.camera,x,y).direction;
const depth=this.camera.position.distanceTo(anchor);
if(this.semanticSelection&&!e.ctrlKey&&!e.metaKey) {
const before=this.camera.position.clone();panCamera(this.camera,navigationDepth(this.camera,anchor),e.deltaX,e.deltaY,this.canvas.clientHeight);
this.lastAnchor=anchor.add(this.camera.position.clone().sub(before));
this.camera.updateMatrixWorld();return;
}
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));this.camera.updateMatrixWorld();
if(isOrthographic(this.camera)) {
const factor=Math.exp(Math.max(-.8,Math.min(.8,delta*this.navigation.zoom*.002)));
const next=Math.max(.05,Math.min(5000,this.camera.top*factor)),ratio=next/this.camera.top;
const offset=anchor.clone().sub(this.camera.position);offset.addScaledVector(this.camera.getWorldDirection(new Vector3()),-navigationDepth(this.camera,anchor));
this.camera.position.addScaledVector(offset,1-ratio);
this.camera.top=next;this.camera.bottom=-next;this.camera.left=-next*this.aspect;this.camera.right=next*this.aspect;this.camera.updateProjectionMatrix();
} else this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));
this.lastAnchor=anchor;this.camera.updateMatrixWorld();
};
private keyDown=(e:KeyboardEvent)=>{
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
e.preventDefault();this.keys.add(e.code);
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private clear=()=>{this.keys.clear();this.gesture=null;};
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
private cancelGesture(){const id=this.gesture?.id;this.gesture=null;if(id!==undefined&&this.surface.hasPointerCapture(id))this.surface.releasePointerCapture(id);}
private clear=()=>{this.keys.clear();this.cancelGesture();};
resize(width:number,height:number){this.cancelGesture();this.aspect=width/height;if(isOrthographic(this.camera)){this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;}else this.camera.aspect=this.aspect;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
setProjection(mode:EditorProjection){this.clear();this.camera=switchProjection(this.camera,mode,this.aspect,navigationDepth(this.camera,this.lastAnchor??this.sceneCenter));}
view(direction:number[]){
this.clear();this.topPoints=null;
const depth=navigationDepth(this.camera,this.lastAnchor??this.sceneCenter),target=this.camera.position.clone().addScaledVector(this.camera.getWorldDirection(new Vector3()),depth);
const d=new Vector3(...direction).normalize();this.camera.position.copy(target).addScaledVector(d,depth);
this.camera.up.set(0,1,0);if(Math.abs(d.y)>.999)this.camera.up.set(0,0,-Math.sign(d.y));
this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();this.lastAnchor=target;
}
home(point:number[]){
this.clear();this.lastAnchor=null;
this.topPoints=null;
const target=new Vector3(...point);
if(isOrthographic(this.camera)){this.camera.top=6.5;this.camera.bottom=-6.5;this.camera.left=-6.5*this.aspect;this.camera.right=6.5*this.aspect;this.camera.updateProjectionMatrix();}
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
top(points:number[][]){
if(!points.length)return;
this.clear();this.lastAnchor=null;
this.topPoints=points;
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
const span=Math.max((high[0]-low[0])/this.camera.aspect,high[2]-low[2],10);
const span=Math.max((high[0]-low[0])/this.aspect,high[2]-low[2],10);
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
this.camera.position.copy(target).add(new Vector3(0,distance,0));
if(isOrthographic(this.camera)){this.camera.top=span*.575;this.camera.bottom=-this.camera.top;this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;this.camera.updateProjectionMatrix();}
this.lastAnchor=target;this.camera.position.copy(target).add(new Vector3(0,distance,0));
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.addMode=add;}
snapshot(){return {position:this.camera.position.toArray(),quaternion:this.camera.quaternion.toArray(),anchor:this.lastAnchor?.toArray()??null,projection:this.projection,span:isOrthographic(this.camera)?this.camera.top:null};}
restore(view:SceneView){
this.clear();this.topPoints=null;this.setProjection(view.projection);
this.camera.position.fromArray(view.position);this.camera.quaternion.fromArray(view.quaternion);
this.lastAnchor=view.anchor?new Vector3(...view.anchor):null;
if(isOrthographic(this.camera)&&view.span!==null){this.camera.top=view.span;this.camera.bottom=-view.span;this.camera.left=-view.span*this.aspect;this.camera.right=view.span*this.aspect;}
this.camera.updateProjectionMatrix();this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
this.cancelGesture();
this.topPoints=null;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
@@ -35,9 +35,10 @@ export class EditorCollisionLayer {
fragmentGLSL: `
varying vec3 surfacePosition;
uniform float surfaceClip;
uniform float surfaceFloor;
uniform float surfaceOpacity;
void main(void) {
if (surfacePosition.y > surfaceClip) discard;
if (surfacePosition.y > surfaceClip || surfacePosition.y < surfaceFloor) discard;
vec3 normal = normalize(cross(dFdx(surfacePosition), dFdy(surfacePosition)));
float shade = 0.42 + 0.58 * abs(dot(normal, normalize(vec3(0.3, 1.0, 0.4))));
gl_FragColor = vec4(vec3(0.2, 0.95, 0.42) * shade, surfaceOpacity);
@@ -64,7 +65,8 @@ export class EditorCollisionLayer {
this.material.depthWrite = true;
this.material.update();
}
setClip(height: number) {
setClip(height: number, floor = -Infinity) {
this.material.setParameter("surfaceFloor", Number.isFinite(floor) ? floor : -1e9);
this.material.setParameter("surfaceClip", Number.isFinite(height) ? height : 1e9);
}
dispose() {
@@ -0,0 +1,38 @@
import { Application, Entity, LAYERID_WORLD, Picker } from "playcanvas";
/** Visual navigation only. Gaussian depth never becomes a route/collision surface. */
export class EditorSurfacePicker {
private picker: Picker | null = null;
private tail: Promise<void> = Promise.resolve();
private request = 0;
private disposed = false;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {}
pick(x: number, y: number): Promise<number[] | null> {
const request = ++this.request;
// Keep one GPU readback in flight; superseded clicks never resize its buffer.
const result = this.tail.then(async () => {
if (this.disposed || request !== this.request || x < 0 || x >= 1 || y < 0 || y >= 1) return null;
const world = this.app.scene.layers.getLayerById(LAYERID_WORLD);
if (!world) return null;
const width = Math.max(1, Math.round(this.canvas.clientWidth));
const height = Math.max(1, Math.round(this.canvas.clientHeight));
this.picker ??= new Picker(this.app, width, height, true);
this.picker.resize(width, height);
// Exclude infrastructure, route markers and gizmos from the depth measurement.
this.picker.prepare(this.camera.camera!, this.app.scene, [world]);
const point = await this.picker.getWorldPointAsync(x * width, y * height);
if (this.disposed || request !== this.request || !point) return null;
const xyz = [point.x, point.y, point.z];
return xyz.every(Number.isFinite) ? xyz : null;
});
this.tail = result.then(() => undefined, () => undefined);
return result;
}
invalidate() { this.request++; }
dispose() {
this.disposed = true; this.invalidate();
this.picker?.destroy(); this.picker = null;
}
}
@@ -54,16 +54,20 @@ export class EditorTerrain {
indices: geometry.index!.array as Uint16Array | Uint32Array,
}));
}
pick(origin: number[], direction: number[], clip = Infinity) {
pick(origin: number[], direction: number[], clip = Infinity, floor = -Infinity) {
return this.pickSurface(origin,direction,clip,true,floor);
}
/** Camera navigation may select walls; waypoint admission remains ground-only. */
pickSurface(origin: number[], direction: number[], clip = Infinity, groundOnly = false, floor = -Infinity) {
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && (!groundOnly || Math.abs(hit.face?.normal.y ?? 0) > .35))
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
}
ground(x: number, z: number, near: number, clip = Infinity) {
ground(x: number, z: number, near: number, clip = Infinity, floor = -Infinity) {
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
}
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
@@ -1,38 +1,58 @@
import { Application, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
import { Application, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, PRIMITIVE_TRIANGLES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import { URBAN_COLORS, urbanPaths, type UrbanMap } from "../../core/simulation/urbanMap";
import { URBAN_COLORS, urbanPaths, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import { urbanSurface } from "../../core/simulation/urbanSurface";
/** Read-only contours. This layer never enters terrain picking, collision or routing. */
/** Read-only observed surfaces and physical contours; never routing or collision input. */
export class EditorUrbanMapLayer {
private entity: Entity;
private mesh: Mesh;
private material: ShaderMaterial;
private meshes: Mesh[] = [];
private groups = new Map<string,Entity>();
private materials: ShaderMaterial[];
private surfaceLayer = new Layer({ name: "Urban pedestrian coverage" });
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[] = [];
const at=app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1;
app.scene.layers.insert(this.surfaceLayer,at);app.scene.layers.insert(this.layer,at+2);
camera.camera!.layers = [...camera.camera!.layers, this.surfaceLayer.id, this.layer.id];
this.materials=[false,true].map(surface=>{
const material=new ShaderMaterial({ uniqueName: surface?"urban-ground-coverage":"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; uniform float mapFloor;
void main(void) { if(mapHeight>mapClip || mapHeight<mapFloor) discard; gl_FragColor=mapColor; }` });
material.depthTest=false;material.depthWrite=false;
if(surface){material.blendType=BLEND_NORMAL;material.cull=CULLFACE_NONE;}
return material;
});
this.entity = new Entity("Urban infrastructure",app);
const groups = new Map<string, {positions:number[];colors:number[];surface:boolean}>();
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);
const surface=urbanSurface(feature),key=feature.properties.class+(surface?":surface":":line");
if (!groups.has(key)) groups.set(key,{positions:[],colors:[],surface:!!surface});
const group=groups.get(key)!;
if(surface){
for(const i of surface.indices){group.positions.push(...toEditor(surface.positions.slice(i*3,i*3+3)));group.colors.push(...color,48);}
}else for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
group.positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
group.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] });
for (const [key,{positions,colors,surface}] of groups) {
if (!positions.length) continue;
const mesh=new Mesh(app.graphicsDevice);mesh.setPositions(positions);mesh.setColors32(colors);mesh.update(surface?PRIMITIVE_TRIANGLES:PRIMITIVE_LINES);this.meshes.push(mesh);
const entity=new Entity(key,app);entity.addComponent("render",{meshInstances:[new MeshInstance(mesh,this.materials[surface?1:0])],layers:[surface?this.surfaceLayer.id:this.layer.id],castShadows:false,receiveShadows:false});
this.entity.addChild(entity);this.groups.set(key,entity);
}
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
}
setClasses(selected:readonly UrbanClassId[]) {
for (const [key,entity] of this.groups) entity.enabled=selected.includes(key.split(":")[0] as UrbanClassId);
}
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(); }
setClip(height: number, floor = -Infinity) { for(const material of this.materials) { material.setParameter("mapClip",Number.isFinite(height)?height:1e9); material.setParameter("mapFloor",Number.isFinite(floor)?floor:-1e9); } }
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id&&id!==this.surfaceLayer.id);this.app.scene.layers.remove(this.layer);this.app.scene.layers.remove(this.surfaceLayer);this.entity.destroy();for(const mesh of this.meshes)mesh.destroy();for(const material of this.materials)material.destroy(); }
}
@@ -0,0 +1,23 @@
import { useState } from "react";
import { Icon, IconButton, LayerStackIndicator, ProgressButton, ToastStack } from "@nodedc/ui-react";
import type { UrbanMap } from "../../core/simulation/urbanMap";
import { analysisProgressLabel, useInfrastructureAnalysis } from "../../core/simulation/infrastructureAnalysis";
export function InfrastructureAnalysis({worldId,worldSha,busy,hasMap,onMap}:{worldId:string;worldSha:string;busy:boolean;hasMap:boolean;onMap:(map:UrbanMap)=>void}) {
const {job,error,clearError,sending,checking,start,cancel}=useInfrastructureAnalysis(worldId,worldSha,onMap);
const [dismissedFailure,setDismissedFailure]=useState<string|null>(null);
const pending=job?.status==="queued"||job?.status==="running";
const phase=sending?(pending?"Отменяем расчёт":"Запускаем расчёт"):checking?"Проверяем состояние":pending?analysisProgressLabel(job):null;
const recalculate=hasMap||job?.status==="ready";
return <>
{!phase&&!busy?<IconButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} title={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} onClick={()=>void start(recalculate)}><Icon name="layers"/></IconButton>:null}
{phase?<ProgressButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"}
icon={phase?<LayerStackIndicator/>:<Icon name="layers"/>} disabled={busy}
title={pending?"Прогноз уточняется по выполненным этапам. Ожидание Worker и подготовка исходного проекта считаются отдельно.":undefined}
progress={phase?{label:phase,value:pending&&!job.progress?.stale?job.progress?.fraction??undefined:undefined}:undefined}
onClick={()=>void start(recalculate)}/>:null}
{pending&&!job.cancel_requested?<IconButton label="Отменить расчёт инфраструктуры" loading={sending}
onClick={()=>void cancel()}><Icon name="stop"/></IconButton>:null}
{error?<ToastStack items={[{id:"infrastructure",tone:"error",title:"Не удалось выполнить расчёт",description:error}]} onDismiss={clearError}/>:null}
{job?.status==="failed"&&job.error&&dismissedFailure!==job.key?<ToastStack items={[{id:job.key,tone:"error",title:"Расчёт не завершён",description:job.error}]} onDismiss={()=>setDismissedFailure(job.key)}/>:null}
</>;
}
@@ -0,0 +1,22 @@
import {usePlannerPreferences} from "./usePlannerPreferences";
import {useEffect,useState} from "react";
import {Button,Dropdown,Icon,IconButton,NavigationCube} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {useSimulationLayout} from "./useSimulationLayout";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditorRuntime;viewport:HTMLElement;semantic:boolean;disabled:boolean}) {
const [preferences]=usePlannerPreferences();
const [layout,updateLayout]=useSimulationLayout();
const projection=layout.projection;
const [quaternion,setQuaternion]=useState<[number,number,number,number]>([0,0,0,1]);
useEffect(()=>{viewport.style.setProperty("--planner-cube-size",`${preferences.cube.size}px`);return()=>{viewport.style.removeProperty("--planner-cube-size");};},[viewport,preferences.cube.size]);
useEffect(()=>{runtime.watchCamera(setQuaternion);return()=>runtime.watchCamera(null);},[runtime]);
useEffect(()=>{runtime.setProjection(projection);},[runtime,projection]);
return <>
<Dropdown placement="bottom-end" width={220} trigger={({toggle,setTriggerRef,open})=><IconButton ref={setTriggerRef}
label={`Проекция: ${projection==="orthographic"?"ортографическая":"перспективная"}`} title="Выбрать проекцию" disabled={disabled} aria-expanded={open} onClick={toggle}><Icon name={projection}/></IconButton>}>
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}</div>}
</Dropdown>
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
</>;
}
@@ -0,0 +1,10 @@
import {ColorField,ControlRow,RangeControl} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
export function PlannerCubeSettings({value,set}:{value:PlannerPreferences["cube"];set:(key:string,value:string|number)=>void}) {
return <>
<RangeControl label="Размер 3D-куба" min={48} max={160} step={1} value={value.size} onChange={v=>set("size",v)} formatValue={v=>`${v} px`}/>
<RangeControl label="Непрозрачность куба" min={.2} max={1} step={.05} value={value.opacity} onChange={v=>set("opacity",v)} formatValue={v=>`${Math.round(v*100)}%`}/>
<RangeControl label="Прозрачность линий" min={0} max={1} step={.05} value={1-value.edgeOpacity} onChange={v=>set("edgeOpacity",1-v)} formatValue={v=>`${Math.round(v*100)}%`}/>
{([["face","Грани"],["text","Подписи"],["edge","Рёбра"],["hover","Подсветка"],["hoverText","Подписи при наведении"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -1,15 +1,18 @@
import {useSimulationLayout} from "./useSimulationLayout";
import { useEffect, useState } from "react";
import { Icon, IconButton } from "@nodedc/ui-react";
import { Checker, Dropdown, SegmentedButton } 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;
export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilityChange}: {
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;onVisibilityChange:(visible:boolean)=>void;
}) {
const [memory,setMemory]=useState<SpatialExperience|null>(null),[visible,setVisible]=useState(false);
const [memory,setMemory]=useState<SpatialExperience|null>(null);
const [layout,updateLayout]=useSimulationLayout();
const visible=layout.memory,setVisible=(memory:boolean)=>updateLayout({memory});
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
@@ -22,10 +25,23 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport}: {
};
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
},[worldId,worldSha,runtime]);
useEffect(()=>runtime.showExperience(visible),[runtime,visible,memory]);
useEffect(()=>{runtime.showExperience(visible);onVisibilityChange(visible&&!!memory);},[runtime,visible,memory,onVisibilityChange]);
useEffect(()=>()=>onVisibilityChange(false),[onVisibilityChange]);
return <>
<IconButton label={error??(memory?`Память локации · посещено ${memory.visits.length} участков · ${memory.attempts.length} попыток`:"В этой локации ещё нет сохранённого опыта")}
disabled={!memory} aria-pressed={visible} onClick={()=>setVisible(v=>!v)}><Icon name="database"/></IconButton>
<Dropdown placement="bottom-start" width={340} surfaceRole="dialog"
trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton ref={setTriggerRef} aria-label="Память локации" active={visible||open}
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
<div className="ai-polygon__layer-options">
<strong>Память локации</strong>
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
{error?<p role="alert">{error}</p>:memory?<>
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
</div>
</Dropdown>
{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"];
@@ -0,0 +1,21 @@
import { GlassSurface, SegmentedControl } from "@nodedc/ui-react";
import { URBAN_COLORS, URBAN_LABELS, availableUrbanClasses, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
export function PlannerLegend({map,memory,selected,onChange,disabled=false}: {
map:UrbanMap|null;memory:boolean;selected:readonly UrbanClassId[];
onChange:(selected:UrbanClassId[])=>void;disabled?:boolean;
}) {
const classes=map?availableUrbanClasses(map):[];
if(!classes.length&&!memory)return null;
const swatch=(id:string)=><i className="ai-local-editor__legend-swatch" aria-hidden="true"
style={{background:`rgb(${URBAN_COLORS[id].join(",")})`}}/>;
return <div className="ai-local-editor__legend nodedc-scene-controls" inert={disabled}>
{classes.length?<SegmentedControl label="Слои инфраструктуры" selectionMode="multiple"
className="ai-local-editor__legend-controls" value={selected} onChange={onChange}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id],icon:swatch(id)}))}/>:null}
{memory?<GlassSurface padding="sm" materialRim={false} aria-label="Легенда памяти">
<span className="ai-inference-preview__legend">{[["visited","Проехал"],["attempt","Попытка проезда"],["revisited","Позже проехал"]].map(([id,label])=>
<span key={id}>{swatch(id)}{label}</span>)}</span>
</GlassSurface>:null}
</div>;
}
@@ -1,4 +1,4 @@
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
import { Application, BLEND_NORMAL, Color, Entity, Layer, PROJECTION_ORTHOGRAPHIC, StandardMaterial, Vec3 } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
@@ -69,11 +69,14 @@ export class PlannerMarkers {
if(point)this.centroid.setPosition(point.x,point.y,point.z);
return changed;
}
private pixelLength(depth:number,pixels:number) {
return this.camera.camera!.projection===PROJECTION_ORTHOGRAPHIC?2*this.camera.camera!.orthoHeight*pixels/Math.max(1,this.canvas.clientHeight):axisWorldLength(depth,this.canvas.clientHeight,pixels);
}
update(dt: number) {
this.elapsed+=dt;
if(this.centroid?.enabled) {
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
const size=this.pixelLength(depth,this.preferences.navigation.centroidPixels);
this.centroid.setLocalScale(size,size,size);
}
const w=this.preferences.waypoint,p=this.preferences.pivot;
@@ -84,7 +87,7 @@ export class PlannerMarkers {
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
this.pivot.enabled=depth>0;
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
this.axisLength=this.pixelLength(depth,p.pixels);
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
for(const {axis,shaft,cone} of this.arrows) {
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
@@ -1,9 +1,11 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import {PlannerCubeSettings} from "./PlannerCubeSettings";
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation"|"toolbar"|"cube">("pivot");
const [saved,update] = usePlannerPreferences();
const [value,setValue] = useState(saved);
const [rect,setRect] = useState(()=>{
@@ -38,13 +40,13 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
window.removeEventListener("keydown",escape);
};
},[onClose]);
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
const set = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, next: string|number|boolean) => {
const base=pending.current??value;
const changed={...base,[group]:{...base[group],[key]:next}};
pending.current=changed;setValue(changed);
if(!editing.current)commit();
};
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
const range = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, label: string, min: number, max: number, step: number, unit: string) =>
<RangeControl key={key} label={label} min={min} max={max} step={step}
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
@@ -59,8 +61,8 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
}}>
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
{section === "pivot" ? <>
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"},{value:"toolbar",label:"Тулбар"},{value:"cube",label:"3D-куб"}]}/>
{section === "cube" ? <PlannerCubeSettings value={value.cube} set={(key,v)=>set("cube",key,v)}/> : section === "toolbar" ? <PlannerToolbarSettings value={value.toolbar} set={(key,v)=>set("toolbar",key,v)}/> : section === "pivot" ? <>
{range("pivot","pixels","Размер осей",50,220,5,"px")}
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
{range("pivot","cone","Размер конусов",10,40,1,"px")}
@@ -0,0 +1,16 @@
import {Checker,ColorField,ControlRow,RangeControl,Select} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
type Settings=PlannerPreferences["toolbar"];
export function PlannerToolbarSettings({value,set}:{value:Settings;set:(key:string,value:string|number|boolean)=>void}) {
const range=(key:keyof Settings,label:string,min:number,max:number,step:number,unit:string)=><RangeControl label={label} value={Number(value[key])} min={min} max={max} step={step} onChange={v=>set(key,v)} formatValue={v=>`${unit==="с"?v/1000:v} ${unit}`}/>;
return <>
<Select label="Положение тулбара" value={value.placement} options={[{value:"left",label:"Слева"},{value:"right",label:"Справа"},{value:"top",label:"Сверху"},{value:"bottom",label:"Снизу"}]} onChange={v=>set("placement",v)}/>
{range("minSize","Минимальный размер",18,42,1,"px")}
{range("maxSize","Максимальный размер",value.minSize,88,1,"px")}
{range("lensCount","Линза",1,13,2,"иконок")}
{range("gap","Расстояние между кнопками",0,24,1,"px")}
<Checker label="Автоскрытие" checked={value.autoHide} onChange={v=>set("autoHide",v)}/>
{value.autoHide?range("hideDelay","Задержка скрытия",0,15000,250,"с"):null}
{([["background","Фон"],["border","Рамка"],["outline","Подсветка"],["accent","Цвет инструментов"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -0,0 +1,57 @@
import {useEffect,useState} from "react";
import {createPortal} from "react-dom";
import {semanticPaths,semanticMembers,isRigidMarking} from "../../core/simulation/semanticEdits";
import {curveControlScale,curveControlPoint} from "../../core/simulation/semanticCurveControls";
import {editablePaths,knots} from "../../core/simulation/semanticVector";
import {URBAN_COLORS} from "../../core/simulation/urbanMap";
import {useSemanticGestures} from "./useSemanticGestures";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export type {SemanticChoice} from "./semanticEditorTypes";
export function SemanticEditOverlay(props:SemanticOverlayProps) {
const {runtime,viewport,map,original,layers,selected}=props;
const [,redraw]=useState(0);
const {hover,ghostMap,marquee,brush}=useSemanticGestures(props);
useEffect(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
const rect=viewport.querySelector("canvas")?.getBoundingClientRect();if(!rect)return null;
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*rect.width,q[1]*rect.height]:null;};
const line=(path:number[][])=>{const p=path.map(project);return p.map((v,i)=>v?`${i&&p[i-1]?"L":"M"}${v[0]},${v[1]}`:"").join(" ");};
const selectedIds=new Set([...(selected?[selected.feature_id]:[]),...props.selection.map(v=>v.feature_id)]);
const chosen=[...new Set([...selectedIds].flatMap(id=>semanticMembers(map,id)))],highlight=hover?semanticMembers(map,hover):[];
const point=semanticAnchor(props),g=point?runtime.semanticGizmo(point):null,base=point?project(point):null;
const featureColor=(id:string)=>`rgb(${(URBAN_COLORS[id]??URBAN_COLORS.road_boundary).join(",")})`;
const color=featureColor(chosen[0]?.properties.class??layers.at(-1)??"road_boundary");
const visible=map.features.filter(f=>layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
const node=selected&&!selected.object&&chosen[0]&&!isRigidMarking(chosen[0])?knots(chosen[0],selected.path)[selected.index]:null;
const handleScale=node?curveControlScale(knots(chosen[0],selected!.path),selected!.index,chosen[0].geometry.type==="Polygon",project):1;
return createPortal(<svg className="ai-local-editor__markers" width="100%" height="100%" aria-label="Редактор контуров">
{original?.features.filter(f=>f.properties.review_status!=="rejected").flatMap(f=>semanticPaths(f).map((r,i)=><path key={`${f.id}-${i}`} d={line(r)} fill="none" stroke={`rgb(${URBAN_COLORS[f.properties.class]?.join(",")??"255,255,255"})`} strokeWidth={1.5} strokeDasharray="5 5" opacity={.65}/>))}
{visible.map(f=><g key={f.id} data-semantic-feature={f.id}>
{semanticPaths(f).map((r,i)=><g key={i}>
{chosen.includes(f)||highlight.includes(f)?<><path d={line(r)} fill="none" stroke="var(--nodedc-glass-panel-bg)" strokeWidth={6}/><path d={line(r)} fill="none" stroke={highlight.includes(f)?"var(--nodedc-text-primary)":featureColor(f.properties.class)} strokeWidth={3}/></>:null}
</g>)}
{props.editing&&!isRigidMarking(f)&&chosen.includes(f)?editablePaths(f).flatMap((r,i)=>r.slice(0,r.length-Number(f.geometry.type==="Polygon")).map((v,k)=>{const p=project(v);const active=props.selection.some(s=>!s.object&&s.feature_id===f.id&&s.path===i&&s.index===k);return p?<circle key={`${i}-${k}`} data-semantic-vertex={`${f.id}:${i}:${k}`} cx={p[0]} cy={p[1]} r={active?5:3} fill={active?"var(--nodedc-text-primary)":featureColor(f.properties.class)} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={1.5}/>:null;})):null}
</g>)}
{ghostMap?.features.map(f=><path key={f.id} d={semanticPaths(f).map(line).join(" ")} fill={color} fillRule="evenodd" fillOpacity={.4} stroke={color} strokeWidth={2}/>)}
{brush.length?<><path d={line(brush)} fill="none" stroke={color} strokeWidth={2}/>{brush.map((v,i)=>{const p=project(v);return p?<circle key={i} cx={p[0]} cy={p[1]} r={i?3:6} fill={color}/>:null;})}</>:null}
{marquee?<rect x={Math.min(marquee[0],marquee[2])} y={Math.min(marquee[1],marquee[3])} width={Math.abs(marquee[2]-marquee[0])} height={Math.abs(marquee[3]-marquee[1])} fill="var(--nodedc-text-primary)" fillOpacity={.1} stroke="var(--nodedc-text-primary)" strokeDasharray="4 3"/>:null}
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
</g>;
})}
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
</g>:null}
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
if(!a||!b||!node[key].some(Boolean))return null;
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
}):null}
</svg>,viewport);
}
@@ -0,0 +1,147 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
import type {AiEditorRuntime} from "./AiEditorRuntime";
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
import {SemanticTools} from "./SemanticTools";
import type {SemanticTool} from "./semanticEditorTypes";
import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVector";
export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,source,headerHost}:{
headerHost:HTMLElement|null;worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;active:boolean;busy:boolean;source:UrbanMap;
}) {
const [revision,setRevision]=useState<SemanticRevision|null>(null);
const [draft,setDraft]=useState<SemanticDraft|null>(null);
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
const [loading,setLoading]=useState(true);
const [editing,setEditing]=useState(true);
const [layout,updateLayout]=useSimulationLayout();
const visible=layout.visible,setVisible=(v:typeof visible|((prior:typeof visible)=>typeof visible))=>updateLayout({visible:typeof v==="function"?v(visible):v});
const [selection,setSelection]=useState<Vertex[]>([]),[wholeContour,setWholeContour]=useState(false);
const selectVertices=(vertices:Vertex[],whole=false)=>{setSelection(vertices);setWholeContour(whole);};
const axis=layout.axis,setAxis=(axis:SemanticAxis)=>updateLayout({axis});
const areaMode=layout.areaMode,setAreaMode=(areaMode:typeof layout.areaMode)=>updateLayout({areaMode});
const layers=layout.layers,setLayers=(layers:UrbanClassId[])=>updateLayout({layers});
const selected=selection[0]??null;
const setSelected=(v:Vertex|null)=>selectVertices(v?[v]:[]);
const [choices,setChoices]=useState<SemanticChoice[]>([]);
const [tool,setTool]=useState<SemanticTool>("select");
const [template,setTemplate]=useState<string|null>(null);
const [preview,setPreview]=useState<SemanticOperation|null>(null);
const attempt=useRef<{key:string;signature:string}|null>(null);
const current=useRef({draft,revision});current.current={draft,revision};
const accept=(value:SemanticRevision)=>{
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
};
useEffect(()=>{
if(!active||revision)return;
const abort=new AbortController();
setLoading(true);setError(null);
void semanticRequest(worldId,undefined,abort.signal).then(accept)
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
return()=>abort.abort();
},[active,worldId,worldSha,revision]);
useEffect(()=>{if(active){setEditing(true);}},[active]);
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
const operate=(op:SemanticOperation)=>{
if(busy||saving)return;
try{const prior=current.current.draft!,next=commitSemantic(prior,op);setDraft(next);setError(null);
if(op.kind==="duplicate_vertex"&&next!==prior)setSelected({feature_id:op.feature_id,path:op.path,index:duplicateIndex(op.index,prior.map.features.find(f=>f.id===op.feature_id)!.geometry.type==="Polygon",op.side)});
if(op.kind==="duplicate_marking"&&next!==prior)setSelected({feature_id:op.new_feature_id,path:0,index:0,object:true});
if(op.kind==="insert")setSelected({...op,index:op.index+1});
}
catch(e){setError((e as Error).message);}
};
const removeSelected=()=>{
if(!selected||!draft)return;
const f=draft.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
operate(isRigidMarking(f)||selected.object?{kind:"remove",feature_id:f.id}:{kind:"delete_vertices",vertices:selection});setSelected(null);
};
const display=draft?.map??source;
let overlay=display;
if(preview)try{overlay=semanticOperation(display,preview);}catch{/* Retain the last valid preview. */}
useEffect(()=>{
if(!active)return;
const hidden=editing&&selected&&preview?.kind!=="duplicate_marking"?semanticMembers(display,selected.feature_id):[];
const rendered=hidden.length?{...display,features:display.features.filter(f=>!hidden.includes(f))}:display;
runtime.setUrbanMap(rendered);runtime.setUrbanClasses(layers);runtime.showUrbanMap(visible.user);
},[runtime,active,display,editing,selected?.feature_id,visible.user,preview?.kind,layers]);
useEffect(()=>{
if(!active)return;
runtime.setAddMode(false);
const keyboard=(e:KeyboardEvent)=>{
if(!editing||busy||saving||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||document.querySelector('[data-dropdown-lineage]'))return;
if((e.metaKey||e.ctrlKey)&&e.code==="KeyZ"){
e.preventDefault();e.stopImmediatePropagation();setPreview(null);
setDraft(s=>s?(e.shiftKey?redoSemantic(s):undoSemantic(s)):s);setSelected(null);
}else if(!e.ctrlKey&&!e.metaKey&&["KeyV","KeyA","KeyP","KeyR"].includes(e.code)) {
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id)),area=layers.some(id=>["pedestrian_area","sidewalk"].includes(id));
if((e.code==="KeyA"&&!contours&&!selection.some(v=>{const f=display.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);}))||(["KeyP","KeyR"].includes(e.code)&&!area))return;
e.preventDefault();e.stopImmediatePropagation();setTemplate(null);setTool(e.code==="KeyV"?"select":e.code==="KeyA"?"insert":e.code==="KeyP"?"pen":"rectangle");
}else if((e.key==="Delete"||e.key==="Backspace")&&selected){
e.preventDefault();e.stopImmediatePropagation();removeSelected();
}
};
document.addEventListener("keydown",keyboard,true);
return()=>document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
useEffect(()=>{
if(!draft?.operations.length)return;
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
},[draft?.operations.length]);
const save=async()=>{
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
const signature=JSON.stringify(body);
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
setSaving(true);setError(null);
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
catch(e){setError((e as Error).message);}
finally{setSaving(false);}
};
if(!active)return null;
const classes=availableUrbanClasses(display);
if(!classes.includes("road_marking"))classes.push("road_marking");
const overlaySelection=preview?.kind==="duplicate_marking"&&overlay!==display?[{feature_id:preview.new_feature_id,path:0,index:0,object:true as const}]:preview?.kind==="duplicate_vertex"&&overlay!==display?[{feature_id:preview.feature_id,path:preview.path,index:duplicateIndex(preview.index,display.features.find(f=>f.id===preview.feature_id)!.geometry.type==="Polygon",preview.side)}]:selection;
const marking=layers.some(id=>["road_marking","crosswalk_marking"].includes(id));
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id));
const chooseTool=(next:SemanticTool)=>{setTool(next);setTemplate(null);setPreview(null);};
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
const controls=<>
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
</>;
return <>
{headerHost?createPortal(controls,headerHost):null}
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
</div>,viewport)}
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
axis={axis} areaMode={areaMode} onSelect={setSelected} onSelection={selectVertices} onChoose={setChoices} onOperation={operate} onPreview={setPreview} onError={setError}
onExit={()=>{setEditing(false);setSelected(null);chooseTool("select");}}/>
<Window open={choices.length>0} onClose={()=>setChoices([])} title="Выберите контур">
{choices.map(({vertex,selection,wholeContour,operation},index)=><Button key={vertex.feature_id} onClick={()=>{selectVertices(selection,wholeContour);if(operation)operate(operation);setChoices([]);}}>{URBAN_LABELS[display.features.find(f=>f.id===vertex.feature_id)?.properties.class as UrbanClassId]} · {index+1}</Button>)}
</Window>
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
</>;
}
@@ -0,0 +1,47 @@
import {Button,Checker,Toolbar,type ToolbarItem} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {MARKING_TEMPLATES,isEditableMarking,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {UrbanMap} from "../../core/simulation/urbanMap";
import type {SemanticTool} from "./semanticEditorTypes";
import {usePlannerPreferences} from "./usePlannerPreferences";
export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:SemanticTool;setTool:(v:SemanticTool)=>void;marking:boolean;contours:boolean;area:boolean;template:string|null;setTemplate:(v:string)=>void;
selection:Vertex[];map:UrbanMap;operate:(op:SemanticOperation)=>void;remove:()=>void;undo:()=>void;redo:()=>void;canUndo:boolean;canRedo:boolean;axis:SemanticAxis;setAxis:(v:SemanticAxis)=>void;
visible:{model:boolean;user:boolean};setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
const [prefs,update]=usePlannerPreferences();
const items:ToolbarItem[]=[{id:"hold",label:prefs.toolbar.autoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!prefs.toolbar.autoHide,onSelect:()=>{try{update({...prefs,toolbar:{...prefs.toolbar,autoHide:!prefs.toolbar.autoHide}});}catch{p.onError("Не удалось сохранить закрепление тулбара.");}}}];
const editableMarking=p.selection.some(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);});
const menu=(children:React.ReactNode)=><div className="semantic-tools__menu">{children}</div>;
if(p.editing){
items.push({id:"select",label:"Выделение",shortcut:"V",icon:"select",active:p.tool==="select"&&!p.template,onSelect:()=>p.setTool("select")});
if(p.contours||editableMarking)items.push({id:"insert",label:"Добавить точку на контур",shortcut:"A",icon:"add-point",active:p.tool==="insert",onSelect:()=>p.setTool("insert")});
if(p.area){
items.push({id:"pen",label:"Перо: замкните контур или Enter",shortcut:"P",icon:"pen",active:p.tool==="pen",onSelect:()=>p.setTool("pen")},
{id:"rectangle",label:"Прямоугольник: два противоположных угла",shortcut:"R",icon:"rectangle",active:p.tool==="rectangle",onSelect:()=>p.setTool("rectangle")},
{id:"area-mode",label:"Действие области",icon:p.areaMode==="union"?"plus":"trash",onSelect:()=>{},menu:close=>menu(([['union','Заполнить область'],['difference','Вырезать область']] as const).map(([id,label])=><Button key={id} width="full" variant={p.areaMode===id?"primary":"secondary"} tone="neutral" aria-pressed={p.areaMode===id} onClick={()=>{p.setAreaMode(id);close();}}>{label}</Button>))});
}
items.push({id:"axes",label:`Оси перемещения: ${p.axis.toUpperCase()}`,icon:"target",onSelect:()=>{},menu:close=>menu((["x","y","z","xy","xz","yz"] as const).map(axis=><Button key={axis} width="full" variant={p.axis===axis?"primary":"secondary"} tone="neutral" aria-pressed={p.axis===axis} onClick={()=>{p.setAxis(axis);close();}}>{axis.toUpperCase()}</Button>))});
if(p.selection.length===1&&!p.selection[0].object){
const v=p.selection[0],f=p.map.features.find(f=>f.id===v.feature_id),nodes=f?knots(f,v.path):[],n=nodes[v.index];
const curved=!!n&&[...n.incoming,...n.outgoing].some(Boolean);
if(n)items.push({id:"properties",label:"Свойства точки",icon:"curve",onSelect:()=>{},menu:close=>menu(<>
<Button width="full" variant={!curved?"primary":"secondary"} tone="neutral" aria-pressed={!curved} onClick={()=>{p.operate({...v,kind:"curve",incoming:[0,0],outgoing:[0,0]});close();}}>Угловая точка</Button>
<Button width="full" variant={curved?"primary":"secondary"} tone="neutral" aria-pressed={curved} onClick={()=>{
const closed=f!.geometry.type==="Polygon",prev=nodes[v.index-1]??(closed?nodes.at(-1)!:n),next=nodes[v.index+1]??(closed?nodes[0]:n);
const tangent=next.point.slice(0,2).map((a,k)=>a-prev.point[k]),length=Math.hypot(...tangent)||1;
const before=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-prev.point[k]))/3,after=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-next.point[k]))/3;
p.operate({...v,kind:"curve",incoming:tangent.map(x=>-x/length*before),outgoing:tangent.map(x=>x/length*after)});close();
}}>Кривая с ручками</Button>
</>)});
}
if(p.selection.length)items.push({id:"delete",label:"Удалить выделенное",shortcut:"Delete",icon:"trash",onSelect:p.remove});
if(p.canUndo)items.push({id:"undo",label:"Отменить",shortcut:"Control+Z Meta+Z",icon:"undo",onSelect:p.undo});
if(p.canRedo)items.push({id:"redo",label:"Повторить",shortcut:"Control+Shift+Z Meta+Shift+Z",icon:"redo",onSelect:p.redo});
}
items.push({id:"visibility",label:"Видимость разметки",icon:"eye",onSelect:()=>{},menu:menu(<>
<Checker label="Алгоритмическая разметка" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
}
@@ -27,7 +27,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
return <div className="ai-polygon__observation">
<div className="ai-polygon__observation-toolbar">
<div className="ai-polygon__observation-toolbar nodedc-viewport-controls">
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
@@ -3,26 +3,30 @@ import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
export function SimulationViewTools({expanded,toggle,semantic=false,planning=false,routeEditing=planning,boundsRef,children}: {expanded:boolean;toggle:()=>void;semantic?:boolean;planning?:boolean;routeEditing?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
const [prefs,update]=usePlannerPreferences();
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
return <>
<div className="ai-simulation__view-tools nodedc-scene-controls">
{children}
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
<div className={`ai-simulation__view-tools nodedc-scene-controls ${planning?"ai-simulation__view-tools--planning":""}`}>
{!planning?children:null}
<div className="ai-simulation__display-tools">
{!semantic?<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>:null}
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
{planning?<IconButton label="Настройки сцены" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
</div>
{planning?children:null}
</div>
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
@@ -258,7 +258,7 @@ export function SimulationViewport({
</StatusBadge>
<span>Engine 2.21.4</span>
</div>
<div className="simulation-viewport__controls">
<div className="simulation-viewport__controls nodedc-viewport-controls">
<Select
label="Качество Gaussian-сцены"
value={quality}
@@ -13,7 +13,7 @@ export function localScene(cache: EditorCache): SimulationWorldManifest {
return {
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
collision: { meshUrl: saved ? saved.collision_url : editorAssetUrl(cache.key,"collision.glb"), available: saved ? !!saved.collision_url : true },
transforms: { worldFromVisual: Array.from(visual.data),
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
};
@@ -0,0 +1,20 @@
import type {UrbanClassId,UrbanMap} from "../../core/simulation/urbanMap";
import {isRigidMarking,semanticMembers,semanticPivot,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export type SemanticTool="select"|"insert"|"pen"|"rectangle";
export type SemanticChoice={vertex:Vertex;selection:Vertex[];wholeContour?:boolean;operation?:SemanticOperation};
export interface SemanticOverlayProps {
runtime:AiEditorRuntime;viewport:HTMLElement;map:UrbanMap;original:UrbanMap|null;layers:readonly UrbanClassId[];
selected:Vertex|null;selection:Vertex[];wholeContour?:boolean;editing:boolean;blocked:boolean;tool:SemanticTool;template:string|null;
axis:SemanticAxis;areaMode:"union"|"difference";
onSelect:(v:Vertex|null)=>void;onSelection:(v:Vertex[],wholeContour?:boolean)=>void;onChoose:(v:SemanticChoice[])=>void;
onPlaced:()=>void;onOperation:(op:SemanticOperation)=>void;onPreview:(op:SemanticOperation|null)=>void;
onError:(message:string)=>void;onExit:()=>void;
}
export function semanticAnchor(p:SemanticOverlayProps) {
const members=p.selected?semanticMembers(p.map,p.selected.feature_id):[];if(!members.length)return null;
if(isRigidMarking(members[0])||p.selected?.object)return semanticPivot(members);
const points=p.selection.flatMap(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);const q=f?knots(f,v.path)[v.index]?.point:null;return q?[q]:[];});
return points.length?[0,1,2].map(k=>points.reduce((n,q)=>n+q[k],0)/points.length):null;
}
@@ -0,0 +1,170 @@
import {curveControlScale,moveCurveControl} from "../../core/simulation/semanticCurveControls";
import {useEffect,useRef,useState} from "react";
import {isMarking,isRigidMarking,semanticOperation,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {semanticHits,semanticHitSelection} from "../../core/simulation/semanticPicking";
import {duplicateSide,editablePaths,knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import {regionOperation} from "../../core/simulation/semanticArea";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export function useSemanticGestures(props:SemanticOverlayProps) {
const latest=useRef(props);latest.current=props;
const [hover,setHover]=useState<string|null>(null),[ghost,setGhost]=useState<SemanticOperation|null>(null);
const [marquee,setMarquee]=useState<number[]|null>(null),[brush,setBrush]=useState<number[][]>([]);
useEffect(()=>{
const {runtime,viewport}=props,canvas=viewport.querySelector("canvas")!;
let generation=0,disposed=false,picking=false,pending:number[]|null=null,placing=false;
let shape:number[][]=[],rectangle:number[]|null=null,orbit:number|null=null;
let box:{id:number;start:number[];shift:boolean}|null=null;
let drag:{id:number;point:number[];start:number[];screen:number[];axis:SemanticAxis|"rotate";op:SemanticOperation|null;selected:Vertex;selection:Vertex[];map:SemanticOverlayProps["map"];handle?:"incoming"|"outgoing";handleScale?:number;handleStart?:number[];duplicate?:Vertex;copy?:{feature_id:string;new_feature_id:string}}|null=null;
const stop=(e:Event)=>{e.preventDefault();e.stopImmediatePropagation();};
const screen=(e:PointerEvent)=>{const r=canvas.getBoundingClientRect();return [e.clientX-r.left,e.clientY-r.top];};
const norm=(e:PointerEvent)=>{const xy=screen(e);return [xy[0]/canvas.clientWidth,xy[1]/canvas.clientHeight];};
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*canvas.clientWidth,q[1]*canvas.clientHeight]:null;};
const hits=(e:PointerEvent)=>semanticHits(latest.current.map,latest.current.layers,screen(e),project,latest.current.tool==="select",latest.current.selection.map(v=>v.feature_id));
const focus=()=>canvas.focus({preventScroll:true});
const place=(position:number[],id:string):Extract<SemanticOperation,{kind:"place"}>=>({kind:"place",feature_id:id,template_id:latest.current.template!,position,surface:"gaussian-visual"});
const pick=async()=>{
if(picking||!pending)return;const xy=pending;pending=null;picking=true;const version=generation;
try{const point=await runtime.pickSemanticSurface(xy[0],xy[1]);
if(!disposed&&version===generation&&latest.current.template)setGhost(point?place(point,"user-preview-placement"):null);
}catch{if(!disposed)setGhost(null);}finally{picking=false;if(pending&&!disposed)void pick();}
};
const release=(id:number)=>{if(viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);};
const finish=(cancel:boolean)=>{
const d=drag;drag=null;latest.current.onPreview(null);
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
runtime.setNavigation(!latest.current.blocked);
};
const commitShape=(points:number[][])=>{
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
p.onOperation(regionOperation(f,[...points,points[0]],p.areaMode));
}catch(e){latest.current.onError((e as Error).message);}
shape=[];rectangle=null;setBrush([]);
};
const beginDrag=(e:PointerEvent,p:SemanticOverlayProps,selected:Vertex,selection:Vertex[],activeAxis:SemanticAxis|"rotate",handle?:"incoming"|"outgoing")=>{
const f=p.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
const copy=e.shiftKey&&!handle&&activeAxis!=="rotate"&&isMarking(f)&&(isRigidMarking(f)||selected.object);
const duplicate=e.shiftKey&&!handle&&activeAxis!=="rotate"&&!copy&&!isRigidMarking(f);
if(duplicate&&selection.length!==1){stop(e);p.onError("Для продолжения сплайна выберите одну точку.");return;}
const point=semanticAnchor({...p,selected,selection});if(!point)return;
const [x,y]=norm(e),start=runtime.moveSemantic(point,x,y,activeAxis==="rotate"?"xy":activeAxis);if(!start)return;
stop(e);focus();drag={id:e.pointerId,point,start,screen:screen(e),axis:activeAxis,op:null,selected,selection,map:p.map,handle,
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
};
const down=(e:PointerEvent)=>{
const p=latest.current;if(!p.editing||p.blocked)return;
const target=e.target as Element,[x,y]=norm(e);
if(e.ctrlKey&&[0,2].includes(e.button)&&(target===canvas||target.closest("[data-semantic-axis],[data-semantic-handle]"))){
if(drag||box)return;
generation++;pending=null;setGhost(null);setHover(null);orbit=e.pointerId;
e.preventDefault();return; // Bubble to EditorCamera; never edit during this gesture.
}
if(e.button!==0)return;
const axis=target.closest<SVGElement>("[data-semantic-axis]")?.dataset.semanticAxis as SemanticAxis|"rotate"|undefined;
const handle=target.closest<SVGElement>("[data-semantic-handle]")?.dataset.semanticHandle as "incoming"|"outgoing"|undefined;
if((axis||handle)&&p.selected){
beginDrag(e,p,p.selected,p.selection,handle?"xy":axis!,handle);return;
}
if(e.target!==canvas)return;stop(e);focus();
if(p.template){
if(placing)return;placing=true;generation++;pending=null;const version=generation;
void runtime.pickSemanticSurface(x,y).then(point=>{
if(!disposed&&version===generation&&point){const op=place(point,`user-${crypto.randomUUID()}`);p.onOperation(op);p.onSelect({feature_id:op.feature_id,path:0,index:0,object:true});p.onPlaced();setGhost(null);}
}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
if(p.tool==="pen"||p.tool==="rectangle"){
if(shape.length>=128){p.onError("Замкните область: не более 128 точек за один контур.");return;}
const first=shape[0]?project(shape[0]):null;
if(p.tool==="pen"&&shape.length>=3&&first&&Math.hypot(screen(e)[0]-first[0],screen(e)[1]-first[1])<12){commitShape(shape);return;}
const version=generation;
if(p.tool==="rectangle"&&rectangle){const q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)commitShape([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]]]);return;}
if(placing)return;placing=true;
void runtime.pickSemanticSurface(x,y).then(point=>{if(!disposed&&version===generation&&point){
if(p.tool==="rectangle")rectangle=point;shape=[...shape,point];setBrush(shape);
}}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
const options=hits(e);
if(!options.length){box={id:e.pointerId,start:screen(e),shift:e.shiftKey};viewport.setPointerCapture(e.pointerId);return;}
const best=options[0],near=options.filter(c=>!!c.point===!!best.point&&c.distance<=best.distance+2);
const ids=[...new Set(near.map(c=>c.vertex.feature_id))];
const choice=(h:typeof best)=>{
const s=h.segment,t=s?s.start+(s.end-s.start)*runtime.semanticSegmentParameter(s.a,s.b,s.t):h.t;
const selection=p.tool==="select"?semanticHitSelection(p.map,h):[h.vertex],vertex=selection[0];
return {vertex,selection,wholeContour:p.tool==="select"&&!h.point&&!vertex.object,operation:p.tool==="insert"&&t>0&&t<1?{...h.vertex,kind:"insert" as const,t}:undefined};
};
if(ids.length>1){p.onChoose(ids.map(id=>choice(near.find(c=>c.vertex.feature_id===id)!)));return;}
const picked=choice(best),vertex=picked.vertex;
if(p.tool==="select"&&!best.point&&!vertex.object){
const selection=e.shiftKey?[...p.selection.filter(v=>!v.object),...picked.selection]:picked.selection;
p.onSelection([...new Map(selection.map(v=>[JSON.stringify(v),v])).values()],!e.shiftKey);
}else if(e.shiftKey&&p.tool==="select"&&!vertex.object){
const previous=p.selection.filter(v=>!v.object),exists=previous.some(v=>JSON.stringify(v)===JSON.stringify(vertex));p.onSelection(exists?previous.filter(v=>JSON.stringify(v)!==JSON.stringify(vertex)):[...previous,vertex]);
}else if(p.tool==="select"&&best.point){
const selected=!p.wholeContour&&p.selection.some(v=>!v.object&&v.feature_id===vertex.feature_id&&v.path===vertex.path&&v.index===vertex.index)?p.selection:[vertex];
p.onSelection(selected);beginDrag(e,p,vertex,selected,p.axis);
}else p.onSelect(vertex);
if(p.tool==="insert"&&choice(best).operation)p.onOperation(choice(best).operation!);
};
const move=(e:PointerEvent)=>{
if(orbit===e.pointerId)return;
const p=latest.current;
if(box&&e.pointerId===box.id){stop(e);setMarquee([...box.start,...screen(e)]);return;}
if(!drag){
if(!p.editing||p.blocked||e.target!==canvas){setHover(null);return;}
if(rectangle){const [x,y]=norm(e),q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)setBrush([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]],rectangle]);return;}
if(p.template){pending=norm(e);void pick();}else setHover(hits(e)[0]?.vertex.feature_id??null);return;
}
if(e.pointerId!==drag.id)return;if(p.blocked){finish(true);return;}stop(e);
if(Math.hypot(...screen(e).map((v,k)=>v-drag!.screen[k]))<2){drag.op=null;p.onPreview(null);return;}
const [x,y]=norm(e),q=runtime.moveSemantic(drag.point,x,y,drag.axis==="rotate"?"xy":drag.axis);if(!q)return;
const selected=drag.selected,selection=drag.selection,map=drag.map;
if(drag.handle){const f=map.features.find(f=>f.id===selected.feature_id)!;const node=knots(f,selected.path)[selected.index];
const value=moveCurveControl(drag.handleStart!,drag.start,q,drag.handleScale!);
drag.op={kind:"curve",...selected,incoming:drag.handle==="incoming"?value:node.incoming,outgoing:drag.handle==="outgoing"?value:node.outgoing};
}else if(drag.axis==="rotate"){
const angle=Math.atan2(q[1]-drag.point[1],q[0]-drag.point[0])-Math.atan2(drag.start[1]-drag.point[1],drag.start[0]-drag.point[0]);
drag.op={kind:"transform",feature_id:selected.feature_id,delta:[0,0],angle};
}else {
const delta=q.map((v,k)=>drag!.axis.includes("xyz"[k])?v-drag!.start[k]:0);
drag.op=drag.copy?{kind:"duplicate_marking",...drag.copy,axis:drag.axis,delta}:drag.duplicate?{kind:"duplicate_vertex",...drag.duplicate,axis:drag.axis,delta,
side:duplicateSide(knots(map.features.find(f=>f.id===drag!.duplicate!.feature_id)!,drag.duplicate.path),drag.duplicate.index,map.features.find(f=>f.id===drag!.duplicate!.feature_id)!.geometry.type==="Polygon",delta)}:
{kind:!selected.object?"translate_vertices":"translate",feature_id:selected.feature_id,vertices:selection.filter(v=>!v.object),axis:drag.axis,delta};
}
p.onPreview(drag.op);
};
const up=(e:PointerEvent)=>{
if(orbit===e.pointerId){orbit=null;return;}
if(box&&box.id===e.pointerId){stop(e);const p=latest.current,end=screen(e),start=box.start;
const selected:Vertex[]=box.shift?p.selection.filter(v=>!v.object):[];
if(Math.hypot(end[0]-start[0],end[1]-start[1])>3)for(const f of p.map.features){
if(!p.layers.includes(f.properties.class as typeof p.layers[number])||f.properties.review_status==="rejected"||isRigidMarking(f))continue;
editablePaths(f).forEach((path,j)=>path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((v,i)=>{
const q=project(v);if(q&&q.every((v,k)=>v>=Math.min(start[k],end[k])&&v<=Math.max(start[k],end[k])))selected.push({feature_id:f.id,path:j,index:i});
}));
}
p.onSelection([...new Map(selected.map(v=>[JSON.stringify(v),v])).values()]);finish(true);
}else if(drag&&e.pointerId===drag.id){stop(e);finish(false);}
};
const cancel=()=>{orbit=null;generation++;pending=null;finish(true);shape=[];rectangle=null;setBrush([]);setGhost(null);};
const key=(e:KeyboardEvent)=>{
const p=latest.current;if(!p.editing||p.blocked||e.defaultPrevented)return;
if(e.key==="Escape"){
// Dropdown gets the first Escape. Editor owns placement even after focus left canvas.
if(document.querySelector('[data-dropdown-lineage]'))return;
stop(e);
if(drag||box||shape.length||p.template||p.tool!=="select"){cancel();p.onPlaced();}
else if(p.selection.length)p.onSelection([]);else p.onExit();
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
};
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
window.addEventListener("blur",cancel);
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
return {hover,ghostMap,marquee,brush};
}
@@ -6,7 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
if (view.current.querySelector('[role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
if (view.current.querySelector('[data-semantic-editing="true"], [role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
event.preventDefault();
event.stopPropagation();
void document.exitFullscreen().catch(() => undefined);
@@ -0,0 +1,22 @@
import {useSyncExternalStore} from "react";
import {normalizeSimulationLayout,normalizeSceneView,type SimulationLayout,type SceneView} from "../../core/simulation/simulationLayout";
const KEY="missioncore.simulation-layout/v1",SCENES="missioncore.simulation-cameras/v1";
const listeners=new Set<()=>void>();
function read(key:string){try{return JSON.parse(localStorage.getItem(key)??"null");}catch{return null;}}
let current=normalizeSimulationLayout(read(KEY));
export const getSimulationLayout=()=>current;
export function updateSimulationLayout(patch:Partial<SimulationLayout>){
const next=normalizeSimulationLayout({...current,...patch});
// UI choices stay usable in private/blocked storage; no edits or observations are stored here.
try{localStorage.setItem(KEY,JSON.stringify(next));}catch{/* Session-only fallback. */}
current=next;listeners.forEach(fn=>fn());
}
window.addEventListener("storage",e=>{if(e.key!==KEY&&e.key!==null)return;current=normalizeSimulationLayout(read(KEY));listeners.forEach(fn=>fn());});
export function useSimulationLayout(){return [useSyncExternalStore(fn=>{listeners.add(fn);return()=>{listeners.delete(fn);};},getSimulationLayout),updateSimulationLayout] as const;}
export function readSceneView(key:string){return normalizeSceneView(read(SCENES)?.[key]);}
export function writeSceneView(key:string,value:SceneView){
const valid=normalizeSceneView(value);if(!valid)return;
const old=read(SCENES),entries=old&&typeof old==="object"?Object.entries(old):[];
const next=Object.fromEntries([...entries.filter(([k,v])=>k!==key&&normalizeSceneView(v)).slice(-15),[key,valid]]);
try{localStorage.setItem(SCENES,JSON.stringify(next));}catch{/* Keep the live scene usable. */}
}
@@ -1,6 +1,6 @@
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
export interface EditorCache {
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
local_scene?: { visual_url: string; collision_url: string | null; visual_rotation: number[]; collision_rotation: number[] };
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
error: string | null;
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
@@ -31,6 +31,7 @@ export interface AiSource {
description?: string;
}
export interface AiWorld extends AiSource {
display_name?: string; removed?: boolean;
local_scene?: { project_id: string };
inference_ready?: boolean; inference_message?: string;
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
@@ -123,7 +124,7 @@ export interface AiPlanningCommand {
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
}
export interface AiCatalog {
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
sources: AiSource[]; worlds: AiWorld[]; removed_worlds?: AiWorld[]; runs: AiRun[];
robots: AiRobot[];
plans: AiPlan[];
runtime: { available: boolean; active_run: AiRun | null };
@@ -142,6 +143,8 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
}
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
export const updateAiWorld = (id:string, changes:{display_name?:string;removed?:boolean}) =>
polygonRequest<AiWorld>(`/worlds/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
export const aiPlanName = (plan: AiPlan) => plan.display_name ?? plan.name;
export const updateAiPlan = (id:string, changes:{display_name?:string;removed?:boolean}) =>
polygonRequest<AiPlan>(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
@@ -1,17 +1,18 @@
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
import { Quaternion, Vector3 } from "three";
import {screenSpan,type ProjectionCamera} from "./editorProjection";
const UP = new Vector3(0,1,0);
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
export function navigationDepth(camera: ProjectionCamera, anchor: Vector3) {
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
}
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
export function panCamera(camera: ProjectionCamera, depth: number, dx: number, dy: number, height: number) {
const scale=screenSpan(camera,depth)/Math.max(1,height);
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
camera.updateMatrixWorld();
}
/** Rotate the complete camera pose about the picked point: no lookAt snap.
* The picked point keeps its screen coordinates, including off-centre clicks. */
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
export function orbitCamera(camera: ProjectionCamera, anchor: Vector3, dx: number, dy: number, height: number) {
const factor=2*Math.PI/Math.max(1,height);
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
const forward=camera.getWorldDirection(new Vector3());
@@ -0,0 +1,21 @@
import {OrthographicCamera,PerspectiveCamera,Ray,Vector3} from "three";
export type EditorProjection = "orthographic"|"perspective";
export type ProjectionCamera = OrthographicCamera|PerspectiveCamera;
export const isOrthographic=(camera:ProjectionCamera):camera is OrthographicCamera=>"isOrthographicCamera" in camera;
export function screenSpan(camera:ProjectionCamera,depth:number) {
return isOrthographic(camera)?(camera.top-camera.bottom)/camera.zoom:2*depth*Math.tan(camera.fov*Math.PI/360)/camera.zoom;
}
export function cameraRay(camera:ProjectionCamera,x:number,y:number) {
const near=new Vector3(x*2-1,1-y*2,-1).unproject(camera);
const far=new Vector3(x*2-1,1-y*2,1).unproject(camera);
return new Ray(near,far.sub(near).normalize());
}
/** Match scale on the focal plane; switching projection must never move geometry. */
export function switchProjection(camera:ProjectionCamera,mode:EditorProjection,aspect:number,depth:number):ProjectionCamera {
if(isOrthographic(camera)===(mode==="orthographic"))return camera;
const span=screenSpan(camera,depth),half=span/2;
const next=mode==="orthographic"?new OrthographicCamera(-half*aspect,half*aspect,half,-half,camera.near,camera.far):new PerspectiveCamera(60,aspect,camera.near,camera.far);
next.position.copy(camera.position);next.quaternion.copy(camera.quaternion);next.up.copy(camera.up);
if(mode==="perspective")next.position.addScaledVector(camera.getWorldDirection(new Vector3()),depth-half/Math.tan(Math.PI/6));
next.updateProjectionMatrix();next.updateMatrixWorld();return next;
}
@@ -0,0 +1,79 @@
import { useEffect, useRef, useState } from "react";
import { loadUrbanMap, type UrbanMap } from "./urbanMap";
export interface AnalysisProgress {label:string;stage:number|null;stages:number;fraction:number|null;eta_seconds:number|null;stale:boolean;eta_basis:string}
export interface AnalysisJob {key:string;request_id?:string|null;status:"queued"|"running"|"ready"|"failed"|"cancelled";phase:string;completed:number;total:number;error:string|null;progress?:AnalysisProgress;cancel_requested?:boolean;queue?:{position:number|null;total:number;waiting:number}}
export function analysisProgressLabel(job:AnalysisJob):string {
const p=job.progress;
if(!p)return job.status==="queued"?"Ожидание Worker":"Расчёт инфраструктуры";
const stage=p.stage?` · этап ${p.stage} из ${p.stages}`:"";
const eta=p.eta_seconds===null?"":` · ≈ ${Math.max(1,Math.ceil(p.eta_seconds/60))} мин${job.status==="queued"?" на расчёт":job.phase==="preparing"?" после подготовки":" осталось"}`;
return `${p.stale?"Связь с расчётом потеряна":p.label}${job.status==="queued"&&job.queue?.position?` · №${job.queue.position}`:stage}${eta}`;
}
export function useInfrastructureAnalysis(worldId:string,worldSha:string,onMap:(map:UrbanMap)=>void) {
const [job,setJob]=useState<AnalysisJob|null>(null),[error,setError]=useState<string|null>(null);
const [sending,setSending]=useState(false),[checking,setChecking]=useState(true);
const callback=useRef(onMap);callback.current=onMap;
const lifecycle=useRef<AbortController|null>(null),generation=useRef(0),requestId=useRef<string|null>(null),commandPending=useRef(false);
const endpoint=`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/infrastructure-analysis`;
useEffect(()=>{
const abort=new AbortController();lifecycle.current=abort;let timer:ReturnType<typeof setTimeout>;let loaded:string|null=null;
generation.current++;requestId.current=null;commandPending.current=false;setJob(null);setError(null);setChecking(true);setSending(false);
const refresh=async()=>{
if(commandPending.current){timer=setTimeout(refresh,3000);return;}
const revision=generation.current;
try {
const response=await fetch(endpoint,{signal:abort.signal,cache:"no-store"});
if(!response.ok)throw new Error("Не удалось проверить расчёт инфраструктуры.");
const row=await response.json() as AnalysisJob|null;
if(abort.signal.aborted||revision!==generation.current)return;
if(row?.request_id&&row.request_id===requestId.current)requestId.current=null;
setJob(row);
if(row?.status==="ready"&&loaded!==row.key){
const map=await loadUrbanMap(worldId,worldSha,abort.signal);
if(map&&!abort.signal.aborted&&revision===generation.current){callback.current(map);loaded=row.key;}
}
} catch(e){if(!abort.signal.aborted&&revision===generation.current)setError((e as Error).message);}
finally{if(!abort.signal.aborted){setChecking(false);timer=setTimeout(refresh,3000);}}
};
void refresh();return()=>{abort.abort();clearTimeout(timer);};
},[endpoint,worldId,worldSha]);
const start=async(force:boolean)=>{
const abort=lifecycle.current;if(!abort||abort.signal.aborted||commandPending.current)return;
generation.current++;commandPending.current=true;setSending(true);setError(null);
requestId.current??=crypto.randomUUID().replaceAll("-","");
try {
const response=await fetch(endpoint,{method:"POST",signal:abort.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({force,request_id:requestId.current})});
const body=await response.json();
if(!response.ok)throw new Error(typeof body.detail==="string"?body.detail:"Не удалось начать расчёт.");
if(!abort.signal.aborted){setJob(body);requestId.current=null;}
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
};
const cancel=async()=>{
const abort=lifecycle.current;if(!abort||abort.signal.aborted||!job||commandPending.current)return;
generation.current++;commandPending.current=true;setSending(true);setError(null);
try{
const response=await fetch(`${endpoint}/${job.key}/cancel`,{method:"POST",signal:abort.signal});
const row=await response.json();if(!response.ok)throw new Error(typeof row.detail==="string"?row.detail:"Не удалось отменить расчёт.");
if(!abort.signal.aborted)setJob(row);
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
};
return {job,error,cancel,clearError:()=>setError(null),sending,checking,start};
}
export function useInfrastructureQueue(){
const [jobs,setJobs]=useState<(AnalysisJob&{world_id:string;name:string})[]>([]),[unavailable,setUnavailable]=useState(false);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const refresh=async()=>{
try{const response=await fetch('/api/v1/ai-polygon/infrastructure-analysis/queue',{signal:abort.signal,cache:'no-store'});
if(!response.ok)throw new Error('Queue unavailable');
const value=await response.json();if(!abort.signal.aborted){setJobs(value.jobs);setUnavailable(false);}
}catch{if(!abort.signal.aborted)setUnavailable(true);}
finally{if(!abort.signal.aborted)timer=setTimeout(refresh,3000);}
};
void refresh();return()=>{abort.abort();clearTimeout(timer);};
},[]);
return {jobs,unavailable};
}
@@ -0,0 +1,22 @@
import { planMatchesDraft } from "./planDraft";
import type { AiPlan, AiRobot, AiWaypoint } from "./aiPolygon";
import type { EditorCache } from "./aiEditor";
import type { PreparedRoute } from "./routePreparation";
/** The same admission conditions drive visibility and command entry points. */
export function plannerActions(input: {
draft: {cache:EditorCache;points:AiWaypoint[]}|null; robot:AiRobot|undefined;
plan:AiPlan|undefined; routeRequired:boolean; route:PreparedRoute|null; routeKey:string|null;
busy:boolean; runtimeAvailable:boolean; inferenceReady:boolean; activeRun:boolean;
}) {
const {draft,robot,plan,routeRequired,route,routeKey,busy}=input;
const pointsReady=!!draft && !!robot && draft.points.length>=2;
const routeReady=pointsReady && (!routeRequired || (!!route && !!routeKey));
const changed=!!draft && !!robot && (!planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points)
|| (routeRequired && !!route && plan?.prepared_route?.sha256!==route.sha256));
return {
save:!busy && routeReady && changed,
prepare:!busy && pointsReady && routeRequired && !routeReady && input.runtimeAvailable,
launch:!busy && routeReady && input.runtimeAvailable && input.inferenceReady && !input.activeRun,
};
}
@@ -1,14 +1,18 @@
import type { GaussianQuality } from "./gaussianQuality";
export interface PlannerPreferences {
cube: {size:number;face:string;text:string;edge:string;hover:string;hoverText:string;opacity:number;edgeOpacity:number};
quality: GaussianQuality;
toolbar: { placement:"left"|"right"|"top"|"bottom"; minSize:number; maxSize:number; lensCount:number; gap:number; autoHide:boolean; hideDelay:number; background:string; border:string; outline:string; accent:string };
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
}
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
cube: {size:66,face:"#292929",text:"#eeeeee",edge:"#888888",hover:"#eeeeee",hoverText:"#161616",opacity:1,edgeOpacity:1},
quality: "medium",
toolbar: { placement:"right",minSize:25,maxSize:42,lensCount:3,gap:10,autoHide:true,hideDelay:5000,background:"#141416",border:"#141416",outline:"#3b3b3d",accent:"#edf0eb" },
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
@@ -21,7 +25,15 @@ export function normalizePlannerPreferences(value: unknown): PlannerPreferences
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
const c:Partial<PlannerPreferences["cube"]>=v.cube??{},dc=d.cube;
const t:Partial<PlannerPreferences["toolbar"]>=v.toolbar??{}, dt=d.toolbar;
const minSize=n(t.minSize,dt.minSize,18,42), lens=Math.round(n(t.lensCount,dt.lensCount,1,13));
return {
cube:{size:n(c.size,dc.size,48,160),face:color(c.face,dc.face),text:color(c.text,dc.text),edge:color(c.edge,dc.edge),hover:color(c.hover,dc.hover),hoverText:color(c.hoverText,dc.hoverText),opacity:n(c.opacity,dc.opacity,.2,1),edgeOpacity:n(c.edgeOpacity,dc.edgeOpacity,0,1)},
toolbar:{placement:["left","right","top","bottom"].includes(t.placement??"")?t.placement!:dt.placement,
minSize,maxSize:Math.max(minSize,n(t.maxSize,dt.maxSize,18,88)),lensCount:lens%2?lens:Math.min(13,lens+1),gap:n(t.gap,dt.gap,0,24),
autoHide:typeof t.autoHide==="boolean"?t.autoHide:dt.autoHide,hideDelay:n(t.hideDelay,dt.hideDelay,0,15000),
background:color(t.background,dt.background),border:color(t.border,dt.border),outline:color(t.outline,dt.outline),accent:color(t.accent,dt.accent)},
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
@@ -0,0 +1,11 @@
/** Scene-space height range, independent of the reduced collision proxy. */
export function sceneClipBounds(visual: readonly [number, number], collision: readonly [number, number] | null): [number, number] {
const low = Math.floor(Math.min(visual[0], collision?.[0] ?? visual[0]));
const high = Math.ceil(Math.max(500, visual[1], collision?.[1] ?? visual[1]));
return [low, Math.max(low + 1, high)];
}
/** Native range inputs can round a fractional max slightly down on readback. */
export function sceneClipValue(value: number, [low, high]: readonly [number, number]): number {
return value >= high - Math.max(1, high - low) * 1e-9 ? Infinity : value;
}
@@ -0,0 +1,25 @@
import clipping from "polygon-clipping";
import type {UrbanMapFeature} from "./urbanMap";
import {geometryPaths,type RegionOperation} from "./semanticVector";
/** Retain existing heights; new intersection vertices interpolate the nearest measured edge. */
export function regionOperation(feature:UrbanMapFeature|undefined,brush:number[][],mode:"union"|"difference"):RegionOperation {
if(mode==="difference"&&!feature)throw new Error("Сначала выберите пешеходную область для вырезания.");
if(brush.length<4)throw new Error("Замкните область минимум из трёх точек.");
if(feature&&feature.geometry.type!=="Polygon")throw new Error("Выберите пешеходную область.");
const old=feature?geometryPaths(feature):[],subject=old.map(r=>r.map(p=>p.slice(0,2) as [number,number]));
const paint=[brush.map(p=>p.slice(0,2) as [number,number])];
const result=mode==="union"?clipping.union(subject.length?subject:paint,paint):subject.length?clipping.difference(subject,paint):[];
const seeds=[...old,brush];
const height=(p:number[])=>{
for(const ring of seeds)for(const q of ring)if(p[0]===q[0]&&p[1]===q[1])return q[2];
let best=Infinity,z=brush[0][2];
for(const ring of seeds)for(let i=0;i<ring.length-1;i++){
const a=ring[i],b=ring[i+1],dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
const d=Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy);
if(d<best){best=d;z=a[2]+t*(b[2]-a[2]);}
}return z;
};
return {kind:"region",feature_id:feature?.id??`user-${crypto.randomUUID()}`,token:crypto.randomUUID(),mode,brush,
polygons:result.map(p=>p.map(r=>r.map(v=>[...v,height(v)])))};
}
@@ -0,0 +1,14 @@
import type {Knot} from "./semanticVector";
export function curveControlScale(nodes:Knot[],index:number,closed:boolean,project:(p:number[])=>number[]|null):number {
const node=nodes[index],base=node&&project(node.point);if(!base)return 1;
const neighbors=[nodes[index-1]??(closed?nodes.at(-1):undefined),nodes[index+1]??(closed?nodes[0]:undefined)];
const lengths=neighbors.map(n=>n&&project(n.point)).filter((q):q is number[]=>!!q).map(q=>Math.hypot(q[0]-base[0],q[1]-base[1])/3).filter(d=>d>1e-6);
return lengths.length?Math.max(1,36/Math.min(...lengths)):1;
}
export function curveControlPoint(node:Knot,key:"incoming"|"outgoing",scale:number):number[] {
return [node.point[0]+node[key][0]*scale,node.point[1]+node[key][1]*scale,node.point[2]];
}
/** Drag starts at the displayed handle, but persists only the corresponding physical delta. */
export function moveCurveControl(vector:number[],start:number[],current:number[],scale:number):number[] {
return vector.map((v,k)=>v+(current[k]-start[k])/scale);
}
@@ -0,0 +1,172 @@
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
export {isMarking,isRigidMarking,isEditableMarking} from "./semanticFeaturePolicy";
import {vectorOperation,knots,withKnots,insertKnot,type VectorOperation} from "./semanticVector";
import MARKING_TEMPLATES from "../../../../../src/k1link/simulation/ai_polygon/marking-templates.json";
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
export type Vertex = { feature_id:string; path:number; index:number; object?:true };
export type VertexOperation = Vertex & (
{kind:"move";position:number[]}|{kind:"insert";t:number}|{kind:"delete"}
);
export type SemanticOperation = VectorOperation | VertexOperation |
{kind:"retemplate";feature_id:string;template_id:string;frame:number[][]} |
{kind:"transform";feature_id:string;delta:number[];angle:number} |
{kind:"remove";feature_id:string} |
{kind:"place";feature_id:string;template_id:string;position:number[];surface:"gaussian-visual"};
export {MARKING_TEMPLATES};
export function semanticMembers(map:UrbanMap,id:string) {
const f=map.features.find(f=>f.id===id);
if(!f)return [];
const group=f.properties.semantic_element_id;
return group?map.features.filter(q=>q.properties.semantic_element_id===group):[f];
}
export function semanticPivot(features:UrbanMapFeature[]) {
const points=features.flatMap(f=>semanticPaths(f).flat());
return [0,1,2].map(k=>(Math.min(...points.map(p=>p[k]))+Math.max(...points.map(p=>p[k])))/2);
}
function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperation|VectorOperation>):UrbanMap {
if(op.kind==="retemplate") {
const members=semanticMembers(map,op.feature_id),t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
if(members.length!==1||members[0].properties.class!=="road_marking"||members[0].properties.review_status==="rejected"||!t||t.polygons.length!==1||op.frame.length!==3||op.frame.some(v=>v.length!==3||v.some(x=>!Number.isFinite(x)||Math.abs(x)>1e6)))throw new Error("Некорректная замена шаблона.");
const [o,a,b]=op.frame,la=Math.hypot(a[0],a[1]),lb=Math.hypot(b[0],b[1]);
if([la,lb].some(n=>n<.01||n>100)||Math.abs(a[0]*b[0]+a[1]*b[1])>1e-8*la*lb||a[0]*b[1]-a[1]*b[0]<=0||Math.abs(a[2])>la||Math.abs(b[2])>lb)throw new Error("Некорректные оси шаблона.");
const f=members[0],properties={...f.properties,template_id:t.id,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};delete properties.editor_curves;
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(q=>q===f?{...f,properties,geometry:{type:"Polygon",coordinates:t.polygons[0].map(r=>r.map(p=>o.map((v,k)=>v+p[0]*a[k]+p[1]*b[k])))}}:q)};
}
if(op.kind==="place") {
const t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
if(!t||op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||map.features.some(f=>f.id===op.feature_id))throw new Error("Некорректное размещение.");
const features:UrbanMapFeature[]=t.polygons.map((rings,i)=>({id:i?`${op.feature_id}-${i}`:op.feature_id,
geometry:{type:"Polygon",coordinates:rings.map(r=>r.map(v=>[v[0]+op.position[0],v[1]+op.position[1],op.position[2]]))},
properties:{class:"road_marking",authority:"observation-only",route_permission:"unassigned",...(op.template_id==="linear_marking"?{subtype:"linear_marking"}:{semantic_element_id:op.feature_id}),
template_id:op.template_id,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}}));
return {...map,schema_version:"missioncore.urban-edit/v1",features:[...map.features,...features]};
}
const members=semanticMembers(map,op.feature_id);
if(!members.length||members.some(f=>!isMarking(f)))throw new Error("Выберите элемент разметки.");
if(op.kind==="transform" && (op.delta.length!==2||op.delta.some(v=>!Number.isFinite(v))||!Number.isFinite(op.angle)))throw new Error("Некорректное перемещение.");
if(op.kind==="transform"&&!op.angle&&op.delta.every(v=>v===0))return map;
const centre=semanticPivot(members);
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>{
if(!members.includes(f))return f;
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:op.kind==="remove"?"rejected" as const:"unreviewed" as const};
if(op.kind==="remove")return {...f,properties};
const c=Math.cos(op.angle),s=Math.sin(op.angle);
const rings=semanticPaths(f).map(r=>r.map(p=>{
let [x,y]=p;
if(op.angle)[x,y]=[centre[0]+c*(x-centre[0])-s*(y-centre[1]),centre[1]+s*(x-centre[0])+c*(y-centre[1])];
return [x+op.delta[0],y+op.delta[1],p[2]];
}));
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([path,nodes])=>[path,nodes.map(n=>{
const c=Math.cos(op.angle),s=Math.sin(op.angle),rotate=(v:number[])=>[c*v[0]-s*v[1],s*v[0]+c*v[1]];
const relative=rotate([n.point[0]-centre[0],n.point[1]-centre[1]]);
const point=op.angle?[centre[0]+relative[0]+op.delta[0],centre[1]+relative[1]+op.delta[1],n.point[2]]:[n.point[0]+op.delta[0],n.point[1]+op.delta[1],n.point[2]];
return {...n,point,incoming:op.angle?rotate(n.incoming):n.incoming,outgoing:op.angle?rotate(n.outgoing):n.outgoing};
})]));
return {...f,properties,geometry:f.geometry.type==="Polygon"?{type:"Polygon" as const,coordinates:rings}:{type:"LineString" as const,coordinates:rings[0]}};
})};
}
export interface SemanticRevision {
schema_version:"missioncore.semantic-editor/v1";
revision:string|null;model_sha256:string;latest_model_sha256:string;
model:UrbanMap;edited:UrbanMap;
history:{revision:string;created_at:string;actions:number}[];
learning:{state:string;dataset_ready:boolean};
}
export const semanticPaths=(f:UrbanMapFeature):number[][][]=>
f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
/** Copy only the edited feature. Untouched coordinates never round-trip through GPU. */
export function semanticOperation(map:UrbanMap, op:SemanticOperation):UrbanMap {
if(op.kind==="curve"||op.kind==="delete_vertices"||op.kind==="region"||op.kind==="translate"||op.kind==="translate_vertices"||op.kind==="duplicate_vertex"||op.kind==="duplicate_marking")return vectorOperation(map,op);
if(op.kind==="place"||op.kind==="transform"||op.kind==="remove"||op.kind==="retemplate")return objectOperation(map,op);
const feature=map.features.find(f=>f.id===op.feature_id);
if(!feature)throw new Error("Контур не найден.");
if(isRigidMarking(feature))throw new Error("Разметка редактируется целиком.");
if(feature.properties.editor_curves?.[String(op.path)]) {
let nodes=knots(feature,op.path).map(k=>({...k}));
if(!nodes[op.index])throw new Error("Точка не найдена.");
if(op.kind==="move") {
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==nodes[op.index].point[2])throw new Error("Редактирование сохраняет высоту.");
nodes[op.index]={...nodes[op.index],point:op.position};
} else if(op.kind==="insert")nodes=insertKnot(nodes,op.index,op.t,feature.geometry.type==="Polygon");
else nodes.splice(op.index,1);
return {...map,features:map.features.map(f=>f===feature?withKnots(f,op.path,nodes):f)};
}
const rings=semanticPaths(feature).map(p=>p.map(v=>[...v]));
const points=rings[op.path],closed=feature.geometry.type==="Polygon";
if(!points||op.index<0||op.index>=points.length-Number(closed))throw new Error("Точка не найдена.");
if(op.kind==="insert"){
if(op.index>=points.length-1||!(op.t>0&&op.t<1))throw new Error("Выберите середину сегмента.");
const a=points[op.index],b=points[op.index+1];
points.splice(op.index+1,0,a.map((v,k)=>v+op.t*(b[k]-v)));
}else if(op.kind==="move"){
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==points[op.index][2])
throw new Error("Редактирование в плане сохраняет высоту.");
if(points[op.index].every((v,k)=>v===op.position[k]))return map;
points[op.index]=[...op.position];
}else{
if(points.length<=(closed?4:2))throw new Error("В контуре недостаточно точек для удаления.");
points.splice(op.index,1);
}
if(closed)points[points.length-1]=[...points[0]];
const edited:UrbanMapFeature={...feature,geometry:closed?{type:"Polygon",coordinates:rings}:{type:"LineString",coordinates:rings[0]},
properties:{...feature.properties,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>f===feature?edited:f)};
}
export interface SemanticDraft {
base:UrbanMap;map:UrbanMap;operations:SemanticOperation[];future:SemanticOperation[];
}
export const semanticDraft=(base:UrbanMap):SemanticDraft=>({base,map:base,operations:[],future:[]});
export function commitSemantic(s:SemanticDraft,op:SemanticOperation):SemanticDraft {
if(s.operations.length>=256)throw new Error("Сохраните изменения перед продолжением.");
const map=semanticOperation(s.map,op);
return map===s.map?s:{...s,map,operations:[...s.operations,op],future:[]};
}
export function undoSemantic(s:SemanticDraft):SemanticDraft {
const last=s.operations.at(-1);if(!last)return s;
const operations=s.operations.slice(0,-1);
return {...s,operations,map:operations.reduce(semanticOperation,s.base),future:[last,...s.future]};
}
export function redoSemantic(s:SemanticDraft):SemanticDraft {
const next=s.future[0];if(!next)return s;
return {...commitSemantic(s,next),future:s.future.slice(1)};
}
/** CSS pixel distance; backing buffer DPR must not change the capture radius. */
export function segmentHit(p:number[],a:number[],b:number[]) {
const dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
return {t,distance:Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)};
}
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal):Promise<SemanticRevision> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits`,{
method:body?"POST":"GET",cache:"no-store",signal,
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
});
if(!response.ok){
const error=await response.json().catch(()=>null);
throw new Error(typeof error?.detail==="string"?error.detail:"Не удалось открыть или сохранить правки.");
}
const result=await response.json() as SemanticRevision;
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
return result;
}
export interface SemanticDelivery {revision:string|null;state:string;training_eligible:false}
export async function semanticDelivery(worldId:string,signal:AbortSignal):Promise<SemanticDelivery> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits/status`,{
cache:"no-store",signal,
});
if(!response.ok)throw new Error("Не удалось обновить статус доставки.");
return await response.json() as SemanticDelivery;
}
export function semanticDeliveryLabel(state:string):string {
switch(state){
case "received":return "На Worker · в очереди подготовки";
case "building":return "Worker готовит пример";
case "draft-ready":return "Пример на Worker · ожидает проверки";
case "failed":return "Правки на Worker · подготовка не завершена";
case "unavailable":return "Правки сохранены · статус доставки недоступен";
default:return "Правки сохранены · ожидаем доставку на Worker";
}
}
@@ -0,0 +1,5 @@
import type {UrbanMapFeature} from "./urbanMap";
export const isMarking=(f:UrbanMapFeature)=>["road_marking","crosswalk_marking"].includes(f.properties.class);
/** Only explicit line classification admits vertex editing; unknown symbols stay rigid. */
export const isEditableMarking=(f:UrbanMapFeature)=>f.properties.class==="road_marking"&&f.properties.subtype==="linear_marking"&&(!f.properties.template_id||f.properties.template_id==="linear_marking")&&!f.properties.semantic_element_id;
export const isRigidMarking=(f:UrbanMapFeature)=>isMarking(f)&&!isEditableMarking(f);
@@ -0,0 +1,53 @@
import {editablePaths,knots,curvePoint} from "./semanticVector";
import {isMarking,isRigidMarking,segmentHit,type Vertex} from "./semanticEdits";
import type {UrbanMap,UrbanClassId} from "./urbanMap";
export interface SemanticHit {vertex:Vertex;distance:number;t:number;point?:number[];segment?:{a:number[];b:number[];start:number;end:number;t:number}}
export function semanticHits(map:UrbanMap,layers:UrbanClassId|readonly UrbanClassId[],at:number[],project:(v:number[])=>number[]|null,vertices:boolean,activeFeatures?:string|readonly string[]):SemanticHit[] {
const hits:SemanticHit[]=[];
const selected=new Set(typeof activeFeatures==="string"?[activeFeatures]:activeFeatures??[]);
for(const f of map.features) {
if(!(typeof layers==="string"?[layers]:layers).includes(f.properties.class as UrbanClassId)||f.properties.review_status==="rejected"||(!vertices&&isRigidMarking(f)))continue;
editablePaths(f).forEach((path,pathIndex)=>{
if(vertices&&!isRigidMarking(f)&&selected.has(f.id))path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((point,index)=>{
const p=project(point),distance=p?Math.hypot(p[0]-at[0],p[1]-at[1]):Infinity;
if(distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index},distance,t:0,point});
});
const nodes=knots(f,pathIndex);
for(let i=0;i<path.length-1;i++) {
const n=nodes[i],next=nodes[(i+1)%nodes.length];
const steps=n.outgoing.some(Boolean)||next.incoming.some(Boolean)?16:1;
for(let j=0;j<steps;j++) {
const A=steps===1?path[i]:curvePoint(n,next,j/steps),B=steps===1?path[i+1]:curvePoint(n,next,(j+1)/steps);
const a=project(A),b=project(B);if(!a||!b)continue;
const hit=segmentHit(at,a,b);
if(hit.distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index:i},distance:hit.distance,t:(j+hit.t)/steps,segment:{a:A,b:B,start:j/steps,end:(j+1)/steps,t:hit.t}});
}
}
});
// Pick the painted interior, excluding holes, for filled marking elements.
if(f.geometry.type==="Polygon") {
const inside=(ring:number[][])=>{
const p=ring.map(project);if(p.some(v=>!v))return false;
let yes=false;
for(let i=1;i<p.length;i++) {const a=p[i-1]!,b=p[i]!;
if((a[1]>at[1])!==(b[1]>at[1])&&at[0]<(b[0]-a[0])*(at[1]-a[1])/(b[1]-a[1])+a[0])yes=!yes;
}return yes;
};
if(inside(f.geometry.coordinates[0])&&!f.geometry.coordinates.slice(1).some(inside))hits.push({vertex:{feature_id:f.id,path:0,index:0},distance:0,t:0});
}
}
return hits.sort((a,b)=>Number(!!b.point)-Number(!!a.point)||a.distance-b.distance);
}
/** Preserve the gesture's grab offset. Non-selected axes never change. */
export function semanticDrag(origin:number[],start:number[],hit:number[],axis:"x"|"y"|"xy") {
return origin.map((v,k)=>k===2||(axis==="x"&&k!==0)||(axis==="y"&&k!==1)?v:v+(hit[k]-start[k]));
}
/** A body hit selects every editable knot; only a visible vertex hit selects one. */
export function semanticHitSelection(map:UrbanMap,hit:SemanticHit):Vertex[] {
const f=map.features.find(f=>f.id===hit.vertex.feature_id);
if(!f||f.properties.review_status==="rejected")return [];
if(hit.point)return [hit.vertex];
if(isMarking(f))return [{...hit.vertex,object:true}];
return editablePaths(f).flatMap((_,path)=>knots(f,path).map((_,index)=>({feature_id:f.id,path,index})));
}
@@ -0,0 +1,146 @@
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
import type {UrbanMap,UrbanMapFeature} from "./urbanMap";
export interface Knot {point:number[]; incoming:number[]; outgoing:number[]}
export interface CurveOperation {kind:"curve";feature_id:string;path:number;index:number;incoming:number[];outgoing:number[]}
export interface GroupDelete {kind:"delete_vertices";vertices:{feature_id:string;path:number;index:number}[]}
export interface RegionOperation {kind:"region";feature_id:string;token:string;mode:"union"|"difference";brush:number[][];polygons:number[][][][]}
export type SemanticAxis="x"|"y"|"z"|"xy"|"xz"|"yz";
export type TranslateOperation = ({kind:"translate"}|{kind:"translate_vertices"}) & {feature_id:string;vertices:{feature_id:string;path:number;index:number}[];delta:number[];axis:SemanticAxis}
export interface DuplicateVertexOperation {kind:"duplicate_vertex";feature_id:string;path:number;index:number;delta:number[];axis:SemanticAxis;side?:"before"|"after"}
/** Omitted side is the immutable legacy replay contract. New gestures persist their choice. */
export const duplicateIndex=(index:number,closed:boolean,side?:"before"|"after")=>side?index+Number(side==="after"):!closed&&index===0?0:index+1;
/** Compare local arms, not world-axis signs or unequal segment lengths. */
export function duplicateSide(nodes:Knot[],index:number,closed:boolean,delta:number[]):"before"|"after" {
const node=nodes[index];
const alignment=(neighbor:Knot|undefined,handle:number[])=>{
if(!neighbor)return null;
const arm=handle.some(Boolean)?handle:neighbor.point.slice(0,2).map((v,k)=>v-node.point[k]);
const length=Math.hypot(...arm);
return length?arm.reduce((sum,v,k)=>sum+v*delta[k],0)/length:0;
};
const before=alignment(index>0?nodes[index-1]:closed?nodes.at(-1):undefined,node.incoming);
const after=alignment(index+1<nodes.length?nodes[index+1]:closed?nodes[0]:undefined,node.outgoing);
// At an open end a sideways drag continues around the corner. Insert inward
// only when movement along the existing arm dominates its perpendicular part.
// A tiny inward component must not turn an extension into a folded segment.
const inward=Math.hypot(delta[0],delta[1])/Math.SQRT2;
if(before===null)return after!==null&&after>inward?"after":"before";
if(after===null)return before>inward?"before":"after";
return before>after?"before":"after";
}
export interface DuplicateMarkingOperation {kind:"duplicate_marking";feature_id:string;new_feature_id:string;delta:number[];axis:SemanticAxis}
export type VectorOperation=DuplicateMarkingOperation|CurveOperation|GroupDelete|RegionOperation|TranslateOperation|DuplicateVertexOperation;
export const geometryPaths=(f:UrbanMapFeature):number[][][]=>f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
export function knots(f:UrbanMapFeature,path:number):Knot[] {
const saved=f.properties.editor_curves?.[String(path)];
return saved??geometryPaths(f)[path].slice(0,geometryPaths(f)[path].length-Number(f.geometry.type==="Polygon")).map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
}
export const editablePaths=(f:UrbanMapFeature)=>geometryPaths(f).map((_,i)=>{
const points=knots(f,i).map(k=>k.point);return f.geometry.type==="Polygon"?[...points,points[0]]:points;
});
export function curvePoint(a:Knot,b:Knot,t:number) {
const u=1-t;
return [0,1].map(k=>u*u*u*a.point[k]+3*u*u*t*(a.point[k]+a.outgoing[k])+3*u*t*t*(b.point[k]+b.incoming[k])+t*t*t*b.point[k]).concat(a.point[2]+t*(b.point[2]-a.point[2]));
}
export function curvePath(nodes:Knot[],closed:boolean) {
const path:number[][]=[];
for(let i=0;i<nodes.length-Number(!closed);i++) {
const a=nodes[i],b=nodes[(i+1)%nodes.length];path.push(a.point);
if(a.outgoing.some(Boolean)||b.incoming.some(Boolean))for(let j=1;j<16;j++)path.push(curvePoint(a,b,j/16));
}
path.push(closed?nodes[0].point:nodes.at(-1)!.point);return path;
}
export function withKnots(f:UrbanMapFeature,path:number,nodes:Knot[]):UrbanMapFeature {
const closed=f.geometry.type==="Polygon";
if(nodes.length<(closed?3:2))throw new Error("В контуре недостаточно точек. Выберите весь контур для удаления.");
const paths=geometryPaths(f).slice();paths[path]=curvePath(nodes,closed);
return {...f,geometry:closed?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties:{...f.properties,
editor_curves:{...f.properties.editor_curves,[String(path)]:nodes},confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
}
export function vectorOperation(map:UrbanMap,op:VectorOperation):UrbanMap {
let features=map.features;
if(op.kind==="duplicate_marking") {
const selected=features.find(f=>f.id===op.feature_id);
if(!selected||selected.properties.review_status==="rejected"||!isMarking(selected)||!/^user-[a-zA-Z0-9-]{16,64}$/.test(op.new_feature_id))throw new Error("Выберите элемент разметки.");
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
const group=selected.properties.semantic_element_id,members=group?features.filter(f=>f.properties.semantic_element_id===group):[selected];
const moved=vectorOperation({...map,features:members},{kind:"translate",feature_id:op.feature_id,vertices:[],axis:op.axis,delta:op.delta});
const copies=moved.features.map((f,i)=>{const q=structuredClone(f);q.id=i?`${op.new_feature_id}-${i}`:op.new_feature_id;
if(group)q.properties.semantic_element_id=op.new_feature_id;
delete q.properties.height_projection;q.properties.height_source="human-copy-unverified";return q;});
if(copies.some(q=>features.some(f=>f.id===q.id||f.properties.semantic_element_id===op.new_feature_id)))throw new Error("Элемент уже существует.");
features=[...features,...copies];
} else if(op.kind==="duplicate_vertex") {
const f=features.find(f=>f.id===op.feature_id);
if(!f||f.properties.review_status==="rejected"||isRigidMarking(f))throw new Error("Выберите точку редактируемого контура.");
if(!Number.isInteger(op.path)||!geometryPaths(f)[op.path]||!Number.isInteger(op.index))throw new Error("Точка не найдена.");
const nodes=knots(f,op.path),n=nodes[op.index];if(!n)throw new Error("Точка не найдена.");
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
if(!op.delta[0]&&!op.delta[1])throw new Error("Продолжение контура должно иметь длину в плане: используйте X, Y или плоскость.");
if(nodes.length>=4095)throw new Error("Достигнут предел числа точек контура.");
if(op.side!==undefined&&op.side!=="before"&&op.side!=="after")throw new Error("Некорректная сторона вставки.");
const next=nodes.slice(),index=duplicateIndex(op.index,f.geometry.type==="Polygon",op.side);
next.splice(index,0,{point:n.point.map((v,k)=>op.delta[k]===0?v:v+op.delta[k]),incoming:[...n.incoming],outgoing:[...n.outgoing]});
const q=withKnots(f,op.path,next);delete q.properties.height_projection;q.properties.height_source="human-vertex-extension-unverified";
features=features.map(v=>v===f?q:v);
} else if(op.kind==="translate"||op.kind==="translate_vertices") {
if(op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
const selected=features.find(f=>f.id===op.feature_id);if(!selected)throw new Error("Элемент не найден.");
const group=selected.properties.semantic_element_id;
const marking=op.kind==="translate"&&isMarking(selected);
if(op.kind==="translate_vertices"&&op.vertices.some(v=>{const f=features.find(f=>f.id===v.feature_id);return !f||isRigidMarking(f);}))throw new Error("Выберите вершины редактируемого контура.");
features=features.map(f=>{
if(marking&&(f.id===selected.id||(group&&f.properties.semantic_element_id===group))) {
const paths=geometryPaths(f).map(p=>p.map(v=>v.map((x,k)=>x+op.delta[k])));
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([p,nodes])=>[p,nodes.map(n=>({...n,point:n.point.map((v,k)=>v+op.delta[k])}))]));
return {...f,geometry:f.geometry.type==="Polygon"?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties};
}
if(marking)return f;
let q=f;
geometryPaths(f).forEach((_,p)=>{const indices=new Set(op.vertices.filter(v=>v.feature_id===f.id&&v.path===p).map(v=>v.index));
if(indices.size)q=withKnots(q,p,knots(f,p).map((n,i)=>indices.has(i)?{...n,point:n.point.map((v,k)=>v+op.delta[k])}:n));
});return q;
});
} else if(op.kind==="region") {
const previous=features.find(f=>f.id===op.feature_id);
if(previous&&!['pedestrian_area','sidewalk'].includes(previous.properties.class))throw new Error("Выберите пешеходную область.");
const properties={...previous?.properties,class:previous?.properties.class??"pedestrian_area",authority:"observation-only" as const,route_permission:"unassigned" as const,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const,editor_curves:undefined,region_origin_id:op.feature_id};
const created=op.polygons.map((coordinates,i)=>({id:i?`${op.feature_id}-${op.token}-${i}`:op.feature_id,properties,geometry:{type:"Polygon" as const,coordinates}}));
features=features.filter(f=>f!==previous);
if(created.length)features=[...features,...created];
else if(previous)features=[...features,{...previous,properties:{...properties,review_status:"rejected"}}];
} else if(op.kind==="curve") {
const f=features.find(f=>f.id===op.feature_id);if(!f)throw new Error("Контур не найден.");
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
const nodes=knots(f,op.path).map(k=>({...k}));
if(nodes[op.index].incoming.every((v,k)=>v===op.incoming[k])&&nodes[op.index].outgoing.every((v,k)=>v===op.outgoing[k]))return map;
nodes[op.index]={...nodes[op.index],incoming:op.incoming,outgoing:op.outgoing};
const edited=withKnots(f,op.path,nodes);features=features.map(q=>q===f?edited:q);
} else {
features=features.map(f=>{
const chosen=op.vertices.filter(v=>v.feature_id===f.id);if(!chosen.length)return f;
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
const paths=geometryPaths(f),all=paths.every((_,p)=>knots(f,p).every((_,i)=>chosen.some(v=>v.path===p&&v.index===i)));
if(all)return {...f,properties:{...f.properties,review_status:"rejected" as const}};
let edited=f;
paths.forEach((_,p)=>{if(!chosen.some(v=>v.path===p))return;
const nodes=knots(f,p).filter((_,i)=>!chosen.some(v=>v.path===p&&v.index===i));edited=withKnots(edited,p,nodes);
});return edited;
});
}
return {...map,schema_version:"missioncore.urban-edit/v1",features};
}
/** De Casteljau inserts an anchor without changing the physical cubic. */
export function insertKnot(nodes:Knot[],i:number,t:number,closed:boolean) {
const j=(i+1)%nodes.length;if(!closed&&j===0)throw new Error("Выберите сегмент.");
const a=nodes[i],b=nodes[j],mix=(x:number[],y:number[])=>x.map((v,k)=>v+t*(y[k]-v));
const A=a.point.slice(0,2),B=A.map((v,k)=>v+a.outgoing[k]),D=b.point.slice(0,2),C=D.map((v,k)=>v+b.incoming[k]);
const ab=mix(A,B),bc=mix(B,C),cd=mix(C,D),abc=mix(ab,bc),bcd=mix(bc,cd),point=mix(abc,bcd);
const sub=(x:number[],y:number[])=>x.map((v,k)=>v-y[k]);
const next=nodes.map(k=>({...k}));next[i]={...a,outgoing:sub(ab,A)};next[j]={...b,incoming:sub(cd,D)};
next.splice(i+1,0,{point:[...point,a.point[2]+t*(b.point[2]-a.point[2])],incoming:sub(abc,point),outgoing:sub(bcd,point)});return next;
}
@@ -0,0 +1,28 @@
import type {UrbanClassId} from "./urbanMap";
import type {EditorProjection} from "./editorProjection";
import type {SemanticAxis} from "./semanticVector";
export interface SimulationLayout {
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
sceneLayers:{gaussian:boolean;collision:boolean}; infrastructure:boolean; memory:boolean;
layers:UrbanClassId[]; urbanLayers:UrbanClassId[];
visible:{model:boolean;user:boolean}; axis:SemanticAxis; areaMode:"union"|"difference";
}
const classes:UrbanClassId[]=["road_boundary","pedestrian_boundary","building_facade","curb","curb_cut","sidewalk","pedestrian_area","carriageway","service_lane","bike_lane","parking","crosswalk_area","crosswalk_marking","road_marking"];
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
export function normalizeSimulationLayout(raw:unknown):SimulationLayout {
const v=(raw&&typeof raw==="object"?raw:{}) as Partial<SimulationLayout>,d=DEFAULT_SIMULATION_LAYOUT;
const pick=<T extends string>(x:unknown,values:readonly T[],fallback:T):T=>values.includes(x as T)?x as T:fallback;
const bool=(x:unknown,f:boolean)=>typeof x==="boolean"?x:f;
const layers=(x:unknown,f:UrbanClassId[])=>Array.isArray(x)?Array.from(new Set(x.filter((k):k is UrbanClassId=>classes.includes(k)))):f;
return {mode:pick(v.mode,["view","semantic","planning"],d.mode),projection:pick(v.projection,["perspective","orthographic"],d.projection),
sceneLayers:{gaussian:bool(v.sceneLayers?.gaussian,true),collision:bool(v.sceneLayers?.collision,false)},infrastructure:bool(v.infrastructure,false),memory:bool(v.memory,false),
layers:layers(v.layers,d.layers),urbanLayers:layers(v.urbanLayers,d.urbanLayers),visible:{model:bool(v.visible?.model,false),user:bool(v.visible?.user,true)},
axis:pick(v.axis,["x","y","z","xy","xz","yz"],d.axis),areaMode:pick(v.areaMode,["union","difference"],d.areaMode)};
}
export interface SceneView {position:number[];quaternion:number[];anchor:number[]|null;projection:EditorProjection;span:number|null;clip:[number|null,number|null]}
export function normalizeSceneView(raw:unknown):SceneView|null {
const v=raw as SceneView|undefined;
const vec=(x:unknown,n:number)=>Array.isArray(x)&&x.length===n&&x.every(k=>typeof k==="number"&&Number.isFinite(k)&&Math.abs(k)<1e6);
if(!v||!vec(v.position,3)||!vec(v.quaternion,4)||Math.abs(Math.hypot(...v.quaternion)-1)>1e-5||v.anchor!==null&&!vec(v.anchor,3)||!["perspective","orthographic"].includes(v.projection)||v.span!==null&&!(Number.isFinite(v.span)&&v.span>0&&v.span<=5000)||!Array.isArray(v.clip)||v.clip.length!==2||v.clip.some(x=>x!==null&&!(Number.isFinite(x)&&Math.abs(x)<1e6))||(v.clip[0]??-Infinity)>(v.clip[1]??Infinity))return null;
return {position:v.position,quaternion:v.quaternion,anchor:v.anchor,projection:v.projection,span:v.span,clip:v.clip};
}
@@ -1,12 +1,13 @@
export interface UrbanMapFeature {
id: string;
properties: { class: string; authority: "observation-only"; route_permission: "unassigned"; confidence?: number; review_status?: "unreviewed"|"accepted"|"rejected" };
properties: { subtype?:string; height_source?:string; editor_curves?:Record<string,import("./semanticVector").Knot[]>; semantic_element_id?:string; template_id?:string; class: string; authority: "observation-only"; route_permission: "unassigned"; height_projection?: {method:string;surface_sha256:string}; confidence?: number|null; confidence_status?: "not-assessed"; review_status?: "unreviewed"|"accepted"|"rejected" };
geometry: { type: "Polygon"; coordinates: number[][][] } | { type: "LineString"; coordinates: number[][] };
}
export interface UrbanMap {
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2";
source: { world_sha256: string; collider_sha256: string };
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2"|"missioncore.urban-map/v3"|"missioncore.urban-edit/v1";
source: { world_sha256: string; collider_sha256: string|null };
features: UrbanMapFeature[];
analysis?: {scope:"whole-scene";tiles_total:number;tiles_mapped?:number;tiles_without_ground?:number};
coverage: { accepted_cells: number; cell_m: number; kind?: "objects-only" };
}
export const URBAN_COLORS: Record<string, [number, number, number]> = {
@@ -15,17 +16,23 @@ export const URBAN_COLORS: Record<string, [number, number, number]> = {
carriageway: [90,130,200], service_lane: [110,150,210], bike_lane: [150,110,220], parking: [140,140,150],
crosswalk_area: [255,225,35], crosswalk_marking: [255,225,35], road_marking: [245,245,245],
};
export const URBAN_LABELS: Record<string, string> = {
// The new contours share the existing semantic renderer palette.
URBAN_COLORS.road_boundary = URBAN_COLORS.curb;
URBAN_COLORS.pedestrian_boundary = URBAN_COLORS.pedestrian_area;
URBAN_COLORS.building_facade = URBAN_COLORS.carriageway;
URBAN_COLORS.road_marking = URBAN_COLORS.crosswalk_marking;
export const URBAN_LABELS = {
road_boundary: "Граница дороги", pedestrian_boundary: "Граница пешеходной зоны", building_facade: "Фасад",
curb: "Бордюр", curb_cut: "Съезд", sidewalk: "Тротуар", pedestrian_area: "Пешеходная зона",
carriageway: "Проезжая часть", service_lane: "Служебный проезд", bike_lane: "Велополоса", parking: "Парковка",
crosswalk_area: "Переход", crosswalk_marking: "Зебра", road_marking: "Разметка",
};
} as const;
export async function loadUrbanMap(worldId: string, worldSha: string, signal: AbortSignal): Promise<UrbanMap|null> {
const response = await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/urban-map`, { signal, cache: "no-store" });
if (response.status === 404) return null;
if (!response.ok) throw new Error("Не удалось загрузить карту инфраструктуры.");
const result = await response.json() as UrbanMap;
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2","missioncore.urban-map/v3"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
throw new Error("Карта относится к другой версии сцены.");
}
return result;
@@ -34,3 +41,22 @@ export async function loadUrbanMap(worldId: string, worldSha: string, signal: Ab
export function urbanPaths(feature: UrbanMapFeature): number[][][] {
return feature.properties.review_status === "rejected" ? [] : feature.geometry.type === "Polygon" ? feature.geometry.coordinates : [feature.geometry.coordinates];
}
export type UrbanClassId = keyof typeof URBAN_LABELS;
export const ALL_URBAN_CLASSES = Object.keys(URBAN_LABELS) as UrbanClassId[];
/** Legend choices describe the source map, even when every class is hidden. */
export function availableUrbanClasses(map:UrbanMap):UrbanClassId[] {
const present=new Set(map.features.filter(f=>f.properties.review_status!=="rejected").map(f=>f.properties.class));
return ALL_URBAN_CLASSES.filter(id=>present.has(id));
}
export function visibleUrbanMap(map:UrbanMap, selected:readonly UrbanClassId[]):UrbanMap {
return {...map,features:map.features.filter(f=>f.properties.review_status!=="rejected" && selected.includes(f.properties.class as UrbanClassId))};
}
/** Bounded framing coordinates, including polygon holes and open line ends. */
export function urbanExtent(map:UrbanMap):number[][] {
const low=[Infinity,Infinity,Infinity],high=[-Infinity,-Infinity,-Infinity];
for(const feature of map.features) for(const ring of urbanPaths(feature)) for(const point of ring)
for(let i=0;i<3;i++){low[i]=Math.min(low[i],point[i]);high[i]=Math.max(high[i],point[i]);}
return Number.isFinite(low[0])?[low,high]:[];
}
@@ -0,0 +1,13 @@
import { ShapeUtils, Vector2 } from "three";
import type { UrbanMapFeature } from "./urbanMap";
/** A coverage polygon is a surface, never a surveyed curb. Preserve its holes. */
export function urbanSurface(feature: UrbanMapFeature): { positions: number[]; indices: number[] } | null {
if (feature.properties.review_status === "rejected" || feature.properties.class !== "pedestrian_area"
|| feature.geometry.type !== "Polygon" || !feature.properties.height_projection) return null;
const rings = feature.geometry.coordinates.map(ring => ring.slice(0, -1));
if (!rings.length || rings.some(ring => ring.length < 3)) return null;
const planar = rings.map(ring => ring.map(point => new Vector2(point[0], point[1])));
const faces = ShapeUtils.triangulateShape(planar[0], planar.slice(1));
return { positions: rings.flat().flat(), indices: faces.flat() };
}
+30 -3
View File
@@ -4,6 +4,14 @@
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
/* Header selectors and available actions share the window action row. */
.ai-polygon__location-actions { margin-left: auto; justify-content: flex-end; }
.ai-polygon__planner-actions { justify-content: flex-end; }
.ai-polygon__mode-field { width: 15rem; min-width: 0; }
.ai-polygon__task-field { min-width: 0; }
.ai-polygon__actions:has(> .ai-polygon__mode-field) { align-items: flex-start; }
.ai-polygon__location-actions > .ai-polygon__actions:empty,
.ai-polygon__planner-actions > .ai-polygon__actions:empty { display: none; }
.ai-polygon__robot-select { width: 12rem; flex: 0 0 12rem; }
.ai-polygon__report { font-size: var(--nodedc-font-size-sm); }
.ai-polygon__report dl { margin: 0; display: grid; gap: .5rem; }
@@ -73,11 +81,20 @@
/* View controls float above the render target; there is no separate header strip. */
.ai-simulation__view-tools { max-width: calc(100% - 6rem); flex-wrap: wrap; justify-content: flex-end; position: absolute; z-index: 3; top: .5rem; right: .5rem; display: flex; align-items: center; gap: .5rem; }
.ai-simulation__view-tools > .nodedc-select-anchor { width: 10rem; }
.ai-simulation__display-tools { display: flex; align-items: center; justify-content: flex-end; gap: .5rem; }
.ai-simulation__display-tools > .nodedc-select-anchor { width: 10rem; }
.ai-simulation__view-tools--planning { flex-direction: row-reverse; justify-content: flex-start; align-items: flex-start; }
.ai-simulation__view-tools--planning .ai-simulation__display-tools { flex: 0 0 auto; max-width: 100%; }
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .5rem; max-width: 100%; }
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: max(33.333%, calc(var(--planner-cube-size, 66px) + 20px)); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: contents; }
.ai-local-editor__tool-row { flex: 0 0 auto; display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .5rem; max-width: 100%; }
.ai-local-editor__layers { max-width: 100%; overflow-x: auto; flex-shrink: 0; }
.ai-local-editor__legend { position: absolute; z-index: 2; bottom: .75rem; left: 50%; transform: translateX(-50%); width: max-content; max-width: calc(100% - 9rem); display: flex; flex-direction: column; align-items: center; gap: .5rem; }
.ai-local-editor__legend-controls { max-width: 100%; flex-wrap: wrap; justify-content: center; }
.ai-local-editor__legend-swatch { display: inline-block; width: .65rem; height: .65rem; flex: 0 0 .65rem; border-radius: 50%; }
.ai-local-editor > .ai-local-editor__loading { position: absolute; inset: 0; background: var(--nodedc-canvas); }
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
.ai-local-editor canvas { outline: none; }
@@ -171,3 +188,13 @@
@container (max-width: 32rem) {
.ai-polygon__run-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
/* Caption-bearing selectors align window actions to the control row. */
.nodedc-application-panel__actions:has(.ai-polygon__mode-field) { align-items: flex-start; }
.ai-local-editor__marking-template { flex: 0 1 12rem; width: 12rem; max-width: 100%; }
.semantic-tools__menu { display: flex; flex-direction: column; gap: .25rem; }
.ai-polygon__semantic-actions { display: contents; }
.ai-local-editor__cube { position: absolute; top: 8px; left: 4px; z-index: 5; }
@@ -1,3 +1,4 @@
import { Button } from "@nodedc/ui-react";
import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
@@ -355,11 +356,11 @@ export function PolygonRoverScene({
<div ref={hostRef} className="polygon-rover-scene__viewport">
{renderError ? <p className="polygon-rover-scene__error">{renderError}</p> : null}
</div>
<div className="polygon-rover-scene__toolbar">
<button type="button" onClick={() => setFollowRover((value) => !value)}>
<div className="polygon-rover-scene__toolbar nodedc-viewport-controls">
<Button onClick={() => setFollowRover((value) => !value)}>
{followRover ? "Следовать за ровером" : "Свободная камера"}
</button>
<button type="button" onClick={resetCamera}>Сбросить ракурс</button>
</Button>
<Button onClick={resetCamera}>Сбросить ракурс</Button>
</div>
<div className="polygon-rover-scene__help">
<span>ЛКМ · вращение</span>
@@ -1,7 +1,8 @@
import { useRoutePreparation } from "../../core/simulation/routePreparation";
import { viewedAiRun } from "../../core/simulation/viewedAiRun";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, ResourceList, ResourceRow, StatusBadge, ToastStack } from "@nodedc/ui-react";
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, StatusBadge, ToastStack } from "@nodedc/ui-react";
import { AiLocationCatalog } from "../../components/simulation/AiLocationCatalog";
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
@@ -13,6 +14,7 @@ import { AiConfiguration } from "../../components/simulation/AiConfiguration";
import { AiSessionSection } from "../../components/simulation/AiSessionSection";
import { AiTaskSelect } from "../../components/simulation/AiTaskSelect";
import { AiPlanSaveWindow } from "../../components/simulation/AiPlanSaveWindow";
import { plannerActions } from "../../core/simulation/plannerActions";
import { planMatchesDraft } from "../../core/simulation/planDraft";
import type { AiPlan, AiWaypoint } from "../../core/simulation/aiPolygon";
import { aiPlanName, updateAiPlan, removeAiRun, fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules } from "../../core/simulation/aiPolygon";
@@ -22,16 +24,19 @@ import { RoverSettingsWindow } from "../../components/simulation/RoverSettingsWi
import { currentSelection } from "../../core/simulation/runConfiguration";
import { saveLocalPlan } from "../../core/simulation/aiEditor";
import {useSimulationLayout} from "../../components/simulation/useSimulationLayout";
import type { LocalDraft } from "../../components/simulation/AiLocalPlanner";
const LocalManualScene = lazy(() => import("../../components/simulation/LocalManualScene").then((m) => ({ default: m.LocalManualScene })));
const AiLocalPlanner = lazy(() => import("../../components/simulation/AiLocalPlanner").then((m) => ({ default: m.AiLocalPlanner })));
const EMPTY_POINTS:AiWaypoint[]=[];
export function AiPolygonWorkspace() {
export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
const [mode,setMode] = useState<"manual"|"inference">("inference");
const [manual,setManual] = useState(false);
const [importChoice,setImportChoice] = useState(false);
const [planning, setPlanning] = useState(false);
const [layout,updateLayout]=useSimulationLayout();
const sceneMode=layout.mode, setSceneMode=(mode:typeof sceneMode)=>updateLayout({mode});
const [draft, setDraft] = useState<LocalDraft | null>(null);
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
@@ -121,7 +126,11 @@ export function AiPolygonWorkspace() {
const openWorld = (world: AiWorld) => {
if (world.status === "uploading") setImporting({ source: world, resume: world });
else {
setSelectedId(world.world_id); setRunId(catalog?.runtime.active_run?.world.world_id===world.world_id?catalog.runtime.active_run.run_id:null); setPlanId(null);setEditorPlan(null);setSettingsOpen(!world.settings.prepared);
const active=catalog?.runtime.active_run?.world.world_id===world.world_id?catalog.runtime.active_run:null;
const saved=catalog?.plans.find(p=>p.world_id===world.world_id&&p.robot_id===robot?.robot_id&&p.robot_sha256===robot?.sha256);
setSelectedId(world.world_id);setMode("inference");setManual(false);setRunId(active?.run_id??null);
setPlanId(saved?.plan_id??"");setEditorPlan(saved??null);setDraft(null);
setSettingsOpen(!world.settings.prepared);setPlanning(world.settings.prepared&&!active);
}
};
const returnToLocations = () => { setManual(false); setPlanning(false); setDraft(null); setSelectedId(null); setRunId(null); };
@@ -136,9 +145,17 @@ export function AiPolygonWorkspace() {
plan?.settings?.max_speed_mps ?? selected?.settings.max_speed_mps ?? .15);
const routeRequired=!!selected?.local_scene;
const preparation=useRoutePreparation(draft?.cache??null,robot,draft?.points??EMPTY_POINTS,plan,setError);
const available=plannerActions({draft,robot,plan,routeRequired,route:preparation.route,routeKey:preparation.key,
busy:starting||saving||preparation.busy,runtimeAvailable:!!catalog?.runtime.available,
inferenceReady:selected?.inference_ready!==false,activeRun:!!catalog?.runtime.active_run});
const canEdit=!!robot && !!selected?.settings.prepared && !starting;
const canLaunchSaved=!!robot && !!plan && plan.points.length>=2 && (!routeRequired||!!plan.prepared_route)
&& selected?.inference_ready!==false && !!catalog?.runtime.available && !catalog.runtime.active_run && !starting;
const start = (purpose: "planning" | "evaluation", task=plan) => {
if (!selected || !robot) return;
if (purpose === "planning") { setEditorPlan(plan??(planId===null?previousPlan:null)??null);setSettingsOpen(false); setDraft(null); setPlanning(true); return; }
if (!selected || !robot || starting) return;
if (purpose === "planning") { setSceneMode("planning");setEditorPlan(plan??(planId===null?previousPlan:null)??null);setSettingsOpen(false); setDraft(null); setPlanning(true); return; }
if(!task || task.points.length<2 || (routeRequired&&!task.prepared_route)
|| selected.inference_ready===false || !catalog?.runtime.available || catalog.runtime.active_run)return;
setStarting(true);
void fetchAiModules().then((fresh) => {
setModules(fresh);
@@ -148,7 +165,7 @@ export function AiPolygonWorkspace() {
}).then(acceptRun).catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false));
};
const save = () => {
if (!draft || !robot) return;
if (!draft || !robot || !available.save) return;
setSaving(true);setSaveError(null);
void saveLocalPlan(draft.cache, robot, draft.points, planName, draft.id, draft.sequence, preparation.key).then(async (saved) => {
setPlanId(saved.plan_id);setSaveOpen(false);
@@ -160,14 +177,37 @@ export function AiPolygonWorkspace() {
setSaveError(null);setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
};
const launchDraft = () => {
if(!draft||!robot)return;
if(!draft||!robot||!available.launch)return;
if(routeRequired && (!preparation.route || !preparation.key))return;
if(planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points) && (!routeRequired || plan?.prepared_route?.sha256===preparation.route?.sha256))start("evaluation",plan);
else openSave(true);
};
const planLocation=(world:AiWorld)=>{
if(!robot||!world.settings.prepared)return;
const saved=catalog?.plans.find(p=>p.world_id===world.world_id&&p.robot_id===robot.robot_id&&p.robot_sha256===robot.sha256);
setSelectedId(world.world_id);setMode("inference");setManual(false);setRunId(null);setSettingsOpen(false);
setSceneMode("planning");
setPlanId(saved?.plan_id??"");setEditorPlan(saved??null);setDraft(null);setPlanning(true);
};
const connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
{catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"}
</StatusBadge>;
const taskSelector = mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
disabled={running||starting||saving||preparation.busy} onUpdated={planUpdated}
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null;
const routeActions = selected && catalog ? <div className="ai-polygon__actions">{mode === "manual" ? (manual||canEdit?<Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button>:null) : planning ? <>
{available.save?<Button onClick={()=>openSave()}>Сохранить задание</Button>:null}
{available.prepare||preparation.busy?<Button variant="primary" icon={<Icon name="plan"/>} loading={preparation.busy}
title="Рассчитать путь между точками по геометрии поверхности"
onClick={()=>{if(available.prepare)void preparation.prepare();}}>Спланировать маршрут</Button>:null}
{available.launch||starting?<IconButton label="Запустить симуляцию" aria-busy={starting} disabled={starting}
onClick={launchDraft}><Icon name="play"/></IconButton>:null}
</> : !running ? <>
{canEdit?<Button onClick={() => start("planning")}>Подготовить маршрут</Button>:null}
{canLaunchSaved||starting?<Button variant="primary" icon={<Icon name="play" />} loading={starting}
onClick={() => start("evaluation")}>Запустить симуляцию</Button>:null}
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div> : null;
const sceneActions = selected && catalog ? <>
{!planning&&!manual&&!running&&!starting?<><div className="ai-polygon__robot-select"><InspectorSelectField label="Режим" value={mode}
options={[{value:"inference",label:"Inference"},{value:"manual",label:"Ручное управление"}]}
@@ -177,31 +217,12 @@ export function AiPolygonWorkspace() {
value={running ? run.robot?.robot_id ?? "" : robot?.robot_id ?? ""}
options={(catalog.robots ?? []).map((item) => ({ value: item.robot_id, label: item.name }))}
disabled={planning || manual || starting || running} onChange={(id)=>{setRobotId(id);setPlanId(null);}} /></div>
<IconButton label="Настройки ровера" disabled={!robot || !roverSettings || starting}
onClick={()=>setRoverSettingsOpen(true)}><Icon name="settings"/></IconButton>
{robot&&roverSettings&&!starting?<IconButton label="Настройки ровера"
onClick={()=>setRoverSettingsOpen(true)}><Icon name="settings"/></IconButton>:null}
</div>
{roverSettings?<p>{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом</p>:null}</>:null}
{mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
disabled={running||starting||saving||preparation.busy} onUpdated={planUpdated}
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null}
<div className="ai-polygon__actions">{mode === "manual" ? <Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
disabled={!robot || !selected.settings.prepared}
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button> : planning ? <>
<Button disabled={starting || saving || preparation.busy || (routeRequired && !preparation.route) || !draft || draft.points.length < 2}
onClick={()=>openSave()}>Сохранить задание</Button>
{!routeRequired || preparation.route ? <Button variant="primary" icon={<Icon name="play"/>} loading={starting}
disabled={saving || !draft || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={launchDraft}>Запустить симуляцию</Button> : <Button variant="primary" icon={<Icon name="plan"/>}
loading={preparation.busy} disabled={saving || starting || !draft || draft.points.length<2 || !catalog.runtime.available}
onClick={()=>void preparation.prepare()}>Спланировать маршрут</Button>}
{preparation.busy?<p role="status">Рассчитываем маршрут по сцене</p>:null}
</> : !running ? <>
<Button loading={starting} disabled={!robot || !selected.settings.prepared}
onClick={() => start("planning")}>Подготовить маршрут</Button>
<Button variant="primary" icon={<Icon name="play" />} loading={starting}
disabled={!robot || !plan || (routeRequired && !plan.prepared_route) || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={() => start("evaluation")}>Запустить симуляцию</Button>
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div>
{taskSelector}
{routeActions}
</> : null;
return <div className="ai-polygon">
<header className="ai-polygon__head">
@@ -211,8 +232,9 @@ export function AiPolygonWorkspace() {
</IconButton> : null}
<h2>{selected?.name ?? "Доступные локации"}</h2>
</div>
<div className="ai-polygon__actions" ref={setActionsHost}>
{selected ? null : <>{connection}
<div className="ai-polygon__actions ai-polygon__location-actions" ref={setActionsHost}>
{selected ? !planning&&!manual&&!running&&canEdit?<IconButton label="Подготовить маршрут"
onClick={()=>start("planning")}><Icon name="plan"/></IconButton>:null : <>{connection}
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
</div>
</header>
@@ -223,14 +245,9 @@ export function AiPolygonWorkspace() {
<Button disabled={removing!==null} onClick={()=>void undoRemove()}>Отменить удаление</Button>
</GlassSurface>:null}
{catalog ? !selected ? <section aria-label="Доступные локации" className="ai-polygon__section">
<ResourceList>{catalog.worlds.map((world) => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
{catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
</StatusBadge> : undefined}
actions={<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => openWorld(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>}/>
</li>)}</ResourceList>
<AiLocationCatalog worlds={catalog.worlds} removedWorlds={catalog.removed_worlds ?? []}
activeWorldId={catalog.runtime.active_run?.world.world_id}
paused={catalog.runtime.active_run?.state === "paused"} onOpen={openWorld} onPlan={planLocation} canPlan={!!robot} onChanged={load}/>
</section> : <section className="ai-polygon__section" aria-label={`Симуляция ${selected.name}`}>
{!running && !planning && !manual ? <AiSessionSection key={`${selected.world_id}:configuration`}
scope={`${selected.world_id}:configuration`} title="Конфигурация">
@@ -255,13 +272,15 @@ export function AiPolygonWorkspace() {
{mode === "inference" && !planning && !running && catalog.runtime.active_run ? <div className="ai-polygon__facts"><p>Выполняется симуляция «{catalog.runtime.active_run.world.name}».</p>
{catalog.runtime.active_run.world.world_id===selected.world_id?<Button onClick={()=>acceptRun(catalog.runtime.active_run!)}>Открыть текущую симуляцию</Button>:null}</div> : null}
{manual && robot ? <Suspense fallback={<LoadingRegion loading label="Открываем ручное управление" />}>
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={actionsHost} headerActions={sceneActions} />
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={headerToolsHost??actionsHost} headerActions={sceneActions} />
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
sceneMode={sceneMode} onSceneMode={setSceneMode}
busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft}
actionsHost={headerToolsHost??actionsHost} headerActions={taskSelector} routeActions={routeActions} routeActionsHost={actionsHost} />
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
{mode === "inference" && running && run ? <AiWorldStream key={run.run_id} world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
actionsHost={actionsHost} headerActions={sceneActions}
actionsHost={headerToolsHost??actionsHost} headerActions={sceneActions}
controls={<AiRunView run={run} />} /> : mode === "inference" ? <div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">{connection}{selected.inference_ready===false?<p>{selected.inference_message}</p>:null}</div> : null}
</LoadingRegion>}
{mode === "inference" && !planning ? <AiRunReport key={selected.world_id} worldId={selected.world_id} modules={modules} onRemove={removeRun} removing={removing} runs={catalog.runs.filter((item) => item.world.world_id === selected.world_id)} /> : null}
@@ -1,6 +1,6 @@
import { AiPolygonWorkspace } from "./AiPolygonWorkspace";
/** One location library; execution mode is selected inside the location. */
export function SimulationWorkspace() {
return <AiPolygonWorkspace />;
export function SimulationWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
return <AiPolygonWorkspace headerToolsHost={headerToolsHost} />;
}
@@ -0,0 +1,146 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {test} from 'node:test';
import ts from 'typescript';
import {Vector3} from 'three';
function moduleUrl(url){
const code=ts.transpileModule(readFileSync(url,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
.replace(/from "([^"]+)"/g,(_,name)=>`from "${name.startsWith('.')?moduleUrl(new URL(name+'.ts',url)):import.meta.resolve(name)}"`);
return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`;
}
const {EditorCamera}=await import(moduleUrl(new URL('../src/components/simulation/EditorCamera.ts',import.meta.url)));
class Surface extends EventTarget {
captures=new Set();clientWidth=1000;clientHeight=600;
closest(){return null;}focus(){}
getBoundingClientRect(){return {left:0,top:0,width:this.clientWidth,height:this.clientHeight};}
setPointerCapture(id){this.captures.add(id);}hasPointerCapture(id){return this.captures.has(id);}
releasePointerCapture(id){this.captures.delete(id);}
}
const tick=()=>new Promise(resolve=>setImmediate(resolve));
function fixture(){
globalThis.window=new EventTarget();globalThis.document={activeElement:null};
const surface=new Surface(),c=new EditorCamera(surface,surface);c.resize(1000,600);c.home([0,0,0]);
const point=new Vector3(2,0,-1),screen=point.clone().project(c.camera);
const x=(screen.x+1)*500,y=(1-screen.y)*300;
function event(type,props={}){const e=new Event(type,{cancelable:true});Object.assign(e,{pointerId:1,button:0,clientX:x,clientY:y,...props});surface.dispatchEvent(e);return e;}
return {surface,c,point,screen,x,y,event};
}
test('Gaussian depth supplies off-centre orbit pivot without a collision mesh; buffered motion preserves projection',async()=>{
const f=fixture();let resolve;f.c.pickSurface=()=>new Promise(r=>resolve=r);
const before=f.c.camera.position.clone();f.event('pointerdown');f.event('pointermove',{clientX:f.x+40,clientY:f.y+20});
assert.ok(f.c.camera.position.equals(before));assert.equal(f.c.rotationCenter,null);
resolve(f.point.toArray());await tick();
assert.ok(f.c.rotationCenter.distanceTo(f.point)<1e-10);
assert.ok(f.point.clone().project(f.c.camera).distanceTo(f.screen)<1e-10);
assert.ok(f.c.camera.position.distanceTo(before)>.1);
f.c.dispose();
});
test('released and superseded async picks cannot move the camera or replace the next pivot',async()=>{
const f=fixture(),pending=[];f.c.pickSurface=()=>new Promise(r=>pending.push(r));
f.event('pointerdown');f.event('pointermove',{clientX:f.x+20});f.event('pointerup');
const before=f.c.camera.position.clone();pending[0]([99,99,99]);await tick();assert.ok(f.c.camera.position.equals(before));
f.event('pointerdown');f.event('pointerdown',{pointerId:2});pending[1]([99,99,99]);await tick();
assert.equal(f.c.rotationCenter,null);pending[2](f.point.toArray());await tick();
assert.ok(f.c.rotationCenter.distanceTo(f.point)<1e-10);f.c.dispose();
});
test('view, resize, layer and mode changes invalidate in-flight surface picks',async()=>{
for(const cancel of [c=>c.home([1,0,1]),c=>c.top([[0,0,0],[10,0,10]]),c=>c.resize(800,600),c=>c.invalidateSurface(),c=>c.setAddMode(true),c=>c.setNavigation(false)]){
const f=fixture();let resolve;f.c.pickSurface=()=>new Promise(r=>resolve=r);
f.event('pointerdown');f.event('pointermove',{clientX:f.x+20});cancel(f.c);
const before=f.c.camera.position.clone();resolve(f.point.toArray());await tick();
assert.ok(f.c.camera.position.equals(before));assert.equal(f.c.rotationCenter,null);assert.equal(f.surface.captures.size,0);f.c.dispose();
}
});
test('empty sky fallback remains on clicked ray instead of camera centre',async()=>{
const f=fixture();f.c.pickSurface=async()=>null;f.event('pointerdown');await tick();
const projected=f.c.rotationCenter.clone().project(f.c.camera);
assert.ok(Math.abs(projected.x-f.screen.x)<1e-10);assert.ok(Math.abs(projected.y-f.screen.y)<1e-10);
f.c.dispose();
});
test('waypoint add mode does not start orbit or visual picking',()=>{
const f=fixture();let picks=0;f.c.pickSurface=async()=>{picks++;return [0,0,0];};f.c.setAddMode(true);f.event('pointerdown');
assert.equal(picks,0);assert.equal(f.c.rotationCenter,null);f.c.dispose();
});
test('semantic editing reserves bare left drag for tools and Ctrl-left drag for orbit',()=>{
const f=fixture();f.c.semanticSelection=true;
const before=f.c.camera.position.clone();
f.event('pointerdown');f.event('pointermove',{clientX:f.x+40});f.event('pointerup');
assert.ok(f.c.camera.position.equals(before));assert.equal(f.surface.captures.size,0);
const down=f.event('pointerdown',{ctrlKey:true});
// Modifier changes mid-gesture must not change camera ownership.
f.event('pointermove',{clientX:f.x+40,ctrlKey:false});
assert.equal(down.defaultPrevented,true);assert.ok(f.c.camera.position.distanceTo(before)>.1);
f.event('pointerup');const ended=f.c.camera.position.clone();
f.event('pointermove',{clientX:f.x+80});assert.ok(f.c.camera.position.equals(ended));
f.c.dispose();
});
test('Ctrl-click mapped to the secondary button on macOS still orbits instead of panning',()=>{
const f=fixture();f.c.semanticSelection=true;
const orientation=f.c.camera.quaternion.clone();
f.event('pointerdown',{ctrlKey:true,button:2});f.event('pointermove',{clientX:f.x+40});
assert.ok(f.c.camera.quaternion.angleTo(orientation)>.01);assert.ok(f.c.rotationCenter);
f.event('pointercancel');assert.equal(f.surface.captures.size,0);f.c.dispose();
});
test('Ctrl-orbit accepts a semantic handle or pivot, but never an unrelated toolbar control',()=>{
for(const allowed of [false,true]){
const f=fixture();f.c.semanticSelection=true;
const e=new Event('pointerdown',{cancelable:true});
Object.assign(e,{pointerId:1,button:0,ctrlKey:true,clientX:f.x,clientY:f.y});
const target={closest(selector){return allowed&&selector.includes('data-semantic-')?this:null;}};
Object.defineProperty(e,'target',{value:target});
const before=f.c.camera.position.clone();f.surface.dispatchEvent(e);f.event('pointermove',{clientX:f.x+40});
assert.equal(f.c.camera.position.equals(before),!allowed);f.c.dispose();
}
});
test('leaving semantic editing restores unmodified left-drag orbit; right-drag pan is preserved',()=>{
const f=fixture();f.c.semanticSelection=true;const before=f.c.camera.position.clone(),q=f.c.camera.quaternion.clone();
f.event('pointerdown',{button:2});f.event('pointermove',{clientX:f.x+40});f.event('pointerup');
assert.ok(f.c.camera.position.distanceTo(before)>.1);assert.ok(f.c.camera.quaternion.equals(q));
f.c.semanticSelection=false;f.event('pointerdown');f.event('pointermove',{clientX:f.x+40});
assert.ok(f.c.camera.quaternion.angleTo(q)>.01);f.c.dispose();
});
const {cameraRay,screenSpan}=await import(moduleUrl(new URL('../src/core/simulation/editorProjection.ts',import.meta.url)));
test('orthographic projection preserves focal-plane framing; depth never changes line width',()=>{
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);
const samples=[new Vector3(0,0,0),new Vector3(2,0,3)],before=samples.map(p=>p.clone().project(f.c.camera));
f.c.setProjection('orthographic');assert.equal(f.c.camera.isOrthographicCamera,true);
samples.forEach((p,i)=>{const q=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-before[i].x,q.y-before[i].y)<1e-8);});
const q=samples[1].clone().project(f.c.camera),above=samples[1].clone().add(new Vector3(0,10,0)).project(f.c.camera);
assert.ok(Math.hypot(q.x-above.x,q.y-above.y)<1e-8);
f.c.setProjection('perspective');samples.forEach((p,i)=>{const q=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-before[i].x,q.y-before[i].y)<1e-8);});f.c.dispose();
});
test('orthographic cursor zoom keeps anchor fixed, pan is metric, resize preserves shape',()=>{
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection('orthographic');
const p=new Vector3(4,0,2),q=p.clone().project(f.c.camera);f.c.pick=()=>p.toArray();
const span=screenSpan(f.c.camera,5);
f.event('wheel',{clientX:(q.x+1)*500,clientY:(1-q.y)*300,deltaY:-120,deltaMode:0});
const after=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-after.x,q.y-after.y)<1e-8);assert.ok(screenSpan(f.c.camera,5)<span);
f.c.semanticSelection=true;f.event('wheel',{deltaX:40,deltaY:20});
const moved=p.clone().project(f.c.camera);assert.ok(Math.abs((moved.x-after.x)*500-40)<1e-8);assert.ok(Math.abs((moved.y-after.y)*300+20)<1e-8);
const oldSpan=screenSpan(f.c.camera,5);f.c.resize(600,600);assert.equal(screenSpan(f.c.camera,5),oldSpan);
assert.equal(f.c.camera.right-f.c.camera.left,f.c.camera.top-f.c.camera.bottom);f.c.dispose();
});
test('all 26 cube directions preserve focus, orthographic scale, and matching parallel pick rays',()=>{
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection('orthographic');const span=screenSpan(f.c.camera,5);
for(const x of [-1,0,1])for(const y of [-1,0,1])for(const z of [-1,0,1]){
if(!x&&!y&&!z)continue;f.c.view([x,y,z]);
const expected=new Vector3(x,y,z).normalize().negate(),direction=f.c.camera.getWorldDirection(new Vector3());assert.ok(direction.distanceTo(expected)<1e-8);
const a=cameraRay(f.c.camera,.3,.4),b=cameraRay(f.c.camera,.8,.6);assert.ok(a.direction.distanceTo(b.direction)<1e-8);assert.ok(a.origin.distanceTo(b.origin)>1);
assert.equal(screenSpan(f.c.camera,5),span);assert.ok(new Vector3().project(f.c.camera).length()<1.01);
}
f.c.dispose();
});
test('camera snapshot restores exact pose, orthographic scale and orbit anchor after reopening',()=>{
for(const projection of ['orthographic','perspective']){
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection(projection);f.c.view([1,1,1]);
const stored={...f.c.snapshot(),clip:[null,77]};f.c.dispose();
const next=fixture();next.c.restore(JSON.parse(JSON.stringify(stored)));
assert.deepEqual(next.c.snapshot(),{position:stored.position,quaternion:stored.quaternion,anchor:stored.anchor,projection,span:stored.span});
const old=next.c.snapshot();next.c.resize(1400,800);
assert.deepEqual(next.c.snapshot(),old);next.c.dispose();
}
});
@@ -3,10 +3,12 @@ import {readFileSync} from 'node:fs';
import {test} from 'node:test';
import ts from 'typescript';
import {PerspectiveCamera,Vector3} from 'three';
async function source(name){
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace('from "three"',`from "${import.meta.resolve('three')}"`);
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
function moduleUrl(url){
const code=ts.transpileModule(readFileSync(url,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
.replace(/from "([^"]+)"/g,(_,name)=>`from "${name.startsWith('.')?moduleUrl(new URL(name+'.ts',url)):import.meta.resolve(name)}"`);
return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`;
}
async function source(name){return import(moduleUrl(new URL(`../src/core/simulation/${name}.ts`,import.meta.url)));}
const {panCamera,orbitCamera,navigationDepth}=await source('editorNavigation');
const {editWaypoints,waypointEditing,waypointShortcut}=await source('waypointEditing');
const {streamRecovery}=await source('streamRecovery');
@@ -82,3 +84,11 @@ test('catalog discovery of a run cannot claim an idle or historical viewer',()=>
assert.equal(viewedAiRun(catalog,'forest','new'),live);
assert.equal(viewedAiRun(catalog,'bamboo','new'),undefined);
});
test('cube preferences migrate without changing older settings and validate saved presentation',()=>{
const p=normalizePlannerPreferences({pivot:{pixels:125},cube:{size:500,face:'red',opacity:-1,edgeOpacity:-2,text:'#123456'}});
assert.equal(p.pivot.pixels,125);assert.equal(p.cube.size,160);assert.equal(p.cube.face,'#292929');assert.equal(p.cube.opacity,.2);assert.equal(p.cube.text,'#123456');
assert.equal(normalizePlannerPreferences({}).cube.size,66);
assert.equal(p.cube.edgeOpacity,0);assert.equal(normalizePlannerPreferences({}).cube.edgeOpacity,1);
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(p))),p);
});
@@ -0,0 +1,46 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
import {PerspectiveCamera,Vector3} from 'three';
import {Camera,GraphNode,ASPECT_MANUAL} from 'playcanvas';
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
function moduleUrl(p){return url(ts.transpileModule(readFileSync(p,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace(/from "([^"]+)"/g,(_,n)=>`from "${n.startsWith('.')?moduleUrl(new URL(n+'.ts',p)):import.meta.resolve(n)}"`));}
const projection=moduleUrl(new URL('../src/core/simulation/editorProjection.ts',import.meta.url));
const coordinates=moduleUrl(new URL('../src/core/simulation/aiEditorCoordinates.ts',import.meta.url));
const drag=moduleUrl(new URL('../src/core/simulation/waypointDrag.ts',import.meta.url));
const {switchProjection}=await import(projection),{toEditor}=await import(coordinates);
// Execute the real runtime methods against the real PlayCanvas camera math, without a GPU/app.
const source=readFileSync(new URL('../src/components/simulation/AiEditorRuntime.ts',import.meta.url),'utf8');
const ast=ts.createSourceFile('runtime.ts',source,ts.ScriptTarget.Latest,true);
const cls=ast.statements.find(s=>ts.isClassDeclaration(s));
const names=new Set(['syncCamera','project','projectSemantic','moveSemantic','semanticGizmo','semanticSegmentParameter']);
const methods=cls.members.filter(m=>names.has(m.name?.getText(ast))).map(m=>m.getText(ast)).join('\n');
const actual=`import {Vec3,PROJECTION_ORTHOGRAPHIC,PROJECTION_PERSPECTIVE} from "${import.meta.resolve('playcanvas')}";import {isOrthographic,screenSpan} from "${projection}";import {toEditor,toMission} from "${coordinates}";import {dragWaypoint} from "${drag}";export class Runtime {${methods}}`;
const {Runtime}=await import(url(ts.transpileModule(actual,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText));
function fixture(mode){
let c=new PerspectiveCamera(60,1.5,.05,3000);c.position.set(7,12,20);c.lookAt(0,0,0);c.updateMatrixWorld();
c=switchProjection(c,mode,1.5,c.position.length());
const pc=new Camera(),node=new GraphNode();pc.node=node;pc.aspectRatioMode=ASPECT_MANUAL;pc.aspectRatio=1.5;pc.fov=60;pc.nearClip=.05;pc.farClip=3000;
node.camera={get projection(){return pc.projection;},set projection(v){pc.projection=v;},get orthoHeight(){return pc.orthoHeight;},set orthoHeight(v){pc.orthoHeight=v;},worldToScreen:p=>pc.worldToScreen(p,900,600),screenToWorld:(x,y,z)=>pc.screenToWorld(x,y,z,900,600)};
const r=new Runtime();Object.assign(r,{camera:node,controls:{camera:c},canvas:{clientWidth:900,clientHeight:600},clip:Infinity,clipFloor:-Infinity,preferences:{pivot:{pixels:100}}});r.syncCamera();return {r,c,pc};
}
for(const mode of ['orthographic','perspective']){
test(`${mode}: render and overlay projection agree; axis/plane dragging lands under cursor`,()=>{
const {r,c}=fixture(mode),a=[1,2,0];
for(const [axis,b] of [['x',[3,2,0]],['y',[1,4,0]],['z',[1,2,3]],['xy',[3,4,0]],['xz',[3,2,3]],['yz',[1,4,3]]]){
const pixel=r.projectSemantic(b),q=new Vector3(...toEditor(b)).project(c);
assert.ok(Math.abs(pixel[0]-(q.x+1)/2)<1e-6);assert.ok(Math.abs(pixel[1]-(1-q.y)/2)<1e-6);
const moved=r.moveSemantic(a,...pixel,axis);assert.ok(moved);moved.forEach((v,k)=>assert.ok(Math.abs(v-b[k])<2e-4,`${axis} ${v} != ${b[k]}`));
}
});
test(`${mode}: inserted point on a sloping segment matches the pixel interpolation`,()=>{
const {r}=fixture(mode),a=[-3,-2,0],b=[4,5,4],pa=r.projectSemantic(a),pb=r.projectSemantic(b);
for(const u of [.1,.4,.8]){const t=r.semanticSegmentParameter(a,b,u),p=r.projectSemantic(a.map((v,k)=>v+(b[k]-v)*t));p.forEach((v,k)=>assert.ok(Math.abs(v-(pa[k]+(pb[k]-pa[k])*u))<1e-6));}
});
}
test('orthographic gizmo keeps its pixel size at different depths; clipping still applies',()=>{
const {r}=fixture('orthographic');assert.equal(r.semanticGizmo([0,0,0]).length,r.semanticGizmo([0,0,10]).length);
r.clip=2;r.clipFloor=-1;assert.equal(r.projectSemantic([0,0,3]),null);assert.equal(r.projectSemantic([0,0,-2]),null);
const pixel=r.projectSemantic([1,2,0]);assert.ok(r.moveSemantic([1,2,0],...pixel,'xy'));
});
@@ -0,0 +1,21 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,Terrain;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({EditorTerrain:Terrain}=await server.ssrLoadModule('/src/components/simulation/EditorTerrain.ts'));
});
after(async()=>{await server?.close();});
test('picking and ground snapping cannot select surfaces hidden by either plane',()=>{
const terrain=Object.create(Terrain.prototype);
const hit=(y,distance,normal=1)=>({point:{y},distance,face:{normal:{y:normal}}});
const lower=hit(-3,1), middle=hit(2,3), upper=hit(9,2), wall=hit(1,1.5,0);
terrain.trees=[{raycast:()=>[lower,middle,upper,wall]}];terrain.bounds={max:{y:10}};
assert.equal(terrain.pick([0,20,0],[0,-1,0],5,0),middle.point);
assert.equal(terrain.pickSurface([0,20,0],[0,-1,0],5,false,0),wall.point);
assert.equal(terrain.ground(0,0,-3,5,0),middle.point);
assert.equal(terrain.pick([0,20,0],[0,-1,0],1,0),null);
assert.equal(terrain.pick([0,20,0],[0,-1,0]),lower.point);
assert.equal(terrain.ground(0,0,-3),lower.point);
});
@@ -0,0 +1,73 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const built=await build({entryPoints:[new URL('../src/core/simulation/infrastructureAnalysis.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'analysis-fixture',setup(b){
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
b.onResolve({filter:/^\.\/urbanMap$/},()=>({path:'map',namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},args=>({contents:args.path==='react'?`
export const useRef=v=>({current:v});
export const useState=v=>{const index=globalThis.analysisFixture.index++;return [index===0?globalThis.analysisFixture.seed:v,value=>globalThis.analysisFixture.writes.push({index,value})];};
export const useEffect=f=>globalThis.analysisFixture.effects.push(f);
`:`export const loadUrbanMap=async()=>{throw new Error('Unexpected stale map load');};`}));
}}]});
const {useInfrastructureAnalysis,analysisProgressLabel}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64'));
const flush=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
const response=value=>({ok:true,json:async()=>value});
const queued={key:'a'.repeat(64),status:'queued',phase:'queued',completed:0,total:0,error:null};
async function fixture(run,seed=null){
const original=Object.fromEntries(['analysisFixture','fetch','setTimeout','clearTimeout'].map(k=>[k,globalThis[k]]));
const state={index:0,seed,writes:[],effects:[]},calls=[],timers=[],get=deferred(),post=deferred();
globalThis.analysisFixture=state;
globalThis.setTimeout=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearTimeout=()=>{};
globalThis.fetch=async(url,init={})=>{calls.push({url,init});return init.method==='POST'?post.promise:get.promise;};
const hook=useInfrastructureAnalysis('fixture','b'.repeat(64),()=>{throw new Error('Unexpected stale map callback');});
const cleanups=state.effects.map(f=>f());let cleaned=false;
const clean=()=>{if(!cleaned){cleaned=true;cleanups.forEach(f=>f?.());}};
try{await run({hook,calls,get,post,state,timers,clean});}
finally{clean();await flush();for(const [key,value]of Object.entries(original)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
}
test('twenty immediate calculation clicks make one request before React rerenders',async()=>fixture(async f=>{
const attempts=Array.from({length:20},()=>f.hook.start(true));
assert.equal(f.calls.filter(c=>c.init.method==='POST').length,1);
f.post.resolve(response(queued));await Promise.all(attempts);f.get.resolve(response(null));await flush();
assert.equal(f.state.writes.filter(w=>w.index===0).at(-1).value.key,queued.key);
}));
test('a poll predating calculation cannot replace the acknowledged queued job',async()=>fixture(async f=>{
const starting=f.hook.start(true);f.post.resolve(response(queued));await starting;
f.get.resolve(response({...queued,status:'ready'}));await flush();
assert.deepEqual(f.state.writes.filter(w=>w.index===0).at(-1).value,queued);
}));
test('polling pauses during cancellation and late replies cannot undo unmount',async()=>fixture(async f=>{
f.get.resolve(response({...queued,status:'running'}));await flush();
const cancelling=f.hook.cancel();const before=f.calls.length;
await f.timers.at(-1).f();assert.equal(f.calls.length,before);
assert.match(f.calls.at(-1).url,new RegExp('/'+queued.key+'/cancel$'));
f.clean();const writes=f.state.writes.length;
f.post.resolve(response({...queued,status:'cancelled'}));await cancelling;await flush();
assert.equal(f.state.writes.length,writes);
}, {...queued,status:'running'}));
test('retry after an unknown network outcome keeps the same request identity',async()=>fixture(async f=>{
f.post.resolve({ok:false,json:async()=>({detail:'Try again'})});
await f.hook.start(true);await f.hook.start(true);
const bodies=f.calls.filter(c=>c.init.method==='POST').map(c=>JSON.parse(c.init.body));
assert.equal(bodies.length,2);assert.equal(bodies[0].request_id,bodies[1].request_id);
f.get.resolve(response(null));await flush();
}));
test('an observed terminal generation acknowledges a lost response before the next retry',async()=>fixture(async f=>{
f.post.resolve({ok:false,json:async()=>({detail:'Response lost'})});
await f.hook.start(true);
const first=JSON.parse(f.calls.find(c=>c.init.method==='POST').init.body).request_id;
f.get.resolve(response({...queued,status:'failed',request_id:first}));await flush();
await f.timers.at(-1).f();await flush();
await f.hook.start(true);
const second=JSON.parse(f.calls.filter(c=>c.init.method==='POST').at(-1).init.body).request_id;
assert.notEqual(second,first,'a new attempt must not return the old terminal generation');
}));
test('stage counts are explicit and lost connection never retains an ETA',()=>{
const job={...queued,status:'running',progress:{label:'Построение видов сцены',stage:2,stages:90,eta_seconds:600,stale:false}};
assert.equal(analysisProgressLabel(job),'Построение видов сцены · этап 2 из 90 · ≈ 10 мин осталось');
assert.equal(analysisProgressLabel({...job,progress:{...job.progress,stale:true,eta_seconds:null}}),'Связь с расчётом потеряна · этап 2 из 90');
});
@@ -0,0 +1,17 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {test} from 'node:test';
import ts from 'typescript';
const source=readFileSync(new URL('../src/components/simulation/localScene.ts',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
.replace('from "playcanvas"',`from "${import.meta.resolve('playcanvas')}"`)
.replace(/import \{ editorAssetUrl \} from [^;]+;/,'const editorAssetUrl=(key,name)=>`/cache/${key}/${name}`;');
const {localScene}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
test('visual-only project never substitutes a nonexistent editor collider URL',()=>{
const cache={key:'fixture',world:{world_id:'scan'},local_scene:{visual_url:'/scan/lod-meta.json',
collision_url:null,visual_rotation:[180,0,0],collision_rotation:[0,0,0]}};
assert.deepEqual(localScene(cache).collision,{meshUrl:null,available:false});
assert.equal(localScene(cache).visual.streamedSogUrl,'/scan/lod-meta.json');
cache.local_scene.collision_url='/scan/collision.glb';
assert.deepEqual(localScene(cache).collision,{meshUrl:'/scan/collision.glb',available:true});
});
@@ -0,0 +1,37 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../src/core/simulation/plannerActions.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
const {plannerActions}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
const points=[{id:'start',position:[0,0,0]},{id:'finish',position:[3,1,0]}];
const route={sha256:'route-v1'};
const plan={points,editor_cache_key:'scene-v1',robot_sha256:'robot-v1',prepared_route:route};
const input={draft:{cache:{key:'scene-v1'},points},robot:{sha256:'robot-v1'},plan:undefined,routeRequired:true,
route:null,routeKey:null,busy:false,runtimeAvailable:true,inferenceReady:true,activeRun:false};
const state=changes=>plannerActions({...input,...changes});
const none={save:false,prepare:false,launch:false};
test('no draft, robot, start or finish means no route actions, even for legacy scenes',()=>{
assert.deepEqual(state({draft:null}),none);
assert.deepEqual(state({robot:undefined}),none);
for(const points of [[],input.draft.points.slice(0,1)])for(const routeRequired of [true,false])
assert.deepEqual(state({draft:{...input.draft,points},routeRequired}),none);
});
test('two points offer calculation; an admitted route offers save and launch',()=>{
assert.deepEqual(state({}),{save:false,prepare:true,launch:false});
assert.deepEqual(state({route,routeKey:'key'}),{save:true,prepare:false,launch:true});
assert.equal(state({route,routeKey:null}).launch,false);
});
test('loading, saving and undoing to the saved task hide save without hiding launch',()=>{
const saved={route,routeKey:'key',plan};
assert.deepEqual(state(saved),{save:false,prepare:false,launch:true});
const changed=structuredClone(points);changed[1].position[2]=.2;
assert.deepEqual(state({...saved,draft:{...input.draft,points:changed},route:null,routeKey:null}),{save:false,prepare:true,launch:false});
assert.equal(state(saved).save,false);
assert.equal(state({...saved,route:{sha256:'route-v2'}}).save,true);
});
test('busy commands hide other actions; offline or occupied Worker prevents launch',()=>{
assert.deepEqual(state({route,routeKey:'key',busy:true}),none);
assert.deepEqual(state({runtimeAvailable:false}),none);
for(const condition of [{runtimeAvailable:false},{inferenceReady:false},{activeRun:true}])
assert.deepEqual(state({route,routeKey:'key',...condition}),{save:true,prepare:false,launch:false});
});
@@ -49,3 +49,30 @@ test('world-size centroid preference migrates to independent pixel size; emissio
assert.ok(Math.abs(pixels-14)<1e-8);
}
});
test('toolbar preferences migrate old storage and preserve all four placements and valid sizes',()=>{
assert.deepEqual(normalizePlannerPreferences({pivot:{}}).toolbar,DEFAULT_PLANNER_PREFERENCES.toolbar);
for(const placement of ['left','right','top','bottom']){
const p=normalizePlannerPreferences({toolbar:{placement,minSize:40,maxSize:20,lensCount:4,hideDelay:500,gap:3,autoHide:false}}).toolbar;
assert.equal(p.placement,placement);assert.equal(p.maxSize,40);assert.equal(p.lensCount,5);assert.equal(p.hideDelay,500);assert.equal(p.autoHide,false);
}
const p=normalizePlannerPreferences({toolbar:{placement:'oops',hideDelay:Infinity,minSize:NaN,background:'url(x)'}}).toolbar;
assert.deepEqual(p,DEFAULT_PLANNER_PREFERENCES.toolbar);
});
const {normalizeSimulationLayout,DEFAULT_SIMULATION_LAYOUT,normalizeSceneView}=await source('simulationLayout');
test('layout keeps global modes/projection/layers while transient editing state cannot enter storage',()=>{
for(const mode of ['view','semantic','planning'])for(const projection of ['orthographic','perspective']){
const value={...DEFAULT_SIMULATION_LAYOUT,mode,projection,layers:['road_boundary','road_marking'],visible:{model:true,user:true},axis:'xz'};
assert.deepEqual(normalizeSimulationLayout(JSON.parse(JSON.stringify(value))),value);
}
assert.deepEqual(normalizeSimulationLayout({mode:'oops',projection:'oops'}),DEFAULT_SIMULATION_LAYOUT);
assert.deepEqual(normalizeSimulationLayout({layers:[]}).layers,[]);
assert.deepEqual(normalizeSimulationLayout({layers:['road_boundary','oops','road_boundary'],selection:['unsafe'],operations:[{}]}).layers,['road_boundary']);
assert.equal('operations' in normalizeSimulationLayout({operations:[{}]}),false);
});
test('camera snapshots preserve pose and unbounded slice, and reject malformed storage',()=>{
const view={position:[1,2,3],quaternion:[0,0,0,1],anchor:[4,5,6],projection:'orthographic',span:20,clip:[null,500]};
assert.deepEqual(normalizeSceneView(JSON.parse(JSON.stringify(view))),view);
for(const bad of [{...view,quaternion:[1,1,1,1]},{...view,clip:[10,1]},{...view,span:Infinity},{...view,position:[NaN,0,0]}])assert.equal(normalizeSceneView(bad),null);
});
@@ -0,0 +1,18 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../src/core/simulation/sceneClip.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
const {sceneClipBounds,sceneClipValue}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
test('Gaussian clipping covers visual and collision extents with at least a 500 m ceiling',()=>{
assert.deepEqual(sceneClipBounds([-51.4623,210.4],[-30,77.72065000000002]),[-52,500]);
assert.deepEqual(sceneClipBounds([-60.3,912.7],null),[-61,913]);
assert.deepEqual(sceneClipBounds([5,80],[-75.2,1000.1]),[-76,1001]);
});
test('native rounded maximum disables clipping and returning to a finite height clips again',()=>{
const oldBounds=[-51.4623,77.72065000000002];
assert.ok(77.72065 < oldBounds[1]);
assert.equal(sceneClipValue(77.72065,oldBounds),Infinity);
assert.equal(sceneClipValue(76.4288206,oldBounds),76.4288206);
const bounds=sceneClipBounds([-51.4623,210.4],oldBounds);
assert.deepEqual([40,500,40,500].map(v=>sceneClipValue(v,bounds)),[40,Infinity,40,Infinity]);
});
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import ts from "typescript";
const moduleURL=(s)=>`data:text/javascript;base64,${Buffer.from(ts.transpileModule(s,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText).toString("base64")}`;
const read=n=>readFileSync(new URL(`../src/core/simulation/${n}.ts`,import.meta.url),"utf8");
const policy=moduleURL(read("semanticFeaturePolicy"));
const vector=moduleURL(read("semanticVector").replace('"./semanticFeaturePolicy"',JSON.stringify(policy)));
const {regionOperation}=await import(moduleURL(read("semanticArea").replace('"./semanticVector"',JSON.stringify(vector)).replace('"polygon-clipping"',JSON.stringify(import.meta.resolve("polygon-clipping")))));
const {curveControlScale,curveControlPoint,moveCurveControl}=await import(moduleURL(read("semanticCurveControls")));
const ring=(x,y,w,h,z=2)=>[[x,y,z],[x+w,y,z],[x+w,y+h,z],[x,y+h,z],[x,y,z]];
const area={id:"area",properties:{class:"pedestrian_area"},geometry:{type:"Polygon",coordinates:[ring(0,0,10,10),ring(2,2,2,2)]}};
const size=r=>Math.abs(r.slice(1).reduce((a,p,i)=>a+r[i][0]*p[1]-p[0]*r[i][1],0)/2);
const total=polys=>polys.reduce((s,p)=>s+size(p[0])-p.slice(1).reduce((s,r)=>s+size(r),0),0);
test("region fill closes existing holes and cut splits without losing parts or source heights",()=>{
const original=JSON.stringify(area);
const filled=regionOperation(area,ring(1,1,4,4),"union");assert.equal(total(filled.polygons),100);assert.equal(filled.polygons[0].length,1);
const split=regionOperation(area,ring(5,-1,1,12),"difference");assert.equal(split.polygons.length,2);assert.equal(total(split.polygons),86);
assert.equal(JSON.stringify(area),original);assert.ok(split.polygons.flat(2).every(p=>p[2]===2));
assert.throws(()=>regionOperation(undefined,ring(0,0,1,1),"difference"));
assert.equal(total(regionOperation(undefined,ring(0,0,1,1),"union").polygons),1);
});
test("curve handles remain visible on dense contours without altering physical coordinates; drag has no jump",()=>{
const nodes=[0,1,2].map(i=>({point:[i*.03,0,2],incoming:[-.01,0],outgoing:[.01,0]}));
const input=JSON.stringify(nodes),project=p=>p.map(v=>v*10),scale=curveControlScale(nodes,1,false,project);
const p=curveControlPoint(nodes[1],"outgoing",scale);
assert.ok(Math.abs((p[0]-.03)*10-36)<1e-9);assert.equal(JSON.stringify(nodes),input);
assert.deepEqual(moveCurveControl(nodes[1].outgoing,[9,8],[9,8],scale),nodes[1].outgoing);
const shifted=moveCurveControl(nodes[1].outgoing,[9,8],[10,10],scale);
assert.ok(Math.abs((shifted[0]-.01)*scale-1)<1e-9);assert.equal(shifted[1]*scale,2);
});
@@ -0,0 +1,212 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import ts from "typescript";
const policyCode=ts.transpileModule(readFileSync(new URL("../src/core/simulation/semanticFeaturePolicy.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const policyUrl=`data:text/javascript;base64,${Buffer.from(policyCode).toString("base64")}`;
const policy=s=>s.replaceAll('"./semanticFeaturePolicy"',JSON.stringify(policyUrl));
const vectorCode=ts.transpileModule(policy(readFileSync(new URL("../src/core/simulation/semanticVector.ts",import.meta.url),"utf8")),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const vectorUrl=`data:text/javascript;base64,${Buffer.from(vectorCode).toString("base64")}`;
const source=readFileSync(new URL("../src/core/simulation/semanticEdits.ts",import.meta.url),"utf8").replace(/import MARKING_TEMPLATES from [^;]+;/, `const MARKING_TEMPLATES=${readFileSync(new URL("../../../src/k1link/simulation/ai_polygon/marking-templates.json",import.meta.url),"utf8")};`);
const code=ts.transpileModule(policy(source).replace('from "./semanticVector"',`from "${vectorUrl}"`),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {semanticDraft,commitSemantic,undoSemantic,redoSemantic,segmentHit,semanticOperation}=await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
const feature=(id,coordinates)=>({id,properties:{class:"curb",authority:"observation-only",route_permission:"unassigned"},geometry:{type:"LineString",coordinates}});
const map={schema_version:"missioncore.urban-map/v3",features:[feature("a",[[0,0,2],[2,0,2],[4,1,2]]),feature("b",[[0,5,2],[4,5,2]])]};
const vertex={feature_id:"a",path:0,index:1};
test("gesture history restores exact input and redo; no-op has no new revision",()=>{
const s=semanticDraft(map);
assert.strictEqual(commitSemantic(s,{...vertex,kind:"move",position:[2,0,2]}),s);
const moved=commitSemantic(s,{...vertex,kind:"move",position:[2,.2,2]});
assert.equal(moved.operations.length,1);
assert.strictEqual(moved.map.features[1],map.features[1]);
const undone=undoSemantic(moved);
assert.strictEqual(undone.map,map);
assert.deepEqual(redoSemantic(undone).map,moved.map);
assert.deepEqual(map.features[0].geometry.coordinates[1],[2,0,2]);
});
test("insertion only on chosen segment preserves existing coordinates; no arbitrary height",()=>{
const s=commitSemantic(semanticDraft(map),{...vertex,index:0,kind:"insert",t:.25});
assert.deepEqual(s.map.features[0].geometry.coordinates,[[0,0,2],[.5,0,2],[2,0,2],[4,1,2]]);
assert.throws(()=>commitSemantic(s,{...vertex,kind:"insert",t:2}));
assert.throws(()=>commitSemantic(s,{...vertex,kind:"move",position:[2,0,3]}));
const restored=commitSemantic(s,{...vertex,kind:"delete"});
assert.deepEqual(restored.map.features[0].geometry,map.features[0].geometry);
});
test("closed polygon first vertex moves and closure follows; minimum geometry retained",()=>{
const base={...map,features:[{...map.features[0],geometry:{type:"Polygon",coordinates:[[[0,0,2],[2,0,2],[0,2,2],[0,0,2]]]}}]};
const s=commitSemantic(semanticDraft(base),{...vertex,index:0,kind:"move",position:[-.1,0,2]});
assert.deepEqual(s.map.features[0].geometry.coordinates[0].at(-1),[-.1,0,2]);
assert.throws(()=>commitSemantic(s,{...vertex,kind:"delete"}));
});
test("hit testing uses CSS coordinates and handles degenerate projected segment",()=>{
assert.deepEqual(segmentHit([50,5],[0,0],[100,0]),{t:.5,distance:5});
assert.deepEqual(segmentHit([0,3],[0,0],[0,0]),{t:0,distance:3});
});
test("marking placement, group transform and undo preserve rigid shape and height",()=>{
const op={kind:"place",feature_id:"user-test-1234567890",template_id:"zebra",position:[3,4,2],surface:"gaussian-visual"};
const placed=commitSemantic(semanticDraft(map),op);
assert.equal(placed.map.features.length,8);
const transform={kind:"transform",feature_id:op.feature_id+"-2",delta:[.5,.25],angle:.5};
const moved=commitSemantic(placed,transform);
assert.equal(moved.map.features[1],map.features[1]);
assert.deepEqual(undoSemantic(moved).map,placed.map);
assert.deepEqual(redoSemantic(undoSemantic(moved)).map,moved.map);
assert.strictEqual(semanticOperation(placed.map,{...transform,delta:[0,0],angle:0}),placed.map);
assert.throws(()=>semanticOperation(placed.map,{kind:"delete",feature_id:op.feature_id,path:0,index:1}));
const removed=semanticOperation(moved.map,{kind:"remove",feature_id:op.feature_id});
assert.equal(removed.features.filter(f=>f.properties.review_status==="rejected").length,6);
});
const moduleUrl=`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`;
const pickingSource=readFileSync(new URL("../src/core/simulation/semanticPicking.ts",import.meta.url),"utf8").replace('from "./semanticEdits"',`from "${moduleUrl}"`);
const pickingCode=ts.transpileModule(pickingSource.replace('from "./semanticVector"',`from "${vectorUrl}"`),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {semanticHits,semanticDrag}=await import(`data:text/javascript;base64,${Buffer.from(pickingCode).toString("base64")}`);
test("only selected contour vertices are pickable; rigid markings never expose vertices",()=>{
const unselected=semanticHits(map,"curb",[2,0],p=>p,true);
assert.ok(unselected.length);assert.ok(unselected.every(h=>!h.point));
const hit=semanticHits(map,"curb",[2,0],p=>p,true,["b"]);
assert.ok(hit.some(h=>h.vertex.feature_id==="b"&&h.point));
assert.ok(hit.filter(h=>h.point).every(h=>h.vertex.feature_id==="b"));
const placed=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-test-1234567890",template_id:"letter_A",position:[0,0,0],surface:"gaussian-visual"});
assert.ok(semanticHits(placed,"road_marking",[0,0],p=>p,true).length);
assert.ok(semanticHits(placed,"road_marking",[0,0],p=>p,true).every(h=>!h.point));
});
test("pivot grab offset: exact no-op, selected axis only, immutable elevation",()=>{
const p=[329.66974637628715,-46.85091895999632,2.5206789941457233],start=[333.1234,-41.9876,2.5];
assert.deepEqual(semanticDrag(p,start,start,"xy"),p);
assert.deepEqual(semanticDrag(p,start,[start[0]+.5,start[1]+9,800],"x"),[p[0]+.5,p[1],p[2]]);
assert.deepEqual(semanticDrag(p,start,[start[0]+9,start[1]+.5,800],"y"),[p[0],p[1]+.5,p[2]]);
});
const {knots,curvePoint}=await import(vectorUrl);
test("curves persist control points, exact heights and grouped delete is one undo",()=>{
const f={id:"road",properties:{class:"road_boundary"},geometry:{type:"LineString",coordinates:[[0,0,2.1],[2,0,2.2],[4,0,2.3],[6,0,2.4],[8,0,2.5]]}};
const base={...map,features:[f]},v={feature_id:"road",path:0,index:1};
const curved=commitSemantic(semanticDraft(base),{kind:"curve",...v,incoming:[-.6,-.3],outgoing:[.6,.3]});
assert.equal(knots(curved.map.features[0],0).length,5);
assert.equal(curved.map.features[0].geometry.coordinates.length,35);
assert.equal(knots(curved.map.features[0],0)[1].point[2],2.2);
const removed=commitSemantic(curved,{kind:"delete_vertices",vertices:[v,{...v,index:2}]});
assert.equal(knots(removed.map.features[0],0).length,3);
assert.deepEqual(undoSemantic(removed).map,curved.map);
assert.deepEqual(redoSemantic(undoSemantic(removed)).map,removed.map);
assert.throws(()=>semanticOperation(base,{kind:"delete_vertices",vertices:[0,1,2,3].map(index=>({...v,index}))}));
assert.equal(semanticOperation(base,{kind:"delete_vertices",vertices:[0,1,2,3,4].map(index=>({...v,index}))}).features[0].properties.review_status,"rejected");
});
test("curve insertion uses De Casteljau; unchanged cubic is geometrically identical",()=>{
const base={...map,features:[{id:"r",properties:{class:"road_boundary"},geometry:{type:"LineString",coordinates:[[0,0,1],[4,0,3]]}}]};
let c=semanticOperation(base,{kind:"curve",feature_id:"r",path:0,index:0,incoming:[0,0],outgoing:[1,2]});
c=semanticOperation(c,{kind:"curve",feature_id:"r",path:0,index:1,incoming:[-1,2],outgoing:[0,0]});
const before=knots(c.features[0],0),after=knots(semanticOperation(c,{kind:"insert",feature_id:"r",path:0,index:0,t:.4}).features[0],0);
for(let i=0;i<=40;i++){const t=i/40,a=curvePoint(before[0],before[1],t),b=t<=.4?curvePoint(after[0],after[1],t/.4):curvePoint(after[1],after[2],(t-.4)/.6);assert.ok(a.every((v,k)=>Math.abs(v-b[k])<1e-12));}
});
test("explicit Z translation is rigid and planar translation cannot change Z",()=>{
const base=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-z-1234567890123456",template_id:"zebra",position:[0,0,2],surface:"gaussian-visual"});
const op={kind:"translate",feature_id:base.features[0].id,vertices:[],axis:"z",delta:[0,0,.3]};
const moved=semanticOperation(base,op);
assert.ok(moved.features.every(f=>f.geometry.coordinates.flat().every(p=>p[2]===2.3)));
assert.throws(()=>semanticOperation(base,{...op,axis:"xy"}));
assert.strictEqual(semanticOperation(base,{...op,delta:[0,0,0]}),base);
});
test("Shift duplicate extends either end, inserts inside, preserves source knots and is one undo",()=>{
for(const [index,delta,inserted] of [[0,[-1,0,0],0],[1,[1,0,0],2],[2,[1,0,0],3]]){
const before=semanticDraft(map),op={kind:"duplicate_vertex",feature_id:"a",path:0,index,axis:"x",delta};
const result=commitSemantic(before,op),nodes=knots(result.map.features[0],0),p=map.features[0].geometry.coordinates[index];
assert.equal(nodes.length,4);assert.deepEqual(nodes[inserted].point,p.map((v,k)=>v+delta[k]));
assert.deepEqual(nodes.filter((_,i)=>i!==inserted).map(n=>n.point),map.features[0].geometry.coordinates);
assert.equal(result.operations.length,1);assert.strictEqual(undoSemantic(result).map,map);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
assert.strictEqual(result.map.features[1],map.features[1]);
assert.strictEqual(commitSemantic(before,{...op,delta:[0,0,0]}),before);
}
});
test("duplicate preserves cubic handles, source coordinates and polygon closure",()=>{
const polygon={...map.features[0],geometry:{type:"Polygon",coordinates:[[[0,0,2],[4,0,2],[4,4,2],[0,4,2],[0,0,2]]]}};
const base=semanticOperation({...map,features:[polygon]},{kind:"curve",feature_id:"a",path:0,index:1,incoming:[-.3,0],outgoing:[0,.3]});
const source=knots(base.features[0],0),before=JSON.stringify(base);
const result=semanticOperation(base,{kind:"duplicate_vertex",feature_id:"a",path:0,index:1,axis:"xy",delta:[.5,.5,0]}),next=knots(result.features[0],0);
assert.deepEqual(next[1],source[1]);assert.deepEqual(next[2].incoming,source[1].incoming);assert.deepEqual(next[2].outgoing,source[1].outgoing);
assert.deepEqual(result.features[0].geometry.coordinates[0][0],result.features[0].geometry.coordinates[0].at(-1));assert.equal(JSON.stringify(base),before);
assert.throws(()=>semanticOperation(base,{kind:"duplicate_vertex",feature_id:"a",path:0,index:1,axis:"x",delta:[0,1,0]}));
});
const strip=()=>({id:"strip",properties:{class:"road_marking",subtype:"linear_marking",authority:"observation-only",route_permission:"unassigned"},geometry:{type:"Polygon",coordinates:[[[0,0,2],[4,0,2],[4,.2,2],[0,.2,2],[0,0,2]]]}});
test("explicit line strips expose editable corners; two end vertices stretch while legacy translation stays rigid",()=>{
const f=strip(),base={...map,features:[f]},vertices=[1,2].map(index=>({feature_id:f.id,path:0,index}));
const op={kind:"translate_vertices",feature_id:f.id,vertices,axis:"x",delta:[2,0,0]},result=commitSemantic(semanticDraft(base),op);
assert.deepEqual(result.map.features[0].geometry.coordinates[0],[[0,0,2],[6,0,2],[6,.2,2],[0,.2,2],[0,0,2]]);
assert.strictEqual(undoSemantic(result).map,base);
const legacy=semanticOperation(base,{...op,kind:"translate"});assert.deepEqual(legacy.features[0].geometry.coordinates[0][0],[2,0,2]);
for(const subtype of [undefined,"letter_A","straight_arrow","bicycle","crosswalk"]){
const symbol={...f,properties:{...f.properties,subtype}},m={...base,features:[symbol]};
assert.throws(()=>semanticOperation(m,op));assert.throws(()=>semanticOperation(m,{kind:"duplicate_vertex",feature_id:f.id,path:0,index:1,axis:"x",delta:[1,0,0]}));
}
});
test("new linear marking is editable; whole-object copies retain shape, curves and independent identity",()=>{
const placed=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-linear-123456789012",template_id:"linear_marking",position:[2,3,4],surface:"gaussian-visual"});
const f=placed.features[0],v={feature_id:f.id,path:0,index:1};
assert.equal(f.properties.subtype,"linear_marking");assert.equal(f.properties.semantic_element_id,undefined);
const edited=semanticOperation(placed,{kind:"translate_vertices",feature_id:f.id,vertices:[v,{...v,index:2}],axis:"x",delta:[2,0,0]});
const curved=semanticOperation(edited,{kind:"curve",...v,incoming:[-.2,0],outgoing:[0,.02]});
const snapshot=JSON.stringify(curved),op={kind:"duplicate_marking",feature_id:f.id,new_feature_id:"user-copy-1234567890123456",axis:"y",delta:[0,2,0]};
const d=commitSemantic(semanticDraft(curved),op),copy=d.map.features[1];
assert.equal(JSON.stringify(curved),snapshot);assert.strictEqual(d.map.features[0],curved.features[0]);
assert.equal(copy.id,op.new_feature_id);assert.equal(copy.properties.semantic_element_id,undefined);
assert.deepEqual(knots(copy,0).map(n=>n.point),knots(curved.features[0],0).map(n=>[n.point[0],n.point[1]+2,n.point[2]]));
assert.equal(copy.properties.height_source,"human-copy-unverified");assert.strictEqual(undoSemantic(d).map,curved);
assert.throws(()=>semanticOperation(d.map,op));assert.strictEqual(semanticOperation(curved,{...op,delta:[0,0,0]}),curved);
const letter=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-letter-123456789012",template_id:"letter_A",position:[0,0,2],surface:"gaussian-visual"});
const copied=semanticOperation(letter,{...op,feature_id:letter.features[0].id});
assert.equal(copied.features.length,2);assert.equal(copied.features[1].properties.semantic_element_id,op.new_feature_id);
assert.throws(()=>semanticOperation(copied,{kind:"curve",feature_id:op.new_feature_id,path:0,index:0,incoming:[1,0],outgoing:[1,0]}));
const selectedHits=semanticHits(placed,"road_marking",[50,30],p=>p.map(v=>v*100),true,f.id);
assert.ok(selectedHits.every(h=>!h.point));
const corners=semanticHits(placed,"road_marking",f.geometry.coordinates[0][0].map(v=>v*100),p=>p.map(v=>v*100),true,f.id);
assert.ok(corners.some(h=>h.point));
});
const {duplicateSide,duplicateIndex}=await import(vectorUrl);
const directionCases=JSON.parse(readFileSync(new URL("../../../tests/fixtures/semantic_duplicate_direction.json",import.meta.url),"utf8"));
for(const c of directionCases)test(`directional Shift insertion: ${c.name}`,()=>{
const nodes=c.points.map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
assert.equal(duplicateSide(nodes,c.index,c.closed,c.delta),c.side);
const geometry=c.closed?{type:"Polygon",coordinates:[[...c.points,c.points[0]]]}:{type:"LineString",coordinates:c.points};
const base={...map,features:[{...feature("a",[]),geometry}]},before=structuredClone(base);
const op={kind:"duplicate_vertex",feature_id:"a",path:0,index:c.index,delta:c.delta,axis:c.delta[2]?"yz":"xy",side:c.side};
const result=commitSemantic(semanticDraft(base),op),slot=c.index+Number(c.side==="after");
assert.equal(duplicateIndex(c.index,c.closed,c.side),slot);
const points=knots(result.map.features[0],0).map(n=>n.point);
const expected=structuredClone(c.points);expected.splice(slot,0,c.points[c.index].map((v,k)=>v+c.delta[k]));
assert.deepEqual(points,expected);assert.deepEqual(base,before);
assert.deepEqual(undoSemantic(result).map,base);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
if(c.closed)assert.deepEqual(result.map.features[0].geometry.coordinates[0][0],result.map.features[0].geometry.coordinates[0].at(-1));
});
test("curve direction follows tangent arms and ignores height",()=>{
const nodes=[{point:[0,10,2],incoming:[0,0],outgoing:[0,0]},{point:[0,0,2],incoming:[-1,0],outgoing:[1,0]},{point:[0,-10,2],incoming:[0,0],outgoing:[0,0]}];
assert.equal(duplicateSide(nodes,1,false,[-1,0,100]),"before");
assert.equal(duplicateSide(nodes,1,false,[1,0,-100]),"after");
});
test('retemplate old recognized letters retains identity and undo restores exact geometry',()=>{
const base={schema_version:'missioncore.urban-map/v3',features:[{id:'recognized-A',properties:{class:'road_marking',subtype:'letter_A'},geometry:{type:'Polygon',coordinates:[[[0,0,1],[1,0,1],[1,1,1],[0,0,1]]]}}]};
const op={kind:'retemplate',feature_id:'recognized-A',template_id:'letter_A_v3',frame:[[20,30,4],[0,1,.1],[-1,0,.2]]};
const draft=commitSemantic(semanticDraft(base),op);
assert.equal(draft.map.features[0].id,'recognized-A');assert.equal(draft.map.features[0].properties.template_id,'letter_A_v3');
assert.equal(draft.map.features[0].geometry.coordinates.length,2);
assert.deepEqual(undoSemantic(draft).map,base);assert.deepEqual(redoSemantic(undoSemantic(draft)).map,draft.map);
assert.throws(()=>semanticOperation(base,{...op,frame:[[0,0,0],[1,0,0],[1,1,0]]}));
});
for(const cls of ["road_boundary","pedestrian_boundary","building_facade","pedestrian_area","sidewalk","road_marking"])test(`Shift insertion uses direction for ${cls} contours`,()=>{
const closed=["pedestrian_area","sidewalk","road_marking"].includes(cls);
const points=closed?[[0,5,2],[0,0,2],[10,-1,2],[10,5,2]]:[[0,.1,2],[10,0,2]];
const index=1,delta=[0,3,0],nodes=points.map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
const side=duplicateSide(nodes,index,closed,delta);assert.equal(side,closed?"before":"after");
const geometry=closed?{type:"Polygon",coordinates:[[...points,points[0]]]}:{type:"LineString",coordinates:points};
const base={...map,features:[{...feature("a",[]),properties:{class:cls,...(cls==="road_marking"?{subtype:"linear_marking"}:{})},geometry}]};
const op={kind:"duplicate_vertex",feature_id:"a",path:0,index,delta,axis:"y",side};
const result=commitSemantic(semanticDraft(base),op),expected=structuredClone(points);
expected.splice(index+Number(side==="after"),0,[points[index][0],points[index][1]+3,points[index][2]]);
assert.deepEqual(knots(result.map.features[0],0).map(n=>n.point),expected);
assert.deepEqual(undoSemantic(result).map,base);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
});
@@ -0,0 +1,193 @@
import assert from 'node:assert/strict';
import {test} from 'node:test';
import {readFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
import ts from 'typescript';
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
const hooks=url('export const useRef=x=>({current:x});export const useState=x=>[x,()=>{}];export const useEffect=f=>{globalThis.cleanups.push(f());};');
const cache=new Map();
function module(p){
p=path.resolve(p);if(cache.has(p))return cache.get(p);
let s=readFileSync(p,'utf8').replace(/import MARKING_TEMPLATES from "([^"]+)";/,(_,file)=>`const MARKING_TEMPLATES=${readFileSync(path.resolve(path.dirname(p),file),'utf8')};`);
s=ts.transpileModule(s,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
s=s.replace(/from "([^"]+)"/g,(_,spec)=>`from ${JSON.stringify(spec==='react'?hooks:spec.startsWith('.')?module(path.resolve(path.dirname(p),spec+'.ts')):import.meta.resolve(spec))}`);
const value=url(s);cache.set(p,value);return value;
}
const root=fileURLToPath(new URL('../src/',import.meta.url));
const {useSemanticGestures}=await import(module(root+'components/simulation/useSemanticGestures.ts'));
const edits=await import(module(root+'core/simulation/semanticEdits.ts'));
const {semanticOperation}=edits;
class Target {
listeners=new Map();capture=new Set();
addEventListener(n,f){this.listeners.set(n,[...(this.listeners.get(n)||[]),f]);}
removeEventListener(n,f){this.listeners.set(n,(this.listeners.get(n)||[]).filter(v=>v!==f));}
emit(n,e){e.preventDefault=()=>{e.defaultPrevented=true;};e.stopImmediatePropagation=()=>{e.stopped=true;};for(const f of this.listeners.get(n)||[]){f(e);if(e.stopped)break;}return e;}
setPointerCapture(i){this.capture.add(i);}hasPointerCapture(i){return this.capture.has(i);}releasePointerCapture(i){this.capture.delete(i);}
}
function setup({marking=false,whole=false}={}){
globalThis.cleanups=[];globalThis.document=new Target();document.querySelector=()=>null;globalThis.window=new Target();
const canvas={clientWidth:100,clientHeight:100,getBoundingClientRect:()=>({left:0,top:0}),focus(){},closest:()=>null};
const viewport=new Target();viewport.querySelector=()=>canvas;
const map={features:[{id:'line',properties:{class:marking?'road_marking':'road_boundary',...(marking?{subtype:'linear_marking'}:{})},geometry:marking?{type:'Polygon',coordinates:[[[0,0,2],[10,0,2],[10,1,2],[0,1,2],[0,0,2]]]}:{type:'LineString',coordinates:[[0,0,2],[10,0,2],[20,0,2]]}}]};
const selected={feature_id:'line',path:0,index:marking?1:2,...(whole?{object:true}:{})};
const previews=[],commits=[],errors=[],selections=[];let navigation=true;
const p={map,viewport,layers:[map.features[0].properties.class],selected,selection:[selected],editing:true,blocked:false,tool:'select',template:null,axis:'x',areaMode:'union',
runtime:{semanticSegmentParameter:(_a,_b,t)=>t,projectSemantic:v=>[v[0]/100,v[1]/100],moveSemantic:(v,x,y)=>[x*100,y*100,v[2]],setNavigation:v=>{navigation=v;}},
onPreview:op=>previews.push(op),onOperation:op=>{semanticOperation(map,op);commits.push(op);},onSelection:v=>selections.push(v),onSelect:v=>selections.push(v?[v]:[]),onChoose(){},onError:e=>errors.push(e),onPlaced(){},onExit(){}};
useSemanticGestures(p);
const axis={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'x'}}:null};
const event=(x,o={})=>({target:axis,button:0,pointerId:1,clientX:x,clientY:0,shiftKey:true,...o});
return {p,canvas,viewport,event,previews,commits,selections,errors,navigation:()=>navigation,dispose:()=>{for(const c of cleanups)c();}};
}
test('Shift pivot duplicates once on release; click and Escape do not commit',()=>{
const s=setup(),snapshot=JSON.stringify(s.p.map);
try{
s.viewport.emit('pointerdown',s.event(30));assert.equal(s.navigation(),false);
s.viewport.emit('pointermove',s.event(40));s.viewport.emit('pointermove',s.event(45));
assert.equal(s.commits.length,0);assert.equal(JSON.stringify(s.p.map),snapshot);
assert.deepEqual(s.previews.at(-1),{kind:'duplicate_vertex',feature_id:'line',path:0,index:2,axis:'x',delta:[15,0,0],side:'after'});
s.viewport.emit('pointerup',s.event(45));assert.equal(s.commits.length,1);assert.equal(s.navigation(),true);
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointerup',s.event(30));assert.equal(s.commits.length,1);
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointermove',s.event(40));document.emit('keydown',{key:'Escape'});s.viewport.emit('pointerup',s.event(40));assert.equal(s.commits.length,1);assert.equal(s.previews.at(-1),null);
}finally{s.dispose();}
});
test('whole strip Shift copies object; two vertices stretch; Ctrl owns camera',()=>{
const s=setup({marking:true,whole:true});
try{
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointermove',s.event(40));const first=s.previews.at(-1);s.viewport.emit('pointermove',s.event(45));
assert.equal(first.kind,'duplicate_marking');assert.equal(first.new_feature_id,s.previews.at(-1).new_feature_id);
s.viewport.emit('pointerup',s.event(45));assert.equal(s.commits.length,1);
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected,{...s.p.selected,index:2}];
s.viewport.emit('pointerdown',s.event(30,{shiftKey:false}));s.viewport.emit('pointermove',s.event(40,{shiftKey:false}));s.viewport.emit('pointerup',s.event(40,{shiftKey:false}));
assert.equal(s.commits[1].kind,'translate_vertices');assert.equal(s.commits[1].vertices.length,2);
const e=s.viewport.emit('pointerdown',s.event(30,{ctrlKey:true}));assert.equal(e.stopped,undefined);
s.viewport.emit('pointermove',s.event(40,{ctrlKey:true}));s.viewport.emit('pointerup',s.event(40,{ctrlKey:true}));assert.equal(s.commits.length,2);
}finally{s.dispose();}
});
test('first press grabs another vertex of the selected line before React updates selection; undo restores it',()=>{
const s=setup(),snapshot=JSON.stringify(s.p.map);s.p.selected={feature_id:'line',path:0,index:0};s.p.selection=[s.p.selected];
try{
const e=x=>s.event(x,{target:s.canvas,shiftKey:false,clientY:0});
s.viewport.emit('pointerdown',e(20));assert.equal(s.navigation(),false);assert.deepEqual(s.selections.at(-1),[{feature_id:'line',path:0,index:2}]);
// Deliberately leave props.selected stale: the gesture owns its captured target.
s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
assert.equal(s.commits.length,1);assert.equal(s.commits[0].kind,'translate_vertices');
assert.deepEqual(s.commits[0].delta,[15,0,0]);assert.equal(JSON.stringify(s.p.map),snapshot);
const {semanticDraft,commitSemantic,undoSemantic}=edits;
const d=commitSemantic(semanticDraft(s.p.map),s.commits[0]);assert.equal(d.map.features[0].geometry.coordinates[2][0],35);
assert.deepEqual(undoSemantic(d).map,s.p.map);
}finally{s.dispose();}
});
test('a click, cancelled first drag, and Ctrl orbit never commit a point edit',()=>{
const s=setup();s.p.selected=null;s.p.selection=[];
try{
const e=(x,o={})=>s.event(x,{target:s.canvas,shiftKey:false,...o});
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointerup',e(20));assert.equal(s.commits.length,0);
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));document.emit('keydown',{key:'Escape'});s.viewport.emit('pointerup',e(35));assert.equal(s.commits.length,0);assert.equal(s.navigation(),true);
assert.equal(s.viewport.emit('pointerdown',e(20,{ctrlKey:true})).stopped,undefined);
s.viewport.emit('pointermove',e(40,{ctrlKey:true}));s.viewport.emit('pointerup',e(40,{ctrlKey:true}));assert.equal(s.commits.length,0);
}finally{s.dispose();}
});
test('multi-layer mask governs hits and marquee; hidden layers cannot be edited',()=>{
const s=setup();
s.p.map.features.push({...s.p.map.features[0],id:'ped',properties:{class:'pedestrian_boundary'}});
try{
const e=(x,y=0)=>s.event(x,{target:s.canvas,shiftKey:false,clientY:y});
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
assert.equal(s.commits.length,1);assert.deepEqual(s.commits[0].vertices,[{feature_id:'line',path:0,index:2}]);
for(const layers of [['road_boundary'],['road_boundary','pedestrian_boundary'],[]]){
s.p.layers=layers;s.viewport.emit('pointerdown',e(-20,-20));s.viewport.emit('pointermove',e(50,30));s.viewport.emit('pointerup',e(50,30));
assert.deepEqual([...new Set(s.selections.at(-1).map(v=>v.feature_id))],layers.length===2?['line','ped']:layers.length?['line']:[]);
}
}finally{s.dispose();}
});
test('direct grab preserves a selected group and only the chosen axes',()=>{
const s=setup();s.p.selection=[{feature_id:'line',path:0,index:1},{feature_id:'line',path:0,index:2}];s.p.selected=s.p.selection[0];
try{
const e=(x,y)=>s.event(x,{target:s.canvas,shiftKey:false,clientY:y});
s.viewport.emit('pointerdown',e(20,0));s.viewport.emit('pointermove',e(35,12));s.viewport.emit('pointerup',e(35,12));
assert.deepEqual(s.commits[0].vertices,s.p.selection);assert.deepEqual(s.commits[0].delta,[15,0,0]);
}finally{s.dispose();}
});
test('interior Shift drag chooses incoming or outgoing arm; release freezes preview order',()=>{
const s=setup();s.p.map.features[0].geometry.coordinates=[[0,10,2],[0,0,2],[10,-1,2]];
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected];s.p.axis='xy';
const target={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'xy'}}:null};
const e=(x,y)=>s.event(x,{target,clientY:y});
try{
s.viewport.emit('pointerdown',e(0,0));s.viewport.emit('pointermove',e(0,3));
assert.equal(s.previews.at(-1).side,'before');
s.viewport.emit('pointermove',e(3,-.3));assert.equal(s.previews.at(-1).side,'after');
s.viewport.emit('pointermove',e(0,4));const preview=s.previews.at(-1);
s.viewport.emit('pointerup',e(0,4));assert.deepEqual(s.commits,[preview]);
const points=semanticOperation(s.p.map,preview).features[0].geometry.coordinates;
assert.deepEqual(points,[[0,10,2],[0,4,2],[0,0,2],[10,-1,2]]);
}finally{s.dispose();}
});
test('an unselected contour is selected before its hidden vertices can move',()=>{
const s=setup();s.p.selected=null;s.p.selection=[];
try{
const e=x=>s.event(x,{target:s.canvas,shiftKey:false,clientY:0});
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
assert.equal(s.commits.length,0);assert.equal(s.selections.at(-1)[0].feature_id,'line');
s.p.selection=s.selections.at(-1);s.p.selected=s.p.selection[0];
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
assert.equal(s.commits.length,1);assert.deepEqual(s.commits[0].delta,[15,0,0]);
}finally{s.dispose();}
});
test('facade body selects every vertex; whole Delete and undo preserve valid geometry',()=>{
const s=setup();s.p.selected=null;s.p.selection=[];
s.p.layers=['building_facade'];s.p.map.features[0].properties.class='building_facade';
s.p.map.features[0].geometry.coordinates=[[0,0,2],[80,0,2]];
try{
const e=x=>s.event(x,{target:s.canvas,shiftKey:false});
s.viewport.emit('pointerdown',e(40));s.viewport.emit('pointerup',e(40));
const selected=s.selections.at(-1);
assert.deepEqual(selected,[{feature_id:'line',path:0,index:0},{feature_id:'line',path:0,index:1}]);
const {semanticDraft,commitSemantic,undoSemantic}=edits;
const initial=semanticDraft(s.p.map),removed=commitSemantic(initial,{kind:'delete_vertices',vertices:selected});
assert.equal(removed.map.features[0].properties.review_status,'rejected');
assert.deepEqual(undoSemantic(removed).map,initial.map);
assert.throws(()=>semanticOperation(s.p.map,{kind:'delete_vertices',vertices:[selected[0]]}));
// After selecting the contour, its visible vertex remains individually selectable/draggable.
s.p.selection=selected;s.p.selected=selected[0];s.p.wholeContour=true;
s.viewport.emit('pointerdown',e(80));s.viewport.emit('pointermove',e(90));s.viewport.emit('pointerup',e(90));
assert.deepEqual(s.commits[0].vertices,[selected[1]]);
assert.deepEqual(s.commits[0].delta,[10,0,0]);
}finally{s.dispose();}
});
test('body selection includes all curve anchors and polygon holes, not the sampled curve vertices',()=>{
const s=setup();s.p.selected=null;s.p.selection=[];
const f=s.p.map.features[0];f.geometry={type:'Polygon',coordinates:[[[0,0,2],[80,0,2],[80,80,2],[0,80,2],[0,0,2]],[[20,20,2],[20,40,2],[40,40,2],[40,20,2],[20,20,2]]]};
s.p.map=semanticOperation(s.p.map,{kind:'curve',feature_id:'line',path:0,index:0,incoming:[0,0],outgoing:[10,-10]});
try{
const e=s.event(80,{target:s.canvas,shiftKey:false,clientY:40});
s.viewport.emit('pointerdown',e);s.viewport.emit('pointerup',e);
const selection=s.selections.at(-1);assert.equal(selection.length,8);
const deleted=semanticOperation(s.p.map,{kind:'delete_vertices',vertices:selection});
assert.equal(deleted.features[0].properties.review_status,'rejected');
}finally{s.dispose();}
});
test('Shift Y at a facade endpoint extends around a corner and commits preview order once',()=>{
const s=setup();
s.p.map.features[0].properties.class='building_facade';s.p.layers=['building_facade'];
s.p.map.features[0].geometry.coordinates=[[0,.1,2],[10,0,2]];
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected];
const target={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'y'}}:null};
const e=y=>s.event(10,{target,clientY:y});
try{
s.viewport.emit('pointerdown',e(0));s.viewport.emit('pointermove',e(3));
const preview=s.previews.at(-1);assert.equal(preview.kind,'duplicate_vertex');assert.equal(preview.side,'after');
assert.deepEqual(preview.delta,[0,3,0]);assert.equal(s.commits.length,0);
s.viewport.emit('pointerup',e(3));assert.deepEqual(s.commits,[preview]);
assert.deepEqual(semanticOperation(s.p.map,s.commits[0]).features[0].geometry.coordinates,[[0,.1,2],[10,0,2],[10,3,2]]);
}finally{s.dispose();}
});
@@ -18,7 +18,7 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
]);
assert.match(productModel, /id: "simulations"[\s\S]*root: "polygon"[\s\S]*kind: "simulations"/);
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace \/>/);
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace headerToolsHost=\{props.headerToolsHost\} \/>/);
assert.match(catalog, /simulation-catalog__table/);
@@ -32,7 +32,7 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
assert.match(workspace, /<AiPolygonWorkspace \/>/);
assert.match(workspace, /<AiPolygonWorkspace headerToolsHost=\{headerToolsHost\} \/>/);
assert.doesNotMatch(workspace, /simulation-profile|LccGaussianWorkspace/);
assert.match(styles, /styles\/simulation\.css/);
});
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import ts from "typescript";
const code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/urbanMap.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {ALL_URBAN_CLASSES,availableUrbanClasses,visibleUrbanMap,urbanPaths,loadUrbanMap,urbanExtent}=await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
const classes=["road_boundary","pedestrian_area","pedestrian_boundary","building_facade","road_marking"];
const map={schema_version:"missioncore.urban-map/v3",source:{world_sha256:"source"},features:classes.map((c,i)=>({id:String(i),properties:{class:c},geometry:{type:"LineString",coordinates:[[0,0,0],[1,1,1]]}}))};
test("legend classes independently hide boundaries and fills without losing choices or geometry",()=>{
assert.equal(visibleUrbanMap(map,ALL_URBAN_CLASSES).features.length,5);
assert.equal(visibleUrbanMap(map,[]).features.length,0);
assert.deepEqual(visibleUrbanMap(map,["pedestrian_area"]).features.map(f=>f.properties.class),["pedestrian_area"]);
assert.deepEqual(visibleUrbanMap(map,["pedestrian_boundary"]).features.map(f=>f.properties.class),["pedestrian_boundary"]);
assert.strictEqual(visibleUrbanMap(map,["building_facade"]).features[0],map.features[3]);
assert.equal(availableUrbanClasses(map).length,5);
const withRejected={...map,features:[...map.features,{...map.features[0],properties:{class:"curb",review_status:"rejected"}}]};
assert.equal(availableUrbanClasses(withRejected).includes("curb"),false);
assert.equal(visibleUrbanMap(withRejected,["curb"]).features.length,0);
});
test("rejected observations stay hidden and holes/open lines retain their paths",()=>{
assert.deepEqual(urbanPaths({...map.features[0],properties:{review_status:"rejected"}}),[]);
assert.deepEqual(urbanPaths(map.features[0]),[map.features[0].geometry.coordinates]);
const rings=[[[0,0,0],[1,0,0],[0,1,0],[0,0,0]],[[.2,.2,0],[.3,.2,0],[.2,.3,0],[.2,.2,0]]];
assert.strictEqual(urbanPaths({properties:{},geometry:{type:"Polygon",coordinates:rings}}),rings);
});
test("v3 loads only for the exact selected Gaussian revision",async()=>{
const original=globalThis.fetch;globalThis.fetch=async()=>({ok:true,status:200,json:async()=>map});
try {assert.strictEqual(await loadUrbanMap("world","source",new AbortController().signal),map);await assert.rejects(loadUrbanMap("world","different",new AbortController().signal));}
finally {globalThis.fetch=original;}
});
test("infrastructure framing works without waypoints and ignores rejected outliers",()=>{
const features=[{...map.features[0],geometry:{type:"LineString",coordinates:[[-12,4,-2],[35,80,6]]}},{...map.features[1],properties:{review_status:"rejected"},geometry:{type:"LineString",coordinates:[[900,900,900],[999,999,999]]}}];
assert.deepEqual(urbanExtent({...map,features}),[[-12,4,-2],[35,80,6]]);
assert.deepEqual(urbanExtent({...map,features:[]}),[]);
});
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import ts from "typescript";
let code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/urbanSurface.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
code=code.replace('from "three"',`from ${JSON.stringify(import.meta.resolve('three'))}`);
const {urbanSurface}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const ring=[[0,0,2],[8,0,2.8],[8,6,3.4],[0,6,2.6],[0,0,2]];
const hole=[[2,2,2.4],[4,2,2.6],[4,4,2.8],[2,4,2.6],[2,2,2.4]];
const feature={properties:{class:'pedestrian_area',height_projection:{method:'test'},review_status:'unreviewed'},geometry:{type:'Polygon',coordinates:[ring,hole]}};
test('ground coverage triangulation preserves hole, area, source heights and input',()=>{
const before=JSON.stringify(feature),g=urbanSurface(feature);assert.equal(JSON.stringify(feature),before);assert.deepEqual(g.positions,[...ring.slice(0,-1),...hole.slice(0,-1)].flat());let area=0;
for(let i=0;i<g.indices.length;i+=3){const p=g.indices.slice(i,i+3).map(k=>g.positions.slice(k*3,k*3+3));area+=Math.abs((p[1][0]-p[0][0])*(p[2][1]-p[0][1])-(p[2][0]-p[0][0])*(p[1][1]-p[0][1]))/2;const c=[0,1].map(k=>p.reduce((s,x)=>s+x[k],0)/3);assert.ok(!(c[0]>2&&c[0]<4&&c[1]>2&&c[1]<4));}
assert.equal(area,44);
});
test('physical boundaries and unqualified heights never become filled ground',()=>{
assert.equal(urbanSurface({...feature,properties:{class:'pedestrian_boundary',height_projection:{}}}),null);
assert.equal(urbanSurface({...feature,properties:{class:'pedestrian_area'}}),null);
assert.equal(urbanSurface({...feature,properties:{...feature.properties,review_status:'rejected'}}),null);
});
test('concave pedestrian outline stays concave',()=>{
const coords=[[0,0,0],[4,0,0],[4,1,0],[1,1,0],[1,4,0],[0,4,0],[0,0,0]];
const g=urbanSurface({...feature,geometry:{type:'Polygon',coordinates:[coords]}});let area=0;
for(let i=0;i<g.indices.length;i+=3){const p=g.indices.slice(i,i+3).map(k=>g.positions.slice(k*3,k*3+3));area+=Math.abs((p[1][0]-p[0][0])*(p[2][1]-p[0][1])-(p[2][0]-p[0][0])*(p[1][1]-p[0][1]))/2;}
assert.equal(area,7);
});
File diff suppressed because it is too large Load Diff
@@ -10,7 +10,7 @@ param(
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\runtime\simulation'
$name='ndc-ai-polygon-worker'
foreach($marker in @('active.json','editor-active.json','route-active.json')) {
foreach($marker in @('active.json','editor-active.json','route-active.json','infrastructure-active.json')) {
if(Test-Path "$root\state\$marker") { throw 'Active simulation work prevents update' }
}
$task=Get-ScheduledTask -TaskName $name
+60
View File
@@ -0,0 +1,60 @@
"""Plan/apply exact qualified artifacts through the existing local worker API.
No inference or geometry processing. Immutable previous versions are retained.
Token is read only for apply and never emitted. Re-running an applied plan is safe.
"""
from pathlib import Path
import argparse,hashlib,json,sys,urllib.request,urllib.error
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
from k1link.simulation.ai_polygon.qualified_maps import qualified_document
BASE='http://127.0.0.1:8000/api/v1/ai-polygon'
def encoded(obj):return json.dumps(obj,sort_keys=True,ensure_ascii=False,allow_nan=False).encode()
def sha(raw):return hashlib.sha256(raw).hexdigest()
def get(path):
try:
with urllib.request.urlopen(BASE+path,timeout=30)as r:return json.load(r)
except urllib.error.HTTPError as e:
if e.code==404:return None
raise
def main():
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('mode',choices=['plan','apply']);ap.add_argument('manifest',type=Path);ap.add_argument('evidence',type=Path);args=ap.parse_args()
manifest_raw=args.manifest.read_bytes();m=json.loads(manifest_raw);dest=args.evidence;dest.mkdir(parents=True,exist_ok=True);planpath=dest/'publication-plan.json'
vpath=Path(m['verification']);vraw=vpath.read_bytes();v=json.loads(vraw)
if sha(vraw)!=m['verification_sha256']or not v['passed']or v['source_snapshot']!=m['source_snapshot']:raise ValueError('Qualification receipt mismatch')
catalog=get('/catalog');worlds={w['world_id']:w for w in catalog['worlds']};items=[]
for item in m['scenes']:
world=worlds[item['world_id']];raw=Path(item['artifact']).read_bytes();audit=v['scenes'][item['scene']]['audit']
if not audit['passed']or audit['full_map_sha256']!=item['artifact_sha256']:raise ValueError('Artifact is not qualified')
document=qualified_document(raw,world,artifact_sha256=item['artifact_sha256'],source_world_sha256=item['source_world_sha256'],qualification=m['qualification'],source_snapshot=m['source_snapshot'],tiles_total=item['tiles_total'])
body=encoded(document)
if len(body)>12*1024**2:raise ValueError('Map exceeds API size limit')
current=get('/worlds/'+item['world_id']+'/urban-map');items.append(dict(scene=item['scene'],world_id=item['world_id'],world_sha256=world['sha256'],collider_sha256=world.get('collider_sha256'),target_sha256=sha(body),current_sha256=sha(encoded(current))if current is not None else None,document=document,current=current))
if args.mode=='plan':
if planpath.exists():raise ValueError('Existing plan retained; choose a fresh evidence directory')
for i in items:
(dest/(i['scene']+'-target.json')).write_bytes(encoded(i['document']))
(dest/(i['scene']+'-previous.json')).write_bytes(encoded(i['current']))
plan=dict(manifest_sha256=sha(manifest_raw),items=[{k:x for k,x in i.items()if k not in ['document','current']}for i in items]);planpath.write_text(json.dumps(plan,indent=2));print(json.dumps(plan));return
plan=json.loads(planpath.read_text())
if plan['manifest_sha256']!=sha(manifest_raw):raise ValueError('Publication manifest changed')
planned={x['scene']:x for x in plan['items']}
# Preflight every scene before the first write; never overwrite unrelated updates.
for i in items:
p=planned[i['scene']]
for k in ['world_id','world_sha256','collider_sha256','target_sha256']:
if i[k]!=p[k]:raise ValueError('Source/target changed since planning: '+k)
if i['current_sha256']not in [p['current_sha256'],p['target_sha256']]:raise ValueError('Live map changed since planning')
token=(Path(__file__).resolve().parents[1]/'.runtime/mission-core/ai-polygon/worker.token').read_text().strip();results=[]
for i in items:
if i['current_sha256']!=i['target_sha256']:
req=urllib.request.Request(BASE+'/worker/worlds/'+i['world_id']+'/urban-map',data=encoded(i['document']),headers={'Content-Type':'application/json','Authorization':'Bearer '+token},method='POST')
with urllib.request.urlopen(req,timeout=30)as response:receipt=json.load(response)
if receipt['sha256']!=i['target_sha256']:raise ValueError('Unexpected saved map hash')
saved=get('/worlds/'+i['world_id']+'/urban-map')
if saved!=i['document']:raise ValueError('Readback differs from qualified map')
results.append(dict(scene=i['scene'],world_id=i['world_id'],sha256=i['target_sha256'],features=len(saved['features']),readback_exact=True))
(dest/'publication-result.json').write_text(json.dumps(dict(complete=len(results)==len(items),scenes=results),indent=2))
print(json.dumps(dict(complete=True,scenes=results)))
if __name__=='__main__':main()
+101
View File
@@ -0,0 +1,101 @@
"""Build an immutable worker release from a verified installed release and explicit overlays.
Does not activate services. The complete predecessor remains the rollback.
"""
import argparse
import base64
import hashlib
import json
import re
import shutil
from pathlib import Path, PurePosixPath
def sha(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def confined(root, relative):
path = PurePosixPath(relative)
if (
path.is_absolute()
or not path.parts
or ".." in path.parts
or "\\" in relative
or ":" in relative
):
raise ValueError("Invalid release path")
target = root.joinpath(*path.parts)
if target.is_symlink() or not target.resolve().is_relative_to(root.resolve()):
raise ValueError("Release path escaped its owner")
return target
def stage(runtime, recipe):
previous = recipe["base_release"]
if not re.fullmatch("[a-f0-9]{16}", previous):
raise ValueError("Invalid base release")
releases = runtime / "releases"
base = releases / ("ai-polygon-" + previous)
manifest_path = releases / ("ai-polygon-" + previous + ".manifest.json")
if sha(manifest_path) != recipe["base_manifest_sha256"] or not sha(manifest_path).startswith(
previous
):
raise ValueError("Base manifest changed")
before = json.loads(manifest_path.read_text())
for name, digest in before.items():
if sha(confined(base, name)) != digest:
raise ValueError("Base file changed: " + name)
overlays = {}
for name, item in recipe["overlays"].items():
confined(base, name)
raw = base64.b64decode(item["base64"], validate=True)
if hashlib.sha256(raw).hexdigest() != item["sha256"]:
raise ValueError("Overlay changed: " + name)
overlays[name] = raw
if not overlays:
raise ValueError("Empty patch")
after = {**before, **{name: hashlib.sha256(raw).hexdigest() for name, raw in overlays.items()}}
encoded = json.dumps(after, sort_keys=True, indent=2).encode()
identity = hashlib.sha256(encoded).hexdigest()
target = releases / ("ai-polygon-" + identity[:16])
output_manifest = target.with_suffix(".manifest.json")
if target.exists() or output_manifest.exists():
raise ValueError("Release already exists; inspect it instead of overwriting")
temporary = releases / (".staging-" + identity[:16])
temporary.mkdir()
for name, digest in after.items():
dest = confined(temporary, name)
dest.parent.mkdir(parents=True, exist_ok=True)
if name in overlays:
dest.write_bytes(overlays[name])
else:
shutil.copyfile(confined(base, name), dest)
if sha(dest) != digest:
raise ValueError("Staged content changed: " + name)
temporary.rename(target)
output_manifest.write_bytes(encoded)
result = dict(
previous=previous,
release=identity[:16],
manifest_sha256=identity,
files=len(after),
changed=sorted(overlays),
activated=False,
previous_files_verified=len(before),
recipe_sha256=hashlib.sha256(json.dumps(recipe, sort_keys=True).encode()).hexdigest(),
)
receipt = runtime / "preparations" / ("worker-patch-" + identity[:16] + ".json")
receipt.parent.mkdir(exist_ok=True)
receipt.write_text(json.dumps(result, indent=2))
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--runtime", type=Path, required=True)
parser.add_argument("--recipe", type=Path, required=True)
args = parser.parse_args()
print(json.dumps(stage(args.runtime, json.loads(args.recipe.read_text()))))
@@ -0,0 +1,87 @@
# Infrastructure queue and operator progress
The Core owns a persistent FIFO of whole-scene analysis requests; the connected
Worker executes one request while holding the existing simulation GPU reservation.
Editor preparation, route preparation and simulation retain their existing
reservation policy. FIFO here applies to infrastructure analysis requests.
## Admission and identity
`InfrastructureJobs.request` binds the Gaussian world hash, collider, local-scene
transform and exact provider closure. Repeated requests for an active world return
the same job. An explicit recalculation supplies a 32-character lowercase hex
request ID and creates an immutable generation. Repeating that ID is idempotent.
Retries after failure or cancellation get a new generation. Ready map history is
retained; only a validated successful publication replaces the latest map.
At most 32 queued/running/unreleased jobs are admitted. Overflow is explicit,
never eviction. Monotonic persisted sequence numbers determine FIFO independently
of directory order or wall-clock precision. Terminal rows still owning resources
precede queued rows until cleanup releases them.
## Dispatch and termination
Selection, simulation reservation and claim execute under the same job-store lock
as cancellation. A queued cancellation therefore cannot strand a reservation
between selection and claim. A running cancellation is a request, not a release.
The next Worker progress call is rejected, causing the existing stage runner's
`finally` to stop/remove its exact owned container. Worker reconciliation then
sends the authenticated release receipt. Errors and bounded stage timeouts follow
the same cleanup path. Late publication after cancellation is rejected before any
map write. Queue state survives Core restart; the Worker's persisted container
marker supports reconciliation after Worker restart. A missing Worker or unknown
cleanup state keeps the resource reserved; absence of telemetry is not proof that
a container stopped.
## Operator API
- `GET /api/v1/ai-polygon/infrastructure-analysis/queue`: active jobs and position.
- `GET /api/v1/ai-polygon/worlds/{world_id}/infrastructure-analysis`: current job.
- `POST` to that world endpoint: `{force, request_id}` (body optional for first run).
- `POST .../infrastructure-analysis/{key}/cancel`: world-bound cancellation.
Progress counts actual completed stages. The 90-stage all-class definition uses 87 historical stage durations, one
qualified shared-semantic measurement (251.484 seconds on Smolensk 6.3), and
two explicitly estimated missing stages. The old surface/layer pair is replaced
by one shared stage; its two former weights are not counted again. A completed-prefix speed ratio adjusts the remaining estimate. Queue wait
and source preparation are excluded and labeled as such. A stale heartbeat (>20s)
suppresses ETA; elapsed time never synthesizes completion percentage.
## Acceptance
The focused backend tests cover 20-job FIFO, duplicate clicks, capacity, stale
provider, ownership, cancellation/late-publication barriers, restart, dispatch
races and measured progress. The frontend tests exercise 20 immediate clicks,
late polling, cancellation/unmount and idempotent retry after an unknown response.
`evaluation/queue_worker_canary.py` runs an isolated durable store on Worker006
with real bounded Docker containers: exit 7, running cancellation, timeout,
waiting cancellation and reopened persistence. It uses the exact Core atomic JSON
writer extracted from its frozen source to avoid importing the unrelated Gaussian
reader into the native Windows coordinator. No operator maps or jobs are modified.
## Control-plane disconnection
Infrastructure computation is owned by Worker. Lost TCP responses and HTTP 5xx
responses during progress reporting retain the same running container and local
stage chain. Pulses coalesce to the latest local progress; they never create
a backlog or replay dispatch. On the explicit expired-session response, Worker
registers the same instance and immutable capabilities, then retries the rejected
observation. Cancellation, ownership changes and invalid payloads remain terminal.
A missing heartbeat does not release the persistent exclusive GPU reservation.
After local validation produces `urban-map.json`, Worker records its SHA-256 in
`infrastructure-active.json` before sending `complete`. Reconciliation delivers
this immutable pending result before releasing ownership or polling another job.
A lost success response is safe because Core accepts an identical completed map
idempotently and rejects changed content. Retry cadence remains bounded when
registration works but receipt delivery does not. A confirmed cancellation or
publication rejection preserves the local evidence and releases after cleanup.
This guarantees continuity across Core/tunnel outages while the Worker process
and Docker remain alive. It does not claim mid-stage recovery after a Worker/host
crash: the existing orphan-container cleanup still applies. Previously failed
jobs are immutable history and are not silently reclassified as completed.
Acceptance includes reconstruction of the actual Core router and persistent GPU
queue, plus an isolated Worker canary with real Docker execution, TCP outages,
lost completion acknowledgement, cancellation and FIFO advancement.
+27 -2
View File
@@ -5,6 +5,8 @@ import ast
import hashlib
import json
import tarfile
import runpy
import urllib.request
from pathlib import Path
root = Path(__file__).resolve().parents[2]
@@ -14,10 +16,30 @@ args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
files = sorted(
p
for folder in (root / "src", root / "simulation/ai-polygon")
for folder in (root / "src", root / "simulation/ai-polygon", root / "simulation/urban-mapping")
for p in folder.rglob("*")
if p.is_file() and not p.is_symlink() and "__pycache__" not in p.parts
if p.is_file() and not p.is_symlink() and "__pycache__" not in p.parts and ".build" not in p.parts
)
# Only the declared Gaussian pipeline closure ships; historical review scripts
# and private qualification directories are not part of the worker artifact.
from infrastructure_pipeline import definition_files
module = root / "simulation/urban-plan-research"
_, urban_files = definition_files(module)
files.extend(module / relative for relative in urban_files)
# Pinned runtime wheels are artifact assets, never a global pip installation.
pins = runpy.run_path(str(module / "catalog_pass/catalog_dependency_pins.py"))["PINS"]
cache = args.output / "urban-dependencies"
cache.mkdir(exist_ok=True)
assets = {}
for pin in pins:
path = cache / pin["file"]
if not path.exists() or hashlib.sha256(path.read_bytes()).hexdigest() != pin["sha256"]:
with urllib.request.urlopen(pin["url"], timeout=120) as response:
raw = response.read(32 * 1024**2 + 1)
if len(raw) > 32 * 1024**2 or hashlib.sha256(raw).hexdigest() != pin["sha256"]:
raise ValueError("Pinned urban runtime dependency changed")
path.write_bytes(raw)
assets["simulation/urban-plan-research/pipeline/vendor/" + pin["file"]] = path
files.extend((root / "apps/control-station/public/vendor/playcanvas/draco/1.5.7").glob("*"))
# The canonical Rover 006 asset is shared with PlayCanvas, not a second model.
for profile in (root / "simulation/ai-polygon/robots").glob("*.json"):
@@ -32,12 +54,15 @@ for source in files:
manifest = {
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
}
manifest.update({name: hashlib.sha256(p.read_bytes()).hexdigest() for name, p in assets.items()})
encoded = json.dumps(manifest, sort_keys=True, indent=2).encode()
identity = hashlib.sha256(encoded).hexdigest()
path = args.output / ("ai-polygon-" + identity[:16] + ".tgz")
with tarfile.open(path, "w:gz") as archive:
for p in files:
archive.add(p, arcname=p.relative_to(root).as_posix(), recursive=False)
for name, asset in assets.items():
archive.add(asset, arcname=name, recursive=False)
manifest_path = path.with_suffix(".manifest.json")
manifest_path.write_bytes(encoded)
print(
+8 -5
View File
@@ -40,7 +40,9 @@ class CoreClient:
self.instance = instance
self._connections = threading.local()
def request(self, path: str, body=None):
def request(self, path: str, body=None, *, max_response_bytes=4 * 1024**2):
if not 0 < max_response_bytes <= 24 * 1024**2:
raise ValueError("Core response budget exceeds bounded transport")
connection = getattr(self._connections, "connection", None)
if (
connection is not None
@@ -63,8 +65,8 @@ class CoreClient:
},
)
response = connection.getresponse()
raw = response.read(4 * 1024**2 + 1)
if len(raw) > 4 * 1024**2:
raw = response.read(max_response_bytes + 1)
if len(raw) > max_response_bytes:
raise RuntimeError("Core response exceeds admitted size")
if response.status not in (200, 201):
try:
@@ -98,7 +100,7 @@ class CoreClient:
PREFIX + "/worlds/" + world["world_id"] + "/source.ply", world, target, pulse=pulse
)
def download_asset(self, path: str, descriptor: dict, target: Path, pulse=None):
def download_asset(self, path: str, descriptor: dict, target: Path, pulse=None, *, authenticated=False):
if not path.startswith("/api/v1/") or ".." in path or "\\" in path:
raise ValueError("Invalid Core asset path")
world = descriptor
@@ -109,7 +111,8 @@ class CoreClient:
try:
if pulse:
pulse()
connection.request("GET", path)
connection.request("GET", path, headers={"Authorization": "Bearer " + self.token}
if authenticated else {})
response = connection.getresponse()
if pulse:
pulse()
@@ -0,0 +1,168 @@
"""Exact-identity Docker lifecycle for the separately packaged mapping module."""
import json
import subprocess
import time
from pathlib import Path
from local_state import read_json, write_json
def docker(*args, check=True):
result = subprocess.run(
["docker", *map(str, args)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
if check and result.returncode:
raise RuntimeError("Infrastructure Docker operation failed: " + result.stderr[-1000:])
return result
def inspect_owned(name, key):
result = docker("container", "inspect", name, check=False)
if result.returncode:
# Prove absence from a successful daemon listing; a dead daemon is not absence.
ids = docker("ps", "-aq", "--filter", "name=^/" + name + "$").stdout.strip()
if ids:
raise RuntimeError("Cannot inspect analysis container")
return None
row = json.loads(result.stdout)[0]
labels = row["Config"].get("Labels") or {}
if (
labels.get("com.nodedc.analysis") != key
or labels.get("com.nodedc.stack") != "urban-mapping"
):
raise RuntimeError("Analysis container identity changed")
return row
def cleanup(marker):
record = read_json(marker)
if not record:
return
for name in list(record["containers"]):
row = inspect_owned(name, record["key"])
if row:
docker("rm", "-f", row["Id"])
if inspect_owned(name, record["key"]):
raise RuntimeError("Analysis container was not released")
# Retain only unresolved ownership, not every historical stage. Exit
# receipts hold history; rescanning it made long pipelines quadratic.
record["containers"].remove(name)
write_json(marker, record)
def resource_arguments(resources=None):
"""Bound one owned container; never alter Docker or host-wide limits."""
values={"cpus":4,"memory_gib":16}
if resources is not None:
if not isinstance(resources,dict) or set(resources)-set(values):
raise ValueError("Unsupported infrastructure resource profile")
values.update(resources)
for key,lower,upper in [("cpus",1,12),("memory_gib",8,32)]:
if type(values[key])is not int or not lower<=values[key]<=upper:
raise ValueError("Infrastructure resource limit out of bounds: "+key)
return ["--cpus",str(values["cpus"]),"--memory",str(values["memory_gib"])+"g"]
def run_container(marker, phase, image, mounts, command, output, pulse, timeout, *,
gpu=True, executable=None, environment=None, volumes=(), readonly=False, resources=None):
resource_args = resource_arguments(resources)
record = read_json(marker)
name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase
if name not in record["containers"]:
record["containers"].append(name)
write_json(marker, record) # Persist intent before Docker creation.
previous = inspect_owned(name, record["key"])
if previous:
raise RuntimeError("Unreconciled analysis container")
config = json.loads(docker("image", "inspect", image).stdout)[0]["Config"]
inherited = next(
(e.partition("=")[2] for e in config.get("Env", []) if e.startswith("PYTHONPATH=")), ""
)
pythonpath = "/geometry:/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e"
if inherited:
pythonpath += ":" + inherited
args = [
"create",
"--name",
name,
"--network",
"none",
*resource_args,
"--shm-size",
"1g",
"--label",
"com.nodedc.product=mission-core",
"--label",
"com.nodedc.stack=urban-mapping",
"--label",
"com.nodedc.role=" + phase,
"--label",
"com.nodedc.managed-by=infrastructure-worker",
"--label",
"com.nodedc.analysis=" + record["key"],
"-e",
"PYTHONDONTWRITEBYTECODE=1",
"-e",
"PYTHONFAULTHANDLER=1",
"-e",
"OMP_NUM_THREADS=4",
"-e",
"PYTHONPATH=" + pythonpath,
]
if gpu:
args += ["--gpus", "all"]
if readonly:
args += ["--read-only", "--pids-limit", "512", "--cap-drop", "ALL",
"--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,exec,size=1g"]
for variable, value in (environment or {}).items():
if variable == "PYTHONPATH":
value = value + (":" + inherited if inherited else "")
args += ["-e", variable + "=" + str(value)]
for volume, destination in volumes:
if not volume.startswith("ndc-"):
raise ValueError("Analysis cache volume requires owned namespace")
args += ["--mount", "type=volume,source=" + volume + ",target=" + destination]
for source, destination, readonly in mounts:
args += [
"--mount",
"type=bind,source="
+ str(Path(source).resolve())
+ ",target="
+ destination
+ (",readonly" if readonly else ""),
]
exe = executable or ("/usr/bin/python3" if phase == "survey" else "/opt/conda/envs/goose/bin/python")
args += ["--entrypoint", exe, image, *command]
cid = docker(*args).stdout.strip()
row = inspect_owned(name, record["key"])
if not row or row["Id"] != cid:
raise RuntimeError("Docker create identity mismatch")
deadline = time.monotonic() + timeout
try:
docker("start", cid)
while True:
pulse()
row = inspect_owned(name, record["key"])
if not row:
raise RuntimeError("Analysis container disappeared")
if not row["State"]["Running"]:
logs = docker("logs", "--tail", "2000", cid, check=False)
(output / (phase + ".log")).write_text(logs.stdout + logs.stderr, encoding="utf-8")
write_json(output / (phase + "-exit.json"), row["State"])
if row["State"]["ExitCode"]:
state = row["State"]
raise RuntimeError(
f"Analysis {phase} exited {state['ExitCode']}; OOM={state['OOMKilled']}"
)
return
if time.monotonic() >= deadline:
raise TimeoutError("Infrastructure analysis exceeded its bounded runtime")
time.sleep(1)
finally:
cleanup(marker)
@@ -0,0 +1,20 @@
"""Final map admission runs inside the pinned scientific runtime, not host Python."""
import hashlib
import json
from pathlib import Path
from k1link.simulation.ai_polygon.qualified_maps import qualified_document
root = Path('/analysis')
request = json.loads((root/'publication-request.json').read_bytes())
plan = root/request['plan']
if not plan.resolve().is_relative_to(root.resolve()):
raise ValueError('Analysis plan escaped owned output')
raw = plan.read_bytes()
count = len(json.loads((root/'ortho/survey/tile-index.json').read_bytes())['tiles'])
document = qualified_document(raw, request['world'],
artifact_sha256=hashlib.sha256(raw).hexdigest(),
source_world_sha256=request['world']['sha256'],
qualification='analysis-'+request['key'][:16],
source_snapshot=request['snapshot'], tiles_total=count)
document['analysis'].update(job_key=request['key'], provider_sha256=request['provider'])
(root/'urban-map.json').write_text(json.dumps(document, allow_nan=False),encoding='utf-8')
@@ -0,0 +1,228 @@
"""Original LCC + native poses adapter; read-only producer, owned derived PLY.
Provider job/ingest receipts bind the input to the selected project. No scan
names, qualification paths, mesh, or point cloud participate in resolution.
"""
import base64
import hashlib
import json
import math
import re
import shutil
import subprocess
import time
from pathlib import Path, PurePosixPath
from local_state import write_json
from infrastructure_sources import checksum
MAX_POSES_BYTES = 16 * 1024**2
def confined(root, name):
rel = PurePosixPath(name.replace("\\", "/"))
if rel.is_absolute() or ".." in rel.parts or ":" in name:
raise ValueError("Invalid original source member")
path = root.joinpath(*rel.parts)
if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Original source escaped producer package")
return path
def trajectory(raw):
if not 0 < len(raw) <= MAX_POSES_BYTES:
raise ValueError("Trajectory exceeds bounded input size")
doc = json.loads(raw)
poses = doc.get("poses")
if not isinstance(poses, list) or not 100 <= len(poses) <= 500000:
raise ValueError("Missing complete native scanning trajectory")
for pose in poses:
xyz = pose.get("T")
if not isinstance(xyz, list) or len(xyz) != 3 or any(
type(v) not in (int, float) or not math.isfinite(v) for v in xyz
):
raise ValueError("Invalid trajectory coordinate")
return doc
def archive_trajectory(producer, source, package, sevenzip, pulse, fallback=None):
archives = package["files"]
if len(archives) != 1:
raise ValueError("Ambiguous original archive")
descriptor = archives[0]
candidates = []
for receipt in (producer / "ingests").glob("*/record.json"):
record = json.loads(receipt.read_text(encoding="utf-8"))
if record.get("document", {}).get("source", {}).get("bundle_sha256") != source["bundle_sha256"]:
continue
upload = record.get("archive_upload_id", "")
if not re.fullmatch(r"[a-zA-Z0-9-]{1,80}", upload):
raise ValueError("Invalid archive identity")
path = producer / "uploads" / upload
if path.is_file() and not path.is_symlink() and path.stat().st_size == descriptor["byte_length"]:
if checksum(path, pulse) == descriptor["sha256"]:
candidates.append(path)
if not candidates:
if fallback is None:
raise ValueError("Verified original archive is unavailable on this Worker")
return fallback(descriptor)
return read_archive_trajectory(sorted(candidates)[0], sevenzip, pulse)
def read_archive_trajectory(archive, sevenzip, pulse):
listing = subprocess.run([str(sevenzip), "l", "-slt", "-ba", "-sccUTF-8", str(archive)],
capture_output=True, timeout=120, check=True).stdout.decode("utf-8-sig")
members = []
for block in re.split(r"\r?\n\r?\n", listing):
fields = dict(line.split(" = ", 1) for line in block.splitlines() if " = " in line)
name = fields.get("Path", "").replace("\\", "/")
if PurePosixPath(name).name.lower() == "poses.json":
confined(Path("/archive"), name)
if fields.get("Folder") == "+" or not 0 < int(fields.get("Size", 0)) <= MAX_POSES_BYTES:
raise ValueError("Invalid archived trajectory")
members.append((name, int(fields["Size"])))
if len(members) != 1:
raise ValueError("Original archive needs one unambiguous poses.json")
name, size = members[0]
pulse()
raw = subprocess.run([str(sevenzip), "e", "-so", "-spd", str(archive), name],
capture_output=True, timeout=120, check=True).stdout
if len(raw) != size:
raise ValueError("Archived trajectory size mismatch")
trajectory(raw)
return raw
def resolve_gaussian_entry(package, world, producer, pulse=lambda: None):
if package["world_sha256"] != world["sha256"]:
raise ValueError("Gaussian world changed after admission")
# Current renderer/frame qualification is LCC native Z-up with the viewer's
# 180-degree X conversion. Reject unsupported calibrations explicitly.
rx, ry, rz = world["local_scene"]["visual_rotation"]
if abs((rx - 180 + 180) % 360 - 180) > 1e-6 or abs(ry) > 1e-6 or abs(rz) > 1e-6:
raise ValueError("Gaussian infrastructure frame is not qualified for this calibration")
job_id = package["provider_job_id"]
if not re.fullmatch(r"gsp-[0-9]{14}-[a-f0-9]{8}", job_id):
raise ValueError("Invalid Gaussian producer identity")
job = producer / "jobs" / job_id
record = json.loads((job / "job.json").read_text(encoding="utf-8"))
source = record["request"]["source"]
if record.get("state") != "ready" or source["bundle_sha256"] != package["bundle_sha256"] or source["format"] != "lcc":
raise ValueError("Original LCC producer identity mismatch")
root = job / "work/source-bundle"
entries = [m for m in source["members"] if m["logical_path"] == source["entrypoint"]]
if len(entries) != 1 or PurePosixPath(source["entrypoint"]).suffix.lower() != ".lcc":
raise ValueError("Original Gaussian entrypoint is not a verified LCC member")
for member in source["members"]:
# Source mesh members may coexist in a producer record; they are never
# opened by Gaussian analysis, hashed as geometry, or mounted as input.
if PurePosixPath(member["logical_path"]).suffix.lower() not in (".lcc", ".bin"):
continue
path = confined(root, member["logical_path"])
if path.stat().st_size != member["byte_length"] or checksum(path, pulse) != member["sha256"]:
raise ValueError("Original Gaussian member changed")
entry = confined(root, source["entrypoint"])
return entry, source
def resolve_native(package, world, producer, sevenzip, pulse=lambda: None, fallback=None):
entry, source = resolve_gaussian_entry(package, world, producer, pulse)
if package["kind"] == "folder":
p = package["trajectory"]
raw = base64.b64decode(p["base64"], validate=True)
if len(raw) != p["byte_length"] or hashlib.sha256(raw).hexdigest() != p["sha256"]:
raise ValueError("Trajectory transport mismatch")
elif package["kind"] == "archive":
raw = archive_trajectory(producer, source, package, sevenzip, pulse, fallback)
else:
raise ValueError("Unsupported original Gaussian source")
trajectory(raw)
return entry, raw, source
def transferred_trajectory(descriptor, world, state, profile, pulse, client):
if client is None:
raise ValueError("Original archive transfer is unavailable")
identity = descriptor["sha256"]
if not re.fullmatch("[a-f0-9]{64}", identity):
raise ValueError("Invalid archive digest")
cache = Path(state) / "infrastructure-trajectories" / identity
cache.mkdir(parents=True, exist_ok=True)
target = cache / "poses.json"
receipt = cache / "source.json"
if receipt.exists():
record = json.loads(receipt.read_text())
if record["archive_sha256"] != identity or checksum(target, pulse) != record["poses_sha256"]:
raise ValueError("Cached native trajectory changed")
raw = target.read_bytes()
trajectory(raw)
return raw
if shutil.disk_usage(cache).free < descriptor["byte_length"] + 10 * 1024**3:
raise RuntimeError("Insufficient space for temporary original-archive transfer")
archive = cache / "original.archive"
try:
client.download_asset("/api/v1/ai-polygon/worker/worlds/" + world["world_id"] +
"/infrastructure-archive", descriptor, archive, pulse=pulse, authenticated=True)
if archive.stat().st_size != descriptor["byte_length"] or checksum(archive, pulse) != identity:
raise ValueError("Original archive transport mismatch")
raw = read_archive_trajectory(archive, Path(profile["sevenzip"]), pulse)
target.write_bytes(raw)
write_json(receipt, dict(archive_sha256=identity, poses_sha256=hashlib.sha256(raw).hexdigest()))
return raw
finally:
archive.unlink(missing_ok=True)
archive.with_suffix(".part").unlink(missing_ok=True)
def prepare_native(package, world, state, profile, pulse, *, client=None, output_root=None):
runtime = Path(state).parent
entry, poses, source = resolve_native(package, world, Path(profile["producer_data"]),
Path(profile["sevenzip"]), pulse,
lambda descriptor: transferred_trajectory(descriptor, world, state, profile, pulse, client))
converter = runtime / profile["splat_transform"]
key = hashlib.sha256(json.dumps(dict(bundle=source["bundle_sha256"],
poses=hashlib.sha256(poses).hexdigest(), lod=1, adapter=checksum(Path(__file__)),
converter=checksum(converter)), sort_keys=True).encode()).hexdigest()
root = (Path(output_root) if output_root is not None else Path(state) / "infrastructure-sources") / key
root.mkdir(parents=True, exist_ok=True)
receipt = root / "source.json"
ply = root / "full-lod1.ply"
if receipt.exists():
previous = json.loads(receipt.read_text())
if checksum(ply, pulse) != previous["sha256"] or (root / "poses.json").read_bytes() != poses:
raise ValueError("Shared Gaussian analysis source changed")
return root, previous
if shutil.disk_usage(root).free < 30 * 1024**3:
raise RuntimeError("Insufficient disk space for complete Gaussian source adaptation")
command = [shutil.which("node"), "--max-old-space-size=8192", str(converter),
"--gpu", "cpu", "--max-workers", "4", "-w", "--select-lod", "1", str(entry),
"-r", "180,0,0", str(ply)]
with (root / "adapt.log").open("wb") as log:
proc = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 1800
while proc.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Gaussian source adaptation timed out")
time.sleep(1)
if proc.returncode:
raise RuntimeError("Complete Gaussian source adaptation failed")
finally:
if proc.poll() is None:
# Windows tree termination covers the converter's own workers.
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=30)
proc.wait(timeout=30)
with ply.open("rb") as stream:
header = stream.read(65536).split(b"end_header", 1)[0]
if not all(key in header for key in [b"opacity", b"scale_0", b"rot_0", b"f_dc_0"]):
raise ValueError("Adapted source lacks Gaussian attributes")
(root / "poses.json").write_bytes(poses)
result = dict(ply=ply.name, sha256=checksum(ply, pulse), lod=1,
source_to_world=[[1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,0,1]],
bundle_sha256=source["bundle_sha256"], poses_sha256=hashlib.sha256(poses).hexdigest(),
adapter_key=key, coverage="complete-source-selected-LOD", spatially_cropped=False,
gaussian_only=True, collider_input=False, point_cloud_input=False)
write_json(receipt, result)
return root, result
@@ -0,0 +1,225 @@
"""Artifact-owned execution of the Gaussian-only infrastructure stage chain.
All modules and mount aliases come from the shipped definition. Original
sources are read-only; generated stage artifacts belong to one analysis key.
"""
import hashlib
import json
import shutil
import time
from pathlib import Path
from infrastructure_containers import run_container
from infrastructure_sources import checksum
from local_state import write_json
MODULE = Path(__file__).resolve().parents[1] / "urban-plan-research"
DEFINITION = MODULE / "pipeline/definition.json"
GPU_STAGES = {"pose_survey", "ortho_render", "ortho_segment", "mv_render", "mv_infer",
"semantic_layers", "render_coverage", "semantic_symbols", "semantic_compact_symbols"}
SEMANTIC_STAGES = {"ortho_semantic_survey", "ortho_segment", "semantic_layers",
"semantic_symbols", "semantic_compact_symbols"}
def validate_stage_outputs(definition):
"""Cross-group evidence has one declared producer and a later consumer."""
import re
groups = definition["groups"]
positions = {g["group"]: i for i, g in enumerate(groups)}
if len(positions) != len(groups):
raise ValueError("Duplicate pipeline group")
reserved = {"input", "candidate", "out", "survey", "ortho", "blind", "base",
"release", "assets", "run", "evidence", "base_survey", "continuity",
"fullplan", "multiview", "models", "cache", "baseline.json"}
reserved.update(str(alias) for alias in definition.get("aliases", {}).values())
owners = set()
for index, group in enumerate(groups):
for stage, mounts in group.get("stage_outputs", {}).items():
if stage not in group["stages"] or not isinstance(mounts, dict):
raise ValueError("Output owner is not an executable stage")
for alias, target in mounts.items():
if (not re.fullmatch(r"[a-z][a-z0-9_-]*", target)
or target not in positions or positions[target] <= index):
raise ValueError("Output must belong to a later declared group")
if not re.fullmatch(r"/[a-z][a-z0-9_-]*", alias) or alias[1:] in reserved:
raise ValueError("Output shadows or escapes an existing runtime mount")
if target in owners:
raise ValueError("Cross-group output has multiple producers")
owners.add(target)
def stage_output_mounts(output, group, stage):
mounts = []
for alias, target in group.get("stage_outputs", {}).get(stage, {}).items():
path = output / target
if path.is_symlink() or not path.resolve().is_relative_to(output.resolve()):
raise ValueError("Pipeline output escapes owned analysis directory")
path.mkdir(parents=True, exist_ok=True)
mounts.append((path, alias, False))
return mounts
def definition_files(module=MODULE):
definition = json.loads((module / "pipeline/definition.json").read_text())
validate_stage_outputs(definition)
result = {"pipeline/definition.json", "pipeline/config-ortho.json", "pipeline/config-mv.json",
"pipeline/worker-profile.json"}
for group in definition["groups"]:
for alias, relative in group["files"].items():
for name in (alias, relative):
if Path(name).is_absolute() or ".." in Path(name).parts or "\\" in name:
raise ValueError("Pipeline source escapes artifact")
path = module / relative
if path.is_symlink() or not path.resolve().is_relative_to(module.resolve()):
raise ValueError("Pipeline source escapes artifact")
result.add(relative)
if not all(stage + ".py" in group["files"] for stage in group["stages"]):
raise ValueError("Pipeline entrypoint missing from bundle")
return definition, sorted(result)
def prepare_layout(root, module=MODULE):
definition, files = definition_files(module)
hashes = {name: checksum(module / name) for name in files}
snapshot = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest()
target = root / "modules" / snapshot
for group in definition["groups"]:
for alias, relative in group["files"].items():
dest = target / group["group"] / alias
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists():
if checksum(dest) != hashes[relative]:
raise ValueError("Prepared module bytes changed")
else:
shutil.copyfile(module / relative, dest)
if checksum(dest) != hashes[relative]:
raise ValueError("Module changed during preparation")
# Docker cannot create nested mountpoints below the read-only module
# bind. Reserve empty files before mounting the pinned wheel assets.
for wheel in (module / "pipeline/vendor").glob("*.whl"):
slot = target / group["group"] / wheel.name
if slot.exists() and (slot.is_symlink() or slot.stat().st_size):
raise ValueError("Dependency mountpoint changed")
slot.touch(exist_ok=True)
write_json(root / "source-manifest.json", dict(snapshot=snapshot, files=hashes))
return definition, target, snapshot
def output_inventory(folder):
# Cache acceptance never trusts an exit code alone. Include semantic images,
# geometry, map and reports; exclude diagnostic logs and stage receipts.
return {p.relative_to(folder).as_posix(): checksum(p) for p in sorted(folder.rglob("*"))
if p.is_file() and not p.is_symlink() and p.suffix != ".log"
and not p.name.endswith(("-exit.json", "-execution.json"))}
def run_pipeline(package, source, output, marker, profile, runtime, pulse, *, module=MODULE):
definition, modules, snapshot = prepare_layout(output, module)
stages = [(g, stage) for g in definition["groups"] for stage in g["stages"]]
for name in ["base-survey", "ortho/survey", "ortho/evidence", "multiview/mapillary/evidence",
"geometry", "continuity"]:
(output / name).mkdir(parents=True, exist_ok=True)
for config, dest in [("config-ortho.json", "ortho"), ("config-mv.json", "multiview")]:
cfg = json.loads((module / "pipeline" / config).read_text())
cfg["scenes"] = {"scene": dict(source_survey="base-survey", package="input", trajectory="poses.json")}
for model in cfg.get("models", {}).values():
model["directory"] = str(runtime / model["directory"])
write_json(output / dest / "config.json", cfg)
for target in [output / "poses.json", output / "ortho/poses.json"]:
target.write_bytes((package / "poses.json").read_bytes())
write_json(output / "request.json", dict(source=source))
write_json(output / "baseline.json", dict(type="FeatureCollection", features=[]))
dependencies = module / "pipeline/vendor"
previous = None
deadline = time.monotonic() + profile["maximum_seconds"]
for index, (group, stage) in enumerate(stages):
if time.monotonic() > deadline:
raise TimeoutError("Gaussian infrastructure job exceeded its execution budget")
name = group["group"]
out = output / ("geometry" if name == "base" else name)
out.mkdir(exist_ok=True)
if previous:
check = previous / "crosswalk-standard-check.json"
if check.exists():
(out / check.name).write_bytes(check.read_bytes())
write_json(output / "progress.json", dict(phase="survey" if name == "base" else "refining",
completed=index, total=len(stages)))
pulse()
mounts = [(modules/name, "/candidate", True), (package, "/input", True),
(output/"base-survey", "/base_survey", name != "base"),
(output/"ortho", "/ortho", True),
(output/"ortho/survey", "/survey", name != "base"), (out, "/out", False)]
if name == "base":
runname = "ortho" if stage.startswith("ortho_") else "multiview"
evidence = output / ("ortho/evidence" if runname == "ortho" else "multiview/mapillary/evidence")
mounts += [(output, "/blind", False), (output/"continuity", "/continuity", False),
(output/"baseline.json", "/baseline.json", True),
(output/runname, "/run", False), (evidence, "/evidence", False)]
cfg = json.loads((output/"multiview/config.json").read_text())
for key, model in cfg["models"].items():
mounts.append((Path(model["directory"]), "/models/" + key, True))
else:
mounts += [(output/"geometry", "/base", True), (output/"multiview", "/multiview", True)]
if previous:
mounts.append((previous, "/fullplan", True))
for folder, alias in definition["aliases"].items():
if folder != name and (output/folder).exists():
mounts.append((output/folder, "/"+alias, True))
mounts += stage_output_mounts(output, group, stage)
for destination, relative in group.get("input_files", {}).items():
mounts = [m for m in mounts if m[1] != destination]
mounts.append((output / relative, destination, True))
if stage in group.get("self_symbol_stages", []):
mounts = [m for m in mounts if m[1] != "/symbolplan"]
mounts.append((out, "/symbolplan", True))
if group.get("extra_coverage"):
mounts.append((output / group["extra_coverage"], "/out/coverage", True))
for dependency in dependencies.glob("*.whl"):
mounts.append((dependency, "/candidate/"+dependency.name, True))
semantic = stage in SEMANTIC_STAGES
if semantic:
mounts += [(module.parents[1], "/release", True),
(runtime/profile["semantic_model"], "/assets", True)]
env = dict(SCENE="scene", ORTHO_SCENE="scene", MV_MODEL="mapillary",
PYTHONPATH="/candidate:/candidate/mapping:/release/simulation/ai-polygon",
OPENBLAS_NUM_THREADS="3", OMP_NUM_THREADS="3", HF_HUB_OFFLINE="1",
TRANSFORMERS_OFFLINE="1", HF_HOME="/tmp/hf", MPLCONFIGDIR="/tmp/matplotlib",
XDG_CACHE_HOME="/tmp/cache", TORCH_HOME="/tmp/torch")
env.update(group.get("environment", {}))
env["WINDOW_SOURCE"] = "/candidate/linear_window_support.py"
if group.get("extra_coverage"):
env["EXTRA_COVERAGE_ROOT"] = "/out/coverage"
gpu = semantic or stage in GPU_STAGES
volumes = [("ndc-urban-mapping-cache", "/cache")] if stage in {"pose_survey", "ortho_render", "mv_render", "render_coverage"} else []
if volumes:
env["TORCH_EXTENSIONS_DIR"] = "/cache/torch"
entry = "import runpy;" + ("import torch;torch.cuda.set_per_process_memory_fraction(.30);" if gpu and not semantic else "")
if stage == "final_symbol_admission":
entry += "import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];"
if stage == "semantic_compact_symbols" and not json.loads((out/"symbol-patches.json").read_text())["patches"]:
write_json(out/"symbol-semantics.json", dict(records=[],
patch_manifest_sha256=checksum(out/"symbol-patches.json"),
class_labels=["bicycle"], prompts=["bicycle", "bike symbol", "bicycle road marking"],
class_ids=[0,0,0], manual_rois=[], empty_search=True))
continue
entry += "runpy.run_path('/candidate/"+stage+".py',run_name='__main__')"
phase = str(index).zfill(3)+"-"+stage.replace("_", "-")
started = time.monotonic()
run_container(marker, phase, profile["semantic_image" if semantic else "mapper_image"],
mounts, ["-B", "-c", entry], out, pulse,
min(profile["maximum_stage_seconds"], max(1,deadline-time.monotonic())),
gpu=gpu, executable="python3", environment=env, volumes=volumes, readonly=True,
resources=group.get("stage_resources", {}).get(stage))
write_json(out/(stage+"-execution.json"), dict(snapshot=snapshot, stage=stage,
seconds=time.monotonic()-started, exit_code=0, input_source_sha256=source["sha256"],
poses_sha256=source["poses_sha256"], gaussian_only=True))
# Within a group /fullplan stays the prior group's output.
if index+1 == len(stages) or stages[index+1][0]["group"] != name:
if name != "base" and group.get("map_output", True):
if group.get("map_file"):
(out/"full-map.json").write_bytes((out/group["map_file"]).read_bytes())
previous = out
write_json(out/"group-inventory.json", dict(files=output_inventory(out)))
if previous is None or not (previous/"full-map.json").is_file():
raise ValueError("Pipeline did not produce a complete map")
return previous/"full-map.json", snapshot
@@ -0,0 +1,196 @@
"""Whole-scene Gaussian/trajectory analysis with owned Worker lifecycle."""
import contextlib
import json
import logging
import shutil
import subprocess
import time
from pathlib import Path
from core_client import CoreRequestRejected
from infrastructure_containers import cleanup, docker, run_container
from infrastructure_gaussian_sources import prepare_native
from infrastructure_pipeline import MODULE, run_pipeline
from infrastructure_sources import checksum
from infrastructure_transport import registered_request, report_progress, unavailable
from local_state import read_json, write_json
from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity
def capability(state):
profile = json.loads((MODULE / "pipeline/worker-profile.json").read_text())
runtime = Path(state).parent
try:
for key in ("mapper_image", "semantic_image"):
actual = docker("image", "inspect", profile[key], "--format", "{{.Id}}").stdout.strip()
if actual != profile[key]:
return None
import runpy
for pin in runpy.run_path(str(MODULE / "catalog_pass/catalog_dependency_pins.py"))["PINS"]:
if checksum(MODULE / "pipeline/vendor" / pin["file"]) != pin["sha256"]:
return None
for path in [runtime / profile["splat_transform"], Path(profile["sevenzip"])]:
if not path.is_file():
return None
cfg = read_json(MODULE / "pipeline/config-mv.json")
for model in cfg["models"].values():
for name, sha in model["files"].items():
if checksum(runtime / model["directory"] / name) != sha:
return None
model = read_json(Path(__file__).with_name("sam3-research") / "large-model.json")
for name, sha in model["files"].items():
if checksum(runtime / profile["semantic_model"] / name) != sha:
return None
return provider_identity()
except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired):
logging.exception("Gaussian infrastructure capability is unavailable")
return None
def reconcile(client, marker, hello=None):
record = read_json(marker)
if not record:
return
cleanup(marker)
record = read_json(marker)
endpoint = "/worker/infrastructure-analysis/" + record["key"]
if record.get("completion"):
# The result outbox is durable before the first HTTP attempt. Replaying
# identical complete is validated/idempotent at Core, including lost ACKs.
output = (
Path(read_json(MODULE / "pipeline/worker-profile.json")["job_root"]) / record["key"]
)
document = output / "urban-map.json"
if checksum(document) != record["completion"]["sha256"]:
raise ValueError("Pending infrastructure result changed")
try:
registered_request(
client, endpoint, dict(action="complete", map=read_json(document)), hello=hello
)
except CoreRequestRejected as exc:
if exc.status != 400 and not (
exc.status == 409
and exc.detail
in ("Analysis cancellation requested", "Analysis is not owned by this worker")
):
raise
# A confirmed cancellation/validation rejection is terminal, unlike
# an unavailable Core. Preserve evidence; never publish around it.
write_json(
output / "publication-rejection.json", dict(status=exc.status, detail=exc.detail)
)
record.pop("completion")
write_json(marker, record)
registered_request(
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
)
marker.unlink()
def source_package(client, endpoint, pulse, deadline):
# This is a read, so an interrupted response may safely be fetched again.
while True:
pulse()
try:
return client.request(endpoint, max_response_bytes=24 * 1024**2)
except Exception as exc:
if not unavailable(exc):
raise
if time.monotonic() >= deadline:
raise TimeoutError(
"Infrastructure source wait exceeded its runtime budget"
) from exc
time.sleep(3)
def prepare_infrastructure(client, row, state, marker, hello=None):
state = Path(state)
profile = read_json(MODULE / "pipeline/worker-profile.json")
if row["identity"]["provider_sha256"] != provider_identity():
raise ValueError("Infrastructure provider changed")
runtime = state.parent
output = Path(profile["job_root"]) / row["key"]
output.mkdir(parents=True, exist_ok=True)
write_json(marker, dict(key=row["key"], owner=client.instance, containers=[]))
endpoint = "/worker/infrastructure-analysis/" + row["key"]
last_pulse = -float("inf")
connected = True
phase = dict(phase="preparing", completed=0, total=0)
def pulse():
nonlocal last_pulse, phase, connected
if time.monotonic() - last_pulse < 3:
return
progress = output / "progress.json"
if progress.exists():
with contextlib.suppress(ValueError, OSError):
phase = read_json(progress)
response = report_progress(client, endpoint, phase, hello=hello)
online = response is not None
if online != connected:
logging.warning(
"Infrastructure control %s; local computation retained",
"restored" if online else "unavailable",
)
connected = online
last_pulse = time.monotonic()
try:
if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3:
raise RuntimeError("Insufficient space for Gaussian analysis results")
pulse()
package = source_package(
client,
"/worker/worlds/" + row["world"]["world_id"] + "/infrastructure-source",
pulse,
time.monotonic() + profile["maximum_seconds"],
)
inputs, source = prepare_native(package, row["world"], state, profile, pulse, client=client)
plan, snapshot = run_pipeline(inputs, source, output, marker, profile, runtime, pulse)
if row["identity"]["provider_sha256"] != provider_identity():
raise ValueError("Infrastructure provider changed during execution")
write_json(
output / "publication-request.json",
dict(
plan=plan.relative_to(output).as_posix(),
world=row["world"],
key=row["key"],
snapshot=snapshot,
provider=row["identity"]["provider_sha256"],
),
)
release = Path(__file__).resolve().parents[2]
run_container(
marker,
"publication",
profile["mapper_image"],
[(release, "/release", True), (output, "/analysis", False)],
["-B", "/release/simulation/ai-polygon/infrastructure_document.py"],
output,
pulse,
300,
gpu=False,
executable="python3",
environment={"PYTHONPATH": "/release/src"},
readonly=True,
)
record = read_json(marker)
record["completion"] = dict(sha256=checksum(output / "urban-map.json"))
write_json(marker, record)
except Exception as exc:
logging.exception("Infrastructure analysis failed")
write_json(output / "failure.json", dict(type=type(exc).__name__, message=str(exc)))
try:
registered_request(client, endpoint, dict(action="fail"), hello=hello)
except Exception:
logging.warning("Infrastructure failure receipt awaits reconciliation")
finally:
try:
reconcile(client, marker, hello)
except Exception:
# Keep the durable marker. The coordinator's existing reconnect loop
# retries cleanup/release before polling any subsequent job.
logging.exception("Infrastructure release awaits reconciliation")
@@ -0,0 +1,67 @@
"""Read-only source resolution. Analysis never copies or downloads a scene."""
import hashlib
import json
from pathlib import Path
def checksum(path, pulse=lambda: None):
h = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024**2), b""):
h.update(block)
pulse()
return h.hexdigest()
def resolve_sources(world, state, pulse=lambda: None):
"""Reuse the simulator's verified complete-scene artifact, including its frame.
Missing assets are a producer/preparation error, never permission to clone a
Gaussian Pipeline package into the mapping job. No mkdir or file writes here.
"""
root = (Path(state) / "project-packages" / world["sha256"]).resolve()
terrain_path = root / "terrain.json"
if not terrain_path.is_file():
raise ValueError("Worker has no prepared shared scene; prepare this location first")
terrain = json.loads(terrain_path.read_text(encoding="utf-8"))
if (
terrain.get("source_sha256") != world["sha256"]
or terrain.get("source_collider_sha256") != world["collider_sha256"]
or terrain.get("collision_rotation") != world["local_scene"]["collision_rotation"]
):
raise ValueError("Shared scene calibration or collider changed")
collider = root / (world["collider_sha256"] + ".decoded.glb")
metadata = json.loads(collider.with_suffix(".json").read_text(encoding="utf-8"))
if (
metadata["source_sha256"] != world["collider_sha256"]
or checksum(collider, pulse) != metadata["sha256"]
):
raise ValueError("Shared collider checksum mismatch")
candidates = []
for path in root.glob("*.json"):
if path == terrain_path or path.name.endswith(".decoded.json"):
continue
row = json.loads(path.read_text(encoding="utf-8"))
source = path.with_suffix(".ply")
if (
row.get("source_sha256") == world["sha256"]
and row.get("coverage") == "complete-source"
and row.get("spatially_cropped") is False
and source.is_file()
):
candidates.append((row.get("lod", 0), source, row))
if not candidates:
raise ValueError("Worker has no verified complete shared Gaussian representation")
# Preserve the best representation already present. No new LOD conversion.
lod, source, receipt = sorted(candidates, key=lambda c: c[0])[0]
if source.is_symlink() or collider.is_symlink() or checksum(source, pulse) != receipt["sha256"]:
raise ValueError("Shared Gaussian source changed")
return root, dict(
ply=source.name,
sha256=receipt["sha256"],
lod=lod,
world_sha256=world["sha256"],
collider_sha256=world["collider_sha256"],
source_to_world=[[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]],
)
@@ -0,0 +1,77 @@
"""Reuse verified survey derivatives across vectorizer releases without copying them."""
import hashlib
import json
import re
from pathlib import Path
from local_state import read_json, write_json
def file_hash(path):
result = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(8 * 1024**2), b''):
result.update(block)
return result.hexdigest()
def survey_identity(module, terrain, profile):
# Vector code may change without invalidating the measured survey. All code
# that creates cameras, renders, segments or projects ground remains bound.
files = {name: file_hash(module / name) for name in
('whole_scene.py', 'mapping.py', 'atlas.py', 'job.example.json')}
files['terrain.py'] = file_hash(terrain)
content = dict(files=files, mapper_image=profile['mapper_image'],
semantic_model=profile['semantic_model'])
return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()
def verify_tiles(folder, request, pulse):
index = read_json(folder / 'tile-index.json')
if not index or not 0 < len(index.get('tiles', [])) <= 256:
raise ValueError('Missing completed survey index')
for tile in index['tiles']:
pulse()
if not re.fullmatch(r'tile-\d{3}-\d{3}', tile['id']):
raise ValueError('Invalid survey tile path')
if tile['status'] == 'no-surface':
continue
if tile['status'] not in ('surveyed', 'unobserved-ground'):
raise ValueError('Survey is incomplete')
part = folder / tile['id']
receipt = read_json(part / 'survey-receipt.json')
job = read_json(part / 'job.json')
if (not receipt or not job or receipt['status'] != tile['status']
or receipt['job_sha256'] != file_hash(part / 'job.json')
or job['source'] != request['source'] or job['model'] != request['model']):
raise ValueError('Survey input identity changed')
if set(receipt['files']) != {'top.png', 'top.geometry.npz', 'surface-atlas.npz'}:
raise ValueError('Unexpected survey artifacts')
for name, expected in receipt['files'].items():
if file_hash(part / name) != expected:
raise ValueError('Survey artifact changed')
return index
def record_survey(folder, request, identity, pulse):
verify_tiles(folder, request, pulse)
write_json(folder / 'survey-cache.json', dict(
schema_version='missioncore.infrastructure-survey-cache/v1',
survey_sha256=identity, source=request['source'], model=request['model'],
index_sha256=file_hash(folder / 'tile-index.json')))
def find_survey(jobs, request, identity, pulse):
for path in sorted(jobs.glob('*/survey-cache.json')):
try:
record = read_json(path)
if (record['schema_version'] != 'missioncore.infrastructure-survey-cache/v1'
or record['survey_sha256'] != identity
or record['source'] != request['source'] or record['model'] != request['model']
or record['index_sha256'] != file_hash(path.parent / 'tile-index.json')):
continue
verify_tiles(path.parent, request, pulse)
return path.parent
except (OSError, ValueError, KeyError, TypeError):
continue
return None
@@ -0,0 +1,41 @@
"""Infrastructure observations survive control-plane loss; commands stay fenced."""
import http.client
from core_client import CoreRequestRejected
EXPIRED_SESSION = "Сессия Worker истекла; требуется переподключение."
def unavailable(exc):
return isinstance(exc, (OSError, http.client.HTTPException)) or (
isinstance(exc, CoreRequestRejected) and 500 <= exc.status <= 599
)
def registered_request(client, endpoint, body=None, *, hello=None, **kwargs):
"""Retry only an explicit pre-execution session rejection, with the same owner.
Callers use this for reads and idempotent observations/receipts, never dispatch.
A cancellation, changed owner or invalid result is not a transport outage.
"""
try:
return client.request(endpoint, body, **kwargs)
except CoreRequestRejected as exc:
if exc.status != 409 or exc.detail != EXPIRED_SESSION or hello is None:
raise
if hello["instance_id"] != client.instance:
raise ValueError("Infrastructure reconnect owner changed") from exc
client.request("/worker/register", hello)
return client.request(endpoint, body, **kwargs)
def report_progress(client, endpoint, phase, *, hello=None):
# A missed observation must never unwind run_container's cleanup guard.
# The next pulse sends the latest local progress, without a growing queue.
try:
return registered_request(client, endpoint, dict(action="progress", **phase), hello=hello)
except Exception as exc:
if not unavailable(exc):
raise
return None
+11
View File
@@ -260,7 +260,10 @@ def main():
}
from k1link.simulation.ai_polygon.route_preparation import provider_identity
from infrastructure_preparer import capability, prepare_infrastructure, reconcile
hello = {
"infrastructure_provider_sha256": capability(args.state),
"route_provider_sha256": provider_identity(),
"worker_id": "worker-006-ai-polygon",
"instance_id": instance,
@@ -346,8 +349,10 @@ def main():
connect()
editor_marker = args.state / "editor-active.json"
route_marker = args.state / "route-active.json"
infrastructure_marker = args.state / "infrastructure-active.json"
while True:
try:
reconcile(client, infrastructure_marker, hello)
# A prior coordinator's Windows Job killed all native descendants on exit.
# Retain the marker until Core accepts that resource-release receipt.
if route_marker.exists():
@@ -361,6 +366,9 @@ def main():
polled = client.request("/worker/poll", {"instance_id": instance})
except Exception:
connect()
# A pending receipt may fail while registration succeeds. Bound
# retries without discarding its marker or busy-looping on Core.
time.sleep(3)
continue
if polled["action"] == "idle":
time.sleep(0.5)
@@ -386,6 +394,9 @@ def main():
editor_job.close()
# Receipt is sent at the top of the loop, after the Job is closed.
continue
if polled["action"] == "infrastructure-analysis":
prepare_infrastructure(client, polled["analysis"], args.state, infrastructure_marker, hello)
continue
run = polled["run"]
if run.get("clock") != "realtime":
raise RuntimeError("A realtime worker cannot execute lockstep work")
@@ -103,6 +103,19 @@ class PlanLibraryUpdate(Contract):
removed: bool | None = Field(default=None, strict=True)
class WorldLibraryUpdate(Contract):
display_name: str | None = Field(default=None, min_length=1, max_length=120)
removed: bool | None = Field(default=None, strict=True)
@model_validator(mode="after")
def require_change(self):
if self.display_name is None and self.removed is None:
raise ValueError("Укажите название или действие с локацией.")
if self.display_name and any(ord(c) < 32 for c in self.display_name):
raise ValueError("Название содержит недопустимые символы.")
return self
class WorkerWorldCreate(WorldCreate):
"""Attestation from the connected Worker after validating its local files."""
@@ -151,6 +164,7 @@ class WorkerHello(Contract):
rover_settings_versions: list[Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"]] = Field(
default_factory=list, max_length=2
)
infrastructure_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
route_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
execution_inputs_versions: list[
Literal[
@@ -0,0 +1,332 @@
"""Durable, content-bound whole-scene analysis using the simulation GPU reservation."""
import hashlib
import json
import re
import threading
import time
import uuid
from pathlib import Path
from .run_inputs import digest
def write_json(path, value):
# The Windows coordinator imports provider_identity before any model runtime.
from .worlds import write_json as persist
persist(path, value)
def provider_identity():
root = Path(__file__).resolve().parents[4]
module = root / "simulation/urban-mapping"
files = [
p
for p in module.rglob("*")
if p.is_file()
and p.suffix in {".py", ".json"}
and ".build" not in p.parts
and "__pycache__" not in p.parts
]
files += [
*[
root / ("simulation/ai-polygon/" + n + ".py")
for n in (
"infrastructure_preparer",
"infrastructure_transport",
"infrastructure_sources",
"infrastructure_survey_cache",
"infrastructure_containers",
"core_client",
"terrain",
)
]
]
# Exact declared algorithm closure, including presets and metric policies.
research = root / "simulation/urban-plan-research"
definition = json.loads((research / "pipeline/definition.json").read_text(encoding="utf-8"))
relative = {value for group in definition["groups"] for value in group["files"].values()}
relative.update(
{
"pipeline/definition.json",
"pipeline/config-mv.json",
"pipeline/config-ortho.json",
"pipeline/worker-profile.json",
}
)
files += [research / name for name in sorted(relative)]
files += [
root / "simulation/ai-polygon" / (name + ".py")
for name in (
"infrastructure_pipeline",
"infrastructure_gaussian_sources",
"infrastructure_document",
)
]
return digest(
{p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
)
class InfrastructureJobs:
def __init__(self, data_dir):
self.root = Path(data_dir) / "ai-polygon/infrastructure-jobs"
self.root.mkdir(parents=True, exist_ok=True)
self.lock = threading.RLock()
def path(self, key):
if not re.fullmatch("[a-f0-9]{64}", key):
raise ValueError("Invalid analysis identity")
return self.root / (key + ".json")
def get(self, key):
row = json.loads(self.path(key).read_text(encoding="utf-8"))
if row["key"] != key or digest(row["identity"]) != key:
raise ValueError("Analysis identity changed")
return row
def current(self, world):
provider = provider_identity()
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
rows = [
r
for r in rows
if r["identity"]["world_sha256"] == world["sha256"]
and r["identity"]["collider_sha256"] == world.get("collider_sha256")
and r["identity"]["provider_sha256"] == provider
]
return max(rows, key=lambda r: r["created_at"], default=None)
def request(self, world, force=False, request_id=None):
with self.lock:
if not world.get("local_scene"):
raise ValueError(
"Для анализа нужен исходный Gaussian-проект с маршрутом сканирования."
)
identity = dict(
world_sha256=world["sha256"],
collider_sha256=world.get("collider_sha256"),
scene=world["local_scene"],
provider_sha256=provider_identity(),
scope="whole-scene",
)
# Force creates a new content-bound generation, never overwrites the
# old ready map. Retried HTTP requests share one request identity.
if force:
if not isinstance(request_id, str) or not re.fullmatch("[a-f0-9]{32}", request_id):
raise ValueError("A recalculation requires a request identity")
identity["generation"] = request_id
key = digest(identity)
if force and self.path(key).exists():
return self.get(key)
current = self.current(world)
if current and (
current["status"] in ("queued", "running") or not current.get("released", True)
):
return current
if not force and current and current["status"] == "ready":
return current
if self.path(key).exists():
row = self.get(key)
if row["status"] not in ("failed", "cancelled") or not row.get("released", True):
return row
return self.request(world, True, request_id or uuid.uuid4().hex)
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
if (
sum(
r["status"] in ("queued", "running") or not r.get("released", True)
for r in rows
)
>= 32
):
raise RuntimeError(
"Очередь заполнена: дождитесь завершения или отмените лишние расчёты."
)
sequence = max((r.get("queue_sequence", 0) for r in rows), default=0) + 1
row = dict(
queue_sequence=sequence,
key=key,
identity=identity,
world=world,
status="queued",
owner=None,
phase="queued",
completed=0,
total=0,
error=None,
result=None,
created_at=time.time(),
released=True,
)
write_json(self.path(key), row)
return row
def pending(self):
with self.lock:
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
# A source-tree digest is only needed to admit queued work. Idle
# worker polls and cleanup must not repeatedly hash the module.
provider = provider_identity() if any(r["status"] == "queued" for r in rows) else None
for row in rows:
if row["status"] == "queued" and row["identity"]["provider_sha256"] != provider:
row.update(
status="failed", error="Модуль анализа обновлён. Запустите анализ заново."
)
write_json(self.path(row["key"]), row)
rows = [
r
for r in rows
if r["status"] in ("queued", "running") or not r.get("released", True)
]
# Cleanup ownership precedes waiting jobs, including after a crash.
return min(rows, key=self.queue_order, default=None)
@staticmethod
def queue_order(row):
return (
0 if not row.get("released", True) else 1,
row.get("queue_sequence", 0),
row["created_at"],
row["key"],
)
def queue_rows(self):
with self.lock:
rows = [json.loads(p.read_text(encoding="utf-8")) for p in self.root.glob("*.json")]
return sorted(
[
r
for r in rows
if r["status"] in ("queued", "running") or not r.get("released", True)
],
key=self.queue_order,
)
def present(self, row):
if not row:
return None
result = public_job(row)
rows = self.queue_rows()
keys = [r["key"] for r in rows]
result["queue"] = dict(
position=keys.index(row["key"]) + 1 if row["key"] in keys else None,
total=len(rows),
waiting=sum(r["status"] == "queued" for r in rows),
)
if row.get("cancel_requested") and not row.get("released", True):
result["progress"].update(
label="Отмена · освобождаем Worker", eta_seconds=None, fraction=None
)
return result
def cancel(self, key):
with self.lock:
row = self.get(key)
if row["status"] in ("ready", "failed", "cancelled"):
return row
row["cancel_requested"] = True
row["cancel_requested_at"] = time.time()
if row["status"] == "queued":
row.update(status="cancelled", phase="cancelled", finished_at=time.time())
# Running stays owned until the worker's existing finally/cleanup
# sends release. A progress rejection interrupts its bounded stage.
write_json(self.path(key), row)
return row
def dispatch(self, owner, queue, worker_provider):
# Keep selection, GPU reservation and claim atomic with cancellation.
# Otherwise cancellation between reserve and claim strands the lease.
with self.lock:
row = self.pending()
if not row or row["status"] not in ("queued", "running"):
return None
if row["identity"]["provider_sha256"] != worker_provider:
return None
if row.get("cancel_requested") or row["owner"] not in (None, owner):
return None
queue.reserve_simulation("aicache-" + row["key"])
return self.claim(row["key"], owner)
def claim(self, key, owner):
with self.lock:
row = self.get(key)
pending = self.pending()
if not pending or pending["key"] != key:
raise RuntimeError("Analysis must wait its FIFO turn")
if row.get("cancel_requested"):
raise RuntimeError("Analysis cancellation requested")
if row["owner"] not in (None, owner) or row["status"] not in ("queued", "running"):
raise RuntimeError("Analysis belongs to another Worker session")
row.setdefault("started_at", time.time())
row.update(status="running", owner=owner, released=False, updated_at=time.time())
write_json(self.path(key), row)
return row
def update(self, key, body, owner):
with self.lock:
row = self.get(key)
action = body.get("action")
if row["owner"] != owner and not (
action == "release" and body.get("previous_owner") == row["owner"]
):
raise RuntimeError("Analysis owner changed")
if row.get("cancel_requested") and action in ("progress", "complete"):
raise RuntimeError("Analysis cancellation requested")
if action == "progress" and row["status"] == "running":
phase = body.get("phase")
if phase not in ("preparing", "survey", "vectorizing", "assembling", "refining"):
raise ValueError("Invalid analysis phase")
done, total = body.get("completed", 0), body.get("total", 0)
if type(done) is not int or type(total) is not int or not 0 <= done <= total <= 256:
raise ValueError("Invalid analysis progress")
if row.get("total") and (total != row["total"] or done < row["completed"]):
raise ValueError("Analysis progress cannot move backwards")
from .infrastructure_progress import record_progress
record_progress(row, phase, done, total, time.time())
elif action == "complete" and row["status"] == "running":
row.update(
status="ready",
phase="ready",
result=body["result"],
error=None,
finished_at=time.time(),
)
elif action == "fail" and row["status"] != "ready":
row.update(
status="failed",
error=(
"Анализ не завершён. Предыдущая карта сохранена; можно повторить попытку."
),
)
elif action == "release":
if row["status"] == "running":
row.update(
status="failed",
error=(
"Worker прервал анализ. Предыдущая карта сохранена; повторите попытку."
),
)
row["released"] = True
else:
raise ValueError("Invalid analysis state transition")
if row.get("cancel_requested") and action in ("fail", "release"):
row.update(
status="cancelled", phase="cancelled", error=None, finished_at=time.time()
)
write_json(self.path(key), row)
return row
def public_job(row):
if not row:
return None
from .infrastructure_progress import progress_view
public = {
k: v for k, v in row.items() if k not in ("owner", "world", "identity", "stage_history")
}
public["request_id"] = row["identity"].get("generation")
public["progress"] = progress_view(row)
return public
@@ -0,0 +1,130 @@
"""Measured stage history and an explicitly approximate remaining-time forecast.
A historical full infrastructure run seeds weights, never the arrow-only path.
Progress counts completed stages; time never advances the completion fraction.
"""
import json
import math
import statistics
import time
from functools import lru_cache
from pathlib import Path
PHASES = {
"queued": "В очереди",
"preparing": "Подготовка локации",
"survey": "Обзор локации",
"vectorizing": "Распознавание инфраструктуры",
"assembling": "Сборка карты",
"refining": "Уточнение объектов",
"ready": "Готово",
}
def stage_label(group, stage):
if stage == "pose_survey":
return "Обзор локации"
if "render" in stage:
return "Построение видов сцены"
if "semantic" in stage or stage in ("mv_infer", "ortho_segment"):
return "Распознавание объектов"
if "audit" in stage or "verify" in stage or "admission" in stage:
return "Проверка объектов"
if "arrow" in group or "arrow" in stage:
return "Восстановление стрелок"
if "bicycle" in group or "compact" in stage:
return "Восстановление велоразметки"
if "cross" in group or "cross" in stage:
return "Восстановление переходов"
if "linear" in group or "zigzag" in group:
return "Восстановление линий"
if group == "base":
return "Определение поверхностей"
return "Согласование инфраструктуры"
@lru_cache(maxsize=1)
def plan():
root = Path(__file__).resolve().parents[4] / "simulation/urban-plan-research/pipeline"
definition = json.loads((root / "definition.json").read_text())
stages = [(g["group"], s) for g in definition["groups"] for s in g["stages"]]
profile = (
json.loads((root / "timing-profile.json").read_text())
if (root / "timing-profile.json").exists()
else {"stages": []}
)
measured = {
(("base" if r["group"] == "geometry" else r["group"]), r["stage"]): r["seconds"]
for r in profile["stages"]
}
fallback = statistics.median(measured.values()) if measured else None
return [
dict(
group=g,
stage=s,
label=stage_label(g, s),
seconds=measured.get((g, s), fallback),
measured=(g, s) in measured,
)
for g, s in stages
], profile.get("job_key")
def record_progress(row, phase, done, total, now):
previous = (row["phase"], row["completed"], row["total"])
if previous != (phase, done, total):
row["stage_started_at"] = now
history = row.setdefault("stage_history", [])
history.append(dict(phase=phase, completed=done, total=total, at=now))
if len(history) > 257:
raise ValueError("Analysis progress history exceeds stage budget")
if total and "pipeline_started_at" not in row:
row["pipeline_started_at"] = now
row.update(phase=phase, completed=done, total=total, updated_at=now)
def progress_view(row, now=None):
now = time.time() if now is None else now
stages, reference = plan()
total = len(stages)
done = row.get("completed", 0)
status = row["status"]
running = status == "running"
pending = status in ("queued", "running")
comparable = row.get("total", 0) in (0, total)
label = PHASES.get(row["phase"], "Расчёт инфраструктуры")
if running and row.get("total") == total:
label = stages[min(done, total - 1)]["label"]
stale = running and now - row.get("updated_at", row.get("started_at", now)) > 20
eta = None
basis = "previous-full-run"
if pending and comparable and all(s["seconds"] is not None for s in stages):
weights = [s["seconds"] for s in stages]
scale = 1.0
if running and done > 0 and row.get("pipeline_started_at") is not None:
completed_seconds = max(
0, row.get("stage_started_at", now) - row["pipeline_started_at"]
)
baseline = sum(weights[:done])
if completed_seconds > 0 and baseline > 0:
scale = completed_seconds / baseline
basis = "current-run-and-history"
elapsed = (
max(0, now - row.get("stage_started_at", now)) if running and row.get("total") else 0
)
remaining = sum(weights[done:]) * scale - elapsed
# Never promise zero while a real stage is still running.
eta = max(60, math.ceil(remaining / 60) * 60)
return dict(
label="Нет обновлений от Worker" if stale else label,
stage=min(done + 1, total) if running and row.get("total") == total else None,
stages=total if comparable else row.get("total"),
fraction=done / total if running and row.get("total") == total else None,
eta_seconds=None if stale else eta,
eta_basis=basis,
estimate_reference=reference,
estimate_scope="processing-excludes-queue-and-source-preparation",
stale=stale,
elapsed_seconds=max(0, now - row["started_at"]) if "started_at" in row else None,
)
+1 -1
View File
@@ -5,7 +5,7 @@ import re
from k1link.simulation.ai_polygon.worlds import write_json
IDENTITY = re.compile(r"^(?:aiplan|airun)-[a-f0-9]{32}$")
IDENTITY = re.compile(r"^(?:aiplan|airun|aiworld)-[a-f0-9]{32}$")
class LibraryMetadata:
File diff suppressed because one or more lines are too long
@@ -47,6 +47,9 @@ class ProjectWorlds:
"artifacts": project["artifacts"],
}
digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
files = self.cache_files(
{"storage": {"project_id": project["project_id"]}, "local_scene": scene}
)
return {
"schema_version": "missioncore.ai-polygon-world/v1",
"world_id": project["project_id"].replace("sim-", "aiworld-", 1),
@@ -62,15 +65,14 @@ class ProjectWorlds:
"splat_count": None,
"created_at": project["created_at_utc"],
"settings": WorldSettings(
prepared=bool(scene["collision_url"]), rotation_degrees=(90, 0, 0)
prepared=True, rotation_degrees=(90, 0, 0)
).model_dump(mode="json"),
"storage": {"kind": "project", "project_id": project["project_id"]},
"local_scene": scene,
"collider_sha256": self.cache_files(
{"storage": {"project_id": project["project_id"]}, "local_scene": scene}
)["collision.glb"]["sha256"],
"inference_ready": True,
"collider_sha256": files.get("collision.glb", {}).get("sha256"),
"inference_ready": "collision.glb" in files,
"inference_message": None if "collision.glb" in files else
"Скан доступен для просмотра. Для запуска ровера нужна поверхность коллизий.",
}
def package(self, world):
@@ -78,6 +80,7 @@ class ProjectWorlds:
prefix = f"/api/v1/simulation-worlds/projects/{project['project_id']}/artifacts/"
paths = {
k: unquote(world["local_scene"][k + "_url"].removeprefix(prefix))
if world["local_scene"].get(k + "_url") else None
for k in ("visual", "collision")
}
artifacts = [
@@ -95,6 +98,55 @@ class ProjectWorlds:
"collision_path": paths["collision"],
}
def analysis_package(self, world):
"""Read original source identity and optional native trajectory, not meshes."""
import base64
project = self.projects.get(world["storage"]["project_id"])
if self.world(project)["sha256"] != world["sha256"]:
raise ValueError("Gaussian project changed")
source = project["source"]
result = dict(world_sha256=world["sha256"], project_id=project["project_id"],
provider_job_id=project["provider"]["job_id"],
bundle_sha256=source["bundle_sha256"], kind=source["kind"],
files=[{k: f[k] for k in ("logical_path", "byte_length", "sha256")}
for f in source["files"]], trajectory=None)
if source["kind"] == "folder":
from pathlib import PurePosixPath
candidates = [f for f in source["files"]
if PurePosixPath(f["logical_path"]).name.lower() == "poses.json"]
if len(candidates) != 1:
raise ValueError("Original Gaussian folder needs one poses.json")
item = candidates[0]
if not 0 < item["byte_length"] <= 16 * 1024**2:
raise ValueError("Trajectory exceeds analysis transport budget")
root = self.projects.source_root(project["project_id"]).resolve()
path = root / item["logical_path"]
if path.is_symlink() or not path.resolve().is_relative_to(root):
raise ValueError("Trajectory escaped its project")
raw = path.read_bytes()
if len(raw) != item["byte_length"] or hashlib.sha256(raw).hexdigest() != item["sha256"]:
raise ValueError("Original trajectory changed")
result["trajectory"] = dict(sha256=item["sha256"], byte_length=len(raw),
base64=base64.b64encode(raw).decode("ascii"))
return result
def analysis_archive(self, world):
"""Serve only the original archive belonging to this exact world."""
project = self.projects.get(world["storage"]["project_id"])
if self.world(project)["sha256"] != world["sha256"]:
raise ValueError("Gaussian project changed")
source = project["source"]
if source["kind"] != "archive" or len(source["files"]) != 1:
raise ValueError("Project does not contain one original archive")
descriptor = source["files"][0]
root = self.projects.source_root(project["project_id"]).resolve()
path = root / descriptor["logical_path"]
if path.is_symlink() or not path.resolve().is_relative_to(root):
raise ValueError("Original archive escaped its project")
if not path.is_file() or path.stat().st_size != descriptor["byte_length"]:
raise FileNotFoundError("Original archive is unavailable")
return path, descriptor
def cache_files(self, world):
result = {}
project_id = world["storage"]["project_id"]
@@ -103,6 +155,8 @@ class ProjectWorlds:
("scene.sog", world["local_scene"]["visual_url"]),
("collision.glb", world["local_scene"]["collision_url"]),
):
if name == "collision.glb" and not url:
continue
if not url or not url.startswith(prefix):
raise ValueError("В локации отсутствует локальная сцена или поверхность.")
path, descriptor = self.projects.artifact_path(project_id, unquote(url[len(prefix) :]))
@@ -0,0 +1,52 @@
"""Lossless admission of a qualified Gaussian plan to the existing viewer."""
import copy
import hashlib
import json
import re
from k1link.simulation.ai_polygon.urban_maps import validate_map
def qualified_document(raw: bytes, world: dict, *, artifact_sha256: str,
source_world_sha256: str, qualification: str,
source_snapshot: str, tiles_total: int) -> dict:
if hashlib.sha256(raw).hexdigest() != artifact_sha256:
raise ValueError("Qualified artifact content changed")
if source_world_sha256 != world["sha256"]:
raise ValueError("Qualified artifact belongs to another Gaussian scene")
if not re.fullmatch(r"[a-z0-9-]{1,100}", qualification):
raise ValueError("Invalid qualification identity")
if type(tiles_total) is not int or not 0 < tiles_total <= 10000:
raise ValueError("Invalid observed tile count")
plan = json.loads(raw)
if (plan.get("schema_version") not in {
"missioncore.refined-full-plan-research/v1", "missioncore.systematic-plan/v1"}
or plan.get("point_clouds") is not False
or plan.get("manual_geometry") is not False):
raise ValueError("Expected the qualified automatic Gaussian plan")
features = copy.deepcopy(plan["features"])
for feature in features:
p = feature["properties"]
if p.get("route_permission", "unassigned") != "unassigned":
raise ValueError("Plan cannot grant route permissions")
if p.get("authority", "observation-only") != "observation-only":
raise ValueError("Plan cannot escalate observation authority")
p["authority"] = "observation-only"
p["route_permission"] = "unassigned"
p.setdefault("review_status", "unreviewed")
if "confidence" not in p:
p.update(confidence=None, confidence_status="not-assessed")
result = {
"schema_version": "missioncore.urban-map/v3", "type": "FeatureCollection",
"coordinate_system": {"frame": "scene-local", "units": "metres", "up": "Z", "georeferenced": False},
"source": {"world_sha256": source_world_sha256,
"collider_sha256": world.get("collider_sha256"),
"gaussian_only": True, "collider_input": False,
"artifact_sha256": artifact_sha256,
"qualification": qualification, "source_snapshot": source_snapshot},
"coverage": {"cell_m": .05, "accepted_cells": 0, "kind": "objects-only", "measured": False},
"analysis": {"scope": "whole-scene", "tiles_total": tiles_total},
"logical_layers": ["roads", "pedestrian_zones", "buildings", "road_markings"],
"features": features,
}
return validate_map(result, world)
@@ -72,11 +72,20 @@ def write_json(path, row):
persist(path, row)
def _file_signature(path):
value = path.stat(follow_symlinks=False)
return (value.st_dev, value.st_ino, value.st_size,
value.st_mtime_ns, value.st_ctime_ns)
class RoutePreparationStore:
def __init__(self, data_dir):
self.root = Path(data_dir) / "ai-polygon/route-preparations"
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
self.lock = threading.RLock()
# Only inactive file metadata is cached. Active jobs and claims always
# re-read and validate their content and ownership.
self._inactive_files = {}
def path(self, key):
if not KEY.fullmatch(key):
@@ -122,10 +131,23 @@ class RoutePreparationStore:
def pending(self):
with self.lock:
for path in sorted(self.root.glob("*.json")):
paths = sorted(self.root.glob("*.json"))
present = {path.name for path in paths}
self._inactive_files = {name: stamp for name, stamp in self._inactive_files.items()
if name in present}
for candidate in paths:
path = self.path(candidate.stem)
before = _file_signature(path)
if self._inactive_files.get(path.name) == before:
continue
row = json.loads(path.read_text())
if row["status"] in {"queued", "preparing"}:
self._inactive_files.pop(path.name, None)
return self.get(path.stem)
if row["status"] in {"ready", "failed"} and before == _file_signature(path):
if len(self._inactive_files) >= 512:
self._inactive_files.pop(next(iter(self._inactive_files)))
self._inactive_files[path.name] = before
return None
def claim(self, key, owner):
+3 -1
View File
@@ -239,7 +239,9 @@ class RunStore:
raise RuntimeError("Контроль занятости Worker недоступен.")
if self.active is not None:
raise RuntimeError("Сначала завершите текущий прогон.")
world = self.worlds.get(request.world_id)
from .world_library import WorldLibrary
world = WorldLibrary(self.worlds).require_visible(request.world_id)
if world.get("inference_ready") is False:
raise RuntimeError(world["inference_message"])
if world.get("local_scene") and "project-sog" not in self.worker.get(
@@ -0,0 +1,470 @@
"""Small human map revisions. No images, training or automatic-map publication."""
import copy
import hashlib
import json
import math
import re
from datetime import UTC, datetime
from k1link.cache_budget import cache_publication
from k1link.simulation.ai_polygon.semantic_objects import is_rigid_marking, object_operation
from k1link.simulation.ai_polygon.semantic_vectors import vector_operation
from k1link.simulation.ai_polygon.urban_maps import validate_map
from k1link.simulation.ai_polygon.worlds import write_json
HASH = re.compile(r"[0-9a-f]{64}")
REQUEST = re.compile(r"[a-zA-Z0-9_-]{16,80}")
MAX_STATE = 8 * 1024**2
# A collection contains at most 256 bounded four-window shards. This is receipt
# metadata, not a relaxation of geometry or training admission.
MAX_OBSERVATION_WINDOWS = 256 * 4
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
def paths(feature):
geometry = feature["geometry"]
return geometry["coordinates"] if geometry["type"] == "Polygon" else [geometry["coordinates"]]
def _cross(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def _intersects(a, b, c, d):
if any(max(a[k], b[k]) < min(c[k], d[k]) or max(c[k], d[k]) < min(a[k], b[k]) for k in (0, 1)):
return False
return _cross(a, b, c) * _cross(a, b, d) <= 0 and _cross(c, d, a) * _cross(c, d, b) <= 0
def validate_path(points, closed):
if len(points) < (4 if closed else 2) or len(points) > 4096:
raise ValueError("Недопустимое число точек контура.")
if closed and points[0] != points[-1]:
raise ValueError("Контур должен быть замкнут.")
for point in points:
if len(point) != 3 or any(
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6 for v in point
):
raise ValueError("Некорректные координаты.")
segments = list(zip(points, points[1:], strict=False))
if any(a[:2] == b[:2] for a, b in segments):
raise ValueError("Совпадающие точки контура.")
for a, b, c in zip(points, points[1:], points[2:], strict=False):
if _cross(a, b, c) == 0 and sum((a[k] - b[k]) * (c[k] - b[k]) for k in (0, 1)) > 0:
raise ValueError("Контур возвращается по собственному сегменту.")
for i, (a, b) in enumerate(segments):
for j in range(i + 2, len(segments)):
if closed and i == 0 and j == len(segments) - 1:
continue
c, d = segments[j]
# Plan editing is admitted only for the affected path; other objects
# and pre-existing geometry are not normalized or re-approximated.
if _intersects(a, b, c, d):
raise ValueError("Правка создаёт самопересечение контура в плане.")
if closed and sum(a[0] * b[1] - b[0] * a[1] for a, b in segments) == 0:
raise ValueError("Контур не имеет площади.")
def _inside(point, ring):
x, y = point[:2]
inside = False
for a, b in zip(ring, ring[1:], strict=False):
if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
inside = not inside
return inside
def validate_holes(rings):
for i, ring in enumerate(rings):
for other in rings[i + 1 :]:
if any(
_intersects(a, b, c, d)
for a, b in zip(ring, ring[1:], strict=False)
for c, d in zip(other, other[1:], strict=False)
):
raise ValueError("Границы полигона пересекаются.")
if i and (
not _inside(ring[0], rings[0])
or any(_inside(ring[0], hole) for j, hole in enumerate(rings[1:], 1) if i != j)
):
raise ValueError("Внутренняя граница должна оставаться внутри своей области.")
def apply_operations(document, operations, *, verified_history=False, origin="human-edit"):
if not isinstance(operations, list) or not 1 <= len(operations) <= 256:
raise ValueError("Сохраните от 1 до 256 действий за один раз.")
result = document if verified_history else copy.deepcopy(document)
changed = False
by_id = {f.get("id"): f for f in result["features"]}
for op in operations:
if not isinstance(op, dict):
raise ValueError("Некорректное действие.")
kind = op.get("kind")
if kind == "region":
validate_path(op.get("brush", []), True)
curved = (
isinstance(op.get("feature_id"), str)
and kind in ("move", "insert", "delete")
and bool(
by_id.get(op.get("feature_id"), {})
.get("properties", {})
.get("editor_curves", {})
.get(str(op.get("path")))
)
)
if (
kind
in (
"retemplate",
"place",
"transform",
"remove",
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
)
or curved
):
handler = (
object_operation
if kind in ("place", "transform", "remove", "retemplate")
else vector_operation
)
updated = handler(result["features"], op, origin)
if updated is result["features"]:
continue
if not verified_history:
previous = {f["id"]: f for f in result["features"]}
for f in updated:
if (
previous.get(f["id"]) is f
or f["properties"].get("review_status") == "rejected"
):
continue
rings = paths(f)
for ring in rings:
validate_path(ring, f["geometry"]["type"] == "Polygon")
if f["geometry"]["type"] == "Polygon":
validate_holes(rings)
result["features"] = updated
by_id = {f["id"]: f for f in updated}
changed = True
continue
fields = {"kind", "feature_id", "path", "index"}
fields |= {"position"} if kind == "move" else {"t"} if kind == "insert" else set()
if kind not in ("move", "insert", "delete") or set(op) != fields:
raise ValueError("Неизвестное действие.")
feature = by_id.get(op["feature_id"]) if isinstance(op["feature_id"], str) else None
if not feature or feature["properties"].get("review_status") == "rejected":
raise ValueError("Выберите существующий видимый контур.")
if not verified_history and is_rigid_marking(feature):
raise ValueError("Элемент разметки перемещается целиком; вершины не редактируются.")
rings = paths(feature)
path, index = op["path"], op["index"]
if type(path) is not int or not 0 <= path < len(rings):
raise ValueError("Контур не найден.")
points = rings[path]
closed = feature["geometry"]["type"] == "Polygon"
count = len(points) - int(closed)
if type(index) is not int or not 0 <= index < count:
raise ValueError("Точка не найдена.")
if kind == "insert":
t = op["t"]
if index >= len(points) - 1 or type(t) not in (int, float) or not 0 < t < 1:
raise ValueError("Новая точка должна лежать внутри выбранного сегмента.")
a, b = points[index : index + 2]
points.insert(index + 1, [a[k] + t * (b[k] - a[k]) for k in range(3)])
elif kind == "move":
point = op["position"]
if (
not isinstance(point, list)
or len(point) != 3
or any(
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6
for v in point
)
):
raise ValueError("Некорректные координаты.")
if point[2] != points[index][2]:
raise ValueError("Редактирование в плане сохраняет исходную высоту.")
if point == points[index]:
continue
points[index] = point[:]
else:
points.pop(index)
if closed:
points[-1] = points[0][:]
if not verified_history:
validate_path(points, closed)
if closed and len(rings) > 1 and not verified_history:
validate_holes(rings)
feature["properties"] = {
**feature["properties"],
"confidence": None,
"confidence_status": "not-assessed",
"review_status": "unreviewed",
"annotation_origin": origin,
}
changed = True
if not changed:
return result
# A human draft is not Gaussian-only inference or a training-ready truth.
result["schema_version"] = "missioncore.urban-edit/v1"
result["source"] = {k: v for k, v in result["source"].items() if k != "gaussian_only"}
return result
class SemanticEdits:
def __init__(self, data_dir, maps):
self.root = data_dir / "ai-polygon" / "semantic-edits"
self.maps = maps
def _path(self, world):
if not HASH.fullmatch(world["sha256"]):
raise ValueError("Некорректная версия сцены.")
return self.root / (world["sha256"] + ".json")
def _read(self, world):
path = self._path(world)
if not path.exists():
return {"schema_version": "missioncore.semantic-edits/v1", "revisions": []}
if path.is_symlink() or path.stat().st_size > MAX_STATE:
raise ValueError("Хранилище правок не прошло проверку.")
state = json.loads(path.read_text())
revisions = state["revisions"]
for i, row in enumerate(revisions):
payload = {k: v for k, v in row.items() if k != "revision"}
if digest(payload) != row["revision"] or row["parent"] != (
revisions[i - 1]["revision"] if i else None
):
raise ValueError("Нарушена целостность истории правок.")
return state
def _model(self, world, sha):
if not isinstance(sha, str) or not HASH.fullmatch(sha):
raise ValueError("Некорректная версия алгоритма.")
path = self.maps.directory(world) / (sha + ".json")
if path.is_symlink():
raise ValueError("Недопустимая ссылка на карту.")
document = json.loads(path.read_text())
if digest(document) != sha:
raise ValueError("Исходная карта изменилась.")
validate_map(document, world)
if document["schema_version"] == "missioncore.urban-map/v1":
raise ValueError("Для редактора нужна векторная карта инфраструктуры.")
return document
def _view(self, world, state):
revisions = state["revisions"]
latest = self.maps.get(world)
sha = revisions[0]["model_sha256"] if revisions else digest(latest)
model = self._model(world, sha)
edited = copy.deepcopy(model) if revisions else model
for row in revisions:
if row["model_sha256"] != sha:
raise ValueError("Изменилась основа ручной версии.")
edited = apply_operations(
edited,
row["operations"],
verified_history=True,
origin=row.get("origin", "human-edit"),
)
return self._response(state, model, edited, sha, digest(latest))
@staticmethod
def _response(state, model, edited, sha, latest_sha):
revisions = state["revisions"]
head = revisions[-1] if revisions else None
return {
"schema_version": "missioncore.semantic-editor/v1",
"model_sha256": sha,
"latest_model_sha256": latest_sha,
"revision": head["revision"] if head else None,
"model": model,
"edited": edited,
"history": [
{
"revision": r["revision"],
"created_at": r["created_at"],
"actions": len(r["operations"]),
}
for r in revisions
],
"learning": {
"state": "queued" if head else "no-edits",
**(state.get("deliveries", {}).get(head["revision"], {}) if head else {}),
"dataset_ready": False,
},
}
def get(self, world):
return self._view(world, self._read(world))
def export(self, world, revision):
"""Portable annotation metadata, explicitly not an image dataset."""
state = self._read(world)
index = next(
(i for i, row in enumerate(state["revisions"]) if row["revision"] == revision),
None,
)
if index is None:
raise FileNotFoundError("Ревизия не найдена.")
rows = state["revisions"][: index + 1]
view = self._view(world, {**state, "revisions": rows})
package = {
"schema_version": "missioncore.semantic-annotation-export/v1",
"world_sha256": world["sha256"],
"collider_sha256": world.get("collider_sha256"),
"model_sha256": view["model_sha256"],
"revision": revision,
"model": view["model"],
"edited": view["edited"],
"revisions": rows,
"review": {"state": "draft", "complete_regions": [], "dataset_ready": False},
}
return {"sha256": digest(package), "package": package}
def save(self, world, body):
if not isinstance(body, dict) or set(body) - {"origin"} != {
"expected_revision",
"model_sha256",
"request_id",
"operations",
}:
raise ValueError("Некорректный запрос сохранения.")
if not isinstance(body["request_id"], str) or not REQUEST.fullmatch(body["request_id"]):
raise ValueError("Некорректный идентификатор сохранения.")
if body.get("origin", "human-edit") not in ("human-edit", "agent-proposal"):
raise ValueError("Некорректное происхождение правки.")
request_hash = digest(body)
# Reserve a bounded complete atomic replacement. Shared lock handles
# concurrent tabs/processes; an idempotent replay needs no new capacity.
with cache_publication(self.root, 0, limit=64 * 1024**2):
state = self._read(world)
revisions = state["revisions"]
for row in revisions:
if row["request_id"] == body["request_id"]:
if row["request_sha256"] != request_hash:
raise RuntimeError(
"Идентификатор сохранения уже использован для другой правки."
)
return self._view(world, state)
head = revisions[-1]["revision"] if revisions else None
if body["expected_revision"] != head:
raise RuntimeError("Карта изменена в другом окне. Откройте сохранённую версию.")
if not revisions:
# Use the displayed immutable model even if a new analysis just
# published; never silently rebase a human operation by index.
model = self._model(world, body["model_sha256"])
view = self._response(
state, model, model, body["model_sha256"], digest(self.maps.get(world))
)
else:
view = self._view(world, state)
if body["model_sha256"] != view["model_sha256"]:
raise RuntimeError("Правки относятся к другой основе.")
edited = apply_operations(
view["edited"], body["operations"], origin=body.get("origin", "human-edit")
)
if edited == view["edited"]:
raise ValueError("Нет изменений для сохранения.")
row = {
**body,
"parent": head,
"created_at": datetime.now(UTC).isoformat(),
"request_sha256": request_hash,
}
row["revision"] = digest(row)
state["revisions"].append(row)
raw = json.dumps(state, ensure_ascii=False, allow_nan=False).encode()
if len(raw) > MAX_STATE:
raise ValueError(
"Лимит локальных семантических правок достигнут. История сохранена."
)
# Account for the temporary replacement while the common lock is held.
import shutil
from k1link.cache_budget import FREE_RESERVE, usage
if usage(self.root)[0] + len(raw) > 64 * 1024**2 or shutil.disk_usage(
self.root
).free < FREE_RESERVE + len(raw):
raise ValueError("Недостаточно места для сохранения правок.")
write_json(self._path(world), state)
# Return the exact admitted geometry. Replaying the entire history
# here duplicated work and could fail after a successful commit.
return self._response(
state, view["model"], edited, view["model_sha256"], view["latest_model_sha256"]
)
def pending(self, worlds):
"""The revision itself is the durable outbox: no dual-write window."""
rows = []
for world in worlds:
state = self._read(world)
for revision in state["revisions"]:
if revision["revision"] not in state.get("deliveries", {}):
rows.append(
{
"world_id": world["world_id"],
"world_sha256": world["sha256"],
"revision": revision["revision"],
"created_at": revision["created_at"],
}
)
return sorted(rows, key=lambda r: (r["created_at"], r["revision"]))[:20]
def receipt(self, world, revision, body):
allowed = {"state", "package_sha256", "dataset_sha256", "sample_count"}
if not isinstance(body, dict) or set(body) != allowed:
raise ValueError("Некорректная квитанция.")
order = {"received": 1, "building": 2, "draft-ready": 3, "failed": 3}
if body["state"] not in order or not HASH.fullmatch(str(body["package_sha256"])):
raise ValueError("Некорректное состояние доставки.")
ready = body["state"] == "draft-ready"
if (
type(body["sample_count"]) is not int
or not 0 <= body["sample_count"] <= MAX_OBSERVATION_WINDOWS
or (
ready
and (not body["sample_count"] or not HASH.fullmatch(str(body["dataset_sha256"])))
)
or (not ready and (body["dataset_sha256"] is not None or body["sample_count"] != 0))
):
raise ValueError("Некорректный результат подготовки.")
with cache_publication(self.root, 0, limit=64 * 1024**2):
package = self.export(world, revision)
if body["package_sha256"] != package["sha256"]:
raise ValueError("Квитанция относится к другой аннотации.")
state = self._read(world)
deliveries = state.setdefault("deliveries", {})
previous = deliveries.get(revision)
if previous:
if previous == body or order[previous["state"]] > order[body["state"]]:
return previous
if order[previous["state"]] == 3:
raise RuntimeError("Завершённая квитанция неизменна.")
deliveries[revision] = body
raw = json.dumps(state, ensure_ascii=False, allow_nan=False).encode()
import shutil
from k1link.cache_budget import FREE_RESERVE, usage
if (
len(raw) > MAX_STATE
or usage(self.root)[0] + len(raw) > 64 * 1024**2
or shutil.disk_usage(self.root).free < FREE_RESERVE + len(raw)
):
raise ValueError("Недостаточно места для квитанции.")
write_json(self._path(world), state)
return body
@@ -0,0 +1,230 @@
"""Rigid marking operations shared by Core and the portable Worker builder."""
import copy
import json
import math
import re
from pathlib import Path
def catalog():
local = Path(__file__).with_name("marking-templates.json")
return json.loads(local.read_text())
def paths(f):
g = f["geometry"]
return g["coordinates"] if g["type"] == "Polygon" else [g["coordinates"]]
def is_rigid_marking(f):
p = f["properties"]
return p["class"] in ("road_marking", "crosswalk_marking") and not (
p["class"] == "road_marking"
and p.get("subtype") == "linear_marking"
and p.get("template_id") in (None, "", "linear_marking")
and not p.get("semantic_element_id")
)
def members(features, feature_id):
selected = next((f for f in features if f["id"] == feature_id), None)
if not selected or selected["properties"].get("review_status") == "rejected":
raise ValueError("Выберите существующий элемент.")
group = selected["properties"].get("semantic_element_id")
return (
[f for f in features if f["properties"].get("semantic_element_id") == group]
if group
else [selected]
)
def pivot(features):
points = [p for f in features for ring in paths(f) for p in ring]
return [(min(p[k] for p in points) + max(p[k] for p in points)) / 2 for k in range(3)]
def numbers(value, count):
return (
isinstance(value, list)
and len(value) == count
and all(type(v) in (int, float) and math.isfinite(v) and abs(v) <= 1e6 for v in value)
)
def object_operation(features, op, origin="human-edit"):
"""New list, unchanged objects retained; no-op returns the same list."""
kind = op.get("kind")
if kind == "retemplate":
if set(op) != {"kind", "feature_id", "template_id", "frame"}:
raise ValueError("Некорректная замена шаблона.")
chosen = members(features, op["feature_id"])
template = next((t for t in catalog()["templates"] if t["id"] == op["template_id"]), None)
frame = op["frame"]
if (
len(chosen) != 1
or chosen[0]["properties"]["class"] != "road_marking"
or not template
or len(template["polygons"]) != 1
or not isinstance(frame, list)
or len(frame) != 3
or not all(numbers(v, 3) for v in frame)
):
raise ValueError("Замена требует одного элемента и плоскости шаблона.")
origin_point, along, across = frame
lengths = [math.hypot(*v[:2]) for v in (along, across)]
if (
any(not 0.01 <= n <= 100 for n in lengths)
or abs(sum(along[k] * across[k] for k in (0, 1))) > 1e-8 * lengths[0] * lengths[1]
or along[0] * across[1] - along[1] * across[0] <= 0
or any(abs(v[2]) > n for v, n in zip((along, across), lengths, strict=True))
):
raise ValueError("Некорректные оси шаблона.")
q = copy.deepcopy(chosen[0])
q["geometry"] = dict(
type="Polygon",
coordinates=[
[
[origin_point[k] + p[0] * along[k] + p[1] * across[k] for k in range(3)]
for p in ring
]
for ring in template["polygons"][0]
],
)
q["properties"].pop("editor_curves", None)
q["properties"].update(
template_id=template["id"],
template_source=template["source"],
template_frame=frame,
height_source="existing-surface-plane-unverified",
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
authority="observation-only",
route_permission="unassigned",
)
return [q if f is chosen[0] else f for f in features]
if kind == "place":
if (
set(op) != {"kind", "feature_id", "template_id", "position", "surface"}
or op["surface"] != "gaussian-visual"
):
raise ValueError("Некорректное размещение.")
if not isinstance(op["feature_id"], str) or not re.fullmatch(
r"user-[a-zA-Z0-9-]{16,64}", op["feature_id"]
):
raise ValueError("Некорректный идентификатор элемента.")
if not numbers(op["position"], 3):
raise ValueError("Некорректная точка поверхности.")
template = next((t for t in catalog()["templates"] if t["id"] == op["template_id"]), None)
if not template:
raise ValueError("Неизвестный шаблон.")
new_ids = {
op["feature_id"] if i == 0 else f"{op['feature_id']}-{i}"
for i in range(len(template["polygons"]))
}
if any(
f["id"] in new_ids or f["properties"].get("semantic_element_id") == op["feature_id"]
for f in features
):
raise ValueError("Элемент уже существует.")
result = features[:]
for i, polygon in enumerate(template["polygons"]):
result.append(
dict(
id=op["feature_id"] if i == 0 else f"{op['feature_id']}-{i}",
geometry=dict(
type="Polygon",
coordinates=[
[
[
p[0] + op["position"][0],
p[1] + op["position"][1],
op["position"][2],
]
for p in ring
]
for ring in polygon
],
),
properties=dict(
**{"class": "road_marking"},
authority="observation-only",
route_permission="unassigned",
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
**(
{"subtype": "linear_marking"}
if template["id"] == "linear_marking"
else {"semantic_element_id": op["feature_id"]}
),
template_id=template["id"],
template_source=template["source"],
height_source="gaussian-visual-pick-unverified",
),
)
)
return result
expected = (
{"kind", "feature_id", "delta", "angle"} if kind == "transform" else {"kind", "feature_id"}
)
if kind not in ("transform", "remove") or set(op) != expected:
raise ValueError("Неизвестное действие элемента.")
chosen = members(features, op["feature_id"])
if any(f["properties"]["class"] not in ("road_marking", "crosswalk_marking") for f in chosen):
raise ValueError("Действие предназначено для элемента разметки.")
if kind == "transform":
if (
not numbers(op["delta"], 2)
or type(op["angle"]) not in (int, float)
or not math.isfinite(op["angle"])
or abs(op["angle"]) > math.pi * 2
):
raise ValueError("Некорректное перемещение элемента.")
if op["delta"] == [0, 0] and op["angle"] == 0:
return features
ids = {f["id"] for f in chosen}
centre = pivot(chosen)
result = []
for f in features:
if f["id"] not in ids:
result.append(f)
continue
q = copy.deepcopy(f)
q["properties"].update(
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin=origin,
)
if kind == "remove":
q["properties"]["review_status"] = "rejected"
else:
c, s = math.cos(op["angle"]), math.sin(op["angle"])
for ring in paths(q):
for p in ring:
x, y = p[:2]
# Translation never subtracts/re-adds a pivot; retain no-op axes exactly.
if op["angle"]:
x, y = (
centre[0] + c * (x - centre[0]) - s * (y - centre[1]),
centre[1] + s * (x - centre[0]) + c * (y - centre[1]),
)
p[0], p[1] = x + op["delta"][0], y + op["delta"][1]
for nodes in q["properties"].get("editor_curves", {}).values():
for node in nodes:
x, y = node["point"][:2]
if op["angle"]:
x, y = (
centre[0] + c * (x - centre[0]) - s * (y - centre[1]),
centre[1] + s * (x - centre[0]) + c * (y - centre[1]),
)
for key in ("incoming", "outgoing"):
a, b = node[key]
node[key] = [c * a - s * b, s * a + c * b]
node["point"][:2] = [x + op["delta"][0], y + op["delta"][1]]
result.append(q)
return result
@@ -0,0 +1,387 @@
"""Portable vector editing. Geometry checks remain at Core's admission boundary."""
import copy
import re
try:
from .semantic_objects import is_rigid_marking, members, numbers, paths
except ImportError:
from semantic_objects import is_rigid_marking, members, numbers, paths
def knots(f, path):
saved = f["properties"].get("editor_curves", {}).get(str(path))
if saved is not None:
return copy.deepcopy(saved)
points = paths(f)[path]
if f["geometry"]["type"] == "Polygon":
points = points[:-1]
return [dict(point=p[:], incoming=[0, 0], outgoing=[0, 0]) for p in points]
def curve_point(a, b, t):
u = 1 - t
return [
u * u * u * a["point"][k]
+ 3 * u * u * t * (a["point"][k] + a["outgoing"][k])
+ 3 * u * t * t * (b["point"][k] + b["incoming"][k])
+ t * t * t * b["point"][k]
for k in (0, 1)
] + [a["point"][2] + t * (b["point"][2] - a["point"][2])]
def with_knots(f, path, nodes):
closed = f["geometry"]["type"] == "Polygon"
if not (3 if closed else 2) <= len(nodes) <= 4095:
raise ValueError("В контуре недостаточно точек. Выберите весь контур для удаления.")
curve = []
for i in range(len(nodes) - int(not closed)):
a, b = nodes[i], nodes[(i + 1) % len(nodes)]
curve.append(a["point"][:])
if any(a["outgoing"]) or any(b["incoming"]):
curve.extend(curve_point(a, b, j / 16) for j in range(1, 16))
curve.append(nodes[0 if closed else -1]["point"][:])
q = copy.deepcopy(f)
q["properties"].setdefault("editor_curves", {})[str(path)] = nodes
if closed:
q["geometry"]["coordinates"][path] = curve
else:
q["geometry"]["coordinates"] = curve
return q
def insert_knot(nodes, i, t, closed):
j = (i + 1) % len(nodes)
if not closed and j == 0 or type(t) not in (int, float) or not 0 < t < 1:
raise ValueError("Выберите середину сегмента.")
a, b = nodes[i], nodes[j]
def mix(x, y):
return [v + t * (y[k] - v) for k, v in enumerate(x)]
def sub(x, y):
return [v - y[k] for k, v in enumerate(x)]
A, D = a["point"][:2], b["point"][:2]
B = [v + a["outgoing"][k] for k, v in enumerate(A)]
C = [v + b["incoming"][k] for k, v in enumerate(D)]
ab, bc, cd = mix(A, B), mix(B, C), mix(C, D)
abc, bcd = mix(ab, bc), mix(bc, cd)
point = mix(abc, bcd)
a["outgoing"], b["incoming"] = sub(ab, A), sub(cd, D)
nodes.insert(
i + 1,
dict(
point=point + [a["point"][2] + t * (b["point"][2] - a["point"][2])],
incoming=sub(abc, point),
outgoing=sub(bcd, point),
),
)
def contour(features, fid):
selected = members(features, fid)
if len(selected) != 1 or is_rigid_marking(selected[0]):
raise ValueError("Разметка редактируется целиком.")
return selected[0]
def validate_index(f, op):
p, i = op.get("path"), op.get("index")
rings = paths(f)
if type(p) is not int or not 0 <= p < len(rings):
raise ValueError("Контур не найден.")
saved = f["properties"].get("editor_curves", {}).get(str(p))
count = (
len(saved) if saved is not None
else len(rings[p]) - int(f["geometry"]["type"] == "Polygon")
)
if type(i) is not int or not 0 <= i < count:
raise ValueError("Точка не найдена.")
def index_nodes(f, op):
validate_index(f, op)
return knots(f, op["path"])
def duplicate_vertex(features, op, origin):
if (
set(op) - {"side"} != {"kind", "feature_id", "path", "index", "delta", "axis"}
or ("side" in op and op["side"] not in ("before", "after"))
or op["axis"] not in ("x", "y", "z", "xy", "xz", "yz")
or not numbers(op["delta"], 3)
or any(v and "xyz"[k] not in op["axis"] for k, v in enumerate(op["delta"]))
):
raise ValueError("Некорректное перемещение по осям.")
f = contour(features, op["feature_id"])
nodes = index_nodes(f, op)
if op["delta"] == [0, 0, 0]:
return features
if not any(op["delta"][:2]):
raise ValueError(
"Продолжение контура должно иметь длину в плане: используйте X, Y или плоскость."
)
node = copy.deepcopy(nodes[op["index"]])
node["point"] = [
v + op["delta"][k] if op["delta"][k] else v for k, v in enumerate(node["point"])
]
# Old revisions keep their original order. New gestures explicitly record
# the chosen arm so preview, persistence and Worker replay cannot disagree.
index = (
op["index"] + int(op["side"] == "after")
if "side" in op
else 0
if f["geometry"]["type"] == "LineString" and op["index"] == 0
else op["index"] + 1
)
nodes.insert(index, node)
q = with_knots(f, op["path"], nodes)
q["properties"].pop("height_projection", None)
q["properties"].update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
height_source="human-vertex-extension-unverified",
)
return [q if v is f else v for v in features]
def duplicate_marking(features, op, origin):
if (
set(op) != {"kind", "feature_id", "new_feature_id", "delta", "axis"}
or not isinstance(op["new_feature_id"], str)
or not re.fullmatch(r"user-[a-zA-Z0-9-]{16,64}", op["new_feature_id"])
):
raise ValueError("Некорректное копирование элемента.")
chosen = members(features, op["feature_id"])
if any(f["properties"]["class"] not in ("road_marking", "crosswalk_marking") for f in chosen):
raise ValueError("Выберите элемент разметки.")
moved = vector_operation(
chosen,
dict(
kind="translate",
feature_id=op["feature_id"],
vertices=[],
delta=op["delta"],
axis=op["axis"],
),
origin,
)
if moved is chosen:
return features
copies = copy.deepcopy(moved)
for i, q in enumerate(copies):
q["id"] = op["new_feature_id"] if i == 0 else f"{op['new_feature_id']}-{i}"
if q["properties"].get("semantic_element_id"):
q["properties"]["semantic_element_id"] = op["new_feature_id"]
q["properties"].pop("height_projection", None)
q["properties"]["height_source"] = "human-copy-unverified"
ids = {q["id"] for q in copies}
if any(
f["id"] in ids or f["properties"].get("semantic_element_id") == op["new_feature_id"]
for f in features
):
raise ValueError("Элемент уже существует.")
return features + copies
def vector_operation(features, op, origin="human-edit"):
kind = op["kind"]
updated = {}
if kind == "duplicate_marking":
return duplicate_marking(features, op, origin)
if kind == "duplicate_vertex":
return duplicate_vertex(features, op, origin)
if kind in ("translate", "translate_vertices"):
if (
set(op) != {"kind", "feature_id", "vertices", "delta", "axis"}
or op["axis"] not in ("x", "y", "z", "xy", "xz", "yz")
or not numbers(op["delta"], 3)
or any(v and "xyz"[k] not in op["axis"] for k, v in enumerate(op["delta"]))
):
raise ValueError("Некорректное перемещение по осям.")
if op["delta"] == [0, 0, 0]:
return features
selected = members(features, op["feature_id"])
if kind == "translate" and selected[0]["properties"]["class"] in (
"road_marking",
"crosswalk_marking",
):
for f in selected:
q = copy.deepcopy(f)
for ring in paths(q):
for point in ring:
for k in range(3):
point[k] += op["delta"][k]
for nodes in q["properties"].get("editor_curves", {}).values():
for node in nodes:
node["point"] = [v + op["delta"][k] for k, v in enumerate(node["point"])]
updated[f["id"]] = q
else:
if not isinstance(op["vertices"], list) or not 1 <= len(op["vertices"]) <= 4096:
raise ValueError("Некорректное выделение.")
groups = {}
for v in op["vertices"]:
if set(v) != {"feature_id", "path", "index"}:
raise ValueError("Некорректная точка.")
f = contour(features, v["feature_id"])
validate_index(f, v)
groups.setdefault(f["id"], {}).setdefault(v["path"], set()).add(v["index"])
for fid, chosen in groups.items():
q = contour(features, fid)
for p, indices in chosen.items():
nodes = knots(q, p)
for i in indices:
nodes[i]["point"] = [
v + op["delta"][k] for k, v in enumerate(nodes[i]["point"])
]
q = with_knots(q, p, nodes)
updated[fid] = q
if op["delta"][2]:
for q in updated.values():
q["properties"].pop("height_projection", None)
q["properties"]["height_source"] = "human-axis-edit-unverified"
elif kind == "delete_vertices":
if (
set(op) != {"kind", "vertices"}
or not isinstance(op["vertices"], list)
or not 1 <= len(op["vertices"]) <= 4096
):
raise ValueError("Некорректное выделение.")
groups = {}
for v in op["vertices"]:
if set(v) != {"feature_id", "path", "index"}:
raise ValueError("Некорректное выделение.")
f = contour(features, v["feature_id"])
validate_index(f, v)
groups.setdefault(f["id"], {}).setdefault(v["path"], set()).add(v["index"])
for fid, chosen in groups.items():
f = contour(features, fid)
all_selected = all(
len(chosen.get(p, set())) == len(knots(f, p)) for p in range(len(paths(f)))
)
if all_selected:
q = copy.deepcopy(f)
q["properties"]["review_status"] = "rejected"
else:
q = f
for p, indices in chosen.items():
q = with_knots(q, p, [k for i, k in enumerate(knots(f, p)) if i not in indices])
updated[fid] = q
elif kind == "region":
if (
set(op) != {"kind", "feature_id", "token", "mode", "brush", "polygons"}
or op["mode"] not in ("union", "difference")
or not isinstance(op["token"], str)
or not re.fullmatch(r"[a-zA-Z0-9-]{16,64}", op["token"])
):
raise ValueError("Некорректная область.")
previous = next((f for f in features if f["id"] == op["feature_id"]), None)
if previous and (
previous["properties"]["class"] not in ("pedestrian_area", "sidewalk")
or previous["properties"].get("review_status") == "rejected"
):
raise ValueError("Выберите пешеходную область.")
if not previous and (
op["mode"] != "union" or not re.fullmatch(r"user-[a-zA-Z0-9-]{16,64}", op["feature_id"])
):
raise ValueError("Неизвестная область.")
brush = op["brush"]
if (
not isinstance(brush, list)
or not 4 <= len(brush) <= 129
or brush[0] != brush[-1]
or not all(numbers(p, 3) for p in brush)
):
raise ValueError("Некорректный контур пера.")
polygons = op["polygons"]
if (
not isinstance(polygons, list)
or len(polygons) > 64
or not polygons
and op["mode"] != "difference"
):
raise ValueError("Некорректный результат области.")
props = (
copy.deepcopy(previous["properties"])
if previous
else dict(
**{"class": "pedestrian_area"},
authority="observation-only",
route_permission="unassigned",
)
)
props.pop("editor_curves", None)
props.update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
height_source="human-region-unverified",
region_origin_id=op["feature_id"],
)
result = [f for f in features if f is not previous]
for i, polygon in enumerate(polygons):
fid = op["feature_id"] if i == 0 else f"{op['feature_id']}-{op['token']}-{i}"
if any(f["id"] == fid for f in result) or not isinstance(polygon, list) or not polygon:
raise ValueError("Некорректный идентификатор или полигон.")
result.append(
dict(
id=fid,
properties=copy.deepcopy(props),
geometry=dict(type="Polygon", coordinates=copy.deepcopy(polygon)),
)
)
if not polygons and previous:
q = copy.deepcopy(previous)
q["properties"].update(props, review_status="rejected")
result.append(q)
return result
else:
fields = {"kind", "feature_id", "path", "index"}
fields |= (
{"position"}
if kind == "move"
else {"t"}
if kind == "insert"
else {"incoming", "outgoing"}
if kind == "curve"
else set()
)
if kind not in ("move", "insert", "delete", "curve") or set(op) != fields:
raise ValueError("Некорректная векторная операция.")
f = contour(features, op["feature_id"])
nodes = index_nodes(f, op)
i = op["index"]
if kind == "curve":
if (
set(op) != {"kind", "feature_id", "path", "index", "incoming", "outgoing"}
or not numbers(op["incoming"], 2)
or not numbers(op["outgoing"], 2)
):
raise ValueError("Некорректные ручки кривой.")
if nodes[i]["incoming"] == op["incoming"] and nodes[i]["outgoing"] == op["outgoing"]:
return features
nodes[i].update(incoming=op["incoming"][:], outgoing=op["outgoing"][:])
elif kind == "move":
if not numbers(op["position"], 3) or op["position"][2] != nodes[i]["point"][2]:
raise ValueError("Редактирование в плане сохраняет высоту.")
nodes[i]["point"] = op["position"][:]
elif kind == "insert":
insert_knot(nodes, i, op["t"], f["geometry"]["type"] == "Polygon")
elif kind == "delete":
nodes.pop(i)
else:
raise ValueError("Неизвестная векторная операция.")
updated[f["id"]] = with_knots(f, op["path"], nodes)
for q in updated.values():
rejected = q["properties"].get("review_status") == "rejected"
q["properties"].update(
annotation_origin=origin,
confidence=None,
confidence_status="not-assessed",
review_status="rejected" if rejected else "unreviewed",
)
return [updated.get(f["id"], f) for f in features]
+17 -3
View File
@@ -9,6 +9,9 @@ from pathlib import Path
from k1link.simulation.ai_polygon.worlds import write_json
CLASSES = {
"road_boundary",
"pedestrian_boundary",
"building_facade",
"curb",
"bike_lane",
"crosswalk_area",
@@ -28,7 +31,7 @@ def validate_map(document: dict, world: dict) -> dict:
raise ValueError("Infrastructure map must be an object")
if (
document.get("schema_version")
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2"}
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2", "missioncore.urban-map/v3"}
or document.get("type") != "FeatureCollection"
):
raise ValueError("Unsupported infrastructure map")
@@ -46,6 +49,11 @@ def validate_map(document: dict, world: dict) -> dict:
"collider_sha256"
):
raise ValueError("Infrastructure map belongs to a different scene revision")
if document["schema_version"] == "missioncore.urban-map/v3":
if source.get("gaussian_only") is not True or not re.fullmatch(
"[0-9a-f]{64}", str(source.get("artifact_sha256", ""))
):
raise ValueError("Missing Gaussian derivation identity")
coverage = document.get("coverage")
if not isinstance(coverage, dict):
raise ValueError("Missing infrastructure coverage")
@@ -72,7 +80,7 @@ def validate_map(document: dict, world: dict) -> dict:
or prop.get("route_permission") != "unassigned"
):
raise ValueError("Infrastructure observations cannot grant route permissions")
vector = document["schema_version"] == "missioncore.urban-map/v2"
vector = document["schema_version"] in {"missioncore.urban-map/v2", "missioncore.urban-map/v3"}
if vector:
identifier = feature.get("id")
score = prop.get("confidence")
@@ -83,7 +91,13 @@ def validate_map(document: dict, world: dict) -> dict:
):
raise ValueError("Invalid or duplicate infrastructure identity")
identifiers.add(identifier)
if type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 1:
unassessed = (
document["schema_version"] == "missioncore.urban-map/v3"
and score is None
and prop.get("confidence_status") == "not-assessed"
)
measured = type(score) in (int, float) and math.isfinite(score) and 0 <= score <= 1
if not (unassessed or measured):
raise ValueError("Invalid infrastructure confidence")
if prop.get("review_status") not in {"unreviewed", "accepted", "rejected"}:
raise ValueError("Invalid infrastructure review state")
@@ -0,0 +1,31 @@
"""Location labels and reversible removal without changing scan identity."""
from .library import LibraryMetadata
class WorldLibrary:
def __init__(self, worlds):
self.worlds = worlds
self.metadata = LibraryMetadata(worlds.root.parent / "world-library")
def present(self, row):
metadata = self.metadata.get(row["world_id"])
return {**row, **metadata, "name": metadata.get("display_name", row["name"])}
def get(self, world_id):
return self.present(self.worlds.get(world_id))
def list(self):
return [self.present(row) for row in self.worlds.list()]
def update(self, world_id, changes):
with self.worlds.lock:
self.worlds.get(world_id) # Never create metadata for an unknown scan.
self.metadata.update(world_id, changes)
return self.get(world_id)
def require_visible(self, world_id):
row = self.get(world_id)
if row.get("removed"):
raise RuntimeError("Локация удалена из списка. Сначала восстановите её.")
return row
+33 -4
View File
@@ -28,6 +28,7 @@ from k1link.simulation.ai_polygon.contracts import (
WorkerResult,
WorkerWorldCreate,
WorldCreate,
WorldLibraryUpdate,
WorldSettings,
)
from k1link.simulation.ai_polygon.editor_cache import EditorCache
@@ -36,6 +37,7 @@ from k1link.web.route_preparation_api import build_route_preparation_router, pub
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
from k1link.simulation.ai_polygon.runs import RunStore
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
from k1link.simulation.ai_polygon.world_library import WorldLibrary
def build_ai_polygon_router(
@@ -43,6 +45,7 @@ def build_ai_polygon_router(
) -> APIRouter:
worlds = WorldStore(data_dir)
runs = RunStore(worlds, queue)
world_library = WorldLibrary(worlds)
editor = EditorCache(data_dir, worlds)
routes = RoutePreparationStore(data_dir)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
@@ -73,6 +76,12 @@ def build_ai_polygon_router(
from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore
urban_maps = UrbanMapStore(data_dir)
from k1link.web.semantic_edits_api import build_semantic_edits_router
router.include_router(build_semantic_edits_router(data_dir, worlds, urban_maps, invoke, authenticate))
from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs
from k1link.web.infrastructure_api import build_infrastructure_router
infrastructure = InfrastructureJobs(data_dir)
router.include_router(build_infrastructure_router(infrastructure, urban_maps, worlds, runs, invoke, authenticate))
@router.get("/worlds/{world_id}/urban-map")
def urban_map(world_id: str):
@@ -99,7 +108,8 @@ def build_ai_polygon_router(
def catalog():
runtime = runs.status()
runtime = {**runtime, "active_run": public_run(runtime.get("active_run"))}
locations = worlds.list()
all_locations = world_library.list()
locations = [w for w in all_locations if not w.get("removed")]
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
locations = [
{
@@ -116,6 +126,7 @@ def build_ai_polygon_router(
"sources": SOURCES,
"robots": robot_catalog(adapters),
"worlds": locations,
"removed_worlds": [w for w in all_locations if w.get("removed")],
"runtime": runtime,
"runs": [public_run(r) for r in runs.library.visible(runs.list(), "run_id")[:30]],
"plans": [public_plan(p) for p in runs.plans.visible_list()],
@@ -135,7 +146,16 @@ def build_ai_polygon_router(
@router.get("/worlds/{world_id}")
def get_world(world_id: str):
return invoke(worlds.get, world_id)
return invoke(world_library.get, world_id)
@router.patch("/worlds/{world_id}")
def update_world(world_id: str, body: WorldLibraryUpdate):
with runs.lock:
if body.removed and runs.active:
active = invoke(runs.get, runs.active)
if active["world"]["world_id"] == world_id:
raise HTTPException(409, "Сначала завершите симуляцию этой локации.")
return invoke(world_library.update, world_id, body.model_dump(exclude_none=True))
@router.get("/worlds/{world_id}/upload-prefix")
def upload_prefix(world_id: str):
@@ -229,8 +249,8 @@ def build_ai_polygon_router(
@router.post("/runs", status_code=201)
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
if editor.pending() or routes.pending():
raise HTTPException(409, "Дождитесь подготовки сцены и маршрута.")
if editor.pending() or routes.pending() or infrastructure.pending():
raise HTTPException(409, "Дождитесь завершения подготовки сцены, маршрута или анализа инфраструктуры.")
if body.clock == "realtime":
graph = invoke(compose, adapters, body.composition)
body = body.model_copy(update={"composition": graph.selection_document()})
@@ -361,6 +381,15 @@ def build_ai_polygon_router(
except RuntimeError:
return value
return {"action": "route-preparation", "preparation": claimed}
if value["action"] == "idle" and runs.queue is not None:
worker = runs.status().get("worker") or {}
try:
claimed = infrastructure.dispatch(body.instance_id, runs.queue,
worker.get("infrastructure_provider_sha256"))
except RuntimeError:
return value
if claimed:
return {"action":"infrastructure-analysis", "analysis":claimed}
return value
@router.post("/worker/editor-cache/{key}")
+130
View File
@@ -0,0 +1,130 @@
"""Whole-location analysis commands and bounded Worker publication."""
import json
from fastapi import APIRouter, Header, HTTPException, Request
from fastapi.responses import FileResponse
from pydantic import BaseModel, ConfigDict
from k1link.simulation.ai_polygon.infrastructure_jobs import provider_identity
from k1link.simulation.ai_polygon.urban_maps import validate_map
class AnalysisRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
force: bool = False
request_id: str | None = None
def build_infrastructure_router(jobs, maps, worlds, runs, invoke, authenticate):
router = APIRouter()
@router.get("/worlds/{world_id}/infrastructure-analysis")
def status(world_id: str):
world = invoke(worlds.get, world_id)
return jobs.present(invoke(jobs.current, world))
@router.get("/infrastructure-analysis/queue")
def queue_status():
return {
"jobs": [
dict(
jobs.present(row),
world_id=row["world"]["world_id"],
name=row["world"].get("name", "Локация"),
)
for row in jobs.queue_rows()
]
}
@router.post("/worlds/{world_id}/infrastructure-analysis/{key}/cancel")
def cancel(world_id: str, key: str):
with runs.lock:
row = invoke(jobs.get, key)
if row["world"]["world_id"] != world_id:
raise HTTPException(404, "Расчёт не найден.")
return jobs.present(invoke(jobs.cancel, key))
@router.get("/worker/worlds/{world_id}/infrastructure-source")
def source(world_id: str, authorization: str | None = Header(default=None)):
authenticate(authorization)
world = invoke(worlds.get, world_id)
if not world.get("local_scene") or world.get("storage", {}).get("kind") != "project":
raise HTTPException(400, "Для анализа нужен исходный Gaussian-проект.")
return invoke(worlds.projects.analysis_package, world)
@router.get("/worker/worlds/{world_id}/infrastructure-archive")
def archive(world_id: str, authorization: str | None = Header(default=None)):
authenticate(authorization)
world = invoke(worlds.get, world_id)
if world.get("storage", {}).get("kind") != "project":
raise HTTPException(400, "Для анализа нужен исходный Gaussian-проект.")
path, descriptor = invoke(worlds.projects.analysis_archive, world)
return FileResponse(
path,
media_type="application/octet-stream",
headers={"ETag": '"' + descriptor["sha256"] + '"'},
)
@router.post("/worlds/{world_id}/infrastructure-analysis", status_code=202)
def start(world_id: str, body: AnalysisRequest | None = None):
with runs.lock:
worker = runs.status().get("worker") or {}
if worker.get("infrastructure_provider_sha256") != provider_identity():
raise HTTPException(409, "Подключите Worker с модулем анализа инфраструктуры.")
return jobs.present(
invoke(
jobs.request,
invoke(worlds.get, world_id),
bool(body and body.force),
body.request_id if body else None,
)
)
@router.post("/worker/infrastructure-analysis/{key}")
async def update(
key: str,
request: Request,
authorization: str | None = Header(default=None),
instance_id: str = Header(alias="Worker-Instance"),
):
authenticate(authorization)
invoke(runs.heartbeat, instance_id)
raw = bytearray()
async for part in request.stream():
raw.extend(part)
if len(raw) > 12 * 1024**2:
raise HTTPException(413, "Analysis result exceeds transport budget")
try:
body = json.loads(raw)
if not isinstance(body, dict):
raise ValueError("Analysis update must be an object")
with jobs.lock:
row = invoke(jobs.get, key)
if body.get("action") == "complete":
if row["status"] not in ("running", "ready") or row["owner"] != instance_id:
raise RuntimeError("Analysis is not owned by this worker")
if row.get("cancel_requested"):
raise RuntimeError("Analysis cancellation requested")
world = worlds.get(row["world"]["world_id"])
doc = validate_map(body["map"], world)
analysis = doc.get("analysis", {})
if analysis.get("job_key") != key or analysis.get("scope") != "whole-scene":
raise ValueError("Analysis result identity mismatch")
if analysis.get("provider_sha256") != row["identity"]["provider_sha256"]:
raise ValueError("Analysis provider changed")
if row["status"] == "ready":
if maps.get(world) != doc:
raise ValueError("Completed analysis result changed")
return jobs.present(row)
body["result"] = maps.save(world, doc)
value = jobs.update(key, body, instance_id)
if body.get("action") == "release" and runs.queue is not None:
runs.queue.release_simulation("aicache-" + key)
return jobs.present(value)
except (ValueError, KeyError, TypeError) as exc:
raise HTTPException(400, "Invalid infrastructure analysis update") from exc
except RuntimeError as exc:
raise HTTPException(409, str(exc)) from exc
return router
+84
View File
@@ -0,0 +1,84 @@
"""Operator metadata only; training media never enters this API."""
import json
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from k1link.simulation.ai_polygon.semantic_edits import MAX_STATE, SemanticEdits
from k1link.simulation.ai_polygon.semantic_objects import catalog
def build_semantic_edits_router(data_dir, worlds, maps, invoke, authenticate):
router = APIRouter()
store = SemanticEdits(data_dir, maps)
@router.get("/semantic-edits/templates")
def templates():
return catalog()
@router.get("/worlds/{world_id}/semantic-edits")
def get(world_id: str):
return invoke(store.get, invoke(worlds.get, world_id))
@router.post("/worlds/{world_id}/semantic-edits")
async def save(world_id: str, request: Request):
raw = bytearray()
async for chunk in request.stream():
# Group edits carry vertex references: action count is not byte size.
# Admit up to the existing durable metadata budget; store.save still
# checks geometry, action count, history capacity and atomicity.
if len(raw) + len(chunk) > MAX_STATE:
raise HTTPException(
413, "Размер запроса правок превышает 8 МиБ. Черновик не изменён."
)
raw.extend(chunk)
try:
body = json.loads(raw)
except (ValueError, UnicodeDecodeError) as exc:
raise HTTPException(400, "Некорректная правка.") from exc
# File locks, geometry admission and durable I/O must not block the
# event loop that serves the operator's other requests.
return await run_in_threadpool(
lambda: invoke(store.save, invoke(worlds.get, world_id), body)
)
@router.get("/worker/worlds/{world_id}/semantic-edits/{revision}")
def export(world_id: str, revision: str, request: Request):
authenticate(request.headers.get("authorization"))
return invoke(store.export, invoke(worlds.get, world_id), revision)
@router.get("/worker/semantic-edits/pending")
def pending(request: Request):
authenticate(request.headers.get("authorization"))
return {"jobs": invoke(store.pending, invoke(worlds.list))}
@router.get("/worlds/{world_id}/semantic-edits/status")
def status(world_id: str):
world = invoke(worlds.get, world_id)
state = invoke(store._read, world)
head = state["revisions"][-1]["revision"] if state["revisions"] else None
return {
"revision": head,
"state": "queued" if head else "no-edits",
**state.get("deliveries", {}).get(head, {}),
"training_eligible": False,
}
@router.post("/worker/worlds/{world_id}/semantic-edits/{revision}/receipt")
async def receipt(world_id: str, revision: str, request: Request):
authenticate(request.headers.get("authorization"))
raw = bytearray()
async for chunk in request.stream():
raw.extend(chunk)
if len(raw) > 2048:
raise HTTPException(413, "Квитанция слишком велика.")
try:
body = json.loads(raw)
except (ValueError, UnicodeDecodeError) as exc:
raise HTTPException(400, "Некорректная квитанция.") from exc
return await run_in_threadpool(
lambda: invoke(store.receipt, invoke(worlds.get, world_id), revision, body)
)
return router
+491
View File
@@ -0,0 +1,491 @@
[
{
"name": "corner-incoming",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "before"
},
{
"name": "corner-outgoing",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
3,
-0.3,
0
],
"closed": false,
"side": "after"
},
{
"name": "reversed-corner",
"points": [
[
10,
-1,
2
],
[
0,
0,
2
],
[
0,
10,
2
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
},
{
"name": "straight-backward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 1,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "straight-forward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 1,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "unequal-arms",
"points": [
[
-1000,
1,
2
],
[
0,
0,
2
],
[
1,
4,
2
]
],
"index": 1,
"delta": [
0.1,
1,
0
],
"closed": false,
"side": "after"
},
{
"name": "start-outward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 0,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "start-inward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 0,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "end-inward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 2,
"delta": [
-1,
0,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-outward",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
8,
0,
2
]
],
"index": 2,
"delta": [
1,
0,
0
],
"closed": false,
"side": "after"
},
{
"name": "closed-seam-before",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
4,
4,
2
],
[
0,
4,
2
]
],
"index": 0,
"delta": [
0,
1,
0
],
"closed": true,
"side": "before"
},
{
"name": "closed-seam-after",
"points": [
[
0,
0,
2
],
[
4,
0,
2
],
[
4,
4,
2
],
[
0,
4,
2
]
],
"index": 0,
"delta": [
1,
0,
0
],
"closed": true,
"side": "after"
},
{
"name": "elevation-independent",
"points": [
[
0,
10,
2
],
[
0,
0,
2
],
[
10,
-1,
2
]
],
"index": 1,
"delta": [
0,
3,
1
],
"closed": false,
"side": "before"
},
{
"name": "facade-end-around-corner-positive-y",
"points": [
[
269.2913775569102,
-26.747129570459343,
3.333195732927997
],
[
295.88447329183816,
-30.768365587102007,
3.04762348870636
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
},
{
"name": "facade-reversed-start-around-corner-positive-y",
"points": [
[
295.88447329183816,
-30.768365587102007,
3.04762348870636
],
[
269.2913775569102,
-26.747129570459343,
3.333195732927997
]
],
"index": 0,
"delta": [
0,
3,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-near-perpendicular-negative-y",
"points": [
[
0,
-0.1,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
0,
-3,
0
],
"closed": false,
"side": "after"
},
{
"name": "end-dominant-inward",
"points": [
[
0,
0,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
-3,
1,
0
],
"closed": false,
"side": "before"
},
{
"name": "end-exact-perpendicular",
"points": [
[
0,
0,
0
],
[
10,
0,
0
]
],
"index": 1,
"delta": [
0,
3,
0
],
"closed": false,
"side": "after"
}
]

Some files were not shown because too many files have changed in this diff Show More