Skip to content

VectorNorm

vtk-examples/Cxx/Math/VectorNorm

Question

If you have a question about this example, please use the VTK Discourse Forum

Code

VectorNorm.cxx

#include <vtkFloatArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkVectorNorm.h>

// For compatibility with new VTK generic data arrays
#ifdef vtkGenericDataArray_h
#define InsertNextTupleValue InsertNextTypedTuple
#endif

int main(int, char*[])
{
  vtkNew<vtkPoints> points;
  points->InsertNextPoint(1, 2, 3);
  points->InsertNextPoint(4, 5, 6);

  vtkNew<vtkPolyData> polydata;
  polydata->SetPoints(points);

  vtkNew<vtkFloatArray> distances;
  distances->SetNumberOfComponents(3);
  distances->SetName("Distances");

  float v1[3] = {1, 2, 3};
  float v2[3] = {4, 5, 6};
  distances->InsertNextTupleValue(v1);
  distances->InsertNextTupleValue(v2);

  polydata->GetPointData()->SetVectors(distances);

  vtkNew<vtkVectorNorm> vectorNorm;
  vectorNorm->SetInputData(polydata);
  vectorNorm->Update();

  vtkFloatArray* scalars = dynamic_cast<vtkFloatArray*>(
      vectorNorm->GetOutput()->GetPointData()->GetScalars());

  for (vtkIdType i = 0; i < scalars->GetNumberOfTuples(); i++)
  {
    std::cout << "Value " << i << " : " << scalars->GetValue(i) << std::endl;
  }

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(VectorNorm)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
  FiltersCore
  QUIET
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "VectorNorm: Unable to find the VTK build folder.")
endif()

# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(VectorNorm MACOSX_BUNDLE VectorNorm.cxx )
  target_link_libraries(VectorNorm PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS VectorNorm
  MODULES ${VTK_LIBRARIES}
)

Download and Build VectorNorm

Click here to download VectorNorm and its CMakeLists.txt file. Once the tarball VectorNorm.tar has been downloaded and extracted,

cd VectorNorm/build

If VTK is installed:

cmake ..

If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..

Build the project:

make

and run it:

./VectorNorm

WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.