Add prepared urban route guidance to Gaussian simulation planning

Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 23:42:26 +03:00
parent 2e85d95c71
commit 31b74e4571
34 changed files with 1451 additions and 83 deletions
@@ -28,10 +28,12 @@ export class AiEditorRuntime {
private dirty = true;
private previous = "";
private points: AiWaypoint[] = [];
private route: number[][] = [];
clip = Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void) {
private onProject: (markers: EditorMarker[]) => void,
private onRouteProject: (points: ScreenPoint[]) => void = () => undefined) {
canvas.tabIndex = 0;
this.app = new Application(canvas, { graphicsDeviceOptions: { antialias: false, alpha: false,
preserveDrawingBuffer: false, powerPreference: "default" } });
@@ -65,6 +67,7 @@ export class AiEditorRuntime {
const matrix = this.camera.getWorldTransform().data.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
return { id:p.id, base:this.project(x,y,z), top:this.project(x,y+this.preferences.waypoint.height,z),
@@ -100,6 +103,8 @@ export class AiEditorRuntime {
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
this.setClip(Infinity); 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;}
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) {
@@ -1,3 +1,5 @@
import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
@@ -12,9 +14,9 @@ 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 }: {
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false, preparedRoute=null }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
}) {
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
@@ -27,6 +29,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const [editing,edit] = useReducer(editWaypoints,initialPoints,waypointEditing);
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState(Infinity);
@@ -38,7 +42,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
let active = true;
setReady(false); setError(null); setClip(Infinity);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers); }
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
catch (e) { setError((e as Error).message); return; }
runtime.current = view;
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
@@ -49,6 +53,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
runtime.current?.setPoints(points);
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence]);
useEffect(()=>{
runtime.current?.setRoute(preparedRoute?.preview_xyz??[]);
if(preparedRoute && ready){runtime.current?.top();setViewMode("top");}
},[preparedRoute?.sha256,ready]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
@@ -76,7 +84,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
<p>{points.length} точек · первая — старт, последняя — финиш</p></div>
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
@@ -89,6 +97,9 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
</div>:null}
@@ -124,7 +135,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
drag.current=null;edit({type:"commit"});
runtime.current?.setNavigation(!busy);if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }}
onPointerCancel={()=>{edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}}>
<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />
{preparedRoute?<path className="ai-route__line" d={routeProjection.map((p,i)=>p?`${i&&routeProjection[i-1]?"L":"M"}${p[0]*1280},${p[1]*720}`:"").join(" ")} />:null}
{!preparedRoute?<path className="ai-route__line" d={markers.map((m,i)=>m.base?`${i&&markers[i-1].base?"L":"M"}${m.base[0]*1280},${m.base[1]*720}`:"").join(" ")} />:null}
{markers.map((m,i)=>m.base&&m.top ? <g key={m.id} data-waypoint="true" className={`ai-route__marker ${selected===m.id?"is-selected":""}`}
onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
@@ -134,7 +146,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
}}>
<text x={m.top[0]*1280+10} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
<text textAnchor={m.top[0]>.85?"end":"start"} x={m.top[0]*1280+(m.top[0]>.85?-10:10)} y={m.top[1]*720}>{i===0?"Старт":i===markers.length-1?`Финиш · ${i}`:i}</text>
{selected===m.id ? (["x","y","z"] as const).map((axis)=>m[axis] ? <g key={axis} className="ai-local-editor__axis-hit" onPointerDown={(e)=>{
if (busy || e.button !== 0) return;
e.preventDefault();e.stopPropagation();edit({type:"begin"});drag.current={point:points.find((p)=>p.id===m.id)!,axis,offset:m.base!.map((v,i)=>v-position(e)[i])};
@@ -1,7 +1,7 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave}: {
name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
onClose:()=>void;onSave:()=>void;
}) {
return <Window open title={launch?"Сохранить задание и запустить":"Сохранить задание"}
@@ -9,6 +9,7 @@ export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave}: {
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form">
{error?<p role="alert">{error}</p>:null}
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
</div>
@@ -11,6 +11,7 @@ export class EditorCamera {
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private topPoints:number[][]|null=null;
private addMode=false;
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
private forward = new Vector3();
@@ -48,6 +49,7 @@ export class EditorCamera {
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
this.topPoints=null;
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
@@ -59,6 +61,7 @@ export class EditorCamera {
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled)return;
this.topPoints=null;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
@@ -72,15 +75,28 @@ export class EditorCamera {
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private clear=()=>{this.keys.clear();this.gesture=null;};
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();}
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
home(point:number[]){
this.topPoints=null;
const target=new Vector3(...point);
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
top(points:number[][]){
if(!points.length)return;
this.topPoints=points;
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
const span=Math.max((high[0]-low[0])/this.camera.aspect,high[2]-low[2],10);
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
this.camera.position.copy(target).add(new Vector3(0,distance,0));
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.addMode=add;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
this.topPoints=null;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
this.delta.copy(this.forward).multiplyScalar(pressed("KeyW","ArrowUp")-pressed("KeyS","ArrowDown"))
@@ -10,8 +10,8 @@ export const prepareEditor = (world: AiWorld, signal?: AbortSignal) => polygonRe
export const fetchEditor = (key: string, signal?: AbortSignal) => polygonRequest<EditorCache>(`/editor-cache/${key}`, { signal });
export const editorAssetUrl = (key: string, name: string) => `/api/v1/ai-polygon/editor-cache/${key}/${name}`;
export const saveLocalPlan = (cache: EditorCache, robot: AiRobot, points: AiWaypoint[], name: string,
draftId: string, sequence: number) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
draftId: string, sequence: number, routePreparationKey?:string|null) => polygonRequest<AiPlan>("/plans", { method: "POST", body: JSON.stringify({
cache_key: cache.key, robot_id: robot.robot_id, robot_sha256: robot.sha256,
draft_id: draftId, sequence, points, name,
draft_id: draftId, sequence, points, name, route_preparation_key:routePreparationKey??null,
}) });
export { toEditor, toMission } from "./aiEditorCoordinates";
@@ -1,3 +1,4 @@
import type { PreparedRoute } from "./routePreparation";
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
import type { RoverMotion } from "./roverMotion";
import type { RoverSettings } from "./roverSettings";
@@ -112,7 +113,7 @@ export interface AiRouteOverlay {
export interface AiPlanningState { sequence: number; view_revision: number; points: AiWaypoint[];
error: string | null; can_undo: boolean; clip_height: number | null;
height_min?: number | null; height_max?: number | null; camera_moving?: boolean }
export interface AiPlan { plan_id: string; name: string; sha256: string; world_id: string;
export interface AiPlan { prepared_route?:PreparedRoute; route_preparation_key?:string; plan_id: string; name: string; sha256: string; world_id: string;
settings?: Pick<AiWorldSettings, "max_speed_mps">;
display_name?: string; removed?: boolean;
editor_cache_key?: string;
@@ -0,0 +1,63 @@
import { useEffect, useRef, useState } from "react";
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint } from "./aiPolygon";
import type { EditorCache } from "./aiEditor";
export interface PreparedRoute {
sha256:string; preview_xyz:number[][]; length_m:number;
identity:{world_sha256:string;robot_sha256:string;points:AiWaypoint[]};
}
export interface RoutePreparation {
key:string;status:"queued"|"preparing"|"ready"|"failed";error:string|null;result:PreparedRoute|null;
}
export function routeMatches(route:PreparedRoute|null|undefined, cache:EditorCache|null,
robot:AiRobot|undefined, points:AiWaypoint[]) {
return !!route && !!cache && !!robot && route.identity.world_sha256===cache.world.sha256
&& route.identity.robot_sha256===robot.sha256 && JSON.stringify(route.identity.points)===JSON.stringify(points);
}
export function useRoutePreparation(cache:EditorCache|null, robot:AiRobot|undefined,
points:AiWaypoint[], plan:AiPlan|undefined, onError:(message:string)=>void) {
const [job,setJob]=useState<RoutePreparation|null>(null);
const [submitting,setSubmitting]=useState(false);
const generation=useRef(0);
const signature=JSON.stringify([cache?.key,robot?.sha256,points]);
const current=useRef(signature);current.current=signature;
const error=useRef(onError);error.current=onError;
useEffect(()=>{generation.current++;setJob(null);setSubmitting(false);},[signature]);
useEffect(()=>{
if(!job || !["queued","preparing"].includes(job.status))return;
const key=job.key,stamp=generation.current;
let active=true,timer:ReturnType<typeof setTimeout>;
const controller=new AbortController();
const poll=async()=>{
try {
const next=await polygonRequest<RoutePreparation>(`/route-preparations/${key}`,{signal:controller.signal});
if(active && generation.current===stamp){
setJob(next);
if(next.status==="failed")error.current(next.error??"Маршрут не построен.");
else if(next.status!=="ready")timer=setTimeout(()=>void poll(),1000);
}
} catch(caught) {
if(active){error.current((caught as Error).message);setJob(null);}
}
};
timer=setTimeout(()=>void poll(),500);
return()=>{active=false;clearTimeout(timer);controller.abort();};
},[job?.key,job?.status]);
const generated=routeMatches(job?.result,cache,robot,points)?job?.result:null;
const saved=routeMatches(plan?.prepared_route,cache,robot,points)?plan?.prepared_route:null;
const route=generated??saved??null;
const key=generated?job!.key:saved?plan?.route_preparation_key:null;
const prepare=async()=>{
if(!cache||!robot||points.length<2)return;
const stamp=generation.current,snapshot=signature;
setSubmitting(true);
try {
const next=await polygonRequest<RoutePreparation>("/route-preparations",{method:"POST",body:JSON.stringify({
cache_key:cache.key,robot_id:robot.robot_id,robot_sha256:robot.sha256,points,
})});
if(stamp===generation.current && current.current===snapshot)setJob(next);
} catch(caught) {if(stamp===generation.current)error.current((caught as Error).message);}
finally {if(stamp===generation.current)setSubmitting(false);}
};
return {route,key:key??null,prepare,busy:submitting||!!job&&["queued","preparing"].includes(job.status)};
}
@@ -1,3 +1,4 @@
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";
@@ -45,6 +46,7 @@ export function AiPolygonWorkspace() {
const [robotId, setRobotId] = useState<string | null>(null);
const [planId, setPlanId] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saveError,setSaveError] = useState<string|null>(null);
const [saveOpen, setSaveOpen] = useState(false);
const [launchAfterSave,setLaunchAfterSave] = useState(false);
const [editorPlan,setEditorPlan] = useState<AiPlan|null>(null);
@@ -132,6 +134,8 @@ export function AiPolygonWorkspace() {
const plan = planId === null ? plans[0] : plans.find((p) => p.plan_id === planId);
const [roverSettings,setRoverSettings] = useRoverSettings(robot,
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 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; }
@@ -145,19 +149,20 @@ export function AiPolygonWorkspace() {
};
const save = () => {
if (!draft || !robot) return;
setSaving(true);
void saveLocalPlan(draft.cache, robot, draft.points, planName, draft.id, draft.sequence).then(async (saved) => {
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);
setCatalog(prior=>prior?{...prior,plans:[saved,...prior.plans.filter(p=>p.plan_id!==saved.plan_id)]}:prior);
if(launchAfterSave)start("evaluation",saved);
}).catch((caught: Error) => setError(caught.message)).finally(() => setSaving(false));
}).catch((caught: Error) => setSaveError(caught.message)).finally(() => setSaving(false));
};
const openSave = (launch=false) => {
setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
setSaveError(null);setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
};
const launchDraft = () => {
if(!draft||!robot)return;
if(planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points))start("evaluation",plan);
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 connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
@@ -177,21 +182,24 @@ export function AiPolygonWorkspace() {
</div>
{roverSettings?<p>{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом</p>:null}</>:null}
{mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
disabled={running||starting||saving} onUpdated={planUpdated}
disabled={running||starting||saving||preparation.busy} onUpdated={planUpdated}
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null}
<div className="ai-polygon__actions">{mode === "manual" ? <Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
disabled={!robot || !selected.settings.prepared}
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button> : planning ? <>
<Button disabled={starting || saving || !draft || draft.points.length < 2}
<Button disabled={starting || saving || preparation.busy || (routeRequired && !preparation.route) || !draft || draft.points.length < 2}
onClick={()=>openSave()}>Сохранить задание</Button>
<Button variant="primary" icon={<Icon name="play"/>} loading={starting}
disabled={saving || !draft || draft.points.length<2 || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={launchDraft}>Запустить симуляцию</Button>
{!routeRequired || preparation.route ? <Button variant="primary" icon={<Icon name="play"/>} loading={starting}
disabled={saving || !draft || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={launchDraft}>Запустить симуляцию</Button> : <Button variant="primary" icon={<Icon name="plan"/>}
loading={preparation.busy} disabled={saving || starting || !draft || draft.points.length<2 || !catalog.runtime.available}
onClick={()=>void preparation.prepare()}>Спланировать маршрут</Button>}
{preparation.busy?<p role="status">Рассчитываем маршрут по сцене</p>:null}
</> : !running ? <>
<Button loading={starting} disabled={!robot || !selected.settings.prepared}
onClick={() => start("planning")}>Подготовить маршрут</Button>
<Button variant="primary" icon={<Icon name="play" />} loading={starting}
disabled={!robot || !plan || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
disabled={!robot || !plan || (routeRequired && !plan.prepared_route) || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
onClick={() => start("evaluation")}>Запустить симуляцию</Button>
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div>
</> : null;
@@ -250,7 +258,7 @@ export function AiPolygonWorkspace() {
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={actionsHost} headerActions={sceneActions} />
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
busy={starting || saving} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
busy={starting || saving || preparation.busy} preparedRoute={preparation.route} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
{mode === "inference" && running && run ? <AiWorldStream key={run.run_id} world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
actionsHost={actionsHost} headerActions={sceneActions}
@@ -268,7 +276,7 @@ export function AiPolygonWorkspace() {
setRoverSettingsOpen(false);
try {setRoverSettings(value);} catch {setError("Настройки применены, но не сохранены в браузере. После перезагрузки их нужно задать снова.");}
}}/> : null}
{saveOpen?<AiPlanSaveWindow name={planName} onName={setPlanName} busy={saving}
{saveOpen?<AiPlanSaveWindow error={saveError} name={planName} onName={setPlanName} busy={saving}
launch={launchAfterSave} onClose={()=>setSaveOpen(false)} onSave={save}/>:null}
<SimulationSourceImport open={importChoice} onClose={()=>setImportChoice(false)}
onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} />
@@ -15,7 +15,8 @@ test("speed and payload persist per robot revision, with finite physical bounds"
assert.equal(validRoverSettings(loaded,robot),true);
assert.deepEqual(parseRoverSettings(JSON.stringify(loaded),robot),loaded);
assert.notEqual(roverSettingsKey(robot),roverSettingsKey({...robot,sha256:"b".repeat(64)}));
for(const patch of [{max_speed_mps:.4},{max_speed_mps:NaN},{base_mass_kg:0},{payload_mass_kg:-1},
assert.equal(validRoverSettings({...loaded,max_speed_mps:.4},robot),true);
for(const patch of [{max_speed_mps:.01},{max_speed_mps:Infinity},{max_speed_mps:NaN},{base_mass_kg:0},{payload_mass_kg:-1},
{payload_height_m:Infinity},{max_speed_mps:"0.2"}]) {
assert.equal(validRoverSettings({...loaded,...patch},robot),false);
assert.equal(parseRoverSettings(JSON.stringify({...loaded,...patch}),robot),undefined);
@@ -5,7 +5,7 @@ import ts from 'typescript';
const source=ts.transpileModule(readFileSync(new URL('../src/core/simulation/runConfiguration.ts',import.meta.url),'utf8'),
{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {parseSavedSelection,currentSelection,runDurationSeconds,selectionStorageKey}=
const {parseSavedSelection,currentSelection,selectionStorageKey}=
await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
const selection={schema_version:'missioncore.observatory-ai-composition/v1',selections:[
{group:'segmentation',module_id:'outdoor-provider',module_sha256:'a'.repeat(64),parameters:{}},
@@ -33,11 +33,9 @@ test('alternative provider is rebound from full registry and park permissions su
assert.equal(selection.selections[0].module_sha256,'a'.repeat(64));
assert.throws(()=>currentSelection(selection,{...installed,catalog:{groups:[]}}),/недоступен/);
});
test('310 m at 0.15 m/s is not cut off by the old 30-minute ceiling; budgets stay bounded',()=>{
assert.ok(runDurationSeconds(310.34,.15)>310.34/.15+120);
assert.ok(runDurationSeconds(310.34,.15)>1800);
assert.equal(runDurationSeconds(3.4,.15),1800);
assert.equal(runDurationSeconds(100000,.01),7200);
for(const speed of [0,-1,NaN,Infinity])assert.equal(runDurationSeconds(310,speed),1800);
for(const length of [undefined,NaN,-1,Infinity])assert.equal(runDurationSeconds(length,.15),1800);
test('continuous simulation admission does not send a distance-based duration ceiling',()=>{
const api=readFileSync(new URL('../src/core/simulation/aiPolygon.ts',import.meta.url),'utf8');
const start=api.slice(api.indexOf('export const startAiRun'),api.indexOf('export const sendAiPlanningCommand'));
assert.doesNotMatch(start,/duration_seconds|runDurationSeconds/);
assert.match(start,/clock: "realtime"/);
});
@@ -99,7 +99,7 @@ test("PlayCanvas owns the realtime scene graph without an iframe or React entity
assert.match(runtime, /camera\.script\?\.create\(CameraControls/);
assert.match(runtime, /const HOME_POSITION = new Vec3\(0, 1, 0\)/);
assert.match(runtime, /const HOME_FOCUS = new Vec3\(1, 1, 0\)/);
assert.match(await read("core/simulation/gaussianQuality.ts"), /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60/);
assert.match(await read("core/simulation/gaussianQuality.ts"), /maximum: \{[^}]*lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 0, targetFps: 60/);
assert.match(runtime, /app\.scene\.gsplat\.splatBudget = profile\.splatBudget/);
assert.match(runtime, /app\.autoRender = false/);
assert.match(runtime, /app\.systems\.gsplat\?\.on\("frame:request", this\.requestGsplatFrame\)/);
+59 -3
View File
@@ -20,9 +20,9 @@
публичного порта или файлового обмена на каждый поворот камеры.
- Поворот, полёт, zoom, высотный срез, установка и перенос точек выполняются
локально. Picking использует точный collider и BVH, собираемый в Web Worker.
- Сохранение задания передаёт только точки и идентичности. План неизменяем;
редактирование создаёт следующую ревизию. Первая точка задаёт старт, направление
второй — начальный курс, последняя — финиш. Допускается 2–33 точки.
- Сохранение задания передаёт точки, идентичности и ключ подготовленного маршрута. План неизменяем;
редактирование создаёт следующую ревизию. Первая точка задаёт старт, первый участок подготовленного маршрута — начальный
курс, последняя точка — финиш. Для старых заданий без расчёта курс задаётся второй точкой. Допускается 2–33 точки.
- При запуске локальный редактор уничтожается. Worker получает задание, проверяет
collider, размещение ровера и запускает прежние Isaac/AI-композицию/сенсоры.
Mac декодирует видео и рисует телеметрию и маршрут поверх него.
@@ -68,3 +68,59 @@ SOG-кэш используется редактором и локальным
не требует Worker или GPU lease.
Проверка реализации: [локальный редактор и SOG, 02.10](audits/2026-10-02-local-route-editor.md).
## Городской маршрут-ориентир, 08.10.2026
В локальной Gaussian-сцене после установки A/B сначала доступно действие
«Спланировать маршрут». Готовый результат открывается сверху; переключатель
«3D / Вид сверху» остаётся в том же просмотре. Затем доступны сохранение и
«Запустить симуляцию». Изменение точек, сцены или профиля ровера отменяет
применимость предыдущего расчёта. Старые импортированные миры сохраняют
прежний процесс; разведка неизвестной местности сюда не входит.
Порт источника — `missioncore.prepared-route/v1`: идентичность поставщика,
сцены, collider, калибровки, геометрии ровера и точек; граф
`missioncore.route-map/v2`; линия предпросмотра и длина. Core повторно строит
путь по графу и проверяет совпадение линии с тем, что получит runtime.
Следующий картографический адаптер должен выдавать этот контракт, а не
встраивать зависимость от карт в локальный планировщик. Текущий единственный
адаптер — `scene-ground-envelope/v1`, CPU-задание существующего Worker.
Подготовка использует общий арбитраж и завершается освобождением NativeJob.
Адаптер строит связную геометрическую поверхность на слое старта. Малые
замкнутые пропуски до 6 м / 24 м² допускаются только как неизвестная область
глобальной гипотезы; открытые разрывы не соединяются. Это не распознавание
автомобилей: небольшой постоянный объект тоже может попасть в такую область.
Сенсоры обязаны независимо подтвердить опору и свободный объём при движении.
Геометрический источник не знает правил движения, тротуаров, переходов или
временного характера каждого объекта. Его центральная линия улицы не является
пешеходной картой и не доказывает пригодность полного городского маршрута.
`advisory` снимает жёсткое удержание корпуса в капсуле линии. Локальные цели
и объезды по наблюдаемой поверхности разрешены вне неё, явные `no_go`
продолжают действовать. Соседний участок засчитывается только при фактическом
продвижении и текущем положительном whole-body receipt. Финальная точка
сохраняет отдельное подтверждение прибытия. Локальная цель рядом с промежуточным
advisory-ориентиром после отказа native-планировщика исключается из кандидатов;
она не сохраняется как обязательный финиш. Финальная цель и обязательный
возврат к опорной точке сохраняют защиту наблюдённого прибытия.
Измеренная блокировка исключает рёбра активного участка и запускает существующий поиск альтернативы; это
не обещание объезда любой неизвестной преграды. Полный MAROSEYKA A–B требует
отдельной native-приёмки; успешный расчёт и короткий прогон её не заменяют.
Private-artifact расчёта хранится в `ai-polygon/route-preparations/<key>.json`.
Сохранённое задание закрепляет граф; каталог отдаёт компактную проекцию.
Подготовленная геометрия не поступает в поток сенсоров и не даёт разрешение
на управление. Линия в просмотре существует только для оператора.
Native Gaussian-область включает весь рассчитанный изгиб A–B и 12 м
окружающего контекста. После грубой рамки AABB применяется пространственная
выборка по окрестности линии: все атрибуты выбранных Gaussian-записей
сохраняются побайтово. Между выборочными центрами удерживается консервативный
запас, поэтому участок в пределах 12 м не теряется. Количественного лимита,
decimation, обрезки SH и повторного квантования здесь нет.
Полный граф может содержать ветви вне этой визуальной области. Дальний
перемаршрут за её пределы ещё требует пространственной подгрузки сцены;
наличие ветви графа не считается доказательством готовности такого объезда.
+20
View File
@@ -383,3 +383,23 @@ installer с предыдущим release. WebRTC поддерживает од
При запуске AI coordinator сначала ожидает готовность всех выбранных моделей
и локального планировщика; до этого физическое время остановлено и кадры
не отправляются в незапущенные сервисы. Проверки свежести в движении сохранены.
## Перенос воспроизводимого кэша
`scripts/relocate_simulation_cache.py --runtime <root> --destination <path>`
сначала печатает план. `--apply` требует отсутствия active/editor/route jobs,
копирует только `state/project-packages`, сверяет SHA-256 каждого файла,
перепроверяет отсутствие работы, сохраняет исходный путь NTFS junction и
пишет inventory рядом с новым каталогом. Исходные Gaussian packages, run
журналы, credentials и ScheduledTask не меняются. Запускать только staged
версию утилиты с проверенным SHA. Незавершённый перенос требует осмотра,
повторная автоматическая подмена junction запрещена. Gaussian→USD отдельно
проверяет резерв диска до конвертации; валидный кэш переиспользуется без неё.
Для отдельного RTX DerivedDataCache поддержан `--cache isaac-derived-data`.
После ошибки заполнения диска `--fresh` сохраняет все старые байты с inventory
в указанном destination, а junction направляет в новый соседний `.fresh`.
Это инвалидирует только воспроизводимые данные renderer. Старое содержимое
не выдаётся за исправный cache после неполной записи; исходники и доказательства
не удаляются. Каталог проекта этим режимом не сбрасывается.
@@ -9,7 +9,9 @@ param(
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\runtime\simulation'
$name='ndc-ai-polygon-worker'
if(Test-Path "$root\state\active.json") { throw 'Active episode prevents update' }
foreach($marker in @('active.json','editor-active.json','route-active.json')) {
if(Test-Path "$root\state\$marker") { throw 'Active simulation work prevents update' }
}
$task=Get-ScheduledTask -TaskName $name
if(@($task.Actions).Count -ne 1) { throw 'Expected one installed worker action' }
$old=$task.Actions[0]
+91
View File
@@ -0,0 +1,91 @@
"""Relocate only explicitly selected reproducible simulation caches, preserving every verified byte.
Run --apply only while the simulation coordinator is idle. Original source
packages, run evidence, credentials and scheduled-task configuration are untouched.
"""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
def sha(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--runtime',type=Path,required=True)
parser.add_argument('--destination',type=Path,required=True)
parser.add_argument('--apply',action='store_true')
parser.add_argument('--cache',choices=['project','isaac-derived-data'],default='project')
parser.add_argument('--fresh',action='store_true')
args=parser.parse_args()
state=args.runtime/'state'
source=(state/'project-packages' if args.cache=='project' else
args.runtime/'isaac-sim-6.1.0/kit/cache/DerivedDataCache')
if args.fresh and args.cache!='isaac-derived-data':
raise ValueError('Fresh cache is reserved for invalidated renderer-derived data')
for name in ('active.json','editor-active.json','route-active.json'):
if (state/name).exists():
raise RuntimeError('Worker must be idle: '+name)
if source.is_symlink() or source.is_junction():
raise RuntimeError('Cache already redirected; inspect its destination')
target=args.destination.resolve()
if target==source.resolve() or source.resolve() in target.parents:
raise ValueError('Destination must be outside the source cache')
files=sorted(p for p in source.rglob('*') if p.is_file())
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise RuntimeError('Nested cache links are unsupported')
size=sum(p.stat().st_size for p in files)
existing=next(p for p in [target,*target.parents] if p.exists())
report=dict(source=str(source),destination=str(target),files=len(files),bytes=size,
destination_free_bytes=shutil.disk_usage(existing).free,applied=False)
if report['destination_free_bytes']<size+4*1024**3:
raise RuntimeError('Insufficient destination space')
if not args.apply:
print(json.dumps(report));return
target.mkdir(parents=True,exist_ok=True)
inventory={}
for path in files:
relative=path.relative_to(source);destination=target/relative
destination.parent.mkdir(parents=True,exist_ok=True)
digest=sha(path)
if not destination.exists() or destination.stat().st_size!=path.stat().st_size or sha(destination)!=digest:
temporary=destination.with_name(destination.name+'.relocating')
shutil.copy2(path,temporary)
if sha(temporary)!=digest:raise RuntimeError('Cache copy verification failed')
temporary.replace(destination)
inventory[str(relative)]=dict(bytes=path.stat().st_size,sha256=digest)
if set(inventory)!={str(p.relative_to(source)) for p in source.rglob('*') if p.is_file()}:
raise RuntimeError('Cache changed during relocation')
for path in files:
if sha(path)!=inventory[str(path.relative_to(source))]['sha256']:
raise RuntimeError('Source cache changed during relocation')
for name in ('active.json','editor-active.json','route-active.json'):
if (state/name).exists():raise RuntimeError('Worker became active during copy')
active_target=target
if args.fresh:
active_target=target.with_name(target.name+'.fresh')
active_target.mkdir(exist_ok=False)
backup=source.with_name(source.name+'.relocation-source')
if backup.exists():raise RuntimeError('Unfinished prior relocation')
source.rename(backup)
try:
subprocess.run(['cmd','/c','mklink','/J',str(source),str(active_target)],check=True,capture_output=True)
if source.resolve()!=active_target:raise RuntimeError('Junction target mismatch')
except Exception:
if source.is_junction():source.rmdir()
backup.rename(source)
raise
report.update(applied=True,inventory=inventory,active_destination=str(active_target),
previous_bytes_preserved=True,fresh=args.fresh)
(target.parent/(args.cache+'-cache-relocation.json')).write_text(json.dumps(report,indent=2))
shutil.rmtree(backup)
print(json.dumps({k:v for k,v in report.items() if k!='inventory'}))
if __name__=='__main__':main()
+6
View File
@@ -6,6 +6,7 @@ bundle alone is not evidence of which cached USD the renderer will load.
import hashlib
import json
import shutil
import uuid
from pathlib import Path
@@ -83,6 +84,11 @@ def prepare_gaussian(source, convert, recipe, *, cache_root=None):
if valid is not None:
return output, valid
directory.mkdir(parents=True, exist_ok=True)
# USD retains all SH coefficients and is slightly larger than its PLY.
# Refuse before conversion rather than filling the Worker volume midway.
required = int(identity["source_bytes"] * 1.25) + 4 * 1024**3
if shutil.disk_usage(directory).free < required:
raise RuntimeError("Недостаточно места для Gaussian USD-кэша: освободите диск или перенесите кэш.")
token = uuid.uuid4().hex
temporary = directory / (token + ".part.usd")
receipt_temporary = directory / (token + ".part.json")
+35 -18
View File
@@ -23,7 +23,7 @@ def digest(path):
return hashlib.file_digest(stream, "sha256").hexdigest()
def prepare_project(client, run, state, episode, job, pulse):
def prepare_project(client, run, state, episode, job, pulse, isaac):
world = run["world"]
package = client.request("/worker/worlds/" + world["world_id"] + "/project-assets")
if package["world_sha256"] != world["sha256"]:
@@ -86,13 +86,20 @@ def prepare_project(client, run, state, episode, job, pulse):
# Keep 12 m of surrounding visual context in every direction. A saved route
# bounds the adaptation. Retain LOD0 and all SH bands without a count ceiling.
points = run["plan"]["points"]
prior = run["plan"].get("prepared_route")
if prior:
# A curved A/B route needs its entire preview, not just its endpoints.
# Unselected graph branches must not force the whole city into RTX.
# Long detours outside this visual region require spatial streaming;
# the graph never substitutes for live support in such an area.
points = points + [{"position": p} for p in prior["preview_xyz"]]
xyz = [[p["position"][0], p["position"][2], -p["position"][1]] for p in points]
bounds = [min(p[i] for p in xyz) - 12 for i in range(3)] + [
max(p[i] for p in xyz) + 12 for i in range(3)
]
key = hashlib.sha256(
json.dumps(
{"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__))},
{"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__)), "region_adapter": digest(Path(__file__).with_name("route_region.py"))},
sort_keys=True,
).encode()
).hexdigest()
@@ -136,23 +143,33 @@ def prepare_project(client, run, state, episode, job, pulse):
"0,0,180",
str(temporary),
]
commands = [command]
filtered = temporary.with_suffix(".region.ply")
if prior:
region = episode / "visual-region.json"
write_json(region, {"route_xz": [[p[0],-p[1]] for p in prior["preview_xyz"]],
"radius_m": 12, "authority": "visual-context-only"})
commands.append([str(isaac / "python.bat"), str(Path(__file__).with_name("route_region.py")),
"--source",str(temporary),"--output",str(filtered),"--region",str(region)])
with (episode / "project-preparation.log").open("wb") as log:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
job.assign(process)
deadline = time.monotonic() + 600
try:
while process.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Project preparation timed out")
time.sleep(1)
if process.returncode:
raise RuntimeError("SOG adaptation failed; inspect Worker evidence")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
for command in commands:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
job.assign(process)
deadline = time.monotonic() + 600
try:
while process.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Project preparation timed out")
time.sleep(1)
if process.returncode:
raise RuntimeError("SOG adaptation failed; inspect Worker evidence")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
if prior:
filtered.replace(temporary)
with temporary.open("rb") as f:
header = f.read(65536).split(b"end_header", 1)[0].decode("ascii")
count = int(re.search(r"element vertex (\d+)", header)[1])
+19 -1
View File
@@ -236,7 +236,10 @@ def main():
).encode()
).hexdigest(),
}
from k1link.simulation.ai_polygon.route_preparation import provider_identity
hello = {
"route_provider_sha256": provider_identity(),
"worker_id": "worker-006-ai-polygon",
"instance_id": instance,
"runtime": "isaac-sim-6.1",
@@ -320,10 +323,15 @@ def main():
raise
connect()
editor_marker = args.state / "editor-active.json"
route_marker = args.state / "route-active.json"
while True:
try:
# 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():
key = read_json(route_marker)["key"]
client.request("/worker/route-preparations/" + key, {"action": "release"})
route_marker.unlink()
if editor_marker.exists():
key = read_json(editor_marker)["key"]
client.request("/worker/editor-cache/" + key, {"action": "release"})
@@ -335,6 +343,16 @@ def main():
if polled["action"] == "idle":
time.sleep(0.5)
continue
if polled["action"] == "route-preparation":
from route_preparer import prepare_route
route_job = NativeJob()
write_json(route_marker, {"key": polled["preparation"]["key"]})
try:
prepare_route(client, polled["preparation"], args.state, args.isaac, route_job)
finally:
route_job.close()
continue
if polled["action"] == "editor-cache":
from editor_assets import prepare_editor
@@ -391,7 +409,7 @@ def main():
from project_assets import prepare_project
source, terrain_path = prepare_project(
client, run, args.state, episode, job, preparation_pulse
client, run, args.state, episode, job, preparation_pulse, args.isaac
)
else:
terrain_path = prepare_terrain(
+94
View File
@@ -0,0 +1,94 @@
"""Artifact-owned bounded CPU route job on the existing Worker reservation."""
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import time
from contextlib import suppress
from pathlib import Path
from urllib.parse import quote
from local_state import write_json
from model_stack import ROOT
from worker import terminate_episode
def sha(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream,'sha256').hexdigest()
def prepare_route(client, request, state, isaac, job):
if not re.fullmatch(r"[a-f0-9]{64}", request["key"]):
raise ValueError("Invalid route preparation identity")
endpoint='/worker/route-preparations/'+request['key']
last_pulse=-float('inf')
def pulse():
nonlocal last_pulse
if time.monotonic()-last_pulse>=1:
client.request('/worker/heartbeat',{'instance_id':client.instance})
last_pulse=time.monotonic()
target=state.parent/'assets/route-preparations'/request['key']
target.mkdir(parents=True,exist_ok=True)
def execute(command, limit):
with (target/'preparation.log').open('ab') as log:
child=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT,
env={**os.environ,"OPENBLAS_NUM_THREADS":"2","OMP_NUM_THREADS":"2"})
job.assign(child)
deadline=time.monotonic()+limit
try:
while child.poll() is None:
pulse()
if time.monotonic()>deadline:
raise TimeoutError('Route preparation timed out')
time.sleep(.5)
if child.returncode:
raise RuntimeError('Route preparation process failed')
finally:
if child.poll() is None:
terminate_episode(child)
try:
world=request['world']
package=client.request('/worker/worlds/'+world['world_id']+'/project-assets')
if package['world_sha256']!=world['sha256']:
raise ValueError('Route world changed')
item=next(a for a in package['artifacts'] if a['logical_path']==package['collision_path'])
if item['sha256']!=request['identity']['collider_sha256']:
raise ValueError('Route collider changed')
sources=state.parent/'assets/route-sources'
sources.mkdir(parents=True,exist_ok=True)
packed=sources/(item['sha256']+'.glb')
if not packed.exists() or sha(packed)!=item['sha256']:
if shutil.disk_usage(sources).free < item['byte_length']+512*1024**2:
raise RuntimeError('Insufficient route preparation space')
client.download_asset('/api/v1/simulation-worlds/projects/'+package['project_id']+
'/artifacts/'+quote(item['logical_path'],safe='/'),item,packed,pulse=pulse)
decoder=ROOT/'decode_collision.cjs'
decoded=sources/(digest_name(item['sha256'],sha(decoder))+'.decoded.glb')
receipt=decoded.with_suffix('.json')
if not (decoded.exists() and receipt.exists() and json.loads(receipt.read_text())['sha256']==sha(decoded)):
temporary=decoded.with_suffix('.part.glb')
execute([shutil.which('node'),str(decoder),str(packed),str(temporary)],60)
temporary.replace(decoded)
write_json(receipt,{'sha256':sha(decoded),'source_sha256':item['sha256'],'decoder_sha256':sha(decoder)})
request_file=target/'request.json'
write_json(request_file,request)
result_file=target/'result.json'
execute([str(isaac/'python.bat'),str(ROOT/'scene_route_field.py'),
'--request',str(request_file),'--collider',str(decoded),
'--output',str(result_file),'--field-cache',str(state.parent/'assets/route-fields')],480)
if result_file.stat().st_size>4*1024**2:
raise ValueError('Route artifact exceeds transport budget')
result=json.loads(result_file.read_text(encoding='utf-8'))
client.request(endpoint,{'action':'complete','result':result})
except Exception:
logging.exception('Route preparation failed')
with suppress(Exception):
client.request(endpoint,{'action':'fail'})
def digest_name(*parts):
return hashlib.sha256(':'.join(parts).encode()).hexdigest()
+74
View File
@@ -0,0 +1,74 @@
"""Lossless record selection for the spatial context of a curved route.
No count budget, LOD, opacity filter, SH truncation, reordering or requantization.
The selected region is a conservative superset of the 12 m route neighbourhood.
"""
import json
import math
from pathlib import Path
import numpy as np
from scipy.spatial import cKDTree
def route_samples(points, spacing=2.):
points=np.asarray(points,dtype=float)
if points.ndim!=2 or points.shape[1]!=2 or len(points)<2 or not np.isfinite(points).all():
raise ValueError('Invalid route region')
samples=[points[0]]
for a,b in zip(points,points[1:]):
count=max(1,math.ceil(float(np.linalg.norm(b-a))/spacing))
samples.extend(np.linspace(a,b,count+1)[1:])
return np.asarray(samples)
def select_region(source,output,points,radius=12.,chunk=250000):
tree=cKDTree(route_samples(points))
# Any point within radius of a segment is at most this far from a sample.
# Keeping a small superset avoids removing context between sample centres.
bound=math.hypot(radius,1.)
retained=0
with Path(source).open('rb') as src:
lines=[]
while sum(map(len,lines))<65536:
line=src.readline();lines.append(line)
if line.strip()==b'end_header':break
if not line:raise ValueError('Incomplete PLY header')
else:raise ValueError('PLY header exceeds budget')
text=[s.decode('ascii').strip() for s in lines]
if text[:2]!=['ply','format binary_little_endian 1.0']:
raise ValueError('Expected binary float Gaussian PLY')
elements=[i for i,s in enumerate(text) if s.startswith('element ')]
if len(elements)!=1 or not text[elements[0]].startswith('element vertex '):
raise ValueError('Expected a single Gaussian vertex element')
count=int(text[elements[0]].split()[-1]);properties=[s.split() for s in text if s.startswith('property ')]
if any(len(s)!=3 or s[1]!='float' for s in properties):
raise ValueError('Expected float Gaussian attributes')
names=[s[2] for s in properties];xi,zi=names.index('x'),names.index('z')
stride=len(names)*4
if Path(source).stat().st_size!=src.tell()+count*stride:
raise ValueError('PLY record size differs from its header')
def header(total):
return b''.join((f'element vertex {total:020d}\n'.encode() if i==elements[0] else line)
for i,line in enumerate(lines))
with Path(output).open('wb') as dst:
dst.write(header(0))
for start in range(0,count,chunk):
raw=src.read(min(chunk,count-start)*stride)
values=np.frombuffer(raw,dtype='<f4').reshape(-1,len(names))
xy=values[:,[xi,zi]]
if not np.isfinite(xy).all():raise ValueError('Nonfinite Gaussian position')
distance,_=tree.query(xy,workers=2,distance_upper_bound=bound)
keep=np.isfinite(distance)
dst.write(values[keep].tobytes());retained+=int(keep.sum())
if not retained:raise ValueError('Route context contains no Gaussians')
dst.seek(0);dst.write(header(retained))
return dict(source_count=count,retained_count=retained,all_attributes_preserved=True,
radius_m=radius,sampling_superset_radius_m=bound,decimated=False)
if __name__=='__main__':
import argparse
p=argparse.ArgumentParser()
for name in ('source','output','region'):p.add_argument('--'+name,type=Path,required=True)
args=p.parse_args();region=json.loads(args.region.read_text())
print(json.dumps(select_region(args.source,args.output,region['route_xz'],region['radius_m'])),flush=True)
+223
View File
@@ -0,0 +1,223 @@
"""Offline, replaceable geometric route prior. Worker CPU only.
The envelope describes likely connected ground, not a pedestrian/legal map.
Small enclosed occlusions are UNKNOWN, never asserted free. Their obstacle
silhouettes do not sculpt the global route. Live perception remains mandatory.
No prepared field, mesh or inferred height enters the local sensor pipeline.
"""
import json
import hashlib
import math
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
import numpy as np
from scipy import ndimage
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from terrain import load_glb
from k1link.simulation.ai_polygon.route_graph import build_route, PRIOR_MAP_SCHEMA
from k1link.simulation.ai_polygon.route_preparation import SCHEMA, provider_identity
from k1link.simulation.ai_polygon.run_inputs import digest, robot_geometry
CELL = .5
STRIDE = 4 # 2 m graph; the runtime receives coalesced direction segments.
MAX_CELLS = 2_000_000
MAX_NODES = 16384
def ground_envelope(vertices, faces, seed):
triangles = vertices[faces]
normal = np.cross(triangles[:,1]-triangles[:,0],triangles[:,2]-triangles[:,0])
length = np.linalg.norm(normal,axis=1)
flat = np.abs(normal[:,2]) >= np.maximum(1e-8,length)*math.cos(math.radians(25))
samples = np.concatenate((triangles[flat].reshape(-1,3),triangles[flat].mean(axis=1)))
if not len(samples):
raise ValueError("No ground candidates in scene")
origin = np.floor(vertices[:,:2].min(axis=0)/CELL)*CELL-CELL
shape = np.ceil((vertices[:,:2].max(axis=0)-origin)/CELL).astype(int)+2
if int(np.prod(shape)) > MAX_CELLS:
raise ValueError("Scene exceeds route preparation cell budget")
# Lower surface is a declared single-level approximation. Raised roofs are
# disconnected by height, not identified as cars/buildings by their size.
ij = np.floor((samples[:,:2]-origin)/CELL).astype(int)
height = np.full(tuple(shape),np.inf)
np.minimum.at(height,(ij[:,0],ij[:,1]),samples[:,2])
valid = np.isfinite(height)
seed_cell = np.floor((np.asarray(seed[:2])-origin)/CELL).astype(int)
nearby = np.argwhere(valid & (np.abs(height-seed[2]) <= .6))
if not len(nearby):
raise ValueError("Start has no matching ground layer")
nearest = nearby[np.argmin(np.linalg.norm(nearby-seed_cell,axis=1))]
if np.linalg.norm(nearest-seed_cell)*CELL > 1:
raise ValueError("Start outside mapped surface")
# Height connectivity removes roofs and keeps the selected terrain layer.
labels = np.full(height.shape,-1,dtype=np.int32)
labels[valid] = np.arange(np.count_nonzero(valid))
rows,cols = [],[]
for axis in (0,1):
a = (slice(None,-1),slice(None)) if axis==0 else (slice(None),slice(None,-1))
b = (slice(1,None),slice(None)) if axis==0 else (slice(None),slice(1,None))
with np.errstate(invalid='ignore'):
adjacent = valid[a]&valid[b]&(np.abs(height[a]-height[b]) <= .1+CELL*math.tan(math.radians(25)))
rows.extend(labels[a][adjacent]); cols.extend(labels[b][adjacent])
matrix = coo_matrix((np.ones(len(rows),dtype=np.uint8),(rows,cols)),shape=(np.count_nonzero(valid),)*2).tocsr()
_,components = connected_components(matrix,directed=False)
ground = np.zeros(height.shape,dtype=bool)
ground[valid] = components == components[labels[tuple(nearest)]]
# Close only bounded, enclosed holes. No connection across open terrain,
# a scene boundary, a long wall or an unobserved street is invented.
holes = ndimage.binary_fill_holes(ground)&~ground
regions,count = ndimage.label(holes)
unknown = np.zeros(height.shape,dtype=bool)
for index,sl in enumerate(ndimage.find_objects(regions),1):
if sl is None:
continue
local = regions[sl]==index
span = max(s.stop-s.start for s in sl)*CELL
if span > 6 or np.count_nonzero(local)*CELL**2 > 24:
continue
region = regions==index
rim = ndimage.binary_dilation(region)&ground
heights = height[rim]
if not len(heights) or np.ptp(heights) > .8:
continue
unknown |= region
envelope = ground|unknown
nearest_ground = ndimage.distance_transform_edt(~ground,return_distances=False,return_indices=True)
height[unknown] = height[tuple(nearest_ground[:,unknown])]
return origin,height,envelope,unknown
def route_graph(origin, height, envelope, unknown, positions, source, world_sha256):
clearance = ndimage.distance_transform_edt(envelope)*CELL
ids = np.full(envelope.shape,-1,dtype=np.int32)
cells = np.argwhere(envelope & (clearance >= .75))
cells = cells[(cells[:,0]%STRIDE==0)&(cells[:,1]%STRIDE==0)]
if not 1 <= len(cells) <= MAX_NODES-len(positions):
raise ValueError("Route graph exceeds node budget or has no ground")
nodes = []
for i,(x,y) in enumerate(cells):
ids[x,y] = i
nodes.append(dict(id=str(i),xy=(origin+(np.array([x,y])+.5)*CELL).tolist(),z=float(height[x,y])))
edges = []
def line(a,b):
n=max(2,int(np.linalg.norm(b-a)*2)+1)
ij=np.rint(np.linspace(a,b,n)).astype(int)
if np.any(ij<0) or np.any(ij>=np.array(envelope.shape)):
return None
if not envelope[ij[:,0],ij[:,1]].all():
return None
# Keep boundaries expensive. The route follows broad ground structure,
# with a bounded preference that cannot outweigh a long useful detour.
width=float(np.min(clearance[ij[:,0],ij[:,1]]))
z=height[ij[:,0],ij[:,1]]
if np.any(np.abs(np.diff(z))>.5):
return None
return width
def connect(i,j,a,b):
width=line(a,b)
if width is None or width < .5:
return
endpoints=np.rint(np.array([a,b])).astype(int)
actual_height=height[endpoints[:,0],endpoints[:,1]]
if np.any(np.abs(actual_height-np.array([nodes[i]["z"],nodes[j]["z"]]))>.6):
return
length=math.dist(nodes[i]["xy"],nodes[j]["xy"])
if length < .05:
return
edges.append(dict(id=str(len(edges)),start=str(i),end=str(j),half_width_m=min(20,width),
bidirectional=True,cost_m=length*(1+2/max(.5,width))))
for i,a in enumerate(cells):
for dx,dy in ((STRIDE,0),(0,STRIDE),(STRIDE,STRIDE),(STRIDE,-STRIDE)):
b=a+[dx,dy]
if np.any(b<0) or np.any(b>=np.array(envelope.shape)):
continue
j=int(ids[tuple(b)])
if j>=0:
connect(i,j,a,b)
goals=[]
for position in positions:
cell=(np.asarray(position[:2])-origin)/CELL-.5
index=len(nodes)
nodes.append(dict(id=str(index),xy=position[:2],z=position[2]))
distances=np.linalg.norm(cells-cell,axis=1)*CELL
added=len(edges)
for j in np.argsort(distances)[:12]:
if distances[j]>3:
break
connect(index,int(j),cell,cells[j])
if added==len(edges):
raise ValueError("Endpoint is outside connected ground envelope")
goals.append(str(index))
if len(edges)>65536:
raise ValueError("Route graph edge budget exceeded")
graph=dict(schema_version=PRIOR_MAP_SCHEMA,frame="world-xy-metres",world_sha256=world_sha256,
nodes=nodes,edges=edges,no_go=[],corridor_policy="advisory",source=source)
graph["sha256"]=digest(graph)
return dict(map=graph,start_node=goals[0],goal_nodes=goals[1:],blocked_edges=[])
def prepare(request, collider, output, field_cache):
identity=request["identity"]
if identity["provider_sha256"] != provider_identity():
raise ValueError("Installed route provider changed")
world=request["world"]
positions=[p["position"] for p in identity["points"]]
# Terrain extraction is independent of A/B; selection of a height component
# uses the declared start layer and is therefore explicitly cache-bound.
field_identity=dict(world=world["sha256"],collider=identity["collider_sha256"],
provider=identity["provider_sha256"],seed=positions[0],
rotation=world["local_scene"]["collision_rotation"])
cache=Path(field_cache)/(digest(field_identity)+'.npz')
cache.parent.mkdir(parents=True,exist_ok=True)
receipt=cache.with_suffix(".json")
valid_cache=cache.exists() and receipt.exists()
if valid_cache:
with cache.open("rb") as stream:
valid_cache=json.loads(receipt.read_text()).get("sha256")==hashlib.file_digest(stream,"sha256").hexdigest()
if valid_cache:
with np.load(cache,allow_pickle=False) as value:
origin,height,envelope,unknown=(value[k] for k in ('origin','height','envelope','unknown'))
else:
vertices,faces=load_glb(collider,world["local_scene"]["collision_rotation"])
origin,height,envelope,unknown=ground_envelope(vertices,faces,positions[0])
np.savez_compressed(cache,origin=origin,height=height,envelope=envelope,unknown=unknown)
with cache.open("rb") as stream:
receipt.write_text(json.dumps({"sha256":hashlib.file_digest(stream,"sha256").hexdigest(),"identity":field_identity}))
source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')}
routing=route_graph(origin,height,envelope,unknown,positions,source,world['sha256'])
inputs=dict(routing=routing,mission={"route_xy":[p[:2] for p in positions[1:]]},
robot={"geometry":robot_geometry(request['robot'])},sha256=request['key'])
route=build_route(inputs)
if any(leg['status']!='ready' for leg in route['legs']):
raise ValueError("No complete route between all task points")
node_z={tuple(n['xy']):n['z'] for n in routing['map']['nodes']}
preview=[positions[0]]
for leg in route['legs']:
for segment in leg['segments']:
xy=segment['end_xy']; preview.append([*xy,node_z[tuple(xy)]])
result=dict(schema_version=SCHEMA,identity=identity,routing=routing,preview_xyz=preview,
length_m=sum(leg['length_m'] for leg in route['legs']),
evidence=dict(field_sha256=digest(field_identity),cell_m=CELL,
mapped_cells=int(envelope.sum()),uncertain_cells=int(unknown.sum()),
authority='route-intent-only',
limitations=['geometric-prior-not-pedestrian-map','single-ground-layer',
'small-enclosed-occlusions-unknown','live-sensors-required']))
result['sha256']=digest(result)
Path(output).write_text(json.dumps(result,allow_nan=False,separators=(",",":")),encoding='utf-8')
if __name__=='__main__':
import argparse
parser=argparse.ArgumentParser()
for name in ('request','collider','output','field-cache'):
parser.add_argument('--'+name,required=True)
args=parser.parse_args()
prepare(json.loads(Path(args.request).read_text(encoding='utf-8')),args.collider,args.output,args.field_cache)
@@ -190,7 +190,7 @@ def registry(adapter_root: Path) -> ModuleRegistry:
),
ModuleSpec(
"simulation-declared-route",
"Маршрут · объявленная карта",
"Маршрут · карта или сцена",
"preparation",
nav["image"].removeprefix("sha256:"),
digest(
@@ -198,8 +198,9 @@ def registry(adapter_root: Path) -> ModuleRegistry:
name: hashlib.sha256(
Path(__file__).with_name(name).read_bytes()
).hexdigest()
for name in ("route_graph.py", "run_inputs.py")
}
for name in ("route_graph.py", "run_inputs.py", "route_preparation.py")
} | {name: hashlib.sha256((adapter_root/name).read_bytes()).hexdigest()
for name in ("scene_route_field.py", "route_preparer.py")}
),
None,
digest({"route": "missioncore.global-route/v1", "authority": "route-intent-only"}),
@@ -151,6 +151,7 @@ class WorkerHello(Contract):
rover_settings_versions: list[Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"]] = Field(
default_factory=list, max_length=2
)
route_provider_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
execution_inputs_versions: list[
Literal[
"missioncore.simulation-inputs/v1",
@@ -386,7 +387,15 @@ class RealtimeSnapshot(Contract):
planning: PlanningState | None = None
class RoutePrepare(Contract):
cache_key: str = Field(pattern=r"^[a-f0-9]{64}$")
robot_id: str = Field(max_length=80)
robot_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
points: list[RoutePoint] = Field(min_length=2, max_length=33)
class LocalPlanCreate(Contract):
route_preparation_key: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
cache_key: str = Field(pattern=r"^[a-f0-9]{64}$")
draft_id: str = Field(pattern=r"^[a-f0-9]{32}$")
sequence: int = Field(ge=0)
@@ -57,6 +57,7 @@ class PlanStore:
draft_id=None,
cache_key=None,
editor_collider_sha256=None,
prepared_route=None,
):
if not 2 <= len(points) <= 33:
raise ValueError("Нужны старт и финиш: от 2 до 33 точек.")
@@ -72,6 +73,7 @@ class PlanStore:
and old["robot_sha256"] == run["robot"]["sha256"]
and old["name"] == name
and old["points"] == points
and old.get("prepared_route") == prepared_route
):
return old
for point in points:
@@ -119,6 +121,12 @@ class PlanStore:
editor_cache_key=cache_key,
editor_collider_sha256=editor_collider_sha256,
)
if prepared_route is not None:
value["prepared_route"] = prepared_route
value["route_preparation_key"] = self.digest(prepared_route["identity"])
value["length_m"] = prepared_route["length_m"]
next_point = prepared_route["preview_xyz"][1]
settings["heading_degrees"] = math.degrees(math.atan2(next_point[1]-first[1], next_point[0]-first[0]))
row = {**value, "sha256": self.digest(value)}
write_json(self.root / (row["plan_id"] + ".json"), row)
return row
+72 -11
View File
@@ -13,6 +13,7 @@ from k1link.simulation.ai_polygon.run_inputs import digest, number
MAP_SCHEMA = "missioncore.route-map/v1"
ROUTE_SCHEMA = "missioncore.global-route/v1"
PRIOR_MAP_SCHEMA = "missioncore.route-map/v2"
def fields(value, expected):
@@ -35,29 +36,44 @@ def xy(value):
def validate_routing(routing, world_sha256, goals):
fields(routing, "map start_node goal_nodes blocked_edges")
graph = routing["map"]
fields(graph, "schema_version frame world_sha256 nodes edges no_go sha256")
prior = graph.get("schema_version") == PRIOR_MAP_SCHEMA
fields(graph, "schema_version frame world_sha256 nodes edges no_go sha256"
+ (" corridor_policy source" if prior else ""))
if prior:
if graph["corridor_policy"] != "advisory":
raise ValueError("Unsupported route prior policy")
fields(graph["source"], "provider provider_sha256 collider_sha256")
if (not isinstance(graph["source"]["provider"], str)
or not 1 <= len(graph["source"]["provider"]) <= 100
or any(not re.fullmatch(r"[a-f0-9]{64}",str(graph["source"][k]))
for k in ("provider_sha256", "collider_sha256"))):
raise ValueError("Invalid route source identity")
if (
graph["schema_version"] != MAP_SCHEMA
graph["schema_version"] not in {MAP_SCHEMA, PRIOR_MAP_SCHEMA}
or graph["frame"] != "world-xy-metres"
or not re.fullmatch(r"[a-f0-9]{64}", str(world_sha256))
or graph["world_sha256"] != world_sha256
or graph["sha256"] != digest({k: v for k, v in graph.items() if k != "sha256"})
):
raise ValueError("Route map identity or world mismatch")
if not isinstance(graph["nodes"], list) or not 1 <= len(graph["nodes"]) <= 2048:
if not isinstance(graph["nodes"], list) or not 1 <= len(graph["nodes"]) <= (16384 if prior else 2048):
raise ValueError("Invalid route node budget")
nodes = {}
for node in graph["nodes"]:
fields(node, "id xy")
fields(node, "id xy" + (" z" if prior else ""))
if prior:
number(node["z"], -1e7, 1e7)
key = identity(node["id"])
if key in nodes:
raise ValueError("Duplicate route node")
nodes[key] = xy(node["xy"])
if not isinstance(graph["edges"], list) or len(graph["edges"]) > 8192:
if not isinstance(graph["edges"], list) or len(graph["edges"]) > (65536 if prior else 8192):
raise ValueError("Invalid route edge budget")
edges = set()
for edge in graph["edges"]:
fields(edge, "id start end half_width_m bidirectional")
fields(edge, "id start end half_width_m bidirectional" + (" cost_m" if prior else ""))
if prior:
number(edge["cost_m"], 0.05, 1e7)
key = identity(edge["id"])
if (
key in edges
@@ -159,7 +175,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
reason = "declared-blocked"
elif edge["id"] in unavailable:
reason = "observed-unavailable"
elif edge["half_width_m"] < radius:
elif graph.get("corridor_policy") != "advisory" and edge["half_width_m"] < radius:
reason = "insufficient-corridor-width"
elif any(
segment_intersects_box(
@@ -187,7 +203,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
if node == goal:
break
for target, edge, a, b in adjacency[node]:
candidate = cost + math.dist(a, b)
candidate = cost + edge.get("cost_m", math.dist(a, b))
if candidate < distances.get(target, math.inf):
distances[target] = candidate
previous[target] = (node, edge, a, b)
@@ -204,6 +220,8 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
)
cursor = parent
segments.reverse()
if graph.get("corridor_policy") == "advisory":
segments = simplify_prior_segments(segments)
legs.append(
dict(
start_node=start,
@@ -211,7 +229,7 @@ def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0)
start_xy=nodes[start],
goal_xy=nodes[goal],
status="ready" if goal in distances else "unreachable",
length_m=distances.get(goal),
length_m=sum(math.dist(s["start_xy"],s["end_xy"]) for s in segments) if goal in distances else None,
segments=segments,
)
)
@@ -237,7 +255,7 @@ def disc_permitted(point, radius, segments, no_go):
Conservative at junctions: no claim that separately safe corners imply a
safe body inside a non-convex union. No-go rectangles have independent veto.
"""
if not any(
if not any(s.get("guidance_only") is True for s in segments) and not any(
projection(point, s["start_xy"], s["end_xy"])[1] + radius <= s["half_width_m"]
for s in segments
):
@@ -261,7 +279,7 @@ def discs_permitted(points, radius, segments, no_go):
points = np.asarray(points, dtype=float).reshape(-1, 2)
if not np.isfinite(points).all() or not math.isfinite(radius) or radius < 0:
raise ValueError("Invalid corridor goal candidates")
allowed = np.zeros(len(points), dtype=bool)
allowed = np.full(len(points), any(s.get("guidance_only") is True for s in segments), dtype=bool)
for segment in segments:
start, end = np.asarray(segment["start_xy"]), np.asarray(segment["end_xy"])
delta = end - start
@@ -275,3 +293,46 @@ def discs_permitted(points, radius, segments, no_go):
)
allowed &= np.linalg.norm(distance, axis=1) > radius
return allowed
def simplify_prior_segments(segments):
"""Simplify direction intent with RDP, retaining every graph edge identity.
Grid steps may individually look like corners. Fit the entire chain before
splitting long references, so a shallow street does not become alternating
straight/45-degree instructions. No simplified chord grants motion support.
"""
if not segments:
return []
points = [segments[0]["start_xy"]] + [s["end_xy"] for s in segments]
keep = {0, len(points)-1}
pending = [(0,len(points)-1)]
while pending:
a,b = pending.pop()
if b-a <= 1:
continue
distances = [(math.dist(points[i],points[a]) if math.dist(points[a],points[b]) < .05
else projection(points[i],points[a],points[b])[1], i)
for i in range(a+1,b)]
error,index = max(distances)
if error > 1.5:
keep.add(index)
pending.extend(((a,index),(index,b)))
corners = sorted(keep)
stops = [0]
for a,b in zip(corners,corners[1:]):
cursor = a
while math.dist(points[cursor],points[b]) > 20 and cursor+1 < b:
end = cursor+1
while end+1 < b and math.dist(points[cursor],points[end+1]) <= 20:
end += 1
stops.append(end)
cursor = end
stops.append(b)
result = []
for a,b in zip(stops,stops[1:]):
chain = segments[a:b]
result.append({**chain[0], "end_xy": chain[-1]["end_xy"],
"half_width_m": min(s["half_width_m"] for s in chain),
"guidance_only": True, "edge_ids": [s["edge_id"] for s in chain]})
return result
@@ -75,7 +75,7 @@ class RoutedMission(WaypointMission):
)
if receipt is None:
return None
self.unavailable_edges.add(segment["edge_id"])
self.unavailable_edges.update(segment.get("edge_ids", [segment["edge_id"]]))
event = {
"schema_version": "missioncore.route-revision/v1",
"revision": self.route_revision + 1,
@@ -181,7 +181,8 @@ class RoutedMission(WaypointMission):
self.route_failure, self.fault = "outside-route-corridor", "stuck"
return
along, lateral = projection(pose[:2], segment["start_xy"], segment["end_xy"])
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral * (
.15 if segment.get("guidance_only") else 1.)
# Supply a stable segment endpoint. The visual/local planner already
# chooses observed intermediate goals within its own lookahead. A second
# 0.8m target here sits in the camera blind strip and can make it choose
@@ -331,9 +332,17 @@ class RoutedMission(WaypointMission):
return goal is None
def retire_local_goal(self, target, *, failed=False):
# Recovery belongs to the current corner/return anchor. Comparing with
# the final task goal discarded a valid corner goal on every retry.
super().retire_local_goal(self.route_target, failed=failed)
segments = self.leg["segments"]
advisory_joint = (
self.segment_index < len(segments) - 1
and segments[self.segment_index].get("guidance_only")
and not segments[self.segment_index].get("return_to_anchor")
)
# A route hint is not a required body destination. In particular, a
# native planner abort must retire a measured goal near that hint;
# preserving it as task-arrival evidence pins the rover to a blocked
# intermediate point. Explicit goals and return anchors retain it.
super().retire_local_goal(None if advisory_joint else self.route_target, failed=failed)
def arrival_candidate(self, pose):
return (
@@ -414,6 +423,12 @@ class RoutedMission(WaypointMission):
):
return None
adjacent = segments[self.segment_index : self.segment_index + 2]
if adjacent[0].get("guidance_only"):
along, lateral = projection(pose[:2], adjacent[0]["start_xy"], adjacent[0]["end_xy"])
length = math.dist(adjacent[0]["start_xy"], adjacent[0]["end_xy"])
# A soft line must not allow instant graph progress at a distance.
if length - along > 1.5 or lateral > max(2., adjacent[0]["half_width_m"]):
return None
directions = [np.asarray(s["end_xy"]) - s["start_xy"] for s in adjacent]
# A reversal is a visit and return, not a corner that can be cut.
if np.dot(*directions) <= -0.95 * np.linalg.norm(directions[0]) * np.linalg.norm(
@@ -0,0 +1,170 @@
"""Content-bound route preparation; providers supply intent, never live support."""
import copy
import hashlib
import json
import re
import threading
from pathlib import Path
from .run_inputs import digest, robot_geometry
from .route_graph import validate_routing, build_route
PROVIDER = "scene-ground-envelope/v1"
SCHEMA = "missioncore.prepared-route/v1"
KEY = re.compile(r"^[a-f0-9]{64}$")
def provider_identity():
root = Path(__file__).resolve().parents[4]
paths = [root / "simulation/ai-polygon/scene_route_field.py",
root / "simulation/ai-polygon/route_preparer.py",
Path(__file__).with_name("route_graph.py"), Path(__file__)]
return digest({p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths})
def preparation_identity(world, robot, points):
return dict(schema_version=SCHEMA, provider=PROVIDER, provider_sha256=provider_identity(),
world_sha256=world["sha256"], collider_sha256=world.get("collider_sha256"),
settings=world["settings"], robot_sha256=robot["sha256"],
geometry=robot_geometry(robot), points=points)
def validate_prepared(result, identity):
if (not isinstance(result, dict) or result.get("schema_version") != SCHEMA
or result.get("identity") != identity
or result.get("sha256") != digest({k:v for k,v in result.items() if k != "sha256"})):
raise ValueError("Подготовленный маршрут не соответствует заданию.")
positions = [p["position"] for p in identity["points"]]
routing = validate_routing(result["routing"], identity["world_sha256"], [p[:2] for p in positions[1:]])
graph = routing["map"]
if (graph.get("source") != {"provider": identity["provider"],
"provider_sha256": identity["provider_sha256"],
"collider_sha256": identity["collider_sha256"]}
or graph.get("corridor_policy") != "advisory"
or next(n["xy"] for n in graph["nodes"] if n["id"] == routing["start_node"]) != positions[0][:2]):
raise ValueError("Источник или начало маршрута изменились.")
preview = result.get("preview_xyz")
if not isinstance(preview, list) or not 2 <= len(preview) <= 4096:
raise ValueError("Нет траектории для просмотра.")
import math
if any(not isinstance(p,list) or len(p)!=3 or any(type(v) not in (int,float) or not math.isfinite(v) or abs(v)>1e7 for v in p) for p in preview):
raise ValueError("Некорректная траектория.")
if preview[0] != positions[0] or preview[-1] != positions[-1]:
raise ValueError("Траектория не замыкает заданные точки.")
route = build_route(dict(routing=routing, robot={"geometry":identity["geometry"]},
mission={"route_xy":[p[:2] for p in positions[1:]]},sha256=digest(identity)))
if any(leg["status"] != "ready" for leg in route["legs"]):
raise ValueError("Маршрут не соединяет все точки задания.")
heights={tuple(n["xy"]):n["z"] for n in graph["nodes"]}
expected=[positions[0]]
for leg in route["legs"]:
expected.extend([*s["end_xy"],heights[tuple(s["end_xy"])]] for s in leg["segments"])
if preview != expected or not math.isclose(result.get("length_m",-1),
sum(l["length_m"] for l in route["legs"]),abs_tol=1e-6):
raise ValueError("Предпросмотр не соответствует исполняемому маршруту.")
return copy.deepcopy(result)
def write_json(path, row):
# The preparation contract is imported by the lean Worker. Core storage
# dependencies must not be pulled into its scientific Python runtime.
from .worlds import write_json as persist
persist(path, row)
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()
def path(self, key):
if not KEY.fullmatch(key):
raise FileNotFoundError(key)
path = self.root / (key + ".json")
if path.is_symlink():
raise ValueError("Invalid route preparation file")
return path
def get(self, key):
with self.lock:
row = json.loads(self.path(key).read_text())
if row["key"] != key or digest(row["identity"]) != key:
raise ValueError("Route preparation identity changed")
if row["status"] == "ready":
validate_prepared(row["result"], row["identity"])
return row
def request(self, world, robot, points):
with self.lock:
if not world.get("local_scene"):
raise ValueError("Для подготовки маршрута нужна локальная геометрия сцены.")
# Reuse the task's existing point validation without publishing a task.
if not 2 <= len(points) <= 33 or len({p["id"] for p in points}) != len(points):
raise ValueError("Нужны разные старт и финиш.")
import math
positions = [p["position"] for p in points]
if any(len(p)!=3 or any(not math.isfinite(v) or abs(v)>10000 for v in p) for p in positions):
raise ValueError("Некорректная точка маршрута.")
if any(math.dist(a[:2],b[:2])<.15 for a,b in zip(positions,positions[1:])):
raise ValueError("Соседние точки должны быть дальше 15 см.")
identity = preparation_identity(world, robot, points)
key = digest(identity)
path = self.path(key)
if path.exists():
row = self.get(key)
if row["status"] != "failed":
return row
row = dict(key=key, identity=identity, world=world, robot=robot,
status="queued", error=None, result=None, owner=None)
write_json(path,row)
return row
def pending(self):
with self.lock:
for path in sorted(self.root.glob("*.json")):
row = json.loads(path.read_text())
if row["status"] in {"queued", "preparing"}:
return self.get(path.stem)
return None
def claim(self, key, owner):
with self.lock:
row = self.get(key)
if row["owner"] not in (None, owner):
raise RuntimeError("Route preparation belongs to another Worker session")
if row["status"] in {"queued", "preparing"}:
row.update(status="preparing",owner=owner)
write_json(self.path(key),row)
return row
def update(self, key, body, owner):
with self.lock:
row = self.get(key)
if row["owner"] != owner:
raise RuntimeError("Route preparation owner changed")
action = body.get("action")
if action == "complete":
result = validate_prepared(body.get("result"), row["identity"])
if row["status"] == "ready":
if row["result"] != result:
raise ValueError("Route preparation already sealed")
return row
if row["status"] != "preparing":
raise RuntimeError("Route preparation is not running")
row.update(status="ready",result=result,error=None)
elif action == "fail" and row["status"] != "ready":
row.update(status="failed",error="По данным сцены маршрут построить не удалось. Проверьте точки и доступную поверхность.")
elif action == "release":
if row["status"] == "preparing":
row.update(status="failed",error="Подготовка маршрута прервана. Повторите планирование.")
else:
raise ValueError("Unknown route preparation action")
write_json(self.path(key),row)
return row
def for_plan(self, key, world, robot, points):
row = self.get(key)
if row["status"] != "ready":
raise ValueError("Сначала спланируйте маршрут.")
return validate_prepared(row["result"],preparation_identity(world,robot,points))
+15
View File
@@ -356,6 +356,21 @@ class RunStore:
CONTINUOUS_SENSOR_SCHEMA)),
continuous=CONTINUOUS_SENSOR_SCHEMA in versions,
)
if plan and plan.get("prepared_route"):
from .route_preparation import validate_prepared, preparation_identity
from .run_inputs import declared_route_inputs
# Admission uses the unmodified world/profile, before speed/mass
# settings alter execution. The prior grants no motion authority.
original_world = self.worlds.get(request.world_id)
prepared = validate_prepared(plan["prepared_route"],
preparation_identity(original_world, robot, plan["points"]))
if self.worker.get("route_provider_sha256") != prepared["identity"]["provider_sha256"]:
raise ValueError("Worker не поддерживает подготовленный маршрут.")
row["execution_inputs"] = declared_route_inputs(
row["execution_inputs"], prepared["routing"], effective_robot, world["sha256"])
# One map payload per immutable run; the plan identity still binds
# the complete saved task, while this is its execution projection.
row["plan"] = {**plan, "prepared_route": {k:v for k,v in prepared.items() if k != "routing"}}
self._publish(row)
try:
self.queue.reserve_simulation(run_id)
+24 -5
View File
@@ -30,6 +30,8 @@ from k1link.simulation.ai_polygon.contracts import (
WorldSettings,
)
from k1link.simulation.ai_polygon.editor_cache import EditorCache
from k1link.simulation.ai_polygon.route_preparation import RoutePreparationStore, provider_identity
from k1link.web.route_preparation_api import build_route_preparation_router, public_plan, public_run
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
@@ -41,6 +43,7 @@ def build_ai_polygon_router(
worlds = WorldStore(data_dir)
runs = RunStore(worlds, queue)
editor = EditorCache(data_dir, worlds)
routes = RoutePreparationStore(data_dir)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
from k1link.web.ai_profile_api import build_ai_profile_router
@@ -62,9 +65,12 @@ def build_ai_polygon_router(
if not authorization or not secrets.compare_digest(authorization, expected):
raise HTTPException(401, "Worker authentication required")
router.include_router(build_route_preparation_router(routes, worlds, editor, runs, invoke, authenticate))
@router.get("/catalog")
def catalog():
runtime = runs.status()
runtime = {**runtime, "active_run": public_run(runtime.get("active_run"))}
locations = worlds.list()
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
locations = [
@@ -83,8 +89,8 @@ def build_ai_polygon_router(
"robots": robot_catalog(adapters),
"worlds": locations,
"runtime": runtime,
"runs": runs.library.visible(runs.list(), "run_id")[:30],
"plans": runs.plans.visible_list(),
"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()],
}
@router.get("/worker/worlds/{world_id}/project-assets")
@@ -169,16 +175,19 @@ def build_ai_polygon_router(
if cached["status"] != "ready" or editor.identity(world) != cached["identity"]:
raise HTTPException(409, "Локация изменилась. Откройте планирование заново.")
robot = invoke(select_robot, body.robot_id, body.robot_sha256)
prepared = invoke(routes.for_plan, body.route_preparation_key, world, robot,
[p.model_dump(mode="json") for p in body.points]) if body.route_preparation_key else None
context = {"world": world, "robot": robot, "run_id": None}
return invoke(
lambda: runs.plans.create(
context,
body.name,
[p.model_dump() for p in body.points],
[p.model_dump(mode="json") for p in body.points],
body.sequence,
draft_id=body.draft_id,
cache_key=body.cache_key,
editor_collider_sha256=cached["files"]["collision.glb"]["sha256"],
prepared_route=prepared,
)
)
@@ -192,8 +201,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():
raise HTTPException(409, "Дождитесь загрузки локальной сцены.")
if editor.pending() or routes.pending():
raise HTTPException(409, "Дождитесь подготовки сцены и маршрута.")
if body.clock == "realtime":
graph = invoke(compose, adapters, body.composition)
body = body.model_copy(update={"composition": graph.selection_document()})
@@ -306,6 +315,16 @@ def build_ai_polygon_router(
except RuntimeError:
return value
return {"action": "editor-cache", "cache": pending}
if value["action"] == "idle" and runs.queue is not None:
pending = routes.pending()
worker = runs.status().get("worker") or {}
if pending and worker.get("route_provider_sha256") == provider_identity():
try:
runs.queue.reserve_simulation("aicache-" + pending["key"])
claimed = routes.claim(pending["key"],body.instance_id)
except RuntimeError:
return value
return {"action": "route-preparation", "preparation": claimed}
return value
@router.post("/worker/editor-cache/{key}")
+68
View File
@@ -0,0 +1,68 @@
"""Existing simulation planning surface's bounded asynchronous route port."""
import json
from fastapi import APIRouter, Header, HTTPException, Request
from k1link.simulation.ai_polygon.contracts import RoutePrepare
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.route_preparation import provider_identity
def public_plan(plan):
if not plan or not plan.get('prepared_route'):
return plan
return {**plan,'prepared_route':{k:v for k,v in plan['prepared_route'].items() if k!='routing'}}
def public_run(run):
if not run or not (run.get('plan') or {}).get('prepared_route'):
return run
return {**run,'plan':public_plan(run['plan']),
'execution_inputs':{k:v for k,v in run.get('execution_inputs',{}).items() if k!='routing'}}
def public_preparation(row):
return {k:v for k,v in row.items() if k not in ('world','robot','owner','result')} | {
'result': {k:v for k,v in row['result'].items() if k!='routing'} if row.get('result') else None}
def build_route_preparation_router(store, worlds, editor, runs, invoke, authenticate):
router=APIRouter()
@router.post('/route-preparations',status_code=201)
def prepare(body:RoutePrepare):
with runs.lock:
cached=invoke(editor.get,body.cache_key)
world=invoke(worlds.get,cached['world']['world_id'])
if cached['status']!='ready' or editor.identity(world)!=cached['identity']:
raise HTTPException(409,'Локация изменилась. Откройте планирование заново.')
worker=runs.status().get('worker') or {}
if worker.get('route_provider_sha256')!=provider_identity():
raise HTTPException(409,'Подключите Worker с модулем подготовки маршрута.')
robot=invoke(select_robot,body.robot_id,body.robot_sha256)
row=invoke(store.request,world,robot,[p.model_dump(mode="json") for p in body.points])
return public_preparation(row)
@router.get('/route-preparations/{key}')
def status(key:str):
return public_preparation(invoke(store.get,key))
@router.post('/worker/route-preparations/{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 block in request.stream():
raw.extend(block)
if len(raw)>4*1024**2:
raise HTTPException(413,'Route result exceeds budget')
try:
body=json.loads(raw)
except ValueError as exc:
raise HTTPException(400,'Invalid route result') from exc
row=invoke(store.update,key,body,instance_id)
if body.get('action')=='release' and runs.queue is not None:
invoke(runs.queue.release_simulation,'aicache-'+key)
return public_preparation(row)
return router
+180
View File
@@ -0,0 +1,180 @@
"""A route prior cannot become a rail, motion evidence, or a stale task."""
import copy
import math
import numpy as np
import pytest
from k1link.simulation.ai_polygon.route_graph import (
PRIOR_MAP_SCHEMA, build_route, disc_permitted, discs_permitted, validate_routing,
)
from k1link.simulation.ai_polygon.route_preparation import (
RoutePreparationStore, preparation_identity, validate_prepared, SCHEMA,
)
from k1link.simulation.ai_polygon.run_inputs import digest
from k1link.simulation.ai_polygon.robots import select_robot
def fixture():
points=[dict(id='a'*16,position=[0.,0.,0.]),dict(id='b'*16,position=[12.,0.,0.])]
world=dict(sha256='a'*64,world_id='aiworld-'+'a'*32,collider_sha256='b'*64,
settings={'prepared':True},local_scene={'collision_rotation':[0,0,0]})
robot=select_robot('dcd006-v020')
identity=preparation_identity(world,robot,points)
nodes=[dict(id=str(i),xy=p,z=0.) for i,p in enumerate([[0.,0.],[4.,0.],[8.,0.],[12.,0.],[0.,5.],[12.,5.]])]
edges=[]
for a,b in [(0,1),(1,2),(2,3),(0,4),(4,5),(5,3)]:
edges.append(dict(id=str(len(edges)),start=str(a),end=str(b),half_width_m=1.,bidirectional=True,
cost_m=math.dist(nodes[a]['xy'],nodes[b]['xy'])))
graph=dict(schema_version=PRIOR_MAP_SCHEMA,frame='world-xy-metres',world_sha256=world['sha256'],
nodes=nodes,edges=edges,no_go=[],corridor_policy='advisory',
source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')})
graph['sha256']=digest(graph)
routing=dict(map=graph,start_node='0',goal_nodes=['3'],blocked_edges=[])
inputs=dict(routing=routing,robot={'geometry':{'length_m':1.,'width_m':1.}},mission={'route_xy':[[12.,0.]]},sha256='c'*64)
result=dict(schema_version=SCHEMA,identity=identity,routing=routing,preview_xyz=[p['position'] for p in points],length_m=12.)
result['sha256']=digest(result)
return world,robot,points,inputs,result
def test_prior_is_not_a_rail_and_does_not_erase_no_go():
*_,inputs,_=fixture()
route=build_route(inputs)
segments=route['legs'][0]['segments']
assert len(segments)==1 and segments[0]['edge_ids']==['0','1','2']
assert route['authority']=='route-intent-only'
assert disc_permitted([5,4],.8,segments,[]) # freely measured local detour
assert discs_permitted([[5,4],[6,6]],.8,segments,[]).all()
no_go=[dict(lower_xy=[4.,3.],upper_xy=[6.,5.])]
assert not disc_permitted([5,4],.8,segments,no_go)
assert discs_permitted([[5,4],[7,7]],.8,segments,no_go).tolist()==[False,True]
hard=[{k:v for k,v in s.items() if k not in ('guidance_only','edge_ids')} for s in segments]
assert not disc_permitted([5,4],.8,hard,[])
def test_observed_exclusion_can_use_an_alternate_branch():
*_,inputs,_=fixture()
route=build_route(inputs,unavailable_edges=['0','1','2'])
assert route['legs'][0]['status']=='ready'
assert route['legs'][0]['length_m']==22.
assert [s['end_xy'] for s in route['legs'][0]['segments']]==[[0.,5.],[12.,5.],[12.,0.]]
def test_prior_world_and_map_identities_are_not_interchangeable():
*_,inputs,_=fixture()
with pytest.raises(ValueError,match='identity'):
validate_routing(inputs['routing'],'d'*64,[[12.,0.]])
inputs['routing']['map']['edges'][0]['cost_m']=0.
with pytest.raises(ValueError):
validate_routing(inputs['routing'],'a'*64,[[12.,0.]])
def test_preparation_owner_retry_and_stale_draft(tmp_path):
world,robot,points,_,result=fixture()
store=RoutePreparationStore(tmp_path)
row=store.request(world,robot,points)
assert store.request(world,robot,points)==row
store.claim(row['key'],'worker')
with pytest.raises(RuntimeError,match='owner'):
store.update(row['key'],{'action':'complete','result':result},'other')
finished=store.update(row['key'],{'action':'complete','result':result},'worker')
assert finished['status']=='ready' and store.pending() is None
assert store.for_plan(row['key'],world,robot,points)==result
changed=copy.deepcopy(points);changed[-1]['position'][0]+=.1
with pytest.raises(ValueError,match='соответствует'):
store.for_plan(row['key'],world,robot,changed)
assert store.update(row['key'],{'action':'release'},'worker')['status']=='ready'
def test_interrupted_preparation_cannot_launch(tmp_path):
world,robot,points,*_=fixture()
store=RoutePreparationStore(tmp_path)
row=store.request(world,robot,points);store.claim(row['key'],'worker')
store.update(row['key'],{'action':'release'},'worker')
with pytest.raises(ValueError,match='спланируйте'):
store.for_plan(row['key'],world,robot,points)
assert store.request(world,robot,points)['status']=='queued'
def test_http_save_preserves_json_points_in_prepared_route(tmp_path, monkeypatch):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.ai_polygon_api import build_ai_polygon_router
from k1link.simulation.ai_polygon.worlds import WorldStore
from k1link.simulation.ai_polygon.editor_cache import EditorCache
world,robot,points,_,result=fixture()
cache={'world':world,'status':'ready','identity':'test',
'files':{'collision.glb':{'sha256':'b'*64}}}
monkeypatch.setattr(WorldStore,'get',lambda self,key:world)
monkeypatch.setattr(EditorCache,'get',lambda self,key:cache)
monkeypatch.setattr(EditorCache,'identity',lambda self,value:'test')
store=RoutePreparationStore(tmp_path)
row=store.request(world,robot,points);store.claim(row['key'],'worker')
store.update(row['key'],{'action':'complete','result':result},'worker')
app=FastAPI();app.include_router(build_ai_polygon_router(tmp_path))
body=dict(cache_key='a'*64,robot_id=robot['robot_id'],robot_sha256=robot['sha256'],
draft_id='d'*32,sequence=1,name='Prepared route',points=points,
route_preparation_key=row['key'])
with TestClient(app) as client:
response=client.post('/api/v1/ai-polygon/plans',json=body)
assert response.status_code==201,response.text
saved=response.json()
assert saved['prepared_route']['sha256']==result['sha256']
assert client.post('/api/v1/ai-polygon/plans',json=body).json()['plan_id']==saved['plan_id']
body['points'][1]['position'][0]=11.
assert client.post('/api/v1/ai-polygon/plans',json=body).status_code==400
def test_advisory_joint_requires_actual_progress_and_current_support():
from k1link.simulation.ai_polygon.route_mission import RoutedMission
*_,inputs,_=fixture()
inputs['routing']['blocked_edges']=['0','1','2']
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
behavior={'max_speed_mps':1.})
mission=RoutedMission(inputs)
def sample(x,y,t,supported=True):
pose=[x,y,0.,0.,0.,0.,1.]
mission.route_observation(pose,t)
mission.last_time,mission.last_pose=t,tuple(pose)
body=dict(observation=dict(pose=pose,target_xy=mission.arrival_target(),
simulation_time_seconds=t,execution_inputs_sha256=inputs['sha256']),
admitted=supported,collision_free=True,support_known=True,
positive_surface_required=True,support_samples=4,supported_samples=4)
return mission.confirm_corridor_transition(pose,t,body)
assert sample(0.,0.,0.) is None # soft corridor is not permission to skip all joints
assert sample(0.,4.,4.,False) is None
assert sample(0.,4.,5.) is not None
assert mission.segment_index==1 and mission.index==0
assert sample(0.,4.,6.) is None
def test_native_abort_retires_soft_joint_goal_but_keeps_final_and_return_anchor():
from k1link.simulation.ai_polygon.route_mission import RoutedMission
*_, inputs, _ = fixture()
inputs["routing"]["blocked_edges"] = ["0", "1", "2"]
inputs.update(sensors={"schema_version": "missioncore.simulation-sensor-rig/v4"},
behavior={"max_speed_mps": 1.})
mission = RoutedMission(inputs)
pose = [0., 0., 0., 0., 0., 0., 1.]
mission.route_observation(pose, 0.)
mission.last_time, mission.last_pose = 0., tuple(pose)
goal = [0., 4.9, 0.]
mission.goal = goal
aborted = dict(status="blocked", speed_mps=0., yaw_rate_rps=0.,
route_observation={"observation": dict(pose=pose, simulation_time_seconds=0.,
execution_inputs_sha256=inputs["sha256"])},
planning_result=dict(status="aborted", goal_xy=goal[:2]))
mission.reject_local_plan(aborted, pose, 0., inputs["sha256"])
assert mission.goal is None and mission.failed_goals == [goal]
assert mission.segment_index == 0 and mission.index == 0
# Returning from a closed edge and the operator's final goal remain visits.
mission.leg["segments"][0]["return_to_anchor"] = True
mission.goal = goal
mission.retire_local_goal(None, failed=True)
assert mission.goal == goal
mission.segment_index = len(mission.leg["segments"]) - 1
mission.route_observation(pose, 1.)
final = [*mission.route_target, 0.]
mission.goal = final
mission.retire_local_goal(None, failed=True)
assert mission.goal == final
+66
View File
@@ -0,0 +1,66 @@
"""Small synthetic geometry: no scene names, memorized turns or manual paths."""
import importlib.util
from pathlib import Path
import sys
import numpy as np
import pytest
pytest.importorskip('scipy')
ADAPTER=Path(__file__).parents[1]/'simulation/ai-polygon'
sys.path.insert(0,str(ADAPTER))
from scene_route_field import ground_envelope, route_graph
from k1link.simulation.ai_polygon.route_graph import build_route
def street(*,car=False,gap=False):
x,y=np.meshgrid(np.arange(0,24.01,.25),np.arange(-4,4.01,.25),indexing='ij')
vertices=np.column_stack([x.ravel(),y.ravel(),np.zeros(x.size)])
n=y.shape[1]
faces=[]
for i in range(x.shape[0]-1):
for j in range(n-1):
a=i*n+j;b=a+n
if (car and 9<=x[i,j]<13 and -1<=y[i,j]<1) or (gap and 9<=x[i,j]<13):
continue
faces.extend([[a,b,a+1],[a+1,b,b+1]])
if car:
roof=vertices.copy();roof[:,2]=1.5
rows=np.argwhere((x>=9)&(x<13)&(y>=-1)&(y<1))
roof_faces=[]
for i,j in rows:
a=i*n+j;b=a+n
roof_faces.extend([[a,b,a+1],[a+1,b,b+1]])
faces+= (np.asarray(roof_faces)+len(vertices)).tolist()
vertices=np.concatenate([vertices,roof])
return vertices,np.array(faces)
def test_small_enclosed_occlusion_does_not_sculpt_global_directions():
base=ground_envelope(*street(),[1,0,0])
occupied=ground_envelope(*street(car=True),[1,0,0])
assert np.array_equal(base[2],occupied[2])
assert not base[3].any() and occupied[3].any()
source=dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64)
positions=[[1.,0.,0.],[22.,0.,0.]]
def route(field):
graph=route_graph(*field,positions,source,'c'*64)
return build_route(dict(routing=graph,mission={'route_xy':[[22.,0.]]},robot={'geometry':{'length_m':1.,'width_m':1.}},sha256='d'*64))['legs']
assert route(base)==route(occupied)
def test_open_gap_is_not_filled_to_make_a_successful_route():
field=ground_envelope(*street(gap=True),[1,0,0])
origin,height,envelope,unknown=field
far=np.floor((np.array([20,0])-origin)/.5).astype(int)
assert not envelope[tuple(far)] and not unknown[tuple(far)]
with pytest.raises(ValueError,match='Endpoint'):
route_graph(*field,[[1.,0.,0.],[22.,0.,0.]],
dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64)
def test_goal_on_another_height_layer_does_not_attach_to_street():
field=ground_envelope(*street(),[1,0,0])
with pytest.raises(ValueError,match='Endpoint'):
route_graph(*field,[[1.,0.,0.],[22.,0.,2.]],
dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64)
+26
View File
@@ -0,0 +1,26 @@
"""Disk exhaustion must fail before conversion, not corrupt a published cache."""
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import pytest
path=Path(__file__).parents[1]/'simulation/ai-polygon/gaussian_cache.py'
spec=importlib.util.spec_from_file_location('storage_under_test',path)
cache=importlib.util.module_from_spec(spec);spec.loader.exec_module(cache)
def test_disk_budget_precedes_conversion_and_verified_reuse(tmp_path,monkeypatch):
source=tmp_path/'scene.ply';source.write_bytes(b'source')
recipe=dict(reader='reader',writer='writer',runtime='runtime',output_schema='schema')
calls=[]
def convert(source,output):
calls.append(source);output.write_bytes(b'verified-usd')
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=0))
with pytest.raises(RuntimeError,match='Недостаточно места'):
cache.prepare_gaussian(source,convert,recipe)
assert not calls and not list(tmp_path.rglob('receipt.json'))
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=10*1024**3))
path,receipt=cache.prepare_gaussian(source,convert,recipe)
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=0))
assert cache.prepare_gaussian(source,convert,recipe)==(path,receipt)
assert len(calls)==1 and path.read_bytes()==b'verified-usd'
+24
View File
@@ -0,0 +1,24 @@
"""Curved visual context must retain whole original Gaussian records."""
import importlib.util
from pathlib import Path
import numpy as np
path=Path(__file__).parents[1]/'simulation/ai-polygon/route_region.py'
spec=importlib.util.spec_from_file_location('region_under_test',path)
region=importlib.util.module_from_spec(spec);spec.loader.exec_module(region)
def test_curved_region_preserves_context_and_every_attribute(tmp_path):
points=np.array([[0,7,0,10,20],[10,8,1.99,11,21],[20,9,10,12,22],
[0,10,20,13,23],[10,11,10,14,24]],dtype='<f4')
header=('ply\nformat binary_little_endian 1.0\nelement vertex 5\n'
'property float x\nproperty float y\nproperty float z\n'
'property float f_rest_0\nproperty float opacity\nend_header\n').encode()
source=tmp_path/'in.ply';source.write_bytes(header+points.tobytes());output=tmp_path/'out.ply'
receipt=region.select_region(source,output,[[0,0],[20,0],[20,20]],radius=2,chunk=2)
raw=output.read_bytes();end=raw.index(b'end_header\n')+len(b'end_header\n')
assert raw[end:]==points[:3].tobytes()
assert b'element vertex 00000000000000000003\n' in raw[:end]
assert receipt['retained_count']==3 and receipt['source_count']==5
assert receipt['all_attributes_preserved'] and not receipt['decimated']
assert source.read_bytes()==header+points.tobytes()