trimesh库初步接触
背景
最近做了一个很有意思的需求,有这样一个游戏场景,有一个隧道模型(glb),模型是根据我们做的坐标系来建造的,还有一批隧道内的设施模型,比如隧道内的一些设施,都要加载到同一个坐标系地图内,但是这批设备位置不太对,举个例子,本该在隧道壁上的物体跑到了隧道上方,这个时候就需要调整,一个两个或许可以但是数量多了,就需要通过脚本批量处理
代码
import trimesh
import numpy as np# 加载隧道模型,file_path是模型路径
mesh = trimesh.load(file_path, force="mesh")
# 包装点np.array,这里的点是本该在隧道内的物体的点
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))
# 射线方向,例如:向z轴正方向
ray_direction = np.array([0, 0, 1])
# 求从隧道内物体发出的射线和模型的交点
locations, _, _ = mesh.ray.intersects_location([point_xyz_np], [ray_direction])
我用的trimesh的版本是4.0.2
可视化
说实话,光这样说,很抽象,我们能不能看到呢,就是让隧道和隧道内的物体点位可视化,有的兄弟,有的,可以用pyvista 库来做到,但是我要说一下,这个库加载模型很慢,不如用blender
import pyvista as pvdef add_vertical_ray(plotter, start_point, ray_length=5.0, ray_color='blue', ray_width=3):"""在点的Z轴正方向添加射线参数:- plotter: PyVista绘图器- start_point: 起始点坐标 [x, y, z]- ray_length: 射线长度- ray_color: 射线颜色- ray_width: 射线宽度"""# 计算射线终点end_point = start_point + [0, 0, ray_length]# 创建线段line = pv.Line(start_point, end_point)# 添加线段到场景plotter.add_mesh(line, color=ray_color, line_width=ray_width, label='Vertical Ray')return line# 物体点位
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))if point_xyz_np.ndim == 1:# 单个点,需要reshape为(1, 3)point_xyz_np = point_xyz_np.reshape(1, 3)# 检查点坐标的维度
if point_xyz_np.shape[1] != 3:raise ValueError(f"点坐标应该是3维的,但得到的是 {point_xyz_np.shape[1]} 维")plotter = pv.Plotter()
# file_path是隧道glb
mesh = pv.read(file_path)point_colors='red'point_size=10plotter.add_mesh(mesh, color='lightgray', show_edges=True)point_cloud = pv.PolyData(point_xyz_np)plotter.add_mesh(point_cloud, color=point_colors, point_size=point_size, render_points_as_spheres=True)# 添加点
for i, point in enumerate(point_xyz_np):plotter.add_point_labels([point], [f'Point {i}'], font_size=16, text_color='black', shape_color=point_colors)add_vertical_ray(plotter,[point_xyz[0], point_xyz[1], point_xyz[2]])
plotter.add_axes()
plotter.show_grid()
plotter.set_background('white')print("显示可视化界面...")
plotter.show()注
我写的原代码包含部分敏感内容,不能放出来,这里只记录思路哦
