Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
93 lines
5.4 KiB
Python
93 lines
5.4 KiB
Python
"""Bounded whole-scene survey. Tile cameras come from measured geometry, never A/B."""
|
|
import argparse
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import numpy as np
|
|
from mapping import render, infer, write_json, digest, unproject, CLASSES
|
|
from atlas import fuse
|
|
from terrain import load_glb
|
|
|
|
|
|
def plan_tiles(request, vertices, faces):
|
|
triangles = vertices[faces]
|
|
normals = np.cross(triangles[:,1]-triangles[:,0], triangles[:,2]-triangles[:,0])
|
|
flat = np.abs(normals[:,2]) > np.linalg.norm(normals, axis=1)*math.cos(math.radians(25))
|
|
samples = np.concatenate([triangles[flat].reshape(-1,3), triangles[flat].mean(1)])
|
|
if not len(samples):
|
|
raise ValueError('No measured near-horizontal surface in this scene')
|
|
bounds = np.array([vertices[:,:2].min(0), vertices[:,:2].max(0)])
|
|
origin = np.floor(bounds[0]/40)*40
|
|
shape = np.ceil((bounds[1]-origin)/40).astype(int)
|
|
if int(np.prod(shape)) > 256:
|
|
raise ValueError('Scene exceeds the supported 256-tile analysis envelope')
|
|
tiles=[]
|
|
for ix in range(shape[0]):
|
|
for iy in range(shape[1]):
|
|
low=origin+[ix*40,iy*40]; high=low+40; centre=(low+high)/2
|
|
local=samples[((samples[:,:2]>=low-10)&(samples[:,:2]<=high+10)).all(1)]
|
|
item=dict(id=f'tile-{ix:03d}-{iy:03d}',core_bounds=[low.tolist(),high.tolist()],bounds_xy=[(low-10).tolist(),(high+10).tolist()])
|
|
if len(local)<100:
|
|
tiles.append(dict(item,status='no-surface'));continue
|
|
# Lowest measured flat surface per 2m cell supplies camera candidates.
|
|
cells=np.floor((local[:,:2]-(low-10))/2).astype(int)
|
|
order=np.argsort(local[:,2]);_,indices=np.unique(cells[order],axis=0,return_index=True)
|
|
ground=local[order[indices]]
|
|
if len(ground)<8:
|
|
tiles.append(dict(item,status='no-surface'));continue
|
|
cameras=[];used=set()
|
|
for offset in [(-12,-12),(-12,12),(12,-12),(12,12)]:
|
|
anchor=centre+offset; index=int(np.argmin(np.linalg.norm(ground[:,:2]-anchor,axis=1)))
|
|
eye=ground[index].copy()
|
|
if index in used or np.linalg.norm(eye[:2]-anchor)>12:continue
|
|
used.add(index)
|
|
direction=centre-eye[:2]
|
|
if np.linalg.norm(direction)<1:direction=np.array([1.,0.])
|
|
direction/=np.linalg.norm(direction)
|
|
target_xy=eye[:2]+direction*12
|
|
target=ground[np.argmin(np.linalg.norm(ground[:,:2]-target_xy,axis=1))].copy()
|
|
target[:2]=target_xy;eye[2]+=1.8
|
|
cameras.append(dict(id=f'view-{len(cameras)}',projection='pinhole',size=[800,600],eye=eye.tolist(),target=target.tolist(),fov_degrees=100))
|
|
if not cameras:
|
|
tiles.append(dict(item,status='no-surface'));continue
|
|
top_z=float(local[:,2].max()+25)
|
|
top=dict(id='top',projection='ortho',size=[1200,1200],width_m=60,eye=[*centre,top_z],target=[*centre,top_z-1],up=[0,1,0])
|
|
job=dict(schema_version='missioncore.urban-mapping-job/v1',source=request['source'],model=request['model'],
|
|
bounds_xy=item['bounds_xy'],cell_m=.1,halo_m=25,min_confidence=.65,atlas_only=True,views=[top,*cameras])
|
|
tiles.append(dict(item,status='pending',job=job))
|
|
return dict(bounds_xy=bounds.tolist(),tiles=tiles)
|
|
|
|
|
|
def run(request, package, output):
|
|
terrain=json.loads((package/'terrain.json').read_text())
|
|
collider=package/(request['source']['collider_sha256']+'.decoded.glb')
|
|
meta=json.loads(collider.with_suffix('.json').read_text())
|
|
if meta['source_sha256']!=request['source']['collider_sha256'] or digest(collider)!=meta['sha256']:
|
|
raise ValueError('Collider source mismatch')
|
|
vertices,faces=load_glb(collider,terrain['collision_rotation'])
|
|
index=plan_tiles(request,vertices,faces);del vertices,faces
|
|
for i,tile in enumerate(index['tiles']):
|
|
write_json(output/'progress.json',dict(phase='survey',completed=i,total=len(index['tiles'])))
|
|
if tile['status']!='pending':continue
|
|
folder=output/tile['id'];folder.mkdir(exist_ok=True)
|
|
job=tile.pop('job');write_json(folder/'job.json',job)
|
|
receipt=folder/'survey-receipt.json'
|
|
if receipt.exists():
|
|
old=json.loads(receipt.read_text())
|
|
if old['job_sha256']==digest(folder/'job.json') and all((folder/n).exists() and digest(folder/n)==h for n,h in old['files'].items()):
|
|
tile['status']=old['status'];continue
|
|
render(job,folder)
|
|
infer(job,folder)
|
|
fuse(job,folder,unproject,CLASSES,write_json)
|
|
atlas=np.load(folder/'surface-atlas.npz',allow_pickle=False)
|
|
tile['status']='surveyed' if np.count_nonzero(np.isfinite(atlas['z']))>=100 else 'unobserved-ground'
|
|
names=['top.png','top.geometry.npz','surface-atlas.npz']
|
|
write_json(receipt,dict(job_sha256=digest(folder/'job.json'),status=tile['status'],files={n:digest(folder/n) for n in names}))
|
|
write_json(output/'tile-index.json',index)
|
|
write_json(output/'tile-index.json',index)
|
|
write_json(output/'progress.json',dict(phase='survey',completed=len(index['tiles']),total=len(index['tiles'])))
|
|
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser();p.add_argument('--request',type=Path,required=True);p.add_argument('--package',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
|
|
a=p.parse_args();run(json.loads(a.request.read_text()),a.package,a.output)
|