Files
VSAG_SENTRY_SIM_27RMUL/tools/build_meshes.py
T
mzx f7412ec369 初始化:RMUL 2027 哨兵导航仿真工程
- Gazebo Sim (Jetty 10.6) + ROS 2 Lyrical + Nav2 全栈
- 整车模型:URDF/SDF + 减面网格(SolidWorks 装配体实测尺寸)
- 场地:RMUL 2027 官方包(2D 栅格地图 + 3D 场地模型),放在 field/
- sentry_nav C++ 包:self_filter 点云自滤 / patrol 航点巡逻
- 文档:README(含本机开发环境实测)、MID-360 接入说明

已排除:build/ install/ log/ 缓存目录,以及 115 MB 的原始高模
(仿真实际用的是 meshes/base.stl 减面版,约 25.7 万面)
2026-11-14 21:18:04 +08:00

180 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把 SolidWorks 导出的底盘 STL 装配体转成仿真可用的网格。
输入:SW 按零件导出的二进制 STL(装配体坐标系,单位 mm,Y 轴向上)
输出:
meshes/base.stl 底盘(除轮子本体外的全部零件),已转到 ROS 坐标系并居中
meshes/wheel.stl 单个麦轮,已转到 ROS 坐标系并把原点放在轮子中心
meshes/transform.json 坐标变换与四个轮子的关节位置(供 URDF 与人工核对)
坐标约定(REP-103:X 前、Y 左、Z 上):
p_ros = R @ (p_sw - C) / 1000 R = [[0,0,1],[1,0,0],[0,1,0]]
即 ROS_x = SW_z、ROS_y = SW_x、ROS_z = SW_y(把 SW 的 Z 前 / X 左 / Y 上 换成 ROS 约定)
用法:
python3 tools/build_meshes.py --src "/run/media/.../底盘" --out src/sentry_sim/meshes
"""
import argparse
import glob
import json
import os
import struct
import sys
import numpy as np
# SW 装配体坐标 -> ROS(REP-103)
ROT = np.array([[0.0, 0.0, 1.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0]])
SCALE = 0.001 # mm -> m
def read_stl(path):
"""读二进制/ASCII STL,返回 (N,3,3) 的三角面片数组(float32,SW 原始单位)。"""
size = os.path.getsize(path)
with open(path, 'rb') as f:
head = f.read(84)
if len(head) < 84:
return None
n = struct.unpack('<I', head[80:84])[0]
if 84 + n * 50 == size: # 二进制
f.seek(84)
buf = f.read(n * 50)
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
('v', '<9f4'),
('a', '<u2')]))
tris = rec['v'].reshape(-1, 3, 3).astype(np.float64)
return tris
# ASCII 兜底
verts = []
with open(path, 'r', errors='ignore') as f:
for line in f:
s = line.strip()
if s.startswith('vertex'):
verts.append([float(x) for x in s.split()[1:4]])
if not verts or len(verts) % 3:
return None
return np.asarray(verts, dtype=np.float64).reshape(-1, 3, 3)
def write_stl(path, tris):
"""写二进制 STL。"""
n = len(tris)
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
normals = np.cross(v1 - v0, v2 - v0)
leng = np.linalg.norm(normals, axis=1)
leng[leng == 0] = 1.0
normals = normals / leng[:, None]
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
rec['n'] = normals
rec['v'] = tris.reshape(n, 9)
with open(path, 'wb') as f:
f.write(b'sentry_sim converted'.ljust(80, b' '))
f.write(struct.pack('<I', n))
f.write(rec.tobytes())
def to_ros(tris, center):
"""SW 装配体坐标 -> ROS 坐标(米),并平移到 center 为原点。"""
return ((tris - center) @ ROT.T) * SCALE
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--src', required=True, help='SW 导出的 STL 目录')
ap.add_argument('--out', required=True, help='输出 meshes 目录')
args = ap.parse_args()
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
glob.glob(os.path.join(args.src, '*.stl')))
if not files:
sys.exit(f'没找到 STL:{args.src}')
print(f'共 {len(files)} 个 STL')
# ---- 第 1 遍:整体包围盒,确定原点 C ----
gmin = np.full(3, np.inf)
gmax = np.full(3, -np.inf)
for p in files:
t = read_stl(p)
if t is None:
print(f' 跳过(无法解析): {os.path.basename(p)}')
continue
v = t.reshape(-1, 3)
gmin = np.minimum(gmin, v.min(axis=0))
gmax = np.maximum(gmax, v.max(axis=0))
# 原点:X/Z 取包围盒中心,Y 取“地面”(最低点)
center_sw = np.array([(gmin[0] + gmax[0]) / 2.0,
gmin[1],
(gmin[2] + gmax[2]) / 2.0])
print(f'SW 包围盒 min={np.round(gmin, 1)} max={np.round(gmax, 1)}')
print(f'原点 C (mm) = {np.round(center_sw, 2)}')
# ---- 第 2 遍:合并 ----
# 只认「轮系-N 装配体1-1」,排除悬挂摇臂(文件名里也含“装配体1-1”)
wheel_files = [p for p in files
if '装配体1-1' in os.path.basename(p)
and '轮系-' in os.path.basename(p)]
base_files = [p for p in files if p not in wheel_files]
print(f'轮子本体 {len(wheel_files)} 个;底盘 {len(base_files)} 个')
os.makedirs(args.out, exist_ok=True)
base_tris = []
for p in base_files:
t = read_stl(p)
if t is not None:
base_tris.append(to_ros(t, center_sw))
base = np.concatenate(base_tris)
write_stl(os.path.join(args.out, 'base.stl'), base)
print(f'base.stl: {len(base):,} 面')
wheels = {}
for p in wheel_files:
t = read_stl(p)
if t is None:
continue
v = t.reshape(-1, 3)
wheel_center_sw = (v.min(axis=0) + v.max(axis=0)) / 2.0
wheels[os.path.basename(p)] = wheel_center_sw
if 'wheel_raw' not in wheels:
# 以第一个轮子为模板,把原点放在轮子中心
ros = to_ros(t, center_sw) # 先到 ROS 系、底盘中心为原点
wc = (to_ros(t, wheel_center_sw)).reshape(-1, 3).mean(axis=0) * 0 # 占位
# 轮子中心在 ROS 系下的位置
wc_ros = ((wheel_center_sw - center_sw) @ ROT.T) * SCALE
ros_centered = ros - wc_ros
write_stl(os.path.join(args.out, 'wheel.stl'), ros_centered)
print(f'wheel.stl: {len(ros_centered):,} 面(模板:{os.path.basename(p)})')
# ---- 轮子关节位置(ROS,米)----
joints = {}
for name, c_sw in wheels.items():
# 轮系-N 装配体1-1.STL -> N
idx = name.split('轮系-')[-1].split()[0]
c_ros = ((c_sw - center_sw) @ ROT.T) * SCALE
joints[f'wheel_{idx}'] = [round(float(x), 6) for x in c_ros]
meta = {
'source_dir': os.path.abspath(args.src),
'sw_bbox_min_mm': [round(float(x), 2) for x in gmin],
'sw_bbox_max_mm': [round(float(x), 2) for x in gmax],
'origin_sw_mm': [round(float(x), 2) for x in center_sw],
'ros_bbox_size_m': [round(float(x) * SCALE, 4) for x in (gmax - gmin)],
'wheels_ros_m': joints,
'wheel_radius_m': 0.0762,
'note': 'ROS_x=SW_z, ROS_y=SW_x, ROS_z=SW_y;单位 mm->m',
}
with open(os.path.join(args.out, 'transform.json'), 'w') as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
print('\n轮子中心(ROS,米):')
for k, v in joints.items():
print(f' {k}: {v}')
print(f'\n车体尺寸(ROS,米): {meta["ros_bbox_size_m"]}')
if __name__ == '__main__':
main()