1 #include <vtkActor.h>
2 #include <vtkFloatArray.h>
3 #include <vtkLookupTable.h>
4 #include <vtkPointData.h>
5 #include <vtkPolyData.h>
6 #include <vtkPolyDataMapper.h>
7 #include <vtkRenderer.h>
8 #include <vtkRenderWindow.h>
9 #include <vtkRenderWindowInteractor.h>
10 #include <vtkSmartPointer.h>
11 #include <vtkSTLReader.h>
12 #include <vtkInteractorStyleTrackballCamera.h>
13
14 #include <vtkAutoInit.h>
15 VTK_MODULE_INIT(vtkRenderingOpenGL2);
16 VTK_MODULE_INIT(vtkInteractionStyle);
17 VTK_MODULE_INIT(vtkRenderingVolumeOpenGL2);
18 VTK_MODULE_INIT(vtkRenderingFreeType);
19
20 int main(int, char* [])
21 {
22 // 加载一个J20的STL模型
23 vtkSmartPointer<vtkSTLReader> source = vtkSmartPointer<vtkSTLReader>::New();
24 source->SetFileName("C:\Users\wangjun\3D Objects\J20.stl");
25 source->Update();
26
27 int numPts = source->GetOutput()->GetPoints()->GetNumberOfPoints(); // 获取模型的顶点数量
28 vtkSmartPointer<vtkFloatArray> scalars = vtkSmartPointer<vtkFloatArray>::New(); // 创建存储顶点属性的float数组
29 scalars->SetNumberOfValues(numPts);
30 for (int i = 0; i < numPts; ++i) // 为属性数组中的每个元素设置标量值(这个标量值可以当作颜色值)
31 scalars->SetValue(i, i);
32
33 vtkSmartPointer<vtkPolyData> poly = vtkSmartPointer<vtkPolyData>::New();
34 poly->DeepCopy(source->GetOutput());
35 poly->GetPointData()->SetScalars(scalars);
36
37 // 创建颜色查找表
38 vtkSmartPointer<vtkLookupTable> hueLut = vtkSmartPointer<vtkLookupTable>::New();
39 hueLut->SetNumberOfColors(numPts); // 指定颜色查找表中有多少种颜色
40 hueLut->SetHueRange(0.67, 0.0); // 设定HSV颜色范围,色调H取值范围为0°~360°,从红色开始按逆时针方向计算,红色为0°/0.0,绿色为120°/0.34,蓝色为240°/0.67
41 hueLut->Build();
42
43 vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
44 mapper->SetInputData(poly);
45 mapper->SetScalarRange(0, numPts); // 设置标量值的范围
46 mapper->ScalarVisibilityOn();
47 //mapper->SetColorModeToMapScalars(); // 无论变量数据是何种类型,该方法都通过查询表对标量数据进行映射
48 mapper->SetColorModeToDefault(); // 默认的映射器行为,即把unsigned char类型的标量属性数据当作颜色值,不执行隐式。对于其他类型的标量数据,将通过查询表映射。
49 mapper->SetLookupTable(hueLut);
50
51 vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
52 actor->SetMapper(mapper);
53
54 vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
55 renderer->GradientBackgroundOn();
56 renderer->SetBackground(1, 1, 1);
57 renderer->SetBackground2(0, 0, 0);
58
59 vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
60 renderWindow->AddRenderer(renderer);
61
62 vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
63 renderWindowInteractor->SetRenderWindow(renderWindow);
64 vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
65 renderWindowInteractor->SetInteractorStyle(style);
66
67 renderer->AddActor(actor);
68 renderWindow->SetSize(600, 600);
69 renderWindow->Render();
70 renderWindowInteractor->Start();
71
72 return 0;
73 }