Prev Tutorial: Transformations
Next Tutorial: Creating a 3D histogram
Goal
In this tutorial you will learn how to
- Create your own widgets using WidgetAccessor and VTK.
- Show your widget in the visualization window.
Code
You can download the code from here.
#ifndef USE_VTK
#include <iostream>
int main()
{
std::cout << "This sample requires direct compilation with VTK. Stop" << std::endl;
return 0;
}
#else
#include <iostream>
#include <vtkPoints.h>
#include <vtkTriangle.h>
#include <vtkCellArray.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkIdList.h>
#include <vtkActor.h>
#include <vtkProp.h>
static void help()
{
cout
<< "--------------------------------------------------------------------------" << endl
<< "This program shows how to create a custom widget. You can create your own "
<< "widgets by extending Widget2D/Widget3D, and with the help of WidgetAccessor." << endl
<< "Usage:" << endl
<< "./creating_widgets" << endl
<< endl;
}
{
public:
};
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(pt1.
x, pt1.
y, pt1.
z);
points->InsertNextPoint(pt2.
x, pt2.
y, pt2.
z);
points->InsertNextPoint(pt3.
x, pt3.
y, pt3.
z);
vtkSmartPointer<vtkTriangle>
triangle = vtkSmartPointer<vtkTriangle>::New();
triangle->GetPointIds()->SetId(0,0);
triangle->GetPointIds()->SetId(1,1);
triangle->GetPointIds()->SetId(2,2);
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->InsertNextCell(triangle);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->SetPoints(points);
polyData->SetPolys(cells);
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
#if VTK_MAJOR_VERSION <= 5
mapper->SetInput(polyData);
#else
mapper->SetInputData(polyData);
#endif
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
setColor(color);
}
int main()
{
help();
myWindow.showWidget("TRIANGLE", tw);
myWindow.spin();
return 0;
}
#endif
Explanation
Here is the general structure of the program:
- Extend Widget3D class to create a new 3D widget.
class WTriangle : public viz::Widget3D
{
public:
WTriangle(
const Point3f &pt1,
const Point3f &pt2,
const Point3f &pt3,
const viz::Color & color = viz::Color::white());
};
- Assign a VTK actor to the widget.
viz::WidgetAccessor::setProp(*this, actor);
- Set color of the widget.
- Construct a triangle widget and display it in the window.
myWindow.showWidget("TRIANGLE", tw);
Results
Here is the result of the program.