Files
NODEDC_MISSION_CORE/simulation/ai-polygon/route_region.py
T
DCCONSTRUCTIONS 31b74e4571 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.
2026-10-08 23:42:26 +03:00

75 lines
3.7 KiB
Python

"""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)