feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
import {Vector3} from 'three';
|
||||
|
||||
function moduleUrl(url){
|
||||
const code=ts.transpileModule(readFileSync(url,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
|
||||
.replace(/from "([^"]+)"/g,(_,name)=>`from "${name.startsWith('.')?moduleUrl(new URL(name+'.ts',url)):import.meta.resolve(name)}"`);
|
||||
return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`;
|
||||
}
|
||||
const {EditorCamera}=await import(moduleUrl(new URL('../src/components/simulation/EditorCamera.ts',import.meta.url)));
|
||||
class Surface extends EventTarget {
|
||||
captures=new Set();clientWidth=1000;clientHeight=600;
|
||||
closest(){return null;}focus(){}
|
||||
getBoundingClientRect(){return {left:0,top:0,width:this.clientWidth,height:this.clientHeight};}
|
||||
setPointerCapture(id){this.captures.add(id);}hasPointerCapture(id){return this.captures.has(id);}
|
||||
releasePointerCapture(id){this.captures.delete(id);}
|
||||
}
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
function fixture(){
|
||||
globalThis.window=new EventTarget();globalThis.document={activeElement:null};
|
||||
const surface=new Surface(),c=new EditorCamera(surface,surface);c.resize(1000,600);c.home([0,0,0]);
|
||||
const point=new Vector3(2,0,-1),screen=point.clone().project(c.camera);
|
||||
const x=(screen.x+1)*500,y=(1-screen.y)*300;
|
||||
function event(type,props={}){const e=new Event(type,{cancelable:true});Object.assign(e,{pointerId:1,button:0,clientX:x,clientY:y,...props});surface.dispatchEvent(e);return e;}
|
||||
return {surface,c,point,screen,x,y,event};
|
||||
}
|
||||
test('Gaussian depth supplies off-centre orbit pivot without a collision mesh; buffered motion preserves projection',async()=>{
|
||||
const f=fixture();let resolve;f.c.pickSurface=()=>new Promise(r=>resolve=r);
|
||||
const before=f.c.camera.position.clone();f.event('pointerdown');f.event('pointermove',{clientX:f.x+40,clientY:f.y+20});
|
||||
assert.ok(f.c.camera.position.equals(before));assert.equal(f.c.rotationCenter,null);
|
||||
resolve(f.point.toArray());await tick();
|
||||
assert.ok(f.c.rotationCenter.distanceTo(f.point)<1e-10);
|
||||
assert.ok(f.point.clone().project(f.c.camera).distanceTo(f.screen)<1e-10);
|
||||
assert.ok(f.c.camera.position.distanceTo(before)>.1);
|
||||
f.c.dispose();
|
||||
});
|
||||
test('released and superseded async picks cannot move the camera or replace the next pivot',async()=>{
|
||||
const f=fixture(),pending=[];f.c.pickSurface=()=>new Promise(r=>pending.push(r));
|
||||
f.event('pointerdown');f.event('pointermove',{clientX:f.x+20});f.event('pointerup');
|
||||
const before=f.c.camera.position.clone();pending[0]([99,99,99]);await tick();assert.ok(f.c.camera.position.equals(before));
|
||||
f.event('pointerdown');f.event('pointerdown',{pointerId:2});pending[1]([99,99,99]);await tick();
|
||||
assert.equal(f.c.rotationCenter,null);pending[2](f.point.toArray());await tick();
|
||||
assert.ok(f.c.rotationCenter.distanceTo(f.point)<1e-10);f.c.dispose();
|
||||
});
|
||||
test('view, resize, layer and mode changes invalidate in-flight surface picks',async()=>{
|
||||
for(const cancel of [c=>c.home([1,0,1]),c=>c.top([[0,0,0],[10,0,10]]),c=>c.resize(800,600),c=>c.invalidateSurface(),c=>c.setAddMode(true),c=>c.setNavigation(false)]){
|
||||
const f=fixture();let resolve;f.c.pickSurface=()=>new Promise(r=>resolve=r);
|
||||
f.event('pointerdown');f.event('pointermove',{clientX:f.x+20});cancel(f.c);
|
||||
const before=f.c.camera.position.clone();resolve(f.point.toArray());await tick();
|
||||
assert.ok(f.c.camera.position.equals(before));assert.equal(f.c.rotationCenter,null);assert.equal(f.surface.captures.size,0);f.c.dispose();
|
||||
}
|
||||
});
|
||||
test('empty sky fallback remains on clicked ray instead of camera centre',async()=>{
|
||||
const f=fixture();f.c.pickSurface=async()=>null;f.event('pointerdown');await tick();
|
||||
const projected=f.c.rotationCenter.clone().project(f.c.camera);
|
||||
assert.ok(Math.abs(projected.x-f.screen.x)<1e-10);assert.ok(Math.abs(projected.y-f.screen.y)<1e-10);
|
||||
f.c.dispose();
|
||||
});
|
||||
test('waypoint add mode does not start orbit or visual picking',()=>{
|
||||
const f=fixture();let picks=0;f.c.pickSurface=async()=>{picks++;return [0,0,0];};f.c.setAddMode(true);f.event('pointerdown');
|
||||
assert.equal(picks,0);assert.equal(f.c.rotationCenter,null);f.c.dispose();
|
||||
});
|
||||
|
||||
test('semantic editing reserves bare left drag for tools and Ctrl-left drag for orbit',()=>{
|
||||
const f=fixture();f.c.semanticSelection=true;
|
||||
const before=f.c.camera.position.clone();
|
||||
f.event('pointerdown');f.event('pointermove',{clientX:f.x+40});f.event('pointerup');
|
||||
assert.ok(f.c.camera.position.equals(before));assert.equal(f.surface.captures.size,0);
|
||||
const down=f.event('pointerdown',{ctrlKey:true});
|
||||
// Modifier changes mid-gesture must not change camera ownership.
|
||||
f.event('pointermove',{clientX:f.x+40,ctrlKey:false});
|
||||
assert.equal(down.defaultPrevented,true);assert.ok(f.c.camera.position.distanceTo(before)>.1);
|
||||
f.event('pointerup');const ended=f.c.camera.position.clone();
|
||||
f.event('pointermove',{clientX:f.x+80});assert.ok(f.c.camera.position.equals(ended));
|
||||
f.c.dispose();
|
||||
});
|
||||
test('Ctrl-click mapped to the secondary button on macOS still orbits instead of panning',()=>{
|
||||
const f=fixture();f.c.semanticSelection=true;
|
||||
const orientation=f.c.camera.quaternion.clone();
|
||||
f.event('pointerdown',{ctrlKey:true,button:2});f.event('pointermove',{clientX:f.x+40});
|
||||
assert.ok(f.c.camera.quaternion.angleTo(orientation)>.01);assert.ok(f.c.rotationCenter);
|
||||
f.event('pointercancel');assert.equal(f.surface.captures.size,0);f.c.dispose();
|
||||
});
|
||||
test('Ctrl-orbit accepts a semantic handle or pivot, but never an unrelated toolbar control',()=>{
|
||||
for(const allowed of [false,true]){
|
||||
const f=fixture();f.c.semanticSelection=true;
|
||||
const e=new Event('pointerdown',{cancelable:true});
|
||||
Object.assign(e,{pointerId:1,button:0,ctrlKey:true,clientX:f.x,clientY:f.y});
|
||||
const target={closest(selector){return allowed&&selector.includes('data-semantic-')?this:null;}};
|
||||
Object.defineProperty(e,'target',{value:target});
|
||||
const before=f.c.camera.position.clone();f.surface.dispatchEvent(e);f.event('pointermove',{clientX:f.x+40});
|
||||
assert.equal(f.c.camera.position.equals(before),!allowed);f.c.dispose();
|
||||
}
|
||||
});
|
||||
test('leaving semantic editing restores unmodified left-drag orbit; right-drag pan is preserved',()=>{
|
||||
const f=fixture();f.c.semanticSelection=true;const before=f.c.camera.position.clone(),q=f.c.camera.quaternion.clone();
|
||||
f.event('pointerdown',{button:2});f.event('pointermove',{clientX:f.x+40});f.event('pointerup');
|
||||
assert.ok(f.c.camera.position.distanceTo(before)>.1);assert.ok(f.c.camera.quaternion.equals(q));
|
||||
f.c.semanticSelection=false;f.event('pointerdown');f.event('pointermove',{clientX:f.x+40});
|
||||
assert.ok(f.c.camera.quaternion.angleTo(q)>.01);f.c.dispose();
|
||||
});
|
||||
|
||||
const {cameraRay,screenSpan}=await import(moduleUrl(new URL('../src/core/simulation/editorProjection.ts',import.meta.url)));
|
||||
test('orthographic projection preserves focal-plane framing; depth never changes line width',()=>{
|
||||
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);
|
||||
const samples=[new Vector3(0,0,0),new Vector3(2,0,3)],before=samples.map(p=>p.clone().project(f.c.camera));
|
||||
f.c.setProjection('orthographic');assert.equal(f.c.camera.isOrthographicCamera,true);
|
||||
samples.forEach((p,i)=>{const q=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-before[i].x,q.y-before[i].y)<1e-8);});
|
||||
const q=samples[1].clone().project(f.c.camera),above=samples[1].clone().add(new Vector3(0,10,0)).project(f.c.camera);
|
||||
assert.ok(Math.hypot(q.x-above.x,q.y-above.y)<1e-8);
|
||||
f.c.setProjection('perspective');samples.forEach((p,i)=>{const q=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-before[i].x,q.y-before[i].y)<1e-8);});f.c.dispose();
|
||||
});
|
||||
test('orthographic cursor zoom keeps anchor fixed, pan is metric, resize preserves shape',()=>{
|
||||
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection('orthographic');
|
||||
const p=new Vector3(4,0,2),q=p.clone().project(f.c.camera);f.c.pick=()=>p.toArray();
|
||||
const span=screenSpan(f.c.camera,5);
|
||||
f.event('wheel',{clientX:(q.x+1)*500,clientY:(1-q.y)*300,deltaY:-120,deltaMode:0});
|
||||
const after=p.clone().project(f.c.camera);assert.ok(Math.hypot(q.x-after.x,q.y-after.y)<1e-8);assert.ok(screenSpan(f.c.camera,5)<span);
|
||||
f.c.semanticSelection=true;f.event('wheel',{deltaX:40,deltaY:20});
|
||||
const moved=p.clone().project(f.c.camera);assert.ok(Math.abs((moved.x-after.x)*500-40)<1e-8);assert.ok(Math.abs((moved.y-after.y)*300+20)<1e-8);
|
||||
const oldSpan=screenSpan(f.c.camera,5);f.c.resize(600,600);assert.equal(screenSpan(f.c.camera,5),oldSpan);
|
||||
assert.equal(f.c.camera.right-f.c.camera.left,f.c.camera.top-f.c.camera.bottom);f.c.dispose();
|
||||
});
|
||||
test('all 26 cube directions preserve focus, orthographic scale, and matching parallel pick rays',()=>{
|
||||
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection('orthographic');const span=screenSpan(f.c.camera,5);
|
||||
for(const x of [-1,0,1])for(const y of [-1,0,1])for(const z of [-1,0,1]){
|
||||
if(!x&&!y&&!z)continue;f.c.view([x,y,z]);
|
||||
const expected=new Vector3(x,y,z).normalize().negate(),direction=f.c.camera.getWorldDirection(new Vector3());assert.ok(direction.distanceTo(expected)<1e-8);
|
||||
const a=cameraRay(f.c.camera,.3,.4),b=cameraRay(f.c.camera,.8,.6);assert.ok(a.direction.distanceTo(b.direction)<1e-8);assert.ok(a.origin.distanceTo(b.origin)>1);
|
||||
assert.equal(screenSpan(f.c.camera,5),span);assert.ok(new Vector3().project(f.c.camera).length()<1.01);
|
||||
}
|
||||
f.c.dispose();
|
||||
});
|
||||
|
||||
test('camera snapshot restores exact pose, orthographic scale and orbit anchor after reopening',()=>{
|
||||
for(const projection of ['orthographic','perspective']){
|
||||
const f=fixture();f.c.top([[-20,0,-10],[20,0,10]]);f.c.setProjection(projection);f.c.view([1,1,1]);
|
||||
const stored={...f.c.snapshot(),clip:[null,77]};f.c.dispose();
|
||||
const next=fixture();next.c.restore(JSON.parse(JSON.stringify(stored)));
|
||||
assert.deepEqual(next.c.snapshot(),{position:stored.position,quaternion:stored.quaternion,anchor:stored.anchor,projection,span:stored.span});
|
||||
const old=next.c.snapshot();next.c.resize(1400,800);
|
||||
assert.deepEqual(next.c.snapshot(),old);next.c.dispose();
|
||||
}
|
||||
});
|
||||
@@ -3,10 +3,12 @@ import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
import {PerspectiveCamera,Vector3} from 'three';
|
||||
async function source(name){
|
||||
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace('from "three"',`from "${import.meta.resolve('three')}"`);
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
function moduleUrl(url){
|
||||
const code=ts.transpileModule(readFileSync(url,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
|
||||
.replace(/from "([^"]+)"/g,(_,name)=>`from "${name.startsWith('.')?moduleUrl(new URL(name+'.ts',url)):import.meta.resolve(name)}"`);
|
||||
return `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`;
|
||||
}
|
||||
async function source(name){return import(moduleUrl(new URL(`../src/core/simulation/${name}.ts`,import.meta.url)));}
|
||||
const {panCamera,orbitCamera,navigationDepth}=await source('editorNavigation');
|
||||
const {editWaypoints,waypointEditing,waypointShortcut}=await source('waypointEditing');
|
||||
const {streamRecovery}=await source('streamRecovery');
|
||||
@@ -82,3 +84,11 @@ test('catalog discovery of a run cannot claim an idle or historical viewer',()=>
|
||||
assert.equal(viewedAiRun(catalog,'forest','new'),live);
|
||||
assert.equal(viewedAiRun(catalog,'bamboo','new'),undefined);
|
||||
});
|
||||
|
||||
test('cube preferences migrate without changing older settings and validate saved presentation',()=>{
|
||||
const p=normalizePlannerPreferences({pivot:{pixels:125},cube:{size:500,face:'red',opacity:-1,edgeOpacity:-2,text:'#123456'}});
|
||||
assert.equal(p.pivot.pixels,125);assert.equal(p.cube.size,160);assert.equal(p.cube.face,'#292929');assert.equal(p.cube.opacity,.2);assert.equal(p.cube.text,'#123456');
|
||||
assert.equal(normalizePlannerPreferences({}).cube.size,66);
|
||||
assert.equal(p.cube.edgeOpacity,0);assert.equal(normalizePlannerPreferences({}).cube.edgeOpacity,1);
|
||||
assert.deepEqual(normalizePlannerPreferences(JSON.parse(JSON.stringify(p))),p);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import {PerspectiveCamera,Vector3} from 'three';
|
||||
import {Camera,GraphNode,ASPECT_MANUAL} from 'playcanvas';
|
||||
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
|
||||
function moduleUrl(p){return url(ts.transpileModule(readFileSync(p,'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText.replace(/from "([^"]+)"/g,(_,n)=>`from "${n.startsWith('.')?moduleUrl(new URL(n+'.ts',p)):import.meta.resolve(n)}"`));}
|
||||
const projection=moduleUrl(new URL('../src/core/simulation/editorProjection.ts',import.meta.url));
|
||||
const coordinates=moduleUrl(new URL('../src/core/simulation/aiEditorCoordinates.ts',import.meta.url));
|
||||
const drag=moduleUrl(new URL('../src/core/simulation/waypointDrag.ts',import.meta.url));
|
||||
const {switchProjection}=await import(projection),{toEditor}=await import(coordinates);
|
||||
// Execute the real runtime methods against the real PlayCanvas camera math, without a GPU/app.
|
||||
const source=readFileSync(new URL('../src/components/simulation/AiEditorRuntime.ts',import.meta.url),'utf8');
|
||||
const ast=ts.createSourceFile('runtime.ts',source,ts.ScriptTarget.Latest,true);
|
||||
const cls=ast.statements.find(s=>ts.isClassDeclaration(s));
|
||||
const names=new Set(['syncCamera','project','projectSemantic','moveSemantic','semanticGizmo','semanticSegmentParameter']);
|
||||
const methods=cls.members.filter(m=>names.has(m.name?.getText(ast))).map(m=>m.getText(ast)).join('\n');
|
||||
const actual=`import {Vec3,PROJECTION_ORTHOGRAPHIC,PROJECTION_PERSPECTIVE} from "${import.meta.resolve('playcanvas')}";import {isOrthographic,screenSpan} from "${projection}";import {toEditor,toMission} from "${coordinates}";import {dragWaypoint} from "${drag}";export class Runtime {${methods}}`;
|
||||
const {Runtime}=await import(url(ts.transpileModule(actual,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText));
|
||||
function fixture(mode){
|
||||
let c=new PerspectiveCamera(60,1.5,.05,3000);c.position.set(7,12,20);c.lookAt(0,0,0);c.updateMatrixWorld();
|
||||
c=switchProjection(c,mode,1.5,c.position.length());
|
||||
const pc=new Camera(),node=new GraphNode();pc.node=node;pc.aspectRatioMode=ASPECT_MANUAL;pc.aspectRatio=1.5;pc.fov=60;pc.nearClip=.05;pc.farClip=3000;
|
||||
node.camera={get projection(){return pc.projection;},set projection(v){pc.projection=v;},get orthoHeight(){return pc.orthoHeight;},set orthoHeight(v){pc.orthoHeight=v;},worldToScreen:p=>pc.worldToScreen(p,900,600),screenToWorld:(x,y,z)=>pc.screenToWorld(x,y,z,900,600)};
|
||||
const r=new Runtime();Object.assign(r,{camera:node,controls:{camera:c},canvas:{clientWidth:900,clientHeight:600},clip:Infinity,clipFloor:-Infinity,preferences:{pivot:{pixels:100}}});r.syncCamera();return {r,c,pc};
|
||||
}
|
||||
for(const mode of ['orthographic','perspective']){
|
||||
test(`${mode}: render and overlay projection agree; axis/plane dragging lands under cursor`,()=>{
|
||||
const {r,c}=fixture(mode),a=[1,2,0];
|
||||
for(const [axis,b] of [['x',[3,2,0]],['y',[1,4,0]],['z',[1,2,3]],['xy',[3,4,0]],['xz',[3,2,3]],['yz',[1,4,3]]]){
|
||||
const pixel=r.projectSemantic(b),q=new Vector3(...toEditor(b)).project(c);
|
||||
assert.ok(Math.abs(pixel[0]-(q.x+1)/2)<1e-6);assert.ok(Math.abs(pixel[1]-(1-q.y)/2)<1e-6);
|
||||
const moved=r.moveSemantic(a,...pixel,axis);assert.ok(moved);moved.forEach((v,k)=>assert.ok(Math.abs(v-b[k])<2e-4,`${axis} ${v} != ${b[k]}`));
|
||||
}
|
||||
});
|
||||
test(`${mode}: inserted point on a sloping segment matches the pixel interpolation`,()=>{
|
||||
const {r}=fixture(mode),a=[-3,-2,0],b=[4,5,4],pa=r.projectSemantic(a),pb=r.projectSemantic(b);
|
||||
for(const u of [.1,.4,.8]){const t=r.semanticSegmentParameter(a,b,u),p=r.projectSemantic(a.map((v,k)=>v+(b[k]-v)*t));p.forEach((v,k)=>assert.ok(Math.abs(v-(pa[k]+(pb[k]-pa[k])*u))<1e-6));}
|
||||
});
|
||||
}
|
||||
test('orthographic gizmo keeps its pixel size at different depths; clipping still applies',()=>{
|
||||
const {r}=fixture('orthographic');assert.equal(r.semanticGizmo([0,0,0]).length,r.semanticGizmo([0,0,10]).length);
|
||||
r.clip=2;r.clipFloor=-1;assert.equal(r.projectSemantic([0,0,3]),null);assert.equal(r.projectSemantic([0,0,-2]),null);
|
||||
const pixel=r.projectSemantic([1,2,0]);assert.ok(r.moveSemantic([1,2,0],...pixel,'xy'));
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,Terrain;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({EditorTerrain:Terrain}=await server.ssrLoadModule('/src/components/simulation/EditorTerrain.ts'));
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
test('picking and ground snapping cannot select surfaces hidden by either plane',()=>{
|
||||
const terrain=Object.create(Terrain.prototype);
|
||||
const hit=(y,distance,normal=1)=>({point:{y},distance,face:{normal:{y:normal}}});
|
||||
const lower=hit(-3,1), middle=hit(2,3), upper=hit(9,2), wall=hit(1,1.5,0);
|
||||
terrain.trees=[{raycast:()=>[lower,middle,upper,wall]}];terrain.bounds={max:{y:10}};
|
||||
assert.equal(terrain.pick([0,20,0],[0,-1,0],5,0),middle.point);
|
||||
assert.equal(terrain.pickSurface([0,20,0],[0,-1,0],5,false,0),wall.point);
|
||||
assert.equal(terrain.ground(0,0,-3,5,0),middle.point);
|
||||
assert.equal(terrain.pick([0,20,0],[0,-1,0],1,0),null);
|
||||
assert.equal(terrain.pick([0,20,0],[0,-1,0]),lower.point);
|
||||
assert.equal(terrain.ground(0,0,-3),lower.point);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const built=await build({entryPoints:[new URL('../src/core/simulation/infrastructureAnalysis.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'analysis-fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onResolve({filter:/^\.\/urbanMap$/},()=>({path:'map',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},args=>({contents:args.path==='react'?`
|
||||
export const useRef=v=>({current:v});
|
||||
export const useState=v=>{const index=globalThis.analysisFixture.index++;return [index===0?globalThis.analysisFixture.seed:v,value=>globalThis.analysisFixture.writes.push({index,value})];};
|
||||
export const useEffect=f=>globalThis.analysisFixture.effects.push(f);
|
||||
`:`export const loadUrbanMap=async()=>{throw new Error('Unexpected stale map load');};`}));
|
||||
}}]});
|
||||
const {useInfrastructureAnalysis,analysisProgressLabel}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64'));
|
||||
const flush=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
|
||||
const response=value=>({ok:true,json:async()=>value});
|
||||
const queued={key:'a'.repeat(64),status:'queued',phase:'queued',completed:0,total:0,error:null};
|
||||
async function fixture(run,seed=null){
|
||||
const original=Object.fromEntries(['analysisFixture','fetch','setTimeout','clearTimeout'].map(k=>[k,globalThis[k]]));
|
||||
const state={index:0,seed,writes:[],effects:[]},calls=[],timers=[],get=deferred(),post=deferred();
|
||||
globalThis.analysisFixture=state;
|
||||
globalThis.setTimeout=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearTimeout=()=>{};
|
||||
globalThis.fetch=async(url,init={})=>{calls.push({url,init});return init.method==='POST'?post.promise:get.promise;};
|
||||
const hook=useInfrastructureAnalysis('fixture','b'.repeat(64),()=>{throw new Error('Unexpected stale map callback');});
|
||||
const cleanups=state.effects.map(f=>f());let cleaned=false;
|
||||
const clean=()=>{if(!cleaned){cleaned=true;cleanups.forEach(f=>f?.());}};
|
||||
try{await run({hook,calls,get,post,state,timers,clean});}
|
||||
finally{clean();await flush();for(const [key,value]of Object.entries(original)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
|
||||
}
|
||||
test('twenty immediate calculation clicks make one request before React rerenders',async()=>fixture(async f=>{
|
||||
const attempts=Array.from({length:20},()=>f.hook.start(true));
|
||||
assert.equal(f.calls.filter(c=>c.init.method==='POST').length,1);
|
||||
f.post.resolve(response(queued));await Promise.all(attempts);f.get.resolve(response(null));await flush();
|
||||
assert.equal(f.state.writes.filter(w=>w.index===0).at(-1).value.key,queued.key);
|
||||
}));
|
||||
test('a poll predating calculation cannot replace the acknowledged queued job',async()=>fixture(async f=>{
|
||||
const starting=f.hook.start(true);f.post.resolve(response(queued));await starting;
|
||||
f.get.resolve(response({...queued,status:'ready'}));await flush();
|
||||
assert.deepEqual(f.state.writes.filter(w=>w.index===0).at(-1).value,queued);
|
||||
}));
|
||||
test('polling pauses during cancellation and late replies cannot undo unmount',async()=>fixture(async f=>{
|
||||
f.get.resolve(response({...queued,status:'running'}));await flush();
|
||||
const cancelling=f.hook.cancel();const before=f.calls.length;
|
||||
await f.timers.at(-1).f();assert.equal(f.calls.length,before);
|
||||
assert.match(f.calls.at(-1).url,new RegExp('/'+queued.key+'/cancel$'));
|
||||
f.clean();const writes=f.state.writes.length;
|
||||
f.post.resolve(response({...queued,status:'cancelled'}));await cancelling;await flush();
|
||||
assert.equal(f.state.writes.length,writes);
|
||||
}, {...queued,status:'running'}));
|
||||
test('retry after an unknown network outcome keeps the same request identity',async()=>fixture(async f=>{
|
||||
f.post.resolve({ok:false,json:async()=>({detail:'Try again'})});
|
||||
await f.hook.start(true);await f.hook.start(true);
|
||||
const bodies=f.calls.filter(c=>c.init.method==='POST').map(c=>JSON.parse(c.init.body));
|
||||
assert.equal(bodies.length,2);assert.equal(bodies[0].request_id,bodies[1].request_id);
|
||||
f.get.resolve(response(null));await flush();
|
||||
}));
|
||||
|
||||
test('an observed terminal generation acknowledges a lost response before the next retry',async()=>fixture(async f=>{
|
||||
f.post.resolve({ok:false,json:async()=>({detail:'Response lost'})});
|
||||
await f.hook.start(true);
|
||||
const first=JSON.parse(f.calls.find(c=>c.init.method==='POST').init.body).request_id;
|
||||
f.get.resolve(response({...queued,status:'failed',request_id:first}));await flush();
|
||||
await f.timers.at(-1).f();await flush();
|
||||
await f.hook.start(true);
|
||||
const second=JSON.parse(f.calls.filter(c=>c.init.method==='POST').at(-1).init.body).request_id;
|
||||
assert.notEqual(second,first,'a new attempt must not return the old terminal generation');
|
||||
}));
|
||||
|
||||
test('stage counts are explicit and lost connection never retains an ETA',()=>{
|
||||
const job={...queued,status:'running',progress:{label:'Построение видов сцены',stage:2,stages:90,eta_seconds:600,stale:false}};
|
||||
assert.equal(analysisProgressLabel(job),'Построение видов сцены · этап 2 из 90 · ≈ 10 мин осталось');
|
||||
assert.equal(analysisProgressLabel({...job,progress:{...job.progress,stale:true,eta_seconds:null}}),'Связь с расчётом потеряна · этап 2 из 90');
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const source=readFileSync(new URL('../src/components/simulation/localScene.ts',import.meta.url),'utf8');
|
||||
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText
|
||||
.replace('from "playcanvas"',`from "${import.meta.resolve('playcanvas')}"`)
|
||||
.replace(/import \{ editorAssetUrl \} from [^;]+;/,'const editorAssetUrl=(key,name)=>`/cache/${key}/${name}`;');
|
||||
const {localScene}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
test('visual-only project never substitutes a nonexistent editor collider URL',()=>{
|
||||
const cache={key:'fixture',world:{world_id:'scan'},local_scene:{visual_url:'/scan/lod-meta.json',
|
||||
collision_url:null,visual_rotation:[180,0,0],collision_rotation:[0,0,0]}};
|
||||
assert.deepEqual(localScene(cache).collision,{meshUrl:null,available:false});
|
||||
assert.equal(localScene(cache).visual.streamedSogUrl,'/scan/lod-meta.json');
|
||||
cache.local_scene.collision_url='/scan/collision.glb';
|
||||
assert.deepEqual(localScene(cache).collision,{meshUrl:'/scan/collision.glb',available:true});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/simulation/plannerActions.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {plannerActions}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const points=[{id:'start',position:[0,0,0]},{id:'finish',position:[3,1,0]}];
|
||||
const route={sha256:'route-v1'};
|
||||
const plan={points,editor_cache_key:'scene-v1',robot_sha256:'robot-v1',prepared_route:route};
|
||||
const input={draft:{cache:{key:'scene-v1'},points},robot:{sha256:'robot-v1'},plan:undefined,routeRequired:true,
|
||||
route:null,routeKey:null,busy:false,runtimeAvailable:true,inferenceReady:true,activeRun:false};
|
||||
const state=changes=>plannerActions({...input,...changes});
|
||||
const none={save:false,prepare:false,launch:false};
|
||||
test('no draft, robot, start or finish means no route actions, even for legacy scenes',()=>{
|
||||
assert.deepEqual(state({draft:null}),none);
|
||||
assert.deepEqual(state({robot:undefined}),none);
|
||||
for(const points of [[],input.draft.points.slice(0,1)])for(const routeRequired of [true,false])
|
||||
assert.deepEqual(state({draft:{...input.draft,points},routeRequired}),none);
|
||||
});
|
||||
test('two points offer calculation; an admitted route offers save and launch',()=>{
|
||||
assert.deepEqual(state({}),{save:false,prepare:true,launch:false});
|
||||
assert.deepEqual(state({route,routeKey:'key'}),{save:true,prepare:false,launch:true});
|
||||
assert.equal(state({route,routeKey:null}).launch,false);
|
||||
});
|
||||
test('loading, saving and undoing to the saved task hide save without hiding launch',()=>{
|
||||
const saved={route,routeKey:'key',plan};
|
||||
assert.deepEqual(state(saved),{save:false,prepare:false,launch:true});
|
||||
const changed=structuredClone(points);changed[1].position[2]=.2;
|
||||
assert.deepEqual(state({...saved,draft:{...input.draft,points:changed},route:null,routeKey:null}),{save:false,prepare:true,launch:false});
|
||||
assert.equal(state(saved).save,false);
|
||||
assert.equal(state({...saved,route:{sha256:'route-v2'}}).save,true);
|
||||
});
|
||||
test('busy commands hide other actions; offline or occupied Worker prevents launch',()=>{
|
||||
assert.deepEqual(state({route,routeKey:'key',busy:true}),none);
|
||||
assert.deepEqual(state({runtimeAvailable:false}),none);
|
||||
for(const condition of [{runtimeAvailable:false},{inferenceReady:false},{activeRun:true}])
|
||||
assert.deepEqual(state({route,routeKey:'key',...condition}),{save:true,prepare:false,launch:false});
|
||||
});
|
||||
@@ -49,3 +49,30 @@ test('world-size centroid preference migrates to independent pixel size; emissio
|
||||
assert.ok(Math.abs(pixels-14)<1e-8);
|
||||
}
|
||||
});
|
||||
|
||||
test('toolbar preferences migrate old storage and preserve all four placements and valid sizes',()=>{
|
||||
assert.deepEqual(normalizePlannerPreferences({pivot:{}}).toolbar,DEFAULT_PLANNER_PREFERENCES.toolbar);
|
||||
for(const placement of ['left','right','top','bottom']){
|
||||
const p=normalizePlannerPreferences({toolbar:{placement,minSize:40,maxSize:20,lensCount:4,hideDelay:500,gap:3,autoHide:false}}).toolbar;
|
||||
assert.equal(p.placement,placement);assert.equal(p.maxSize,40);assert.equal(p.lensCount,5);assert.equal(p.hideDelay,500);assert.equal(p.autoHide,false);
|
||||
}
|
||||
const p=normalizePlannerPreferences({toolbar:{placement:'oops',hideDelay:Infinity,minSize:NaN,background:'url(x)'}}).toolbar;
|
||||
assert.deepEqual(p,DEFAULT_PLANNER_PREFERENCES.toolbar);
|
||||
});
|
||||
|
||||
const {normalizeSimulationLayout,DEFAULT_SIMULATION_LAYOUT,normalizeSceneView}=await source('simulationLayout');
|
||||
test('layout keeps global modes/projection/layers while transient editing state cannot enter storage',()=>{
|
||||
for(const mode of ['view','semantic','planning'])for(const projection of ['orthographic','perspective']){
|
||||
const value={...DEFAULT_SIMULATION_LAYOUT,mode,projection,layers:['road_boundary','road_marking'],visible:{model:true,user:true},axis:'xz'};
|
||||
assert.deepEqual(normalizeSimulationLayout(JSON.parse(JSON.stringify(value))),value);
|
||||
}
|
||||
assert.deepEqual(normalizeSimulationLayout({mode:'oops',projection:'oops'}),DEFAULT_SIMULATION_LAYOUT);
|
||||
assert.deepEqual(normalizeSimulationLayout({layers:[]}).layers,[]);
|
||||
assert.deepEqual(normalizeSimulationLayout({layers:['road_boundary','oops','road_boundary'],selection:['unsafe'],operations:[{}]}).layers,['road_boundary']);
|
||||
assert.equal('operations' in normalizeSimulationLayout({operations:[{}]}),false);
|
||||
});
|
||||
test('camera snapshots preserve pose and unbounded slice, and reject malformed storage',()=>{
|
||||
const view={position:[1,2,3],quaternion:[0,0,0,1],anchor:[4,5,6],projection:'orthographic',span:20,clip:[null,500]};
|
||||
assert.deepEqual(normalizeSceneView(JSON.parse(JSON.stringify(view))),view);
|
||||
for(const bad of [{...view,quaternion:[1,1,1,1]},{...view,clip:[10,1]},{...view,span:Infinity},{...view,position:[NaN,0,0]}])assert.equal(normalizeSceneView(bad),null);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/simulation/sceneClip.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {sceneClipBounds,sceneClipValue}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('Gaussian clipping covers visual and collision extents with at least a 500 m ceiling',()=>{
|
||||
assert.deepEqual(sceneClipBounds([-51.4623,210.4],[-30,77.72065000000002]),[-52,500]);
|
||||
assert.deepEqual(sceneClipBounds([-60.3,912.7],null),[-61,913]);
|
||||
assert.deepEqual(sceneClipBounds([5,80],[-75.2,1000.1]),[-76,1001]);
|
||||
});
|
||||
test('native rounded maximum disables clipping and returning to a finite height clips again',()=>{
|
||||
const oldBounds=[-51.4623,77.72065000000002];
|
||||
assert.ok(77.72065 < oldBounds[1]);
|
||||
assert.equal(sceneClipValue(77.72065,oldBounds),Infinity);
|
||||
assert.equal(sceneClipValue(76.4288206,oldBounds),76.4288206);
|
||||
const bounds=sceneClipBounds([-51.4623,210.4],oldBounds);
|
||||
assert.deepEqual([40,500,40,500].map(v=>sceneClipValue(v,bounds)),[40,Infinity,40,Infinity]);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {readFileSync} from "node:fs";
|
||||
import {test} from "node:test";
|
||||
import ts from "typescript";
|
||||
const moduleURL=(s)=>`data:text/javascript;base64,${Buffer.from(ts.transpileModule(s,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText).toString("base64")}`;
|
||||
const read=n=>readFileSync(new URL(`../src/core/simulation/${n}.ts`,import.meta.url),"utf8");
|
||||
const policy=moduleURL(read("semanticFeaturePolicy"));
|
||||
const vector=moduleURL(read("semanticVector").replace('"./semanticFeaturePolicy"',JSON.stringify(policy)));
|
||||
const {regionOperation}=await import(moduleURL(read("semanticArea").replace('"./semanticVector"',JSON.stringify(vector)).replace('"polygon-clipping"',JSON.stringify(import.meta.resolve("polygon-clipping")))));
|
||||
const {curveControlScale,curveControlPoint,moveCurveControl}=await import(moduleURL(read("semanticCurveControls")));
|
||||
const ring=(x,y,w,h,z=2)=>[[x,y,z],[x+w,y,z],[x+w,y+h,z],[x,y+h,z],[x,y,z]];
|
||||
const area={id:"area",properties:{class:"pedestrian_area"},geometry:{type:"Polygon",coordinates:[ring(0,0,10,10),ring(2,2,2,2)]}};
|
||||
const size=r=>Math.abs(r.slice(1).reduce((a,p,i)=>a+r[i][0]*p[1]-p[0]*r[i][1],0)/2);
|
||||
const total=polys=>polys.reduce((s,p)=>s+size(p[0])-p.slice(1).reduce((s,r)=>s+size(r),0),0);
|
||||
test("region fill closes existing holes and cut splits without losing parts or source heights",()=>{
|
||||
const original=JSON.stringify(area);
|
||||
const filled=regionOperation(area,ring(1,1,4,4),"union");assert.equal(total(filled.polygons),100);assert.equal(filled.polygons[0].length,1);
|
||||
const split=regionOperation(area,ring(5,-1,1,12),"difference");assert.equal(split.polygons.length,2);assert.equal(total(split.polygons),86);
|
||||
assert.equal(JSON.stringify(area),original);assert.ok(split.polygons.flat(2).every(p=>p[2]===2));
|
||||
assert.throws(()=>regionOperation(undefined,ring(0,0,1,1),"difference"));
|
||||
assert.equal(total(regionOperation(undefined,ring(0,0,1,1),"union").polygons),1);
|
||||
});
|
||||
test("curve handles remain visible on dense contours without altering physical coordinates; drag has no jump",()=>{
|
||||
const nodes=[0,1,2].map(i=>({point:[i*.03,0,2],incoming:[-.01,0],outgoing:[.01,0]}));
|
||||
const input=JSON.stringify(nodes),project=p=>p.map(v=>v*10),scale=curveControlScale(nodes,1,false,project);
|
||||
const p=curveControlPoint(nodes[1],"outgoing",scale);
|
||||
assert.ok(Math.abs((p[0]-.03)*10-36)<1e-9);assert.equal(JSON.stringify(nodes),input);
|
||||
assert.deepEqual(moveCurveControl(nodes[1].outgoing,[9,8],[9,8],scale),nodes[1].outgoing);
|
||||
const shifted=moveCurveControl(nodes[1].outgoing,[9,8],[10,10],scale);
|
||||
assert.ok(Math.abs((shifted[0]-.01)*scale-1)<1e-9);assert.equal(shifted[1]*scale,2);
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {readFileSync} from "node:fs";
|
||||
import {test} from "node:test";
|
||||
import ts from "typescript";
|
||||
const policyCode=ts.transpileModule(readFileSync(new URL("../src/core/simulation/semanticFeaturePolicy.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const policyUrl=`data:text/javascript;base64,${Buffer.from(policyCode).toString("base64")}`;
|
||||
const policy=s=>s.replaceAll('"./semanticFeaturePolicy"',JSON.stringify(policyUrl));
|
||||
const vectorCode=ts.transpileModule(policy(readFileSync(new URL("../src/core/simulation/semanticVector.ts",import.meta.url),"utf8")),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const vectorUrl=`data:text/javascript;base64,${Buffer.from(vectorCode).toString("base64")}`;
|
||||
const source=readFileSync(new URL("../src/core/simulation/semanticEdits.ts",import.meta.url),"utf8").replace(/import MARKING_TEMPLATES from [^;]+;/, `const MARKING_TEMPLATES=${readFileSync(new URL("../../../src/k1link/simulation/ai_polygon/marking-templates.json",import.meta.url),"utf8")};`);
|
||||
const code=ts.transpileModule(policy(source).replace('from "./semanticVector"',`from "${vectorUrl}"`),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {semanticDraft,commitSemantic,undoSemantic,redoSemantic,segmentHit,semanticOperation}=await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
|
||||
const feature=(id,coordinates)=>({id,properties:{class:"curb",authority:"observation-only",route_permission:"unassigned"},geometry:{type:"LineString",coordinates}});
|
||||
const map={schema_version:"missioncore.urban-map/v3",features:[feature("a",[[0,0,2],[2,0,2],[4,1,2]]),feature("b",[[0,5,2],[4,5,2]])]};
|
||||
const vertex={feature_id:"a",path:0,index:1};
|
||||
test("gesture history restores exact input and redo; no-op has no new revision",()=>{
|
||||
const s=semanticDraft(map);
|
||||
assert.strictEqual(commitSemantic(s,{...vertex,kind:"move",position:[2,0,2]}),s);
|
||||
const moved=commitSemantic(s,{...vertex,kind:"move",position:[2,.2,2]});
|
||||
assert.equal(moved.operations.length,1);
|
||||
assert.strictEqual(moved.map.features[1],map.features[1]);
|
||||
const undone=undoSemantic(moved);
|
||||
assert.strictEqual(undone.map,map);
|
||||
assert.deepEqual(redoSemantic(undone).map,moved.map);
|
||||
assert.deepEqual(map.features[0].geometry.coordinates[1],[2,0,2]);
|
||||
});
|
||||
test("insertion only on chosen segment preserves existing coordinates; no arbitrary height",()=>{
|
||||
const s=commitSemantic(semanticDraft(map),{...vertex,index:0,kind:"insert",t:.25});
|
||||
assert.deepEqual(s.map.features[0].geometry.coordinates,[[0,0,2],[.5,0,2],[2,0,2],[4,1,2]]);
|
||||
assert.throws(()=>commitSemantic(s,{...vertex,kind:"insert",t:2}));
|
||||
assert.throws(()=>commitSemantic(s,{...vertex,kind:"move",position:[2,0,3]}));
|
||||
const restored=commitSemantic(s,{...vertex,kind:"delete"});
|
||||
assert.deepEqual(restored.map.features[0].geometry,map.features[0].geometry);
|
||||
});
|
||||
test("closed polygon first vertex moves and closure follows; minimum geometry retained",()=>{
|
||||
const base={...map,features:[{...map.features[0],geometry:{type:"Polygon",coordinates:[[[0,0,2],[2,0,2],[0,2,2],[0,0,2]]]}}]};
|
||||
const s=commitSemantic(semanticDraft(base),{...vertex,index:0,kind:"move",position:[-.1,0,2]});
|
||||
assert.deepEqual(s.map.features[0].geometry.coordinates[0].at(-1),[-.1,0,2]);
|
||||
assert.throws(()=>commitSemantic(s,{...vertex,kind:"delete"}));
|
||||
});
|
||||
test("hit testing uses CSS coordinates and handles degenerate projected segment",()=>{
|
||||
assert.deepEqual(segmentHit([50,5],[0,0],[100,0]),{t:.5,distance:5});
|
||||
assert.deepEqual(segmentHit([0,3],[0,0],[0,0]),{t:0,distance:3});
|
||||
});
|
||||
|
||||
test("marking placement, group transform and undo preserve rigid shape and height",()=>{
|
||||
const op={kind:"place",feature_id:"user-test-1234567890",template_id:"zebra",position:[3,4,2],surface:"gaussian-visual"};
|
||||
const placed=commitSemantic(semanticDraft(map),op);
|
||||
assert.equal(placed.map.features.length,8);
|
||||
const transform={kind:"transform",feature_id:op.feature_id+"-2",delta:[.5,.25],angle:.5};
|
||||
const moved=commitSemantic(placed,transform);
|
||||
assert.equal(moved.map.features[1],map.features[1]);
|
||||
assert.deepEqual(undoSemantic(moved).map,placed.map);
|
||||
assert.deepEqual(redoSemantic(undoSemantic(moved)).map,moved.map);
|
||||
assert.strictEqual(semanticOperation(placed.map,{...transform,delta:[0,0],angle:0}),placed.map);
|
||||
assert.throws(()=>semanticOperation(placed.map,{kind:"delete",feature_id:op.feature_id,path:0,index:1}));
|
||||
const removed=semanticOperation(moved.map,{kind:"remove",feature_id:op.feature_id});
|
||||
assert.equal(removed.features.filter(f=>f.properties.review_status==="rejected").length,6);
|
||||
});
|
||||
const moduleUrl=`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`;
|
||||
const pickingSource=readFileSync(new URL("../src/core/simulation/semanticPicking.ts",import.meta.url),"utf8").replace('from "./semanticEdits"',`from "${moduleUrl}"`);
|
||||
const pickingCode=ts.transpileModule(pickingSource.replace('from "./semanticVector"',`from "${vectorUrl}"`),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {semanticHits,semanticDrag}=await import(`data:text/javascript;base64,${Buffer.from(pickingCode).toString("base64")}`);
|
||||
test("only selected contour vertices are pickable; rigid markings never expose vertices",()=>{
|
||||
const unselected=semanticHits(map,"curb",[2,0],p=>p,true);
|
||||
assert.ok(unselected.length);assert.ok(unselected.every(h=>!h.point));
|
||||
const hit=semanticHits(map,"curb",[2,0],p=>p,true,["b"]);
|
||||
assert.ok(hit.some(h=>h.vertex.feature_id==="b"&&h.point));
|
||||
assert.ok(hit.filter(h=>h.point).every(h=>h.vertex.feature_id==="b"));
|
||||
const placed=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-test-1234567890",template_id:"letter_A",position:[0,0,0],surface:"gaussian-visual"});
|
||||
assert.ok(semanticHits(placed,"road_marking",[0,0],p=>p,true).length);
|
||||
assert.ok(semanticHits(placed,"road_marking",[0,0],p=>p,true).every(h=>!h.point));
|
||||
});
|
||||
test("pivot grab offset: exact no-op, selected axis only, immutable elevation",()=>{
|
||||
const p=[329.66974637628715,-46.85091895999632,2.5206789941457233],start=[333.1234,-41.9876,2.5];
|
||||
assert.deepEqual(semanticDrag(p,start,start,"xy"),p);
|
||||
assert.deepEqual(semanticDrag(p,start,[start[0]+.5,start[1]+9,800],"x"),[p[0]+.5,p[1],p[2]]);
|
||||
assert.deepEqual(semanticDrag(p,start,[start[0]+9,start[1]+.5,800],"y"),[p[0],p[1]+.5,p[2]]);
|
||||
});
|
||||
|
||||
const {knots,curvePoint}=await import(vectorUrl);
|
||||
test("curves persist control points, exact heights and grouped delete is one undo",()=>{
|
||||
const f={id:"road",properties:{class:"road_boundary"},geometry:{type:"LineString",coordinates:[[0,0,2.1],[2,0,2.2],[4,0,2.3],[6,0,2.4],[8,0,2.5]]}};
|
||||
const base={...map,features:[f]},v={feature_id:"road",path:0,index:1};
|
||||
const curved=commitSemantic(semanticDraft(base),{kind:"curve",...v,incoming:[-.6,-.3],outgoing:[.6,.3]});
|
||||
assert.equal(knots(curved.map.features[0],0).length,5);
|
||||
assert.equal(curved.map.features[0].geometry.coordinates.length,35);
|
||||
assert.equal(knots(curved.map.features[0],0)[1].point[2],2.2);
|
||||
const removed=commitSemantic(curved,{kind:"delete_vertices",vertices:[v,{...v,index:2}]});
|
||||
assert.equal(knots(removed.map.features[0],0).length,3);
|
||||
assert.deepEqual(undoSemantic(removed).map,curved.map);
|
||||
assert.deepEqual(redoSemantic(undoSemantic(removed)).map,removed.map);
|
||||
assert.throws(()=>semanticOperation(base,{kind:"delete_vertices",vertices:[0,1,2,3].map(index=>({...v,index}))}));
|
||||
assert.equal(semanticOperation(base,{kind:"delete_vertices",vertices:[0,1,2,3,4].map(index=>({...v,index}))}).features[0].properties.review_status,"rejected");
|
||||
});
|
||||
test("curve insertion uses De Casteljau; unchanged cubic is geometrically identical",()=>{
|
||||
const base={...map,features:[{id:"r",properties:{class:"road_boundary"},geometry:{type:"LineString",coordinates:[[0,0,1],[4,0,3]]}}]};
|
||||
let c=semanticOperation(base,{kind:"curve",feature_id:"r",path:0,index:0,incoming:[0,0],outgoing:[1,2]});
|
||||
c=semanticOperation(c,{kind:"curve",feature_id:"r",path:0,index:1,incoming:[-1,2],outgoing:[0,0]});
|
||||
const before=knots(c.features[0],0),after=knots(semanticOperation(c,{kind:"insert",feature_id:"r",path:0,index:0,t:.4}).features[0],0);
|
||||
for(let i=0;i<=40;i++){const t=i/40,a=curvePoint(before[0],before[1],t),b=t<=.4?curvePoint(after[0],after[1],t/.4):curvePoint(after[1],after[2],(t-.4)/.6);assert.ok(a.every((v,k)=>Math.abs(v-b[k])<1e-12));}
|
||||
});
|
||||
test("explicit Z translation is rigid and planar translation cannot change Z",()=>{
|
||||
const base=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-z-1234567890123456",template_id:"zebra",position:[0,0,2],surface:"gaussian-visual"});
|
||||
const op={kind:"translate",feature_id:base.features[0].id,vertices:[],axis:"z",delta:[0,0,.3]};
|
||||
const moved=semanticOperation(base,op);
|
||||
assert.ok(moved.features.every(f=>f.geometry.coordinates.flat().every(p=>p[2]===2.3)));
|
||||
assert.throws(()=>semanticOperation(base,{...op,axis:"xy"}));
|
||||
assert.strictEqual(semanticOperation(base,{...op,delta:[0,0,0]}),base);
|
||||
});
|
||||
|
||||
test("Shift duplicate extends either end, inserts inside, preserves source knots and is one undo",()=>{
|
||||
for(const [index,delta,inserted] of [[0,[-1,0,0],0],[1,[1,0,0],2],[2,[1,0,0],3]]){
|
||||
const before=semanticDraft(map),op={kind:"duplicate_vertex",feature_id:"a",path:0,index,axis:"x",delta};
|
||||
const result=commitSemantic(before,op),nodes=knots(result.map.features[0],0),p=map.features[0].geometry.coordinates[index];
|
||||
assert.equal(nodes.length,4);assert.deepEqual(nodes[inserted].point,p.map((v,k)=>v+delta[k]));
|
||||
assert.deepEqual(nodes.filter((_,i)=>i!==inserted).map(n=>n.point),map.features[0].geometry.coordinates);
|
||||
assert.equal(result.operations.length,1);assert.strictEqual(undoSemantic(result).map,map);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
|
||||
assert.strictEqual(result.map.features[1],map.features[1]);
|
||||
assert.strictEqual(commitSemantic(before,{...op,delta:[0,0,0]}),before);
|
||||
}
|
||||
});
|
||||
test("duplicate preserves cubic handles, source coordinates and polygon closure",()=>{
|
||||
const polygon={...map.features[0],geometry:{type:"Polygon",coordinates:[[[0,0,2],[4,0,2],[4,4,2],[0,4,2],[0,0,2]]]}};
|
||||
const base=semanticOperation({...map,features:[polygon]},{kind:"curve",feature_id:"a",path:0,index:1,incoming:[-.3,0],outgoing:[0,.3]});
|
||||
const source=knots(base.features[0],0),before=JSON.stringify(base);
|
||||
const result=semanticOperation(base,{kind:"duplicate_vertex",feature_id:"a",path:0,index:1,axis:"xy",delta:[.5,.5,0]}),next=knots(result.features[0],0);
|
||||
assert.deepEqual(next[1],source[1]);assert.deepEqual(next[2].incoming,source[1].incoming);assert.deepEqual(next[2].outgoing,source[1].outgoing);
|
||||
assert.deepEqual(result.features[0].geometry.coordinates[0][0],result.features[0].geometry.coordinates[0].at(-1));assert.equal(JSON.stringify(base),before);
|
||||
assert.throws(()=>semanticOperation(base,{kind:"duplicate_vertex",feature_id:"a",path:0,index:1,axis:"x",delta:[0,1,0]}));
|
||||
});
|
||||
const strip=()=>({id:"strip",properties:{class:"road_marking",subtype:"linear_marking",authority:"observation-only",route_permission:"unassigned"},geometry:{type:"Polygon",coordinates:[[[0,0,2],[4,0,2],[4,.2,2],[0,.2,2],[0,0,2]]]}});
|
||||
test("explicit line strips expose editable corners; two end vertices stretch while legacy translation stays rigid",()=>{
|
||||
const f=strip(),base={...map,features:[f]},vertices=[1,2].map(index=>({feature_id:f.id,path:0,index}));
|
||||
const op={kind:"translate_vertices",feature_id:f.id,vertices,axis:"x",delta:[2,0,0]},result=commitSemantic(semanticDraft(base),op);
|
||||
assert.deepEqual(result.map.features[0].geometry.coordinates[0],[[0,0,2],[6,0,2],[6,.2,2],[0,.2,2],[0,0,2]]);
|
||||
assert.strictEqual(undoSemantic(result).map,base);
|
||||
const legacy=semanticOperation(base,{...op,kind:"translate"});assert.deepEqual(legacy.features[0].geometry.coordinates[0][0],[2,0,2]);
|
||||
for(const subtype of [undefined,"letter_A","straight_arrow","bicycle","crosswalk"]){
|
||||
const symbol={...f,properties:{...f.properties,subtype}},m={...base,features:[symbol]};
|
||||
assert.throws(()=>semanticOperation(m,op));assert.throws(()=>semanticOperation(m,{kind:"duplicate_vertex",feature_id:f.id,path:0,index:1,axis:"x",delta:[1,0,0]}));
|
||||
}
|
||||
});
|
||||
|
||||
test("new linear marking is editable; whole-object copies retain shape, curves and independent identity",()=>{
|
||||
const placed=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-linear-123456789012",template_id:"linear_marking",position:[2,3,4],surface:"gaussian-visual"});
|
||||
const f=placed.features[0],v={feature_id:f.id,path:0,index:1};
|
||||
assert.equal(f.properties.subtype,"linear_marking");assert.equal(f.properties.semantic_element_id,undefined);
|
||||
const edited=semanticOperation(placed,{kind:"translate_vertices",feature_id:f.id,vertices:[v,{...v,index:2}],axis:"x",delta:[2,0,0]});
|
||||
const curved=semanticOperation(edited,{kind:"curve",...v,incoming:[-.2,0],outgoing:[0,.02]});
|
||||
const snapshot=JSON.stringify(curved),op={kind:"duplicate_marking",feature_id:f.id,new_feature_id:"user-copy-1234567890123456",axis:"y",delta:[0,2,0]};
|
||||
const d=commitSemantic(semanticDraft(curved),op),copy=d.map.features[1];
|
||||
assert.equal(JSON.stringify(curved),snapshot);assert.strictEqual(d.map.features[0],curved.features[0]);
|
||||
assert.equal(copy.id,op.new_feature_id);assert.equal(copy.properties.semantic_element_id,undefined);
|
||||
assert.deepEqual(knots(copy,0).map(n=>n.point),knots(curved.features[0],0).map(n=>[n.point[0],n.point[1]+2,n.point[2]]));
|
||||
assert.equal(copy.properties.height_source,"human-copy-unverified");assert.strictEqual(undoSemantic(d).map,curved);
|
||||
assert.throws(()=>semanticOperation(d.map,op));assert.strictEqual(semanticOperation(curved,{...op,delta:[0,0,0]}),curved);
|
||||
const letter=semanticOperation({...map,features:[]},{kind:"place",feature_id:"user-letter-123456789012",template_id:"letter_A",position:[0,0,2],surface:"gaussian-visual"});
|
||||
const copied=semanticOperation(letter,{...op,feature_id:letter.features[0].id});
|
||||
assert.equal(copied.features.length,2);assert.equal(copied.features[1].properties.semantic_element_id,op.new_feature_id);
|
||||
assert.throws(()=>semanticOperation(copied,{kind:"curve",feature_id:op.new_feature_id,path:0,index:0,incoming:[1,0],outgoing:[1,0]}));
|
||||
const selectedHits=semanticHits(placed,"road_marking",[50,30],p=>p.map(v=>v*100),true,f.id);
|
||||
assert.ok(selectedHits.every(h=>!h.point));
|
||||
const corners=semanticHits(placed,"road_marking",f.geometry.coordinates[0][0].map(v=>v*100),p=>p.map(v=>v*100),true,f.id);
|
||||
assert.ok(corners.some(h=>h.point));
|
||||
});
|
||||
|
||||
const {duplicateSide,duplicateIndex}=await import(vectorUrl);
|
||||
const directionCases=JSON.parse(readFileSync(new URL("../../../tests/fixtures/semantic_duplicate_direction.json",import.meta.url),"utf8"));
|
||||
for(const c of directionCases)test(`directional Shift insertion: ${c.name}`,()=>{
|
||||
const nodes=c.points.map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
|
||||
assert.equal(duplicateSide(nodes,c.index,c.closed,c.delta),c.side);
|
||||
const geometry=c.closed?{type:"Polygon",coordinates:[[...c.points,c.points[0]]]}:{type:"LineString",coordinates:c.points};
|
||||
const base={...map,features:[{...feature("a",[]),geometry}]},before=structuredClone(base);
|
||||
const op={kind:"duplicate_vertex",feature_id:"a",path:0,index:c.index,delta:c.delta,axis:c.delta[2]?"yz":"xy",side:c.side};
|
||||
const result=commitSemantic(semanticDraft(base),op),slot=c.index+Number(c.side==="after");
|
||||
assert.equal(duplicateIndex(c.index,c.closed,c.side),slot);
|
||||
const points=knots(result.map.features[0],0).map(n=>n.point);
|
||||
const expected=structuredClone(c.points);expected.splice(slot,0,c.points[c.index].map((v,k)=>v+c.delta[k]));
|
||||
assert.deepEqual(points,expected);assert.deepEqual(base,before);
|
||||
assert.deepEqual(undoSemantic(result).map,base);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
|
||||
if(c.closed)assert.deepEqual(result.map.features[0].geometry.coordinates[0][0],result.map.features[0].geometry.coordinates[0].at(-1));
|
||||
});
|
||||
test("curve direction follows tangent arms and ignores height",()=>{
|
||||
const nodes=[{point:[0,10,2],incoming:[0,0],outgoing:[0,0]},{point:[0,0,2],incoming:[-1,0],outgoing:[1,0]},{point:[0,-10,2],incoming:[0,0],outgoing:[0,0]}];
|
||||
assert.equal(duplicateSide(nodes,1,false,[-1,0,100]),"before");
|
||||
assert.equal(duplicateSide(nodes,1,false,[1,0,-100]),"after");
|
||||
});
|
||||
|
||||
test('retemplate old recognized letters retains identity and undo restores exact geometry',()=>{
|
||||
const base={schema_version:'missioncore.urban-map/v3',features:[{id:'recognized-A',properties:{class:'road_marking',subtype:'letter_A'},geometry:{type:'Polygon',coordinates:[[[0,0,1],[1,0,1],[1,1,1],[0,0,1]]]}}]};
|
||||
const op={kind:'retemplate',feature_id:'recognized-A',template_id:'letter_A_v3',frame:[[20,30,4],[0,1,.1],[-1,0,.2]]};
|
||||
const draft=commitSemantic(semanticDraft(base),op);
|
||||
assert.equal(draft.map.features[0].id,'recognized-A');assert.equal(draft.map.features[0].properties.template_id,'letter_A_v3');
|
||||
assert.equal(draft.map.features[0].geometry.coordinates.length,2);
|
||||
assert.deepEqual(undoSemantic(draft).map,base);assert.deepEqual(redoSemantic(undoSemantic(draft)).map,draft.map);
|
||||
assert.throws(()=>semanticOperation(base,{...op,frame:[[0,0,0],[1,0,0],[1,1,0]]}));
|
||||
});
|
||||
|
||||
for(const cls of ["road_boundary","pedestrian_boundary","building_facade","pedestrian_area","sidewalk","road_marking"])test(`Shift insertion uses direction for ${cls} contours`,()=>{
|
||||
const closed=["pedestrian_area","sidewalk","road_marking"].includes(cls);
|
||||
const points=closed?[[0,5,2],[0,0,2],[10,-1,2],[10,5,2]]:[[0,.1,2],[10,0,2]];
|
||||
const index=1,delta=[0,3,0],nodes=points.map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
|
||||
const side=duplicateSide(nodes,index,closed,delta);assert.equal(side,closed?"before":"after");
|
||||
const geometry=closed?{type:"Polygon",coordinates:[[...points,points[0]]]}:{type:"LineString",coordinates:points};
|
||||
const base={...map,features:[{...feature("a",[]),properties:{class:cls,...(cls==="road_marking"?{subtype:"linear_marking"}:{})},geometry}]};
|
||||
const op={kind:"duplicate_vertex",feature_id:"a",path:0,index,delta,axis:"y",side};
|
||||
const result=commitSemantic(semanticDraft(base),op),expected=structuredClone(points);
|
||||
expected.splice(index+Number(side==="after"),0,[points[index][0],points[index][1]+3,points[index][2]]);
|
||||
assert.deepEqual(knots(result.map.features[0],0).map(n=>n.point),expected);
|
||||
assert.deepEqual(undoSemantic(result).map,base);assert.deepEqual(redoSemantic(undoSemantic(result)).map,result.map);
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import path from 'node:path';
|
||||
import ts from 'typescript';
|
||||
const url=s=>`data:text/javascript;base64,${Buffer.from(s).toString('base64')}`;
|
||||
const hooks=url('export const useRef=x=>({current:x});export const useState=x=>[x,()=>{}];export const useEffect=f=>{globalThis.cleanups.push(f());};');
|
||||
const cache=new Map();
|
||||
function module(p){
|
||||
p=path.resolve(p);if(cache.has(p))return cache.get(p);
|
||||
let s=readFileSync(p,'utf8').replace(/import MARKING_TEMPLATES from "([^"]+)";/,(_,file)=>`const MARKING_TEMPLATES=${readFileSync(path.resolve(path.dirname(p),file),'utf8')};`);
|
||||
s=ts.transpileModule(s,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
s=s.replace(/from "([^"]+)"/g,(_,spec)=>`from ${JSON.stringify(spec==='react'?hooks:spec.startsWith('.')?module(path.resolve(path.dirname(p),spec+'.ts')):import.meta.resolve(spec))}`);
|
||||
const value=url(s);cache.set(p,value);return value;
|
||||
}
|
||||
const root=fileURLToPath(new URL('../src/',import.meta.url));
|
||||
const {useSemanticGestures}=await import(module(root+'components/simulation/useSemanticGestures.ts'));
|
||||
const edits=await import(module(root+'core/simulation/semanticEdits.ts'));
|
||||
const {semanticOperation}=edits;
|
||||
class Target {
|
||||
listeners=new Map();capture=new Set();
|
||||
addEventListener(n,f){this.listeners.set(n,[...(this.listeners.get(n)||[]),f]);}
|
||||
removeEventListener(n,f){this.listeners.set(n,(this.listeners.get(n)||[]).filter(v=>v!==f));}
|
||||
emit(n,e){e.preventDefault=()=>{e.defaultPrevented=true;};e.stopImmediatePropagation=()=>{e.stopped=true;};for(const f of this.listeners.get(n)||[]){f(e);if(e.stopped)break;}return e;}
|
||||
setPointerCapture(i){this.capture.add(i);}hasPointerCapture(i){return this.capture.has(i);}releasePointerCapture(i){this.capture.delete(i);}
|
||||
}
|
||||
function setup({marking=false,whole=false}={}){
|
||||
globalThis.cleanups=[];globalThis.document=new Target();document.querySelector=()=>null;globalThis.window=new Target();
|
||||
const canvas={clientWidth:100,clientHeight:100,getBoundingClientRect:()=>({left:0,top:0}),focus(){},closest:()=>null};
|
||||
const viewport=new Target();viewport.querySelector=()=>canvas;
|
||||
const map={features:[{id:'line',properties:{class:marking?'road_marking':'road_boundary',...(marking?{subtype:'linear_marking'}:{})},geometry:marking?{type:'Polygon',coordinates:[[[0,0,2],[10,0,2],[10,1,2],[0,1,2],[0,0,2]]]}:{type:'LineString',coordinates:[[0,0,2],[10,0,2],[20,0,2]]}}]};
|
||||
const selected={feature_id:'line',path:0,index:marking?1:2,...(whole?{object:true}:{})};
|
||||
const previews=[],commits=[],errors=[],selections=[];let navigation=true;
|
||||
const p={map,viewport,layers:[map.features[0].properties.class],selected,selection:[selected],editing:true,blocked:false,tool:'select',template:null,axis:'x',areaMode:'union',
|
||||
runtime:{semanticSegmentParameter:(_a,_b,t)=>t,projectSemantic:v=>[v[0]/100,v[1]/100],moveSemantic:(v,x,y)=>[x*100,y*100,v[2]],setNavigation:v=>{navigation=v;}},
|
||||
onPreview:op=>previews.push(op),onOperation:op=>{semanticOperation(map,op);commits.push(op);},onSelection:v=>selections.push(v),onSelect:v=>selections.push(v?[v]:[]),onChoose(){},onError:e=>errors.push(e),onPlaced(){},onExit(){}};
|
||||
useSemanticGestures(p);
|
||||
const axis={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'x'}}:null};
|
||||
const event=(x,o={})=>({target:axis,button:0,pointerId:1,clientX:x,clientY:0,shiftKey:true,...o});
|
||||
return {p,canvas,viewport,event,previews,commits,selections,errors,navigation:()=>navigation,dispose:()=>{for(const c of cleanups)c();}};
|
||||
}
|
||||
test('Shift pivot duplicates once on release; click and Escape do not commit',()=>{
|
||||
const s=setup(),snapshot=JSON.stringify(s.p.map);
|
||||
try{
|
||||
s.viewport.emit('pointerdown',s.event(30));assert.equal(s.navigation(),false);
|
||||
s.viewport.emit('pointermove',s.event(40));s.viewport.emit('pointermove',s.event(45));
|
||||
assert.equal(s.commits.length,0);assert.equal(JSON.stringify(s.p.map),snapshot);
|
||||
assert.deepEqual(s.previews.at(-1),{kind:'duplicate_vertex',feature_id:'line',path:0,index:2,axis:'x',delta:[15,0,0],side:'after'});
|
||||
s.viewport.emit('pointerup',s.event(45));assert.equal(s.commits.length,1);assert.equal(s.navigation(),true);
|
||||
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointerup',s.event(30));assert.equal(s.commits.length,1);
|
||||
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointermove',s.event(40));document.emit('keydown',{key:'Escape'});s.viewport.emit('pointerup',s.event(40));assert.equal(s.commits.length,1);assert.equal(s.previews.at(-1),null);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('whole strip Shift copies object; two vertices stretch; Ctrl owns camera',()=>{
|
||||
const s=setup({marking:true,whole:true});
|
||||
try{
|
||||
s.viewport.emit('pointerdown',s.event(30));s.viewport.emit('pointermove',s.event(40));const first=s.previews.at(-1);s.viewport.emit('pointermove',s.event(45));
|
||||
assert.equal(first.kind,'duplicate_marking');assert.equal(first.new_feature_id,s.previews.at(-1).new_feature_id);
|
||||
s.viewport.emit('pointerup',s.event(45));assert.equal(s.commits.length,1);
|
||||
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected,{...s.p.selected,index:2}];
|
||||
s.viewport.emit('pointerdown',s.event(30,{shiftKey:false}));s.viewport.emit('pointermove',s.event(40,{shiftKey:false}));s.viewport.emit('pointerup',s.event(40,{shiftKey:false}));
|
||||
assert.equal(s.commits[1].kind,'translate_vertices');assert.equal(s.commits[1].vertices.length,2);
|
||||
const e=s.viewport.emit('pointerdown',s.event(30,{ctrlKey:true}));assert.equal(e.stopped,undefined);
|
||||
s.viewport.emit('pointermove',s.event(40,{ctrlKey:true}));s.viewport.emit('pointerup',s.event(40,{ctrlKey:true}));assert.equal(s.commits.length,2);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('first press grabs another vertex of the selected line before React updates selection; undo restores it',()=>{
|
||||
const s=setup(),snapshot=JSON.stringify(s.p.map);s.p.selected={feature_id:'line',path:0,index:0};s.p.selection=[s.p.selected];
|
||||
try{
|
||||
const e=x=>s.event(x,{target:s.canvas,shiftKey:false,clientY:0});
|
||||
s.viewport.emit('pointerdown',e(20));assert.equal(s.navigation(),false);assert.deepEqual(s.selections.at(-1),[{feature_id:'line',path:0,index:2}]);
|
||||
// Deliberately leave props.selected stale: the gesture owns its captured target.
|
||||
s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
|
||||
assert.equal(s.commits.length,1);assert.equal(s.commits[0].kind,'translate_vertices');
|
||||
assert.deepEqual(s.commits[0].delta,[15,0,0]);assert.equal(JSON.stringify(s.p.map),snapshot);
|
||||
const {semanticDraft,commitSemantic,undoSemantic}=edits;
|
||||
const d=commitSemantic(semanticDraft(s.p.map),s.commits[0]);assert.equal(d.map.features[0].geometry.coordinates[2][0],35);
|
||||
assert.deepEqual(undoSemantic(d).map,s.p.map);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('a click, cancelled first drag, and Ctrl orbit never commit a point edit',()=>{
|
||||
const s=setup();s.p.selected=null;s.p.selection=[];
|
||||
try{
|
||||
const e=(x,o={})=>s.event(x,{target:s.canvas,shiftKey:false,...o});
|
||||
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointerup',e(20));assert.equal(s.commits.length,0);
|
||||
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));document.emit('keydown',{key:'Escape'});s.viewport.emit('pointerup',e(35));assert.equal(s.commits.length,0);assert.equal(s.navigation(),true);
|
||||
assert.equal(s.viewport.emit('pointerdown',e(20,{ctrlKey:true})).stopped,undefined);
|
||||
s.viewport.emit('pointermove',e(40,{ctrlKey:true}));s.viewport.emit('pointerup',e(40,{ctrlKey:true}));assert.equal(s.commits.length,0);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('multi-layer mask governs hits and marquee; hidden layers cannot be edited',()=>{
|
||||
const s=setup();
|
||||
s.p.map.features.push({...s.p.map.features[0],id:'ped',properties:{class:'pedestrian_boundary'}});
|
||||
try{
|
||||
const e=(x,y=0)=>s.event(x,{target:s.canvas,shiftKey:false,clientY:y});
|
||||
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
|
||||
assert.equal(s.commits.length,1);assert.deepEqual(s.commits[0].vertices,[{feature_id:'line',path:0,index:2}]);
|
||||
for(const layers of [['road_boundary'],['road_boundary','pedestrian_boundary'],[]]){
|
||||
s.p.layers=layers;s.viewport.emit('pointerdown',e(-20,-20));s.viewport.emit('pointermove',e(50,30));s.viewport.emit('pointerup',e(50,30));
|
||||
assert.deepEqual([...new Set(s.selections.at(-1).map(v=>v.feature_id))],layers.length===2?['line','ped']:layers.length?['line']:[]);
|
||||
}
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
test('direct grab preserves a selected group and only the chosen axes',()=>{
|
||||
const s=setup();s.p.selection=[{feature_id:'line',path:0,index:1},{feature_id:'line',path:0,index:2}];s.p.selected=s.p.selection[0];
|
||||
try{
|
||||
const e=(x,y)=>s.event(x,{target:s.canvas,shiftKey:false,clientY:y});
|
||||
s.viewport.emit('pointerdown',e(20,0));s.viewport.emit('pointermove',e(35,12));s.viewport.emit('pointerup',e(35,12));
|
||||
assert.deepEqual(s.commits[0].vertices,s.p.selection);assert.deepEqual(s.commits[0].delta,[15,0,0]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('interior Shift drag chooses incoming or outgoing arm; release freezes preview order',()=>{
|
||||
const s=setup();s.p.map.features[0].geometry.coordinates=[[0,10,2],[0,0,2],[10,-1,2]];
|
||||
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected];s.p.axis='xy';
|
||||
const target={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'xy'}}:null};
|
||||
const e=(x,y)=>s.event(x,{target,clientY:y});
|
||||
try{
|
||||
s.viewport.emit('pointerdown',e(0,0));s.viewport.emit('pointermove',e(0,3));
|
||||
assert.equal(s.previews.at(-1).side,'before');
|
||||
s.viewport.emit('pointermove',e(3,-.3));assert.equal(s.previews.at(-1).side,'after');
|
||||
s.viewport.emit('pointermove',e(0,4));const preview=s.previews.at(-1);
|
||||
s.viewport.emit('pointerup',e(0,4));assert.deepEqual(s.commits,[preview]);
|
||||
const points=semanticOperation(s.p.map,preview).features[0].geometry.coordinates;
|
||||
assert.deepEqual(points,[[0,10,2],[0,4,2],[0,0,2],[10,-1,2]]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('an unselected contour is selected before its hidden vertices can move',()=>{
|
||||
const s=setup();s.p.selected=null;s.p.selection=[];
|
||||
try{
|
||||
const e=x=>s.event(x,{target:s.canvas,shiftKey:false,clientY:0});
|
||||
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
|
||||
assert.equal(s.commits.length,0);assert.equal(s.selections.at(-1)[0].feature_id,'line');
|
||||
s.p.selection=s.selections.at(-1);s.p.selected=s.p.selection[0];
|
||||
s.viewport.emit('pointerdown',e(20));s.viewport.emit('pointermove',e(35));s.viewport.emit('pointerup',e(35));
|
||||
assert.equal(s.commits.length,1);assert.deepEqual(s.commits[0].delta,[15,0,0]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
|
||||
test('facade body selects every vertex; whole Delete and undo preserve valid geometry',()=>{
|
||||
const s=setup();s.p.selected=null;s.p.selection=[];
|
||||
s.p.layers=['building_facade'];s.p.map.features[0].properties.class='building_facade';
|
||||
s.p.map.features[0].geometry.coordinates=[[0,0,2],[80,0,2]];
|
||||
try{
|
||||
const e=x=>s.event(x,{target:s.canvas,shiftKey:false});
|
||||
s.viewport.emit('pointerdown',e(40));s.viewport.emit('pointerup',e(40));
|
||||
const selected=s.selections.at(-1);
|
||||
assert.deepEqual(selected,[{feature_id:'line',path:0,index:0},{feature_id:'line',path:0,index:1}]);
|
||||
const {semanticDraft,commitSemantic,undoSemantic}=edits;
|
||||
const initial=semanticDraft(s.p.map),removed=commitSemantic(initial,{kind:'delete_vertices',vertices:selected});
|
||||
assert.equal(removed.map.features[0].properties.review_status,'rejected');
|
||||
assert.deepEqual(undoSemantic(removed).map,initial.map);
|
||||
assert.throws(()=>semanticOperation(s.p.map,{kind:'delete_vertices',vertices:[selected[0]]}));
|
||||
// After selecting the contour, its visible vertex remains individually selectable/draggable.
|
||||
s.p.selection=selected;s.p.selected=selected[0];s.p.wholeContour=true;
|
||||
s.viewport.emit('pointerdown',e(80));s.viewport.emit('pointermove',e(90));s.viewport.emit('pointerup',e(90));
|
||||
assert.deepEqual(s.commits[0].vertices,[selected[1]]);
|
||||
assert.deepEqual(s.commits[0].delta,[10,0,0]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('body selection includes all curve anchors and polygon holes, not the sampled curve vertices',()=>{
|
||||
const s=setup();s.p.selected=null;s.p.selection=[];
|
||||
const f=s.p.map.features[0];f.geometry={type:'Polygon',coordinates:[[[0,0,2],[80,0,2],[80,80,2],[0,80,2],[0,0,2]],[[20,20,2],[20,40,2],[40,40,2],[40,20,2],[20,20,2]]]};
|
||||
s.p.map=semanticOperation(s.p.map,{kind:'curve',feature_id:'line',path:0,index:0,incoming:[0,0],outgoing:[10,-10]});
|
||||
try{
|
||||
const e=s.event(80,{target:s.canvas,shiftKey:false,clientY:40});
|
||||
s.viewport.emit('pointerdown',e);s.viewport.emit('pointerup',e);
|
||||
const selection=s.selections.at(-1);assert.equal(selection.length,8);
|
||||
const deleted=semanticOperation(s.p.map,{kind:'delete_vertices',vertices:selection});
|
||||
assert.equal(deleted.features[0].properties.review_status,'rejected');
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
|
||||
test('Shift Y at a facade endpoint extends around a corner and commits preview order once',()=>{
|
||||
const s=setup();
|
||||
s.p.map.features[0].properties.class='building_facade';s.p.layers=['building_facade'];
|
||||
s.p.map.features[0].geometry.coordinates=[[0,.1,2],[10,0,2]];
|
||||
s.p.selected={feature_id:'line',path:0,index:1};s.p.selection=[s.p.selected];
|
||||
const target={closest:q=>q.includes('axis')?{dataset:{semanticAxis:'y'}}:null};
|
||||
const e=y=>s.event(10,{target,clientY:y});
|
||||
try{
|
||||
s.viewport.emit('pointerdown',e(0));s.viewport.emit('pointermove',e(3));
|
||||
const preview=s.previews.at(-1);assert.equal(preview.kind,'duplicate_vertex');assert.equal(preview.side,'after');
|
||||
assert.deepEqual(preview.delta,[0,3,0]);assert.equal(s.commits.length,0);
|
||||
s.viewport.emit('pointerup',e(3));assert.deepEqual(s.commits,[preview]);
|
||||
assert.deepEqual(semanticOperation(s.p.map,s.commits[0]).features[0].geometry.coordinates,[[0,.1,2],[10,0,2],[10,3,2]]);
|
||||
}finally{s.dispose();}
|
||||
});
|
||||
@@ -18,7 +18,7 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
|
||||
]);
|
||||
|
||||
assert.match(productModel, /id: "simulations"[\s\S]*root: "polygon"[\s\S]*kind: "simulations"/);
|
||||
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace \/>/);
|
||||
assert.match(workspaceHub, /case "simulations":[\s\S]*<SimulationWorkspace headerToolsHost=\{props.headerToolsHost\} \/>/);
|
||||
assert.match(catalog, /simulation-catalog__table/);
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ test("simulation is a dedicated Polygon workspace with a bounded feature slice",
|
||||
|
||||
|
||||
|
||||
assert.match(workspace, /<AiPolygonWorkspace \/>/);
|
||||
assert.match(workspace, /<AiPolygonWorkspace headerToolsHost=\{headerToolsHost\} \/>/);
|
||||
assert.doesNotMatch(workspace, /simulation-profile|LccGaussianWorkspace/);
|
||||
assert.match(styles, /styles\/simulation\.css/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {readFileSync} from "node:fs";
|
||||
import {test} from "node:test";
|
||||
import ts from "typescript";
|
||||
const code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/urbanMap.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
const {ALL_URBAN_CLASSES,availableUrbanClasses,visibleUrbanMap,urbanPaths,loadUrbanMap,urbanExtent}=await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
|
||||
const classes=["road_boundary","pedestrian_area","pedestrian_boundary","building_facade","road_marking"];
|
||||
const map={schema_version:"missioncore.urban-map/v3",source:{world_sha256:"source"},features:classes.map((c,i)=>({id:String(i),properties:{class:c},geometry:{type:"LineString",coordinates:[[0,0,0],[1,1,1]]}}))};
|
||||
test("legend classes independently hide boundaries and fills without losing choices or geometry",()=>{
|
||||
assert.equal(visibleUrbanMap(map,ALL_URBAN_CLASSES).features.length,5);
|
||||
assert.equal(visibleUrbanMap(map,[]).features.length,0);
|
||||
assert.deepEqual(visibleUrbanMap(map,["pedestrian_area"]).features.map(f=>f.properties.class),["pedestrian_area"]);
|
||||
assert.deepEqual(visibleUrbanMap(map,["pedestrian_boundary"]).features.map(f=>f.properties.class),["pedestrian_boundary"]);
|
||||
assert.strictEqual(visibleUrbanMap(map,["building_facade"]).features[0],map.features[3]);
|
||||
assert.equal(availableUrbanClasses(map).length,5);
|
||||
const withRejected={...map,features:[...map.features,{...map.features[0],properties:{class:"curb",review_status:"rejected"}}]};
|
||||
assert.equal(availableUrbanClasses(withRejected).includes("curb"),false);
|
||||
assert.equal(visibleUrbanMap(withRejected,["curb"]).features.length,0);
|
||||
});
|
||||
test("rejected observations stay hidden and holes/open lines retain their paths",()=>{
|
||||
assert.deepEqual(urbanPaths({...map.features[0],properties:{review_status:"rejected"}}),[]);
|
||||
assert.deepEqual(urbanPaths(map.features[0]),[map.features[0].geometry.coordinates]);
|
||||
const rings=[[[0,0,0],[1,0,0],[0,1,0],[0,0,0]],[[.2,.2,0],[.3,.2,0],[.2,.3,0],[.2,.2,0]]];
|
||||
assert.strictEqual(urbanPaths({properties:{},geometry:{type:"Polygon",coordinates:rings}}),rings);
|
||||
});
|
||||
test("v3 loads only for the exact selected Gaussian revision",async()=>{
|
||||
const original=globalThis.fetch;globalThis.fetch=async()=>({ok:true,status:200,json:async()=>map});
|
||||
try {assert.strictEqual(await loadUrbanMap("world","source",new AbortController().signal),map);await assert.rejects(loadUrbanMap("world","different",new AbortController().signal));}
|
||||
finally {globalThis.fetch=original;}
|
||||
});
|
||||
|
||||
test("infrastructure framing works without waypoints and ignores rejected outliers",()=>{
|
||||
const features=[{...map.features[0],geometry:{type:"LineString",coordinates:[[-12,4,-2],[35,80,6]]}},{...map.features[1],properties:{review_status:"rejected"},geometry:{type:"LineString",coordinates:[[900,900,900],[999,999,999]]}}];
|
||||
assert.deepEqual(urbanExtent({...map,features}),[[-12,4,-2],[35,80,6]]);
|
||||
assert.deepEqual(urbanExtent({...map,features:[]}),[]);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {readFileSync} from "node:fs";
|
||||
import {test} from "node:test";
|
||||
import ts from "typescript";
|
||||
let code=ts.transpileModule(readFileSync(new URL("../src/core/simulation/urbanSurface.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
code=code.replace('from "three"',`from ${JSON.stringify(import.meta.resolve('three'))}`);
|
||||
const {urbanSurface}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
const ring=[[0,0,2],[8,0,2.8],[8,6,3.4],[0,6,2.6],[0,0,2]];
|
||||
const hole=[[2,2,2.4],[4,2,2.6],[4,4,2.8],[2,4,2.6],[2,2,2.4]];
|
||||
const feature={properties:{class:'pedestrian_area',height_projection:{method:'test'},review_status:'unreviewed'},geometry:{type:'Polygon',coordinates:[ring,hole]}};
|
||||
test('ground coverage triangulation preserves hole, area, source heights and input',()=>{
|
||||
const before=JSON.stringify(feature),g=urbanSurface(feature);assert.equal(JSON.stringify(feature),before);assert.deepEqual(g.positions,[...ring.slice(0,-1),...hole.slice(0,-1)].flat());let area=0;
|
||||
for(let i=0;i<g.indices.length;i+=3){const p=g.indices.slice(i,i+3).map(k=>g.positions.slice(k*3,k*3+3));area+=Math.abs((p[1][0]-p[0][0])*(p[2][1]-p[0][1])-(p[2][0]-p[0][0])*(p[1][1]-p[0][1]))/2;const c=[0,1].map(k=>p.reduce((s,x)=>s+x[k],0)/3);assert.ok(!(c[0]>2&&c[0]<4&&c[1]>2&&c[1]<4));}
|
||||
assert.equal(area,44);
|
||||
});
|
||||
test('physical boundaries and unqualified heights never become filled ground',()=>{
|
||||
assert.equal(urbanSurface({...feature,properties:{class:'pedestrian_boundary',height_projection:{}}}),null);
|
||||
assert.equal(urbanSurface({...feature,properties:{class:'pedestrian_area'}}),null);
|
||||
assert.equal(urbanSurface({...feature,properties:{...feature.properties,review_status:'rejected'}}),null);
|
||||
});
|
||||
test('concave pedestrian outline stays concave',()=>{
|
||||
const coords=[[0,0,0],[4,0,0],[4,1,0],[1,1,0],[1,4,0],[0,4,0],[0,0,0]];
|
||||
const g=urbanSurface({...feature,geometry:{type:'Polygon',coordinates:[coords]}});let area=0;
|
||||
for(let i=0;i<g.indices.length;i+=3){const p=g.indices.slice(i,i+3).map(k=>g.positions.slice(k*3,k*3+3));area+=Math.abs((p[1][0]-p[0][0])*(p[2][1]-p[0][1])-(p[2][0]-p[0][0])*(p[1][1]-p[0][1]))/2;}
|
||||
assert.equal(area,7);
|
||||
});
|
||||
Reference in New Issue
Block a user