Search code examples
c++vtk

How to write scalar filed with VTK in C++?


I am starting to learn about VTK. I would like to write an scalar field in a .vts file. The structured grid is being generated with the code included below.

I tried finding information on the user guide and tutorials but I was not able to do it.

// Create a grid
vtkSmartPointer<vtkStructuredGrid> structuredGrid = vtkSmartPointer<vtkStructuredGrid>::New();

vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
unsigned int numi = 20;
unsigned int numj = 30;
unsigned int numk = 1;

for (unsigned int k = 0; k < numk; k++) {
    for (unsigned int j = 0; j < numj; j++) {
        for (unsigned int i = 0; i < numi; i++) {
            points->InsertNextPoint(i, j, k);
        }
    }
}

// Specify the dimensions of the grid
structuredGrid->SetDimensions(numi, numj, numk);
structuredGrid->SetPoints(points);

// Write file
vtkSmartPointer<vtkXMLStructuredGridWriter> writer = vtkSmartPointer<vtkXMLStructuredGridWriter>::New();
writer->SetFileName("output.vts");
writer->SetInputData(structuredGrid);
writer->Write();

Solution

  • Scalar can be set for attribute PointData of vtkStructuredGrid object.
    Then vtkXMLStructuredGridWriter object writes structuredGrid in vts file just as this:

        vtkFloatArray *scalars = vtkFloatArray::New();
        for (int i=0; i< numi*numj*numk; i++) scalars->InsertTuple1(i, 1.0 * i /(numi*numj*numk));
        structuredGrid->GetPointData()->SetScalars( scalars );
    
        // Write file
        vtkSmartPointer<vtkXMLStructuredGridWriter> writer = vtkSmartPointer<vtkXMLStructuredGridWriter>::New();
        writer->SetFileName("output.vts");
        writer->SetInputData(structuredGrid);
        writer->Write();