diff --git a/apps/control-station/package-lock.json b/apps/control-station/package-lock.json index eac33007..a2a152d8 100644 --- a/apps/control-station/package-lock.json +++ b/apps/control-station/package-lock.json @@ -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", diff --git a/apps/control-station/package.json b/apps/control-station/package.json index e4963858..83a8e467 100644 --- a/apps/control-station/package.json +++ b/apps/control-station/package.json @@ -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", diff --git a/apps/control-station/src/components/simulation/AiEditorRuntime.ts b/apps/control-station/src/components/simulation/AiEditorRuntime.ts index 1c63ea5a..c725d041 100644 --- a/apps/control-station/src/components/simulation/AiEditorRuntime.ts +++ b/apps/control-station/src/components/simulation/AiEditorRuntime.ts @@ -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((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.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(); diff --git a/apps/control-station/src/components/simulation/AiLocalPlanner.tsx b/apps/control-station/src/components/simulation/AiLocalPlanner.tsx index 2ec190a6..d123e7b6 100644 --- a/apps/control-station/src/components/simulation/AiLocalPlanner.tsx +++ b/apps/control-station/src/components/simulation/AiLocalPlanner.tsx @@ -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(null); const markerSvg=useRef(null); const host = useRef(null), canvas = useRef(null); const viewport = useRef(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([]); - const [layerMode,setLayerMode]=useState("visual"); + const [layout,updateLayout]=useSimulationLayout(); + const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers}); const [urbanMap,setUrbanMap]=useState(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(null); - const [viewMode,setViewMode]=useState<"3d"|"top">("3d"); const [markers, setMarkers] = useState([]); 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?{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null; + const header=<>{planning?{headerActions}:null} + + - {section === "pivot" ? <> + options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"},{value:"toolbar",label:"Тулбар"},{value:"cube",label:"3D-куб"}]}/> + {section === "cube" ? set("cube",key,v)}/> : section === "toolbar" ? 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")} diff --git a/apps/control-station/src/components/simulation/PlannerToolbarSettings.tsx b/apps/control-station/src/components/simulation/PlannerToolbarSettings.tsx new file mode 100644 index 00000000..1f95eac5 --- /dev/null +++ b/apps/control-station/src/components/simulation/PlannerToolbarSettings.tsx @@ -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)=>set(key,v)} formatValue={v=>`${unit==="с"?v/1000:v} ${unit}`}/>; + return <> + + {!planning?children:null} +
+ {!semantic?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; +} diff --git a/apps/control-station/src/components/simulation/useSemanticGestures.ts b/apps/control-station/src/components/simulation/useSemanticGestures.ts new file mode 100644 index 00000000..4f923bac --- /dev/null +++ b/apps/control-station/src/components/simulation/useSemanticGestures.ts @@ -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(null),[ghost,setGhost]=useState(null); + const [marquee,setMarquee]=useState(null),[brush,setBrush]=useState([]); + 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=>({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("[data-semantic-axis]")?.dataset.semanticAxis as SemanticAxis|"rotate"|undefined; + const handle=target.closest("[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}; +} diff --git a/apps/control-station/src/components/simulation/useSimulationFullscreen.ts b/apps/control-station/src/components/simulation/useSimulationFullscreen.ts index 8015787b..96170eb1 100644 --- a/apps/control-station/src/components/simulation/useSimulationFullscreen.ts +++ b/apps/control-station/src/components/simulation/useSimulationFullscreen.ts @@ -6,7 +6,7 @@ export function useSimulationFullscreen(view: RefObject) 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); diff --git a/apps/control-station/src/components/simulation/useSimulationLayout.ts b/apps/control-station/src/components/simulation/useSimulationLayout.ts new file mode 100644 index 00000000..18748e6f --- /dev/null +++ b/apps/control-station/src/components/simulation/useSimulationLayout.ts @@ -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){ + 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. */} +} diff --git a/apps/control-station/src/core/simulation/aiEditor.ts b/apps/control-station/src/core/simulation/aiEditor.ts index 78f6c714..29ec2527 100644 --- a/apps/control-station/src/core/simulation/aiEditor.ts +++ b/apps/control-station/src/core/simulation/aiEditor.ts @@ -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; diff --git a/apps/control-station/src/core/simulation/aiPolygon.ts b/apps/control-station/src/core/simulation/aiPolygon.ts index 2f26c214..95dd3d88 100644 --- a/apps/control-station/src/core/simulation/aiPolygon.ts +++ b/apps/control-station/src/core/simulation/aiPolygon.ts @@ -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(path: string, init: RequestInit = {}): P } export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`; export const fetchAiCatalog = () => polygonRequest("/catalog"); +export const updateAiWorld = (id:string, changes:{display_name?:string;removed?:boolean}) => + polygonRequest(`/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(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)}); diff --git a/apps/control-station/src/core/simulation/editorNavigation.ts b/apps/control-station/src/core/simulation/editorNavigation.ts index dc422c0c..4fb02b5a 100644 --- a/apps/control-station/src/core/simulation/editorNavigation.ts +++ b/apps/control-station/src/core/simulation/editorNavigation.ts @@ -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()); diff --git a/apps/control-station/src/core/simulation/editorProjection.ts b/apps/control-station/src/core/simulation/editorProjection.ts new file mode 100644 index 00000000..4edf29cd --- /dev/null +++ b/apps/control-station/src/core/simulation/editorProjection.ts @@ -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; +} diff --git a/apps/control-station/src/core/simulation/infrastructureAnalysis.ts b/apps/control-station/src/core/simulation/infrastructureAnalysis.ts new file mode 100644 index 00000000..8ebcaaff --- /dev/null +++ b/apps/control-station/src/core/simulation/infrastructureAnalysis.ts @@ -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(null),[error,setError]=useState(null); + const [sending,setSending]=useState(false),[checking,setChecking]=useState(true); + const callback=useRef(onMap);callback.current=onMap; + const lifecycle=useRef(null),generation=useRef(0),requestId=useRef(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;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; + 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}; +} diff --git a/apps/control-station/src/core/simulation/plannerActions.ts b/apps/control-station/src/core/simulation/plannerActions.ts new file mode 100644 index 00000000..3919736f --- /dev/null +++ b/apps/control-station/src/core/simulation/plannerActions.ts @@ -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, + }; +} diff --git a/apps/control-station/src/core/simulation/plannerPreferences.ts b/apps/control-station/src/core/simulation/plannerPreferences.ts index 3205524a..9a1c1a05 100644 --- a/apps/control-station/src/core/simulation/plannerPreferences.ts +++ b/apps/control-station/src/core/simulation/plannerPreferences.ts @@ -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=v.navigation??{}, dn=d.navigation; const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50); + const c:Partial=v.cube??{},dc=d.cube; + const t:Partial=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)}, diff --git a/apps/control-station/src/core/simulation/sceneClip.ts b/apps/control-station/src/core/simulation/sceneClip.ts new file mode 100644 index 00000000..bd9a55dd --- /dev/null +++ b/apps/control-station/src/core/simulation/sceneClip.ts @@ -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; +} diff --git a/apps/control-station/src/core/simulation/semanticArea.ts b/apps/control-station/src/core/simulation/semanticArea.ts new file mode 100644 index 00000000..436d9ecf --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticArea.ts @@ -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;ip.map(r=>r.map(v=>[...v,height(v)])))}; +} diff --git a/apps/control-station/src/core/simulation/semanticCurveControls.ts b/apps/control-station/src/core/simulation/semanticCurveControls.ts new file mode 100644 index 00000000..1a378342 --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticCurveControls.ts @@ -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); +} diff --git a/apps/control-station/src/core/simulation/semanticEdits.ts b/apps/control-station/src/core/simulation/semanticEdits.ts new file mode 100644 index 00000000..4b387904 --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticEdits.ts @@ -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):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 { + 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 { + 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"; + } +} diff --git a/apps/control-station/src/core/simulation/semanticFeaturePolicy.ts b/apps/control-station/src/core/simulation/semanticFeaturePolicy.ts new file mode 100644 index 00000000..3eb6aaa7 --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticFeaturePolicy.ts @@ -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); diff --git a/apps/control-station/src/core/simulation/semanticPicking.ts b/apps/control-station/src/core/simulation/semanticPicking.ts new file mode 100644 index 00000000..52680abb --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticPicking.ts @@ -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{ + const p=ring.map(project);if(p.some(v=>!v))return false; + let yes=false; + for(let i=1;iat[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}))); +} diff --git a/apps/control-station/src/core/simulation/semanticVector.ts b/apps/control-station/src/core/simulation/semanticVector.ts new file mode 100644 index 00000000..64b797d2 --- /dev/null +++ b/apps/control-station/src/core/simulation/semanticVector.ts @@ -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+1inward?"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;if.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; +} diff --git a/apps/control-station/src/core/simulation/simulationLayout.ts b/apps/control-station/src/core/simulation/simulationLayout.ts new file mode 100644 index 00000000..62c89822 --- /dev/null +++ b/apps/control-station/src/core/simulation/simulationLayout.ts @@ -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,d=DEFAULT_SIMULATION_LAYOUT; + const pick=(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}; +} diff --git a/apps/control-station/src/core/simulation/urbanMap.ts b/apps/control-station/src/core/simulation/urbanMap.ts index ac1e4984..8a2fe47c 100644 --- a/apps/control-station/src/core/simulation/urbanMap.ts +++ b/apps/control-station/src/core/simulation/urbanMap.ts @@ -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; 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 = { @@ -15,17 +16,23 @@ export const URBAN_COLORS: Record = { 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 = { +// 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 { 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]:[]; +} diff --git a/apps/control-station/src/core/simulation/urbanSurface.ts b/apps/control-station/src/core/simulation/urbanSurface.ts new file mode 100644 index 00000000..ffbb01d0 --- /dev/null +++ b/apps/control-station/src/core/simulation/urbanSurface.ts @@ -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() }; +} diff --git a/apps/control-station/src/styles/ai-polygon.css b/apps/control-station/src/styles/ai-polygon.css index 1adb48c6..643e0429 100644 --- a/apps/control-station/src/styles/ai-polygon.css +++ b/apps/control-station/src/styles/ai-polygon.css @@ -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; } diff --git a/apps/control-station/src/workspaces/PolygonRoverScene.tsx b/apps/control-station/src/workspaces/PolygonRoverScene.tsx index 7bfb9629..cea01c9a 100644 --- a/apps/control-station/src/workspaces/PolygonRoverScene.tsx +++ b/apps/control-station/src/workspaces/PolygonRoverScene.tsx @@ -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({
{renderError ?

{renderError}

: null}
-
- - + +
ЛКМ · вращение diff --git a/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx b/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx index 73e7709c..0640ca46 100644 --- a/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx +++ b/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx @@ -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(null); const [catalog, setCatalog] = useState(null); const [selectedId, setSelectedId] = useState(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 = {catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"} ; + const taskSelector = mode==="inference"&&!running&&!starting?{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null; + const routeActions = selected && catalog ?
{mode === "manual" ? (manual||canEdit?:null) : planning ? <> + {available.save?:null} + {available.prepare||preparation.busy?:null} + {available.launch||starting?:null} + : !running ? <> + {canEdit?:null} + {canLaunchSaved||starting?:null} + : }
: null; const sceneActions = selected && catalog ? <> {!planning&&!manual&&!running&&!starting?<>
({ value: item.robot_id, label: item.name }))} disabled={planning || manual || starting || running} onChange={(id)=>{setRobotId(id);setPlanId(null);}} />
- setRoverSettingsOpen(true)}> + {robot&&roverSettings&&!starting?setRoverSettingsOpen(true)}>:null}
{roverSettings?

{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом

:null}:null} - {mode==="inference"&&!running&&!starting?{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null} -
{mode === "manual" ? : planning ? <> - - {!routeRequired || preparation.route ? : } - {preparation.busy?

Рассчитываем маршрут по сцене

:null} - : !running ? <> - - - : }
+ {taskSelector} + {routeActions} : null; return
@@ -211,8 +232,9 @@ export function AiPolygonWorkspace() { : null}

{selected?.name ?? "Доступные локации"}

-
- {selected ? null : <>{connection} +
+ {selected ? !planning&&!manual&&!running&&canEdit?start("planning")}>:null : <>{connection} }
@@ -223,14 +245,9 @@ export function AiPolygonWorkspace() { :null} {catalog ? !selected ?
- {catalog.worlds.map((world) =>
  • - } - status={catalog.runtime.active_run?.world.world_id === world.world_id ? - {catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"} - : undefined} - actions={ openWorld(world)}>}/> -
  • )}
    +
    :
    {!running && !planning && !manual ? @@ -255,13 +272,15 @@ export function AiPolygonWorkspace() { {mode === "inference" && !planning && !running && catalog.runtime.active_run ?

    Выполняется симуляция «{catalog.runtime.active_run.world.name}».

    {catalog.runtime.active_run.world.world_id===selected.world_id?:null}
    : null} {manual && robot ? }> - + : planning ? }> + sceneMode={sceneMode} onSceneMode={setSceneMode} + busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft} + actionsHost={headerToolsHost??actionsHost} headerActions={taskSelector} routeActions={routeActions} routeActionsHost={actionsHost} /> : {mode === "inference" && running && run ? } /> : mode === "inference" ?
    {connection}{selected.inference_ready===false?

    {selected.inference_message}

    :null}
    : null}
    } {mode === "inference" && !planning ? item.world.world_id === selected.world_id)} /> : null} diff --git a/apps/control-station/src/workspaces/simulation/SimulationWorkspace.tsx b/apps/control-station/src/workspaces/simulation/SimulationWorkspace.tsx index fd4df493..d48b90ef 100644 --- a/apps/control-station/src/workspaces/simulation/SimulationWorkspace.tsx +++ b/apps/control-station/src/workspaces/simulation/SimulationWorkspace.tsx @@ -1,6 +1,6 @@ import { AiPolygonWorkspace } from "./AiPolygonWorkspace"; /** One location library; execution mode is selected inside the location. */ -export function SimulationWorkspace() { - return ; +export function SimulationWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) { + return ; } diff --git a/apps/control-station/test/editorCamera.test.mjs b/apps/control-station/test/editorCamera.test.mjs new file mode 100644 index 00000000..344b475c --- /dev/null +++ b/apps/control-station/test/editorCamera.test.mjs @@ -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){ + 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(); + } +}); diff --git a/apps/control-station/test/editorInteraction.test.mjs b/apps/control-station/test/editorInteraction.test.mjs index 56016545..5f80eb81 100644 --- a/apps/control-station/test/editorInteraction.test.mjs +++ b/apps/control-station/test/editorInteraction.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/editorProjectionRuntime.test.mjs b/apps/control-station/test/editorProjectionRuntime.test.mjs new file mode 100644 index 00000000..2bec19f2 --- /dev/null +++ b/apps/control-station/test/editorProjectionRuntime.test.mjs @@ -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')); +}); diff --git a/apps/control-station/test/editorTerrainClip.test.mjs b/apps/control-station/test/editorTerrainClip.test.mjs new file mode 100644 index 00000000..cdfca928 --- /dev/null +++ b/apps/control-station/test/editorTerrainClip.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/infrastructureAnalysis.test.mjs b/apps/control-station/test/infrastructureAnalysis.test.mjs new file mode 100644 index 00000000..c39bde27 --- /dev/null +++ b/apps/control-station/test/infrastructureAnalysis.test.mjs @@ -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'); +}); diff --git a/apps/control-station/test/localScene.test.mjs b/apps/control-station/test/localScene.test.mjs new file mode 100644 index 00000000..c0e5f13c --- /dev/null +++ b/apps/control-station/test/localScene.test.mjs @@ -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}); +}); diff --git a/apps/control-station/test/plannerActions.test.mjs b/apps/control-station/test/plannerActions.test.mjs new file mode 100644 index 00000000..ccb9a1c7 --- /dev/null +++ b/apps/control-station/test/plannerActions.test.mjs @@ -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}); +}); diff --git a/apps/control-station/test/plannerPreferences.test.mjs b/apps/control-station/test/plannerPreferences.test.mjs index 19387553..eb316031 100644 --- a/apps/control-station/test/plannerPreferences.test.mjs +++ b/apps/control-station/test/plannerPreferences.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/sceneClip.test.mjs b/apps/control-station/test/sceneClip.test.mjs new file mode 100644 index 00000000..74f4e28a --- /dev/null +++ b/apps/control-station/test/sceneClip.test.mjs @@ -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]); +}); diff --git a/apps/control-station/test/semanticArea.test.mjs b/apps/control-station/test/semanticArea.test.mjs new file mode 100644 index 00000000..32c937c3 --- /dev/null +++ b/apps/control-station/test/semanticArea.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/semanticEdits.test.mjs b/apps/control-station/test/semanticEdits.test.mjs new file mode 100644 index 00000000..da316250 --- /dev/null +++ b/apps/control-station/test/semanticEdits.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/semanticGestures.test.mjs b/apps/control-station/test/semanticGestures.test.mjs new file mode 100644 index 00000000..74f440c5 --- /dev/null +++ b/apps/control-station/test/semanticGestures.test.mjs @@ -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();} +}); diff --git a/apps/control-station/test/simulationWorkspace.test.mjs b/apps/control-station/test/simulationWorkspace.test.mjs index 4e49de4c..8b708d3a 100644 --- a/apps/control-station/test/simulationWorkspace.test.mjs +++ b/apps/control-station/test/simulationWorkspace.test.mjs @@ -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]*/); + assert.match(workspaceHub, /case "simulations":[\s\S]*/); 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, //); + assert.match(workspace, //); assert.doesNotMatch(workspace, /simulation-profile|LccGaussianWorkspace/); assert.match(styles, /styles\/simulation\.css/); }); diff --git a/apps/control-station/test/urbanMap.test.mjs b/apps/control-station/test/urbanMap.test.mjs new file mode 100644 index 00000000..1a8f7373 --- /dev/null +++ b/apps/control-station/test/urbanMap.test.mjs @@ -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:[]}),[]); +}); diff --git a/apps/control-station/test/urbanSurface.test.mjs b/apps/control-station/test/urbanSurface.test.mjs new file mode 100644 index 00000000..e35c102b --- /dev/null +++ b/apps/control-station/test/urbanSurface.test.mjs @@ -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;ig.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;ig.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); +}); diff --git a/docs/SEMANTIC_EDITOR.md b/docs/SEMANTIC_EDITOR.md new file mode 100644 index 00000000..da6e4048 --- /dev/null +++ b/docs/SEMANTIC_EDITOR.md @@ -0,0 +1,1888 @@ +# Редактор семантики и доставка примеров на Worker — 2026-10-21 + +## Действующая концепция продукта · уточнение 26.10.2026 + +[SCENE_SEMANTICS_PRODUCT_CONCEPT.md](SCENE_SEMANTICS_PRODUCT_CONCEPT.md) задаёт цель: отдельная произвольная сцена ровера, raw-сенсорное облако для пространственной локализации и семантика по Gaussian-наблюдениям. Зебры функционально важны; весь набор наблюдаемой разметки также нужен для интерфейса, промо и проверки сложного распознавания. GPS, адрес, публичная карта и сравнение разных сканов не являются входом или gate; совмещение/географическое сопоставление допускается только по отдельной просьбе владельца. Датированные эксперименты ниже сохраняют свои исходные критерии и не доказывают готовность полного тракта. + + +## Принятая граница + +Это редактор контуров и целых элементов разметки, включая постановку шаблонов. +Контур обучения из `outputs/MISSION_CORE_SEMANTIC_EDITOR_AND_LEARNING_PLAN_2026-10-20.md` +продвинут до проверенной цепочки: сохранение → доставка → наблюдения → переносимый +датасет для проверки. Один реальный пример Маросейки собран и прочитан без Core. +Обучение и утверждение человеком ещё не выполнены. Карта, черновая аннотация, +переносимый пример и допущенный к обучению эталон имеют разные статусы. + +Операторский Mac хранит только разрешённую сцену, результаты и небольшие +семантические ревизии. Новые обучающие изображения, наблюдения, веса и тяжёлые +эксперименты должны создаваться в отдельном постоянном хранилище Worker 006, +вне checkout и записываемого слоя контейнера. Локального резервного пути для +таких данных нет. + +## Интерфейс + +В локальном viewer локации шапка содержит поле «Режим»: + +| Режим | Действия | +| --- | --- | +| Просмотр | Навигация, 3D/вид сверху, качество, срез, слои сцены | +| Семантика | Расчёт/пересчёт инфраструктуры; алгоритм, мои правки, сравнение; редактор | +| Планирование миссии | Выбор задания, установка/изменение точек, доступные действия маршрута и запуска | + +Старый переключатель «Маршрут / Семантика» внутри viewport удалён. Поле +«Режим» использует `FieldFrame` и `Select` Design Guideline. Выбор задания расположен слева от режима; подписи полей находятся снизу (`labelPlacement="below"`). Запуск — круглая кнопка перед закрытием; пересчёт инфраструктуры — круглая кнопка в той же шапке (во время расчёта сохраняется прогресс). Viewport-кнопки +сохраняют общий масштаб `nodedc-scene-controls`. Меню доступно в fullscreen. +Смена режима внутри открытой локации не размонтирует семантический редактор, +не сбрасывает его несохранённые действия и не меняет точки маршрута. +Вход «Подготовить маршрут» по-прежнему открывает планирование; существующий +экран конфигурации и истории симуляций сохранён. + +Редактор: + +- независимый выбор слоёв в легенде: видны и доступны к редактированию только включённые классы; +- вершины показаны только у выбранного контура; клик по телу линии выбирает все её управляющие точки, клик по видимой точке — одну вершину; наведение контрастно выделяет объект; +- первый клик выбирает вершину и показывает пивот; движение с той же зажатой кнопкой сразу перетаскивает вершину по выбранным осям; +- Ctrl + перетаскивание левой кнопкой в редакторе вращает камеру, в том числе поверх пивота/ручки; обычный drag остаётся инструменту. В режиме просмотра камера вращается без Ctrl; +- при нескольких подходящих объектах — явный выбор контура; +- движение за X/Y/Z или XY/XZ/YZ пивот; только явно выбранная ось Z меняет высоту, без заявления о новой привязке к поверхности; +- символы (буквы, стрелки, велосипеды, составная зебра) выделяются целиком: общий пивот и кольцо поворота; +- `linear_marking` — редактируемая полоса: клик по телу выбирает целый элемент и показывает вершины, клик по вершине/рамка/Shift + клик выбирают точки. Две крайние точки можно растягивать пивотом; +- «Линейная разметка» создаёт редактируемый прямоугольник 3 × 0,15 м с проекцией на Gaussian-поверхность. Это начальный размер, не утверждение нормативных размеров; +- Shift + drag пивота копирует выбранный целиком элемент с новым ID (для зебры — новую группу), а для одиночной вершины продолжает сплайн. Исходник неизменен, новая точка/копия выделена, действие отменяется одним Ctrl/Cmd+Z. Сторона вставки выбирается по направлению движения относительно соседних участков (для кривых — локальных ручек): к предыдущему участку — перед выбранной, к следующему — после. У открытого конца движение наружу продолжает сплайн, внутрь вставляет точку на соответствующей стороне. Решение preview фиксируется в операции `side`, поэтому сохранение и Worker воспроизводят тот же порядок. Старые операции без `side` сохраняют прежнюю семантику. Чисто вертикальное продолжение запрещено проверкой совпадения точек в плане; +- Hold — первая кнопка существующего Toolbar; переключает сохраняемый `autoHide` и отменяет уже запущенный таймер скрытия; +- клик по сцене вне открытого меню закрывает его на capture-фазе; этот клик не размещает элемент и не начинает редактирование под меню; +- «Добавить элемент»: стрелка прямо, налево, направо, А, зебра, велосипед; выбор закрывает меню, визуальная проекция следует за указателем, клик ставит элемент, Escape отменяет; +- составная зебра имеет общий ID: перемещение, поворот и удаление охватывают все полосы; +- вставка на выбранном сегменте с перспективно корректным параметром; +- удаление вершины с сохранением минимального размера геометрии; +- отмена/повтор; Escape и отмена указателя возвращают исходную геометрию; +- отдельное сохранение ручной ревизии; +- исходная карта и наложение её пунктирных линий для сравнения. + +Радиус выбора измеряется в CSS-пикселях. Среди вершин активного слоя +выбирается ближайшая; вершина имеет приоритет перед сегментом. При выборе из пересечения сохраняются именно path/index под указателем, а не первая вершина контура. Перетаскивание +не пересобирает всю GPU-карту на каждом событии мыши. Действия сохранения +не допускают параллельного изменения отправленного черновика. + +Несохранённый черновик пока живёт в памяти открытой локации. Перезагрузка +страницы вызывает предупреждение браузера; долговременного хранения +несохранённых действий и общего перехвата всей навигации приложения пока нет. +Перед закрытием локации необходимо сохранить правки. + +## Серверная граница + +Модули: + +- `src/k1link/simulation/ai_polygon/semantic_edits.py`; +- `src/k1link/web/semantic_edits_api.py`; +- `apps/control-station/src/core/simulation/semanticEdits.ts`; +- `apps/control-station/src/components/simulation/SemanticEditor.tsx`; +- `apps/control-station/src/components/simulation/SemanticEditOverlay.tsx`. + +API под `/api/v1/ai-polygon`: + +| Метод/путь | Назначение | +| --- | --- | +| GET `/worlds/{world_id}/semantic-edits` | Исходная карта, ручная версия, история, состояние | +| POST `/worlds/{world_id}/semantic-edits` | Атомарная ревизия операций | +| GET `/worker/worlds/{world_id}/semantic-edits/{revision}` | Аутентифицированный экспорт аннотации | + +POST допускает `expected_revision`, `model_sha256`, `request_id`, +`operations` и необязательный `origin` (`human-edit` / `agent-proposal`); +максимум 8 MiB (бюджет локальной истории) и 256 действий. Размер проверяется +до добавления очередного фрагмента запроса. Групповая правка может содержать +много ссылок на вершины и не обязана укладываться в прежние 256 KiB; число +действий, геометрическая приёмка и атомарность остаются прежними. +Изображения и произвольные +вложения этим контрактом не принимаются. + +Идентичность основы фиксируется по SHA-256. Новый автоматический расчёт +не переносит человеческие операции на другую геометрию по совпавшим индексам. +Исходный объект в UrbanMapStore остаётся неизменным. Повтор идентичного +request_id идемпотентен; иное тело с тем же ID и конкурирующая базовая +ревизия отклоняются. + +Новая геометрия проходит проверку конечных чисел, индексов, минимальной +длины, замкнутости, совпадающих точек, самопересечений и принадлежности +внутренних колец. В старой операции `move` Z должна точно совпадать с исходной. Явная операция `translate` допускает только компоненты выбранной оси/плоскости; изменение Z помечается `human-axis-edit-unverified`. +Нулевое перемещение не меняет геометрию/свидетельства и не создаёт ревизию. +При чтении сохранённой истории проверяются хеши и цепочка родителей; +уже принятую историю воспроизводим без повторной дорогой геометрической проверки. + +Ручная карта получает `missioncore.urban-edit/v1`. Изменённый объект помечается +`human-edit` либо `agent-proposal`, `unreviewed`, `confidence_status=not-assessed`; старое значение +уверенности не выдаётся за оценку исправленной геометрии. Автоматическая +приёмка и публикация карты не изменены. Ручные правки не дают разрешения +маршруту и не считаются свежим автоматическим восстановлением объекта. + +## Хранение и экспорт + +Ревизии хранятся в +`.runtime/mission-core/ai-polygon/semantic-edits/.json`. +Лимит — 8 MiB на сцену, 64 MiB на весь каталог; перед атомарной заменой +учитывается место временного файла и сохраняется резерв свободного диска. +Общая блокировка публикации защищает конкурентные записи. Переполнение +отклоняет новое сохранение, а не удаляет историю. + +Экспорт `missioncore.semantic-annotation-export/v1` содержит модельную +основу, изменённую геометрию, операции, исходные идентичности, ревизии и +хеш пакета. Это **экспорт аннотации**, не самодостаточный обучающий датасет. +`review.state=draft`, `complete_regions=[]`, `dataset_ready=false`. +Этот экспорт используется как вход нового Worker-контура, описанного ниже. +Сам по себе JSON аннотации всё ещё не является обучающим примером. + +## Проверка локального редактора до подключения Worker + +- 21 Python-проверка: реальный HTTP-контракт, авторизация Worker, ограничение + тела, конфликты, повтор запроса, восстановление store, неизменность модели, + нулевое движение, геометрические ошибки, повреждение истории и лимит места. +- TypeScript и production-сборка прошли; остаётся обычное предупреждение + Vite о крупных существующих chunks. +- Полный frontend suite: 1 233 проверки, 0 ошибок. +- Browser QA на опубликованной Маросейке: перемещение и отмена, вставка на + сегменте, сохранение черновика при переключении режимов, сравнение, + возврат сохранённого маршрута 693,7 м, fullscreen/Escape. +- Пробные действия отменены; искусственная правка не записана в рабочую + историю и не выдана за пользовательскую обучающую аннотацию. +- Ни автоматический полный расчёт, ни движение ровера не запускались. +- После штатного перезапуска Core доступен на `:8000`; API редактора возвращает + 582 исходных объекта Маросейки и `revision=null`. Идентичность модельной + карты — `1d934f43d33ad15159049326f1ccf096877da8c1dee6d62b189b2ee134073536`. + +## Предварительное обследование Worker 006 + +SSH `mission-gpu` снова доступен. Работает существующий Scheduled Task +`ndc-ai-polygon-worker`, установленный release `4c4525b7289bdd52`. +Core показывает подключённый симулятор. На момент чтения свободно примерно +64,5 GB на D и 403 GB на C; это снимок, не резервирование места. + +Существующий каталог наборов — `D:\NDC_MISSIONCORE\datasets`. +Новый отдельный подкаталог `urban-learning` теперь создан и подключён +обработчиком, см. актуальную реализацию ниже. + +В `runtime\simulation\state\infrastructure-sources` найдены два адаптированных +источника с `full-lod1.ply`, `poses.json`, `source.json`. Манифесты содержат +SHA исходного bundle, PLY, поз и преобразование `source_to_world`. Исходные +ingests Gaussian Pipeline также присутствуют. Наличие именно нужных панорам, +их калибровка и привязка к выбранной ревизии сцены ещё требуют проверки. +Каталоги прочитаны без копирования медиа на Mac и без изменения Worker. + +## Доставка и подготовка: реализовано + +Сохранённая ревизия является постоянной исходящей очередью Core; второй записи +«сохранить карту, затем поставить задачу» нет. Через Worker bearer API доступны: + +- GET `/worker/semantic-edits/pending` — до 20 ещё не подтверждённых ревизий; +- GET `/worker/worlds/{world_id}/semantic-edits/{revision}` — неизменная аннотация; +- POST тот же путь + `/receipt` — квитанция с хешем аннотации и результатом; +- GET `/worlds/{world_id}/semantic-edits/status` — малый статус для интерфейса. + +Квитанции проверяют идентичность, допустимые переходы и конечный результат. +Поздний повтор ранней квитанции не откатывает состояние. Метаданные доставки +хранятся атомарно в том же ограниченном файле Core, без изображений. + +`simulation/semantic-learning` — отдельный Worker-компонент. Source-only release +собирает `scripts/package_semantic_learning.py`; `install.ps1` проверяет каждый +хеш и образ, регистрирует `ndc-semantic-learning-worker`. Используются имеющиеся +Python, Docker, токен и loopback-туннель. Новые порты/учётные данные не нужны. +Пакет не меняет Gaussian Pipeline и основной обработчик симуляций. + +Worker сначала атомарно сохраняет пакет и очередь SQLite, затем подтверждает +получение. Сборка уже принятого пакета не требует доступности Core. На Worker +хранятся аннотации, исходники для локального рендера, выходные датасеты и логи. +Повтор доставки имеет ту же идентичность; завершённый пример не пересчитывается. +Сбой после публикации каталога до записи статуса восстанавливается по манифесту. +Частичный результат не публикуется; три аварийных прерывания переводят задачу +в ошибку. Ошибка одной задачи освобождает очередь для следующей. + +Один обработчик защищён Windows lock. Очередь допускает 20 незавершённых задач; +при заполнении новые правки остаются в исходящей очереди Core. Лимит допуска +хранилища — 20 GiB, свободный резерв — 12 GiB; переполнение отказывает в новой +работе без удаления результатов. Один датасет ограничен 512 MiB, пакет — 24 MiB, +локальные окна — 16 на ревизию. Логи вращаются: 2 MiB × 3. Существующие данные +симуляций не входят в этот каталог и не удаляются обработчиком. + +Сборка выполняется последовательно и уступает активным маркерам симуляции, +подготовки маршрута/сцены и инфраструктуры. Если такая работа появляется во +время рендера, собственный контейнер снимается и пример ждёт. Это не единый +планировщик всех GPU-продуктов Worker: чужие продуктовые сервисы не управляются. +Контейнер без сети, с read-only root, 4 CPU и 6 GiB RAM; исходник/code read-only, +результат и ограниченный общим бюджетом CUDA-кэш — внешние каталоги Worker. +Имена/labels принадлежат Mission Core. После перезапуска сверяются только +собственные контейнеры. Нативная конвертация защищена Windows Job Object. + +## Датасет и реальная проверка + +Корень: `D:\NDC_MISSIONCORE\datasets\urban-learning`. + +В Маросейке правка `4dbe0d1c…` сдвинула вершину 2 объекта +`refined-7686a7fe0530fa` на +0,22 м по Y к видимому краю бордюра. +X и Z сохранены точно. Это **предложение ассистента** (`agent-proposal`), +не подтверждение владельца. Исходная автоматическая карта 582 объектов +с SHA `1d934f43…` не изменена. + +Получен один пример с верхним и наклонным изображениями 768×768. В пакете: +чистые RGB, approximate Gaussian depth/alpha, матрицы камер и пиксельная +конвенция, original/proposed векторы, проекции, операции, хеши источника и +версии, происхождение, единый `split_group` сцены, карточка датасета и reader. +Сырые панорамы/траектория не использовались: LCC проверен по producer receipt, +а камеры — явно заданные локальные камеры рендера. Gaussian depth не считается +LiDAR-рельефом; новая опора высоты после перемещения XY ещё не подтверждена. + +`training_eligible=false`, review unreviewed, complete_regions пусты. +Маски supervision целиком ignore: непроверенные пиксели не стали фоном. +Для обучения с учителем требуется последующее утверждение и проверка опоры; +изменение точности детектора или факт обучения этим опытом не доказываются. + +Фактическая сборка внутри GPU-контейнера — 165,05 с с холодной подготовкой +CUDA. Это время одного локального примера, не полной карты и не прогноз +следующих запусков. Dataset 12,47 MB / 16 файлов; ZIP 9,57 MB. +SHA манифеста `30ed699ee89dd34cb19ef1a39e98395c46c0f636e8dc1cd72d5d8cd47409afc9`. +Архив: `exports/4dbe0d1ce274e458d0e323092f862f5c80a023eadf71d56dfaa4ff1aedec1c24.zip`. + +Архив распакован в другой Worker-каталог. Встроенный stdlib-reader проверил +хеши; отдельный read-only контейнер без сети, Core и исходной сцены открыл +все PNG/NPZ и проверил размеры, камеры, нулевые supervision masks и сохранение Z. +Проверены очередь при выключенном learning-обработчике, повтор POST, +перезапуск Core во время сборки, перезапуск обработчика после публикации, +повтор приёма и недоступный транспорт: одна задача, одна попытка, тот же SHA. + +В версии 2026-10-20 редактор показывал статус доставки. В текущем UI эта техническая подпись убрана по запросу владельца; Worker-outbox и квитанции сохранены. +Режимы, сравнение, fullscreen и Escape проверены; Core оставлен на :8000. +35 Python-проверок, 1 233 frontend-проверки, архитектура, typecheck и build прошли. +На Worker отдельно проверены 20 задач, отказ 21-й и продвижение после ошибки; +синтетические данные этой проверки удалены. +Установленный release: `f4ecec8d84dd09c4b1ba8587b993cf16b42ccfab4352cd7cfd16674f7083aa37`. + +Машинная квитанция: `outputs/SEMANTIC_DELIVERY_ACCEPTANCE_2026-10-20.json`. +Она содержит полные хеши и результат изолированного чтения. Временные снимки +для выбора правки и проверочная распаковка удалены на Worker. На Mac остаются +исходники, семантическая ревизия, текстовая квитанция и небольшой UI-снимок; +обучающие изображения/NPZ/ZIP на Mac не сохранялись. +После уборки Worker-store занимает 5,467 GB: основная часть — общий Gaussian +источник 5,408 GB, используемый повторно. ZIP и опубликованный dataset остаются +на Worker; CUDA-кэш входит в общий бюджет. На D свободно 59,015 GB. + +## Следующие границы + +- Утверждение человеком объекта/области и выбор только подтверждённой области + supervision; проверка опоры и видимости, пригодности для конкретной задачи. +- Метрически подтверждённая поверхность размещения. Произвольные пешеходные области пером/прямоугольником и постановка шаблонов уже реализованы, но не означают LiDAR/геодезическую проверку. +- Изменение качества алгоритма через обучение и отложенную оценку с разделением + сцен; сейчас выполнена доставка и переносимость, а не этот следующий этап. +- Другие форматы исходников и неподдержанные калибровки требуют отдельного + адаптера; текущий реальный пример принят для LCC/native frame Маросейки. + + +## Пивот и шаблоны — дополнение 2026-10-20 + +`semantic_objects.py` — общий исполнитель `place/transform/remove` для Core и +Worker. Каталог `marking-templates.json` входит в исходники продукта и Worker +release. Координаты опубликованных шаблонов v1 не изменяются задним числом; +новый рисунок требует нового ID. Стрелки используют существующий short preset; +велосипед сохраняет атрибуцию Major Alexey / CC BY-SA 4.0. А и зебра — +редакторские заготовки, соответствие дорожному стандарту не заявлено. + +Сервер запрещает новые правки отдельных вершин разметки. Ранее принятая +подписанная история продолжает воспроизводиться. Новые/трансформированные +полигоны проходят прежние проверки геометрии и отверстий. `place` содержит +точку визуальной поверхности; объект остаётся `unreviewed`, без разрешения +маршруту. В той версии прямое изменение Z не было включено; текущая версия добавляет отдельную явную операцию с пометкой непроверенной высоты. При нулевом жесте нет изменения +геометрии, признаков или новой ревизии; перенос без поворота не вычитает +и не прибавляет центр фигуры к её координатам. + +Worker воспроизводит операции, сверяет итоговую геометрию с принятой ревизией, +сохраняет предыдущее состояние и все части составного элемента, проецирует +каждую часть в оба вида. Близкие изменения полос одной зебры дают один +локальный пример. Для нового элемента `original=null`; это не пример, +найденный алгоритмом. Все маски supervision остаются ignore. + + +### Приёмка этой версии + +Установлен Worker release `d948298152c79a5464bb4638537aba7ec5e69a80fc55596dbaed6a5c08edce6b`. +Изолированный опыт place + transform зебры дал один переносимый пример +с шестью частями в обоих видах за 44,859 с при подготовленном CUDA-кэше. +ZIP распакован и проверен автономным reader; проверочные медиа удалены. +На Mac обучающие медиа не копировались. Рабочая ревизия Маросейки не менялась. + +На живой сцене проверены X-пивот, отмена, вставка точки при пересечении +контуров, постановка и поворот зебры, переключение слоёв, fullscreen/Escape. +Подробности и ограничения: `outputs/MISSION_CORE_SEMANTIC_EDITOR_PIVOT_REPORT_2026-10-20.md`; +хеши и результаты: `outputs/SEMANTIC_EDITOR_PIVOT_ACCEPTANCE_2026-10-20.json`. + +## Текущий редактор — 2026-10-21 + +Вход в «Семантику» сразу включает редактирование. Карандаш, сохранение только +при наличии черновика и пересчёт находятся в шапке; технических подписей о пивоте +и Worker во viewport нет. Gaussian/коллизии/память остаются сверху, ракурс — +одна круглая кнопка. Общий `Toolbar` Design Guideline справа содержит инструменты, +глазик с независимыми слоями алгоритма/ручной карты и качество. Escape сначала +закрывает меню или отменяет незавершённый инструмент, затем снимает выделение, +затем завершает редактирование, не сворачивая fullscreen тем же нажатием. + +В планировщике появился раздел «Тулбар»: четыре стороны, min/max размер, +линза, интервал, автоскрытие/задержка и цвета. Эти настройки сохраняются в +существующем профиле браузера, совместимом со старыми данными. Меню открывается +за максимальной границей увеличенных кнопок; переход к нему защищён ограниченным +треугольником намерения, движение по другим кнопкам меняет открытое меню. +Выбранные оси, качество, тип точки и действие области имеют видимое выделение. + +V — выделение рамкой, Shift — добавить/исключить, Delete — атомарное удаление, +Cmd/Ctrl+Z — отмена. Частичное удаление замкнутого контура соединяет оставшиеся +соседние вершины; минимальный размер и проверки пересечений сохранены. +«Свойства точки» переключают угол/кубическую кривую; ручки увеличиваются на +экране для плотных контуров без изменения физических координат. Движение ручки +учитывает это увеличение и начальный захват. Вставка на кривой использует +De Casteljau. Перо P и прямоугольник R создают, объединяют или вырезают +пешеходную область; отверстия/разделённые части сохраняются, исходные высоты +сохраняются где известны, новые интерполированные высоты остаются непроверенными. + +`letter_A_v2` взята из существующего шаблона распознавания; старый ID не меняет +сохранённую историю. Добавлены совмещённые стрелки прямо-налево/направо и компактный +велосипед с сохранением атрибуции. Геометрия разметки редактируется как целый объект. + +Core и Worker воспроизводят `curve/delete_vertices/region/translate` одним +серверным модулем `semantic_vectors.py`; frontend имеет согласованное исполнение +для черновика. Worker сохраняет original/proposed, операции и все части региона. +Это поддержка подготовки проверяемых примеров, а не выполненное обучение. + +Приёмка текущей версии: 1242 frontend-теста, 31 Python-тест, 8 проверок общих +меню/иконок, архитектура, typecheck, registry, production build и живая Маросейка. +Проверены видимость/перетаскивание ручек, выбранная XZ, меню при max 88 px, +верхнее/правое положение, fullscreen/Escape, Z+undo, прямоугольный вырез/заполнение +и замыкание пера. Пробные правки отменены, оригинальная карта не сохранена заново. + +Worker release `126e974a18c47e8b2e9d23b4da58ddd18a5403f3722b0a94f2cf8dcf7ffe2cd4`. +Изолированное предложение кривой на реальном Gaussian Маросейки: 1 пример, +39,699 с внутри сборщика / 45,515 с вся проверка с готовым CUDA-кэшем; +ZIP проверен автономным reader. Временные медиа/распаковка удалены, сохранена +текстовая квитанция. Это проверка новых операций; исходная реальная доставка +Core→Worker от 2026-10-20 остаётся отдельной приёмкой, не подменена fixture. +См. `outputs/MISSION_CORE_SEMANTIC_EDITOR_REPORT_2026-10-21.md` и +`outputs/SEMANTIC_EDITOR_ACCEPTANCE_2026-10-21.json`. + +## Дополнение 2026-10-21: продолжение и копирование + +Новые операции `duplicate_vertex`, `duplicate_marking`, `translate_vertices` +воспроизводятся одинаково в UI, серверном приёме и переносимом Worker builder. +Старый `translate` сохраняет целое перемещение маркировки, включая линейную, +чтобы ранее сохранённые ревизии не поменяли смысл. Вершины допускает только +явный subtype `linear_marking`; неизвестные/групповые символы остаются цельными. +Копии не наследуют утверждённую опору высоты, имеют `unreviewed` и новую +идентичность; исходная модель не изменяется. Допуск геометрии и лимиты +обучающих окон (16 окон, смещение до 8 м) сохранены. + +## Projection and navigation cube — 2026-10-21 + +Semantic mode opens with a real orthographic camera. The header projection button switches orthographic/perspective without changing geometry; scale matches on the focal plane. The shared Design Guideline NavigationCube controls orientation separately (six faces, twelve edges, eight corners), tracking the camera quaternion. Its Y-up adapter matches the existing Mission Z-up transform; TOP means mission +Z. The clipping ruler occupies the lower two thirds. Add-point uses a centered circled plus; whole marking insertion is last in the toolbar. + +Three input camera and PlayCanvas rendering camera share projection/orthographic height. Panning, zoom around the cursor, pixel-sized pivot, surface picking and line insertion respect the projection. Perspective segment insertion uses optical depth rather than clip-space Z. Pure projection changes also invalidate overlay projection, even if the camera pose did not move. No semantic data or training payload changes. + +Viewport settings dropdown includes `3D-куб`: size 48–160 px (default 66 px, 40% smaller), opacity, face/text/edge/hover/hover-text colors. Values use the existing validated browser preference store. The ruler starts below both the first third and the configured cube height. Dense distant sky splats can cover a top orthographic view at an unlimited ceiling; use the existing height slice to reveal the road (Maroseyka QA: upper 17.33 m). No sky filtering or scene modification is introduced. + +## Selection and layer visibility — 2026-10-21 + +The semantic legend is now a multi-select mask for rendering, model comparison, +editable nodes, hover/picking, and marquee selection. Hidden classes cannot be +selected; changing the mask drops hidden selections and cancels placement tools. +The toolbar offers contour, pedestrian-region and marking tools according to the +visible classes, with point properties determined by the selected feature. + +A first pointer press on a visible vertex immediately owns the drag with the +currently selected X/Y/Z/plane constraint. The gesture captures its selection, +anchor and source geometry before React updates; it cannot accidentally move a +previous selection. A selected group stays grouped. Click without movement does +not create a revision, Escape cancels, release commits once, and Ctrl+Z undoes. +Ctrl still owns camera orbit; Shift on the pivot still duplicates/extends. + +NavigationCube text uses projected face-local tangent vectors, so labels rotate +and foreshorten on each face. The `3D-куб` settings add independent line +transparency (0–100%); faces and labels retain their own colors/opacity. No map +acceptance thresholds, source geometry, save schema, or dataset storage changed. + +## Исправление направления Shift-копии — 2026-10-21 + +Причина обратного угла: внутренняя вершина всегда копировалась после исходной +независимо от движения к предыдущему или следующему сегменту. Теперь выбор +стороны сравнивает направления локальных участков в XY, нормированные по длине; +порядок обхода, длина соседнего сегмента и Z-смещение не подменяют направление. +При равном соответствии сохраняется детерминированный выбор `after`. +Preview вычисляется от неподвижной исходной геометрии; после отпускания +сохраняется один показанный вариант. Индекс выделения и пивот следуют за копией. +Проверки самопересечений, совпадающих точек и замкнутости не ослаблялись. + +Проверка: 35 frontend-тестов, 41 Python-тест, Ruff и production build прошли. +Покрыты угол из обращения, оба направления, обратный обход, концы, замкнутый +шов, касательные кривой, смена направления во время drag, Escape, Undo/Redo, +сохранение/восстановление и смешанная история старых и новых операций. +На установленном Worker выполнены 13 синтетических случаев точного порядка +вершин. Release `7c339485c2d8b92e` работает; Core на `:8000` доступен. +В отдельной тестовой вкладке проверена загрузка сохранённой Маросейки; +ручной Shift-drag через browser automation не воспроизводился, модификатор +проверен тестами обработчика жеста. Пробная вкладка закрыта без записи ревизий. + +По сообщению о неполном сохранении: 162 операции ревизии `f5182fce3a58` +переиграны браузерной и серверной реализацией от одной предыдущей карты. +У 602 объектов совпали геометрия, ручки кривых и статус проверки; максимальное +расхождение координат — 0. Это проверяет только принятую партию, а не действия, +которые могли не попасть в запрос. Текущий пользовательский Chrome не обновлялся. +Подробная квитанция: `outputs/semantic-direction-2026-10-21/report.md`. + +## Ускорение сохранения — 2026-10-21 + +Групповая проверка индексов больше не копирует весь сплайн для каждой вершины; +для изменения остаётся отдельная рабочая копия. `save` возвращает точную уже +проверенную карту после атомарной записи, не воспроизводя всю историю повторно. +POST сохранения и квитанции выполняют блокирующую работу в штатном threadpool. +Проверки геометрии каждого действия, хеши, конфликты, квоты и идемпотентность +не ослаблены. Формат API и Worker-пакета не изменён; новых дисковых кэшей нет. + +На одной и той же принятой истории Маросейки: 2 новых действия после 345 старых +сократились с 16,035 до 0,587 с; партия 162 действий — с 18,524 до 3,499 с. +Результирующие карты побитно совпали в каноническом JSON-хешировании. Это +ограниченные замеры server-side save, не гарантия времени для произвольной карты. +Полный изолированный HTTP save небольшой партии — 0,729 с, последующее чтение +и повтор запроса совпали. 45 основных и 26 связанных тестов, Ruff — успешно. + +Core на `:8000` обновлён без перезагрузки Chrome; живое чтение вернуло ту же +карту и 10 ревизий за 0,920 с. Тестовые ревизии не записывались в рабочую историю. +Квитанции и метод: `outputs/semantic-save-performance-2026-10-21/report.md`. + +### 2026-10-21: selection-only vertices and road letter artwork + +Vertex rendering and picking now require a selected contour; nonselected lines +remain segment-pickable. Multi-selected contours expose their vertices, hidden +layers remain excluded. First-press dragging on a visible point is preserved. +The common catalog adds `letter_A_v3` with the elongated road silhouette from +GOST R 51256-2018 figure B.11. Both historical A ids retain exact geometry and +source metadata for replay and are hidden from new placement. The generator +also retains the editable linear-marking entry. + +The authorized replacement of nine operator-placed A templates is a separate +agent-proposal revision, with unchanged pivot positions, headings and heights. +It does not rewrite fitted algorithm polygons, the immutable model or past edits. +Full checks, live revision evidence and the training audit are recorded in +`outputs/semantic-selection-learning-2026-10-21/report.md`. + +The audit found nine of thirteen human-revision sample jobs rejected by the +8 m observation-displacement bound. Four jobs are review drafts, none are training +eligible. The replacement job encounters the 16-window bound. Saving edits is +independent of both failures. Required next work: tile the final annotation +snapshot, apply bounded per-job render budgets with resume/deduplication, preserve +class/region review scope and ignore masks, and then run a held-out-scene learning +experiment. No acceptance rules were weakened and no training was claimed. + +## Последняя раскладка и полный снимок правок — 2026-10-21 + +Последний режим (просмотр / семантика / планирование), проекция, слои сцены, +видимость инфраструктуры и памяти, семантическая маска классов, модельная/ручная +видимость, ограничение осей и операция области сохраняются в проверяемом +`missioncore.simulation-layout/v1`. Обычное открытие подготовленной локации +в каталоге использует эту раскладку; явное «Подготовить маршрут» выбирает +планирование. Вход в семантику больше не принуждает вид сверху и ортографию. + +Поза камеры, масштаб ортографии и обе границы среза записываются отдельно +для SHA сцены (`missioncore.simulation-cameras/v1`, максимум 16 последних сцен). +Запись выполняется при уходе, pagehide и раз в 1,5 с; восстановление не +центрирует камеру заново при изменении размеров viewport. Глобальная выбранная +проекция применяется после восстановления позы. Это маленькие настройки +браузера, без геометрии правок, изображений и обучающих материалов. Качество, +куб, пивот и DockToolbar используют существующее хранилище предпочтений. + +Дополнительно заменены 14 прежних распознанных letter_A в ручной версии +Маросейки (ревизия f26a71ddb9afd8a169d105779c597decf2b11a99454f79e7ccf6db5d35a00a0b). +Операция retemplate сохраняет ID, позу и габариты, применяя канонический +letter_A_v3 в проверенном локальном фрейме. Высота восстанавливается из +существующей наклонной плоскости объекта, без заявления о новой опоре. +632 других объекта, исходная модель и 15 прежних ревизий совпали полностью. + +Worker собирает наблюдения по окончательной геометрии выбранных классов и +исходной модельной основе, а не по расстоянию каждого перемещения мыши. +Окна 12 м с шагом 10 м покрывают все пересечённые сегментами ячейки. +Исходные координаты и порядок вычислений не меняются. Задание содержит +не более четырёх окон; подтверждённые по хешам части повторно не рендерятся. +Перезапуск с другим сборщиком/образом/аннотацией отклоняется. Коллекция +публикуется атомарно только после проверки всех частей. Ни дальность ручной +правки, ни число операций не используются как критерий семантического качества. + +Формат коллекции missioncore.semantic-collection/v1 объединяет самостоятельные +части missioncore.semantic-dataset/v1. Включены RGB, глубина/alpha, камеры, +исходные/исправленные векторы, проекции, история и переносимый проверяющий reader. +Непроверенные области сохраняют ignore; training_eligible=false. Обучение +модели и подтверждение качества на другой сцене этим экспортом не заявляются. +Квитанция полного прогона и ограничения: outputs/semantic-final-review-2026-10-21/report.md. + +Полный снимок Маросейки опубликован: 213 окон / 426 RGB / 54 части, +1 956 748 748 байт, подготовка 2550,391 с. Независимое чтение всей коллекции +без сети/Core подтвердило хеши, точные векторы и ignore-маски. Core получил +draft-ready с sample_count=213 после согласования предела квитанции с размером +коллекции (максимум 256 × 4 окна). Подробные числа и ограничения в указанном отчёте. + + +## Разделение истории и кандидатов для обучения — 2026-10-21 + +Переносимый `dataset_reader.py` (исходник `simulation/semantic-learning/dataset_store.py`) +теперь предоставляет `review_samples(root)` и `review_index(root)`. Сначала проверяются +все хеши и принадлежность окон одной сцене, ревизии и аннотации. Затем разделяются +`active_candidates` и `rejected_history`, включая их неизменённые проекции по ракурсам. +Ни редакторский `accepted`, ни сохранение, ни непрозрачность Gaussian-пикселя не +допускают объект в обучение: `approved_targets=[]`, `background_targets=[]`, +`complete_regions=[]`, `training_eligible=false`. Поле `proposed_element` по-прежнему +содержит историю и не является списком положительных меток. + +CLI `dataset_reader.py DATASET --review-index NEW_INDEX.json` создаёт небольшой +отдельный индекс вне неизменяемого датасета; существующий файл не перезаписывается. +Все ссылки относительные. Для уже опубликованной коллекции новый reader запускается +отдельно: исходные манифесты, изображения, камеры и семантическая карта не меняются. +Новый reader и индекс проверены на Worker 006 на закреплённой ревизии f26a71dd: +213 окон, 467 активных объектов и 50 удалённых записей; допущенных учебных целей нет. +Это подготовка данных для локальной оценки качества, не обучение модели. + +## Выбор линии и точки — 2026-10-21 + +Клик по телу редактируемого контура выбирает все его управляющие точки, включая +кольца полигона, но без дублирующей замыкающей точки и промежуточных отсчётов кривой. +Delete удаляет весь выбранный контур; Undo восстанавливает его. Клик по отдельной +видимой вершине после такого выбора переключается на одну точку и сразу позволяет +её тянуть. Ручная группа вершин, выбранная рамкой/Shift, сохраняет групповое +перетаскивание. В пересечении контуров окно выбора применяет ту же семантику. +Существующие ограничения корректности частичного удаления не ослаблены. + +### Проверенные локальные предпочтения границ (21 октября 2026) + +`simulation/semantic-learning/boundary_review.py` собирает на Worker малый переносимый пакет из явно просмотренных областей неизменяемой коллекции. Записи связывают исходные RGB/камеры/геометрию с точными диапазонами сегментов; координаты не пересэмплируются. Только явное `edited-better-than-original` на видимом участке допускается в ограниченный опыт ранжирования. Видимость, ручное редактирование и editor accepted сами по себе не являются допуском. Контекстные и неопределённые участки не получают пиксельных целей или фоновых меток. + +Сборка требует заранее закреплённую другую сцену контроля, проверяет исходные SHA, ограничена 12 решениями / 96 MiB и сохраняет резерв Worker 12 GiB. Вложенный stdlib reader проверяет переносимый пакет после перемещения и повторно вычисляет допуск. Учебные кадры остаются только в отдельном Worker store. Первый пакет и ограничения описаны в `outputs/boundary-pilot-2026-10-21/report.md`; обучения модели на этом этапе ещё нет. + +Shift-продолжение у открытых концов: поперечное движение создаёт новый конечный сегмент; вставка внутрь выполняется при преобладающем движении к существующему соседнему сегменту. Внутренние точки сохраняют выбор стороны по соседним ветвям. Правило общее для всех редактируемых классов; сохранённая сторона операции обеспечивает прежнее воспроизведение истории. + + +## Boundary ranking probe — 2026-10-21 + +The separate Worker-only experiment now verifies a portable reviewed pack, fits a bounded +four-term physical ranking probe, and evaluates frozen visual control windows. It is +not production inference: RGB/depth samples lack production semantic/occluder fields. +Two overconfident review preferences were withdrawn; three remain. Fixed and learned +weights both prefer the reviewed candidate in 2/3 cases; the two visibly assessable +Smolensky windows show no improvement. Four control windows remain unknown. No +acceptance threshold, active map, or user draft changed. No full pipeline run is claimed. +See the local engineering report `outputs/boundary-pilot-2026-10-21/rank-probe-report.md`. +Next: distinguish operator intent from positional certainty before using corrections as +training targets; preserve evidence and use new independent control before qualification. + + +## Closed paint-learning hypothesis study — 2026-10-22 + +`simulation/semantic-learning/paint_hypothesis_study.py` runs separate frozen-fit and evaluation phases for matched label quality, photometric augmentation/relative features, and automated road-context ablations. No production maps are written. + +The bounded Worker study covered 23 windows across four scenes, six fitted models and 18 model/context combinations. Exposure robustness improved in controlled counterfactuals, but none of the tested recipes qualified on both study control streets. Accurate positive probes alone did not establish the predeclared transfer gain. Both raw semantic and fused road masks can reject visible paint; neither qualified as a universal hard veto. This rejects these recipes, not the possibility of learning from reviewed maps. + +Sparse assistant-reviewed probes are diagnostic evidence, not complete-scene ground truth. Sretenka and Sadovaya-Triumfalnaya are now exposed controls for this study family. Eleven focused scientific tests passed; changing held-out labels left fitted coefficients, thresholds and model selection bit-exact. Full decisions, limitations, text archive receipt, two visual examples and the separately specified successor experiment are in `outputs/paint-hypotheses-20261022/report.txt`. Worker-only raw-source identities allow reproduction after retirement of this experiment's derived media. + +## Closed object-proposal study — 2026-10-22 + +`simulation/semantic-learning/object_proposal_study.py` reuses the existing paint proposal generator in separately frozen propose/fit/evaluate phases. The optional `retain_uncertain` switch preserves unpublished candidates without bypassing the supplied physical-validity mask; its default leaves the production road-context gates unchanged. No runtime caller enables it. + +The bounded Worker study reviewed 17 windows across six scenes, 42 complete objects and two separately scored clipped zigzags. It localized two different losses: whole objects absent from proposals, and existing proposals rejected by semantic support. Removing hard context increased candidate count from 284 to 472 but did not improve heldout complete-object discovery (13/15 in both cases). The preselected shape scorer recovered 10/15 versus 9/15 for the fixed admission comparator and introduced one verified false positive. Shape-plus-appearance recovered 13/15 but also accepted a drainage grate. None passed the frozen gain/no-additional-false-positive criterion. This does not qualify a production model or establish the limits of object learning from only 35 labelled candidates. + +Four focused checks passed on Worker, including heldout isolation and physical validity. Default generator output was bit-identical to the prior source on two full observation tiles. The comparator covers candidate admission, not downstream fitting or a full-pipeline rerun. Current Mira controls are now exposed; a successor requires fresh control, object assembly and representative negative examples. See `outputs/object-proposals-20261022/report.txt` for decisions, source/input identities, two visual examples, limitations and the verified closeout receipt. + +## Closed assembly/expanded-admission study — 2026-10-22 + +`simulation/semantic-learning/object_assembly_study.py` compares a bounded single-view +fragment assembler and two expanded classifiers against frozen previous and fixed +admission comparators. It does not publish maps or qualify the retained two-view +row fitter. Source, input and policy hashes separate fit from held-out evaluation. + +The 27-window, eight-street study used five training streets, Sretenka validation, +and two control streets excluded from this fit: Pokrovka and Sadovaya-Karetnaya. +The controls remain historical pipeline-development scenes. All ten control windows +were visually reviewed. Assembly left the complete-object proposal ceiling unchanged +at 27/33. Both newly selected admission recipes recovered 21/33 versus the prior +frozen classifier's 27/33. Six visible yield triangles were rejected by the 0.90 +validation-selected threshold despite higher new classifier scores. A post-hoc +common-threshold diagnostic restored 27/33 but introduced two reviewed false positives; +it is not a new selected model. Five of seven Sadovaya-Karetnaya targets lack a +sufficiently complete proposal before classification. Neither hypothesis passed its +predeclared gain/no-extra-error criterion. Sparse negative review cannot establish +whole-scene precision, and ambiguous regions remain unknown. + +Nine focused checks passed, including dark-gap/invalid-gap refusal, original/hole +preservation, adjacent-bar separation and held-out fitting/selection isolation. +The report `outputs/object-assembly-20261022/report.txt` records the closed decisions, +two visual examples, frozen identities, archive/retirement receipt and next gates: +multi-street/family admission validation and independent multi-view candidate recovery, +followed by a full downstream rerun only after stage qualification. + + +## Closed street-grouped selection / observation study — 2026-10-22 + +`simulation/semantic-learning/grouped_selection_study.py` performs leave-one-street-out +threshold selection over six development streets and checks object-identity +nonregression on controls. The preselected threshold .30 found 17/17 complete +objects in seven raw-only reviewed fresh windows, tying the frozen comparator. +Previously exposed regression controls declined from 27/33 to 26/33 and introduced +one explicitly reviewed false positive. The fitted model scores a required true +candidate below a confirmed false candidate; no scalar threshold satisfies full +retention with zero reviewed false positives for this fitted model. It is rejected. + +Visual inspection also confirmed nonpaint contours outside the frozen sparse +negative masks; 17/17 does not imply clean vectors or exhaustive precision. +Fifteen available render/tile variants over three known difficult windows retained +the same 2/7 whole-object proposal ceiling. All share a top-down orientation, so +this does not test truly new oblique evidence. Five scientific checks passed; +production maps, drafts and default inference were unchanged. +See `outputs/grouped-selection-20261022/report.txt` for closed decisions, limitations, +full visual audit, source/input identities and verified archive/retirement receipt. +The specified successor changes visual representation and requires complete +visible-region negative review, rather than retuning the rejected threshold. + +## Closed frozen-visual admission study — 2026-10-22 + +`simulation/semantic-learning/visual_admission_study.py` compares a frozen installed +Mapillary Mask2Former representation, the same-data handcrafted comparator, fused +features and native paint scores. The 40-window study uses identical 104 labels +from six development streets, six new raw-only reviewed windows and 17 exposed +regression windows. Fitting and street-grouped selection exclude both control +streets. New visible-background regions are explicit; unknown remains unlabelled. + +Visual features retain 19/20 new whole objects while reducing reviewed false +candidates from 11 to 1, but regress from the frozen comparator's 44/50 to 19/50 +on the older control. Fused features retain 37/50 with zero reviewed false +candidates there. The preselected handcrafted arm also regresses. No arm qualifies. +All 23 controls were visually inspected; real clipped paint/bicycles are lost +outside the whole-object metric, and legacy sparse negatives do not establish +exhaustive precision. Candidate completeness remains a separate limitation. + +A subsequent fixed-model counterfactual diagnoses orientation instability: +rotating the identical image by 180 degrees changes one control from 0 to 9/16 +objects and another from 7 to 0/7. No best-angle control selection or model update +was performed. A required dash remains rejected at every quarter turn, so this +explains only part of the failure. Four focused tests passed; 17 development +candidate sets were bit-identical to the prior study and 173 source files were +reverified. No maps, drafts, production thresholds or default pipeline changed. +See `outputs/visual-admission-20261022/report.txt` for the closed decision, two +proof images, uniform-rotation-pooling successor protocol and verified storage +closeout. The successor is specified, not yet executed. + +## Closed uniform-quarter-turn admission study — 2026-10-22 + +`simulation/semantic-learning/c4_admission_study.py` tests uniform four-orientation +pooling of the unchanged frozen visual representation. All 48 feature orbits pass +cyclic bit-equality; independent rotated-image inference on two previously unstable +controls preserves accepted IDs (maximum score error 1.91e-8). This qualifies the +bounded feature/scorer invariance check, not full-generator or arbitrary-angle +invariance. The same 104 training labels and six street-grouped folds are retained. + +The preselected C4 visual classifier recovers 62/70 regression and 22/25 fresh +whole objects, versus 38/70 and 9/25 for the identical prior single-view head. +The older simple classifier still preserves 63/70 and 23/25. Both C4 arms lose +two true dashes and add two false tree-pit/curb contours on a fresh negative +window, so neither passes the predeclared qualification. The fused arm is fully +reported but was not selected. Nine whole targets lack adequate proposals. + +All 31 controls were visually inspected. Two fresh background masks wrongly +included clipped/uncertain paint; an explicit post-hoc erratum excludes these +areas without changing original labels, models, positive targets or accepted IDs. +Original and corrected metrics remain separate. Corrected fresh reviewed FP +counts are 6 for the older classifier and 2 for C4; these descriptive post-hoc +numbers do not constitute a new blind qualification. Real clipped lines and +bicycles still disappear outside the whole-object count; sparse legacy negatives +and jagged geometry prevent claims of exhaustive precision or finished vectors. + +Seven focused tests passed, 40 prior candidate sets were bit-identical, and +213 raw source files were reverified. A training coverage audit found 24/36 +positives are crosswalks; dashes, arrows and yield examples each occur on only +one development street. Next is a frozen-representation, independently reviewed +coverage experiment, not another control-driven threshold sweep. No production +maps or defaults changed. `outputs/c4-admission-20261022/report.txt` contains the +closed decisions, audited metrics, two proofs and verified storage closeout. + + +## Frozen multi-area review corpus — 2026-10-23 + +`simulation/semantic-learning/corpus_store.py` adds an indexed metadata reader over +existing `semantic-dataset/v1` and `semantic-collection/v1` exports. It does not +change their contents or copy images. A plan explicitly lists relative dataset +paths and `dataset.json` SHA-256 identities, plus physical-area group assignments. +Current owner policy (26 October): assignments are explicit experiment metadata, +not a request to search for geographical overlap. An unnamed scan can have its +own group; existing declared lineage and source revisions keep their assigned +partition. No geolocation or cross-scan matching occurs in this reader. Group +IDs do not prove physical independence, and GPS/overlap proof is not required +to build or evaluate a declared source set. Existing producer `split_group` constraints also +apply; conflicting assignments fail rather than being silently reassigned. + +The plan format is `missioncore.semantic-corpus-plan/v1`: + +```json +{ + "schema_version": "missioncore.semantic-corpus-plan/v1", + "groups": [ + {"id": "physical-area-a", "split": "train", "worlds": [""]}, + {"id": "physical-area-b", "split": "test", "worlds": [""]} + ], + "datasets": [ + {"path": "datasets/source-a", "sha256": ""}, + {"path": "datasets/source-b", "sha256": ""} + ] +} +``` + +Replace the placeholders with verified identities. Real corpus preparation runs +only in the persistent Worker store. The source-only Worker package already +includes this module through its existing Python source inventory: + +```text +python corpus_store.py build corpora/v1 +python corpus_store.py inspect corpora/v1 --split train --limit 8 +``` + +The build receipt contains `path`, `sha256` and `sample_counts`. Opening the reader +requires that pinned corpus SHA-256. To create a growth version, include the old +receipt as `parent` in a new plan, retain its datasets and physical assignments, +and choose a new output path. Adding unrelated files to the store cannot alter +an existing corpus. The reader does not enumerate the store. Growth versions +cannot silently drop old inputs or move old groups across partitions. An explicit +corrected lineage, rather than a growth version, is needed to revise a wrong +assignment; any affected independence claims must then be reassessed. + +The SQLite index is capped at 256 MiB. Metadata batches default to eight references +and stop at either the requested count (1–128) or 2 MiB of serialized references; +one reference is capped at 256 KiB. These are reader limits, not a promise about +Python object overhead, decoded images, caller-retained batches or trainer memory. +Build validates existing exports one at a time; it still performs full input hash +verification. Opening verifies the index by streaming its checksum and uses an +immutable read-only connection, excluding unbound SQLite journal/WAL state. +`review(reference)` loads one sample's metadata and labels; +`open_member(reference, name)` explicitly verifies and streams a bound member. +The entire store can move together because references are relative. The published +corpus includes its reader sources. `corpus.json` is published last as a completion +marker; failed builds clean only their own scratch and preserve previous versions. + +All entries remain `training_eligible=false`. A partition named `train` does not +approve its labels. Map acceptance, deleted geometry history, per-view evidence, +unknown pixels and complete negative regions retain their prior meanings. All +views and camera references stay available; contextual geometry is not converted +into visible-paint truth. Revisions are retained for review, not declared independent +training examples. Selecting a consistent supervised revision, deduplication, +evidence admission, balanced sampling and the actual trainer remain separate gates. + +Thirty focused synthetic tests passed across corpus, delivery, review and snapshot +readers; static checks passed. The tests cover grouped split refusal, frozen growth, +member tampering, collection paths, relocation with the bundled CLI, lazy media +access, bounded batches/index, and preservation of old data on failure. This is +source implementation acceptance only: no real corpus was built, no Worker was +started, no model was trained, and no throughput or quality claim on 100 scans +is supported. The legacy C4 experiment loader is unchanged. See +`outputs/semantic-corpus-20261023/report.txt` and its verification receipt. + + +## Task-specific supervision admission — 2026-10-23 + +`simulation/semantic-learning/admission_store.py` consumes the pinned corpus through +its public `reference(sample_id)` lookup, without changing raw exports or the +review-only corpus policy. A new immutable supervision release binds explicit +review decisions and one selected `(world_sha256, revision, annotation_sha256)` +identity per source world. Different revisions may remain available in the review +corpus, but cannot be mixed into this supervised release. Draft review changes do +not update a published release; corrections require a new destination and hash. + +Two task contracts are deliberately separate: + +- `observed_paint`: binary visible paint/background on explicitly reviewed pixels + of a named raw input view. Runs are `[row, first_column, exclusive_end_column]`, + sorted integer image indices. Paint, background and explicit unknown runs must + be disjoint and inside the bound camera size. Everything else remains unknown. + `pixel_target(view)` produces one bounded bytearray with 1=paint, 0=reviewed + background and 255=ignore. No projected vector or opaque Gaussian mask supplies + implicit labels. Unknown-only views remain available as inputs but are omitted + from loss targets to avoid an all-ignore loss. +- `contextual_map`: explicitly reviewed intervals `[path, segment, t0, t1]` on a + pinned active source LineString or Polygon contour. Source endpoints are retained; + partial intervals use linear interpolation without curve fitting. Only confirmed + observed/context evidence with named supporting input views becomes a target. + Weak rule proposals and unknown ranges remain in the review record but never + enter target batches. These are partial planar vector targets, not whole-object + or filled-polygon supervision. `supervised_axes=["x","y"]` and + `z_supervision=false`; stored Z remains provenance, not approved metric height. + Curved paths and degenerate planar segments fail explicitly until an appropriate + target contract exists. + +Every decision records reviewer identity/kind (`human` or `assistant`), zoned +review time and reason. This records responsibility; it is not identity +verification, proof of visual correctness, independent human approval, or a +quality certificate. Decisions have the following shape (replace placeholders +with identities and actual visually reviewed scopes; do not use as real labels): + +```json +{ + "schema_version": "missioncore.semantic-admission-decision/v1", + "sample_id": "", + "reviewer": {"id": "", "kind": "human"}, + "reviewed_utc": "2026-10-23T12:00:00+00:00", + "reason": "", + "inputs": [ + {"sample_id": "", "view": "top"}, + {"sample_id": "", "view": "oblique"} + ], + "observed_paint": [ + {"view": "top", "paint": [[1, 2, 5]], "background": [[4, 1, 7]], "unknown": []} + ], + "contextual_map": [ + { + "feature_id": "", + "geometry_sha256": "", + "ranges": [[0, 0, 0.25, 0.75]], + "state": "confirmed", + "evidence": "context", + "support": [{"sample_id": "", "view": "oblique"}], + "reason": "" + } + ] +} +``` + +Context may include adjacent windows from the exact same source world/annotation, +physical group and split. All cited evidence views must also be supplied as model +inputs. Cross-world alignment is not assumed; input mixing across coordinate +frames/revisions or into a control partition fails. Only raw `.png` and bound +camera descriptors enter `inputs`; corrected labels are targets, never image +inputs. Source identities/group IDs in the example are bookkeeping, not features +for a model. Conflicting geometry for one reviewed feature across windows fails. +Deleted history cannot be promoted to a target. Conflicting pixel classes or +vector ranges fail rather than resolving by last-write order. + +Preparation plan (`missioncore.semantic-admission-plan/v1`) contains `corpus` with +its path/hash receipt, `revisions` with the selected source identity objects, and +`decisions` with relative JSON file paths and SHA-256 identities. Preparation and +real review data remain Worker-owned. Source packaging includes the module through +the existing source inventory: + +```text +python admission_store.py build supervision/v1 +python admission_store.py inspect supervision/v1 +``` + +The release copies only bounded decision metadata and portable reader sources; +observations stay in their original datasets. Limits: 2 MiB per decision/compiled +record, 2,048 decisions, 64 MiB of release members, 8 MiB manifest, 16 input views +per decision, four million pixels per mask. An oversized release fails explicitly; +this is not a measured capacity claim for 100 scans. Completion manifest publishes +last, failed builds clean their own scratch, and existing releases are never +replaced. The entire store may relocate together. + +`Supervision.training_batches(task, batch_size=8)` supplies only train examples; +`batches(task, split, batch_size=8)` separately supports validation/test/regression +with `training_eligible=false`. Counts and serialized metadata bound each batch. +`open_image(input_descriptor)` revalidates and streams the exact raw RGB member; +metadata iteration does not decode/read images. A consumer must preserve +`ignore_index=255`, `supervision_scope`, reviewed ranges and supervised axes. +`background_from_absence=false` forbids deriving negative/no-object loss from +unlabelled regions. A standard exhaustive segmentation/detection loss is not +valid for these sparse targets. The legacy C4 study loader is unchanged. + +Verification: 57 focused synthetic tests across admission, corpus, review, delivery +and snapshot modules passed; Ruff passed. A minimal 8×6 fixture yields 3 paint, +6 explicit background and 39 ignored pixels; a contextual interval remains a +separate planar target. Tests exercise contradictory review, geometry/range +identity, context/split/revision isolation, lazy media/tamper checks, portable CLI, +bounded batches, failure cleanup, and preservation of source datasets. Real +imagery was not reviewed or admitted, no real supervision release was prepared, +no Worker was started and no training ran. The next operational milestone is +visually reviewed real supervision followed by the fixed-recipe growth experiment; +synthetic contract tests do not demonstrate recognition accuracy. +See `outputs/semantic-admission-20261023/report.txt` and `verification.json`. + +## Real supervised pixel growth experiment — 2026-10-23 + +The synthetic-only status above describes the admission-contract increment. +Subsequent real review and fitting are now complete in the Worker-owned +`semantic-growth-20261023` experiment. The admitted release contains nine +observed-paint training windows across Maroseyka, Sretenka, Mira44–64 and Smolensk, +five regression windows on Pokrovka and Sadovaya-Karetnaya, and one separately +retained contextual-map target. The contextual target is not used by this probe. +Validation/test remain empty; exposed regression streets are not a blind test. +The release SHA is `a562d56b1e76862196480a8eacca4977c24418dfd9817f0affcd1824ee470086`. + +`simulation/semantic-learning/pixel_growth_probe.py` compares a frozen pretrained +semantic baseline and two linear heads over the same frozen C4-averaged visual +features. One head uses Maroseyka, the other all four training streets. Training-only +normalization, class/area/window weighting and explicit ignore pixels are enforced; +identities and coordinates never enter visual inference. Both heads are frozen +before regression evaluation; threshold 0.5 and the recipe are not retuned. + +The fixed no-regression criterion failed. Expanded versus single-street reviewed +paint recall on Pokrovka changed 99.34% → 100%, but reviewed background false +positive rate worsened 2.31% → 3.48%; Sadovaya-Karetnaya false positives improved +2.05% → 1.51%. Only negatives are reviewed on Sadovaya. Full visual inspection also +shows merged stripe gaps at P1 despite perfect sparse-probe counts. These rates +are not whole-object or whole-street accuracy, and do not qualify either model +for publishing semantic maps. Sparse labels can hide errors; unknown pixels must +remain ignored rather than becoming invented negatives. + +The next isolated question is whether dense reviewed training regions (paint, +stripe gaps and difficult background) improve the same head. A subsequent +representation/decoder change requires its own comparison and independent +validation. No per-location repair, application-state mutation or production +model replacement was performed. Four new regression tests plus admission/corpus +checks passed (44 tests); Ruff passed. Exact inputs, models, visual evidence, +limitations and verified retention receipt are in +`outputs/semantic-growth-20261023/report.txt` and `closeout-receipt.json`. + +## Paired supervision density experiment — 2026-10-23 + +A second completed Worker experiment holds the same nine training images, four +physical streets, frozen features, fitting recipe and five regression targets +constant. `supervision_density_probe.py` compares sparse and expanded reviewed +masks; all previously labelled pixels are preserved. Explicit reviewed paint grew +14,111 → 29,351 pixels and background 103,464 → 377,367. The new supervision SHA +is `a2bad9621a6b5b2f3853ad34876df37a711f1d7521b170280e884b0f32ca084b`. +The sparse model reproduced its previous parameters and control counts exactly. + +Expanded review reduced original per-street false-positive rates on Pokrovka +3.483% → 2.489% and Sadovaya-Karetnaya 1.506% → 0.527%, preserving the original +reviewed-paint recall. P3 alone slightly worsened (74 → 87 false pixels), so this +is not uniform per-window improvement. A separately frozen, exposed diagnostic +ROI on P1 still has essentially 100% false paint in stripe gaps. The full +qualification criterion therefore failed; no map/model was published. + +Posthoc evaluation without refitting shows the training zebra M3 is already +separated well (dense gap FPR 0.197%, paint recall 99.979%). The P1 failure is +transfer to another crossing, not proof that the head cannot separate stripes +anywhere. Next isolate crossing diversity before drawing a causal conclusion +about the frozen representation. All controls remain outside training; no blind +test or independent human-gold claim is made. Seven focused tests and Ruff pass. +Exact results, source/review identities, two visually checked comparisons and +retention receipts: `outputs/semantic-dense-20261023/report.txt`. + +## Crossing-diversity experiment — 2026-10-23 + +`crossing_diversity_probe.py` completes the next fixed-recipe test. Three newly +reviewed crossings on Sretenka, Mira44–64 and Smolensk extend the same nine-window +training set to twelve. The fourth candidate was rejected before fitting because +its draft did not provide reliable gap negatives. All existing inputs and labels +remain unchanged; assistant-reviewed new targets add 18,278 paint and 23,914 +background pixels. The Sretenka crop overlaps an existing train crop by 25%; these +are not twelve independent observations. Additional datasets pin the same raw +render/config/request and unchanged annotation revision, with their own immutable +dataset manifests. Supervision SHA: +`d0fc1bb658eb2b3d066cf153ba01475987e7dbb1dc8095e0419598aae039120d`. + +The same frozen representation, linear head and recipe reproduce the previous +dense baseline exactly. P1 exposed gap-diagnostic FPR improves 100% → 37.461%, +with all 2,885 reviewed paint pixels retained. Qualification still fails: original +Pokrovka recall falls 100% → 91.641% (379 newly missed pixels, all at P2); Sadovaya +background FPR rises 0.527% → 1.247%. Pokrovka background FPR improves 2.489% → +0.888%. Full-frame review confirms cleaner P1 gaps, new holes in worn P2 stripes, +and expanded false paint on the SK2 manhole. Training crossings improve strongly, +but training results are reported separately and are not evidence of transfer. + +Thus these additions alone do not satisfy the fixed acceptance criterion. This +neither proves that larger datasets generally degrade accuracy nor identifies a +fundamental representation limit. Retain reviewed data independently of model +promotion. Next isolate general nonlinear-head capacity on the unchanged dataset; +do not retune thresholds or add street-specific repairs. An unused physical street +and independent review remain prerequisites for a blind/generalization claim. +Nine focused tests and Ruff pass. No live maps or deployed model changed. Worker +retains raw observations and learned parameters; Mac retains compact text and two +visually checked proof images. Exact results, limitations, source identities and +verified archive/cleanup receipts are in +`outputs/semantic-crossing-diversity-20261023/report.txt` and `closeout-receipt.json`. + +## Fixed-data nonlinear head experiment — 2026-10-23 + +`nonlinear_head_probe.py` compares the last twelve-window linear head with a +256→32 tanh→1 MLP under three predefined initializations. All seventeen frozen +feature/target files reproduce byte-for-byte; the same supervision release, +training sample selection, normalization, weighting and threshold are reused. +The linear weights and all control counts reproduce exactly. Every MLP converges +before evaluation; no seed is selected using control results. Nonlinear inference +interpolates features before applying the head, matching native-pixel fitting; +bounded-chunk and full-resolution predictions agree in a separate integration check. + +All three seeds fail the predefined capacity gate. P1 gap FPR worsens 37.461% → +44.883–45.127%, while P2 worn-stripe recall improves 79.840% → 85.106–85.266%. +Original Pokrovka FPR rises 0.888% → 1.015%; Sadovaya FPR only slightly improves +1.247% → 1.223%. Historical regressions remain. Full visual comparisons show all +seeds and all five controls. Training-only weighted data loss improves slightly, +so the specified fit completes and learns training labels, but does not improve +transfer consistently. This rejects the tested MLP/recipe, not every possible +nonlinear head or representation; identical numeric L2 does not imply equivalent +regularization across parameterizations. + +No model/map is published. Twelve focused tests and Ruff pass, plus Worker native +inference checks. Existing reviewed data remains immutable and learned parameters +remain Worker-only. Next establish development validation by withholding whole +training physical streets, then isolate detail-preserving frozen features; current +exposed controls must not become the parameter-selection set. An unexposed street +and independent label review remain necessary for final generalization claims. +Exact results and verified retention receipts: +`outputs/semantic-nonlinear-20261023/report.txt` and `closeout-receipt.json`. + +## Physical-street development selection and feature ablation — 2026-10-23 + +`street_holdout_probe.py` adds grouped development folds without rewriting the +immutable supervision partitions. Every fold excludes one complete TRAIN physical +street from sampling, weighted normalization and fitting; exposed regression streets +cannot participate in selection. Twelve predefined feature/head/regularization +recipes complete all 48 fits over four streets. Features are frozen semantic256, +early encoder192 and concatenated448 channels at the same 128x128 resolution; +heads are linear L2 .001/.01/.1 or tanh32 MLP .01. All original seventeen feature +and target files reproduce byte-for-byte before adding the early feature channels. + +No alternative passes the frozen selection criterion: strictly lower mean street +balanced error and no greater worst-street balanced error than the reference. +Semantic linear L2 .1 lowers mean BER .6577% to .5970%, but raises worst-street BER +1.3561% to1.6579%; Sretenka FPR rises .6481% to2.0091%. All early/combined feature +recipes have worse mean BER. This closes the specified comparison negatively; +it is not a representation impossibility claim or evidence that more data is harmful. + +Only the retained reference is refit for final evaluation. Its parameters and all +five control counts plus the P1 diagnostic exactly reproduce the prior experiment. +P1 still fills37.4607% of reviewed gaps. No model is promoted and no live map changes. +Full-frame visual review covers all12 out-of-fold development frames and all5 +controls. Sparse reviewed coverage remains a material limitation: possible missing +worn upper SR4 crossing stripes lie outside existing scored runs. Unknown pixels +remain255; visual suspicions are not silently converted into scored labels. + +The next package pins six TRAIN-only input references for complete-ROI review, +including crossing interiors/gaps, worn strokes and paint-like utility covers. +It is a review queue, not new supervision. A subsequent spatial-decoder experiment +must be separately preregistered after annotation review, preserve the street +isolation and worst-street gate, and retain a genuinely unused independently +reviewed street before any generalization claim. The present corpus has no such +blind gold. Fifteen focused tests, Ruff and Worker native/chunk equivalence pass. +Exact results and retention evidence are in +`outputs/semantic-loso-features-20261023/report.txt`, `verification.json` and +`closeout-receipt.json`; learned parameters remain Worker-only. + + +## Expanded coverage and spatial residual experiment — 2026-10-23 + +`spatial_decoder_probe.py` completes a fixed comparison after visual review of six +TRAIN-only regions. The new immutable supervision release preserves every old +label and all control targets, expanding reviewed paint from 47,629 to 75,719 +pixels and background from 401,281 to 529,599. Uncertain margins stay unknown; +these are assistant-reviewed labels, not independent human gold. A misplaced SR1 +draft was corrected before admission. Release SHA: +`488c9717476554783c119509719df2fec9013775eb18393265e0ce2b0fbebae4`. + +The original seventeen frozen feature/old-target files reproduce exactly. The +original pretrained representation stays frozen. New 1x1 and 3x3 residual heads +are trained over it, using the same base linear logits, class/street/window-balanced +loss, three predefined seeds and 300 steps. Their parameter counts differ, so +this is not a perfect capacity-isolated spatial comparison. Whole-street development +completes 32 fits: old/new linear references plus both residual families. All arms +are evaluated on the same expanded held-out labels; these BER figures must not +be compared directly with the preceding experiment's sparser coverage. + +Only new-linear passes the fixed development gate: mean street BER 1.2138% to +1.0589%, worst street 3.6085% to 3.4717%. Every spatial seed has worse mean and +worst error than the old reference, although it improves on the matched pointwise +head. Final evaluation occurs after selection is frozen. New-linear fails the +exposed regression gate: Pokrovka recall 91.6409% to 64.8655%, despite FP falling +168 to 56. P1 gap FPR improves 37.4607% to 30.6846%; Sadovaya FP falls 679 to zero. +The worn P2 stripes account for the recall loss. No model is promoted or live map +changed. This closes the specified recipes negatively, not all spatial learning. + +Posthoc score diagnosis also closes the threshold-only shortcut for this fixed +candidate. Preserving old Pokrovka recall requires sigmoid-score threshold at +most .118653; improving P1 gap FP requires a threshold above .448360. The exact +sorted-score bounds have no intersection, so one global threshold or monotonic +scalar recalibration cannot meet these gates. No threshold is changed or selected; +this diagnosis uses exposed controls and is not blind evidence. + +All six annotation overlays, twelve full development frames and five full control +frames were visually inspected. Seventeen focused tests and Ruff pass; Worker +integration verifies zero-residual equivalence, finite synthetic fitting, zero +unknown-pixel weight and actual neighbor dependence of the 3x3 head. Source, +protocol, admission, model states and nine original datasets pass hash verification. +Three compact proof images and reports are retained locally; real learned weights +remain Worker-only. The inventoried 34 derived NPZ files and synthetic toy state +are removed only after verified text archival; real models and admitted data stay. + +The next prepared hypothesis adapts the pretrained pixel representation/decoder +itself, initially freezing the backbone. First audit native/resampled scale +provenance and reserve unused independently reviewed street evidence. It must +separate representation changes from coverage and threshold changes, retain +whole-street validation and not tune against these exposed controls. No claim of +100-scan accuracy or scale readiness follows from this small corpus. Exact results, +visual audit, source identities and retention receipts are in +`outputs/semantic-spatial-20261023/report.txt`, `verification.json` and +`closeout-receipt.json`. Global learning remains open; Worker power-off is deferred +to its natural completion under the owner's instruction. + + +## Pretrained FPN adaptation and transfer-gate audit — 2026-10-23 + +`decoder_adaptation_probe.py` completes the next fixed experiment on unchanged +supervision `488c9717476554783c119509719df2fec9013775eb18393265e0ce2b0fbebae4`. +The scale audit exactly reconstructs all fourteen legacy crops: a 240-wide window +in the 1200 coordinate reference maps to approximately 819.2 native pixels in the +4096 render, then downsamples to 512. It is not a native 240-pixel image enlarged +to 512. All seventeen windows cover twelve metres; all model inputs are 512 square. +No labels or source images change. + +This adapts the installed high-resolution FPN Conv3x3/GroupNorm and mask projection, +plus a linear paint head (656,385 parameters); a matched optimizer control trains +only the head (257 parameters). Backbone, lateral fusion and deformable attention +remain frozen. Three predefined seeds, 120 fixed updates, seeded C4 augmentation, +class/street/window-balanced native-pixel loss and train-only normalization are +shared. Inference averages inverse-aligned C4 features. BF16 inputs are cached as +exact uint16 bits; an initial FP16 roundtrip precision loss was caught before +training. All seventeen original feature/target caches and zero-change masks +reproduce exactly. No parameter or epoch search is conducted. + +All 32 whole-street development fits complete. Every decoder seed improves mean +BER (1.0589% reference to 1.0066–1.0272%) and worst-street BER (3.4717% to +3.2520–3.3757%) versus the new-label linear model and the paired head-only control. +Five final models are frozen before exposed controls: old/new linear and all three +decoder seeds. P1 gap FPR improves from 30.6846% to 6.9508–7.3524%, retaining all +2,885 reviewed paint pixels. However Pokrovka recall falls from 64.8655% to +59.2413–62.4393% (old sparse-label reference 91.6409%). All three fail qualification. +Sadovaya reviewed background stays clear. No model/map is promoted. + +Visual review covers all twelve development frames and all five controls; worn +SR4/P2 losses and P1/SR1 gap gains are visible. All 87 predictions reproduce exactly +after loading the 27 saved neural checkpoints. Twenty-one focused tests and Ruff +pass. Exact scale, source/config/runtime/model identities, two proof JPEGs and +verified text archive/cleanup receipts accompany +`outputs/semantic-decoder-20261023/report.txt`. + +The posthoc `transfer_gates.py` audit identifies a weakness in the composite +selection metric: Sretenka recall already falls 96.9774% to 95.9343–96.2188%, +compensated in BER by fewer false positives. The helper checks recall and FPR +separately per physical held-out group, with leakage/support checks. It does not +rewrite this experiment's frozen choice. Future protocols must state separate +component gates before fitting. The next prepared comparison completes the missing +old-supervision/adapted-decoder cell, keeping all held-out targets identical to +separate coverage effects from representation changes. It has not been executed. + +Metadata-only candidates Mira2–24 and Sadovaya-Triumfalnaya are related corridors; +neither source IDs nor folder names establish independent physical streets. +Their pixels are not opened for this experiment. Physical separation and independent +label review remain required before any blind or production/generalization claim. +The bounded probe loads seventeen records and is not a production 100-scan trainer. +The global learning task remains open; Worker shutdown remains deferred. + +### Coverage × pretrained-tail factorial, 2026-10-23 + +Completed `semantic-coverage-20261023`: 33 new neural fits (24 whole-street +old-supervision development fits and nine missing final diagnostic fits), with +27 unchanged parent neural states reused and both linear references exactly +reproduced. Expanded held-out targets, four physical-street folds, three seeds, +120-step recipe and threshold were fixed. The comparison includes matched +head-only optimizer controls for both supervision releases. Exposed controls +were diagnostic for every preregistered arm, never a recipe/seed selector. + +No family passed the preregistered separate per-street recall/FPR guards plus +mean/worst BER. On Pokrovka, old-label FPN adaptation reduced recall from the +old-linear reference 91.64% to 71.68–76.51%; expanded-label adaptation yielded +59.24–62.44%. Both reduced P1 gap false positives from 37.46% to roughly7–8% +while retaining all reviewed P1 paint. Expanded-label models removed reviewed +Sadovaya false positives; old-label models retained them. Thus reverting label +coverage does not resolve weak-paint loss. This isolates a supervision-recipe +effect and an additional adaptation effect, not the causal contribution of +individual added labels: normalization, initialization and loss weighting also +depend on the training release. No full-model/convergence/scaling claim. + +Reusable offline `coverage_factorial.py` enforces train-only label views, +paired complete street folds, all-seed component guards and descriptive paired +effects; 12 focused checks and Ruff passed. All17 full frames were inspected +with raw/label overlays and worst-pixel envelopes across all seeds. All238 +predictions (204 neural) replayed exactly from frozen models. No live map, +annotation or production model changed. Two bounded proof JPEGs and compact +reports reside in `outputs/semantic-coverage-20261023`; learned parameters remain +Worker006-only. Closeout receipt links the verified text archive and inventories +only this experiment's34 disposable NPZ files. The next bounded hypothesis is +coverage-preserving training-example balance, preceded by a TRAIN-only audit +of worn paint and difficult background; independent physical-street gold is +still required before promotion. + + +### Annotation-cohort loss balance, 2026-10-23 + +Completed `semantic-balance-20261023`: the only training change is equal old/added +reviewed-pixel mass inside each class/street/window, preserving all outer mass. +The expanded labels, initialization, normalization, update count and inference +threshold stay fixed. A before-training visual audit establishes that annotation +age is not paint condition; old pixels are not universally upweighted. A real +default-mode retraining exactly matches all original parameters and recorded loss +values, separating the policy change from a training-engine regression. + +Thirty new neural models (24 whole-street development, six final diagnostic) +complete, with 30 unchanged neural states reused. No balanced family passes the +preregistered all-seed component guards. Mean street BER for balanced adaptation +is 1.0068–1.0340%, versus 1.0066–1.0272% for uniform adaptation. Exposed Pokrovka +recall is 59.06–61.62% versus 59.24–62.44%; weak P2 paint recall is only +1.28–7.45% (24–140 of 1,880 pixels) versus 1.70–9.41%. P1-gap FPR remains about +7%, with all reviewed P1 paint retained. Reviewed Sadovaya background stays clear. +The fixed equal-cohort policy does not solve the weak-paint tradeoff; this is not +a rejection of every possible weighting policy or proof of the ultimate cause. + +All17 full frames, original P1 and its gap diagnostic, and all-three-seed worst +pixel envelopes were visually reviewed. All238 predictions (204 neural) replay +exactly; 16 focused tests and Ruff pass. `verify_gate.py` recomputes the frozen +numerical choice in the pinned container; `verify_worker_v2.py` validates its +receipt on the NumPy-free host without changing frozen training files. Two bounded +proof JPEGs, model/data/source identities, report and archive/cleanup receipts are +in `outputs/semantic-balance-20261023`. No live map, annotation or model changes. + +The prepared next step is a versioned TRAIN-only condition/support inventory +from raw imagery: visible weak paint, clear paint, ambiguous evidence and nuisance +background, distributed by physical street and marking type. Annotation history +cannot replace these attributes. Missing coverage must be reviewed and admitted +as a separate release; the paired comparison must isolate coverage from weights. +Exposed controls remain excluded from training. Independent physically disjoint +human-reviewed evidence is still required before promotion or generalization +claims. No claim about100-scan scaling is made; global learning remains open. + + +### TRAIN-only visual-condition inventory, 2026-10-23 + +Completed `semantic-condition-20261023`: all12 existing TRAIN windows and six +prescribed adjacent candidates were visually inspected, with all42 condition +regions and their overlays checked. The frozen sidecar binds the original +supervision, image/camera identities, source, review, tests and two proof JPEGs. +No control pixels were opened and no model or live map changed. + +`condition_inventory.py` selects only existing class-compatible reviewed pixels; +it rejects non-TRAIN records, missing/mismatched target pins, conflicting condition +pixels and invalid review polygons. Candidates remain all255. Fourteen focused +tests and Ruff pass. The audit is an assistant review of previously exposed +development imagery, not independent blind human ground truth. + +Of75,719 original paint pixels,72,805 are typed clear,2,233 weak-visible,681 untyped. +All weak-visible support is one crossing stripe on Sretenka. Native resolutions +differ, so2.949% is a descriptive pixel count, not physical area or training-loss +mass. Visible unlabelled weak fragments are queued on four TRAIN streets: M1, +MI3, SR2 and SM3-adj2. Candidate regions are not admitted pixel masks. Additional +background candidates have a separate queue to avoid confounding that comparison. + +Camera-footprint checks expose25% overlap between SR2/SR4 and41.67% between +SR2/SR4-adj1; the latter repeats the same weak line and is not new independent +support. Use the SR2 view for that object's future admission. All candidates +retain their physical-street groups. Lower blurred/occluded candidate regions +remain unknown rather than becoming negative road examples. + +The terminal audit result is insufficient weak-visible support, not proof of +causality or a model gain. The next prepared coverage comparison changes only +separately admitted visible weak fragments while holding training architecture +and recipe fixed; condition weighting is a distinct hypothesis. Independent +physically disjoint human-reviewed evidence remains required before promotion. +Reproduction, portable-store verification and bounded retention receipts accompany +`outputs/semantic-condition-20261023/report.txt`. No features/checkpoints/raw-media +exports were created; only two proof JPEGs are retained. Global learning remains +open and Worker006 power-off remains deferred to its requested endpoint. + + +### Visible weak-paint coverage experiment, 2026-10-23 + +Completed `semantic-weak-20261023`: a separate portable release adds955 reviewed +source-visible paint-interior pixels on four TRAIN streets, no background and no +changes to old known labels or exposed controls. One accepted512 observation stays +in the Worker006 store. Thirteen TRAIN windows, four whole-street folds and three +fixed seeds use the existing FPN-tail/head recipe, exact parent initialization and +normalization. Twelve development and three final models are trained;15 actual +parent states are reused. No production or live annotation changes. + +Every seed fails the preregistered component guards. Mean held-street weak recall +gains16.92–18.74 percentage points, mainly M1 and the old SR4 weak stripe. Mira +and SR2 additions were already recognized; Smolensk weak recall remains zero. +Sretenka reviewed-background FPR increases2.675–2.754% to9.077–9.720%, visibly +filling gaps in SR1. Exposed P2 recall improves1.70–9.41% to28.99–42.66%, but its +background gains35–69 false pixels. P1 gap FPR increases and SK2 gains6–10 false +pixels. This fixed coverage/recipe combination is rejected, not all data growth. + +The unchanged equal-class/street/window formula redistributes actual mass: +140 positive pixels in the new Smolensk window receive half that street's positive +mass (6.25% of total final loss). Old foreground weights and stochastic order thus +change even though the policy does not. `weight-audit.json` quantifies every fold; +no pure per-pixel causal attribution is claimed. The prepared next experiment +separates coverage from mass redistribution with a common per-sample augmentation +schedule, before separately testing hard-background admission. No location-specific +thresholds, normative completion or100-scan generalization claims are introduced. + +All18 complete frames and all-three-seed error envelopes are visually reviewed, +with two bounded proof JPEGs;108 predictions replay exactly.29 focused tests and +Ruff pass. An initial missing dependency was repaired before training; an ignored- +pixel comparison bug was repaired after six fits without changing their states. +Original/repaired runners and receipts remain pinned. Verification and hash-verified +text archive/derived-cache cleanup receipts accompany +`outputs/semantic-weak-20261023/report.txt`. Accepted data,15 learned states and +pretrained tail remain in the portable store. Independent human-reviewed physical +streets are still required for promotion. Global learning and deferred Worker006 +shutdown remain open. + + +### Paired coverage/mass experiment and annotation-defect finding, 2026-10-24 + +Completed `semantic-mass-20261024`: 47 real fits (36 development, nine exposed-control +final models, two identity checks). The three arms use the same sample-ID order, +hash-derived per-sample/update rotations, parent initialization, normalization, +120 updates and threshold. Base uses old labels; equal-window and pixel-mass arms +use the exact955 accepted weak-paint additions. The mass arm keeps each street's +foreground total fixed, scales old weights by Nold/(Nold+Nadd), and assigns each +added pixel Mstreet/(Nold+Nadd); background weights do not change. This is native +pixel counting, not physical area or a qualified repeated-admission rule. + +Both added-label arms fail all three preregistered seed-wise component guards. +Mean held-street weak recall gains17.42–18.38pp with equal windows,7.46–7.85pp +with mass. Sretenka label-conflict FPR is2.727–2.761% for paired base, +9.600–9.703% for equal windows,4.933–4.975% for mass. Mass preserves clear-paint +recall but increases numerical background conflicts on every development street. +Smolensk weak paint remains absent for base/mass; equal windows finds only five +of140 pixels in one seed. Exposed P2 recall rises9.95–16.81% to18.03–23.14% +with mass, retaining zero P2 background conflicts; equal windows reaches +33.40–42.82% with53–70 conflicts. Sadovaya stays clear for base/mass; equal +windows produces13–15 conflicts. This controlled baseline differs from the +previous experiment; do not mix their unpaired ranges. + +Native-resolution visual inspection confirmed two annotation defects: the lower +background polygon of the separate P1-gap diagnostic overlaps visible white +paint, and the accepted P3 background rectangle overlaps the continuing line. +These exposed-control targets do not train models. Their FPR, and aggregated +Pokrovka FPR containing P3, mix annotation and model error. Prior numerical +reports using the same target hashes remain reproducible but require this +qualification; earlier roughly7% P1-gap FPR is not clean model-only evidence. +Frozen labels/results were not edited and no model was reranked or promoted. +These defects do not establish that all observed failures are annotation errors. +SR1/SR4 blurred boundaries also need systematic review. + +Next: raw-first native-resolution audit of all18 observation targets plus P1-gap, +including all accepted components rather than only prediction disagreements; +versioned evidence-backed corrections, uncertain boundaries kept unknown, +independent review for disputed regions; then reevaluate all retained paired +models on original and corrected labels without retuning. Exposed controls remain +exposed. Separate TRAIN-only hard-background admission is deferred until this +measurement audit; independent physical-street gold remains required for promotion. + +All18 full frames and three-seed envelopes were reviewed, with two bounded proof +JPEGs and explicit defect receipts. Default and zero-add real fits reproduce +parameters and loss traces exactly; all162 predictions replay exactly. +28 focused tests and Ruff pass. Reports, source/data pins, verification and +verified text-archive/36-NPZ cleanup receipts reside under +`outputs/semantic-mass-20261024`. Forty-five principal and two identity states +remain in the portable Worker006 store. No live map, production model or accepted +annotation changed. No convergence or100-scan scaling claim; global learning +remains open. + + +### Annotation-boundary audit with frozen-model replay, 2026-10-24 + +Completed `semantic-boundary-20261024`: raw-first native/zoom review of all119 +components in18 observation targets plus the separate P1-gap diagnostic. Frozen +before inference, explicit withdrawals only change known0/1 to unknown255. A new +evaluation-only supervision release preserves all input bindings, contextual-map +geometry and split roles; the parent release and live map remain unchanged. +The general `annotation_boundary_review.py` checks raw/target/component pins, +review coverage, bounded polygons and provenance;13 focused tests and Ruff pass. + +Five ordinary masks and P1-gap change. M1 withdraws1274 paint/2011 background, +SR4 withdraws606 background, SR1 2507, P2 425, P3 329, P1-gap672. Main18 targets +retain79934 paint/597096 background pixels. All955 weak-paint additions remain, +including all140 difficult SM3-adj2 pixels. Clear foreground and background +boundaries were both audited; no prediction-derived mask, new label, automatic +background or normative road completion was introduced. This assistant review +of previously exposed imagery is not independent human gold. + +All45 principal states were reevaluated without fitting or retuning. All162 +predictions,18 feature NPZ and18 prediction NPZ reproduce the parent exactly; +old confusion counts reproduce, and old=new+withdrawn contributions holds. +P2's53–70 old equal-window background conflicts all lie in the withdrawn corner +on visible paint. Pokrovka now has zero retained-background conflicts for base +and mass, two per seed for equal-window. P1-gap base FPR changes7.30–7.47% to +0.257–0.317%; this is correction of measurement, not improvement of predictions. +Historical metrics using these same target hashes need that qualification. + +Remaining Sretenka FPR is0.854–0.869% base,3.722–3.814% equal-window,1.221–1.248% +mass. A large inter-stripe fill persists visually for equal-window; small blurred +edge conflicts still need independent adjudication. Weak recall is unchanged: +SM3-adj2 is0/140 for base/mass and0/5/0 for equal-window. P2 retains substantial +missed paint; Sadovaya retains13–15 equal-window false pixels. Both added-label +policies still fail all three seeds' original component guards. No model promoted. + +The finite audit closes with a qualified negative recipe result and a new mask +candidate. Next design: separately admit corrected TRAIN targets, then compare +old/corrected-label fits under the same three policies, whole-street folds, +common schedule and seeds. Recompute weight accounting because withdrawal changes +denominators. No corrected regression/P1-gap label may enter fitting; hard- +background admission remains a separate later hypothesis. Exposed controls cannot +substitute for independently reviewed physically disjoint promotion evidence. + +Seven key areas were visually rechecked against three-policy/three-seed prediction +error envelopes after inference; labels stayed frozen. Compact reports, two mask +proof JPEGs, source/data/model identities, verification and hash-verified text +archive/36-NPZ cleanup receipts reside under `outputs/semantic-boundary-20261024`. +New evaluation-only labels and all47 parent states remain in the Worker006 store. +Global learning and the owner's deferred Worker006 shutdown remain open. + + +### Corrected-TRAIN paired retraining, 2026-10-24 + +Completed `semantic-retrain-20261024`: a separate13-observation TRAIN-only release +admits the previously frozen boundary withdrawals (1274 paint/5124 background), +keeping all955 weak-paint additions. Regression/P1-gap masks only score models. +The general `annotation_training_view.py` validates TRAIN role, aligned labels, +withdrawal-only transitions, cohort preservation and immutable input;12 focused +tests and Ruff pass. Live annotations and the production viewer are unchanged. + +Thirty-six whole-street development fits and nine final fits use the same three +policies, three seeds,120 updates, parent initialization/normalization, paired +sample/augmentation schedules and threshold as45 retained parent models. Initial +linear-head fitting is intentionally not repeated; this tests supervision during +fixed tail/head fine-tuning. All final states freeze before exposed-control scoring. +Old/new models score the same corrected labels, with original-mask counts retained. + +All three correction-vs-old guards and both added-label-policy guards fail. +Mass improves mean held-street weak recall5.25–6.30pp; Maroseyka49.44–53.44% becomes +68.96–71.36%. Smolensk still finds only4/10/2 of140 weak pixels. Sretenka FPR rises +1.221–1.248% to1.283–1.306% for mass and3.722–3.814% to4.350–4.384% for equal-window; +inter-stripe fill persists visually. Exposed P2 recall improves18.03–23.14% to +22.66–25.96% for mass with zero retained-background conflicts. Sadovaya equal-window +false pixels increase13–15 to36–47; base/mass remain zero on reviewed background. +Zero partial-mask FPR does not establish clean predictions on unknown full-frame +areas. No model is selected or promoted. + +Class/street mass stays fixed but withdrawal changes pixel denominators. All-TRAIN +added-positive mass changes0.07375842 to0.07902268 for equal-window and0.005664787 to +0.005782259 for mass. Per-fold/window accounting is retained; no pure per-pixel +causal attribution or physical-area/100-scan generalization claim is made. + +All18 full frames and all-three-policy/seed envelopes are viewed at512 display +width, with enlarged M1, SM3-adj2, P2 and SR1 crops. Two proof JPEGs show gains and +failures. All324 repeated predictions match exactly; old18 prediction NPZ reproduce +byte-exactly.45 new states plus47 parent states (including two identity checks) +remain on Worker006. Verification, content-addressed text archive and scoped36-NPZ +cleanup receipts accompany `outputs/semantic-retrain-20261024/report.txt`. + +This fixed recipe closes negatively despite useful gains. Prepared next hypothesis: +TRAIN-only source-reviewed hard-background interiors, paired no-add/add comparison +with fixed recipe and explicit mass accounting; no control mining or location rules. +Independent human-reviewed physically disjoint gold is still required for promotion. +Global learning remains open; the owner's endpoint Worker006 shutdown stays deferred. + +### Hard-background admission, 2026-10-24 + +Completed the fixed paired experiment `semantic-background-20261024`. A new +TRAIN-only release adds37478 background pixels in14 source-reviewed regions of +nine existing windows across four physical streets. All13 TRAIN observations, +955 previous weak-positive additions, existing known labels and protected +withdrawals are preserved. Only unknown255→background0 is admitted. Most crossing +gaps were already labelled; only711 newly admitted pixels are crossing-gap +interiors. Objects/paving/covers and the unpainted A hole supply the other regions. +No regression/P1-gap annotation enters fitting, and live maps remain unchanged. + +The reusable `background_admission.py` validates TRAIN role, source/target/protected +hashes and legal transitions, then redistributes each window's existing negative +weight mass over its old and new background. Positive weights stay byte-exact; +maximum observed per-window float32 background-mass rounding difference is +2.57e-9. This is an explicit fixed-weight intervention, not location-specific +inference. The optional decoder integration leaves the no-policy API unchanged. +Two real identity fits reproduce parameters and loss traces exactly;45 focused +checks, Ruff and seven synthetic acceptance-gate cases pass. + +Thirty-six whole-street development fits and nine final fits are paired with45 +retained models from the corrected-TRAIN experiment: same three policies/seeds, +initialization, sample schedule,120 updates and threshold. Final models freeze +before exposed-control scoring. All324 old/new predictions replay exactly. +All three policies fail their preregistered non-regression guards: background +false paint decreases in every held street/seed, but weak paint regresses on +Maroseyka and partly Sretenka. For mass, Maroseyka weak recall68.96–71.36% falls to +64.32–68.00%; Sretenka original-background FPR1.283–1.306% falls to1.038–1.049%. +Equal-window Sretenka FPR4.350–4.384% falls to2.826–2.925%, but Maroseyka weak +recall loses1.12–1.60pp; one control P1-gap repeat grows47→49 false pixels. +P2 improves modestly, while substantial weak-paint misses remain. No promotion. + +All18 full frames were inspected across three policies/three-seed envelopes at +512 display width, plus seven enlarged native crops. Planter/curb errors shrink, +but SR1 bridging, M4 symbol-hole fill and SM3-adj2 weak misses persist. Unknown +pixels are shown visually but never counted as negative ground truth. Two saved +proof JPEGs separately show background gains and paint tradeoffs; both inspected. +The fixed recipe closes negatively. It does not establish architecture failure or +100-scan generalization. Assistant-reviewed sparse labels and repeatedly exposed +controls do not replace independent human-reviewed physically disjoint gold. + +Prepared next diagnosis: frozen old/new score ranking at matched false-positive +counts, with complete per-street/per-seed reporting and separate old/new-label +support. Curve-derived oracle thresholds are descriptive only. Any later global +calibration must be nested entirely within TRAIN, never selected from evaluated +streets or exposed controls. No new model/label/threshold search is authorized by +the diagnostic itself; retain the fixed experimental scope. + +Evidence: `outputs/semantic-background-20261024/report.txt`, `visual-review.json`, +`paired-summary.json`, `next-step.json` and verification/closeout receipts. All47 +new states (45principal+2identity),45 parent and47 ancestor states remain in the +Worker006 portable store. Closeout archives verified text before scoped retirement +of36 disposable NPZ. Global learning and endpoint Worker006 shutdown remain open. + + +### Frozen-score ranking diagnosis, 2026-10-24 + +Completed `semantic-score-20261024` without new fitting, labels or deployment. +The reusable `score_diagnostic.py` computes exact tied-score curves, separate +original/added-background budgets, noninterpolated AP and ROC AUC.16 focused +tests and Ruff pass. All324 continuous-score predictions from90 retained states +replay exactly; threshold0 reproduces all18 parent binary NPZ byte-for-byte. + +For both old and new models, the diagnostic chooses the lowest score threshold +respecting each old fixed0 false-positive budget. These are evaluation-label +oracle thresholds: optimistic ranking diagnostics, never deployable calibration. +New oracle is compared against old oracle. Equal-window alone passes the +preregistered weak/clear/original non-regression guards in every held street and +seed, with macro weak-recall gain0.7489–0.9460pp. Base fails one seed; mass fails +all three due to Maroseyka. Weak AP increases in all36 paired comparisons. +This rejects a pure uniform score shift as the complete explanation; it does +not establish a transferable operating threshold or production accuracy. + +The effect remains small: Smolensk weak detection improves16/20/16→20/25/19 of140 +pixels. Oracle thresholds also restore some false curb/paving detections outside +reviewed masks. All18 full frames across three policies/seeds and native crops +M1,SM3-adj2,SR1,P2,M4 were inspected; two saved proof JPEGs were viewed. SR1 gap +bridging, M4 A-hole fill and extensive SM3-adj2/P2 misses persist. + +A post-hoc descriptive window audit, without threshold or label changes, exactly +reproduces1296 aggregate counts. Street budgets conceal local relocation: +equal-window original-background errors increase in M1,MI3,MI2,SR4 in every seed +(12 cases), while other windows improve. For example seed20261023 M1 rises93→115 +and MI3 rises178→251. SR1 window totals decrease but the wrong shape remains. +This audit is separately labelled and does not replace the preregistered gate. + +No model is selected for production. The next bounded hypothesis uses TRAIN-only +nested whole-street calibration: inner models fit on two of the three permitted +streets, including initial linear head and normalization; one scalar threshold +is selected on inner held-out predictions and transferred unchanged to the outer +street. Both model families receive equal calibration opportunity. Reusing an +initialization exposed to an excluded street is forbidden. Existing outer models +require a provenance audit before reuse. No per-location inference rules or +control-derived thresholds are admitted. Failure closes this recipe as +insufficient; further threshold patches are not the fallback. Current development +streets and repeatedly exposed controls cannot replace independently reviewed, +physically disjoint promotion evidence or full-frame error coverage. + +Evidence: `outputs/semantic-score-20261024/report.txt`, `paired-summary.json`, +`window-metrics.json`, `visual-review.json`, `next-step.json` and verification/ +closeout receipts. The fixed requested threshold is0; `fixed.*.threshold` in raw +curve output is only an equivalent observed-score representative on reviewed +support. All139 parent/ancestor states and source datasets/releases are retained. +Closeout verifies a content-addressed text archive before retiring only36 owned +feature/score NPZ. Global learning and endpoint Worker006 shutdown remain open. + +### Nested TRAIN-only threshold transfer, 2026-10-24 + +Completed `semantic-calibration-20261024`. Equal-window old/new families receive +one scalar threshold each, fitted only on inner held-street predictions from the +three allowed TRAIN streets and transferred unchanged to the excluded fourth. +Separate old-fixed0 false-background budgets apply to each inner street and each +original/added-background cohort. Initial linear heads and normalization exclude +both held streets; four outer initializations reproduce exactly before reuse of +24 retained outer models. The historical dense-label initialization recipe is +explicitly retained, preceding later withdrawals/weak additions on allowed streets. + +Seventy-two inner roles deduplicate to36 paired fits by unordered training pair, +family and seed under a frozen stable sample-ID schedule; two additional identity +fits reproduce tensors, losses and schedule. Twelve focused calibration tests +plus16 score-diagnostic tests and Ruff pass. All432 continuous prediction maps +replay exactly. No new labels, live annotations or production model changes. + +Transfer is partial but insufficient as a standalone recipe. Pooled reviewed +background false pixels fall4968→3853,4911→3773,4945→3952 (20.08–23.17%). Macro +held-street weak-recall gains are0.4157/0.4957/0.2292pp; pooled weak counts change +2995→2995,3008→3010,2999→3002. The preregistered primary fails two of three seeds: +Maroseyka weak counts lose3/1 of625; Sretenka clear/original counts lose1/2 pixels. +Seven window/seed original-background increases (M1 three,MI3 three,SR4 one) veto +any blanket non-regression claim, including the third seed that passes primary. + +All18 full frames and six native crops were inspected, with all3 seed envelopes +and all4 outer systems on5 exposed controls. SR1 gap fill shrinks but persists; +M4 A-hole fill, extensive SM3-adj2 weak misses and SK1 false curb/planter contours +remain. P2 recall and P1 gap shape depend strongly on training composition. P1's +separate reviewed gap cohort worsens in9/12 systems. That cohort is not the full +frame display mask; yellow gap fill cannot be read as true paint. Sparse-mask +zero FP does not establish clean full-frame output. Two saved proof JPEGs show +both improvements and unresolved failures, including contrasting P1 systems. + +Close the fixed hard-background-plus-scalar-calibration hypothesis as insufficient; +no further location-specific threshold patches. Prepared next bounded experiment: +frozen parent, matched coarse-only residual, identical native-RGB residual; +zero-output initialization, fixed0 threshold, paired street folds/seeds and class +mass. This tests fine-detail information against added capacity, not a claim that +resolution is already proven causal. PointRend and DeepLabv3+ motivate the general +fine/coarse-feature principle; the proposed small residual probe is not a full +reproduction. Protocol details and stop criteria are in `next-step.json`; it has +not been run in this stage. Independently human-reviewed physically disjoint gold +and full-frame error coverage remain necessary. Repeatedly developed-on streets +are not an unbiased final test merely because inner calibration excludes them. + +Evidence: `outputs/semantic-calibration-20261024/report.txt`, `paired-summary.json`, +`visual-review.json`, `calibration-frozen.json`, `replay.json`, and verification/ +closeout receipts. All177 states (139 ancestor+36 inner+2 identity),10 source +datasets and supervision releases are retained. Verify content-addressed text +archive before deleting only36 inventoried feature/score NPZ. Global learning +and the owner's endpoint Worker006 power-off request remain open. + +Closeout passed: verified text archive +`f67a1ab34cf07f8932edbb33b6dc9a6d4ab4a7c6acd072e2fa33ff62c8e3bad6` +contains76 paths;36 owned NPZ totaling1,051,837,697 bytes were removed afterward. +Post-closeout reverified all177 states, both proofs,10 dataset manifests and eight +durable running containers. No experiment container remains. Local Core8000 +still listens from the canonical checkout (PID55144). Only two final proof JPEGs +and bounded text were delivered to Mac. + + +### Native RGB residual detail probe, 2026-10-24 + +Completed `semantic-detail-20261024`: frozen parent, matched coarse-only residual, +and native-RGB residual. Both learned arms have2929 parameters, identical paired +initial tensors, class/window mass and sample-ID rotations; four excluded streets +×three seeds×two arms give24 principal fits plus two exact identity repeats. +Parent initialization/normalization/fitting and residual training exclude the +whole evaluated street. Fixed0 threshold,120 AdamW updates, no new labels, +location-specific inference, threshold tuning or production integration. + +The fixed recipe fails both preregistered comparisons in every seed. Macro +held-street weak-recall differences against identity are−0.0587/−0.1386/−0.3386pp; +against coarse-only they are−0.08/0/−0.08pp. Pooled reviewed false-background +counts change3660→3646,3578→3608,3708→3652, concealing local regressions. +Sixteen window/cohort/seed/comparator increase records comprise12 versus identity +and4 versus coarse-only; these are not16 distinct windows. All18 full frames, +all three seed envelopes and all four systems on five exposed controls were +inspected, plus six native crops and both saved proof JPEGs. SR1/P1 gap filling, +M4 A-hole fill, SM3-adj2 weak misses and P2 training-composition sensitivity remain. +False curb/planter predictions outside sparse masks also remain visible. + +Post-hoc sensitivity diagnosis changes no fits, labels or thresholds. All24 +models change weights; all12 RGB fits have nonzero RGB-channel gradients. +Descriptive first-loss to last20-mean reductions are2.39–6.09% for RGB. On missed +SM3-adj2 weak pixels, median parent margins1.69/1.65/1.77 dwarf median absolute +corrections0.065/0.071/0.132. This does not prove convergence or justify multiplying +corrections. Muting RGB at inference is an out-of-distribution sensitivity check, +not causal evidence of RGB value. The matched trained coarse-only arm is the +ablation. The small residual probe is not a reproduction of PointRend/DeepLabv3+. + +Ten tensor tests pass without skips; Ruff passes. Zero-output identity is exact, +and C4/full/tiled behavior is tested. Two real repeated fits reproduce tensors, +losses and schedule exactly. All414 maps replay exactly, including216 parent and +198 learned maps. A missing unchanged score helper was staged before scoring or +fitting; the original prefit freeze is retained as frozen-v1, with the dependency +correction explicit. No outcome-driven recipe change occurred. + +Close this fixed120-step recipe negatively. Prepared, not run: measure exact +C4 TRAIN error for the existing states, then a bounded1200-step replay of the +same optimization, requiring the first120 steps to reproduce exactly. A frozen +TRAIN-only capacity screen determines whether a separate transfer experiment is +warranted; failure ends this tiny residual line without further budget/threshold +patches. This is a trainability diagnostic, not promotion or proof of convergence. +Independent human-reviewed physically disjoint gold and fuller error coverage +remain missing. Repeatedly exposed controls do not become final test evidence. + +Evidence: `outputs/semantic-detail-20261024/report.txt`, `paired-summary.json`, +`diagnostic.json`, `visual-review.json`, `next-step.json` and verification/closeout +receipts. Retain26 new plus177 ancestor states,10 source datasets and supervision +releases on Worker006. Archive verified text before retiring only54 owned NPZ; +only two final proof JPEGs and bounded text are delivered to Mac. Live semantic +maps and the production model remain unchanged. Global learning and endpoint +Worker006 power-off remain open. + +Closeout passed: content-addressed text archive +`38560007f8028a258f1544b699a7e792794a77a8a8412805b7e720a0e23429e2` +contains56 text paths. Only54 inventoried disposable NPZ (1,016,505,961 bytes) +were removed after archive verification. Post-closeout reverified203 states, +both proofs,10 dataset manifests and eight durable containers; no experiment +container remains. Core8000 remains running from the canonical checkout +(PID55144). Mac retains only bounded text and the two final proof JPEGs. + + +### Bounded TRAIN fit-capacity diagnosis, 2026-10-24 + +Completed `semantic-fit-capacity-20261024`: same tiny2929-parameter residuals, +parents, immutable labels, class/window mass, sample-ID rotations, AdamWlr1e-4 +and fixed0 threshold, with1200 rather than120 updates. Four three-street training +compositions×three seeds×two arms produce24 principal states plus two exact +repeats. Every fit exactly reproduces the previous first120 loss values, tensors +and schedule. No best intermediate checkpoint is selected. Only the13 permitted +TRAIN frames are evaluated, never excluded streets or exposed regression controls. + +The preregistered TRAIN capacity screen fails all12 RGB and all12 coarse-only +systems. It requires halved native C4 BCE, weak FN and reviewed-background FP, +with no clear-paint recall loss, versus fixed step120. RGB BCE improves11.93–32.69%; +coarse-only10.85–26.19%. RGB has lower final BCE than coarse-only in every paired +system, but final background FP is worse in aggregate. Repeated TRAIN totals +for RGB change weak FN179→144, background FP18211→17880 and clear FN1380→1328; +coarse-only totals178→156,18305→17488,1375→1335. These repeated evaluations are +not independent pixels or new-street accuracy. Background grows in six RGB +systems, clear FN in six; pooled improvement conceals these tradeoffs. + +All13 full TRAIN frames/all three eligible systems/all three seed envelopes +were visually inspected, with seven enlarged native crops. Overview transmission +was resized to1280px (about213px per variant panel); both final1280px JPEGs were +opened. M4 A-hole fill and SR1 broad contours/end-of-gap error persist. Admitted +SM3-adj2 weak strokes are already detected on TRAIN, but overbroad. MI1 cover, +SM1 scooter and M3 stripe-edge false paint grows in specific systems. SM3-adj2 +outer3 gains an unsubstantiated prediction in a bright unresolved scan region; +it is unreviewed, not a numerical FP or a newly asserted negative label. + +No convergence claim: RGB mean loss over final100 steps still improves0.117–3.107% +against preceding100. The frozen finite budget and conservative engineering +capacity criterion close this recipe, not all RGB architectures or a mathematical +capacity bound. No more small-residual budget/threshold sweeps are prepared. +Next is a bounded learned-feature/coarse-score refinement comparison inspired by +PointRend, with feature provenance/alignment tests and TRAIN fit sanity first; +only a passing fixed TRAIN screen can lead to a separately frozen transfer check. +The current raw5x5 RGB branch is not PointRend. The proposed adaptation is not +claimed as a reproduction of its sampling or published accuracy. Independent +human-reviewed physically disjoint gold and fuller background coverage remain +necessary for promotion; unknown annotations must remain unknown. + +Twenty-four tests pass without skips (10 residual,14 capacity-gate); Ruff passes. +All585 TRAIN score maps and metrics replay exactly:117 parent,234 step120, +234 step1200. Two complete repeated fits exactly match tensors/losses/schedule. +Total fit time including repeats1614.07s; peak allocated GPU memory247722496B. +No user annotations or production model changes. Retain26 new states plus203 +ancestors,10 source datasets and supervision releases. Evidence is under +`outputs/semantic-fit-capacity-20261024`: report.txt, paired-summary.json, +curve-summary.json, visual-review.json, architecture-notes.json, next-step.json, +verification and closeout receipts. Archive verified text before retiring only +39 owned NPZ; deliver only two proof JPEGs and bounded text to Mac. Global +learning and the endpoint Worker006 power-off request remain open. + +Closeout passed: verified content-addressed text archive +`1ad05efec7d52bd7aa651206ae172f3f5fda7a0571b0e4ddae13f471b13db9d9` +contains63 paths. Only39 inventoried NPZ totaling1,099,559,873 bytes were removed +after verification. Post-closeout reverified229 retained states, both proof JPEGs, +10 dataset manifests and eight durable containers. No experiment container +remains. Core8000 still runs from the canonical checkout (PID55144); Mac retains +bounded text and the two final JPEGs only. + +### Feature-aware TRAIN refinement and whole-frame veto, 2026-10-24 + +Completed `semantic-feature-refinement-20261024`. A shared198402-parameter +point-wise MLP receives256 frozen parent FPN channels before scalar score +collapse plus the coarse logit, versus an identical head with fine channels +zeroed. Three256-wide layers concatenate coarse score at each layer; zero +residual initialization preserves the parent. Parent C4 alignment, FP16 rounding, +normalization and whole-street provenance are retained. Features remain128x128 +from512 input (effective stride6 for768-native frames); no new native detail is +claimed. This adapts the PointRend fine/coarse head principle, not its complete +adaptive sampling method. No location coordinates, road-rule templates or new +labels enter the fit. + +Four three-street training compositions x three seeds x two arms produce24 +principal states plus two exact repeats. Fixed1200 AdamW steps atlr0.001 sample +1024 known native pixels per frame with probabilities proportional to existing +weights. Paired indices and initialization are identical; prior class/window +mass is preserved in expectation, not exactly each step. Unknown255 has zero +sampling probability. Eight focused tests pass without skips; Ruff passes. +All117 parent scores match the previous stage exactly.351 final score maps and +metrics plus117 feature sets replay exactly. Total fit time525.508s; peak +allocated GPU386144768B. No intermediate checkpoint selection. + +The numeric TRAIN capacity screen passes12/12: feature-head BCE improves +98.75–99.999% versus parent; coarse-only12.35–37.05%. Repeated TRAIN counts +(13 frames x3 eligible compositions x3 seeds, not independent pixels): +parent weakFN184 / clearFN1407 / backgroundFP18284; coarse-only184 /1598 /16897; +feature-head0 /1 /56. No window/cohort regression on the enumerated reviewed +cohorts versus either comparator. This is fit evidence, not transfer evidence. + +Mandatory visual review rejects the current recipe despite numeric success. +All13 full frames, all three eligible systems and three-seed prediction/error +unions were inspected, with enlarged native crops and two final proof JPEGs. +M4 A-hole, MI1 manhole, SM1 scooter and SR1 reviewed gap-edge errors improve. +However, SM3-adj2 gains a large contiguous unsupported fill, and M1 gains +unsubstantiated dash connections. SM3-adj2 contains only140 known paint pixels +and zero reviewed background out of262144;99.9466% remains unknown. Unknown +pixels predicted as paint grow in all nine eligible model instances from +12279–21514 to62422–146711. These are prediction extents, NOT false-positive +counts and NOT new background labels. Sparse mask success cannot certify the +whole image. This qualitative veto is separate from the passed numeric screen; +no new result-selected numerical threshold is claimed. No excluded street or +exposed control is scored after this visual rejection. No convergence or sole +causal explanation is claimed. + +Next: audit and version contextual paint/background/unresolved coverage across +all four streets, preserving positives and uncertain scan regions, then freeze +an equal-budget old-release/new-coverage comparison at the same architecture. +Explicitly audit class/window masses including previously positive-only frames. +Require reviewed-cohort AND whole-frame acceptance before transfer evaluation. +Independent physically disjoint human-reviewed gold remains required for +promotion. User annotations and the production model remain unchanged. + +Evidence: `outputs/semantic-feature-refinement-20261024/report.txt`, decision, +paired summary, unknown review, visual review, next-step and verification/cleanup +receipts. Retain26 new states plus229 ancestor states and10 source datasets; +archive verified text before deleting only39 inventoried derived NPZ. Mac keeps +bounded text and two proof JPEGs. Global learning remains open; Worker006 power +off still belongs to the global endpoint requested by the owner. + +Closeout verified: text archive `fdaba321bdd7989aa9a5dddcea679ed26cb453ff565fb947adbfcc0541acf85b` contains62 paths. Removed only39 inventoried NPZ totaling822,923,124 bytes; reverified255 retained states, two proof JPEGs and10 datasets. Eight durable containers remain running; no experiment container remains. Core8000 is listening. + + +### Context coverage at fixed feature recipe, 2026-10-25 + +Completed `semantic-context-coverage-20261024` (session started2026-10-24). +Visually inspected all13 TRAIN raw frames and23 candidate context polygons; +22 nonempty additions across11 frames introduce315294 reviewed background +pixels on4 streets. Existing labels and protected uncertain withdrawals remain +unchanged; no added paint. Immutable observed-paint release +`ed6aa514f86fc8cb7fcd5baa14766ddfc783e2a130625198abdd8b20130bc0ca`. +This is assistant-reviewed exposed TRAIN, not independent human gold. + +Same198402-parameter feature head, frozen parent features,1200steps, optimizer, +threshold and sampling budget as prior stage. Positive weights byte-identical; +negative mass conserved per street and shared equally among its frames with +reviewed background. SM3-adj2 receives its first negative support. Coverage and +within-street mass redistribution are jointly tested; no label-only causal +isolation is claimed. Generic `context_background.py` implements the mass rule +and frozen comparison gate without street coordinates or inference exceptions. + +24 principal fits plus2 new repeats and2 exact old-release retrain controls. +20 Worker tests pass with0 skips; Ruff passes. Old fits match all tensors, +losses and sampled indices.117 prior coarse predictions and234 prior feature/ +control maps match exactly; all585 comparison maps/metrics and117 feature sets +replay exactly. Fit time624.873s including repeats. Both releases evaluated +against the same expanded masks and weights. + +Repeated TRAIN totals (12 systems, each frame appears9 times): old feature +contextFP82121 / originalBGFP56 / prior-addedBGFP0 / weakFN0 / clearFN1; +new feature0 /43 /3 /0 /6. Total reviewed backgroundFP82177→46. New zero-feature +control has22593 backgroundFP,107 weakFN and1163 clearFN. Weak support28692, +clear support643779, new-background support2837646 repeated pixels. Eight of12 +paired systems pass the frozen full criterion. Four fail old-cohort retention +and/or near-ceiling BCE comparison. No threshold/checkpoint/criterion changes. + +Whole-frame review covered all13 images, all3 eligible training compositions, +all3 seeds as prediction/error unions, native crops, and two final proof JPEGs. +SM3-adj2 large unsupported fill and M1 false dash connections improve. On the +current unknown mask, SM3-adj2 prediction extent drops from61824–127194 to +11219–21148 pixels; these are NOT false-positive labels. Remaining MI3 dashes +are still joined. Source-versus-supervision inspection shows both these visible +dashes and their gaps remain unknown in this experiment's observed-paint mask. +Thus sparse-mask quality still cannot certify the full scene. This does not +mean the live user map lost edits; it was never modified by this experiment. + +Bounded hypothesis closed: added context helps this fixed model substantially, +but the recipe fails full-frame acceptance. No held-street/exposed-control +scoring and no production promotion. Next: complete source-reviewed compact +road ROIs across streets, visible paint plus all relevant interiors/gaps and +background, explicit unresolved ignore, generic coverage/provenance checks, +then same fixed recipe before a frozen transfer diagnostic. Do not claim labels +are the sole possible limit. Independent physically disjoint human-reviewed +gold is still needed for promotion. + +Evidence under `outputs/semantic-context-coverage-20261024`: report, paired +summary, decision, visual/coverage reviews, next-step and verification receipts. +Text archive `0809ad81500f7499d8f4ee838927bf5b6b3f86b49c3f6f84921709f86be076e3` +verified109 paths before removing only39 inventoried derived NPZ totaling +1092985912 bytes. Reverified283 retained states,10 datasets, all releases and +both proof JPEGs. No experiment container remains;8 durable Worker services +and canonical Core8000 (PID22762) remain running. Mac retains bounded text and +2 final JPEGs. Global learning remains open; requested Worker006 power-off is +still deferred to its global endpoint. + + +## 2026-10-25 — Root-reviewed agent pilot + +A bounded annotation/review/root workflow is implemented; see `SEMANTIC_AGENT_CYCLE.md`. Real pilot: four ROIs on four TRAIN streets, eight tasks, three admitted and SR1 quarantined at 38.2% unknown versus frozen 35%. New immutable release adds 986 paint and 25212 background pixels; all prior known labels and unadmitted regions remain exact. No fit or production promotion. Release SHA256 `4a9aeb8720b9134ae553d99f9fb1e4ee09f105ff1f290a73880b6381e0eb428e`. Evidence: `outputs/semantic-agent-pilot-20261025/report.txt`, `verification.json`, two final proof JPEGs. Session-backed Codex execution; no unattended provider/daemon or measured speedup claim. diff --git a/scripts/activate_simulation_worker_release.ps1 b/scripts/activate_simulation_worker_release.ps1 index 73681b9e..0cb12c7d 100644 --- a/scripts/activate_simulation_worker_release.ps1 +++ b/scripts/activate_simulation_worker_release.ps1 @@ -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 diff --git a/scripts/publish_qualified_urban_maps.py b/scripts/publish_qualified_urban_maps.py new file mode 100644 index 00000000..2307bdab --- /dev/null +++ b/scripts/publish_qualified_urban_maps.py @@ -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() diff --git a/scripts/stage_simulation_worker_patch.py b/scripts/stage_simulation_worker_patch.py new file mode 100644 index 00000000..e4a0ef18 --- /dev/null +++ b/scripts/stage_simulation_worker_patch.py @@ -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())))) diff --git a/simulation/ai-polygon/INFRASTRUCTURE_QUEUE.md b/simulation/ai-polygon/INFRASTRUCTURE_QUEUE.md new file mode 100644 index 00000000..080e0f12 --- /dev/null +++ b/simulation/ai-polygon/INFRASTRUCTURE_QUEUE.md @@ -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. diff --git a/simulation/ai-polygon/build_bundle.py b/simulation/ai-polygon/build_bundle.py index 06be8fc3..65c1aa15 100644 --- a/simulation/ai-polygon/build_bundle.py +++ b/simulation/ai-polygon/build_bundle.py @@ -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( diff --git a/simulation/ai-polygon/core_client.py b/simulation/ai-polygon/core_client.py index fe403b2e..4668cb98 100644 --- a/simulation/ai-polygon/core_client.py +++ b/simulation/ai-polygon/core_client.py @@ -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() diff --git a/simulation/ai-polygon/infrastructure_containers.py b/simulation/ai-polygon/infrastructure_containers.py new file mode 100644 index 00000000..37869d45 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_containers.py @@ -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) diff --git a/simulation/ai-polygon/infrastructure_document.py b/simulation/ai-polygon/infrastructure_document.py new file mode 100644 index 00000000..b16f5f47 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_document.py @@ -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') diff --git a/simulation/ai-polygon/infrastructure_gaussian_sources.py b/simulation/ai-polygon/infrastructure_gaussian_sources.py new file mode 100644 index 00000000..44aa6f16 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_gaussian_sources.py @@ -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 diff --git a/simulation/ai-polygon/infrastructure_pipeline.py b/simulation/ai-polygon/infrastructure_pipeline.py new file mode 100644 index 00000000..8a336f15 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_pipeline.py @@ -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 diff --git a/simulation/ai-polygon/infrastructure_preparer.py b/simulation/ai-polygon/infrastructure_preparer.py new file mode 100644 index 00000000..4fe75ecd --- /dev/null +++ b/simulation/ai-polygon/infrastructure_preparer.py @@ -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") diff --git a/simulation/ai-polygon/infrastructure_sources.py b/simulation/ai-polygon/infrastructure_sources.py new file mode 100644 index 00000000..e1c98985 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_sources.py @@ -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]], + ) diff --git a/simulation/ai-polygon/infrastructure_survey_cache.py b/simulation/ai-polygon/infrastructure_survey_cache.py new file mode 100644 index 00000000..12963f77 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_survey_cache.py @@ -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 diff --git a/simulation/ai-polygon/infrastructure_transport.py b/simulation/ai-polygon/infrastructure_transport.py new file mode 100644 index 00000000..b3d4a612 --- /dev/null +++ b/simulation/ai-polygon/infrastructure_transport.py @@ -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 diff --git a/simulation/ai-polygon/realtime_worker.py b/simulation/ai-polygon/realtime_worker.py index 50f49e5e..7f09db3b 100644 --- a/simulation/ai-polygon/realtime_worker.py +++ b/simulation/ai-polygon/realtime_worker.py @@ -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") diff --git a/src/k1link/simulation/ai_polygon/contracts.py b/src/k1link/simulation/ai_polygon/contracts.py index 7339da97..166c6341 100644 --- a/src/k1link/simulation/ai_polygon/contracts.py +++ b/src/k1link/simulation/ai_polygon/contracts.py @@ -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[ diff --git a/src/k1link/simulation/ai_polygon/infrastructure_jobs.py b/src/k1link/simulation/ai_polygon/infrastructure_jobs.py new file mode 100644 index 00000000..b03bae58 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/infrastructure_jobs.py @@ -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 diff --git a/src/k1link/simulation/ai_polygon/infrastructure_progress.py b/src/k1link/simulation/ai_polygon/infrastructure_progress.py new file mode 100644 index 00000000..2a85bcf5 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/infrastructure_progress.py @@ -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, + ) diff --git a/src/k1link/simulation/ai_polygon/library.py b/src/k1link/simulation/ai_polygon/library.py index 1f9431a5..a3b5af5e 100644 --- a/src/k1link/simulation/ai_polygon/library.py +++ b/src/k1link/simulation/ai_polygon/library.py @@ -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: diff --git a/src/k1link/simulation/ai_polygon/marking-templates.json b/src/k1link/simulation/ai_polygon/marking-templates.json new file mode 100644 index 00000000..4a9d9d34 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/marking-templates.json @@ -0,0 +1 @@ +{"version":"semantic-marking-artwork/v1","templates":[{"id":"linear_marking","label":"Линейная разметка","polygons":[[[[-1.5,-0.075],[1.5,-0.075],[1.5,0.075],[-1.5,0.075],[-1.5,-0.075]]]],"source":{"artist":"NODE.DC","license":"project-authored","adaptation":"Editable starter rectangle; dimensions are adjustable, not a standard claim","dimensions_m":[3,0.15]}},{"id":"straight_arrow","label":"Стрелка прямо","polygons":[[[[0.0,-0.075],[2.95,-0.075],[2.95,-0.375],[5.0,0.0],[2.95,0.375],[2.95,0.075],[0.0,0.075],[0.0,-0.075]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short"}},{"id":"right_arrow","label":"Поворот направо","polygons":[[[[0.0,0.075],[0.0,-0.075],[2.6,-0.075],[3.2,-0.675],[2.5,-0.675],[3.7,-0.9750000000000001],[5.0,-0.675],[4.2,-0.675],[3.45,0.075],[0.0,0.075]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short"}},{"id":"left_arrow","label":"Поворот налево","polygons":[[[[0.0,-0.075],[0.0,0.075],[2.6,0.075],[3.2,0.675],[2.5,0.675],[3.7,0.9750000000000001],[5.0,0.675],[4.2,0.675],[3.45,-0.075],[0.0,-0.075]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short"}},{"id":"letter_A","label":"Буква А","polygons":[[[[0.0,-0.7],[4.0,0.0],[0.0,0.7],[0.0,0.5],[1.1,0.3],[1.1,-0.3],[0.0,-0.5],[0.0,-0.7]],[[1.4,-0.24],[3.3,0.0],[1.4,0.24],[1.4,-0.24]]]],"source":{"kind":"editor-artwork","dimensions_m":[4,1.4],"compliance":"not-assessed"},"hidden":true},{"id":"zebra","label":"Зебра","polygons":[[[[-2.75,-2.0],[-2.25,-2.0],[-2.25,2.0],[-2.75,2.0],[-2.75,-2.0]]],[[[-1.75,-2.0],[-1.25,-2.0],[-1.25,2.0],[-1.75,2.0],[-1.75,-2.0]]],[[[-0.75,-2.0],[-0.25,-2.0],[-0.25,2.0],[-0.75,2.0],[-0.75,-2.0]]],[[[0.25,-2.0],[0.75,-2.0],[0.75,2.0],[0.25,2.0],[0.25,-2.0]]],[[[1.25,-2.0],[1.75,-2.0],[1.75,2.0],[1.25,2.0],[1.25,-2.0]]],[[[2.25,-2.0],[2.75,-2.0],[2.75,2.0],[2.25,2.0],[2.25,-2.0]]]],"source":{"kind":"editor-artwork","dimensions_m":[5.5,4],"compliance":"not-assessed"}},{"id":"bicycle","label":"Велосипед · вытянутый","polygons":[[[[0.4462448922387028,0.23731752914149185],[0.43580765653163867,0.23821987326853494],[0.42569317696428244,0.23912631231219994],[0.41587528411990304,0.24003158137968728],[0.4063278085817651,0.24093041557819728],[0.39702458093313675,0.2418175500149305],[0.3879394317572844,0.24268771979708714],[0.37904619163747444,0.2435356600318676],[0.37031869115697547,0.24435610582647244],[0.3617307608990523,0.245143792288102],[0.35325623144697327,0.2458934545239566],[0.3448689333840044,0.24659982764123667],[0.33654269729341313,0.24725764674714268],[0.3282513537584655,0.24786164694887491],[0.3199687333624295,0.24840656335363387],[0.31166866668857063,0.24888713106861987],[0.3033249843201571,0.2492980852010333],[0.30038455957889276,0.24936584632132452],[0.29717807910084115,0.24927858559807187],[0.293753520150014,0.24904975775731863],[0.29015885999042124,0.24869281752510852],[0.28644207588607395,0.2482212196274849],[0.28265114510098277,0.24764841879049104],[0.2788340448991582,0.2469878697401704],[0.27503875254461163,0.24625302720256648],[0.27131324530135315,0.2454573459037228],[0.2677055004333939,0.24461428056968265],[0.26426349520474446,0.24373728592648947],[0.2610352068794153,0.24283981670018673],[0.258068612721418,0.2419353276168179],[0.2554116899947624,0.24103727340242626],[0.2531124159634599,0.24015910878305546],[0.25121876789152064,0.23931428848474878],[0.22874687166430707,0.22862577611743573],[0.20487273085714386,0.21842631379239713],[0.17958980311584627,0.20871824146198803],[0.15289154608623257,0.19950389907856397],[0.12477141741411768,0.19078562659448028],[0.09522287474531965,0.18256576396209234],[0.06423937572565519,0.17484665113375564],[0.03181437800094056,0.16763062806182544],[-0.0020586607830068715,0.16092003469865712],[-0.03738628298037172,0.15471721099660607],[-0.07417503094533617,0.14902449690802766],[-0.11243144703208396,0.14384423238527738],[-0.15216207359479816,0.1391787573807105],[-0.19337345298766162,0.13503041184668235],[-0.23607212756485807,0.13140153573554847],[-0.28026463968057147,0.12829446899966407],[-0.364405129903532,0.1243230823625116],[-0.4478652152914311,0.12282444037690593],[-0.5301040612317844,0.12369734010347727],[-0.6105808331121061,0.12684057860285503],[-0.6887546963199123,0.1321529529356696],[-0.7640848162427183,0.13953326016255047],[-0.8360303582680393,0.14888029734412728],[-0.9040504877833904,0.16009286154103053],[-0.9676043701762871,0.17306974981388945],[-1.0261511708342446,0.18770975922333427],[-1.079150055144777,0.20391168682999472],[-1.1260601884954022,0.22157432969450053],[-1.166340736273633,0.24059648487748175],[-1.199450863866986,0.2608769494395681],[-1.2248497366629754,0.2823145204413894],[-1.2419965200491179,0.3048079949435757],[-1.25,0.32744089160693657],[-1.2491494939561738,0.34972338040507944],[-1.2398375431686346,0.3715203290894812],[-1.2224566888883794,0.3926966054116185],[-1.1973994723664054,0.4131170771229683],[-1.1650584348537092,0.43264661197500753],[-1.1258261176012887,0.451150077719213],[-1.0800950618601406,0.4684923421070616],[-1.028257808881261,0.48453827289002993],[-0.9707068999156481,0.4991527378195952],[-0.9078348762142978,0.512200604647234],[-0.8400342790282083,0.5235467411244233],[-0.7676976496083752,0.53305601500264],[-0.6912175292057967,0.5405932940333609],[-0.6109864590714689,0.5460234459680627],[-0.5273969804563894,0.5492113385582225],[-0.43392600277570303,0.55],[-0.34314393266434684,0.5479766236987007],[-0.25561123179735357,0.5432962314978682],[-0.17188836184975953,0.5361138452410467],[-0.0925357844965986,0.5265844867717796],[-0.018113961412904445,0.5148631779336111],[0.050816645726286414,0.5011049405700851],[0.1136955752459412,0.48546479652474533],[0.16996236547102406,0.46809776764113575],[0.21905655472650154,0.4491588757628001],[0.260417681337338,0.42880314273328246],[0.29348528362849957,0.40718559039612645],[0.3176988999249515,0.38446124059487613],[0.33249806855165887,0.36078511517307543],[0.3373223278335873,0.33631223597426796],[0.33161121609570277,0.31119762484199787],[0.3313487950001286,0.31044396518753614],[0.3311169048907435,0.3096797757474752],[0.33091118419809107,0.3089038865456374],[0.3307272713527166,0.30811512760584503],[0.3305608047851645,0.3073123289519203],[0.3304074229259788,0.30649432060768567],[0.3302627642057038,0.30565993259696334],[0.33012246705488413,0.3048079949435757],[0.3299821699040655,0.30393733767134506],[0.32983751118379045,0.30304679080409364],[0.32968412932460467,0.3021351843656438],[0.3295176627570522,0.30120134837981793],[0.32933374991167774,0.3002441128704382],[0.32912802921902573,0.299262307861327],[0.32889613910964066,0.29825476337630663],[0.3286337180140665,0.2972203094391994],[0.35710567995559295,0.29490346411332957],[0.3855754611123918,0.2925942236326148],[0.41404088069973477,0.2902908330327884],[0.44249975793289487,0.2879915373495838],[0.47094991202714376,0.28569458161873473],[0.4993891621977533,0.2833982108759744],[0.5278153276599974,0.28110067015703655],[0.5562262276291459,0.2788002044976544],[0.5846196813204735,0.2764950589335614],[0.6129935079492508,0.27418347850049113],[0.6413455267307504,0.27186370823417705],[0.6696735568802447,0.26953399317035265],[0.6979754176130057,0.2671925783447513],[0.7262489281443061,0.26483770879310664],[0.7544919076894175,0.2624676295511519],[0.7827021754636128,0.26008058565462067],[0.8014038583606486,0.2584941954556884],[0.8201011796882288,0.25688031081658047],[0.8387897778768982,0.2552395167253855],[0.8574652913572008,0.25357239817019267],[0.8761233585596816,0.2518795401390906],[0.8947596179148847,0.25016152762016824],[0.9133697078533544,0.2484189456015144],[0.9319492668056358,0.24665237907121784],[0.9504939332022726,0.24486241301736766],[0.9689993454738102,0.24304963242805233],[0.9874611420507924,0.2412146222913611],[1.005874961363764,0.23935796759538258],[1.0242364418432688,0.23748025332820538],[1.042541221919852,0.23558206447791896],[1.060784940024058,0.23366398603261163],[1.0789632345864315,0.23172660298037245],[1.0980102083986962,0.22951749296086493],[1.1160540212361907,0.22708257753906325],[1.1330685036821821,0.22442068673878973],[1.1490274863199372,0.22153065058386673],[1.163904799732723,0.21841129909811674],[1.177674274503806,0.21506146230536188],[1.1903097412164532,0.21147997022942439],[1.2017850304539317,0.20766565289412658],[1.212073972799508,0.20361734032329087],[1.2211503988364494,0.19933386254073976],[1.2289881391480226,0.19481404957029524],[1.2355610243174944,0.19005673143577956],[1.2408428849281314,0.18506073816101537],[1.244807551563201,0.1798248997698249],[1.2474288548059698,0.17434804628603023],[1.2486806252397047,0.1686290077334538],[1.2491713018034507,0.1636822509561674],[1.249535492852987,0.15872554938137057],[1.2497862830966795,0.1537583180209745],[1.2499367572428948,0.14877997188689057],[1.25,0.14378992599102958],[1.2499890960763613,0.13878759534530294],[1.2499171301803451,0.13377239496162158],[1.2497971870203184,0.1287437398518968],[1.2496423513046473,0.12370104502803997],[1.2494657077416986,0.11864372550196178],[1.2492803410398388,0.11357119628557377],[1.2490993359074347,0.1084828723907868],[1.2489357770528526,0.10337816882951234],[1.248802749184459,0.0982565006136612],[1.248713337010621,0.09311728275514503],[1.2486806252397047,0.08795993026587434],[1.240252982659272,0.08795993026587434],[1.2317141200577237,0.08795993026587445],[1.2230574950808768,0.08795993026587434],[1.2142765653745469,0.08795993026587434],[1.2053647885845515,0.08795993026587434],[1.196315622356707,0.08795993026587434],[1.1871225243368306,0.08795993026587445],[1.1777789521707387,0.08795993026587429],[1.1682783635042477,0.08795993026587434],[1.1586142159831747,0.08795993026587434],[1.1487799672533368,0.08795993026587434],[1.1387690749605497,0.08795993026587434],[1.1285749967506309,0.08795993026587434],[1.1181911902693966,0.08795993026587434],[1.107611113162664,0.08795993026587434],[1.0968282230762498,0.08795993026587434],[1.0968282230762498,0.08982740724149657],[1.0968282230762496,0.09168669438387494],[1.0968282230762498,0.09353896166918729],[1.0968282230762498,0.09538537907361105],[1.0968282230762496,0.09722711657332411],[1.0968282230762498,0.09906534414450407],[1.0968282230762498,0.10090123176332866],[1.0968282230762498,0.10273594940597564],[1.0968282230762496,0.10457066704862245],[1.0968282230762496,0.10640655466744703],[1.09682822307625,0.10824478223862705],[1.09682822307625,0.1100865197383401],[1.0968282230762498,0.11193293714276398],[1.09682822307625,0.11378520442807616],[1.0968282230762498,0.11564449157045453],[1.0968282230762498,0.11751196854607676],[1.0968282230762498,0.11871002415203097],[1.0968282230762496,0.11990807975798506],[1.0968282230762498,0.12110613536393916],[1.0968282230762498,0.12230419096989337],[1.0968282230762496,0.12350224657584746],[1.0968282230762498,0.12470030218180167],[1.0968282230762498,0.12589835778775577],[1.0968282230762498,0.12709641339370986],[1.0968282230762496,0.12829446899966407],[1.0968282230762496,0.12949252460561828],[1.09682822307625,0.13069058021157243],[1.09682822307625,0.13188863581752652],[1.0968282230762498,0.13308669142348073],[1.09682822307625,0.13428474702943483],[1.0968282230762498,0.13548280263538903],[1.0968282230762498,0.13668085824134324],[1.0962935673538268,0.1446376712297806],[1.0951330264145367,0.1517766708700129],[1.0931743182648863,0.1581598658994578],[1.090245160911382,0.16384926505553266],[1.0861732723605306,0.16890687707565516],[1.0807863706188396,0.17339471069724288],[1.0739121736928157,0.1773747746577134],[1.0653783995889656,0.1809090776944839],[1.0550127663137963,0.18405962854497238],[1.0426429918738143,0.18688843594659627],[1.028096794275527,0.18945750863677302],[1.0112018915254415,0.19182885535292016],[0.9917860016300638,0.19406448483245542],[0.9696768425959013,0.1962264058127962],[0.9447021324294607,0.19837662703136005],[0.9166895891372493,0.20057715722556463],[0.9099716817833817,0.20109691914250322],[0.9032123395196863,0.2016090762142867],[0.8964050199919802,0.20211538340518204],[0.8895431808460801,0.2026175956794552],[0.8826202797278029,0.20311746800137315],[0.8756297742829653,0.20361675533520218],[0.8685651221573836,0.20411721264520882],[0.8614197809968741,0.2046205948956598],[0.8541872084472546,0.2051286570508215],[0.8468608621543416,0.20564315407496053],[0.8394341997639514,0.20616584093234336],[0.8319006789219011,0.20669847258723661],[0.8242537572740072,0.20724280400390666],[0.8164868924660862,0.20780059014662028],[0.8085935421439554,0.20837358597964367],[0.8005671639534307,0.20896354646724363],[0.8002716676228194,0.20799919360278302],[0.7999478210907466,0.20705180539289886],[0.7996021667113965,0.20611962687332464],[0.7992412468389519,0.20520090307979377],[0.7988716038275966,0.20429387904803997],[0.7984997800315131,0.20339679981379655],[0.7981323178048856,0.2025079104127968],[0.7977757595018966,0.2016254558807743],[0.7974366474767296,0.20074768125346276],[0.7971215240835683,0.1998728315665954],[0.7968369316765954,0.19899915185590578],[0.7965894126099946,0.19812488715712723],[0.796385509237949,0.1972482825059932],[0.7962317639146417,0.19636758293823736],[0.7961347189942565,0.19548103348959306],[0.7961009168309761,0.19458687919579387],[0.7961005533668548,0.17324202880605438],[0.7960980091180055,0.15188898858307104],[0.7960911032997013,0.13052892850302178],[0.7960776551272132,0.10916301854208382],[0.7960554838158144,0.08779242867643516],[0.7960224085807768,0.06641832888225341],[0.7959762486373723,0.045041889135716384],[0.7959148232008739,0.023664279413001754],[0.7958359514865531,0.002286669690286902],[0.7957374527096825,-0.019089770056250233],[0.7956171460855345,-0.040463869850432044],[0.7954728508293807,-0.06183445971608048],[0.7953023861564944,-0.08320036967701838],[0.795103571282147,-0.10456042975706781],[0.7948742254216105,-0.12591346998005104],[0.794612167790158,-0.14725832036979047],[0.7947219339547884,-0.14908358070500116],[0.7950715864394731,-0.15081582793408532],[0.7956916562303993,-0.15245564704513215],[0.7966126743137575,-0.15400362302623016],[0.7978651716757348,-0.15546034086546867],[0.7994796793025204,-0.1568263855509361],[0.8014867281803033,-0.15810234207072127],[0.8039168492952712,-0.15928879541291352],[0.8068005736336143,-0.16038633056560092],[0.8101684321815198,-0.16139553251687322],[0.8140509559251768,-0.1623169862548186],[0.8184786758507745,-0.16315127676752594],[0.8234821229445008,-0.16389898904308442],[0.8290918281925443,-0.16456070806958278],[0.8353383225810949,-0.16513701883510967],[0.8422521370963397,-0.16562850632775417],[0.8483779613966205,-0.16602571324007975],[0.8544819778496232,-0.16646620927097988],[0.8605772711637156,-0.1669464844919215],[0.866676926047263,-0.16746302897437138],[0.8727940272086326,-0.16801233278979677],[0.8789416593561911,-0.1685908860096642],[0.8851329071983042,-0.16919517870544087],[0.89138085544334,-0.1698217009485936],[0.8976985887996635,-0.17046694281058938],[0.904099191975642,-0.17112739436289526],[0.9105957496796422,-0.17179954567697786],[0.9172013466200303,-0.17247988682430448],[0.9239290675051726,-0.17316490787634164],[0.9307919970434367,-0.17385109890455663],[0.9378032199431885,-0.1745349499804162],[0.9449758209127945,-0.17521295117538738],[0.9480296464599023,-0.1715485857868636],[0.9510529410208218,-0.16789358020776113],[0.954050066165008,-0.1642479344380805],[0.9570253834619169,-0.16061164847782095],[0.9599832544810032,-0.15698472232698335],[0.9629280407917229,-0.15336715598556705],[0.9658641039635321,-0.14975894945357238],[0.9687958055658854,-0.1461601027309991],[0.9717275071682386,-0.14257061581784747],[0.9746635703400477,-0.13899048871411745],[0.9776083566507675,-0.13541972141980874],[0.9805662276698541,-0.13185831393492164],[0.9835415449667627,-0.12830626625945585],[0.9865386701109489,-0.12476357839341179],[0.9895619646718683,-0.12123025033678914],[0.9926157902189763,-0.117706282089588],[0.9942920867463816,-0.11583900010999548],[0.9959771064126983,-0.11398107793982437],[0.9976795723568376,-0.11213251557907489],[0.9994082077177089,-0.11029331302774681],[1.0011717356342253,-0.10846347028584025],[1.0029788792452967,-0.10664298735335509],[1.0048383616898338,-0.1048318642302919],[1.0067589061067488,-0.10303010091664977],[1.008749235634952,-0.10123769741242927],[1.0108180734133547,-0.09945465371763029],[1.0129741425808676,-0.09768096983225294],[1.0152261662764022,-0.09591664575629699],[1.0175828676388692,-0.09416168148976256],[1.0200529698071799,-0.09241607703264965],[1.0226451959202454,-0.09067983238495825],[1.025368269116976,-0.08895294754668859],[1.0266876438772714,-0.0882844036591538],[1.028386475180197,-0.0876293144976622],[1.030425508900654,-0.08699177497883626],[1.0327654909135413,-0.08637588001929764],[1.0353671670937603,-0.0857857245356679],[1.0381912833162108,-0.08522540344456941],[1.0411985854557928,-0.08469901166262406],[1.0443498193874081,-0.08421064410645329],[1.047605730985955,-0.08376439569267957],[1.0509270661263352,-0.08336436133792446],[1.0542745706834484,-0.0830146359588102],[1.057608990532195,-0.08271931447195835],[1.0608910715474749,-0.08248249179399092],[1.0640815596041895,-0.08230826284153003],[1.0671412005772383,-0.08220072253119737],[1.0700307403415217,-0.08216396577961504],[1.072065775956644,-0.08223650430263185],[1.0742382010096154,-0.08244476006226054],[1.0765109421600634,-0.08277469334436904],[1.0788469260676168,-0.08321226443482477],[1.0812090793919034,-0.08374343361949599],[1.0835603287925508,-0.0843541611842501],[1.0858636009291878,-0.08503040741495449],[1.0880818224614421,-0.08575813259747755],[1.0901779200489417,-0.08652329701768646],[1.092114820351315,-0.08731186096144927],[1.0938554500281894,-0.0881097847146336],[1.0953627357391937,-0.08890302856310706],[1.0965996041439554,-0.08967755279273759],[1.097528981902103,-0.09041931768939282],[1.098113795673264,-0.09111428353894047],[1.0983169721170671,-0.09174841062724826],[1.09857902974852,-0.10298047442711278],[1.098808375609056,-0.11421429319124388],[1.0990071904834036,-0.12545162188390813],[1.09917765515629,-0.136694215469372],[1.0993219504124436,-0.14794382891190194],[1.0994422570365918,-0.15920221717576444],[1.0995407558134624,-0.17047113522522617],[1.099619627527783,-0.18175233802455393],[1.0996810529642818,-0.19304758053801374],[1.099727212907686,-0.2043586177298723],[1.0997602881427238,-0.21568720456439616],[1.0997824594541226,-0.22703509600585192],[1.0997959076266104,-0.23840404701850637],[1.0998028134449147,-0.24979581256662575],[1.099805357693764,-0.2612121476144762],[1.0998057211578853,-0.27265480712632495],[1.090084146305648,-0.27265480712632495],[1.0804432604883376,-0.27265480712632517],[1.0708590750739497,-0.27265480712632495],[1.0613076014304776,-0.27265480712632495],[1.0517648509259168,-0.27265480712632495],[1.0422068349282616,-0.27265480712632495],[1.0326095648055067,-0.27265480712632495],[1.0229490519256466,-0.27265480712632495],[1.0132013076566762,-0.27265480712632495],[1.0033423433665898,-0.27265480712632495],[0.9933481704233826,-0.27265480712632495],[0.9831948001950486,-0.27265480712632495],[0.9728582440495827,-0.27265480712632495],[0.9623145133549793,-0.27265480712632495],[0.9515396194792335,-0.27265480712632495],[0.9405095737903397,-0.27265480712632495],[0.9405582779825927,-0.27032918697912245],[0.9406898519945017,-0.2679959619867649],[0.9408824879787868,-0.265656887113519],[0.9411143780881722,-0.26331371732365116],[0.9413637144753795,-0.260968207581428],[0.9416086892931315,-0.2586221128511158],[0.9418274946941503,-0.2562771880969813],[0.9419983228311579,-0.2539351882832914],[0.9420993658568777,-0.251597868374312],[0.9421088159240312,-0.24926698333430986],[0.9420048651853413,-0.24694428812755154],[0.9417657057935305,-0.2446315377183036],[0.9413695299013205,-0.2423304870708327],[0.940794529661434,-0.24004289114940502],[0.9400188972265935,-0.23777050491828744],[0.9390208247495216,-0.2355150833417462],[0.938291715722207,-0.23452430851527262],[0.9372354889857277,-0.2335042842843571],[0.9358739523873624,-0.23246320048224278],[0.934228913774388,-0.23140924694217424],[0.9323221809940825,-0.23035061349739483],[0.9301755618937231,-0.22929548998114846],[0.9278108643205876,-0.22825206622667893],[0.9252498961219537,-0.22722853206722982],[0.9225144651450985,-0.22623307733604592],[0.9196263792373004,-0.22527389186636992],[0.9166074462458367,-0.2243591654914463],[0.9134794740179843,-0.22349708804451862],[0.9102642704010226,-0.22269584935883102],[0.9069836432422271,-0.22196363926762686],[0.9036594003888768,-0.22130864760415025],[0.9003133496882489,-0.22073906420164513],[0.8877672951494398,-0.21891390136444933],[0.8752430484579085,-0.21733209357221306],[0.8627275249052879,-0.21599364082493622],[0.850207639783212,-0.21489854312261858],[0.8376703083833139,-0.2140468004652606],[0.8251024459972269,-0.21343841285286191],[0.8124909679165853,-0.2130733802854229],[0.7998227894330214,-0.21295170276294317],[0.7870848258381691,-0.213073380285423],[0.7742639924236625,-0.21343841285286191],[0.7613472044811338,-0.2140468004652606],[0.748321377302217,-0.21489854312261858],[0.7351734261785463,-0.21599364082493622],[0.7218902664017541,-0.21733209357221306],[0.7084588132634739,-0.21891390136444933],[0.6948659820553393,-0.22073906420164513],[0.6741416213233051,-0.2236931565522966],[0.6532885942923332,-0.22656944548713165],[0.6323178048860618,-0.22937436587512772],[0.6112401570281303,-0.2321143525852618],[0.5900665546421774,-0.2347958404865117],[0.5688079016518421,-0.23742526444785428],[0.5474751019807624,-0.24000905933826677],[0.5260790595525776,-0.24255366002672707],[0.5046306782909269,-0.24506550138221161],[0.4831408621194486,-0.2475510182736984],[0.4616205149617819,-0.2500166455701647],[0.4400805407415649,-0.2524688181405871],[0.4185318433824372,-0.2549139708539434],[0.3969853268080369,-0.2573585385792111],[0.37545189494200326,-0.25980895618536715],[0.353942451707975,-0.2622716585413889],[0.3473263143080697,-0.2630265856700429],[0.3414189319446863,-0.2637996474294515],[0.3361963159858199,-0.26459961864094694],[0.3316344777994652,-0.26543527412586165],[0.3277094287536165,-0.2663153887055286],[0.32439718021626873,-0.2672487372012805],[0.3216737435554168,-0.26824409443444985],[0.31951513013905464,-0.26931023522636943],[0.31789735133517727,-0.2704559343983721],[0.3167964185117791,-0.27168996677179025],[0.31618834303685495,-0.2730211071679566],[0.3160491362783997,-0.27445813040820366],[0.3163548096044071,-0.2760098113138646],[0.3170813743828733,-0.2776849247062717],[0.3182048419817911,-0.27949224540675766],[0.31970122376915666,-0.2814405482366553],[0.3367088003968437,-0.3042099421207466],[0.34494308006474794,-0.32675528556681066],[0.344702830280573,-0.34894612623103427],[0.3362868185520216,-0.3706520117696056],[0.3199938123867979,-0.3917424898387126],[0.2961225792926043,-0.4120871080945424],[0.2649718867771451,-0.4315554141932826],[0.22684050234812214,-0.45001695579112067],[0.18202719351323982,-0.4673412805442445],[0.13083072778020077,-0.48339793610884185],[0.07354987265670898,-0.4980564701411003],[0.010483395650467076,-0.5111864302972069],[-0.0580699357308212,-0.5226573642333496],[-0.13181135397945387,-0.5323388196057162],[-0.2104420915877261,-0.5401003440704943],[-0.29366338104793543,-0.5458114852838711],[-0.3875643367841115,-0.5494518661607524],[-0.48010012128070967,-0.55],[-0.5705685218553902,-0.5476208534426683],[-0.6582673258258143,-0.5424793931298115],[-0.7424943205096424,-0.5347405857024834],[-0.8225472932245363,-0.5245693978017387],[-0.8977240312881567,-0.5121307960686319],[-0.9673223220181639,-0.4975897471442168],[-1.03063995273222,-0.48111121766954756],[-1.086974710747985,-0.4628601742856786],[-1.1356243833831199,-0.44300158363366415],[-1.1758867579552863,-0.42170041235455846],[-1.207059621782145,-0.3991216270894158],[-1.2284407621813567,-0.37543019447929027],[-1.239327966470582,-0.35079108116523605],[-1.2390190219674828,-0.3253692537883076],[-1.232497385239113,-0.3078641677157308],[-1.221389558228263,-0.2908697762447152],[-1.2058198456644127,-0.27442878350574684],[-1.1859125522770468,-0.2585838936293111],[-1.1617919827956458,-0.24337781074589437],[-1.133582441949693,-0.22885323898598187],[-1.1014082344686709,-0.21505288248005883],[-1.0653936650820612,-0.2020194453586115],[-1.025663038519348,-0.18979563175212533],[-0.9823406595100117,-0.178424145791086],[-0.9355508327835347,-0.16794769160597944],[-0.8854178630694012,-0.15840897332729076],[-0.8320660550970915,-0.1498506950855062],[-0.7756197135960896,-0.1423155610111111],[-0.7162031432958769,-0.13584627523459125],[-0.6539406489259358,-0.13048554188643224],[-0.6475011550889787,-0.12995515268587965],[-0.6415741456630459,-0.12940604386648402],[-0.6361487167244975,-0.12882885561882373],[-0.6312139643496961,-0.1282142281334776],[-0.6267589846150015,-0.12755280160102367],[-0.6227728735967757,-0.12683521621204075],[-0.6192447273713795,-0.1260521121571072],[-0.6161636420151748,-0.12519412962680154],[-0.6135187136045217,-0.12425190881170212],[-0.6112990382157824,-0.12321608990238753],[-0.6094937119253176,-0.12207731308943637],[-0.6080918308094887,-0.1208262185634269],[-0.6070824909446566,-0.11945344651493794],[-0.6064547884071827,-0.11794963713454754],[-0.6061978192734281,-0.11630543061283438],[-0.6063006796197543,-0.11451146714037697],[-0.6067590078767051,-0.11099227629590147],[-0.6070363310012525,-0.10747367043951472],[-0.6071609991948557,-0.1039562345593058],[-0.6071613626589769,-0.10044055364336335],[-0.6070657715950769,-0.09692721267977622],[-0.6069025762046165,-0.0934167966566335],[-0.6067001266890559,-0.08990989056202381],[-0.6064867732498564,-0.0864070793840358],[-0.60629086608848,-0.08290894811075877],[-0.6061407554063853,-0.07941608173028125],[-0.6060647914050346,-0.0759290652306922],[-0.6060913242858899,-0.0724484836000805],[-0.6062487042504092,-0.06897492182653486],[-0.6065652815000557,-0.06550896489814428],[-0.60706940623629,-0.06205119780299739],[-0.6077894286605723,-0.05860220552918327],[-0.608611221038817,-0.05299480220356145],[-0.6082924630044424,-0.04755061055472731],[-0.6068440584810881,-0.042264365689881345],[-0.6042769113923918,-0.03713080271622349],[-0.600601925661993,-0.032144656740955124],[-0.595830005213531,-0.02730066287127564],[-0.5899720539706439,-0.022593556214385968],[-0.5830389758569701,-0.018018071877486497],[-0.5750416747961489,-0.013568944967777274],[-0.565991054711819,-0.009240910592459017],[-0.5558980195276204,-0.005028703858732109],[-0.5447734731671903,-0.0009270598737967095],[-0.5326283195541679,0.003069286255146575],[-0.519473462612192,0.0069655994208974725],[-0.5053198062649016,0.010767144516255267],[-0.49017825443593566,0.01447918643402002],[-0.45556556616515564,0.022495863203549016],[-0.42095723946383057,0.03052189978249975],[-0.38635763590141714,0.03855729617087189],[-0.3517711170473701,0.04660205236866566],[-0.3172020444711452,0.05465616837588083],[-0.28265477974219766,0.06271964419251763],[-0.2481336844299833,0.07079247981857584],[-0.21364312010395814,0.07887467525405556],[-0.17918744833357647,0.08696623049895685],[-0.144771030688295,0.09506714555327966],[-0.11039822873756844,0.10317742041702399],[-0.07607340405085239,0.11129705509018983],[-0.0418009181976029,0.11942604957277714],[-0.007585132747275347,0.12756440386478596],[0.026569590730674886,0.1357121179662164],[0.06065889066679242,0.14386919187706831],[0.0851232972069369,0.14942891867344915],[0.10940669861467756,0.15502608470751628],[0.13353744509147414,0.16066068997926947],[0.15754388683878884,0.1663327344887085],[0.18145437405808185,0.1720422182358337],[0.20529725695081424,0.177789141220645],[0.2291008857184471,0.18357350344314238],[0.25289361056244086,0.18939530490332585],[0.276703781684257,0.19525454560119543],[0.300559749285356,0.2011512255367509],[0.324489863567199,0.20708534470999257],[0.34852247473124653,0.21305690312092035],[0.3726859329789598,0.21906590076953403],[0.39700858851179965,0.22511233765583388],[0.42151879153122696,0.23119621377981986],[0.4462448922387028,0.23731752914149185]],[[0.14105133887097487,0.3131943841852548],[0.14765729927548432,0.3288933195335234],[0.14811998910189117,0.3444764272402009],[0.1427163680106205,0.3598465992825387],[0.13172339566209845,0.3749067276377889],[0.11541803171675058,0.3895597042832031],[0.0940772358350026,0.403708421196033],[0.06797796767728048,0.41725577035353056],[0.03739718690400884,0.43010464373294727],[0.002611853175614076,0.4421579333115352],[-0.03610107384747785,0.4533185310665459],[-0.07846463450484209,0.4634893289752312],[-0.12420186913605225,0.4725732190148429],[-0.1730358180806837,0.4804730931626327],[-0.22468952167830958,0.4870918433958524],[-0.27888602026850506,0.4923323616917537],[-0.33534835419084397,0.49609754002758844],[-0.3963336356385594,0.498405415536096],[-0.45678898639742904,0.49907941931245997],[-0.5163589385568279,0.49817980512983145],[-0.5746880242061296,0.4957668267613615],[-0.6314207754347114,0.49190073798020106],[-0.6862017243319469,0.48664179255950113],[-0.7386754029872109,0.4800502442724127],[-0.788486343489879,0.47218634689208683],[-0.835279077929326,0.46311035419167457],[-0.8786981383949262,0.45288251994432693],[-0.9183880569760552,0.44156309792319487],[-0.9539933657620878,0.42921234190142943],[-0.9851585968423993,0.41589050565218155],[-1.0115282823063647,0.4016578429486024],[-1.0327469542433576,0.3865746075638429],[-1.048459144742754,0.370701053271054],[-1.0581625463889273,0.35453900235244984],[-1.061744485304275,0.3384658696233501],[-1.0594339438852112,0.32257993308268085],[-1.0514599045281523,0.3069794707293677],[-1.0380513496295145,0.2917627605623367],[-1.0194372615857112,0.2770280805805138],[-0.9958466227931555,0.2628737087828251],[-0.9675084156482652,0.2493979231681963],[-0.9346516225474542,0.23669900173555342],[-0.8975052258871368,0.2248752224838222],[-0.8562982080637291,0.2140248634119289],[-0.8112595514736438,0.20424620251879927],[-0.7626182385132987,0.1956375178033592],[-0.710603251579107,0.18829708726453465],[-0.6554435730674837,0.18232318890125154],[-0.5973681853748438,0.17781410071243575],[-0.5437336023161685,0.17516858957864995],[-0.48923324772057186,0.17392821983426943],[-0.43436215972125547,0.17402864278952107],[-0.3796153764514214,0.1754055097546322],[-0.3254879360442722,0.1779944720398296],[-0.2724748766330085,0.18173118095534058],[-0.22107123635083248,0.18655128781139213],[-0.17177205333094547,0.1923904439182113],[-0.12507236570654934,0.19918430058602515],[-0.08146721161084725,0.20686850912506088],[-0.04145162917703926,0.2153787208455452],[-0.005520656538327007,0.22465058705770574],[0.025830668172085902,0.23461975907176924],[0.052107306821000066,0.2452218881979628],[0.07281422127521209,0.25639262574651356],[0.08745637340152079,0.26806762302764847],[0.08606067117575367,0.2682172824803778],[0.08466496894998632,0.26836635694501854],[0.08326926672421964,0.26851426143348145],[0.08187356449845273,0.2686604109576779],[0.08047786227268561,0.26880422052951886],[0.07908216004691848,0.2689451051609155],[0.07768645782115158,0.2690824798637794],[0.07629075559538445,0.26921575965002115],[0.07489505336961733,0.2693443595315522],[0.07349935114385042,0.26946769452028363],[0.0721036489180833,0.26958517962812656],[0.07070794669231617,0.2696962298669924],[0.06931224446654927,0.26980026024879195],[0.06791654224078214,0.2698966857854366],[0.06652084001501501,0.2699849214888373],[0.06512513778924811,0.27006438237090535],[0.03272812680187287,0.2728349834576891],[0.0003005848283095247,0.2756061695325618],[-0.032153126561987655,0.2783785255836121],[-0.06462864579956218,0.2811526365989289],[-0.09712161131495844,0.2839290875666012],[-0.12962766153872152,0.28670846347471757],[-0.16214243490139535,0.2894913493113673],[-0.194661569833525,0.29227833006463855],[-0.22718070476565466,0.2950699907226208],[-0.25969547812832894,0.2978669162734026],[-0.29220152835209157,0.30066969170507285],[-0.32469449386748805,0.30347890200572036],[-0.3571700131050626,0.30629513216343407],[-0.3896237244953593,0.3091189671663027],[-0.4220512664689233,0.31195099200241516],[-0.45444827745629834,0.3147917916598604],[-0.4629867765937252,0.31557928312546024],[-0.4712548584249099,0.3164492579115873],[-0.4791914609774748,0.31740932086339646],[-0.4867355222790426,0.3184670768260427],[-0.49382598035723646,0.3196301306446808],[-0.5004017732396782,0.3209060871644662],[-0.5064018389539913,0.32230255123055357],[-0.5117651155277989,0.32382712768809785],[-0.5164305409887215,0.3254874213822543],[-0.5203370533643845,0.32729103715817753],[-0.5234235906824085,0.3292455798610229],[-0.5256290909704173,0.33135865433594514],[-0.5268924922560339,0.33363786542809926],[-0.5271527325668803,0.33609081798264034],[-0.5263487499305788,0.3387251168447233],[-0.5244194823747528,0.34154836685950307],[-0.5217898194571944,0.343939115680597],[-0.5183859779612812,0.34616665282490316],[-0.5142363080884729,0.34822688337579977],[-0.5093691600402317,0.35011571241666484],[-0.5038128840180178,0.3518290450308764],[-0.4975958302232919,0.3533627863018127],[-0.49074634885751633,0.35471284131285163],[-0.48329279012215065,0.3558751151473715],[-0.4752635042186557,0.35684551288875027],[-0.4666868413484935,0.35761993962036587],[-0.45759115171312326,0.35819430042559663],[-0.4480047855140066,0.3585645003878207],[-0.4379560929526052,0.3587264445904158],[-0.42747342423037993,0.3586760381167603],[-0.4165851295487901,0.3584091860502323],[-0.4053195591092982,0.35792179347420977],[-0.3969624285683968,0.3574587754018891],[-0.3886380097984117,0.3569694328655705],[-0.38034412201461554,0.35645552082952026],[-0.37207858443227937,0.3559187942580052],[-0.3638392162666775,0.3553610081152917],[-0.35562383673307996,0.3547839173656463],[-0.3474302650467609,0.3541892769733356],[-0.33925632042299125,0.35357884190262595],[-0.33109982207704336,0.35295436711778416],[-0.3229585892241911,0.3523176075830766],[-0.3148304410797036,0.35167031826276984],[-0.30671319685885634,0.3510142541211304],[-0.29860467577691896,0.3503511701224248],[-0.2905026970491662,0.3496828212309196],[-0.28240507989086816,0.34901096241088136],[-0.2743096435172976,0.34833734862657656],[-0.24888932633815175,0.3461657753427699],[-0.22342757424917847,0.3439936170708743],[-0.19791784489619357,0.341820288822801],[-0.17235359592501487,0.3396452056104613],[-0.1467282849814593,0.33746778244576614],[-0.12103536971134332,0.3352874343406267],[-0.095268307760483,0.3331035763069543],[-0.0694205567746955,0.3309156233566599],[-0.04348557439979772,0.32872299050165477],[-0.017456818281606168,0.32652509275385005],[0.008672253934062013,0.32432134512515687],[0.03490818460139122,0.3221111626274864],[0.061257516074563645,0.31989396027274986],[0.08772679070776279,0.31766915307285826],[0.11432255085517218,0.31543615603972286],[0.14105133887097487,0.3131943841852548]],[[-0.6048119305789355,-0.18160258107380967],[-0.638790010493937,-0.18295712099352957],[-0.6730036151595373,-0.18547520222196212],[-0.7071997735473143,-0.18908487122417905],[-0.7411255146288498,-0.1937141744652524],[-0.7745278673757232,-0.19929115841025424],[-0.807153860759513,-0.20574386952425672],[-0.8387505237517998,-0.2130003542723321],[-0.8690648853241627,-0.22098865911955234],[-0.8978439744481821,-0.22963683053098938],[-0.9248348200954384,-0.2388729149717156],[-0.9497844512375093,-0.2486249589068027],[-0.9724398968459753,-0.2588210088013232],[-0.9925481858924181,-0.26938911112034913],[-1.0098563473484141,-0.2802573123289521],[-1.0241114101855455,-0.29135365889220466],[-1.0350604033753905,-0.3026061972751788],[-1.043573096560206,-0.31566254643010594],[-1.0479619258248252,-0.32873410527534286],[-1.0483250264819972,-0.34176120502582774],[-1.044760533844471,-0.3546841768964981],[-1.0373665832249976,-0.3674433521022922],[-1.0262413099363252,-0.37997906185814756],[-1.0114828492912027,-0.3922316373790017],[-0.993189336602379,-0.4041414098797931],[-0.9714589071826047,-0.41564871057545905],[-0.9463896963446277,-0.4266938706809378],[-0.9180798394011984,-0.4372172214111669],[-0.8866274716650655,-0.44715909398108444],[-0.8521307284489774,-0.45645981960562776],[-0.8146877450656849,-0.46505972949973495],[-0.7743966568279363,-0.47289915487834433],[-0.731355599048481,-0.479918426956393],[-0.6871514560808865,-0.48583051157828816],[-0.6417893164228508,-0.4906931275687958],[-0.5955068856097003,-0.4945144647611597],[-0.548541869176761,-0.4973027129886236],[-0.5011319726593575,-0.4990660620844314],[-0.45351490159281704,-0.499812701881827],[-0.40592836151246514,-0.4995508222140541],[-0.358610057953628,-0.49828861291435667],[-0.3117976964516318,-0.4960342638159785],[-0.265728982541801,-0.49279596475216314],[-0.22064162175946356,-0.4885819055561549],[-0.17677331963994458,-0.48340027606119707],[-0.1343617817185696,-0.47725926610053415],[-0.09364471353066484,-0.4701670655074095],[-0.05485982061155692,-0.4621318641150671],[-0.018244808496570508,-0.4531618517567504],[0.011362978823998171,-0.44463701533404487],[0.03871147316660695,-0.4354499723947668],[0.06370472000323235,-0.425696660985487],[0.08624676480585536,-0.4154730191527759],[0.10624165304645383,-0.4048749849432043],[0.12359343019700564,-0.39399849640334283],[0.13820614172948975,-0.38293949157976137],[0.14998383311588404,-0.37179390851903094],[0.15883054982816813,-0.360657685267722],[0.16465033733831946,-0.3496267598724052],[0.16734724111831745,-0.338797070379651],[0.16682530664013995,-0.3282645548360301],[0.16298857937576594,-0.3181251512881128],[0.1557411047971735,-0.30847479778246967],[0.1449869283763412,-0.2994094323656714],[0.13063009558524774,-0.2910249930842884],[0.1164106522320032,-0.29274719801784754],[0.10222173986494809,-0.29446940295140667],[0.08805899691462482,-0.2961916078849657],[0.07391806181158,-0.297913812818525],[0.05979457298635715,-0.2996360177520839],[0.04568416886950066,-0.30135822268564316],[0.0315824878915556,-0.30308042761920184],[0.017485168483065472,-0.3048026325527612],[0.0033878490745762324,-0.3065248374863203],[-0.010713831903369275,-0.30824704241987944],[-0.02482423602022532,-0.30996924735343845],[-0.038947724845448395,-0.3116914522869976],[-0.05308865994849343,-0.3134136572205569],[-0.06725140289881582,-0.3151358621541158],[-0.08144031526587181,-0.31685806708767483],[-0.09565975861911591,-0.31858027202123396],[-0.11938669645715572,-0.3214299439980265],[-0.14311363429519552,-0.32428663583188533],[-0.16684057213323578,-0.3271480075704549],[-0.19056750997127536,-0.33001171926137984],[-0.21429444780931517,-0.33287543095230465],[-0.23802138564735476,-0.33573680269087425],[-0.26174832348539456,-0.338593494524733],[-0.2854752613234346,-0.34144316650152573],[-0.3092021991614744,-0.34428347866889675],[-0.332929136999514,-0.3471120910744909],[-0.3566560748375538,-0.34992666376595294],[-0.3803830126755938,-0.352724856790927],[-0.40410995051363363,-0.3555043301970585],[-0.42783688835167344,-0.3582627440319913],[-0.45156382618971325,-0.36099775834337033],[-0.47529076402775283,-0.36370703317884034],[-0.48938735650800025,-0.3651674559426412],[-0.5026465276527872,-0.366255241293848],[-0.5150682774621138,-0.3669721441967275],[-0.5266526059359802,-0.3673199196155459],[-0.5373995130743867,-0.36730032251456946],[-0.5473089988773328,-0.366915107858065],[-0.5563810633448185,-0.3661660306102993],[-0.564615706476844,-0.3650548457355386],[-0.5720129282734092,-0.3635833081980494],[-0.5785727287345146,-0.36175317296209863],[-0.584295107860159,-0.3595661949919523],[-0.5891800656503436,-0.3570241292518771],[-0.5932276021050686,-0.3541287307061398],[-0.5964377172243327,-0.3508817543190067],[-0.5988104110081369,-0.34728495505474455],[-0.6003456834564804,-0.3433400878776196],[-0.6008697987193861,-0.34124349056719994],[-0.6013284904404583,-0.33914689325678005],[-0.6017261201891531,-0.3370502959463604],[-0.6020670495349265,-0.3349536986359405],[-0.6023556400472336,-0.3328571013255208],[-0.6025962532955298,-0.3307605040151008],[-0.6027932508492713,-0.32866390670468126],[-0.6029509942779121,-0.3265673093942614],[-0.6030738451509097,-0.3244707120838416],[-0.6031661650377182,-0.32237411477342204],[-0.603232315507793,-0.32027751746300226],[-0.6032766581305915,-0.31818092015258237],[-0.6033035544755669,-0.3160843228421627],[-0.6033173661121758,-0.31398772553174303],[-0.6033224546098739,-0.31189112822132314],[-0.6033231815381168,-0.3097945309109035],[-0.6035852391695693,-0.30171672288608986],[-0.6038145850301058,-0.29365587951585326],[-0.6040133999044528,-0.2856102458359264],[-0.6041838645773401,-0.2775780668820429],[-0.6043281598334937,-0.2695575876899362],[-0.6044484664576419,-0.2615470532953398],[-0.6045469652345123,-0.2535447087339875],[-0.6046258369488329,-0.24554879904161242],[-0.6046872623853314,-0.237557569253948],[-0.604733422328736,-0.22956926440672776],[-0.6047664975637737,-0.22158212953568535],[-0.6047886688751725,-0.21359440967655396],[-0.6048021170476601,-0.20560434986506748],[-0.6048090228659653,-0.19761019513695866],[-0.604811567114814,-0.1896101905279617],[-0.6048119305789355,-0.18160258107380967]],[[-0.415740802395026,-0.03743655649066013],[-0.3497037331254522,-0.04401669751001602],[-0.2838934654675658,-0.05057928888670671],[-0.2182925531435438,-0.057125500596909684],[-0.1528835498755654,-0.06365650261680256],[-0.08764900938580822,-0.07017346492256327],[-0.022571485396448487,-0.07667755749036931],[0.04236646837033353,-0.08316995029639862],[0.10718229819236158,-0.08965181331682859],[0.1718934503474563,-0.09612431652783704],[0.23651737111344096,-0.10258862990560169],[0.301071506768137,-0.10904592342630015],[0.3655733035893671,-0.11549736706611025],[0.43004020785495267,-0.12194413080120958],[0.4944896658427166,-0.12838738460777588],[0.5589391238304803,-0.13482829846198674],[0.6234060280960663,-0.14126804234001988],[0.6234060280960663,-0.11868145723369239],[0.6234060280960658,-0.09614284115065053],[0.6234060280960668,-0.07364400425764972],[0.6234060280960663,-0.05117675672144684],[0.6234060280960663,-0.028732908708797522],[0.6234060280960663,-0.0063042703864581995],[0.6234060280960663,0.01611734807881482],[0.6234060280960663,0.038540136520265444],[0.6234060280960663,0.060972284771137863],[0.6234060280960663,0.0834219826646756],[0.6234060280960663,0.10589742003412239],[0.6234060280960663,0.1284067867127222],[0.6234060280960663,0.15095827253371885],[0.6234060280960663,0.17356006733035617],[0.6234060280960663,0.19622036093587802],[0.6234060280960663,0.2189473431835281],[0.5579087030466132,0.20273030338457249],[0.49259674469902026,0.18657176239450146],[0.42744616442128125,0.17046470035624872],[0.36243297358139126,0.15440209741274824],[0.2975331835473448,0.13837693370693382],[0.23272280568713688,0.12238218938173928],[0.16797785136876153,0.10641084458009853],[0.10327433196021318,0.09045587944494549],[0.03858825882948791,0.07451027411921401],[-0.026104356655421324,0.058567008745837756],[-0.09082750312651933,0.042619063467750795],[-0.1556051692158109,0.026659418427886994],[-0.22046134355530222,0.010681053769180049],[-0.2854200147769981,-0.005323050365436011],[-0.3505051715129044,-0.021359913833027155],[-0.415740802395026,-0.03743655649066013]],[[0.05917014162597467,-0.24749563940128771],[0.03863696302174069,-0.23903232422592535],[0.015214244653223519,-0.23089367743987232],[-0.010777438124595973,-0.22312357314979137],[-0.03901750995673714,-0.21576588546234576],[-0.06918539548821911,-0.20886448848419925],[-0.10096051936406081,-0.20246325632201512],[-0.13402230622928202,-0.19660606308245654],[-0.16805018072890077,-0.19133678287218692],[-0.2027235675079373,-0.18669928979786987],[-0.2377218912114092,-0.18273745796616836],[-0.2727245764843378,-0.179495161483746],[-0.3074110479717407,-0.1770162744572662],[-0.3414607303186368,-0.17534467099339224],[-0.37455304817004675,-0.1745242251987874],[-0.406367426170988,-0.1745988111801151],[-0.4365832889664809,-0.17561230304403874],[-0.4365832889664809,-0.18369976337231808],[-0.4365832889664809,-0.19179073362913068],[-0.4365832889664809,-0.19988872374300926],[-0.4365832889664809,-0.20799724364248684],[-0.4365832889664809,-0.21611980325609692],[-0.4365832889664809,-0.2242599125123722],[-0.4365832889664809,-0.23242108133984618],[-0.4365832889664809,-0.24060681966705155],[-0.4365832889664809,-0.24882063742252125],[-0.4365832889664809,-0.25706604453478865],[-0.4365832889664809,-0.2653465509323869],[-0.4365832889664809,-0.27366566654384883],[-0.4365832889664809,-0.28202690129770736],[-0.4365832889664809,-0.2904337651224961],[-0.4365832889664809,-0.2988897679467477],[-0.4365832889664809,-0.3073984196989954],[-0.4048626847088328,-0.3035886847703936],[-0.3733318087225008,-0.2997959144963682],[-0.34197103394493267,-0.29601835391265285],[-0.31076073331358156,-0.29225424805498124],[-0.2796812797658954,-0.2885018419590861],[-0.248713046239325,-0.2847593806607015],[-0.21783640567132112,-0.2810251091955609],[-0.18703173099933235,-0.2772972725993974],[-0.15627939516081035,-0.27357411590794467],[-0.12555977109320526,-0.2698538841569361],[-0.09485323173396631,-0.2661348223821053],[-0.06414015002054407,-0.2624151756191855],[-0.03340089889038822,-0.25869318890391046],[-0.002615851280949766,-0.25496710727201355],[0.02823461987032072,-0.25123517575922816],[0.05917014162597467,-0.24749563940128771]],[[-0.43360579088484386,-0.12249850451340472],[-0.37997411553913896,-0.12353286095249716],[-0.32793659382942675,-0.12528850770513533],[-0.27748232183206967,-0.12776602975940776],[-0.22860039562342727,-0.13096601210340375],[-0.18127991127986265,-0.1348890397252116],[-0.13550996487773603,-0.13953569761292084],[-0.09127965249340808,-0.14490657075461955],[-0.04857807020324145,-0.15100224413839736],[-0.007394314083595477,-0.15782330275234235],[0.03228251978916674,-0.16537033158454395],[0.07046333533868565,-0.1736439156230909],[0.10715903648859859,-0.1826446398560717],[0.14238052716254557,-0.1923730892715756],[0.1761387112841648,-0.20282984885769118],[0.20844449277709542,-0.21401550360250743],[0.23930877556497543,-0.2259306384941132],[0.25883479508910523,-0.22353871969684147],[0.2783477299048681,-0.22115323576854728],[0.29786938785954165,-0.21877126176878614],[0.3174215768004043,-0.21638987275711363],[0.3370261045747335,-0.2140061437930859],[0.3567047790298066,-0.21161714993625858],[0.3764794080129007,-0.20921996624618744],[0.39637179937129363,-0.2068116677824281],[0.4164037609522637,-0.2043893296045366],[0.4365971006030883,-0.20195002677206864],[0.456973626171045,-0.19949083434457993],[0.4775551455034106,-0.19700882738162628],[0.49836346644746365,-0.19450108094276342],[0.5194203968504811,-0.19196467008754703],[0.540747744559741,-0.18939666987553327],[0.5623673174225213,-0.18679415536627753],[0.49863097604073525,-0.18029347522898964],[0.4352479217848466,-0.17381911955569984],[0.37218762366866653,-0.16736933338214155],[0.3094195507060067,-0.1609423617440482],[0.24691317191067785,-0.15453644967715308],[0.1846379562964917,-0.14814984221718996],[0.12256337287726016,-0.1417807843998924],[0.06065889066679331,-0.13542752126099333],[-0.0011060213210967174,-0.12908829783622666],[-0.06276189407259869,-0.12276135916132569],[-0.12433925857390138,-0.11644495027202395],[-0.1858686458111931,-0.11013731620405487],[-0.24738058677066244,-0.10383670199315198],[-0.30890561243849923,-0.09754135267504849],[-0.3704742538008903,-0.09124951328547837],[-0.4321170418440259,-0.08495942886017471],[-0.4323790994754786,-0.08748257998537712],[-0.4326084453360153,-0.08996302698009384],[-0.43280726021036187,-0.09240486476094678],[-0.43297772488324915,-0.09481218824455806],[-0.4331220201394026,-0.09718909234754924],[-0.4332423267635508,-0.09953967198654257],[-0.4333408255404212,-0.10186802207815959],[-0.4334196972547417,-0.10417823753902256],[-0.4334811226912403,-0.10647441328575313],[-0.4335272826346448,-0.10876064423497345],[-0.4335603578696825,-0.1110410253033054],[-0.4335825291810813,-0.11331965140737066],[-0.4335959773535689,-0.11560061746379136],[-0.4336028831718741,-0.11788801838918939],[-0.43360542742072283,-0.12018594910018643],[-0.43360579088484386,-0.12249850451340472]]]],"source":{"artist":"Major Alexey","license":"CC BY-SA 4.0","url":"https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg","source_sha256":"53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59","adaptation":"curve sampling and metric scaling"}},{"id":"letter_A_v2","label":"Буква А","polygons":[[[[1.1099999999999999,0.4143822677308887],[-0.01551422985770234,0.6113472579559865],[0.01551422985770234,0.7886527420440134],[4.015514229857702,0.08865274204401337],[4.015514229857702,-0.08865274204401337],[0.01551422985770234,-0.7886527420440134],[-0.01551422985770234,-0.6113472579559865],[1.1099999999999999,-0.4143822677308887],[1.1099999999999999,0.4143822677308887]],[[1.29,-0.3828822677308887],[3.4778986727479357,0.0],[1.29,0.3828822677308887],[1.29,-0.3828822677308887]]]],"source":{"path":"simulation/urban-plan-research/systematic/paint_templates.py","sha256":"97752930ba92ceb2e8f4f34f16857e88dda5799449ed3a8cd01a25976f2e2bdd","dimensions_m":[4.0,1.4],"stroke_m":0.18,"compliance":"not-assessed"},"hidden":true},{"id":"letter_A_v3","label":"Буква А","polygons":[[[[0.0,-0.7],[3.0,-0.125],[3.0,0.125],[0.0,0.7],[0.0,0.45],[0.4,0.375],[0.4,-0.375],[0.0,-0.45],[0.0,-0.7]],[[1.0,-0.25],[2.2,0.0],[1.0,0.25],[1.0,-0.25]]]],"source":{"kind":"road-marking-artwork","standard":"GOST R 51256-2018","figure":"B.11","marking":"1.23.1","dimensions_m":[3,1.4],"top_width_m":0.25,"foot_width_m":0.25,"crossbar_bottom_m":0.4,"crossbar_height_m":0.6,"url":"https://www.mos.ru/upload/documents/files/1106/GOSTR51256-2018TehnicheskiesredstvaorganizaciidorojnogodvijeniyaR_.pdf","adaptation":"Dimensioned silhouette; undimensioned inner slopes traced from figure. Longitudinal axis +X.","compliance":"artwork-reference-not-survey-certification"}},{"id":"straight_right_arrow","label":"Прямо и направо","polygons":[[[[1.9500000000000002,-0.675],[2.75,-0.675],[1.4500000000000002,-0.9750000000000001],[0.25,-0.675],[0.9500000000000002,-0.675],[0.3500000000000001,-0.075],[0.0,-0.075],[0.0,0.075],[1.2000000000000002,0.075],[2.95,0.075],[2.95,0.375],[5.0,0.0],[2.95,-0.375],[2.95,-0.075],[1.35,-0.075],[1.9500000000000002,-0.675]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short"}},{"id":"straight_left_arrow","label":"Прямо и налево","polygons":[[[[1.9500000000000002,0.675],[2.75,0.675],[1.4500000000000002,0.9750000000000001],[0.25,0.675],[0.9500000000000002,0.675],[0.3500000000000001,0.075],[0.0,0.075],[0.0,-0.075],[1.2000000000000002,-0.075],[2.95,-0.075],[2.95,-0.375],[5.0,0.0],[2.95,0.375],[2.95,0.075],[1.35,0.075],[1.9500000000000002,0.675]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short"}},{"id":"bicycle_compact","label":"Велосипед · компактный","polygons":[[[[0.24989713965367355,0.23731752914149185],[0.24405228765771764,0.23821987326853494],[0.23838817909999815,0.23912631231219994],[0.23289015910714567,0.24003158137968728],[0.22754357280578846,0.24093041557819728],[0.22233376532255655,0.2418175500149305],[0.21724608178407925,0.24268771979708714],[0.21226586731698566,0.2435356600318676],[0.20737846704790625,0.24435610582647244],[0.20256922610346928,0.245143792288102],[0.19782348961030502,0.2458934545239566],[0.19312660269504242,0.24659982764123667],[0.18846391048431135,0.24725764674714268],[0.18382075810474066,0.24786164694887491],[0.1791824906829605,0.24840656335363387],[0.17453445334559953,0.24888713106861987],[0.16986199121928797,0.2492980852010333],[0.16821535336417995,0.24936584632132452],[0.16641972429647103,0.24927858559807187],[0.16450197128400784,0.24904975775731863],[0.16248896159463588,0.24869281752510852],[0.16040756249620142,0.2482212196274849],[0.15828464125655034,0.24764841879049104],[0.15614706514352858,0.2469878697401704],[0.1540217014249825,0.24625302720256648],[0.15193541736875776,0.2454573459037228],[0.1499150802427006,0.24461428056968265],[0.1479875573146569,0.24373728592648947],[0.14617971585247255,0.24283981670018673],[0.14451842312399407,0.2419353276168179],[0.14303054639706692,0.24103727340242626],[0.14174295293953754,0.24015910878305546],[0.14068251001925156,0.23931428848474878],[0.12809824813201195,0.22862577611743573],[0.11472872928000055,0.21842631379239713],[0.10057028974487389,0.20871824146198803],[0.08561926580829024,0.19950389907856397],[0.06987199375190589,0.19078562659448028],[0.053324809857378995,0.18256576396209234],[0.035974050406366906,0.17484665113375564],[0.01781605168052671,0.16763062806182544],[-0.001152850038483848,0.16092003469865712],[-0.020936318469008165,0.15471721099660607],[-0.041538017329388256,0.14902449690802766],[-0.06296161033796702,0.14384423238527738],[-0.08521076121308697,0.1391787573807105],[-0.1082891336730905,0.13503041184668235],[-0.1322003914363205,0.13140153573554847],[-0.15694819822112,0.12829446899966407],[-0.20406687274597793,0.1243230823625116],[-0.25080452056320135,0.12282444037690593],[-0.2968582742897993,0.12369734010347727],[-0.3419252665427794,0.12684057860285503],[-0.38570262993915083,0.1321529529356696],[-0.4278874970959222,0.13953326016255047],[-0.4681770006301019,0.14888029734412728],[-0.5062682731586985,0.16009286154103053],[-0.5418584472987208,0.17306974981388945],[-0.5746446556671769,0.18770975922333427],[-0.6043240308810751,0.20391168682999472],[-0.6305937055574252,0.22157432969450053],[-0.6531508123132345,0.24059648487748175],[-0.6716924837655122,0.2608769494395681],[-0.6859158525312662,0.2823145204413894],[-0.695518051227506,0.3048079949435757],[-0.7,0.32744089160693657],[-0.6995237166154573,0.34972338040507944],[-0.6943090241744353,0.3715203290894812],[-0.6845757457774925,0.3926966054116185],[-0.670543704525187,0.4131170771229683],[-0.6524327235180771,0.43264661197500753],[-0.6304626258567216,0.451150077719213],[-0.6048532346416786,0.4684923421070616],[-0.5758243729735062,0.48453827289002993],[-0.5435958639527628,0.4991527378195952],[-0.5083875306800067,0.512200604647234],[-0.47041919625579653,0.5235467411244233],[-0.42991068378069003,0.53305601500264],[-0.38708181635524613,0.5405932940333609],[-0.34215241708002253,0.5460234459680627],[-0.29534230905557807,0.5492113385582225],[-0.2429985615543937,0.55],[-0.19216060229203422,0.5479766236987007],[-0.143142289806518,0.5432962314978682],[-0.09625748263586534,0.5361138452410467],[-0.051820039318095215,0.5265844867717796],[-0.01014381839122649,0.5148631779336111],[0.028457321606720386,0.5011049405700851],[0.06366952213772707,0.48546479652474533],[0.09517892466377346,0.46809776764113575],[0.12267167064684086,0.4491588757628001],[0.14583390154890927,0.42880314273328246],[0.16435175883195977,0.40718559039612645],[0.17791138395797282,0.38446124059487613],[0.18619891838892894,0.36078511517307543],[0.18890050358680888,0.33631223597426796],[0.18570228101359354,0.31119762484199787],[0.185555325200072,0.31044396518753614],[0.18542546673881638,0.3096797757474752],[0.18531026315093097,0.3089038865456374],[0.1852072719575213,0.30811512760584503],[0.18511405067969208,0.3073123289519203],[0.18502815683854812,0.30649432060768567],[0.1849471479551941,0.30565993259696334],[0.1848685815507351,0.3048079949435757],[0.18479001514627666,0.30393733767134506],[0.18470900626292264,0.30304679080409364],[0.1846231124217786,0.3021351843656438],[0.18452989114394922,0.30120134837981793],[0.1844268999505395,0.3002441128704382],[0.18431169636265438,0.299262307861327],[0.18418183790139875,0.29825476337630663],[0.18403488208787722,0.2972203094391994],[0.19997918077513205,0.29490346411332957],[0.21592225822293942,0.2925942236326148],[0.23186289319185147,0.2902908330327884],[0.24779986444242114,0.2879915373495838],[0.2637319507352005,0.28569458161873473],[0.2796579308307418,0.2833982108759744],[0.29557658348959853,0.28110067015703655],[0.31148668747232167,0.2788002044976544],[0.32738702153946514,0.2764950589335614],[0.34327636445158044,0.27418347850049113],[0.3591534949692202,0.27186370823417705],[0.37501719185293697,0.26953399317035265],[0.39086623386328323,0.2671925783447513],[0.4066993997608114,0.26483770879310664],[0.4225154683060738,0.2624676295511519],[0.4383132182596231,0.26008058565462067],[0.44878616068196325,0.2584941954556884],[0.45925666062540815,0.25688031081658047],[0.469722275611063,0.2552395167253855],[0.4801805631600325,0.25357239817019267],[0.49062908079342166,0.2518795401390906],[0.5010653860323353,0.25016152762016824],[0.5114870363978784,0.2484189456015144],[0.5218915894111561,0.24665237907121784],[0.5322766025932726,0.24486241301736766],[0.5426396334653336,0.24304963242805233],[0.5529782395484437,0.2412146222913611],[0.5632899783637079,0.23935796759538258],[0.5735724074322305,0.23748025332820538],[0.5838230842751171,0.23558206447791896],[0.5940395664134724,0.23366398603261163],[0.6042194113684016,0.23172660298037245],[0.6148857167032699,0.22951749296086493],[0.6249902518922668,0.22708257753906325],[0.634518362062022,0.22442068673878973],[0.6434553923391648,0.22153065058386673],[0.6517866878503249,0.21841129909811674],[0.6594975937221313,0.21506146230536188],[0.6665734550812138,0.21147997022942439],[0.6729996170542016,0.20766565289412658],[0.6787614247677245,0.20361734032329087],[0.6838442233484117,0.19933386254073976],[0.6882333579228926,0.19481404957029524],[0.6919141736177968,0.19005673143577956],[0.6948720155597535,0.18506073816101537],[0.6970922288753926,0.1798248997698249],[0.698560158691343,0.17434804628603023],[0.6992611501342345,0.1686290077334538],[0.6995359290099323,0.1636822509561674],[0.6997398759976726,0.15872554938137057],[0.6998803185341405,0.1537583180209745],[0.699964584056021,0.14877997188689057],[0.7,0.14378992599102958],[0.6999938938027623,0.13878759534530294],[0.6999535929009932,0.13377239496162158],[0.6998864247313783,0.1287437398518968],[0.6997997167306025,0.12370104502803997],[0.6997007963353512,0.11864372550196178],[0.6995969909823097,0.11357119628557377],[0.6994956281081633,0.1084828723907868],[0.6994040351495975,0.10337816882951234],[0.699329539543297,0.0982565006136612],[0.6992794687259477,0.09311728275514503],[0.6992611501342345,0.08795993026587434],[0.6945416702891923,0.08795993026587434],[0.6897599072323253,0.08795993026587445],[0.684912197245291,0.08795993026587434],[0.6799948766097462,0.08795993026587434],[0.6750042816073488,0.08795993026587434],[0.6699367485197559,0.08795993026587434],[0.6647886136286252,0.08795993026587445],[0.6595562132156136,0.08795993026587429],[0.6542358835623787,0.08795993026587434],[0.6488239609505778,0.08795993026587434],[0.6433167816618686,0.08795993026587434],[0.6377106819779078,0.08795993026587434],[0.6320019981803533,0.08795993026587434],[0.6261870665508621,0.08795993026587434],[0.6202622233710918,0.08795993026587434],[0.6142238049226998,0.08795993026587434],[0.6142238049226998,0.08982740724149657],[0.6142238049226998,0.09168669438387494],[0.6142238049226998,0.09353896166918729],[0.6142238049226998,0.09538537907361105],[0.6142238049226998,0.09722711657332411],[0.6142238049226998,0.09906534414450407],[0.6142238049226998,0.10090123176332866],[0.6142238049226998,0.10273594940597564],[0.6142238049226998,0.10457066704862245],[0.6142238049226998,0.10640655466744703],[0.6142238049227,0.10824478223862705],[0.6142238049227,0.1100865197383401],[0.6142238049226998,0.11193293714276398],[0.6142238049227,0.11378520442807616],[0.6142238049226998,0.11564449157045453],[0.6142238049226998,0.11751196854607676],[0.6142238049226998,0.11871002415203097],[0.6142238049226998,0.11990807975798506],[0.6142238049226998,0.12110613536393916],[0.6142238049226998,0.12230419096989337],[0.6142238049226998,0.12350224657584746],[0.6142238049226998,0.12470030218180167],[0.6142238049226998,0.12589835778775577],[0.6142238049226998,0.12709641339370986],[0.6142238049226998,0.12829446899966407],[0.6142238049226998,0.12949252460561828],[0.6142238049227,0.13069058021157243],[0.6142238049227,0.13188863581752652],[0.6142238049226998,0.13308669142348073],[0.6142238049227,0.13428474702943483],[0.6142238049226998,0.13548280263538903],[0.6142238049226998,0.13668085824134324],[0.613924397718143,0.1446376712297806],[0.6132744947921405,0.1517766708700129],[0.6121776182283363,0.1581598658994578],[0.6105372901103738,0.16384926505553266],[0.6082570325218971,0.16890687707565516],[0.6052403675465501,0.17339471069724288],[0.6013908172679767,0.1773747746577134],[0.5966119037698208,0.1809090776944839],[0.5908071491357259,0.18405962854497238],[0.583880075449336,0.18688843594659627],[0.5757342047942952,0.18945750863677302],[0.5662730592542472,0.19182885535292016],[0.5554001609128357,0.19406448483245542],[0.5430190318537047,0.1962264058127962],[0.5290331941604979,0.19837662703136005],[0.5133461699168596,0.20057715722556463],[0.5095841417986937,0.20109691914250322],[0.5057989101310243,0.2016090762142867],[0.5019868111955088,0.20211538340518204],[0.4981441812738048,0.2026175956794552],[0.4942673566475696,0.20311746800137315],[0.4903526735984605,0.20361675533520218],[0.4863964684081347,0.20411721264520882],[0.4823950773582495,0.2046205948956598],[0.4783448367304626,0.2051286570508215],[0.4742420828064313,0.20564315407496053],[0.4700831518678127,0.20616584093234336],[0.46586438019626464,0.20669847258723661],[0.461582104073444,0.20724280400390666],[0.45723265978100824,0.20780059014662028],[0.45281238360061493,0.20837358597964367],[0.44831761181392116,0.20896354646724363],[0.4481521338687789,0.20799919360278302],[0.44797077981081806,0.20705180539289886],[0.44777721335838205,0.20611962687332464],[0.44757509822981306,0.20520090307979377],[0.4473680981434541,0.20429387904803997],[0.4471598768176473,0.20339679981379655],[0.44695409797073593,0.2025079104127968],[0.4467544253210621,0.2016254558807743],[0.4465645225869685,0.20074768125346276],[0.4463880534867982,0.1998728315665954],[0.4462286817388934,0.19899915185590578],[0.4460900710615969,0.19812488715712723],[0.4459758851732515,0.1972482825059932],[0.44588978779219934,0.19636758293823736],[0.4458354426367836,0.19548103348959306],[0.44581651342534656,0.19458687919579387],[0.4458163098854387,0.17324202880605438],[0.44581488510608314,0.15188898858307104],[0.44581101784783267,0.13052892850302178],[0.44580348687123933,0.10916301854208382],[0.44579107093685605,0.08779242867643516],[0.445772548805235,0.06641832888225341],[0.44574669923692845,0.045041889135716384],[0.4457123009924894,0.023664279413001754],[0.4456681328324697,0.002286669690286902],[0.4456129735174222,-0.019089770056250233],[0.44554560180789926,-0.040463869850432044],[0.4454647964644532,-0.06183445971608048],[0.44536933624763686,-0.08320036967701838],[0.4452579999180023,-0.10456042975706781],[0.44512956623610184,-0.12591346998005104],[0.4449828139624884,-0.14725832036979047],[0.4450442830146815,-0.14908358070500116],[0.4452400884061049,-0.15081582793408532],[0.4455873274890235,-0.15245564704513215],[0.44610309761570416,-0.15400362302623016],[0.44680449613841144,-0.15546034086546867],[0.4477086204094114,-0.1568263855509361],[0.4488325677809698,-0.15810234207072127],[0.45019343560535185,-0.15928879541291352],[0.451808321234824,-0.16038633056560092],[0.45369432202165105,-0.16139553251687322],[0.455868535318099,-0.1623169862548186],[0.45834805847643373,-0.16315127676752594],[0.46114998884892044,-0.16389898904308442],[0.4642914237878248,-0.16456070806958278],[0.46778946064541305,-0.16513701883510967],[0.47166119677395024,-0.16562850632775417],[0.47509165838210743,-0.16602571324007975],[0.47850990759578893,-0.16646620927097988],[0.4819232718516807,-0.1669464844919215],[0.4853390785864672,-0.16746302897437138],[0.4887646552368342,-0.16801233278979677],[0.492207329239467,-0.1685908860096642],[0.49567442803105033,-0.16919517870544087],[0.4991732790482704,-0.1698217009485936],[0.5027112097278115,-0.17046694281058938],[0.5062955475063595,-0.17112739436289526],[0.5099336198205996,-0.17179954567697786],[0.5136327541072169,-0.17247988682430448],[0.5174002778028967,-0.17316490787634164],[0.5212435183443246,-0.17385109890455663],[0.5251698031681855,-0.1745349499804162],[0.529186459711165,-0.17521295117538738],[0.5308966020175452,-0.1715485857868636],[0.5325896469716602,-0.16789358020776113],[0.5342680370524044,-0.1642479344380805],[0.5359342147386734,-0.16061164847782095],[0.5375906225093617,-0.15698472232698335],[0.5392397028433649,-0.15336715598556705],[0.5408838982195779,-0.14975894945357238],[0.5425256511168958,-0.1461601027309991],[0.5441674040142136,-0.14257061581784747],[0.5458115993904267,-0.13899048871411745],[0.5474606797244298,-0.13541972141980874],[0.5491170874951183,-0.13185831393492164],[0.5507832651813871,-0.12830626625945585],[0.5524616552621313,-0.12476357839341179],[0.5541547002162461,-0.12123025033678914],[0.5558648425226267,-0.117706282089588],[0.5568035685779736,-0.11583900010999548],[0.5577471795911111,-0.11398107793982437],[0.558700560519829,-0.11213251557907489],[0.5596685963219169,-0.11029331302774681],[0.5606561719551661,-0.10846347028584025],[0.5616681723773661,-0.10664298735335509],[0.5627094825463069,-0.1048318642302919],[0.5637849874197792,-0.10303010091664977],[0.5648995719555729,-0.10123769741242927],[0.5660581211114786,-0.09945465371763029],[0.5672655198452858,-0.09768096983225294],[0.5685266531147851,-0.09591664575629699],[0.5698464058777667,-0.09416168148976256],[0.5712296630920207,-0.09241607703264965],[0.5726813097153374,-0.09067983238495825],[0.5742062307055066,-0.08895294754668859],[0.5749450805712719,-0.0882844036591538],[0.5758964261009103,-0.0876293144976622],[0.5770382849843662,-0.08699177497883626],[0.578348674911583,-0.08637588001929764],[0.5798056135725058,-0.0857857245356679],[0.581387118657078,-0.08522540344456941],[0.5830712078552439,-0.08469901166262406],[0.5848358988569485,-0.08421064410645329],[0.5866592093521348,-0.08376439569267957],[0.5885191570307476,-0.08336436133792446],[0.5903937595827311,-0.0830146359588102],[0.5922610346980293,-0.08271931447195835],[0.5940990000665859,-0.08248249179399092],[0.5958856733783461,-0.08230826284153003],[0.5975990723232534,-0.08220072253119737],[0.5992172145912521,-0.08216396577961504],[0.6003568345357206,-0.08223650430263185],[0.6015733925653846,-0.08244476006226054],[0.6028461276096355,-0.08277469334436904],[0.6041542785978653,-0.08321226443482477],[0.6054770844594659,-0.08374343361949599],[0.6067937841238285,-0.0843541611842501],[0.6080836165203451,-0.08503040741495449],[0.6093258205784076,-0.08575813259747755],[0.6104996352274072,-0.08652329701768646],[0.6115842993967363,-0.08731186096144927],[0.6125590520157861,-0.0881097847146336],[0.6134031320139485,-0.08890302856310706],[0.614095778320615,-0.08967755279273759],[0.6146162298651776,-0.09041931768939282],[0.6149437255770278,-0.09111428353894047],[0.6150575043855576,-0.09174841062724826],[0.6152042566591712,-0.10298047442711278],[0.6153326903410714,-0.11421429319124388],[0.615444026670706,-0.12545162188390813],[0.6155394868875224,-0.136694215469372],[0.6156202922309684,-0.14794382891190194],[0.6156876639404913,-0.15920221717576444],[0.615742823255539,-0.17047113522522617],[0.6157869914155584,-0.18175233802455393],[0.6158213896599978,-0.19304758053801374],[0.6158472392283041,-0.2043586177298723],[0.6158657613599253,-0.21568720456439616],[0.6158781772943086,-0.22703509600585192],[0.6158857082709017,-0.23840404701850637],[0.6158895755291522,-0.24979581256662575],[0.6158910003085079,-0.2612121476144762],[0.6158912038484157,-0.27265480712632495],[0.6104471219311629,-0.27265480712632495],[0.6050482258734691,-0.27265480712632517],[0.5996810820414118,-0.27265480712632495],[0.5943322568010674,-0.27265480712632495],[0.5889883165185134,-0.27265480712632495],[0.5836358275598265,-0.27265480712632495],[0.5782613562910838,-0.27265480712632495],[0.572851469078362,-0.27265480712632495],[0.5673927322877386,-0.27265480712632495],[0.5618717122852902,-0.27265480712632495],[0.5562749754370943,-0.27265480712632495],[0.5505890881092272,-0.27265480712632495],[0.5448006166677662,-0.27265480712632495],[0.5388961274787885,-0.27265480712632495],[0.5328621869083707,-0.27265480712632495],[0.5266853613225903,-0.27265480712632495],[0.526712635670252,-0.27032918697912245],[0.5267863171169209,-0.2679959619867649],[0.5268941932681206,-0.265656887113519],[0.5270240517293765,-0.26331371732365116],[0.5271636801062125,-0.260968207581428],[0.5273008660041536,-0.2586221128511158],[0.5274233970287241,-0.2562771880969813],[0.5275190607854484,-0.2539351882832914],[0.5275756448798515,-0.251597868374312],[0.5275809369174574,-0.24926698333430986],[0.5275227245037911,-0.24694428812755154],[0.527388795244377,-0.2446315377183036],[0.5271669367447395,-0.2423304870708327],[0.526844936610403,-0.24004289114940502],[0.5264105824468923,-0.23777050491828744],[0.5258516618597321,-0.2355150833417462],[0.525443360804436,-0.23452430851527262],[0.5248518738320075,-0.2335042842843571],[0.5240894133369229,-0.23246320048224278],[0.5231681917136572,-0.23140924694217424],[0.5221004213566862,-0.23035061349739483],[0.5208983146604849,-0.22929548998114846],[0.519574084019529,-0.22825206622667893],[0.518139941828294,-0.22722853206722982],[0.5166081004812552,-0.22623307733604592],[0.5149907723728882,-0.22527389186636992],[0.5133001698976685,-0.2243591654914463],[0.5115485054500712,-0.22349708804451862],[0.5097479914245726,-0.22269584935883102],[0.5079108402156471,-0.22196363926762686],[0.506049264217771,-0.22130864760415025],[0.5041754758254193,-0.22073906420164513],[0.49714968528368625,-0.21891390136444933],[0.49013610713642874,-0.21733209357221306],[0.48312741394696124,-0.21599364082493622],[0.4761162782785987,-0.21489854312261858],[0.46909537269465573,-0.2140468004652606],[0.462057369758447,-0.21343841285286191],[0.45499494203328766,-0.2130733802854229],[0.44790076208249197,-0.21295170276294317],[0.4407675024693747,-0.213073380285423],[0.43358783575725096,-0.21343841285286191],[0.4263544345094349,-0.2140468004652606],[0.4190599712892415,-0.21489854312261858],[0.41169711865998593,-0.21599364082493622],[0.4042585491849823,-0.21733209357221306],[0.39673693542754535,-0.21891390136444933],[0.38912494995099,-0.22073906420164513],[0.3775193079410509,-0.2236931565522966],[0.3658416128037066,-0.22656944548713165],[0.3540979707361946,-0.22937436587512772],[0.3422944879357529,-0.2321143525852618],[0.33043727059961936,-0.2347958404865117],[0.3185324249250316,-0.23742526444785428],[0.30658605710922693,-0.24000905933826677],[0.29460427334944345,-0.24255366002672707],[0.28259317984291904,-0.24506550138221161],[0.2705588827868912,-0.2475510182736984],[0.2585074883785979,-0.2500166455701647],[0.24644510281527632,-0.2524688181405871],[0.2343778322941648,-0.2549139708539434],[0.22231178301250062,-0.2573585385792111],[0.21025306116752182,-0.25980895618536715],[0.198207772956466,-0.2622716585413889],[0.19450273601251902,-0.2630265856700429],[0.19119460188902432,-0.2637996474294515],[0.18826993695205912,-0.26459961864094694],[0.1857153075677005,-0.26543527412586165],[0.18351728010202523,-0.2663153887055286],[0.18166242092111046,-0.2672487372012805],[0.18013729639103337,-0.26824409443444985],[0.1789284728778706,-0.26931023522636943],[0.17802251674769926,-0.2704559343983721],[0.17740599436659626,-0.27168996677179025],[0.17706547210063878,-0.2730211071679566],[0.17698751631590381,-0.27445813040820366],[0.17715869337846796,-0.2760098113138646],[0.17756556965440903,-0.2776849247062717],[0.178194711509803,-0.27949224540675766],[0.17903268531072772,-0.2814405482366553],[0.18855692822223247,-0.3042099421207466],[0.19316812483625884,-0.32675528556681066],[0.1930335849571209,-0.34894612623103427],[0.18832061838913208,-0.3706520117696056],[0.1791965349366068,-0.3917424898387126],[0.16582864440385842,-0.4120871080945424],[0.14838425659520124,-0.4315554141932826],[0.12703068131494838,-0.45001695579112067],[0.10193522836741428,-0.4673412805442445],[0.07326520755691243,-0.48339793610884185],[0.041187928687757024,-0.4980564701411003],[0.005870701564261562,-0.5111864302972069],[-0.032519164009259874,-0.5226573642333496],[-0.07381435822849416,-0.5323388196057162],[-0.1178475712891266,-0.5401003440704943],[-0.16445149338684384,-0.5458114852838711],[-0.21703602859910243,-0.5494518661607524],[-0.2688560679171974,-0.55],[-0.3195183722390185,-0.5476208534426683],[-0.36862970246245597,-0.5424793931298115],[-0.4157968194853997,-0.5347405857024834],[-0.46062648420574026,-0.5245693978017387],[-0.5027254575213677,-0.5121307960686319],[-0.5417005003301718,-0.4975897471442168],[-0.5771583735300432,-0.48111121766954756],[-0.6087058380188716,-0.4628601742856786],[-0.6359496546945471,-0.44300158363366415],[-0.6584965844549603,-0.42170041235455846],[-0.6759533881980012,-0.3991216270894158],[-0.6879268268215597,-0.37543019447929027],[-0.694023661223526,-0.35079108116523605],[-0.6938506523017903,-0.3253692537883076],[-0.6901985357339033,-0.3078641677157308],[-0.6839781526078272,-0.2908697762447152],[-0.6752591135720711,-0.27442878350574684],[-0.6641110292751462,-0.2585838936293111],[-0.6506035103655616,-0.24337781074589437],[-0.6348061674918279,-0.22885323898598187],[-0.6167886113024557,-0.21505288248005883],[-0.5966204524459543,-0.2020194453586115],[-0.5743713015708348,-0.18979563175212533],[-0.5501107693256065,-0.178424145791086],[-0.5239084663587794,-0.16794769160597944],[-0.4958340033188646,-0.15840897332729076],[-0.46595699085437126,-0.1498506950855062],[-0.43434703961381016,-0.1423155610111111],[-0.40107376024569097,-0.13584627523459125],[-0.36620676339852404,-0.13048554188643224],[-0.362600646849828,-0.12995515268587965],[-0.3592815215713057,-0.12940604386648402],[-0.35624328136571853,-0.12882885561882373],[-0.3534798200358298,-0.1282142281334776],[-0.3509850313844008,-0.12755280160102367],[-0.3487528092141944,-0.12683521621204075],[-0.3467770473279725,-0.1260521121571072],[-0.3450516395284979,-0.12519412962680154],[-0.34357047961853215,-0.12425190881170212],[-0.34232746140083814,-0.12321608990238753],[-0.3413164786781778,-0.12207731308943637],[-0.34053142525331365,-0.1208262185634269],[-0.3399661949290077,-0.11945344651493794],[-0.33961468150802226,-0.11794963713454754],[-0.3394707787931197,-0.11630543061283438],[-0.3395283805870624,-0.11451146714037697],[-0.3397850444109548,-0.11099227629590147],[-0.3399403453607014,-0.10747367043951472],[-0.3400101595491192,-0.1039562345593058],[-0.34001036308902705,-0.10044055364336335],[-0.339956832093243,-0.09692721267977622],[-0.33986544267458524,-0.0934167966566335],[-0.33975207094587134,-0.08990989056202381],[-0.3396325930199196,-0.0864070793840358],[-0.3395228850095488,-0.08290894811075877],[-0.3394388230275758,-0.07941608173028125],[-0.3393962831868193,-0.0759290652306922],[-0.33941114160009833,-0.0724484836000805],[-0.33949927438022914,-0.06897492182653486],[-0.3396765576400312,-0.06550896489814428],[-0.3399588674923224,-0.06205119780299739],[-0.34036208004992047,-0.05860220552918327],[-0.3408222837817375,-0.05299480220356145],[-0.34064377928248774,-0.04755061055472731],[-0.3398326727494093,-0.042264365689881345],[-0.3383950703797394,-0.03713080271622349],[-0.3363370783707161,-0.032144656740955124],[-0.33366480291957734,-0.02730066287127564],[-0.33038435022356055,-0.022593556214385968],[-0.3265018264799032,-0.018018071877486497],[-0.32202333788584336,-0.013568944967777274],[-0.3169549906386186,-0.009240910592459017],[-0.3113028909354674,-0.005028703858732109],[-0.30507314497362653,-0.0009270598737967095],[-0.29827185895033403,0.003069286255146575],[-0.2909051390628275,0.0069655994208974725],[-0.2829790915083449,0.010767144516255267],[-0.27449982248412397,0.01447918643402002],[-0.2551167170524872,0.022495863203549016],[-0.23573605409974513,0.03052189978249975],[-0.21636027610479358,0.03855729617087189],[-0.19699182554652722,0.04660205236866566],[-0.1776331449038413,0.05465616837588083],[-0.15828667665563068,0.06271964419251763],[-0.13895486328079062,0.07079247981857584],[-0.11964014725821655,0.07887467525405556],[-0.10034497106680282,0.08696623049895685],[-0.0810717771854452,0.09506714555327966],[-0.061823008093038326,0.10317742041702399],[-0.04260110626847734,0.11129705509018983],[-0.023408514190657623,0.11942604957277714],[-0.004247674338474195,0.12756440386478596],[0.014878970809177935,0.1357121179662164],[0.033968978773403755,0.14386919187706831],[0.04766904643588466,0.14942891867344915],[0.06126775122421942,0.15502608470751628],[0.07478096925122552,0.16066068997926947],[0.08822457662972175,0.1663327344887085],[0.10161444947252582,0.1720422182358337],[0.11496646389245598,0.177789141220645],[0.12829649600233037,0.18357350344314238],[0.14162042191496688,0.18939530490332585],[0.15495411774318393,0.19525454560119543],[0.16831345959979935,0.2011512255367509],[0.18171432359763143,0.20708534470999257],[0.19517258584949804,0.21305690312092035],[0.20870412246821748,0.21906590076953403],[0.2223248095666078,0.22511233765583388],[0.23605052325748707,0.23119621377981986],[0.24989713965367355,0.23731752914149185]],[[0.07898874976774592,0.3131943841852548],[0.08268808759427122,0.3288933195335234],[0.08294719389705904,0.3444764272402009],[0.07992116608594747,0.3598465992825387],[0.07376510157077512,0.3749067276377889],[0.06463409776138032,0.3895597042832031],[0.05268325206760145,0.403708421196033],[0.038067661899277065,0.41725577035353056],[0.02094242466624495,0.43010464373294727],[0.0014626377783438825,0.4421579333115352],[-0.020216601354587593,0.4533185310665459],[-0.04394019532271157,0.4634893289752312],[-0.06955304671618925,0.4725732190148429],[-0.09690005812518286,0.4804730931626327],[-0.12582613213985336,0.4870918433958524],[-0.15617617135036282,0.4923323616917537],[-0.18779507834687262,0.49609754002758844],[-0.22194683595759326,0.498405415536096],[-0.25580183238256027,0.49907941931245997],[-0.2891610055918236,0.49817980512983145],[-0.32182529355543255,0.4957668267613615],[-0.3535956342434384,0.49190073798020106],[-0.38427296562589025,0.48664179255950113],[-0.41365822567283805,0.4800502442724127],[-0.4415523523543322,0.47218634689208683],[-0.4677562836404225,0.46311035419167457],[-0.49207095750115865,0.45288251994432693],[-0.5142973119065909,0.44156309792319487],[-0.5342362848267691,0.42921234190142943],[-0.5516888142317435,0.41589050565218155],[-0.5664558380915642,0.4016578429486024],[-0.5783382943762803,0.3865746075638429],[-0.5871371210559422,0.370701053271054],[-0.5925710259777992,0.35453900235244984],[-0.594576911770394,0.3384658696233501],[-0.5932830085757181,0.32257993308268085],[-0.5888175465357652,0.3069794707293677],[-0.581308755792528,0.2917627605623367],[-0.5708848664879983,0.2770280805805138],[-0.557674108764167,0.2628737087828251],[-0.5418047127630284,0.2493979231681963],[-0.5234049086265743,0.23669900173555342],[-0.5026029264967965,0.2248752224838222],[-0.47952699651568825,0.2140248634119289],[-0.45430534882524054,0.20424620251879927],[-0.42706621356744723,0.1956375178033592],[-0.3979378208842999,0.18829708726453465],[-0.36704840091779084,0.18232318890125154],[-0.3345261838099125,0.17781410071243575],[-0.30449081729705435,0.17516858957864995],[-0.27397061872352024,0.17392821983426943],[-0.24324280944390306,0.17402864278952107],[-0.21258461081279595,0.1754055097546322],[-0.1822732441847924,0.1779944720398296],[-0.15258593091448475,0.18173118095534058],[-0.12379989235646618,0.18655128781139213],[-0.09619234986532946,0.1923904439182113],[-0.07004052479566762,0.19918430058602515],[-0.04562163850207445,0.20686850912506088],[-0.023212912339141988,0.2153787208455452],[-0.0030915676614631234,0.22465058705770574],[0.014465174176368103,0.23461975907176924],[0.029180091819760036,0.2452218881979628],[0.040775963914118765,0.25639262574651356],[0.04897556910485164,0.26806762302764847],[0.04819397585842205,0.2682172824803778],[0.047412382611992335,0.26836635694501854],[0.04663078936556299,0.26851426143348145],[0.04584919611913353,0.2686604109576779],[0.045067602872703935,0.26880422052951886],[0.044286009626274346,0.2689451051609155],[0.04350441637984488,0.2690824798637794],[0.042722823133415286,0.26921575965002115],[0.0419412298869857,0.2693443595315522],[0.04115963664055623,0.26946769452028363],[0.04037804339412664,0.26958517962812656],[0.039596450147697054,0.2696962298669924],[0.03881485690126758,0.26980026024879195],[0.038033263654837994,0.2698966857854366],[0.037251670408408405,0.2699849214888373],[0.03647007716197894,0.27006438237090535],[0.018327751009048807,0.2728349834576891],[0.00016832750385333383,0.2756061695325618],[-0.018005750874713088,0.2783785255836121],[-0.036192041647754816,0.2811526365989289],[-0.05438810233637672,0.2839290875666012],[-0.07259149046168405,0.28670846347471757],[-0.09079976354478139,0.2894913493113673],[-0.109010479106774,0.29227833006463855],[-0.1272211946687666,0.2950699907226208],[-0.14542946775186422,0.2978669162734026],[-0.16363285587717127,0.30066969170507285],[-0.1818289165657933,0.30347890200572036],[-0.20001520733883504,0.30629513216343407],[-0.2181892857174012,0.3091189671663027],[-0.23634870922259704,0.31195099200241516],[-0.2544910353755271,0.3147917916598604],[-0.2592725948924861,0.31557928312546024],[-0.2639027207179495,0.3164492579115873],[-0.2683472181473859,0.31740932086339646],[-0.27257189247626384,0.3184670768260427],[-0.27654254900005243,0.3196301306446808],[-0.28022499301421977,0.3209060871644662],[-0.2835850298142351,0.32230255123055357],[-0.28658846469556737,0.32382712768809785],[-0.28920110295368406,0.3254874213822543],[-0.29138874988405533,0.32729103715817753],[-0.29311721078214875,0.3292455798610229],[-0.2943522909434337,0.33135865433594514],[-0.2950597956633789,0.33363786542809926],[-0.29520553023745294,0.33609081798264034],[-0.2947552999611241,0.3387251168447233],[-0.2936749101298616,0.34154836685950307],[-0.29220229889602883,0.343939115680597],[-0.2902961476583174,0.34616665282490316],[-0.2879723325295448,0.34822688337579977],[-0.2852467296225297,0.35011571241666484],[-0.28213521505009,0.3518290450308764],[-0.27865366492504345,0.3533627863018127],[-0.27481795536020914,0.35471284131285163],[-0.2706439624684044,0.3558751151473715],[-0.2661475623624472,0.35684551288875027],[-0.2613446311551563,0.35761993962036587],[-0.25625104495934903,0.35819430042559663],[-0.2508826798878437,0.3585645003878207],[-0.24525541205345885,0.3587264445904158],[-0.23938511756901276,0.3586760381167603],[-0.23328767254732244,0.3584091860502323],[-0.22697895310120697,0.35792179347420977],[-0.2222989599983022,0.3574587754018891],[-0.21763728548711053,0.3569694328655705],[-0.21299270832818468,0.35645552082952026],[-0.20836400728207644,0.3559187942580052],[-0.20374996110933935,0.3553610081152917],[-0.19914934857052474,0.3547839173656463],[-0.19456094842618607,0.3541892769733356],[-0.1899835394368751,0.35357884190262595],[-0.18541590036314426,0.35295436711778416],[-0.18085680996554698,0.3523176075830766],[-0.176305047004634,0.35167031826276984],[-0.17175939024095954,0.3510142541211304],[-0.16721861843507463,0.3503511701224248],[-0.16268151034753306,0.3496828212309196],[-0.15814684473888616,0.34901096241088136],[-0.15361340036968665,0.34833734862657656],[-0.13937802274936498,0.3461657753427699],[-0.12511944157953994,0.3439936170708743],[-0.1108339931418684,0.341820288822801],[-0.09651801371800832,0.3396452056104613],[-0.0821678395896172,0.33746778244576614],[-0.06777980703835226,0.3352874343406267],[-0.05335025234587047,0.3331035763069543],[-0.038875511793829476,0.3309156233566599],[-0.024351921663886722,0.32872299050165477],[-0.009775818237699452,0.32652509275385005],[0.004856462203074727,0.32432134512515687],[0.01954858337677908,0.3221111626274864],[0.03430420900175564,0.31989396027274986],[0.04912700279634716,0.31766915307285826],[0.06402062847889642,0.31543615603972286],[0.07898874976774592,0.3131943841852548]],[[-0.33869468112420387,-0.18160258107380967],[-0.3577224058766047,-0.18295712099352957],[-0.3768820244893409,-0.18547520222196212],[-0.396031873186496,-0.18908487122417905],[-0.41503028819215587,-0.1937141744652524],[-0.4337356057304049,-0.19929115841025424],[-0.4520061620253273,-0.20574386952425672],[-0.4697002933010078,-0.2130003542723321],[-0.486676335781531,-0.22098865911955234],[-0.5027926256909819,-0.22963683053098938],[-0.5179074992534455,-0.2388729149717156],[-0.5318792926930052,-0.2486249589068027],[-0.5445663422337461,-0.2588210088013232],[-0.5558269840997541,-0.26938911112034913],[-0.5655195545151119,-0.2802573123289521],[-0.5735023897039054,-0.29135365889220466],[-0.5796338258902186,-0.3026061972751788],[-0.5844009340737153,-0.31566254643010594],[-0.5868586784619021,-0.32873410527534286],[-0.5870620148299184,-0.34176120502582774],[-0.5850658989529037,-0.3546841768964981],[-0.5809252866059986,-0.3674433521022922],[-0.5746951335643421,-0.37997906185814756],[-0.5664303956030735,-0.3922316373790017],[-0.5561860284973321,-0.4041414098797931],[-0.5440169880222586,-0.41564871057545905],[-0.5299782299529914,-0.4266938706809378],[-0.5141247100646711,-0.4372172214111669],[-0.4965113841324366,-0.44715909398108444],[-0.4771932079314273,-0.45645981960562776],[-0.4562251372367835,-0.46505972949973495],[-0.4336621278236443,-0.47289915487834433],[-0.4095591354671494,-0.479918426956393],[-0.38480481540529643,-0.48583051157828816],[-0.3594020171967964,-0.4906931275687958],[-0.33348385594143215,-0.4945144647611597],[-0.3071834467389861,-0.4973027129886236],[-0.2806339046892402,-0.4990660620844314],[-0.2539683448919775,-0.499812701881827],[-0.22731988244698048,-0.4995508222140541],[-0.20082163245403167,-0.49828861291435667],[-0.17460671001291378,-0.4960342638159785],[-0.14880823022340856,-0.49279596475216314],[-0.12355930818529959,-0.4885819055561549],[-0.09899305899836895,-0.48340027606119707],[-0.07524259776239897,-0.47725926610053415],[-0.05244103957717231,-0.4701670655074095],[-0.030721499542471876,-0.4621318641150671],[-0.010217092758079483,-0.4531618517567504],[0.006363268141438975,-0.44463701533404487],[0.02167842497329989,-0.4354499723947668],[0.035674643201810116,-0.425696660985487],[0.048298188291279,-0.4154730191527759],[0.059495325706014145,-0.4048749849432043],[0.06921232091032316,-0.39399849640334283],[0.07739543936851426,-0.38293949157976137],[0.08399094654489506,-0.37179390851903094],[0.08894510790377415,-0.360657685267722],[0.09220418890945889,-0.3496267598724052],[0.09371445502625776,-0.338797070379651],[0.09342217171847836,-0.3282645548360301],[0.09127360445042892,-0.3181251512881128],[0.08721501868641716,-0.30847479778246967],[0.08119267989075106,-0.2994094323656714],[0.07315285352773873,-0.2910249930842884],[0.0651899652499218,-0.29274719801784754],[0.05724417432437092,-0.29446940295140667],[0.0493130382721899,-0.2961916078849657],[0.0413941146144848,-0.297913812818525],[0.033484960872360005,-0.2996360177520839],[0.02558313456692037,-0.30135822268564316],[0.017686193219271135,-0.30308042761920184],[0.009791694350516664,-0.3048026325527612],[0.00189719548176269,-0.3065248374863203],[-0.005999745865886794,-0.30824704241987944],[-0.01390157217132618,-0.30996924735343845],[-0.021810725913451103,-0.3116914522869976],[-0.02972964957115632,-0.3134136572205569],[-0.03766078562333686,-0.3151358621541158],[-0.04560657654888821,-0.31685806708767483],[-0.0535694648267049,-0.31858027202123396],[-0.0668565500160072,-0.3214299439980265],[-0.0801436352053095,-0.32428663583188533],[-0.09343072039461203,-0.3271480075704549],[-0.1067178055839142,-0.33001171926137984],[-0.12000489077321648,-0.33287543095230465],[-0.13329197596251866,-0.33573680269087425],[-0.14657906115182096,-0.338593494524733],[-0.15986614634112337,-0.34144316650152573],[-0.17315323153042567,-0.34428347866889675],[-0.18644031671972783,-0.3471120910744909],[-0.1997274019090301,-0.34992666376595294],[-0.2130144870983325,-0.352724856790927],[-0.22630157228763484,-0.3555043301970585],[-0.2395886574769371,-0.3582627440319913],[-0.2528757426662394,-0.36099775834337033],[-0.2661628278555416,-0.36370703317884034],[-0.2740569196444801,-0.3651674559426412],[-0.28148205548556077,-0.366255241293848],[-0.2884382353787837,-0.3669721441967275],[-0.2949254593241489,-0.3673199196155459],[-0.30094372732165653,-0.36730032251456946],[-0.30649303937130634,-0.366915107858065],[-0.31157339547309837,-0.3661660306102993],[-0.3161847956270326,-0.3650548457355386],[-0.3203272398331091,-0.3635833081980494],[-0.3240007280913281,-0.36175317296209863],[-0.327205260401689,-0.3595661949919523],[-0.3299408367641924,-0.3570241292518771],[-0.33220745717883843,-0.3541287307061398],[-0.3340051216456263,-0.3508817543190067],[-0.33533383016455665,-0.34728495505474455],[-0.336193582735629,-0.3433400878776196],[-0.33648708728285615,-0.34124349056719994],[-0.33674395464665663,-0.33914689325678005],[-0.3369666273059257,-0.3370502959463604],[-0.33715754773955886,-0.3349536986359405],[-0.3373191584264508,-0.3328571013255208],[-0.3374539018454967,-0.3307605040151008],[-0.33756422047559187,-0.32866390670468126],[-0.3376525567956308,-0.3265673093942614],[-0.3377213532845094,-0.3244707120838416],[-0.3377730524211222,-0.32237411477342204],[-0.33781009668436407,-0.32027751746300226],[-0.33783492855313124,-0.31818092015258237],[-0.3378499905063175,-0.3160843228421627],[-0.3378577250228184,-0.31398772553174303],[-0.33786057458152935,-0.31189112822132314],[-0.3378609816613454,-0.3097945309109035],[-0.3380077339349588,-0.30171672288608986],[-0.3381361676168592,-0.29365587951585326],[-0.33824750394649356,-0.2856102458359264],[-0.33834296416331044,-0.2775780668820429],[-0.3384237695067565,-0.2695575876899362],[-0.3384911412162795,-0.2615470532953398],[-0.3385463005313269,-0.2535447087339875],[-0.3385904686913464,-0.24554879904161242],[-0.3386248669357856,-0.237557569253948],[-0.3386507165040921,-0.22956926440672776],[-0.3386692386357132,-0.22158212953568535],[-0.3386816545700966,-0.21359440967655396],[-0.33868918554668964,-0.20560434986506748],[-0.33869305280494055,-0.19761019513695866],[-0.3386944775842958,-0.1896101905279617],[-0.33869468112420387,-0.18160258107380967]],[[-0.23281484934121455,-0.03743655649066013],[-0.19583409055025322,-0.04401669751001602],[-0.1589803406618368,-0.05057928888670671],[-0.1222438297603845,-0.057125500596909684],[-0.08561478793031663,-0.06365650261680256],[-0.0490834452560526,-0.07017346492256327],[-0.012640031822011153,-0.07667755749036931],[0.023725222287386778,-0.08316995029639862],[0.060022086987722476,-0.08965181331682859],[0.09626033219457551,-0.09612431652783704],[0.13244972782352693,-0.10258862990560169],[0.1686000437901567,-0.10904592342630015],[0.2047210500100456,-0.11549736706611025],[0.24082251639877347,-0.12194413080120958],[0.27691421287192125,-0.12838738460777588],[0.31300590934506894,-0.13482829846198674],[0.34910737573379713,-0.14126804234001988],[0.34910737573379713,-0.11868145723369239],[0.34910737573379685,-0.09614284115065053],[0.3491073757337974,-0.07364400425764972],[0.34910737573379713,-0.05117675672144684],[0.34910737573379713,-0.028732908708797522],[0.34910737573379713,-0.0063042703864581995],[0.34910737573379713,0.01611734807881482],[0.34910737573379713,0.038540136520265444],[0.34910737573379713,0.060972284771137863],[0.34910737573379713,0.0834219826646756],[0.34910737573379713,0.10589742003412239],[0.34910737573379713,0.1284067867127222],[0.34910737573379713,0.15095827253371885],[0.34910737573379713,0.17356006733035617],[0.34910737573379713,0.19622036093587802],[0.34910737573379713,0.2189473431835281],[0.3124288737061034,0.20273030338457249],[0.2758541770314513,0.18657176239450146],[0.2393698520759175,0.17046470035624872],[0.2029624652055791,0.15440209741274824],[0.1666185827865131,0.13837693370693382],[0.13032477118479663,0.12238218938173928],[0.09406759676650646,0.10641084458009853],[0.05783362589771938,0.09045587944494549],[0.021609424944513227,0.07451027411921401],[-0.014618439727035939,0.058567008745837756],[-0.05086340175085082,0.042619063467750795],[-0.0871388947608541,0.026659418427886994],[-0.12345835239096922,0.010681053769180049],[-0.15983520827511893,-0.005323050365436011],[-0.19628289604722643,-0.021359913833027155],[-0.23281484934121455,-0.03743655649066013]],[[0.033135279310545815,-0.24749563940128771],[0.021636699292174787,-0.23903232422592535],[0.00851997700580517,-0.23089367743987232],[-0.006035365349773744,-0.22312357314979137],[-0.021849805575772797,-0.21576588546234576],[-0.038743821473402704,-0.20886448848419925],[-0.05653789084387405,-0.20246325632201512],[-0.07505249148839792,-0.19660606308245654],[-0.09410810120818443,-0.19133678287218692],[-0.11352519780444488,-0.18669928979786987],[-0.13312425907838915,-0.18273745796616836],[-0.15272576283122916,-0.179495161483746],[-0.17215018686417477,-0.1770162744572662],[-0.19121800897843658,-0.17534467099339224],[-0.20974970697522619,-0.1745242251987874],[-0.22756575865575326,-0.1745988111801151],[-0.2444866418212293,-0.17561230304403874],[-0.2444866418212293,-0.18369976337231808],[-0.2444866418212293,-0.19179073362913068],[-0.2444866418212293,-0.19988872374300926],[-0.2444866418212293,-0.20799724364248684],[-0.2444866418212293,-0.21611980325609692],[-0.2444866418212293,-0.2242599125123722],[-0.2444866418212293,-0.23242108133984618],[-0.2444866418212293,-0.24060681966705155],[-0.2444866418212293,-0.24882063742252125],[-0.2444866418212293,-0.25706604453478865],[-0.2444866418212293,-0.2653465509323869],[-0.2444866418212293,-0.27366566654384883],[-0.2444866418212293,-0.28202690129770736],[-0.2444866418212293,-0.2904337651224961],[-0.2444866418212293,-0.2988897679467477],[-0.2444866418212293,-0.3073984196989954],[-0.22672310343694635,-0.3035886847703936],[-0.20906581288460044,-0.2997959144963682],[-0.1915037790091623,-0.29601835391265285],[-0.17402601065560566,-0.29225424805498124],[-0.15662151666890142,-0.2885018419590861],[-0.139279305894022,-0.2847593806607015],[-0.12198838717593982,-0.2810251091955609],[-0.10473776935962612,-0.2772972725993974],[-0.08751646129005379,-0.27357411590794467],[-0.07031347181219494,-0.2698538841569361],[-0.05311780977102113,-0.2661348223821053],[-0.03591848401150468,-0.2624151756191855],[-0.018704503378617402,-0.25869318890391046],[-0.0014648767173318688,-0.25496710727201355],[0.015811387127379603,-0.25123517575922816],[0.033135279310545815,-0.24749563940128771]],[[-0.24281924289551254,-0.12249850451340472],[-0.21278550470191782,-0.12353286095249716],[-0.18364449254447895,-0.12528850770513533],[-0.155390100225959,-0.12776602975940776],[-0.12801622154911926,-0.13096601210340375],[-0.10151675031672307,-0.1348890397252116],[-0.07588558033153217,-0.13953569761292084],[-0.05111660539630852,-0.14490657075461955],[-0.02720371931381521,-0.15100224413839736],[-0.004140815886813467,-0.15782330275234235],[0.018078211081933374,-0.16537033158454395],[0.03945946778966396,-0.1736439156230909],[0.0600090604336152,-0.1826446398560717],[0.07973309521102552,-0.1923730892715756],[0.09863767831913228,-0.20282984885769118],[0.11672891595517343,-0.21401550360250743],[0.13401291431638623,-0.2259306384941132],[0.14494748524989892,-0.22353871969684147],[0.15587472874672614,-0.22115323576854728],[0.1668068572013433,-0.21877126176878614],[0.17775608300822637,-0.21638987275711363],[0.18873461856185075,-0.2140061437930859],[0.1997546762566917,-0.21161714993625858],[0.21082846848722436,-0.20921996624618744],[0.2219682076479244,-0.2068116677824281],[0.23318610613326768,-0.2043893296045366],[0.24449437633772947,-0.20195002677206864],[0.2559052306557852,-0.19949083434457993],[0.2674308814819099,-0.19700882738162628],[0.2790835412105796,-0.19450108094276342],[0.2908754222362694,-0.19196467008754703],[0.3028187369534549,-0.18939666987553327],[0.31492569775661194,-0.18679415536627753],[0.27923334658281174,-0.18029347522898964],[0.2437388361995141,-0.17381911955569984],[0.20842506925445323,-0.16736933338214155],[0.17327494839536373,-0.1609423617440482],[0.1382713762699796,-0.15453644967715308],[0.10339725552603536,-0.14814984221718996],[0.06863548881126569,-0.1417807843998924],[0.033968978773404254,-0.13542752126099333],[-0.0006193719398141617,-0.12908829783622666],[-0.035146660680655264,-0.12276135916132569],[-0.06962998480138477,-0.11644495027202395],[-0.10408644165426814,-0.11013731620405487],[-0.13853312859157096,-0.10383670199315198],[-0.17298714296555956,-0.09754135267504849],[-0.20746558212849853,-0.09124951328547837],[-0.24198554343265447,-0.08495942886017471],[-0.24213229570626799,-0.08748257998537712],[-0.24226072938816853,-0.08996302698009384],[-0.24237206571780262,-0.09240486476094678],[-0.24246752593461948,-0.09481218824455806],[-0.24254833127806547,-0.09718909234754924],[-0.24261570298758844,-0.09953967198654257],[-0.24267086230263585,-0.10186802207815959],[-0.24271503046265536,-0.10417823753902256],[-0.24274942870709454,-0.10647441328575313],[-0.24277527827540107,-0.10876064423497345],[-0.24279380040702217,-0.1110410253033054],[-0.24280621634140553,-0.11331965140737066],[-0.2428137473179986,-0.11560061746379136],[-0.2428176145762495,-0.11788801838918939],[-0.24281903935560475,-0.12018594910018643],[-0.24281924289551254,-0.12249850451340472]]]],"source":{"artist":"Major Alexey","license":"CC BY-SA 4.0","url":"https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg","source_sha256":"53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59","adaptation":"compact metric placement variant; same attributed artwork","dimensions_m":[1.4,1.1]}},{"id":"merge_left_arrow","label":"Смещение налево","polygons":[[[[0.0,-0.14],[0.16727478027343753,-0.13987213134765628],[0.3315576171875,-0.13944580078125002],[0.4927862548828125,-0.13865692138671878],[0.6508984375000001,-0.13744140625],[0.8058319091796875,-0.13573516845703126],[0.9575244140625001,-0.13347412109375004],[1.1059136962890626,-0.13059417724609376],[1.2509375,-0.12703125],[1.3925335693359375,-0.12272125244140623],[1.5306396484375,-0.11760009765625001],[1.6651934814453124,-0.11160369873046876],[1.7961328125,-0.10466796875],[1.9233953857421875,-0.09672882080078127],[2.0469189453125,-0.08772216796875001],[2.1666412353515625,-0.07758392333984376],[2.2825,-0.06625],[2.3944329833984375,-0.053656311035156265],[2.5023779296875,-0.03973876953125],[2.6062725830078124,-0.024433288574218753],[2.7060546875,-0.007675781250000013],[2.801661987304688,0.01059783935546875],[2.8930322265625,0.030451660156250004],[2.9801031494140626,0.05194976806640625],[3.0628125,0.07515625],[3.1410980224609375,0.10013519287109375],[3.2148974609375003,0.12695068359375],[3.2841485595703124,0.15566680908203126],[3.3487890625,0.18634765625000002],[3.4087567138671875,0.21905731201171877],[3.4639892578125,0.25385986328125],[3.5144244384765626,0.29081939697265624],[3.56,0.33],[3.79,0.16],[5.0,0.99],[3.05,0.7],[3.29,0.5],[3.2509320068359373,0.4725726318359375],[3.2069091796875,0.4465185546875],[3.1580157470703125,0.4218048095703125],[3.1043359375,0.3983984375],[3.0459539794921877,0.3762664794921875],[2.9829541015624996,0.35537597656250003],[2.9154205322265625,0.3356939697265625],[2.8434375,0.3171875],[2.767089233398438,0.2998236083984375],[2.6864599609375,0.2835693359375],[2.6016339111328124,0.2683917236328125],[2.5126953125,0.2542578125],[2.4197283935546876,0.2411346435546875],[2.3228173828124996,0.2289892578125],[2.2220465087890626,0.2177886962890625],[2.1174999999999997,0.20750000000000002],[2.0092620849609375,0.1980902099609375],[1.8974169921875,0.18952636718750002],[1.7820489501953125,0.18177551269531253],[1.6632421874999999,0.1748046875],[1.5410809326171875,0.1685809326171875],[1.4156494140625,0.1630712890625],[1.2870318603515625,0.1582427978515625],[1.1553125,0.1540625],[1.0205755615234375,0.1504974365234375],[0.8829052734375,0.1475146484375],[0.7423858642578125,0.1450811767578125],[0.5991015625,0.14316406250000002],[0.4531365966796874,0.14173034667968754],[0.3045751953125,0.14074707031250003],[0.1535015869140625,0.14018127441406253],[0.0,0.14],[0.0,-0.14]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short","figure":"B.6"}},{"id":"merge_right_arrow","label":"Смещение направо","polygons":[[[[0.0,0.14],[0.16727478027343753,0.13987213134765628],[0.3315576171875,0.13944580078125002],[0.4927862548828125,0.13865692138671878],[0.6508984375000001,0.13744140625],[0.8058319091796875,0.13573516845703126],[0.9575244140625001,0.13347412109375004],[1.1059136962890626,0.13059417724609376],[1.2509375,0.12703125],[1.3925335693359375,0.12272125244140623],[1.5306396484375,0.11760009765625001],[1.6651934814453124,0.11160369873046876],[1.7961328125,0.10466796875],[1.9233953857421875,0.09672882080078127],[2.0469189453125,0.08772216796875001],[2.1666412353515625,0.07758392333984376],[2.2825,0.06625],[2.3944329833984375,0.053656311035156265],[2.5023779296875,0.03973876953125],[2.6062725830078124,0.024433288574218753],[2.7060546875,0.007675781250000013],[2.801661987304688,-0.01059783935546875],[2.8930322265625,-0.030451660156250004],[2.9801031494140626,-0.05194976806640625],[3.0628125,-0.07515625],[3.1410980224609375,-0.10013519287109375],[3.2148974609375003,-0.12695068359375],[3.2841485595703124,-0.15566680908203126],[3.3487890625,-0.18634765625000002],[3.4087567138671875,-0.21905731201171877],[3.4639892578125,-0.25385986328125],[3.5144244384765626,-0.29081939697265624],[3.56,-0.33],[3.79,-0.16],[5.0,-0.99],[3.05,-0.7],[3.29,-0.5],[3.2509320068359373,-0.4725726318359375],[3.2069091796875,-0.4465185546875],[3.1580157470703125,-0.4218048095703125],[3.1043359375,-0.3983984375],[3.0459539794921877,-0.3762664794921875],[2.9829541015624996,-0.35537597656250003],[2.9154205322265625,-0.3356939697265625],[2.8434375,-0.3171875],[2.767089233398438,-0.2998236083984375],[2.6864599609375,-0.2835693359375],[2.6016339111328124,-0.2683917236328125],[2.5126953125,-0.2542578125],[2.4197283935546876,-0.2411346435546875],[2.3228173828124996,-0.2289892578125],[2.2220465087890626,-0.2177886962890625],[2.1174999999999997,-0.20750000000000002],[2.0092620849609375,-0.1980902099609375],[1.8974169921875,-0.18952636718750002],[1.7820489501953125,-0.18177551269531253],[1.6632421874999999,-0.1748046875],[1.5410809326171875,-0.1685809326171875],[1.4156494140625,-0.1630712890625],[1.2870318603515625,-0.1582427978515625],[1.1553125,-0.1540625],[1.0205755615234375,-0.1504974365234375],[0.8829052734375,-0.1475146484375],[0.7423858642578125,-0.1450811767578125],[0.5991015625,-0.14316406250000002],[0.4531365966796874,-0.14173034667968754],[0.3045751953125,-0.14074707031250003],[0.1535015869140625,-0.14018127441406253],[0.0,-0.14],[0.0,0.14]]]],"source":{"path":"simulation/urban-plan-research/replay/standard_arrow_templates.py","sha256":"c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2","profile":"short","figure":"B.6"}},{"id":"warning_children","label":"Предупреждение: дети","polygons":[[[[-1.35302824797074,0.75],[-1.3680552792089298,0.7496670609281839],[-1.3826482229802934,0.7486898533770064],[-1.3967332038352547,0.7471007918428739],[-1.4102363463242367,0.7449322908221925],[-1.4230837749976644,0.7422167648113682],[-1.435201614405961,0.7389866283068076],[-1.4465159890995518,0.7352742958049168],[-1.4569530236288584,0.7311121818021019],[-1.466438842544307,0.7265327007947693],[-1.4748995703963197,0.7215682672793251],[-1.4822613317353217,0.7162512957521755],[-1.4884502511117361,0.7106142007097269],[-1.4933924530759874,0.7046893966483854],[-1.4970140621784993,0.6985092980645571],[-1.4992412029696958,0.6921063194546485],[-1.5,0.6855128753150657],[-1.5,-0.6855128753150657],[-1.4992412029696953,-0.6921063194546485],[-1.4970140621784997,-0.698509298064557],[-1.493392453075987,-0.7046893966483856],[-1.4884502511117361,-0.7106142007097269],[-1.4822613317353222,-0.7162512957521756],[-1.4748995703963192,-0.7215682672793251],[-1.466438842544307,-0.7265327007947693],[-1.4569530236288584,-0.7311121818021019],[-1.4465159890995514,-0.7352742958049168],[-1.435201614405961,-0.7389866283068078],[-1.4230837749976644,-0.7422167648113682],[-1.4102363463242367,-0.7449322908221925],[-1.3967332038352538,-0.7471007918428739],[-1.3826482229802934,-0.7486898533770064],[-1.3680552792089298,-0.7496670609281839],[-1.35302824797074,-0.75],[-1.3481967617874626,-0.7499651591395414],[-1.3433797246825412,-0.7498609280457269],[-1.3385808581086809,-0.7496877439498986],[-1.3338038835185873,-0.7494460440833985],[-1.3290525223649672,-0.7491362656775683],[-1.324330496100524,-0.7487588459637508],[-1.3196415261779655,-0.7483142221732876],[-1.3149893340499954,-0.7478028315375205],[-1.3103776411693202,-0.7472251112877916],[-1.3058101689886454,-0.7465814986554437],[-1.3012906389606766,-0.7458724308718176],[-1.2968227725381185,-0.7450983451682562],[-1.292410291173677,-0.7442596787761012],[-1.2880569163200581,-0.743356868926695],[-1.2837663694299675,-0.742390352851379],[-1.27954237195611,-0.7413605677814956],[1.42651412398537,-0.05584769246642991],[1.4348331342024656,-0.05357529232387881],[1.4427274620786634,-0.05108564218351559],[1.450181649745122,-0.04839049331239746],[1.4571802393330002,-0.045501596977580744],[1.4637077729734564,-0.04243070444612234],[1.4697487927976494,-0.039189566985079534],[1.4752878409367376,-0.03578993586150899],[1.48030945952188,-0.03224356234246727],[1.484798190684235,-0.028562197695011466],[1.4887385765549612,-0.02475759318619824],[1.4921151592652173,-0.020841500083084878],[1.4949124809461622,-0.01682566965272775],[1.4971150837289542,-0.012721853162183817],[1.498707509744752,-0.00854180187851007],[1.4996743011247144,-0.004297267068763173],[1.5,-1.047333897027107e-16],[1.4996743011247144,0.004297267068762963],[1.498707509744752,0.00854180187850986],[1.4971150837289542,0.012721853162183713],[1.4949124809461622,0.01682566965272764],[1.4921151592652173,0.02084150008308467],[1.4887385765549612,0.02475759318619824],[1.484798190684235,0.028562197695011362],[1.48030945952188,0.03224356234246717],[1.4752878409367376,0.03578993586150867],[1.4697487927976494,0.039189566985079534],[1.4637077729734564,0.04243070444612234],[1.4571802393330002,0.045501596977580536],[1.450181649745122,0.048390493312397136],[1.4427274620786634,0.05108564218351559],[1.4348331342024656,0.053575292323878594],[1.42651412398537,0.055847692466429705],[-1.27954237195611,0.7413605677814954],[-1.283766415563679,0.7423903528513787],[-1.2880570885525802,0.7433568689266946],[-1.2924106510166244,0.744259678776101],[-1.2968233630496218,0.7450983451682559],[-1.301291484745382,0.7458724308718174],[-1.3058112761977148,0.7465814986554433],[-1.3103789975004303,0.7472251112877916],[-1.3149909087473386,0.7478028315375203],[-1.31964327003225,0.7483142221732875],[-1.324332341448974,0.7487588459637508],[-1.3290543830913202,0.7491362656775683],[-1.333805655053098,0.7494460440833983],[-1.3385824174281202,0.7496877439498983],[-1.343380930310194,0.7498609280457268],[-1.348197453793131,0.7499651591395412],[-1.35302824797074,0.75]],[[-1.21087716940804,0.5959052518314343],[-1.2094970281770436,0.5958952971713529],[-1.2081209159568278,0.5958655159591814],[-1.206749909200655,0.5958160323470296],[-1.2053850843617862,0.5957469704870068],[-1.2040275178934832,0.5956584545312223],[-1.2026782862490082,0.5955506086317859],[-1.2013384658816237,0.5954235569408068],[-1.2000091332445906,0.5952774236103945],[-1.1986913647911717,0.5951123327926586],[-1.1973862369746286,0.5949284086397085],[-1.1960948262482236,0.5947257753036538],[-1.1948182090652182,0.5945045569366036],[-1.1935574618788736,0.5942648776906677],[-1.192313661142454,0.5940068617179555],[-1.1910878833092187,0.5937306331705763],[-1.1898812048324312,0.5934363162006397],[1.0897178562280327,0.015955957136329513],[1.09209471629006,0.015306801292224143],[1.0943502385404023,0.014595577490262562],[1.096480006445105,0.013825640536358982],[1.0984796034702127,0.013000345236428245],[1.1003446130817718,0.012123046396384674],[1.102070618745827,0.011197098822142685],[1.1036532039284235,0.01022585731961681],[1.105087952095607,0.009212676694721684],[1.1063704467134228,0.008160911753371518],[1.107496271247916,0.0070739173014810475],[1.108461009165132,0.005955048144964489],[1.1092602439311163,0.004807659089736685],[1.109889559011914,0.003635104941711743],[1.1103445378735706,0.0024407405068042963],[1.1106207639821313,0.0012279205909289772],[1.1107138208036413,0.0],[1.1106207639821313,-0.00122790034873725],[1.1103445378735706,-0.0024406649359551323],[1.109889559011914,-0.0036349470526158933],[1.1092602439311163,-0.0048073999896819895],[1.108461009165132,-0.005954677038115563],[1.107496271247916,-0.007073431488878651],[1.1063704467134228,-0.00816031663293371],[1.105087952095607,-0.009211985761242776],[1.1036532039284235,-0.010225092164768306],[1.102070618745827,-0.01119628913447213],[1.1003446130817718,-0.01212222996131691],[1.098479603470213,-0.012999567936264576],[1.0964800064451048,-0.01382495635027749],[1.0943502385404025,-0.014595048494317784],[1.09209471629006,-0.01530649765934771],[1.0897178562280327,-0.015955957136329513],[-1.1898812048324312,-0.5934363162006397],[-1.1910878833092187,-0.5937306331705763],[-1.1923136611424532,-0.5940068617179555],[-1.193557461878874,-0.5942648776906678],[-1.1948182090652177,-0.594504556936604],[-1.1960948262482236,-0.5947257753036538],[-1.1973862369746286,-0.5949284086397089],[-1.1986913647911717,-0.5951123327926588],[-1.2000091332445906,-0.5952774236103948],[-1.2013384658816237,-0.5954235569408071],[-1.2026782862490082,-0.5955506086317861],[-1.2040275178934827,-0.5956584545312227],[-1.2053850843617857,-0.595746970487007],[-1.2067499092006542,-0.59581603234703],[-1.2081209159568278,-0.5958655159591817],[-1.2094970281770436,-0.5958952971713531],[-1.21087716940804,-0.5959052518314345],[-1.2151707057626182,-0.595810129274086],[-1.2193401916432913,-0.5955309350207005],[-1.2233645224149639,-0.5950769291992692],[-1.2272225934425407,-0.594457371937783],[-1.230893300090926,-0.5936815233642325],[-1.2343555377250248,-0.5927586436066083],[-1.237588201709741,-0.5916979927929018],[-1.2405701874099804,-0.5905088310511035],[-1.243280390190646,-0.5892004185092039],[-1.2456977054166436,-0.5877820152951946],[-1.2478010284528782,-0.5862628815370656],[-1.2495692546642534,-0.5846522773628084],[-1.2509812794156745,-0.5829594629004134],[-1.2520159980720456,-0.5811936982778715],[-1.2526523059982715,-0.5793642436231736],[-1.2528690985592572,-0.5774803590643104],[-1.2528690985592572,0.5774803590643101],[-1.2526523059982715,0.5793642436231732],[-1.2520159980720456,0.581193698277871],[-1.2509812794156745,0.582959462900413],[-1.2495692546642534,0.584652277362808],[-1.2478010284528782,0.5862628815370654],[-1.2456977054166445,0.5877820152951941],[-1.243280390190646,0.5892004185092037],[-1.2405701874099804,0.5905088310511031],[-1.237588201709741,0.5916979927929014],[-1.2343555377250244,0.5927586436066079],[-1.230893300090926,0.5936815233642321],[-1.2272225934425403,0.5944573719377826],[-1.2233645224149634,0.5950769291992688],[-1.2193401916432913,0.5955309350207002],[-1.2151707057626182,0.5958101292740855],[-1.21087716940804,0.5959052518314343]]],[[[-0.9516987834938124,0.30571134825995316],[-0.9537762429463403,0.30621785333028206],[-0.9558864204268693,0.30669322590968306],[-0.9580274890404352,0.30713725278040266],[-0.9601976218920725,0.30754972072468795],[-0.9623949920868178,0.3079304165247854],[-0.9646177727297061,0.308279126962942],[-0.9668641369257736,0.30859563882140456],[-0.9691322577800552,0.3088797388824197],[-0.9714203083975854,0.3091312139282344],[-0.973726461883401,0.3093498507410953],[-0.9760488913425371,0.3095354361032492],[-0.9783857698800293,0.30968775679694294],[-0.9807352706009129,0.30980659960442336],[-0.9830955666102228,0.30989175130793706],[-0.9854648310129952,0.3099429986897311],[-0.9878412369142651,0.309960128532052],[-0.9952318810320748,0.3097963790968901],[-1.0024089506715557,0.3093157610908642],[-1.0093361232240694,0.308534219963164],[-1.015977076080977,0.3074677011629793],[-1.0222954866336407,0.30613215013949946],[-1.0282550322734219,0.30454351234191446],[-1.033819390391682,0.30271773321941375],[-1.0389522383797831,0.30067075822118716],[-1.0436172536290869,0.2984185327964243],[-1.0477781135309545,0.29597700239431485],[-1.051398495476747,0.2933621124640485],[-1.0544420768578275,0.29058980845481486],[-1.0568725350655575,0.2876760358158036],[-1.0586535474912973,0.28463673999620454],[-1.0597487915264088,0.2814878664452072],[-1.0601219445622547,0.2782453606120013],[-1.0599617560145562,0.2761318072457676],[-1.0594862589285339,0.27404423675687817],[-1.0587030561397972,0.2719884222184228],[-1.0576197504839566,0.26997013670349196],[-1.056243944796622,0.26799515328517576],[-1.0545832419134045,0.2660692450365643],[-1.052645244669912,0.26419818503074777],[-1.0504375559017558,0.2623877463408164],[-1.0479677784445456,0.2606437020398602],[-1.0452435151338912,0.2589718252009696],[-1.0422723688054027,0.25737788889723445],[-1.039061942294691,0.2558676662017452],[-1.0356198384373645,0.25444693018759207],[-1.0319536600690347,0.2531214539278648],[-1.0280710100253105,0.25189701049565394],[-1.0239794911418025,0.25077937296404945],[-0.6791375697590922,0.16342142888728392],[-0.5540310152388712,0.0720634405907758],[-0.5519742677722963,0.07066700465309145],[-0.5497317306238738,0.06934258773473317],[-0.5473134670938116,0.06809268367372562],[-0.5447295404823191,0.0669197863080938],[-0.5419900140896048,0.06582638947586253],[-0.5391049512158763,0.06481498701505685],[-0.5360844151613433,0.06388807276370179],[-0.5329384692262145,0.06304814055982204],[-0.5296771767106985,0.06229768424144254],[-0.5263106009150036,0.061639197646588414],[-0.5228488051393398,0.061075174613284496],[-0.5193018526839142,0.0606081089795558],[-0.5156798068489361,0.060240494583427034],[-0.5119927309346144,0.059974825262923345],[-0.5082506882411573,0.05981359485606934],[-0.5044637420687748,0.05975929720089034],[-0.5025630331662754,0.059773001164712306],[-0.500667934123062,0.059813999699904606],[-0.49877992121789205,0.05988212277205625],[-0.4969004707295259,0.05997720034675652],[-0.4950310589367226,0.060099062389594615],[-0.49317316211824114,0.060247538866159855],[-0.49132825655284074,0.060422459742041204],[-0.48949781851928087,0.060623654982827985],[-0.48768332429632055,0.060850954554109694],[-0.485886250162719,0.06110418842147502],[-0.4841080723972353,0.06138318655051357],[-0.4823502672786293,0.06168777890681445],[-0.48061431108565955,0.06201779545596674],[-0.47890168009708534,0.06237306616355974],[-0.47721385059166677,0.06275342099518266],[-0.4755522988481613,0.06315868991642479],[-0.24495361991425257,0.1215748124345917],[-0.24329206817074778,0.12198008135583385],[-0.24160423866532876,0.12236043618745676],[-0.23989160767675455,0.12271570689504986],[-0.2381556514837846,0.12304572344420216],[-0.23639784636517858,0.12335031580050293],[-0.23461966859969507,0.12362931392954146],[-0.23282259446609332,0.12388254779690688],[-0.231008100243133,0.1241098473681884],[-0.22917766220957336,0.1243110426089753],[-0.22733275664417318,0.12448596348485663],[-0.2254748598256917,0.12463443996142187],[-0.22360544803288818,0.12475630200425998],[-0.22172599754452205,0.12485137957896025],[-0.21983798463935234,0.12491950265111187],[-0.21794288559613828,0.12496050118630408],[-0.21604217669363956,0.12497420515012614],[-0.21414146779114018,0.12496050118630408],[-0.2122463687479268,0.12491950265111187],[-0.2103583558427573,0.12485137957896025],[-0.20847890535439095,0.12475630200425998],[-0.20660949356158786,0.12463443996142178],[-0.20475159674310617,0.12448596348485674],[-0.20290669117770554,0.1243110426089753],[-0.20107625314414568,0.1241098473681884],[-0.1992617589211858,0.12388254779690688],[-0.19746468478758405,0.12362931392954146],[-0.1956865070221001,0.12335031580050293],[-0.19392870190349454,0.12304572344420216],[-0.1921927457105248,0.12271570689504986],[-0.1904801147219506,0.12236043618745676],[-0.18879228521653157,0.12198008135583385],[-0.18713073347302656,0.1215748124345917],[0.13636669032212012,0.03962457438497713],[0.1381670932592851,0.039185755605284325],[0.13999583459746523,0.03877385894063316],[0.14185133348815637,0.03838907601710583],[0.14373200908285422,0.03803159846078455],[0.14563628053305333,0.03770161789775088],[0.1475625669902494,0.03739932595408702],[0.1495092876059374,0.03712491425587497],[0.1514748615316135,0.03687857442919683],[0.15345770791877222,0.03666049810013447],[0.15545624591890927,0.036470876894769896],[0.15746889468351988,0.0363099024391853],[0.15949407336409904,0.036177766359462266],[0.1615302011121429,0.0360746602816832],[0.16357569707914643,0.03600077583193009],[0.16562898041660468,0.03595630463628451],[0.16768847027601286,0.03594143832082898],[0.1740934215197747,0.036083346431081006],[0.18031335197687515,0.03649986011475944],[0.18631677385161227,0.037177163401247874],[0.192072199348285,0.038101440319929805],[0.19754814067119097,0.039258874900188936],[0.20271311002462822,0.040635651171408736],[0.2075356196128948,0.04221795316297261],[0.21198418164028854,0.04399196490426435],[0.21602730831110817,0.045943870424667355],[0.2196335118296513,0.0480598537535652],[0.22277130440021597,0.0503260989203415],[0.22540919822710048,0.05272878995437995],[0.2275157055146031,0.055254110885063795],[0.22905933846702142,0.057888245741777006],[0.23000860928865396,0.0606173785539027],[0.23033203018379855,0.06342769335082472],[0.2301932251238501,0.06525943132475334],[0.22978119777253792,0.06706863569081366],[0.22910252987266477,0.06885030527816183],[0.228163803167031,0.07059943891595297],[0.22697159939843914,0.07231103543334313],[0.2255325003096904,0.07398009365948785],[0.22385308764358625,0.07560161242354244],[0.22193994314292786,0.07717059055466295],[0.21979964855051737,0.07868202688200492],[0.21743878560915597,0.08013092023472389],[0.2148639360616451,0.08151226944197566],[0.21208168165078645,0.08282107333291572],[0.20909860411938208,0.08405233073669975],[0.20592128521023256,0.08520104048248342],[0.20255630666614,0.08626220139942246],[0.19901025022990582,0.0872308123166723],[-0.27386926232778075,0.20702209513140635],[-0.27553081407128577,0.2074273640526485],[-0.2772186435767048,0.20780771888427144],[-0.2789312745652788,0.20816298959186452],[-0.2806672307582483,0.20849300614101682],[-0.2824250358768545,0.2087975984973177],[-0.28420321364233825,0.20907659662635614],[-0.28600028777593955,0.20932983049372156],[-0.2878147819989003,0.20955713006500307],[-0.28964522003245996,0.20975832530578992],[-0.29149012559786014,0.2099332461816713],[-0.29334802241634184,0.21008172265823652],[-0.29521743420914515,0.21020358470107453],[-0.2970968846975113,0.21029866227577487],[-0.298984897602681,0.21036678534792652],[-0.3008799966458948,0.21040778388311876],[-0.30278070554839376,0.2104214878469408],[-0.30468141445089225,0.21040778388311876],[-0.30657651349410675,0.21036678534792652],[-0.308464526399276,0.21029866227577487],[-0.31034397688764237,0.21020358470107464],[-0.31221338868044546,0.21008172265823644],[-0.31407128549892716,0.2099332461816713],[-0.3159161910643271,0.20975832530578986],[-0.3177466290978872,0.20955713006500307],[-0.31956112332084796,0.20932983049372156],[-0.3213581974544495,0.20907659662635614],[-0.32313637521993277,0.2087975984973177],[-0.3248941803385388,0.20849300614101682],[-0.32663013653150896,0.20816298959186452],[-0.3283427675200825,0.20780771888427152],[-0.3300305970255015,0.2074273640526485],[-0.33169214876900677,0.20702209513140635],[-0.49895020177121974,0.16465036923485105],[-0.5622194414233586,0.20429705349114863],[-0.5631442224206857,0.20486012019334843],[-0.5641025087946852,0.20541117652843693],[-0.5650936546734,0.20594995799844165],[-0.5661170141848735,0.2064762001053903],[-0.5671719414571488,0.20698963835131062],[-0.5682577906182682,0.20749000823823024],[-0.5693739157962745,0.20797704526817662],[-0.5705196711192113,0.20845048494317753],[-0.5716944107151205,0.20891006276526078],[-0.5728974887120444,0.209355514236454],[-0.5741282592380275,0.20978657485878466],[-0.5753860764211121,0.2102029801342806],[-0.5766702943893405,0.21060446556496934],[-0.5779802672707559,0.21099076665287864],[-0.5793153491934007,0.21136161890003607],[-0.5806748942853184,0.21171675780846946],[-0.9516987834938124,0.30571134825995316]]],[[[-0.6710373266258225,0.12055960084312309],[-0.8842387493123822,0.06655071267485224],[-0.8875120745249792,0.06565659437276139],[-0.8906182173192567,0.06467701623601554],[-0.8935511064988155,0.06361659888225392],[-0.8963046708672593,0.06247996292911572],[-0.8988728392281913,0.06127172899424035],[-0.9012495403852134,0.059996517695267],[-0.9034287031419281,0.05865894964983499],[-0.9054042563019395,0.057263645475583325],[-0.9071701286688483,0.05581522579015161],[-0.9087202490462585,0.054318311211178714],[-0.9100485462377725,0.052777522356304285],[-0.9111489490469937,0.05119747984316732],[-0.9120153862775235,0.0495828042894072],[-0.9126417867329653,0.04793811631266316],[-0.9130220792169217,0.04626803653057428],[-0.9131501925329957,0.04457718556078007],[-0.9131501925329957,-0.012687381159441593],[-0.768588777237015,-0.012687381159441593],[-0.768588777237015,0.02260365844670789],[-0.5965730386619694,0.0661803723302331],[-0.6710373266258225,0.12055960084312309]]],[[[-0.3443023250931172,0.22336129003729202],[-0.40434658458644246,0.2689923794643516],[-0.27900487526297457,0.30074399716993655],[-0.27545881882674017,0.3017126283293782],[-0.2720938402826478,0.3027738445749747],[-0.2689165213734983,0.30392263663900476],[-0.2659334438420937,0.30515399525374765],[-0.2631511894312353,0.3064629111514822],[-0.2605763398837244,0.3078443750644872],[-0.2582154769423628,0.3092933777250417],[-0.2560751823499525,0.31080490986542464],[-0.2541620378492939,0.3123739622179149],[-0.25248262518318976,0.31399552551479154],[-0.2510435260944406,0.3156645904883335],[-0.24985132232584895,0.3173761478708194],[-0.24891259562021562,0.3191251883945286],[-0.24823392772034225,0.32090670279173983],[-0.2478219003690303,0.32271568179473203],[-0.2476830953090816,0.3245471161357842],[-0.2480065162042262,0.32735743093270614],[-0.24895578702585874,0.3300865637448319],[-0.25049941997827707,0.33272069860154496],[-0.25260592726577924,0.3352460195322289],[-0.2552438210926642,0.3376487105662673],[-0.25838161366322865,0.33991495573304364],[-0.261987817181772,0.3420309390619416],[-0.2660309438525914,0.3439828445823446],[-0.27047950587998537,0.34575685632363634],[-0.27530201546825195,0.34733915831520024],[-0.2804669848216892,0.34871593458642003],[-0.28594292614459516,0.34987336916667905],[-0.2916983516412679,0.350797646085361],[-0.29770177351600524,0.3514749493718494],[-0.3039217039731055,0.351891463055528],[-0.3103266552168673,0.35203337116577993],[-0.3123861450762755,0.3520185250925161],[-0.3144394284137335,0.3519741092255282],[-0.3164849243807373,0.35190030709402137],[-0.3185210521287811,0.3517973022272011],[-0.3205462308093603,0.3516652781542726],[-0.32255887957397045,0.35150441840444124],[-0.3245574175741077,0.3513149065069122],[-0.3265402639612667,0.3510969259908908],[-0.32850583788694276,0.35085066038558244],[-0.330452558502631,0.3505762932201923],[-0.33237884495982706,0.3502740080239257],[-0.33428311641002617,0.34994398832598805],[-0.33616379200472357,0.3495864176555845],[-0.33801929089541494,0.34920147954192043],[-0.3398480322335953,0.3487893575142011],[-0.34164843517076005,0.3483502351016318],[-0.5254135155223167,0.30179790103621607],[-0.5286868407349137,0.3009037827341252],[-0.5317929835291908,0.29992420459737934],[-0.5347258727087496,0.29886378724361773],[-0.5374794370771934,0.29772715129047966],[-0.5400476054381254,0.2965189173556042],[-0.5424243065951475,0.29524370605663086],[-0.5446034693518627,0.2939061380111987],[-0.5465790225118732,0.2925108338369471],[-0.5483448948787824,0.2910624141515154],[-0.5498950152561926,0.28956549957254263],[-0.5512233124477071,0.2880247107176681],[-0.5523237152569278,0.2864446682045311],[-0.5531901524874576,0.284829992650771],[-0.5538165529428993,0.28318530467402686],[-0.5541968454268558,0.2815152248919382],[-0.5543249587429298,0.2798243739221439],[-0.5542937262204299,0.2789903956216007],[-0.5542002870017133,0.2781588787715755],[-0.5540450286099543,0.2773304711222051],[-0.5538283385683274,0.2765058204236253],[-0.5535506044000065,0.2756855744259726],[-0.5532122136281656,0.2748703808793834],[-0.5528135537759797,0.27406088753399405],[-0.5523550123666228,0.2732577421399409],[-0.55183697692327,0.2724615924473602],[-0.5512598349690938,0.2716730862063884],[-0.5506239740272703,0.2708928711671618],[-0.549929781620973,0.27012159507981676],[-0.549177645273375,0.26935990569448964],[-0.5483679525076526,0.2686084507613167],[-0.5475010908469797,0.2678678780304343],[-0.54657744781453,0.26713883525197896],[-0.452805270826947,0.1958731925180197],[-0.3443023250931172,0.22336129003729202]]],[[[-0.056380463674881476,0.2782453606120013],[-0.07026167397774574,0.2779302247727521],[-0.08367711218091367,0.2770126921025382],[-0.09656747493639539,0.275534574872661],[-0.10887345889620015,0.27353768535442124],[-0.12053576071233807,0.27106383581912014],[-0.1314950770368184,0.26815483853805844],[-0.1416921045216517,0.26485250578253744],[-0.1510675398188468,0.26119864982385804],[-0.15956207958041402,0.25723508293332126],[-0.1671164204583626,0.2530036173822281],[-0.17367125910470316,0.24854606544187963],[-0.17916729217144467,0.2439042393835768],[-0.18354521631059706,0.23911995147862075],[-0.18674572817416957,0.2342350139983123],[-0.1887095244141732,0.2292912392139527],[-0.18937730168261657,0.22433043939684277],[-0.18753496217675414,0.21700175431968743],[-0.18229594514121894,0.21023118965271842],[-0.17409225279909046,0.20400697523616684],[-0.16335588737344686,0.19831734091026337],[-0.15051885108736784,0.193150516515239],[-0.13601314616393245,0.18849473189132449],[-0.12027077482621906,0.1843382168787507],[-0.10372373929730716,0.1806692013177484],[-0.08680404180027512,0.17747591504854843],[-0.0699436845582031,0.1747465879113818],[-0.05357466979416858,0.1724694497464792],[-0.0381289997312515,0.1706327303940716],[-0.024038676592530672,0.16922465969438974],[-0.011735702601084919,0.16823346748766446],[-0.0016520799799937258,0.1676473836141268],[0.005780189047665196,0.16745463791400733],[0.017019764592260733,0.16761108621551435],[0.027933236310106357,0.16808187956131243],[0.03846554515464318,0.16886919061331732],[0.04856163207931452,0.16997519203344486],[0.058166438037562385,0.17140205648361037],[0.06722490398282943,0.17315195662572969],[0.07568197086855855,0.17522706512171818],[0.08348257964819195,0.17762955463349192],[0.09057167127517163,0.18036159782296643],[0.09689418670294092,0.18342536735205728],[0.1023950668849416,0.18682303588268026],[0.10701925277461655,0.19055677607675076],[0.11071168532540843,0.1946287605961846],[0.11341730549075946,0.19904116210289746],[0.11508105422411252,0.203796153258805],[0.11564787247890962,0.20889590672582287],[0.11464767619124538,0.2144132282697967],[0.11173461015480335,0.22013127678518785],[0.10703995860940863,0.22597323990166163],[0.10069500579488633,0.23186230524888352],[0.09283103595106201,0.23772166045651816],[0.08357933331776168,0.2434744931542312],[0.07307118213480934,0.24904399097168745],[0.06143786664203166,0.25435334153855227],[0.048810671079253076,0.2593257324844908],[0.03532087968629938,0.26388435143916833],[0.021099776702995676,0.26795238603225],[0.006278646369167973,0.27145302389340104],[-0.009011227075359063,0.27430945265228635],[-0.024638559390759873,0.2764448599385715],[-0.040472066337209345,0.2777824333819213],[-0.056380463674881476,0.2782453606120013]]],[[[-0.9830205634477052,-0.029601432719661633],[-0.9909033855763232,-0.02977608279999989],[-0.9985585778225925,-0.030288699212934596],[-1.0059473755667594,-0.03112228121634581],[-1.0130310141890728,-0.032259828068113214],[-1.0197707290697786,-0.03368433902611666],[-1.0261277555891262,-0.03537881334823611],[-1.0320633291273604,-0.037326250292351246],[-1.0375386850647303,-0.03950964911634224],[-1.0425150587814835,-0.041912009078088654],[-1.0469536856578667,-0.044516329435470556],[-1.050815801074127,-0.047305609446367816],[-1.0540626404105131,-0.05026284836865999],[-1.056655439047271,-0.053371045460227376],[-1.0585554323646496,-0.05661319997894962],[-1.0597238557428952,-0.05997231118270659],[-1.0601219445622547,-0.06343137832937816],[-1.0597239018766063,-0.0668901418431733],[-1.0585556045971716,-0.07024902768386204],[-1.056655798890219,-0.07349102701244736],[-1.0540632309220164,-0.07659913098993276],[-1.050816646858833,-0.07955633077732095],[-1.046954792866936,-0.08234561753561531],[-1.0425164151125932,-0.08494998242581905],[-1.037540259762074,-0.08735241660893539],[-1.032065072981645,-0.08953591124596727],[-1.0261296009375744,-0.09148345749791803],[-1.0197725897961312,-0.09317804652579065],[-1.013032785723584,-0.09460266949058863],[-1.0059489348861987,-0.09574031755331477],[-0.9985597834502453,-0.09657398187497246],[-0.990904077581992,-0.0970866536165646],[-0.9830205634477052,-0.0972613239390947],[-0.5751865491452541,-0.0972613239390947],[-0.37960074073763006,-0.2459004613593149],[-0.37620448353732616,-0.24829399932406554],[-0.37248366645180764,-0.25056533112871826],[-0.3684558325936629,-0.25271001158796214],[-0.3641385250754803,-0.2547235955164866],[-0.3595492870098491,-0.2566016377289813],[-0.35470566150935756,-0.25833969304013493],[-0.3496251916865951,-0.2599333162646373],[-0.34432542065415017,-0.2613780622171778],[-0.33882389152461134,-0.26266948571244575],[-0.33313814741056724,-0.2638031415651302],[-0.3272857314246078,-0.26477458458992076],[-0.3212841866793199,-0.26557936960150647],[-0.3151510562872939,-0.26621305141457696],[-0.3089038833611175,-0.2666711848438216],[-0.3025602110133807,-0.26694932470392924],[-0.2961375823566712,-0.26704302580958983],[-0.29296930360453466,-0.2670201858698865],[-0.2898105468503953,-0.2669518549778993],[-0.28666374795420557,-0.26683831652431333],[-0.2835313427759183,-0.26667985389981297],[-0.2804157671754868,-0.2664767504950829],[-0.2773194570128621,-0.2662292897008076],[-0.27424484814799843,-0.2659377549076718],[-0.2711943764408482,-0.2656024295063603],[-0.2681704777513638,-0.2652235968875578],[-0.26517558793949814,-0.26480154044194876],[-0.2622121428652038,-0.26433654356021785],[-0.2592825783884334,-0.26382888963304996],[-0.25638933036914024,-0.2632788620511295],[-0.2535348346672768,-0.26268674420514104],[-0.2507215271427954,-0.2620528194857694],[-0.24795184365564915,-0.26137737128369914],[0.038550690557275225,-0.18879987618472066],[0.038550690557275225,-0.263934746399776],[0.1734749581130508,-0.22977315272025112],[0.1734749581130508,-0.1308222661144112],[0.17336781308132565,-0.12927680176306647],[0.17304926493128026,-0.12774720189214436],[0.17252364408060794,-0.12623711009616181],[0.1717952809470018,-0.12475016996963582],[0.17086850594815695,-0.12329002510708326],[0.1697476495017658,-0.12186031910302098],[0.1684370420255228,-0.12046469555196587],[0.16694101393712146,-0.11910679804843534],[0.16526389565425537,-0.11779027018694585],[0.16341001759461826,-0.11651875556201455],[0.16138371017590414,-0.11529589776815824],[0.15918930381580654,-0.11412534039989389],[0.15683112893201923,-0.11301072705173855],[0.15431351594223597,-0.11195570131820906],[0.1516407952641503,-0.11096390679382223],[0.148817297315456,-0.11003898707309526],[0.06060905094040914,-0.0829396547912091],[0.058764970655843296,-0.0823959427731181],[0.05687968374040975,-0.08188502040672034],[0.054955484577348335,-0.08140720347020754],[0.0529946675498969,-0.08096280774177138],[0.05099952704129329,-0.08055214899960325],[0.048972357434776015,-0.08017554302189434],[0.04691545311358314,-0.07983330558683634],[0.04483110846095384,-0.07952575247262061],[0.04272161786012507,-0.07925319945743868],[0.04058927569433668,-0.07901596231948202],[0.038436376346825396,-0.07881435683694221],[0.0362652142008304,-0.07864869878801056],[0.03407808363958997,-0.07851930395087843],[0.03187727904634219,-0.07842648810373765],[0.02966509480432533,-0.07837056702477946],[0.02744382529677769,-0.07835185649219517],[0.02554311639427853,-0.07836556045601725],[0.023648017351065143,-0.07840655899120945],[0.02176000444589543,-0.07847468206336108],[0.0198805539575293,-0.07856975963806145],[0.01801114216472577,-0.07869162168089945],[0.016153245346244516,-0.07884009815746468],[0.014308339780844115,-0.07901501903334604],[0.012477901747284026,-0.0792162142741328],[0.01066340752432371,-0.07944351384541443],[0.00886633339072218,-0.07969674771277986],[0.007088155625238679,-0.07997574584181841],[0.005330350506632442,-0.08028033819811917],[0.0035943943136627077,-0.08061035474727146],[0.0018817633250889365,-0.08096562545486456],[0.00019393381966970047,-0.08134598028648748],[-0.0014676179238353182,-0.08175124920772962],[-0.31351804183236,-0.16080140913579885],[-0.46946346912123493,-0.042288813879103215],[-0.47150124230497914,-0.040852569647102266],[-0.4737337858663566,-0.0394896804190834],[-0.47615056901688546,-0.03820281006748234],[-0.478741060968082,-0.03699462246473483],[-0.4814947309314652,-0.03586778148327638],[-0.48440104811855145,-0.034824950995543016],[-0.48744948174085967,-0.03386879487397025],[-0.4906295010099062,-0.03300197699099384],[-0.49393057513720895,-0.032227161219049574],[-0.4973421733342853,-0.03154701143057321],[-0.500853764812653,-0.030964191498000244],[-0.50445481878383,-0.030481365293766507],[-0.508134804459333,-0.03010119669030773],[-0.5118831910506803,-0.02982634956005964],[-0.5156894477693887,-0.02965948777545785],[-0.5195430438269764,-0.029603275208938296],[-0.9830205634477052,-0.029601432719661633]]],[[[-0.48938863950348743,-0.2047484633639432],[-0.754437497113055,-0.27189245758589686],[-0.7571647150316152,-0.27263754927363293],[-0.7597528059794412,-0.27345384489510705],[-0.762196689097137,-0.27433749573492516],[-0.7644912835253068,-0.2752846530776941],[-0.766631508404553,-0.2762914682080201],[-0.7686122828754813,-0.2773540924105103],[-0.7704285260786943,-0.2784686769697708],[-0.772075157154795,-0.2796313731704081],[-0.7735470952443881,-0.28083833229702887],[-0.7748392594880764,-0.28208570563424],[-0.7759465690264644,-0.28336964446664764],[-0.7768639430001549,-0.2846863000788586],[-0.7775863005497534,-0.2860318237554792],[-0.7781085608158618,-0.28740236678111586],[-0.7784256429390837,-0.2887940804403756],[-0.7785324660600237,-0.29020311601786475],[-0.778506439470537,-0.29089804080702064],[-0.7784285770431172,-0.2915909170863704],[-0.7782992047893242,-0.2922812077630926],[-0.7781186487207163,-0.2929683757443658],[-0.777887234848853,-0.2936518839373686],[-0.7776052891852938,-0.29433119524927953],[-0.7772731377415982,-0.29500577258727745],[-0.7768911065293249,-0.295675078858541],[-0.7764595215600352,-0.2963385769702486],[-0.775978708845285,-0.2969957298295789],[-0.775448994396637,-0.29764600034371064],[-0.7748707042256484,-0.2982888514198223],[-0.7742441643438793,-0.2989237459650925],[-0.7735697007628883,-0.2995501468866999],[-0.7728476394942363,-0.3001675170918231],[-0.7720783065494814,-0.30077531948764064],[-0.6059330396697757,-0.42719772120926264],[-0.47239450577598996,-0.3933677755995461],[-0.585684531433059,-0.3072682516987752],[-0.4122914575818526,-0.26334330734195127],[-0.48938863950348743,-0.2047484633639432]]],[[[-0.028250070336481414,-0.06656176761051256],[-0.2093906551160869,-0.020674572173989953],[-0.115694063600976,0.05053211090311452],[-0.11453969460155689,0.051443642438211],[-0.11345627925000312,0.05236952973570416],[-0.11244430348807288,0.053308971204800305],[-0.11150425325752389,0.05426116525470577],[-0.11063661450011497,0.05522531029462678],[-0.1098418731576043,0.05620060473376953],[-0.10912051517174937,0.05718624698134038],[-0.10847302648430968,0.058181435446545623],[-0.10789989303704295,0.05918536853859158],[-0.1074016007717069,0.0601972446666844],[-0.10697863563005994,0.061216262240030475],[-0.1066314835538611,0.062241619667836035],[-0.10636063048486766,0.06327251535930731],[-0.1061665623648389,0.06430814772365051],[-0.10604976513553188,0.06534771517007207],[-0.10601072473870543,0.0663904161077783],[-0.10638392390826246,0.0696332255738606],[-0.10747929404218515,0.07278232448792618],[-0.10926049407835103,0.07582177549766207],[-0.11169118295463631,0.07873564125075533],[-0.11473501960891874,0.08150798439489323],[-0.11835566297907563,0.08412286757776231],[-0.12251677200298383,0.08656435344704984],[-0.12718200561852044,0.08881650465044308],[-0.13231502276356255,0.09086338383562868],[-0.13787948237598746,0.0926890536502937],[-0.14383904339367226,0.09427757674212553],[-0.15015736475449426,0.09561301575881087],[-0.15679810539633054,0.09667943334803683],[-0.1637249242570582,0.09746089215749046],[-0.1709014802745541,0.09794145483485892],[-0.17829143238669554,0.09810518402782903],[-0.1831084038792281,0.09803489774011795],[-0.18786615814003094,0.0978262628191192],[-0.19255153783466272,0.09748261517803519],[-0.1971513856286824,0.09700729073006795],[-0.20165254418764844,0.09640362538841987],[-0.20604185617711823,0.09567495506629287],[-0.2103061642626507,0.09482461567688921],[-0.21443231110980498,0.09385594313341097],[-0.21840713938413847,0.09277227334906062],[-0.22221749175121053,0.09157694223703998],[-0.22585021087657897,0.09027328571055145],[-0.2292921394258025,0.08886463968279716],[-0.23253012006443963,0.08735434006697906],[-0.23555099545804836,0.08574572277629976],[-0.23834160827218742,0.08404212372396107],[-0.24088880117241485,0.08224687882316527],[-0.37795465711490284,-0.02191825243577075],[-0.37872399005965773,-0.02252573095652017],[-0.3794460513283102,-0.02314282046991767],[-0.3801205149093001,-0.023768983883141588],[-0.3807470547910694,-0.024403684103371008],[-0.38132534496205794,-0.025046384037784065],[-0.38185505941070663,-0.02569654659355973],[-0.38233587212545594,-0.026353634677876447],[-0.3827674570947466,-0.02701711119791278],[-0.38314948830701967,-0.027686439060847487],[-0.38348163975071525,-0.028361081173859125],[-0.38376358541427424,-0.029040500444126247],[-0.3839949992861378,-0.029724159778827617],[-0.3841755553547457,-0.030411522085141578],[-0.38430492760853885,-0.031102050270246998],[-0.38438279003595843,-0.03179520724132244],[-0.3844088166254447,-0.032490455905546556],[-0.3843020396382162,-0.03389949148303558],[-0.38398508361380435,-0.03529120514229535],[-0.3834630109581223,-0.03666174816793225],[-0.3827408840770805,-0.03800727184455292],[-0.3818237653765917,-0.03932392745676365],[-0.3807167172625676,-0.04060786628917126],[-0.3794248021409192,-0.041855239626382275],[-0.3779530824175592,-0.043062198753003295],[-0.3763066204984,-0.044224894953640626],[-0.37449047878935193,-0.04533947951290109],[-0.37250971969632785,-0.04640210371539111],[-0.3703694056252389,-0.04740891884571727],[-0.3680745989819978,-0.04835607618848611],[-0.36563036217251543,-0.04923972702830412],[-0.3630417576027045,-0.05005602264977814],[-0.3603138476784764,-0.050801114337514455],[-0.16317433789225722,-0.10074178618280435],[-0.028250070336481414,-0.06656176761051256]]],[[[0.26117510214536765,0.0008457025780110018],[0.24310670394423628,0.00038727091380794717],[0.2261323697804032,-0.0009287657371615222],[0.2102619845703937,-0.0030135198624374453],[0.19550543323073333,-0.005778103949559965],[0.18187260067794653,-0.00913363048606933],[0.16937337182855972,-0.01299121195950579],[0.15801763159909754,-0.01726196085740928],[0.1478152649060851,-0.021856989667320144],[0.13877615666604814,-0.02668741087677833],[0.130910191795512,-0.0316643369733245],[0.12422725521100175,-0.03669888044449827],[0.11873723182904272,-0.0417021537778401],[0.11445000656615978,-0.04658526946088992],[0.11137546433887913,-0.0512593399811882],[0.10952349006372541,-0.05563547782627497],[0.10890396865722418,-0.05962479548369027],[0.11057990591708267,-0.06544555827799345],[0.11539972642258167,-0.07129478429287099],[0.12305144326260486,-0.077116729231173],[0.13322306952603724,-0.08285564879574905],[0.14560261830176224,-0.08845579868944882],[0.1598781026786651,-0.09386143461512236],[0.17573753574562945,-0.0990168122756193],[0.19286893059154053,-0.10386618737378948],[0.21096030030528135,-0.1083538156124825],[0.2296996579757371,-0.11242395269454841],[0.24877501669179214,-0.11602085432283685],[0.2678743895423301,-0.1190887762001974],[0.2866857896162358,-0.12157197402948014],[0.30489723000239355,-0.12341470351353487],[0.32219672378968767,-0.12456122035521111],[0.33827228406700227,-0.12495578025735884],[0.35074136197311945,-0.12460818224009602],[0.3626463107072071,-0.12388954754681755],[0.3739539693576366,-0.12281040751515669],[0.3846311770127784,-0.12138129348274686],[0.3946447727610036,-0.11961273678722144],[0.40396159569068324,-0.11751526876621382],[0.4125484848901886,-0.11509942075735735],[0.42037227944789013,-0.11237572409828561],[0.42739981845215924,-0.10935471012663198],[0.4335979409913666,-0.1060469101800296],[0.43893348615388295,-0.1024628555961119],[0.44337329302808004,-0.09861307771251267],[0.44688420070232815,-0.09450810786686485],[0.44943304826499864,-0.09015847739680208],[0.450986674804462,-0.08557471763995772],[0.45151191940908975,-0.0807673599339651],[0.4504755132840812,-0.07396245461358733],[0.44744440235774174,-0.06700173029895302],[0.44253574780310045,-0.059967265029213825],[0.4358667107931855,-0.05294113684352106],[0.4275544525010262,-0.04600542378102622],[0.41771613409965136,-0.03924220388088116],[0.40646891676208896,-0.032733555182237084],[0.39392996166136873,-0.026561555724245622],[0.3802164299705191,-0.02080828354605819],[0.36544548286256884,-0.015555816686826408],[0.3497342815105471,-0.010886233185701808],[0.333199987087482,-0.006881611081835907],[0.31595976076640264,-0.003624028414380226],[0.2981307637203381,-0.0011955632224859745],[0.27983015712231696,0.0003217064546949073],[0.26117510214536765,0.0008457025780110018]]]],"source":{"artist":"Юкатан; Nikolaev ec06ffa5","license":"CC BY-SA 3.0","license_url":"https://creativecommons.org/licenses/by-sa/3.0/","url":"https://commons.wikimedia.org/wiki/File:RU_road_sign_1.23.svg","source_sha256":"d95ebe7bbdded1453414144c0adaa8327ba742c0cc4bc5464e5013f93d17a607","dimensions_m":[3,1.5],"marking":"1.24.1","sign":"1.23","adaptation":"White road-paint silhouette; curve sampling; longitudinal stretch","compliance":"visual-placement-preset-not-survey-certification"}}]} diff --git a/src/k1link/simulation/ai_polygon/project_worlds.py b/src/k1link/simulation/ai_polygon/project_worlds.py index fb5f7616..556f5e55 100644 --- a/src/k1link/simulation/ai_polygon/project_worlds.py +++ b/src/k1link/simulation/ai_polygon/project_worlds.py @@ -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) :])) diff --git a/src/k1link/simulation/ai_polygon/qualified_maps.py b/src/k1link/simulation/ai_polygon/qualified_maps.py new file mode 100644 index 00000000..8bd68a7c --- /dev/null +++ b/src/k1link/simulation/ai_polygon/qualified_maps.py @@ -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) diff --git a/src/k1link/simulation/ai_polygon/route_preparation.py b/src/k1link/simulation/ai_polygon/route_preparation.py index 5cd99ddf..9d57ab4d 100644 --- a/src/k1link/simulation/ai_polygon/route_preparation.py +++ b/src/k1link/simulation/ai_polygon/route_preparation.py @@ -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): diff --git a/src/k1link/simulation/ai_polygon/runs.py b/src/k1link/simulation/ai_polygon/runs.py index 186ec996..02384116 100644 --- a/src/k1link/simulation/ai_polygon/runs.py +++ b/src/k1link/simulation/ai_polygon/runs.py @@ -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( diff --git a/src/k1link/simulation/ai_polygon/semantic_edits.py b/src/k1link/simulation/ai_polygon/semantic_edits.py new file mode 100644 index 00000000..4f082ec7 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/semantic_edits.py @@ -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 diff --git a/src/k1link/simulation/ai_polygon/semantic_objects.py b/src/k1link/simulation/ai_polygon/semantic_objects.py new file mode 100644 index 00000000..debe7f07 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/semantic_objects.py @@ -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 diff --git a/src/k1link/simulation/ai_polygon/semantic_vectors.py b/src/k1link/simulation/ai_polygon/semantic_vectors.py new file mode 100644 index 00000000..5bb4f5be --- /dev/null +++ b/src/k1link/simulation/ai_polygon/semantic_vectors.py @@ -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] diff --git a/src/k1link/simulation/ai_polygon/urban_maps.py b/src/k1link/simulation/ai_polygon/urban_maps.py index b2b388d6..2339dc00 100644 --- a/src/k1link/simulation/ai_polygon/urban_maps.py +++ b/src/k1link/simulation/ai_polygon/urban_maps.py @@ -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") diff --git a/src/k1link/simulation/ai_polygon/world_library.py b/src/k1link/simulation/ai_polygon/world_library.py new file mode 100644 index 00000000..f4249735 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/world_library.py @@ -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 diff --git a/src/k1link/web/ai_polygon_api.py b/src/k1link/web/ai_polygon_api.py index afcab80d..19259d74 100644 --- a/src/k1link/web/ai_polygon_api.py +++ b/src/k1link/web/ai_polygon_api.py @@ -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}") diff --git a/src/k1link/web/infrastructure_api.py b/src/k1link/web/infrastructure_api.py new file mode 100644 index 00000000..deea8c07 --- /dev/null +++ b/src/k1link/web/infrastructure_api.py @@ -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 diff --git a/src/k1link/web/semantic_edits_api.py b/src/k1link/web/semantic_edits_api.py new file mode 100644 index 00000000..eea6de4f --- /dev/null +++ b/src/k1link/web/semantic_edits_api.py @@ -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 diff --git a/tests/fixtures/semantic_duplicate_direction.json b/tests/fixtures/semantic_duplicate_direction.json new file mode 100644 index 00000000..a304d807 --- /dev/null +++ b/tests/fixtures/semantic_duplicate_direction.json @@ -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" + } +] diff --git a/tests/test_gaussian_infrastructure_pipeline.py b/tests/test_gaussian_infrastructure_pipeline.py new file mode 100644 index 00000000..f98aedb0 --- /dev/null +++ b/tests/test_gaussian_infrastructure_pipeline.py @@ -0,0 +1,185 @@ +"""Source ownership, no-collider admission and shipped pipeline closure.""" +import base64 +import hashlib +import json +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def modules(monkeypatch): + monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) + import infrastructure_gaussian_sources as sources + import infrastructure_pipeline as pipeline + return sources, pipeline + + +def test_original_lcc_and_poses_are_read_only_and_mesh_is_not_opened(modules, tmp_path): + sources, _ = modules + job = "gsp-20261015000000-1234abcd" + root = tmp_path / "jobs" / job + native = root / "work/source-bundle" + native.mkdir(parents=True) + files = {"scan.lcc": b"{}", "data.bin": b"Gaussians"} + members = [] + for name, content in files.items(): + (native/name).write_bytes(content) + members.append(dict(logical_path=name, byte_length=len(content), sha256=hashlib.sha256(content).hexdigest())) + # A producer can include a source mesh. It deliberately does not exist here; + # analysis must neither require it nor treat it as evidence. + members.append(dict(logical_path="Mesh_Files/scene.ply", byte_length=123, sha256="e"*64)) + original = dict(format="lcc", entrypoint="scan.lcc", bundle_sha256="b"*64, members=members) + (root/"job.json").write_text(json.dumps(dict(state="ready", request=dict(source=original)))) + raw = json.dumps(dict(poses=[dict(T=[i*.1, 0, 1.7]) for i in range(120)])).encode() + world = dict(sha256="a"*64, local_scene=dict(visual_rotation=[-180,0,0])) + package = dict(world_sha256=world["sha256"], provider_job_id=job, bundle_sha256="b"*64, + kind="folder", trajectory=dict(base64=base64.b64encode(raw).decode(), + sha256=hashlib.sha256(raw).hexdigest(), byte_length=len(raw))) + before = {p.relative_to(tmp_path).as_posix(): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} + entry, poses, source = sources.resolve_native(package, world, tmp_path, tmp_path/"7z") + assert entry == native/"scan.lcc" and poses == raw and source == original + assert {p.relative_to(tmp_path).as_posix(): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before + (native/"data.bin").write_bytes(b"changed!") + with pytest.raises(ValueError, match="member changed"): + sources.resolve_native(package, world, tmp_path, tmp_path/"7z") + + +def test_native_frames_and_trajectory_must_be_valid(modules, tmp_path): + sources, _ = modules + for values in [[True,0,0], [float("nan"),0,0], [1,2], "xyz"]: + raw = json.dumps(dict(poses=[dict(T=values)]*100)).encode() + with pytest.raises(ValueError, match="coordinate"): + sources.trajectory(raw) + with pytest.raises(ValueError, match="trajectory"): + sources.trajectory(b'{"poses":[]}') + with pytest.raises(ValueError, match="calibration"): + sources.resolve_native(dict(world_sha256="a"), + dict(sha256="a", local_scene=dict(visual_rotation=[0,0,0])), tmp_path, tmp_path/"7z") + for member in ["../secret", "/secret", "C:/secret", "x/../../secret", "..\\secret"]: + with pytest.raises(ValueError): + sources.confined(tmp_path, member) + + +def test_analysis_does_not_require_collision_mesh(tmp_path): + from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs + jobs = InfrastructureJobs(tmp_path) + world = dict(sha256="a"*64, world_id="aiworld-"+"a"*32, + local_scene=dict(visual_rotation=[180,0,0]), collider_sha256=None) + row = jobs.request(world) + assert row["status"] == "queued" and row["identity"]["collider_sha256"] is None + assert jobs.request(world) == row + + +def test_bundle_uses_canonical_files_and_fails_if_staged_code_changes(modules, tmp_path): + _, pipeline = modules + definition, files = pipeline.definition_files() + # Complexity is not an acceptance criterion: consolidating the pipeline + # must not fail solely because it uses fewer groups. + assert definition["schema"] == "missioncore.gaussian-infrastructure-pipeline/v1" + assert definition["gaussian_only"] is True and definition["manual_rois"] == [] + names = [group["group"] for group in definition["groups"]] + assert names and len(names) == len(set(names)) + assert all(".runtime" not in p and "qualification" not in p for p in files) + assert not any("apply_review.py" == Path(p).name for p in files) + definition, target, snapshot = pipeline.prepare_layout(tmp_path) + assert len(snapshot) == 64 + group = definition["groups"][0] + alias = next(iter(group["files"])) + (target/group["group"]/alias).write_text("tampered") + with pytest.raises(ValueError, match="module bytes changed"): + pipeline.prepare_layout(tmp_path) + + +def test_analysis_failure_preserves_map_and_releases_only_after_cleanup(modules, monkeypatch, tmp_path): + import infrastructure_preparer as preparer + events = [] + class Client: + instance = "worker" + def request(self, path, body=None, **kwargs): + events.append(body.get("action") if body else "source") + return {} + profile = dict(job_root=str(tmp_path/"jobs"), minimum_free_gib=0, maximum_seconds=60) + original_read = preparer.read_json + monkeypatch.setattr(preparer, "read_json", lambda p: profile if str(p).endswith("worker-profile.json") else original_read(p)) + monkeypatch.setattr(preparer, "provider_identity", lambda: "d"*64) + monkeypatch.setattr(preparer, "prepare_native", lambda *a, **kw: (_ for _ in ()).throw(ValueError("bad source"))) + monkeypatch.setattr(preparer, "cleanup", lambda *a: events.append("cleanup")) + row = dict(key="a"*64, identity=dict(provider_sha256="d"*64), world=dict(world_id="example")) + preparer.prepare_infrastructure(Client(), row, tmp_path/"state", tmp_path/"active.json") + assert events == ["progress", "source", "fail", "cleanup", "release"] + assert not list(tmp_path.rglob("urban-map.json")) + assert not (tmp_path/"active.json").exists() + + +def test_readonly_modules_reserve_dependency_mountpoints(modules, tmp_path): + _, pipeline = modules + module = tmp_path / "source" + vendor = module / "pipeline/vendor" + vendor.mkdir(parents=True) + (vendor / "dependency.whl").write_bytes(b"pinned-wheel") + (module / "stage.py").write_text("pass\n") + definition = dict(groups=[dict(group="stage", stages=["stage"], files={"stage.py": "stage.py"})]) + (module / "pipeline/definition.json").write_text(json.dumps(definition)) + for name in ["config-ortho.json", "config-mv.json", "worker-profile.json"]: + (module / "pipeline" / name).write_text("{}") + _, target, _ = pipeline.prepare_layout(tmp_path / "output", module=module) + slot = target / "stage/dependency.whl" + assert slot.is_file() and slot.read_bytes() == b"" + assert (vendor / "dependency.whl").read_bytes() == b"pinned-wheel" + slot.write_bytes(b"unexpected-content") + with pytest.raises(ValueError, match="Dependency mountpoint changed"): + pipeline.prepare_layout(tmp_path / "output", module=module) + + +def test_archive_trajectory_rejects_ambiguous_and_escaping_members(modules, monkeypatch, tmp_path): + from types import SimpleNamespace + sources, _ = modules + archive = tmp_path/'original.rar' + archive.write_bytes(b'archive') + raw = json.dumps(dict(poses=[dict(T=[i,0,1.7])for i in range(120)])).encode() + listing = f"Path = assets/poses.json\nSize = {len(raw)}\nFolder = -\n" + calls = [] + def run(args, **kwargs): + calls.append(args) + return SimpleNamespace(stdout=listing.encode() if args[1]=='l' else raw) + monkeypatch.setattr(sources.subprocess, 'run', run) + assert sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) == raw + assert calls[-1][-1]=='assets/poses.json' and '-spd' in calls[-1] + listing += '\n'+listing + with pytest.raises(ValueError, match='unambiguous'): + sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) + listing = f"Path = ../poses.json\nSize = {len(raw)}\nFolder = -\n" + with pytest.raises(ValueError, match='source member'): + sources.read_archive_trajectory(archive, tmp_path/'7z', lambda:None) + + +def test_host_coordinator_import_does_not_require_scientific_packages(): + import subprocess,sys + script = f"import sys;sys.path[:0]={[str(ROOT/'src'),str(ROOT/'simulation/ai-polygon')]!r};import infrastructure_preparer" + subprocess.run([sys.executable,'-S','-c',script],check=True,capture_output=True,timeout=10) + + +def test_archive_fallback_is_verified_cached_and_temporary_copy_removed(modules, monkeypatch, tmp_path): + from types import SimpleNamespace + sources, _ = modules + raw = json.dumps(dict(poses=[dict(T=[i,0,1.7])for i in range(120)])).encode() + archive=b'original rar';digest=hashlib.sha256(archive).hexdigest() + descriptor=dict(byte_length=len(archive),sha256=digest) + class Client: + calls=0 + def download_asset(self, path, desc, target, **options): + self.calls+=1 + assert path.endswith('/example/infrastructure-archive') and options['authenticated'] + target.write_bytes(archive) + client=Client() + monkeypatch.setattr(sources.shutil,'disk_usage',lambda _:SimpleNamespace(free=100*1024**3)) + monkeypatch.setattr(sources,'read_archive_trajectory',lambda *args:raw) + call=lambda:sources.transferred_trajectory(descriptor,dict(world_id='example'),tmp_path,dict(sevenzip='7z'),lambda:None,client) + assert call()==raw and call()==raw and client.calls==1 + assert not list(tmp_path.rglob('*.archive')) and not list(tmp_path.rglob('*.part')) + next(tmp_path.rglob('poses.json')).write_text('tampered') + with pytest.raises(ValueError,match='trajectory changed'): + call() diff --git a/tests/test_infrastructure_api.py b/tests/test_infrastructure_api.py new file mode 100644 index 00000000..c78c103e --- /dev/null +++ b/tests/test_infrastructure_api.py @@ -0,0 +1,312 @@ +"""Publication through the HTTP boundary preserves scene and worker ownership.""" + +import copy +import threading +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient +from test_infrastructure_jobs import world +from test_urban_maps import document + +from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs, provider_identity +from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore +from k1link.web.infrastructure_api import build_infrastructure_router + + +@pytest.fixture +def api(tmp_path): + scene = world() + jobs, maps = InfrastructureJobs(tmp_path), UrbanMapStore(tmp_path) + released = [] + + def authenticate(value): + if value != "Bearer test-only": + raise HTTPException(401) + + def heartbeat(value): + if value != "owner": + raise RuntimeError("Worker session expired") + + def invoke(fn, *args): + try: + return fn(*args) + except FileNotFoundError as exc: + raise HTTPException(404) from exc + except ValueError as exc: + raise HTTPException(400) from exc + except RuntimeError as exc: + raise HTTPException(409) from exc + + runs = SimpleNamespace( + lock=threading.RLock(), + heartbeat=heartbeat, + status=lambda: {"worker": {"infrastructure_provider_sha256": provider_identity()}}, + queue=SimpleNamespace(release_simulation=released.append), + ) + app = FastAPI() + app.include_router( + build_infrastructure_router( + jobs, maps, SimpleNamespace(get=lambda _: scene), runs, invoke, authenticate + ) + ) + return TestClient(app), jobs, maps, scene, released + + +def test_publish_is_idempotent_and_releases_only_after_cleanup(api): + client, jobs, maps, scene, released = api + route = f"/worlds/{scene['world_id']}/infrastructure-analysis" + row = client.post(route).json() + assert client.post(route).json() == row + key = row["key"] + jobs.claim(key, "owner") + endpoint = f"/worker/infrastructure-analysis/{key}" + headers = {"Authorization": "Bearer test-only", "Worker-Instance": "owner"} + doc = document(scene) + doc["analysis"] = dict(job_key=key, scope="whole-scene", provider_sha256=provider_identity()) + assert ( + client.post( + endpoint, json={"action": "complete", "map": doc}, headers={"Worker-Instance": "owner"} + ).status_code + == 401 + ) + assert client.post(endpoint, json=[], headers=headers).status_code == 400 + stale = copy.deepcopy(doc) + stale["analysis"]["provider_sha256"] = "f" * 64 + assert ( + client.post( + endpoint, json={"action": "complete", "map": stale}, headers=headers + ).status_code + == 400 + ) + assert ( + client.post(endpoint, json={"action": "complete", "map": doc}, headers=headers).status_code + == 200 + ) + assert maps.get(scene) == doc + assert ( + client.post(endpoint, json={"action": "complete", "map": doc}, headers=headers).status_code + == 200 + ) + assert not released and jobs.pending()["status"] == "ready" + changed = copy.deepcopy(doc) + changed["features"] = [] + assert ( + client.post( + endpoint, json={"action": "complete", "map": changed}, headers=headers + ).status_code + == 400 + ) + assert maps.get(scene) == doc + assert client.post(endpoint, json={"action": "release"}, headers=headers).status_code == 200 + assert released == ["aicache-" + key] and jobs.pending() is None + + +def test_force_request_does_not_publish_or_destroy_previous_map(api): + client, jobs, maps, scene, released = api + route = f"/worlds/{scene['world_id']}/infrastructure-analysis" + old = document(scene) + maps.save(scene, old) + assert client.post(route, json={"force": True}).status_code == 400 + assert client.post(route, json={"force": "yes", "request_id": "a" * 32}).status_code == 422 + request = {"force": True, "request_id": "a" * 32} + first = client.post(route, json=request) + assert first.status_code == 202 + assert client.post(route, json=request).json()["key"] == first.json()["key"] + assert maps.get(scene) == old + assert first.json()["progress"]["eta_seconds"] > 0 + assert client.get(route).json()["progress"]["fraction"] is None + + +def test_cancellation_rejects_late_publication_until_owned_cleanup(api): + client, jobs, maps, scene, released = api + route = f"/worlds/{scene['world_id']}/infrastructure-analysis" + old = document(scene) + maps.save(scene, old) + row = client.post(route).json() + key = row["key"] + jobs.claim(key, "owner") + assert client.post(route + "/" + key + "/cancel").json()["cancel_requested"] + headers = {"Authorization": "Bearer test-only", "Worker-Instance": "owner"} + endpoint = f"/worker/infrastructure-analysis/{key}" + assert ( + client.post( + endpoint, + json=dict(action="progress", phase="survey", completed=0, total=91), + headers=headers, + ).status_code + == 409 + ) + doc = document(scene) + doc["analysis"] = dict(job_key=key, scope="whole-scene", provider_sha256=provider_identity()) + assert ( + client.post(endpoint, json=dict(action="complete", map=doc), headers=headers).status_code + == 409 + ) + assert maps.get(scene) == old and not released + assert ( + client.post(endpoint, json=dict(action="release"), headers=headers).json()["status"] + == "cancelled" + ) + assert released == ["aicache-" + key] + assert client.get("/infrastructure-analysis/queue").json() == {"jobs": []} + + +def test_real_worker_poll_advances_only_after_global_reservation_release(tmp_path, monkeypatch): + from test_observatory_recorded_jobs import _definitions + + from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue + from k1link.web.ai_polygon_api import build_ai_polygon_router + + monkeypatch.setattr( + "k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64 + ) + jobs = InfrastructureJobs(tmp_path) + first = jobs.request(world()) + second_world = {**world(), "world_id": "aiworld-" + "b" * 32, "sha256": "d" * 64} + second = jobs.request(second_world) + queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions()) + app = FastAPI() + app.include_router(build_ai_polygon_router(tmp_path, queue)) + token = (tmp_path / "ai-polygon/worker.token").read_text() + headers = {"Authorization": "Bearer " + token, "Worker-Instance": "a" * 32} + root = "/api/v1/ai-polygon" + with TestClient(app) as client: + registered = client.post( + root + "/worker/register", + headers=headers, + json={ + "worker_id": "worker-006", + "instance_id": "a" * 32, + "runtime": "isaac-sim-6.1", + "model_ids": ["ddrnet-goose-pytorch-reference", "rf_detr_large"], + "profile_sha256": "b" * 64, + "runtime_sources": {k: "c" * 64 for k in ("worker", "scene", "models", "robot")}, + "infrastructure_provider_sha256": "f" * 64, + }, + ) + assert registered.status_code == 200 + + def poll(): + r = client.post(root + "/worker/poll", headers=headers, json={"instance_id": "a" * 32}) + assert r.status_code == 200 + return r.json() + + def update(row, action): + return client.post( + root + "/worker/infrastructure-analysis/" + row["key"], + headers=headers, + json={"action": action}, + ) + + assert poll()["analysis"]["key"] == first["key"] + assert update(first, "fail").status_code == 200 + assert poll()["action"] == "idle" + with pytest.raises(RuntimeError): + queue.reserve_simulation("airun-" + "c" * 32) + assert update(first, "release").status_code == 200 + assert poll()["analysis"]["key"] == second["key"] + route = root + "/worlds/" + second_world["world_id"] + "/infrastructure-analysis/" + assert client.post(route + second["key"] + "/cancel").status_code == 200 + assert poll()["action"] == "idle" + assert update(second, "release").status_code == 200 + assert poll()["action"] == "idle" + queue.reserve_simulation("airun-" + "c" * 32) + queue.release_simulation("airun-" + "c" * 32) + + +@pytest.mark.parametrize("cancel_during_outage", [False, True]) +def test_real_core_restart_preserves_running_job_and_same_worker( + tmp_path, monkeypatch, cancel_during_outage +): + from pathlib import Path + + from test_observatory_recorded_jobs import _definitions + + from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue + from k1link.simulation.ai_polygon.worlds import WorldStore + from k1link.web.ai_polygon_api import build_ai_polygon_router + + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "simulation/ai-polygon")) + from core_client import CoreRequestRejected + from infrastructure_transport import report_progress + + monkeypatch.setattr( + "k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64 + ) + scene = world() + monkeypatch.setattr(WorldStore, "get", lambda self, key: scene) + root = "/api/v1/ai-polygon" + hello = dict( + worker_id="worker-006", + instance_id="a" * 32, + runtime="isaac-sim-6.1", + model_ids=["ddrnet-goose-pytorch-reference", "rf_detr_large"], + profile_sha256="b" * 64, + runtime_sources={k: "c" * 64 for k in ("worker", "scene", "models", "robot")}, + infrastructure_provider_sha256="f" * 64, + ) + + def core(): + queue = ObservatoryRecordedJobQueue(tmp_path, definitions=_definitions()) + app = FastAPI() + app.include_router(build_ai_polygon_router(tmp_path, queue)) + return TestClient(app), queue + + api, queue = core() + token = (tmp_path / "ai-polygon/worker.token").read_text() + headers = {"Authorization": "Bearer " + token, "Worker-Instance": hello["instance_id"]} + + class Client: + instance = hello["instance_id"] + + def request(self, path, body=None): + response = api.post(root + path, headers=headers, json=body) + if response.status_code != 200: + raise CoreRequestRejected(response.status_code, response.json().get("detail")) + return response.json() + + client = Client() + client.request("/worker/register", hello) + jobs = InfrastructureJobs(tmp_path) + first = jobs.request(scene) + second = jobs.request({**scene, "world_id": "aiworld-" + "c" * 32, "sha256": "e" * 64}) + assert ( + client.request("/worker/poll", dict(instance_id=client.instance))["analysis"]["key"] + == first["key"] + ) + endpoint = "/worker/infrastructure-analysis/" + first["key"] + assert report_progress( + client, endpoint, dict(phase="survey", completed=8, total=90), hello=hello + ) + api.close() + # Reconstruct the actual Core router and queue from the same persisted state: + # Worker registration is lost, the job and exclusive GPU reservation survive. + api, queue = core() + jobs = InfrastructureJobs(tmp_path) + if cancel_during_outage: + jobs.cancel(first["key"]) + with pytest.raises(RuntimeError): + queue.reserve_simulation("airun-" + "d" * 32) + if cancel_during_outage: + with pytest.raises(CoreRequestRejected, match="409"): + report_progress( + client, endpoint, dict(phase="refining", completed=9, total=90), hello=hello + ) + assert jobs.get(first["key"])["completed"] == 8 + else: + assert report_progress( + client, endpoint, dict(phase="refining", completed=9, total=90), hello=hello + ) + assert jobs.get(first["key"])["completed"] == 9 + doc = document(scene) + doc["analysis"] = dict(job_key=first["key"], scope="whole-scene", provider_sha256="f" * 64) + assert client.request(endpoint, dict(action="complete", map=doc))["status"] == "ready" + assert jobs.pending()["key"] == first["key"] + assert client.request(endpoint, dict(action="release"))["released"] + assert ( + client.request("/worker/poll", dict(instance_id=client.instance))["analysis"]["key"] + == second["key"] + ) + api.close() diff --git a/tests/test_infrastructure_idle_pending.py b/tests/test_infrastructure_idle_pending.py new file mode 100644 index 00000000..c136cd76 --- /dev/null +++ b/tests/test_infrastructure_idle_pending.py @@ -0,0 +1,34 @@ +"""Idle polls do no provider hashing; queued work still verifies current code.""" +import pytest +from test_infrastructure_jobs import world + +from k1link.simulation.ai_polygon import infrastructure_jobs as module + + +@pytest.mark.parametrize("status,released", [("running", False), ("ready", False), + ("failed", True), ("ready", True)]) +def test_pending_without_queue_does_not_read_source_tree(tmp_path, monkeypatch, status, released): + store = module.InfrastructureJobs(tmp_path) + monkeypatch.setattr(module, "provider_identity", lambda: "f" * 64) + row = store.request(world()) + row.update(status=status, released=released) + module.write_json(store.path(row["key"]), row) + + def forbidden(): + raise AssertionError("idle poll hashed provider source") + + monkeypatch.setattr(module, "provider_identity", forbidden) + result = store.pending() + assert result == (row if status == "running" or not released else None) + store.path(row["key"]).unlink() + assert store.pending() is None + + +def test_queued_work_rechecks_identity_and_rejects_source_change(tmp_path, monkeypatch): + store = module.InfrastructureJobs(tmp_path) + monkeypatch.setattr(module, "provider_identity", lambda: "f" * 64) + row = store.request(world()) + assert store.pending()["key"] == row["key"] + monkeypatch.setattr(module, "provider_identity", lambda: "e" * 64) + assert store.pending() is None + assert store.get(row["key"])["status"] == "failed" diff --git a/tests/test_infrastructure_jobs.py b/tests/test_infrastructure_jobs.py new file mode 100644 index 00000000..e2a18596 --- /dev/null +++ b/tests/test_infrastructure_jobs.py @@ -0,0 +1,301 @@ +"""Admission, restart and zero-copy inputs for full-location mapping.""" + +import importlib.util +import json +from pathlib import Path + +import pytest + +from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs + +ROOT = Path(__file__).resolve().parents[1] + + +def world(): + return dict( + world_id="aiworld-" + "a" * 32, + sha256="b" * 64, + collider_sha256="c" * 64, + local_scene=dict(visual_rotation=[0, 0, 0], collision_rotation=[0, 0, 0]), + ) + + +def test_idempotency_owner_and_restart_do_not_release_early(tmp_path): + store = InfrastructureJobs(tmp_path) + row = store.request(world()) + key = row["key"] + assert store.request(world()) == row + store.claim(key, "owner") + with pytest.raises(RuntimeError): + store.claim(key, "other") + store.update(key, dict(action="fail"), "owner") + assert store.pending()["key"] == key + assert store.request(world())["status"] == "failed" + with pytest.raises(RuntimeError): + store.update(key, dict(action="release"), "other") + store.update(key, dict(action="release", previous_owner="owner"), "restarted-worker") + assert store.pending() is None + assert store.request(world())["status"] == "queued" + + +def test_completed_map_still_holds_gpu_until_cleanup(tmp_path): + store = InfrastructureJobs(tmp_path) + key = store.request(world())["key"] + store.claim(key, "owner") + store.update(key, dict(action="complete", result={"sha256": "d" * 64}), "owner") + assert store.pending()["status"] == "ready" + assert store.request(world())["status"] == "ready" + store.update(key, dict(action="release"), "owner") + assert store.pending() is None + changed = world() + changed["collider_sha256"] = "e" * 64 + assert store.current(changed) is None + + +def test_invalid_progress_and_old_provider(tmp_path, monkeypatch): + store = InfrastructureJobs(tmp_path) + key = store.request(world())["key"] + store.claim(key, "owner") + for body in [ + dict(phase="copy-source", completed=0, total=10), + dict(phase="survey", completed=11, total=10), + ]: + with pytest.raises(ValueError): + store.update(key, dict(action="progress", **body), "owner") + store.update(key, dict(action="release"), "owner") + store.request(world()) + monkeypatch.setattr( + "k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64 + ) + assert store.pending() is None + assert store.current(world()) is None + assert store.request(world())["key"] != key + + +def sources(): + spec = importlib.util.spec_from_file_location( + "infrastructure_sources", ROOT / "simulation/ai-polygon/infrastructure_sources.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_existing_files_reused_without_writing_or_copying(tmp_path): + module = sources() + w = world() + root = tmp_path / "project-packages" / w["sha256"] + root.mkdir(parents=True) + collider = root / (w["collider_sha256"] + ".decoded.glb") + collider.write_bytes(b"fixture collider") + collider.with_suffix(".json").write_text( + json.dumps(dict(source_sha256=w["collider_sha256"], sha256=module.checksum(collider))) + ) + source = root / "existing.ply" + source.write_bytes(b"fixture complete ply") + source.with_suffix(".json").write_text( + json.dumps( + dict( + source_sha256=w["sha256"], + sha256=module.checksum(source), + coverage="complete-source", + spatially_cropped=False, + lod=1, + ) + ) + ) + (root / "terrain.json").write_text( + json.dumps( + dict( + source_sha256=w["sha256"], + source_collider_sha256=w["collider_sha256"], + collision_rotation=[0, 0, 0], + ) + ) + ) + before = {str(p): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} + resolved, descriptor = module.resolve_sources(w, tmp_path) + assert ( + resolved == root + and descriptor["ply"] == source.name + and descriptor["sha256"] == module.checksum(source) + ) + assert {str(p): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before + source.write_bytes(b"changed") + with pytest.raises(ValueError, match="changed"): + module.resolve_sources(w, tmp_path) + + +def test_absent_scene_does_not_create_a_cache(tmp_path): + with pytest.raises(ValueError, match="prepared shared scene"): + sources().resolve_sources(world(), tmp_path) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize("resources,cpus,memory", [(None,"4","16g"), ({"cpus":8,"memory_gib":24},"8","24g")]) +def test_container_preserves_image_pythonpath_and_shared_readonly_mount(tmp_path, monkeypatch, resources, cpus, memory): + from types import SimpleNamespace + + monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) + import infrastructure_containers as containers + + marker = tmp_path / "active.json" + marker.write_text(json.dumps(dict(key="a" * 64, containers=[]))) + commands = [] + + def docker(*args, **kwargs): + commands.append(args) + output = ( + json.dumps([{"Config": {"Env": ["PYTHONPATH=/vendor/python"]}}]) + if args[:2] == ("image", "inspect") + else "container-id" + ) + return SimpleNamespace(stdout=output, stderr="", returncode=0) + + states = iter( + [ + None, + {"Id": "container-id"}, + {"Id": "container-id", "State": {"Running": False, "ExitCode": 0}}, + ] + ) + monkeypatch.setattr(containers, "docker", docker) + + def inspect(name, key): + assert name == "ndc-infrastructure-" + "a" * 16 + "-survey" + assert key == "a" * 64 + return next(states) + + monkeypatch.setattr(containers, "inspect_owned", inspect) + monkeypatch.setattr(containers, "cleanup", lambda *args: None) + source = tmp_path / "existing-source" + containers.run_container( + marker, + "survey", + "pinned-image", + [(source, "/input", True)], + ["/app/whole_scene.py"], + tmp_path, + lambda: None, + 10, + environment={"PYTHONPATH": "/candidate", "OMP_NUM_THREADS": "2"}, + volumes=[("ndc-test-cache", "/cache")], + readonly=True, + resources=resources, + ) + create = next(c for c in commands if c[0] == "create") + assert ( + "PYTHONPATH=/geometry:/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e:/vendor/python" + in create + ) + assert "type=bind,source=" + str(source.resolve()) + ",target=/input,readonly" in create + assert create[create.index("--network") + 1] == "none" + assert create[create.index("--cpus") + 1] == cpus + assert create[create.index("--memory") + 1] == memory + assert all(command[0] != "update" for command in commands) + assert not source.exists() + + +def test_cleanup_remembers_only_unresolved_containers(tmp_path, monkeypatch): + monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) + import infrastructure_containers as containers + + marker = tmp_path / "active.json" + marker.write_text(json.dumps(dict(key="a" * 64, containers=["missing", "done", "unresolved"]))) + removed = [] + + def inspect(name, key): + if name == "unresolved": + raise RuntimeError("Analysis container identity changed") + return {"Id": "owned-id"} if name == "done" and not removed else None + + monkeypatch.setattr(containers, "inspect_owned", inspect) + monkeypatch.setattr(containers, "docker", lambda *args: removed.append(args)) + with pytest.raises(RuntimeError, match="identity changed"): + containers.cleanup(marker) + assert removed == [("rm", "-f", "owned-id")] + assert json.loads(marker.read_text())["containers"] == ["unresolved"] + monkeypatch.setattr(containers, "inspect_owned", lambda *args: None) + containers.cleanup(marker) + assert json.loads(marker.read_text())["containers"] == [] + + +def test_recalculation_is_new_idempotent_generation_and_preserves_ready(tmp_path): + store = InfrastructureJobs(tmp_path) + first = store.request(world()) + key = first["key"] + store.claim(key, "owner") + store.update(key, dict(action="complete", result={"sha256": "d" * 64}), "owner") + # Cleanup still owns the GPU; force must not enqueue another run yet. + assert store.request(world(), True, "a" * 32)["key"] == key + store.update(key, dict(action="release"), "owner") + old = store.get(key) + new = store.request(world(), True, "a" * 32) + assert new["key"] != key and new["status"] == "queued" + assert store.get(key) == old + assert store.request(world(), True, "a" * 32) == new + assert store.request(world(), True, "b" * 32) == new + assert store.request(world()) == new + assert store.current(world()) == new + store.claim(new["key"], "second") + store.update(new["key"], dict(action="fail"), "second") + store.update(new["key"], dict(action="release"), "second") + assert store.get(key) == old + with pytest.raises(ValueError): + store.request(world(), True, None) + + +def test_eta_uses_stage_costs_never_advances_measured_progress(monkeypatch): + from k1link.simulation.ai_polygon import infrastructure_progress as progress + + stages = [ + dict(label="Обзор", seconds=100), + dict(label="Разметка", seconds=300), + dict(label="Проверка", seconds=100), + ] + monkeypatch.setattr(progress, "plan", lambda: (stages, "measured-run")) + row = dict(status="queued", phase="queued", completed=0, total=0) + queued = progress.progress_view(row, 1000) + assert queued["eta_seconds"] == 540 and queued["fraction"] is None + row.update(status="running", started_at=1000, updated_at=1000) + progress.record_progress(row, "survey", 0, 3, 1000) + progress.record_progress(row, "refining", 1, 3, 1200) + value = progress.progress_view(row, 1205) + assert value["eta_seconds"] == 840 and value["fraction"] == 1 / 3 and value["stage"] == 2 + later = progress.progress_view(row, 1210) + assert later["fraction"] == value["fraction"] + stale = progress.progress_view(row, 1230) + assert stale["stale"] and stale["eta_seconds"] is None + + +def test_heartbeat_does_not_restart_stage_timer_and_regression_is_rejected(tmp_path, monkeypatch): + from k1link.simulation.ai_polygon import infrastructure_jobs as module + + store = InfrastructureJobs(tmp_path) + key = store.request(world())["key"] + store.claim(key, "owner") + monkeypatch.setattr(module.time, "time", lambda: 1000) + body = dict(action="progress", phase="survey", completed=1, total=91) + store.update(key, body, "owner") + monkeypatch.setattr(module.time, "time", lambda: 1005) + row = store.update(key, body, "owner") + assert ( + row["stage_started_at"] == 1000 + and row["updated_at"] == 1005 + and len(row["stage_history"]) == 1 + ) + with pytest.raises(ValueError): + store.update(key, dict(body, completed=0), "owner") + + +@pytest.mark.parametrize("resources", [{"cpus":0}, {"cpus":13}, {"cpus":True}, {"cpus":"8"}, {"memory_gib":7}, {"memory_gib":33}, {"unknown":1}, []]) +def test_invalid_container_resources_fail_before_docker_or_ownership(tmp_path, monkeypatch, resources): + monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) + import infrastructure_containers as containers + def forbidden(*args, **kwargs): + raise AssertionError("Invalid profile reached Docker") + monkeypatch.setattr(containers, "docker", forbidden) + marker=tmp_path/"absent.json" + with pytest.raises(ValueError, match="resource"): + containers.run_container(marker,"test","image",[],[],tmp_path,lambda:None,1,resources=resources) + assert not marker.exists() diff --git a/tests/test_infrastructure_queue.py b/tests/test_infrastructure_queue.py new file mode 100644 index 00000000..5551bff0 --- /dev/null +++ b/tests/test_infrastructure_queue.py @@ -0,0 +1,123 @@ +"""Twenty-job FIFO, crash recovery and cancellation use the real durable store.""" + +import concurrent.futures + +import pytest +from test_infrastructure_jobs import world + +from k1link.simulation.ai_polygon.infrastructure_jobs import InfrastructureJobs + + +@pytest.fixture +def store(tmp_path, monkeypatch): + monkeypatch.setattr( + "k1link.simulation.ai_polygon.infrastructure_jobs.provider_identity", lambda: "f" * 64 + ) + return InfrastructureJobs(tmp_path) + + +def scene(index): + result = world() + result.update(world_id="aiworld-" + format(index, "032x"), sha256=format(index, "064x")) + return result + + +def test_twenty_jobs_run_fifo_after_failure_cancel_and_restart(store): + jobs = [store.request(scene(i)) for i in range(1, 21)] + assert [r["key"] for r in store.queue_rows()] == [r["key"] for r in jobs] + assert store.present(jobs[-1])["queue"]["position"] == 20 + # A caller cannot jump the queue, even if it knows an identity. + with pytest.raises(RuntimeError): + store.claim(jobs[4]["key"], "worker") + first = jobs[0]["key"] + store.claim(first, "worker") + store.update(first, dict(action="fail"), "worker") + assert store.pending()["key"] == first + with pytest.raises(RuntimeError): + store.claim(jobs[1]["key"], "worker") + store.update(first, dict(action="release"), "worker") + assert store.pending()["key"] == jobs[1]["key"] + second = jobs[1]["key"] + store.claim(second, "worker") + store.cancel(second) + with pytest.raises(RuntimeError): + store.update( + second, dict(action="progress", phase="survey", completed=0, total=91), "worker" + ) + with pytest.raises(RuntimeError): + store.update(second, dict(action="complete", result={}), "worker") + assert store.pending()["key"] == second + # Persisted cancellation and cleanup barrier survive a coordinator restart. + restored = InfrastructureJobs(store.root.parents[1]) + assert restored.get(second)["cancel_requested"] + restored.update(second, dict(action="release", previous_owner="worker"), "new-worker") + assert restored.get(second)["status"] == "cancelled" + # Removing a waiting job never acquires a worker or delays its successor. + restored.cancel(jobs[4]["key"]) + seen = [] + while row := restored.pending(): + seen.append(row["key"]) + restored.claim(row["key"], "new-worker") + restored.update(row["key"], dict(action="complete", result={}), "new-worker") + assert restored.pending()["key"] == row["key"] + restored.update(row["key"], dict(action="release"), "new-worker") + assert seen == [j["key"] for i, j in enumerate(jobs) if i not in (0, 1, 4)] + assert restored.queue_rows() == [] + + +def test_parallel_clicks_deduplicate_and_failed_retry_has_new_identity(store): + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + rows = list(pool.map(lambda _: store.request(scene(1), True, "a" * 32), range(20))) + assert len({r["key"] for r in rows}) == 1 and len(store.queue_rows()) == 1 + key = rows[0]["key"] + store.cancel(key) + new = store.request(scene(1)) + assert new["key"] != key and store.get(key)["status"] == "cancelled" + + +def test_pending_limit_is_explicit_and_never_discards_jobs(store): + for i in range(1, 33): + store.request(scene(i)) + with pytest.raises(RuntimeError, match="Очередь заполнена"): + store.request(scene(33)) + assert len(store.queue_rows()) == 32 + + +def test_cancel_during_dispatch_cannot_strand_a_gpu_reservation(store): + import threading + from types import SimpleNamespace + + row = store.request(scene(1)) + entered = threading.Event() + cancel_started = threading.Event() + leases = [] + + def reserve(owner): + entered.set() + assert cancel_started.wait(3) + leases.append(owner) + + def cancel(): + assert entered.wait(3) + cancel_started.set() + return store.cancel(row["key"]) + + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + dispatched = pool.submit( + store.dispatch, "worker", SimpleNamespace(reserve_simulation=reserve), "f" * 64 + ) + cancelled = pool.submit(cancel) + assert dispatched.result(timeout=5)["status"] == "running" + assert cancelled.result(timeout=5)["status"] == "running" + assert leases == ["aicache-" + row["key"]] + assert store.get(row["key"])["cancel_requested"] + store.update(row["key"], dict(action="release"), "worker") + assert store.pending() is None + # Cancel before dispatch must not take any reservation. + waiting = store.request(scene(2)) + store.cancel(waiting["key"]) + assert ( + store.dispatch("worker", SimpleNamespace(reserve_simulation=leases.append), "f" * 64) + is None + ) + assert len(leases) == 1 diff --git a/tests/test_infrastructure_recovery.py b/tests/test_infrastructure_recovery.py new file mode 100644 index 00000000..744532e1 --- /dev/null +++ b/tests/test_infrastructure_recovery.py @@ -0,0 +1,248 @@ +"""Transient transport loss and a lost release receipt never strand the coordinator.""" + +import http.client +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def preparer(monkeypatch): + monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) + import infrastructure_preparer + + monkeypatch.setattr(infrastructure_preparer.time, "sleep", lambda seconds: None) + return infrastructure_preparer + + +@pytest.mark.parametrize( + "error", [ConnectionAbortedError, http.client.RemoteDisconnected, TimeoutError] +) +def test_indefinite_transport_loss_is_not_calculation_failure(preparer, error): + calls = [] + + class Client: + def request(self, endpoint, body): + calls.append((endpoint, body)) + raise error() + + phase = dict(phase="survey", completed=1, total=90) + for _ in range(100): + assert preparer.report_progress(Client(), "/job", phase) is None + assert calls == [("/job", dict(action="progress", **phase))] * 100 + + +@pytest.mark.parametrize("status", [400, 401, 403, 409]) +def test_confirmed_rejection_still_stops_calculation(preparer, status): + from core_client import CoreRequestRejected + + calls = [] + + class Client: + def request(self, *args): + calls.append(args) + raise CoreRequestRejected(status, "cancelled or invalid owner") + + with pytest.raises(CoreRequestRejected): + preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90)) + assert len(calls) == 1 + + +@pytest.mark.parametrize("status", [500, 502, 503, 504]) +def test_temporary_gateway_outage_keeps_calculation(preparer, status): + from core_client import CoreRequestRejected + + class Client: + def request(self, *args): + raise CoreRequestRejected(status, "upstream unavailable") + + assert ( + preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90)) + is None + ) + + +def test_core_restart_recovers_registration_without_reclaim(preparer): + from core_client import CoreRequestRejected + from infrastructure_transport import EXPIRED_SESSION + + calls = [] + + class Client: + instance = "same-owner" + + def request(self, endpoint, body): + calls.append((endpoint, body)) + if len(calls) == 1: + raise CoreRequestRejected(409, EXPIRED_SESSION) + return {"ok": True} + + phase = dict(phase="survey", completed=8, total=90) + hello = dict(instance_id="same-owner", immutable_provider="same-provider") + assert preparer.report_progress(Client(), "/job", phase, hello=hello) == {"ok": True} + assert calls == [ + ("/job", dict(action="progress", **phase)), + ("/worker/register", hello), + ("/job", dict(action="progress", **phase)), + ] + + +@pytest.mark.parametrize("failure", ["transport", "cleanup"]) +def test_failed_receipt_keeps_marker_until_reconnect_and_cleanup( + preparer, monkeypatch, tmp_path, failure +): + events = [] + + class Client: + instance = "worker" + online = False + + def request(self, path, body=None, **kwargs): + action = body.get("action") if body else "source" + events.append(action) + if action in ("fail", "release") and not self.online: + raise ConnectionAbortedError() + return {} + + client = Client() + profile = dict(job_root=str(tmp_path / "jobs"), minimum_free_gib=0, maximum_seconds=60) + read = preparer.read_json + monkeypatch.setattr( + preparer, + "read_json", + lambda p: profile if str(p).endswith("worker-profile.json") else read(p), + ) + monkeypatch.setattr(preparer, "provider_identity", lambda: "d" * 64) + + def source(*args, **kwargs): + raise ValueError("Invalid source") + + def cleanup(marker): + events.append("cleanup") + if failure == "cleanup" and not client.online: + raise RuntimeError("Docker unavailable; cannot prove release") + + monkeypatch.setattr(preparer, "prepare_native", source) + monkeypatch.setattr(preparer, "cleanup", cleanup) + row = dict( + key="a" * 64, identity=dict(provider_sha256="d" * 64), world=dict(world_id="example") + ) + marker = tmp_path / "active.json" + # The coordinator must regain control even when fail AND release fail. + preparer.prepare_infrastructure(client, row, tmp_path / "state", marker) + assert marker.exists() + assert not list(tmp_path.rglob("urban-map.json")) + if failure == "cleanup": + assert "release" not in events + client.online = True + preparer.reconcile(client, marker) + assert events[-2:] == ["cleanup", "release"] + assert not marker.exists() + # Idempotent retry after acknowledgement cannot release a different job. + count = len(events) + preparer.reconcile(client, marker) + assert len(events) == count + + +def outbox(preparer, monkeypatch, tmp_path): + profile = dict(job_root=str(tmp_path), maximum_seconds=60) + read = preparer.read_json + monkeypatch.setattr( + preparer, + "read_json", + lambda p: profile if str(p).endswith("worker-profile.json") else read(p), + ) + key = "a" * 64 + output = tmp_path / key + output.mkdir() + preparer.write_json(output / "urban-map.json", {"features": [], "verified": "fixture"}) + marker = tmp_path / "active.json" + preparer.write_json( + marker, + dict( + key=key, + owner="worker", + containers=[], + completion=dict(sha256=preparer.checksum(output / "urban-map.json")), + ), + ) + return marker, output + + +@pytest.mark.parametrize("lost_ack", [False, True]) +def test_result_outbox_survives_outage_and_lost_ack(preparer, monkeypatch, tmp_path, lost_ack): + marker, output = outbox(preparer, monkeypatch, tmp_path) + events, maps = [], [] + + class Client: + instance = "worker" + online = False + + def request(self, path, body): + events.append(body["action"]) + if body["action"] == "complete": + if self.online or lost_ack: + if maps: + assert maps[0] == body["map"] + else: + maps.append(body["map"]) + if not self.online: + raise ConnectionResetError() + return {"ok": True} + + client = Client() + for _ in range(4): + with pytest.raises(ConnectionResetError): + preparer.reconcile(client, marker) + assert marker.exists() and preparer.read_json(marker)["completion"] + assert "release" not in events + client.online = True + preparer.reconcile(client, marker) + assert events[-2:] == ["complete", "release"] and len(maps) == 1 + assert not marker.exists() and (output / "urban-map.json").exists() + + +def test_cancel_while_result_offline_rejects_publication_then_releases( + preparer, monkeypatch, tmp_path +): + from core_client import CoreRequestRejected + + marker, output = outbox(preparer, monkeypatch, tmp_path) + events = [] + + class Client: + def request(self, path, body): + events.append(body["action"]) + if body["action"] == "complete": + raise CoreRequestRejected(409, "Analysis cancellation requested") + return {} + + preparer.reconcile(Client(), marker) + assert events == ["complete", "release"] and not marker.exists() + assert (output / "publication-rejection.json").exists() + + +def test_pending_result_tamper_keeps_queue_barrier(preparer, monkeypatch, tmp_path): + marker, output = outbox(preparer, monkeypatch, tmp_path) + (output / "urban-map.json").write_text("{}") + with pytest.raises(ValueError, match="result changed"): + preparer.reconcile(object(), marker) + assert marker.exists() + + +def test_source_read_retries_transport_only(preparer): + calls = [] + + class Client: + def request(self, path, **kwargs): + calls.append(path) + if len(calls) < 5: + raise ConnectionResetError() + return {"source": "verified"} + + assert preparer.source_package(Client(), "/source", lambda: None, float("inf")) == { + "source": "verified" + } + assert len(calls) == 5 diff --git a/tests/test_infrastructure_survey_cache.py b/tests/test_infrastructure_survey_cache.py new file mode 100644 index 00000000..acfbfaea --- /dev/null +++ b/tests/test_infrastructure_survey_cache.py @@ -0,0 +1,36 @@ +import json +from pathlib import Path +import sys +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'simulation/ai-polygon')) +from infrastructure_survey_cache import file_hash, find_survey, record_survey + +def make_survey(tmp_path): + folder=tmp_path/'old';part=folder/'tile-000-000';part.mkdir(parents=True) + request={'source':{'sha256':'source'},'model':{'revision':'model'}} + (part/'job.json').write_text(json.dumps(request)) + files={} + for name in ('top.png','top.geometry.npz','surface-atlas.npz'): + (part/name).write_bytes(b'original-derived-data');files[name]=file_hash(part/name) + (part/'survey-receipt.json').write_text(json.dumps({'status':'surveyed','job_sha256':file_hash(part/'job.json'),'files':files})) + (folder/'tile-index.json').write_text(json.dumps({'tiles':[{'id':part.name,'status':'surveyed'}]})) + return folder,request + +def test_reuse_returns_existing_directory_without_copy_and_rejects_changed_data(tmp_path): + folder,request=make_survey(tmp_path) + record_survey(folder,request,'survey-v1',lambda:None) + before={str(p.relative_to(tmp_path)) for p in tmp_path.rglob('*')} + assert find_survey(tmp_path,request,'survey-v1',lambda:None)==folder + assert before=={str(p.relative_to(tmp_path)) for p in tmp_path.rglob('*')} + assert find_survey(tmp_path,request,'survey-v2',lambda:None) is None + assert find_survey(tmp_path,{**request,'source':{}},'survey-v1',lambda:None) is None + (folder/'tile-000-000/top.png').write_bytes(b'corrupt') + assert find_survey(tmp_path,request,'survey-v1',lambda:None) is None + +def test_partial_survey_is_never_admitted_as_complete(tmp_path): + folder,request=make_survey(tmp_path) + (folder/'tile-index.json').write_text(json.dumps({'tiles':[{'id':'tile-000-000','status':'pending'}]})) + with pytest.raises(ValueError,match='incomplete'): + record_survey(folder,request,'survey-v1',lambda:None) + assert not (folder/'survey-cache.json').exists() diff --git a/tests/test_project_worlds_visual_only.py b/tests/test_project_worlds_visual_only.py new file mode 100644 index 00000000..e1386f18 --- /dev/null +++ b/tests/test_project_worlds_visual_only.py @@ -0,0 +1,87 @@ +"""A missing optional collider must not hide a valid Gaussian project.""" +import hashlib +from types import SimpleNamespace + +import pytest + +from k1link.simulation.ai_polygon.editor_cache import EditorCache +from k1link.simulation.ai_polygon.project_worlds import ProjectWorlds +from k1link.simulation.ai_polygon.contracts import RunCreate +from test_ai_polygon import runs + + +def project_worlds(tmp_path, collision): + pid = "sim-" + "a" * 32 + prefix = f"/api/v1/simulation-worlds/projects/{pid}/artifacts/" + artifacts = [] + for name in ["streamed/lod-meta.json"] + (["collision.glb"] if collision else []): + path = tmp_path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"fixture") + artifacts.append(dict(logical_path=name, byte_length=7, + sha256=hashlib.sha256(b"fixture").hexdigest())) + project = dict(project_id=pid, name="Gaussian scan", created_at_utc="2026-10-15T00:00:00Z", + source={"bundle_sha256": "b" * 64}, provider={"job_id": "gsp-test"}, + artifacts=artifacts, + viewer_settings={k: {"rotation_degrees": dict(x=0, y=0, z=0)} + for k in ("visual", "collision")}, + world_manifest={"visual": dict(streamed_sog_url=prefix + artifacts[0]["logical_path"], + preview_sog_url=None), + "collision": {"mesh_url": prefix + "collision.glb" if collision else None}}) + worlds = object.__new__(ProjectWorlds) + worlds.projects = SimpleNamespace(get=lambda _: project, list=lambda: [project], + artifact_path=lambda _, name: (tmp_path / name, next(a for a in artifacts if a["logical_path"] == name))) + return worlds, project + + +@pytest.mark.parametrize("collision", [False, True]) +def test_catalog_package_and_editor_preserve_available_assets(tmp_path, collision): + projects, project = project_worlds(tmp_path, collision) + world, = projects.list() + assert world["settings"]["prepared"] + assert world["inference_ready"] is collision + assert bool(world["collider_sha256"]) is collision + assert bool(world["inference_message"]) is not collision + package = projects.package(world) + assert package["visual_path"] == "streamed/lod-meta.json" + assert package["collision_path"] == ("collision.glb" if collision else None) + cache = EditorCache(tmp_path / "cache", SimpleNamespace(projects=projects, get=lambda _: world)) + row = cache.request(world["world_id"]) + assert row["status"] == "ready" + assert set(row["files"]) == ({"scene.sog", "collision.glb"} if collision else {"scene.sog"}) + assert cache.get(row["key"])["local_scene"] == world["local_scene"] + + +def test_present_but_invalid_collider_is_not_silently_ignored(tmp_path): + worlds, project = project_worlds(tmp_path, True) + project["world_manifest"]["collision"]["mesh_url"] = "https://example.invalid/collision.glb" + with pytest.raises(ValueError, match="отсутствует"): + worlds.list() + + +def test_missing_visual_is_still_rejected(tmp_path): + worlds, project = project_worlds(tmp_path, False) + project["world_manifest"]["visual"]["streamed_sog_url"] = None + with pytest.raises(ValueError, match="отсутствует"): + worlds.list() + + +def test_visual_only_world_cannot_start_rover(runs, monkeypatch): + store, _, world = runs + world.update(inference_ready=False, inference_message="Нужна поверхность коллизий.") + monkeypatch.setattr(store.worlds, "get", lambda _: world) + with pytest.raises(RuntimeError, match="Нужна поверхность"): + store.start(RunCreate(world_id=world["world_id"]), "visual-only-world-test") + + +def test_analysis_archive_is_bound_to_world_and_confined(tmp_path): + worlds, project = project_worlds(tmp_path, False) + raw=b'original archive';(tmp_path/'scan.rar').write_bytes(raw) + project['source'].update(kind='archive',files=[dict(logical_path='scan.rar',byte_length=len(raw),sha256=hashlib.sha256(raw).hexdigest())]) + worlds.projects.source_root=lambda _:tmp_path + world=worlds.world(project) + path,descriptor=worlds.analysis_archive(world) + assert path.read_bytes()==raw and descriptor['sha256']==hashlib.sha256(raw).hexdigest() + project['source']['files'][0]['logical_path']='../scan.rar' + with pytest.raises(ValueError,match='escaped'): + worlds.analysis_archive(world) diff --git a/tests/test_qualified_urban_maps.py b/tests/test_qualified_urban_maps.py new file mode 100644 index 00000000..48fcbc69 --- /dev/null +++ b/tests/test_qualified_urban_maps.py @@ -0,0 +1,85 @@ +import copy +import hashlib +import json + +import pytest + +from k1link.simulation.ai_polygon.qualified_maps import qualified_document +from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore, validate_map + + +def source(): + return dict(schema_version="missioncore.refined-full-plan-research/v1", type="FeatureCollection", + point_clouds=False, manual_geometry=False, features=[dict(type="Feature", id="front-1", + properties=dict(**{"class": "building_facade"}, review_status="unreviewed"), + geometry=dict(type="LineString", coordinates=[[1, 2, 3], [4, 5, 6]]))]) + + +WORLD = {"sha256": "a" * 64, "collider_sha256": "b" * 64} + + +def adapt(plan=None, **kwargs): + raw = json.dumps(source() if plan is None else plan).encode() + options = dict(artifact_sha256=hashlib.sha256(raw).hexdigest(), source_world_sha256=WORLD["sha256"], + qualification="symbol-pass-20261014", source_snapshot="test", tiles_total=3) + return qualified_document(raw, WORLD, **{**options, **kwargs}) + + +def test_lossless_geometry_and_honest_confidence(tmp_path): + plan = source() + result = adapt(plan) + assert result["features"][0]["geometry"] == plan["features"][0]["geometry"] + p = result["features"][0]["properties"] + assert p["confidence"] is None and p["confidence_status"] == "not-assessed" + assert p["authority"] == "observation-only" and p["route_permission"] == "unassigned" + assert "confidence" not in plan["features"][0]["properties"] + store = UrbanMapStore(tmp_path) + store.save(WORLD, result) + assert store.get(WORLD) == result + + +@pytest.mark.parametrize("change", [dict(artifact_sha256="0" * 64), dict(source_world_sha256="c" * 64), dict(tiles_total=-1)]) +def test_changed_or_foreign_source_rejected(change): + with pytest.raises(ValueError): adapt(**change) + + +@pytest.mark.parametrize("property,value", [("route_permission", "allowed"), ("authority", "navigation")]) +def test_import_never_promotes_authority(property, value): + plan = source(); plan["features"][0]["properties"][property] = value + with pytest.raises(ValueError): adapt(plan) + + +def test_null_confidence_requires_v3_explicit_unknown(): + result = adapt() + bad = copy.deepcopy(result); bad["schema_version"] = "missioncore.urban-map/v2" + with pytest.raises(ValueError): validate_map(bad, WORLD) + bad = copy.deepcopy(result); del bad["features"][0]["properties"]["confidence_status"] + with pytest.raises(ValueError): validate_map(bad, WORLD) + bad = copy.deepcopy(result); bad["features"][0]["properties"]["confidence"] = float("nan") + with pytest.raises(ValueError): validate_map(bad, WORLD) + + +def test_polygons_holes_and_open_ends_stay_exact(): + plan = source(); plan["features"].append(dict(type="Feature", id="bike-1", + properties={"class":"road_marking","subtype":"bicycle"}, geometry=dict(type="Polygon",coordinates=[ + [[0,0,0],[4,0,0],[4,4,0],[0,4,0],[0,0,0]],[[1,1,0],[1,2,0],[2,2,0],[2,1,0],[1,1,0]]]))) + result = adapt(plan) + assert [f["geometry"] for f in result["features"]] == [f["geometry"] for f in plan["features"]] + + +def test_systematic_plan_is_lossless_and_keeps_observation_authority(): + plan = source() + plan["schema_version"] = "missioncore.systematic-plan/v1" + result = adapt(plan) + assert result["features"][0]["geometry"] == plan["features"][0]["geometry"] + assert result["features"][0]["properties"]["route_permission"] == "unassigned" + plan["features"][0]["properties"]["authority"] = "navigation" + with pytest.raises(ValueError): + adapt(plan) + + +def test_unregistered_plan_schema_still_fails(): + plan = source() + plan["schema_version"] = "missioncore.systematic-plan/v999" + with pytest.raises(ValueError, match="qualified automatic Gaussian plan"): + adapt(plan) diff --git a/tests/test_route_pending_index.py b/tests/test_route_pending_index.py new file mode 100644 index 00000000..53ba338a --- /dev/null +++ b/tests/test_route_pending_index.py @@ -0,0 +1,120 @@ +"""Idle Worker polling must not repeatedly parse completed scene geometry.""" +import json +import os +from pathlib import Path + +import pytest + +from k1link.simulation.ai_polygon.route_preparation import RoutePreparationStore +from k1link.simulation.ai_polygon.run_inputs import digest + + +def put(store, identity=None, status="failed", owner=None): + identity = identity or {"case": 1} + key = digest(identity) + row = dict(key=key, identity=identity, status=status, owner=owner, result=None) + path = store.path(key) + path.write_text(json.dumps(row)) + return path, row + + +def test_idle_scan_skips_unchanged_completed_payload(tmp_path, monkeypatch): + store = RoutePreparationStore(tmp_path) + path, _ = put(store) + assert store.pending() is None + original = Path.read_text + + def forbid_read(candidate, *args, **kwargs): + assert candidate != path, "unchanged completed geometry was parsed again" + return original(candidate, *args, **kwargs) + + monkeypatch.setattr(Path, "read_text", forbid_read) + assert store.pending() is None + assert store.pending() is None + + +def test_external_same_size_change_preserved_mtime_is_not_hidden(tmp_path): + store = RoutePreparationStore(tmp_path) + path, row = put(store) + assert store.pending() is None + before = path.stat() + row["status"] = "queued" # exactly the same encoded length + path.write_text(json.dumps(row)) + os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns)) + assert path.stat().st_size == before.st_size + assert store.pending() == row + assert store.claim(row["key"], "worker")["status"] == "preparing" + with pytest.raises(RuntimeError, match="another Worker"): + store.claim(row["key"], "other") + + +def test_atomic_replacement_and_new_jobs_are_visible(tmp_path): + store = RoutePreparationStore(tmp_path) + path, row = put(store) + assert store.pending() is None + row["status"] = "queued" + replacement = path.with_suffix(".tmp") + replacement.write_text(json.dumps(row)) + replacement.replace(path) + assert store.pending() == row + path.unlink() + assert store.pending() is None + assert not store._inactive_files + _, other = put(store, {"case": 2}, "queued") + assert store.pending() == other + + +def test_pending_and_claim_still_validate_identity(tmp_path): + store = RoutePreparationStore(tmp_path) + path, row = put(store) + assert store.pending() is None + row.update(status="queued", identity={"forged": True}) + path.write_text(json.dumps(row)) + with pytest.raises(ValueError, match="identity changed"): + store.pending() + with pytest.raises(ValueError, match="identity changed"): + store.claim(row["key"], "worker") + + +def test_broken_changed_file_and_symlink_fail_closed(tmp_path): + store = RoutePreparationStore(tmp_path) + path, _ = put(store) + assert store.pending() is None + path.write_text("{") + with pytest.raises(json.JSONDecodeError): + store.pending() + path.unlink() + target = tmp_path / "target.json" + target.write_text("{}") + path.symlink_to(target) + with pytest.raises(ValueError, match="Invalid route"): + store.pending() + + +def test_metadata_index_bounded_and_contains_no_geometry(tmp_path): + store = RoutePreparationStore(tmp_path) + for number in range(514): + put(store, {"case": number}) + assert store.pending() is None + assert len(store._inactive_files) == 512 + assert all(len(stamp) == 5 and all(isinstance(n, int) for n in stamp) + for stamp in store._inactive_files.values()) + + +def test_file_changed_during_parse_is_not_cached(tmp_path, monkeypatch): + store = RoutePreparationStore(tmp_path) + path, row = put(store) + original = Path.read_text + + def mutate(candidate, *args, **kwargs): + content = original(candidate, *args, **kwargs) + if candidate == path: + row["status"] = "queued" + path.write_text(json.dumps(row)) + return content + + monkeypatch.setattr(Path, "read_text", mutate) + assert store.pending() is None + assert not store._inactive_files + monkeypatch.setattr(Path, "read_text", original) + assert store.pending() == row diff --git a/tests/test_semantic_edits.py b/tests/test_semantic_edits.py new file mode 100644 index 00000000..3af75471 --- /dev/null +++ b/tests/test_semantic_edits.py @@ -0,0 +1,240 @@ +"""Human revisions never mutate inference; test failures before/after durable commit.""" + +import copy +import json +from concurrent.futures import ThreadPoolExecutor + +import pytest +from test_urban_maps import document + +from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, apply_operations +from k1link.simulation.ai_polygon.urban_maps import UrbanMapStore + + +def make_setup(tmp_path): + world = {"sha256": "a" * 64, "collider_sha256": "b" * 64} + model = document(world) + model["schema_version"] = "missioncore.urban-map/v3" + model["source"].update(gaussian_only=True, artifact_sha256="c" * 64) + model["features"] = [ + { + "type": "Feature", + "id": "curb-1", + "properties": { + "class": "curb", + "authority": "observation-only", + "route_permission": "unassigned", + "confidence": 0.9, + "review_status": "accepted", + }, + "geometry": {"type": "LineString", "coordinates": [[0, 0, 2], [2, 0, 2], [4, 1, 2]]}, + }, + { + "type": "Feature", + "id": "facade-1", + "properties": { + "class": "building_facade", + "authority": "observation-only", + "route_permission": "unassigned", + "confidence": 0.8, + "review_status": "accepted", + }, + "geometry": {"type": "LineString", "coordinates": [[0, 5, 2], [4, 5, 2]]}, + }, + ] + maps = UrbanMapStore(tmp_path) + receipt = maps.save(world, model) + store = SemanticEdits(tmp_path, maps) + return world, model, maps, store, receipt["sha256"] + + +@pytest.fixture +def setup(tmp_path): + return make_setup(tmp_path) + + +def change(sha, *, request="first-request-0001", parent=None): + return { + "expected_revision": parent, + "model_sha256": sha, + "request_id": request, + "operations": [ + {"kind": "move", "feature_id": "curb-1", "path": 0, "index": 1, "position": [2, 0.5, 2]} + ], + } + + +def test_save_restart_repeat_and_source_immutability(setup): + world, model, maps, store, sha = setup + saved = store.save(world, change(sha)) + assert maps.get(world) == model + assert saved["model"] == model + assert saved["edited"]["features"][1] == model["features"][1] + assert saved["edited"]["schema_version"] == "missioncore.urban-edit/v1" + assert "gaussian_only" not in saved["edited"]["source"] + assert not saved["learning"]["dataset_ready"] + restarted = SemanticEdits(store.root.parents[1], maps) + assert restarted.get(world) == saved + assert restarted.save(world, change(sha)) == saved + assert len(json.loads(store._path(world).read_text())["revisions"]) == 1 + altered = change(sha) + altered["operations"][0]["position"][0] = 3 + with pytest.raises(RuntimeError, match="идентификатор|Идентификатор"): + store.save(world, altered) + + +def test_frozen_model_survives_new_analysis_and_conflict(setup): + world, model, maps, store, sha = setup + first = store.save(world, change(sha)) + newer = copy.deepcopy(model) + newer["features"][0]["geometry"]["coordinates"][1] = [2, -0.5, 2] + maps.save(world, newer) + view = store.get(world) + assert view["model"] == model + assert view["latest_model_sha256"] != sha + with pytest.raises(RuntimeError, match="другом окне"): + store.save(world, change(sha, request="second-request-0002")) + second = change(sha, request="second-request-0002", parent=first["revision"]) + second["operations"] = [ + {"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.5} + ] + assert len(store.save(world, second)["history"]) == 2 + assert maps.get(world) == newer + + +def test_concurrent_save_has_one_winner(setup): + world, _, _, store, sha = setup + + def save(i): + try: + return store.save(world, change(sha, request=f"concurrent-request-{i:04}")) + except RuntimeError: + return None + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(save, (1, 2))) + assert sum(r is not None for r in results) == 1 + assert len(store.get(world)["history"]) == 1 + + +def test_no_approximation_insert_and_delete_roundtrip(setup): + _, model, _, _, _ = setup + inserted = apply_operations( + model, [{"kind": "insert", "feature_id": "curb-1", "path": 0, "index": 0, "t": 0.25}] + ) + assert inserted["features"][0]["geometry"]["coordinates"] == [ + [0, 0, 2], + [0.5, 0, 2], + [2, 0, 2], + [4, 1, 2], + ] + restored = apply_operations( + inserted, [{"kind": "delete", "feature_id": "curb-1", "path": 0, "index": 1}] + ) + assert restored["features"][0]["geometry"] == model["features"][0]["geometry"] + + +def test_no_op_preserves_evidence_and_does_not_create_revision(setup): + world, model, _, store, sha = setup + body = change(sha) + body["operations"][0]["position"] = [2, 0, 2] + assert apply_operations(model, body["operations"]) == model + with pytest.raises(ValueError, match="Нет изменений"): + store.save(world, body) + assert store.get(world)["revision"] is None + + +@pytest.mark.parametrize("position", [[2, 0, 3], [0, 0, 2], [float("nan"), 0, 2], [True, 0, 2]]) +def test_invalid_save_never_commits(setup, position): + world, _, _, store, sha = setup + body = change(sha) + body["operations"][0]["position"] = position + with pytest.raises(ValueError): + store.save(world, body) + assert store.get(world)["revision"] is None + + +def test_polygon_closure_and_crossing_rejection(setup): + _, model, _, _, _ = setup + model["features"][0]["geometry"] = { + "type": "Polygon", + "coordinates": [[[0, 0, 2], [2, 0, 2], [2, 2, 2], [0, 2, 2], [0, 0, 2]]], + } + moved = apply_operations( + model, + [{"kind": "move", "feature_id": "curb-1", "path": 0, "index": 0, "position": [-0.5, 0, 2]}], + ) + ring = moved["features"][0]["geometry"]["coordinates"][0] + assert ring[0] == ring[-1] == [-0.5, 0, 2] + with pytest.raises(ValueError, match="самопересечение"): + apply_operations( + model, + [ + { + "kind": "move", + "feature_id": "curb-1", + "path": 0, + "index": 1, + "position": [1, 3, 2], + } + ], + ) + + +def test_corrupt_history_refused_and_budget_preserves_state(setup, monkeypatch): + world, _, _, store, sha = setup + monkeypatch.setattr("k1link.simulation.ai_polygon.semantic_edits.MAX_STATE", 1) + with pytest.raises(ValueError, match="Лимит"): + store.save(world, change(sha)) + assert not store._path(world).exists() + monkeypatch.undo() + store.save(world, change(sha)) + state = json.loads(store._path(world).read_text()) + state["revisions"][0]["operations"][0]["position"][0] = 9 + store._path(world).write_text(json.dumps(state)) + with pytest.raises(ValueError, match="целостность"): + store.get(world) + + +def test_directional_duplicate_persists_without_reinterpreting_prior_history(setup): + world, model, maps, store, sha = setup + first = store.save(world, change(sha)) + request = change(sha, request="directional-copy-0002", parent=first["revision"]) + request["operations"] = [{ + "kind": "duplicate_vertex", "feature_id": "curb-1", "path": 0, + "index": 1, "delta": [-0.5, 0, 0], "axis": "x", "side": "before", + }] + saved = store.save(world, request) + assert saved["edited"]["features"][0]["geometry"]["coordinates"] == [ + [0, 0, 2], [1.5, 0.5, 2], [2, 0.5, 2], [4, 1, 2], + ] + assert SemanticEdits(store.root.parents[1], maps).get(world) == saved + assert store.export(world, first["revision"])["package"]["edited"] == first["edited"] + assert maps.get(world) == model + + +def test_save_returns_admitted_geometry_without_a_second_history_replay(setup, monkeypatch): + from k1link.simulation.ai_polygon import semantic_edits + + world, _, maps, store, sha = setup + first = store.save(world, change(sha)) + request = change(sha, request="admitted-save-0002", parent=first["revision"]) + request["origin"] = "agent-proposal" + request["operations"] = [dict(kind="duplicate_vertex", feature_id="curb-1", path=0, + index=2, delta=[1, 0, 0], axis="x", side="after")] + real = semantic_edits.apply_operations + admitted = [] + replayed = [] + + def track(*args, **kwargs): + result = real(*args, **kwargs) + (replayed if kwargs.get("verified_history") else admitted).append(result) + return result + + monkeypatch.setattr(semantic_edits, "apply_operations", track) + saved = store.save(world, request) + assert len(replayed) == len(first["history"]) + assert len(admitted) == 1 and saved["edited"] is admitted[0] + assert saved["edited"]["features"][0]["properties"]["annotation_origin"] == "agent-proposal" + assert SemanticEdits(store.root.parents[1], maps).get(world) == saved + assert store.save(world, request) == saved diff --git a/tests/test_semantic_edits_api.py b/tests/test_semantic_edits_api.py new file mode 100644 index 00000000..ad8210f9 --- /dev/null +++ b/tests/test_semantic_edits_api.py @@ -0,0 +1,162 @@ +"""Exercise real HTTP admission without starting or mutating the operator service.""" + +import copy +import json +from types import SimpleNamespace + +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient +from test_semantic_edits import change, make_setup + +from k1link.simulation.ai_polygon.semantic_edits import MAX_STATE, SemanticEdits +from k1link.web.semantic_edits_api import build_semantic_edits_router + + +def test_http_limits_conflict_and_worker_export(tmp_path): + world, model, maps, store, sha = make_setup(tmp_path) + world["world_id"] = "fixture" + + def invoke(fn, *args): + try: + return fn(*args) + except FileNotFoundError as exc: + raise HTTPException(404) from exc + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except RuntimeError as exc: + raise HTTPException(409, str(exc)) from exc + + def authenticate(authorization): + if authorization != "Bearer synthetic-test-token": + raise HTTPException(401) + + app = FastAPI() + app.include_router( + build_semantic_edits_router( + store.root.parents[1], + SimpleNamespace(get=lambda _: world, list=lambda: [world]), + maps, + invoke, + authenticate, + ) + ) + with TestClient(app) as client: + path = "/worlds/fixture/semantic-edits" + assert client.get("/worker/semantic-edits/pending").status_code == 401 + assert client.get(path).json()["model"] == model + assert client.post(path, content=b"x" * (MAX_STATE + 1)).status_code == 413 + assert client.post(path, json={"image": "not-allowed"}).status_code == 400 + saved = client.post(path, json=change(sha)) + assert saved.status_code == 200 + revision = saved.json()["revision"] + assert client.post(path, json=change(sha)).json()["revision"] == revision + assert client.post(path, json=change(sha, request="conflicting-save-02")).status_code == 409 + export_path = f"/worker/worlds/fixture/semantic-edits/{revision}" + assert client.get(export_path).status_code == 401 + exported = client.get(export_path, headers={"Authorization": "Bearer synthetic-test-token"}) + assert exported.status_code == 200 + assert exported.json() == store.export(world, revision) + assert not exported.json()["package"]["review"]["dataset_ready"] + assert client.get(path).json()["model"] == model + + headers = {"Authorization": "Bearer synthetic-test-token"} + assert ( + client.get("/worker/semantic-edits/pending", headers=headers).json()["jobs"][0][ + "revision" + ] + == revision + ) + receipt = { + "state": "received", + "package_sha256": exported.json()["sha256"], + "dataset_sha256": None, + "sample_count": 0, + } + ack = export_path + "/receipt" + assert client.post(ack, json=receipt).status_code == 401 + assert client.post(ack, json=receipt, headers=headers).status_code == 200 + assert client.post(ack, json=receipt, headers=headers).status_code == 200 + assert client.get("/worker/semantic-edits/pending", headers=headers).json()["jobs"] == [] + assert client.get(path + "/status").json()["state"] == "received" + assert client.post(ack, content=b"x" * 2049, headers=headers).status_code == 413 + + +def test_large_group_edit_round_trip_and_atomic_rejection(tmp_path): + world, model, maps, store, _ = make_setup(tmp_path) + feature = model["features"][0] + feature["id"] = fid = "road-" + "a" * 64 + feature["geometry"]["coordinates"] = [[i, 0, 2] for i in range(20)] + sha = maps.save(world, model)["sha256"] + op = { + "kind": "translate_vertices", "feature_id": fid, + "vertices": [{"feature_id": fid, "path": 0, "index": i} for i in range(20)], + "axis": "y", "delta": [0, 0.125, 0], + } + body = change(sha, request="large-group-edit-0001") + body["operations"] = [copy.deepcopy(op) for _ in range(162)] + raw = json.dumps(body).encode() + assert 256 * 1024 < len(raw) < MAX_STATE + + def invoke(fn, *args): + try: + return fn(*args) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + except RuntimeError as exc: + raise HTTPException(409, str(exc)) from exc + + app = FastAPI() + app.include_router(build_semantic_edits_router( + tmp_path, SimpleNamespace(get=lambda _: world), maps, invoke, lambda _: None, + )) + path = "/worlds/fixture/semantic-edits" + with TestClient(app) as client: + saved = client.post(path, content=raw, headers={"Content-Type": "application/json"}) + assert saved.status_code == 200, saved.text + view = saved.json() + assert view["edited"]["features"][0]["geometry"]["coordinates"] == [ + [i, 20.25, 2] for i in range(20) + ] + assert view["history"][-1]["actions"] == 162 + assert view["model"] == model + assert client.post(path, json=body).json()["revision"] == view["revision"] + assert SemanticEdits(tmp_path, maps).get(world) == view + before = store._path(world).read_bytes() + invalid = { + **body, "request_id": "invalid-large-edit-02", "expected_revision": view["revision"] + } + invalid["operations"] = body["operations"] + [{ + "kind": "move", "feature_id": fid, "path": 0, "index": 1, + "position": [2, 40.5, 2], + }] + # The final move coincides with the next vertex after the valid prefix. + assert client.post(path, json=invalid).status_code == 400 + conflict = {**body, "request_id": "conflicting-large-03"} + assert client.post(path, json=conflict).status_code == 409 + assert store._path(world).read_bytes() == before + assert client.get(path).json() == view + + +def test_save_and_worker_receipt_run_outside_the_event_loop(tmp_path, monkeypatch): + import threading + + world, _, maps, store, _ = make_setup(tmp_path) + monkeypatch.setattr(SemanticEdits, "save", lambda *args: {"thread": threading.get_ident()}) + monkeypatch.setattr(SemanticEdits, "receipt", lambda *args: {"thread": threading.get_ident()}) + app = FastAPI() + + @app.get("/probe") + async def probe(): + return {"thread": threading.get_ident()} + + app.include_router(build_semantic_edits_router( + store.root.parents[1], SimpleNamespace(get=lambda _: world), maps, + lambda fn, *args: fn(*args), lambda _: None, + )) + with TestClient(app) as client: + event_loop = client.get("/probe").json()["thread"] + for path in ("/worlds/fixture/semantic-edits", + "/worker/worlds/fixture/semantic-edits/revision/receipt"): + response = client.post(path, json={}) + assert response.status_code == 200 + assert response.json()["thread"] != event_loop diff --git a/tests/test_shared_semantic_pipeline.py b/tests/test_shared_semantic_pipeline.py new file mode 100644 index 00000000..4d8b25be --- /dev/null +++ b/tests/test_shared_semantic_pipeline.py @@ -0,0 +1,127 @@ +import json +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "simulation/ai-polygon")) +import infrastructure_pipeline as pipeline # noqa: E402 - canonical worker modules + + +def definition(): + return { + "groups": [ + { + "group": "base", + "stages": ["ortho_semantic_survey"], + "files": {"ortho_semantic_survey.py": "stage.py"}, + "stage_outputs": {"ortho_semantic_survey": {"/layers": "full_plan"}}, + }, + { + "group": "full_plan", + "stages": ["assemble_layers"], + "files": {"assemble_layers.py": "assemble.py"}, + }, + ], + "aliases": {"full_plan": "fullplan"}, + } + + +def test_full_runner_passes_joint_outputs_to_original_consumer(tmp_path, monkeypatch): + module = tmp_path / "module" + (module / "pipeline").mkdir(parents=True) + (module / "pipeline/definition.json").write_text(json.dumps(definition())) + for name in ["config-ortho.json", "config-mv.json", "worker-profile.json"]: + (module / "pipeline" / name).write_text(json.dumps({"models": {}})) + (module / "stage.py").write_text("pass\n") + (module / "assemble.py").write_text("pass\n") + package = tmp_path / "input" + package.mkdir() + (package / "poses.json").write_text("{}") + output = tmp_path / "output" + output.mkdir() + calls = [] + + def run(marker, phase, image, mounts, cmd, out, pulse, timeout, **kwargs): + calls.append((phase, image, mounts, kwargs)) + m = {alias: (path, ro) for path, alias, ro in mounts} + if "semantic" in phase: + assert image == "semantic-image" and kwargs["gpu"] + assert m["/run"] == (output / "ortho", False) + assert m["/layers"] == (output / "full_plan", False) + assert m["/input"] == (package, True) + (m["/layers"][0] / "evidence").mkdir() + (m["/layers"][0] / "evidence/report.json").write_text('{"complete":true}') + else: + assert image == "mapper-image" and not kwargs["gpu"] + assert json.loads((out / "evidence/report.json").read_text())["complete"] + (out / "full-map.json").write_text('{"features":[]}') + + monkeypatch.setattr(pipeline, "run_container", run) + result, snapshot = pipeline.run_pipeline( + package, + {"sha256": "a" * 64, "poses_sha256": "b" * 64}, + output, + tmp_path / "marker", + { + "maximum_seconds": 1000, + "maximum_stage_seconds": 100, + "semantic_model": "assets/model", + "semantic_image": "semantic-image", + "mapper_image": "mapper-image", + }, + tmp_path / "runtime", + lambda: None, + module=module, + ) + assert result == output / "full_plan/full-map.json" and len(snapshot) == 64 + assert len(calls) == 2 and (output / "full_plan/group-inventory.json").is_file() + + +@pytest.mark.parametrize("target", ["base", "missing", "../private", "/input"]) +def test_invalid_target_refused(target): + d = definition() + d["groups"][0]["stage_outputs"]["ortho_semantic_survey"]["/layers"] = target + with pytest.raises(ValueError): + pipeline.validate_stage_outputs(d) + + +@pytest.mark.parametrize("alias", ["/input", "/fullplan", "/layers/escape", "../layers", "/survey"]) +def test_alias_cannot_shadow_inputs(alias): + d = definition() + d["groups"][0]["stage_outputs"]["ortho_semantic_survey"] = {alias: "full_plan"} + with pytest.raises(ValueError): + pipeline.validate_stage_outputs(d) + + +def test_escape_through_existing_link_refused(tmp_path): + output = tmp_path / "owned" + outside = tmp_path / "outside" + output.mkdir() + outside.mkdir() + (output / "full_plan").symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match="escapes"): + pipeline.stage_output_mounts(output, definition()["groups"][0], "ortho_semantic_survey") + assert not list(outside.iterdir()) + + +def test_unique_publisher_required(): + d = definition() + g = d["groups"][0] + g["stages"].append("second") + g["stage_outputs"]["second"] = {"/other": "full_plan"} + with pytest.raises(ValueError, match="multiple"): + pipeline.validate_stage_outputs(d) + + +def test_shipped_graph_uses_one_semantic_producer_with_measured_duration(): + from k1link.simulation.ai_polygon.infrastructure_progress import plan + + stages, _ = plan() + assert len(stages) == 90 + names = [r["stage"] for r in stages] + assert names.count("ortho_semantic_survey") == 1 + assert "ortho_segment" not in names and "semantic_layers" not in names + row = next(r for r in stages if r["stage"] == "ortho_semantic_survey") + assert row["measured"] and row["seconds"] == 251.484 diff --git a/tests/test_simulation_patch_release.py b/tests/test_simulation_patch_release.py new file mode 100644 index 00000000..2cc8a22d --- /dev/null +++ b/tests/test_simulation_patch_release.py @@ -0,0 +1,64 @@ +import base64 +import hashlib +import importlib.util +import json +from pathlib import Path + +import pytest + +spec = importlib.util.spec_from_file_location( + "stage_patch", Path(__file__).resolve().parents[1] / "scripts/stage_simulation_worker_patch.py" +) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +def fixture(tmp_path): + manifest = { + "source.py": hashlib.sha256(b"old").hexdigest(), + "keep.py": hashlib.sha256(b"keep").hexdigest(), + } + encoded = json.dumps(manifest, sort_keys=True, indent=2).encode() + digest = hashlib.sha256(encoded).hexdigest() + releases = tmp_path / "releases" + base = releases / ("ai-polygon-" + digest[:16]) + base.mkdir(parents=True) + (base / "source.py").write_bytes(b"old") + (base / "keep.py").write_bytes(b"keep") + base.with_suffix(".manifest.json").write_bytes(encoded) + recipe = dict( + base_release=digest[:16], + base_manifest_sha256=digest, + overlays={ + "source.py": dict( + base64=base64.b64encode(b"new").decode(), sha256=hashlib.sha256(b"new").hexdigest() + ) + }, + ) + return base, recipe + + +def test_patch_preserves_predecessor_and_every_undeclared_file(tmp_path): + base, recipe = fixture(tmp_path) + result = module.stage(tmp_path, recipe) + new = tmp_path / "releases" / ("ai-polygon-" + result["release"]) + assert (base / "source.py").read_bytes() == b"old" + assert (new / "source.py").read_bytes() == b"new" + assert (new / "keep.py").read_bytes() == b"keep" + assert result["changed"] == ["source.py"] and not result["activated"] + with pytest.raises(ValueError, match="already exists"): + module.stage(tmp_path, recipe) + + +def test_corrupted_predecessor_refuses_before_staging(tmp_path): + base, recipe = fixture(tmp_path) + (base / "keep.py").write_bytes(b"corrupt") + with pytest.raises(ValueError, match="Base file changed"): + module.stage(tmp_path, recipe) + assert len(list((tmp_path / "releases").iterdir())) == 2 + + +@pytest.mark.parametrize("path", ["../outside", "/absolute", "C:/outside", "a\\b"]) +def test_escape_rejected(tmp_path, path): + with pytest.raises(ValueError): + module.confined(tmp_path, path) diff --git a/tests/test_whole_infrastructure.py b/tests/test_whole_infrastructure.py new file mode 100644 index 00000000..cb325f87 --- /dev/null +++ b/tests/test_whole_infrastructure.py @@ -0,0 +1,36 @@ +"""Whole-scene coverage and overlap ownership, with bounded synthetic geometry.""" +import sys +from pathlib import Path +import numpy as np +ROOT=Path(__file__).resolve().parents[1] +sys.path[:0]=[str(ROOT/'simulation/urban-mapping'),str(ROOT/'simulation/urban-mapping/vector'),str(ROOT/'simulation/ai-polygon')] +from whole_scene import plan_tiles + + +def test_whole_scene_uses_all_bounds_even_beyond_route(): + v=np.array([[x,y,0.] for x in range(0,121,2) for y in range(0,21,2)]) + f=[] + for x in range(60): + for y in range(10): + i=x*11+y;f.extend([[i,i+1,i+11],[i+1,i+12,i+11]]) + request={'source':{},'model':{}} + result=plan_tiles(request,v,np.array(f)) + assert len(result['tiles'])==3 + assert result['bounds_xy']==[[0.,0.],[120.,20.]] + assert all(t['status']=='pending' for t in result['tiles']) + assert result['tiles'][-1]['core_bounds'][1][0]==120 + assert all(t['job']['views'][0]['size']==[1200,1200] for t in result['tiles']) + + +def test_overlap_owns_polygons_once_and_retains_xyz(): + import pytest + pytest.importorskip("shapely") + from whole_vectors import merge + polygon={'id':'crossing','geometry':{'type':'Polygon','coordinates':[[[38,2,3],[42,2,3],[42,6,3],[38,2,3]]]},'properties':{}} + line={'id':'curb','geometry':{'type':'LineString','coordinates':[[30,1,3],[50,1,3]]},'properties':{}} + tiles=[dict(id='left',core_bounds=[[0,0],[40,40]],status='surveyed'),dict(id='right',core_bounds=[[40,0],[80,40]],status='surveyed')] + result=merge({'tiles':tiles,'bounds_xy':[[0,0],[80,40]]},[(t,dict(features=[polygon,line])) for t in tiles],dict(key='a'*64,identity={'provider_sha256':'b'*64},source={})) + assert sum(f['geometry']['type']=='Polygon' for f in result['features'])==1 + lines=[f['geometry']['coordinates'] for f in result['features'] if f['geometry']['type']=='LineString'] + assert lines==[[[30.,1.,3.],[40.,1.,3.]],[[40.,1.,3.],[50.,1.,3.]]] + assert result['analysis']['tiles_mapped']==2 diff --git a/tests/test_world_library.py b/tests/test_world_library.py new file mode 100644 index 00000000..3e640c23 --- /dev/null +++ b/tests/test_world_library.py @@ -0,0 +1,96 @@ +"""Location settings preserve source files, geometry identity and run evidence.""" + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from test_ai_polygon import make_world +from test_ai_polygon_realtime import realtime as _realtime +from test_simulation_location_library import project_fixture + +from k1link.simulation.ai_polygon.contracts import RunCreate, WorkerWorldCreate, WorldSettings +from k1link.simulation.ai_polygon.world_library import WorldLibrary +from k1link.simulation.ai_polygon.worlds import WorldStore +from k1link.web.ai_polygon_api import build_ai_polygon_router + +realtime = _realtime +API = "/api/v1/ai-polygon" + + +def client_for(root): + app = FastAPI() + app.include_router(build_ai_polygon_router(root)) + return TestClient(app) + + +@pytest.mark.parametrize("kind", ["local", "worker", "project"]) +def test_rename_remove_restore_survives_restart_without_rewriting_source(tmp_path, kind): + worlds = WorldStore(tmp_path) + if kind == "project": + worlds, project = project_fixture(tmp_path) + row = worlds.projects.world(project) + elif kind == "worker": + request = WorkerWorldCreate(name="Worker scan", filename="scan.ply", byte_length=1024, + author="test", license="CC0", sha256="b" * 64, collider_sha256="c" * 64, + splat_count=10, settings=WorldSettings(prepared=True)) + row = worlds.register_worker_asset(request, "worker-006") + else: + row = make_world(worlds) + identity = row["world_id"] + original = worlds.get(identity) + files = {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} + with client_for(tmp_path) as client: + response = client.patch(f"{API}/worlds/{identity}", json={"display_name":" Новое имя "}) + assert response.status_code == 200 + assert response.json()["name"] == "Новое имя" + assert response.json()["sha256"] == original["sha256"] + assert client.patch(f"{API}/worlds/{identity}", json={"removed":True}).status_code == 200 + with client_for(tmp_path) as client: + catalog = client.get(f"{API}/catalog").json() + assert not catalog["worlds"] + assert catalog["removed_worlds"][0]["world_id"] == identity + assert catalog["removed_worlds"][0]["name"] == "Новое имя" + assert client.patch(f"{API}/worlds/{identity}", json={"removed":False}).status_code == 200 + assert client.get(f"{API}/catalog").json()["worlds"][0]["name"] == "Новое имя" + assert worlds.get(identity) == original + for p, before in files.items(): + assert p.read_bytes() == before, p + if kind == "worker": + assert worlds.register_worker_asset(request, "worker-006")["world_id"] == identity + assert len(worlds.list()) == 1 + + +def test_invalid_mutations_and_unknown_scan_have_no_effect(tmp_path): + worlds = WorldStore(tmp_path) + row = make_world(worlds) + with client_for(tmp_path) as client: + for changes in [{}, {"display_name":" "}, {"display_name":"x"*121}, + {"display_name":"bad\x00name"}, {"removed":"yes"}, {"sha256":"bad"}]: + assert client.patch(f"{API}/worlds/{row['world_id']}", json=changes).status_code == 422 + assert client.patch(f"{API}/worlds/aiworld-{'f'*32}", json={"removed":True}).status_code == 404 + assert WorldLibrary(worlds).get(row["world_id"]) == row + + +def test_active_world_cannot_be_removed_and_removed_world_cannot_start(realtime, tmp_path): + store, hello, run = realtime + identity = run["world"]["world_id"] + with client_for(tmp_path) as client: + assert client.patch(f"{API}/worlds/{identity}", json={"removed":True}).status_code == 409 + assert client.patch(f"{API}/worlds/{identity}", json={"display_name":"Renamed"}).status_code == 200 + assert store.get(run["run_id"])["world"]["name"] == run["world"]["name"] + store.finish(run["run_id"], hello.instance_id, "stopped", "") + WorldLibrary(store.worlds).update(identity, {"removed":True}) + with pytest.raises(RuntimeError, match="удалена"): + store.start(RunCreate(world_id=identity, clock="realtime"), "removed-location") + assert store.active is None + + +def test_metadata_cannot_follow_symlink(tmp_path): + worlds = WorldStore(tmp_path) + row = make_world(worlds) + library = WorldLibrary(worlds) + outside = tmp_path / "untouched.json" + outside.write_text('{"name":"original"}') + library.metadata.path(row["world_id"]).symlink_to(outside) + with pytest.raises(ValueError, match="regular"): + library.update(row["world_id"], {"removed":True}) + assert outside.read_text() == '{"name":"original"}'