一、概述
vtkCommand是VTK中的一个重要的类,用于处理事件和回调机制。它允许用户在特定事件发生时执行自定义的操作,例如在交互操作、数据更新或渲染过程中触发某些功能。
二、主要功能
1、事件处理:vtkCommand用于监听和处理VTK管线中的各种事件
2、回调机制:通过回调函数,用户可以在事件发生时执行自定义代码
3、事件类型:VTK定义了多种事件类型,如StartEvent、EndEvent、ProgressEvent等。
三、常用事件类型
StartEvent | 某个过程开始时触发 |
EndEvent | 某个过程结束时触发 |
ProgressEvent | 过程进行中触发,常用于更新进度条 |
ModifiedEvent | 对象被修改时触发 |
PickEvent | 用户进行拾起操作时触发 |
InteractionEvent | 用户进行交互操作时触发 |
四、使用步骤
1、创建一个类继承于vtkCommand,并重写Execute方法
class vtkMyCallback : public vtkCommand
{
public:
static vtkMyCallback* New()
{
return new vtkMyCallback;
}
void Execute(vtkObject* caller, unsigned long, void*) override
{
auto renderer = reinterpret_cast<vtkRenderer*>(caller);
std::cout << renderer->GetActiveCamera()->GetPosition()[0] << " "
<< renderer->GetActiveCamera()->GetPosition()[1] << " "
<< renderer->GetActiveCamera()->GetPosition()[2] << std::endl;
}
vtkMyCallback() = default;
};
2、创建vtkCommand对象 ,经对象添加到需要监听的对象中
//渲染器对象
vtkNew<vtkRenderer> ren1;
vtkNew<vtkMyCallback> mo1;
ren1->AddObserver(vtkCommand::StartEvent, mo1);
五、完整示例
namespace {
class vtkMyCallback : public vtkCommand
{
public:
static vtkMyCallback* New()
{
return new vtkMyCallback;
}
void Execute(vtkObject* caller, unsigned long, void*) override
{
// Note the use of reinterpret_cast to cast the caller to the expected type.
auto renderer = reinterpret_cast<vtkRenderer*>(caller);
std::cout << renderer->GetActiveCamera()->GetPosition()[0] << " "
<< renderer->GetActiveCamera()->GetPosition()[1] << " "
<< renderer->GetActiveCamera()->GetPosition()[2] << std::endl;
}
vtkMyCallback() = default;
};
}
int main(int, char*[])
{
//创建VTK命名颜色
vtkNew<vtkNamedColors> colors;
//创建多边形圆锥体
vtkNew<vtkConeSource> cone;
cone->SetHeight(3.0);
cone->SetRadius(1.0);
cone->SetResolution(10);
//将多边形数据映射到圆形基于映射器
vtkNew<vtkPolyDataMapper> coneMapper;
coneMapper->SetInputConnection(cone->GetOutputPort());
//创建渲染创建中的实体(几何体和属性)
vtkNew<vtkActor> coneActor;
coneActor->SetMapper(coneMapper);
coneActor->GetProperty()->SetColor(colors->GetColor3d("MistyRose").GetData());
//创建渲染器
vtkNew<vtkRenderer> ren1;
ren1->AddActor(coneActor);
ren1->SetBackground(colors->GetColor3d("MidnightBlue").GetData());
ren1->ResetCamera();
//为渲染器创建绘制窗口
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer(ren1);
renWin->SetSize(300, 300);
renWin->SetWindowName("Tutorial_Step2");
//注册监听的事件及回调
vtkNew<vtkMyCallback> mo1;
ren1->AddObserver(vtkCommand::StartEvent, mo1);
for (int i = 0; i < 360; ++i)
{
renWin->Render();
ren1->GetActiveCamera()->Azimuth(1);
}
return EXIT_SUCCESS;
}
运行结果,物体旋转的同时,打印数据:
15.2107 1 0
15.2084 1 -0.265464
15.2014 1 -0.530846
15.1899 1 -0.796067
15.1737 1 -1.06105
15.1528 1 -1.3257
15.1274 1 -1.58995
15.0973 1 -1.85372
15.0627 1 -2.11692
15.0234 1 -2.37948
14.9796 1 -2.64131
14.9312 1 -2.90234
14.8783 1 -3.16248
14.8209 1 -3.42167
14.7589 1 -3.6798
14.6924 1 -3.93682
14.6215 1 -4.19264
14.5461 1 -4.44718
14.4662 1 -4.70037
14.382 1 -4.95212
14.2934 1 -5.20237
14.2004 1 -5.45103