VTK读取stl文件用D算法计算指定两点之间的最短路径经过的点
程序员文章站
2022-04-01 08:45:59
...
转载:https://blog.csdn.net/wolfcsharp/article/details/84886128
基本流程:
(1)读入stl文件
(2)设置起点,终点
(3)计算最短路径
(4)打印一条最短路径经过的所有点的索引
(5)在原三维结构中画出最短路径并显示
#include <vtkAutoInit.h>
VTK_MODULE_INIT(vtkRenderingOpenGL2);
VTK_MODULE_INIT(vtkInteractionStyle);
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkDijkstraGraphGeodesicPath.h>
#include <vtkProperty.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkPolyData.h>
#include <vtkSTLReader.h>
int main()
{
//读取stl文件
std::string inputFilename = "line.stl";
vtkSmartPointer<vtkSTLReader> reader = vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName(inputFilename.c_str());
reader->Update();
//设置起点终点,D算法求解最短路径
vtkSmartPointer<vtkDijkstraGraphGeodesicPath> dijstra = vtkSmartPointer<vtkDijkstraGraphGeodesicPath>::New();
dijstra->SetInputData(reader->GetOutput());
dijstra->SetStartVertex(0);
dijstra->SetEndVertex(16);
dijstra->Update();
//打印最短路径的索引号
//D算法求解后,dijstra->GetIdList()可以得到完整的最短路径的索引,提取这些点的索引号必须再用一个for对IdList->GetId(i)进行提取
vtkSmartPointer<vtkIdList> IdList = vtkSmartPointer<vtkIdList>::New();
IdList = dijstra->GetIdList();
for (int i = 0; i < IdList->GetNumberOfIds(); i++)
{
cout << IdList->GetId(i) << endl;
}
//在原三维结构中画出最短路径并显示
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(reader->GetOutput());
vtkSmartPointer<vtkPolyDataMapper> pathMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
pathMapper->SetInputData(dijstra->GetOutput());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkActor> pathActor = vtkSmartPointer<vtkActor>::New();
pathActor->SetMapper(pathMapper);
pathActor->GetProperty()->SetColor(1, 0, 0);
pathActor->GetProperty()->SetLineWidth(5);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renderer->AddActor(actor);
renderer->AddActor(pathActor);
renderer->SetBackground(0, 0, 0);
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(renderer);
rw->SetSize(640, 480);
rw->SetWindowName("Calculating Geodesic Path");
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
rwi->Initialize();
rwi->Start();
return 0;
}