feat(sim): integrate Gazebo Classic with Point-LIO and SCAN navigation

Import the complete field and a simplified omnidirectional robot in sim_ws.
Reuse original Point-LIO, SCAN and controller implementations with isolated
simulation profiles, timed MID360/IMU data, readiness and command guards.
Support known-corridor terrain paths, optional sensor stress profiles and
separate physics/algorithm launch processes.

Remove retired Fortress resources and operating instructions; add build,
usage, scope and durable validation documentation.

Validation: full build script; 8 adapter tests and 4 SCAN CTest targets;
8 continuous mild-noise routes; red/blue terrain 4 cases each; noise 9/9;
visibility characterization 9/9; default sensors 16/16; loss-stop and
post-build straight navigation. Real wheels/network remain unverified.
This commit is contained in:
2026-11-08 19:04:32 +08:00
parent b6f84ac118
commit 664eaa81e5
83 changed files with 16948 additions and 12 deletions
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/python3
"""Independent geometry, acquisition-time and specific-force acceptance, no truth into LIO."""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import sys
import time
import xml.etree.ElementTree as ET
import numpy as np
import rclpy
from livox_ros_driver2.msg import CustomMsg
from sensor_msgs.msg import Imu
from std_msgs.msg import String
from rclpy.qos import qos_profile_sensor_data
from check_omni_robot import Sim,sim_env
from check_slope_drive import SlopeProbe
ROOT=Path(__file__).resolve().parents[2]
MOUNT=np.array([0.,0.,.30])
def json_value(value):
if isinstance(value,np.generic):return value.item()
raise TypeError('unsupported evidence value: '+type(value).__name__)
def rotate(q,v):
"""Quaternion xyzw, row vectors, broadcasting allowed."""
return v+2*np.cross(q[..., :3],np.cross(q[..., :3],v)+q[...,3,None]*v)
def interpolate(states,times):
times=np.asarray(times)
ts=np.array([s['stamp'] for s in states])
# Duplicate state samples are legal; select distinct independent query times.
ts,idx=np.unique(ts,return_index=True);states=[states[i] for i in idx]
if np.min(times)<ts[0] or np.max(times)>ts[-1]:raise ValueError('no bracketing independent truth')
hi=np.clip(np.searchsorted(ts,times,side='right'),1,len(ts)-1);lo=hi-1
if np.max(ts[hi]-ts[lo])>.12:raise ValueError('truth gap exceeds 120 ms')
w=(times-ts[lo])/(ts[hi]-ts[lo])
pos=np.array([s['pos'] for s in states]);q=np.array([s['quaternion'] for s in states])
qa,qb=q[lo],q[hi];qb=np.where(np.sum(qa*qb,axis=-1,keepdims=True)<0,-qb,qb)
qq=qa+(qb-qa)*w[:,None];qq/=np.linalg.norm(qq,axis=-1,keepdims=True)
return pos[lo]+(pos[hi]-pos[lo])*w[:,None],qq
def scene_shapes():
"""Read authoritative static primitives and triangles; independent of ODE ray code."""
base=ROOT/'sim_ws/src/robocon_gazebo/models/robocon_ground_full'
result=[]
for c in ET.parse(base/'model.sdf').findall('.//collision'):
p=np.fromstring(c.findtext('pose','0 0 0 0 0 0'),sep=' ')
r,pitch,y=p[3:];cx,sx=np.cos(r),np.sin(r);cy,sy=np.cos(pitch),np.sin(pitch);cz,sz=np.cos(y),np.sin(y)
R=np.array([[cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx],
[sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx],[-sy,cy*sx,cy*cx]])
geom=c.find('geometry');box=geom.find('box');cylinder=geom.find('cylinder');mesh=geom.find('mesh')
if box is not None:shape=('box',np.fromstring(box.findtext('size'),sep=' ')/2)
elif cylinder is not None:shape=('cylinder',(float(cylinder.findtext('radius')),float(cylinder.findtext('length'))/2))
elif mesh is not None:
path=base/'meshes'/Path(mesh.findtext('uri')).name
vertices=[];faces=[]
for line in path.read_text().splitlines():
if line.startswith('v '):vertices.append(list(map(float,line.split()[1:])))
if line.startswith('f '):faces.append([int(s.split('/')[0])-1 for s in line.split()[1:]])
vertices=np.array(vertices)*np.fromstring(mesh.findtext('scale','1 1 1'),sep=' ')
shape=('mesh',vertices[np.array(faces)])
else:raise ValueError('unhandled scene geometry')
result.append((p[:3],R,*shape))
return result
def ray_ranges(origins,directions,shapes):
best=np.full(len(origins),np.inf)
for center,R,kind,value in shapes:
o=(origins-center)@R;d=directions@R
if kind=='box':
safe=np.where(np.abs(d)>1e-12,d,1e-12)
a=(-value-o)/safe;b=(value-o)/safe
enter=np.max(np.minimum(a,b),axis=1);leave=np.min(np.maximum(a,b),axis=1)
hit=np.where((leave>=np.maximum(enter,0))&(enter>0),enter,np.inf)
elif kind=='cylinder':
radius,height=value
A=np.sum(d[:,:2]**2,axis=1);B=2*np.sum(o[:,:2]*d[:,:2],axis=1)
C=np.sum(o[:,:2]**2,axis=1)-radius**2;disc=B*B-4*A*C
hit=np.full(len(o),np.inf)
for sign in (-1,1):
t=(-B+sign*np.sqrt(np.maximum(disc,0)))/np.maximum(2*A,1e-20)
good=(disc>=0)&(t>0)&(np.abs(o[:,2]+t*d[:,2])<=height)
hit=np.minimum(hit,np.where(good,t,np.inf))
for z in (-height,height):
t=(z-o[:,2])/np.where(np.abs(d[:,2])>1e-12,d[:,2],1e-12)
xy=o[:,:2]+t[:,None]*d[:,:2]
hit=np.minimum(hit,np.where((t>0)&(np.sum(xy**2,axis=1)<=radius**2),t,np.inf))
else:
hit=np.full(len(o),np.inf)
for a,b,c in value:
e1,e2=b-a,c-a;h=np.cross(d,e2);det=h@e1
safe=np.where(np.abs(det)>1e-12,det,1e-12);s=o-a
u=np.sum(s*h,axis=1)/safe;q=np.cross(s,e1);v=np.sum(d*q,axis=1)/safe
t=q@e2/safe
good=(np.abs(det)>1e-12)&(u>=0)&(v>=0)&(u+v<=1)&(t>0)
hit=np.minimum(hit,np.where(good,t,np.inf))
best=np.minimum(best,hit)
return best
class SensorProbe(SlopeProbe):
def __init__(self):
super().__init__();self.frames=[];self.imus=[];self.sensor_status=[]
self.create_subscription(CustomMsg,'/sim/mid360/lidar',self.on_frame,qos_profile_sensor_data)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(String,'/sim/mid360/status',lambda m:self.sensor_status.append(json.loads(m.data)),10)
def on_frame(self,m):
self.frames.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
timebase=int(m.timebase),frame=m.header.frame_id,point_num=m.point_num,
xyz=np.array([[p.x,p.y,p.z] for p in m.points]),
offsets=np.array([p.offset_time for p in m.points],dtype=np.uint32),
line=np.array([p.line for p in m.points],dtype=np.uint8),
tag=np.array([p.tag for p in m.points],dtype=np.uint8)))
def on_imu(self,m):
a=m.linear_acceleration;w=m.angular_velocity
self.imus.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,frame=m.header.frame_id,
acc=[a.x,a.y,a.z],gyro=[w.x,w.y,w.z],orientation_covariance_0=m.orientation_covariance[0]))
def phase(p,cmd,duration):
t0=p.now();states=[p.get_state()];nxt=t0
def sample():
nonlocal nxt
if p.now()<nxt:return
s=p.get_state()
if s is None:raise RuntimeError('missing independent Gazebo state')
states.append(s);nxt=p.now()+.025
p.hold(*cmd,duration,sampler=sample)
states.append(p.get_state())
if any(s is None for s in states):raise RuntimeError('invalid truth sample')
return dict(t0=t0,t1=p.now(),states=states)
def geometry_check(p,record,shapes,out,name):
states=record['states'];frames=[f for f in p.frames if f['t']>states[0]['stamp']+.15 and f['t']+.1<states[-1]['stamp']-.05]
if len(frames)<4:raise RuntimeError('insufficient complete sensor frames')
errors=[];instant_errors=[];saved={}
for i,f in enumerate(frames[::max(1,len(frames)//6)]):
idx=np.arange(0,len(f['xyz']),max(1,len(f['xyz'])//600))
xyz=f['xyz'][idx];ranges=np.linalg.norm(xyz,axis=1);direction=xyz/ranges[:,None]
times=f['t']+f['offsets'][idx]*1e-9
pos,q=interpolate(states,times)
origins=pos+rotate(q,np.broadcast_to(MOUNT,pos.shape));directions=rotate(q,direction)
expected=ray_ranges(origins,directions,shapes)
errors.extend(np.abs(expected-ranges).tolist())
end_pos,end_q=interpolate(states,np.full(len(xyz),f['t']+.099))
wrong=ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes)
instant_errors.extend(np.abs(wrong-ranges).tolist())
saved[str(i)+'_xyz']=f['xyz'];saved[str(i)+'_offset_ns']=f['offsets']
saved[str(i)+'_query_t']=times;saved[str(i)+'_expected_range']=expected
np.savez_compressed(out/(name+'_clouds.npz'),**saved)
finite=np.isfinite(errors)
# At object silhouettes a tiny interpolation error may change occlusion.
# Check the distribution and retain all errors instead of removing them.
e=np.asarray(errors);wrong=np.asarray(instant_errors)
return dict(samples=len(e),finite_fraction=float(np.mean(finite)),
p95_range_error_m=float(np.quantile(e,.95)),p99_range_error_m=float(np.quantile(e,.99)),
instantaneous_p95_error_m=float(np.quantile(wrong,.95)),
ok=bool(np.mean(finite)>.98 and np.quantile(e,.95)<.005 and np.quantile(e,.99)<.02))
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--case',choices=('flat','slope'),default='flat');args=ap.parse_args()
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
sim,p=Sim(str(out/'sim')),None
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
result=dict(status='INVALID',case=args.case,checks={},collector_sha256=hashlib.sha256(source).hexdigest())
wall=time.monotonic()
try:
spawn=(1.4,3.5125,.6,0.) if args.case=='slope' else (-4.5,4.5,.17,0.)
ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',spawn=spawn)
result['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=SensorProbe()
if not p.wait_clock():raise RuntimeError('no clock')
p.pump(1.5)
if len(p.frames)<5 or len(p.imus)<100:raise RuntimeError('missing lidar or IMU stream')
records={};shapes=scene_shapes()
records['stationary']=phase(p,(0.,0.,0.),2.)
for name,cmd,duration in ([] if args.case=='slope' else [
('forward',(.3,0.,0.),2.5),('lateral',(0.,-.2,0.),1.5),('turn',(0.,0.,.3),2.)]):
records[name]=phase(p,cmd,duration)
records['stop']=phase(p,(0.,0.,0.),.5)
# Finish live collection before CPU-heavy offline ray intersections.
# Otherwise the probe's own analysis can overflow its IMU receive queue.
if args.case=='flat':
if not p.set_state(-4.5,4.5,1.2,0.):raise RuntimeError('drop set failed')
drop=phase(p,(.3,0.,0.),.23)
free=[m for m in p.imus if drop['t0']+.04<m['t']<drop['t1']-.02]
result['free_fall']=dict(samples=free,truth=drop)
geometry={}
for name in records:
if name!='stop':geometry[name]=geometry_check(p,records[name],shapes,out,name)
frames=[f for f in p.frames if records['stationary']['t0']<=f['t']<records['stop']['t1']-.1]
checks=result['checks']
checks['geometry']=all(g['ok'] for g in geometry.values())
checks['frame_and_count']=all(f['frame']=='lidar' and f['point_num']==len(f['xyz']) and len(f['xyz'])>500 for f in frames)
checks['finite_fov']=all(np.isfinite(f['xyz']).all() and np.min(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))>=math.radians(-7)-1e-6 and np.max(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))<=math.radians(52)+1e-6 for f in frames)
checks['timebase']=all(abs(f['t']*1e9-f['timebase'])<1 for f in frames)
checks['actual_batch_times']=all(np.min(f['offsets'])>=0 and np.max(f['offsets'])<100000000 and len(np.unique(f['offsets']))>50 and np.all(f['offsets']%1000000==0) and np.all(np.diff(f['offsets'].astype(np.int64))>=0) for f in frames)
checks['frame_rate']=len(frames)>5 and np.max(np.abs(np.diff([f['t'] for f in frames])-.1))<1e-6
checks['livox_flags']=all(np.max(f['line'])<4 and np.all(f['tag']==0x10) for f in frames)
checks['ray_budget']=len(p.sensor_status)>5 and all(s['rays']==20000 and s['last_sample_ns']-s['first_sample_ns']==99000000 for s in p.sensor_status)
checks['pattern_continues']=not np.allclose(frames[0]['xyz'][:100],frames[1]['xyz'][:100])
st=records['stationary'];imu=[m for m in p.imus if st['t0']+.2<m['t']<st['t1']]
if len(imu)<100:raise RuntimeError('too few stationary IMUs')
pos,q=interpolate(st['states'],np.array([m['t'] for m in imu]));inverse=q.copy();inverse[:,:3]*=-1
expected=rotate(inverse,np.broadcast_to([0,0,9.8],pos.shape))
acc=np.array([m['acc'] for m in imu]);gyro=np.array([m['gyro'] for m in imu])
stationary_error=np.linalg.norm(acc-expected,axis=1)
checks['imu_specific_force']=bool(np.quantile(stationary_error,.95)<.05 and np.max(np.linalg.norm(gyro,axis=1))<.01)
checks['imu_frame_rate']=all(m['frame']=='mid360_imu' for m in imu) and abs(1/np.median(np.diff([m['t'] for m in imu]))-200)<2
checks['no_attitude_oracle']=all(m['orientation_covariance_0']==-1. for m in p.imus)
measured_imu=[m for m in p.imus if st['t0']<=m['t']<=records['stop']['t1']]
imu_times=np.array([m['t'] for m in measured_imu]);imu_intervals=np.diff(imu_times)
imu_rate=(len(imu_times)-1)/(imu_times[-1]-imu_times[0])
checks['imu_continuity']=bool(abs(imu_rate-200)<2 and np.min(imu_intervals)>0 and np.max(imu_intervals)<.02)
if args.case=='flat':
tr=records['turn'];moving=[m for m in p.imus if tr['t0']+.3<m['t']<tr['t1']-.1]
checks['gyro_motion']=len(moving)>100 and abs(np.median([m['gyro'][2] for m in moving])-.3)<.02
checks['real_scan_distortion']=max(geometry[n]['instantaneous_p95_error_m'] for n in ('forward','turn'))>.015
checks['free_fall_imu']=len(free)>20 and np.quantile([np.linalg.norm(m['acc']) for m in free],.95)<.05
else:
checks['slope_physically_tilted']=abs(np.median([s['rpy'][1] for s in st['states']])-math.atan2(.597,3.5))<.02
result.update(geometry=geometry,records=records,imus=p.imus,sensor_status=p.sensor_status,
stationary_imu_p95_error_m_s2=float(np.quantile(stationary_error,.95)),
stationary_imu_mean=np.mean(acc,axis=0).tolist(),frame_returns=[len(f['xyz']) for f in frames],
measured_imu_rate_hz=float(imu_rate),maximum_imu_interval_s=float(np.max(imu_intervals)),
sim_duration_s=p.now()-records['stationary']['t0'],wall_duration_s=time.monotonic()-wall)
result['status']='PASS' if all(checks.values()) else 'FAIL'
print(json.dumps(dict(status=result['status'],checks=checks,geometry=geometry),indent=2,default=json_value),flush=True)
except Exception as exc:
result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
result['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(result,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[result['status']]
if __name__=='__main__':sys.exit(main())