# CardinalSpline

VTKExamples/Cxx/Utilities/CardinalSpline

### Description¶

This example takes two points that have associated scalar values and allows you to interpolate the value at any point on the line between them using cardinal spline interpolation.

Question

### Code¶

CardinalSpline.cxx

#include <vtkSmartPointer.h>
#include <vtkCardinalSpline.h>
#include <vtkFloatArray.h>

int main(int, char *[])
{
// Create a scalar array.  The array could be associated with the scalars of a vtkDataSet
vtkSmartPointer<vtkFloatArray> distances =
vtkSmartPointer<vtkFloatArray>::New();
distances->SetNumberOfComponents(1);
distances->SetName("Distances");
distances->InsertNextValue(100.0);
distances->InsertNextValue(300.0);

// Create a cardinal spline to show how to linearly interpolate between two scalar values
vtkSmartPointer<vtkCardinalSpline> spline =
vtkSmartPointer<vtkCardinalSpline>::New();
spline->ClosedOff();

// Set the left and right second derivatives to 0 corresponding to linear interpolation
spline->SetLeftConstraint(2);
spline->SetLeftValue(0);
spline->SetRightConstraint(2);
spline->SetRightValue(0);
double* r = distances->GetRange();
double xmin = r;
double xmax = r;
double length = xmax-xmin;
for( vtkIdType i = 0; i < distances->GetNumberOfTuples(); ++i )
{
double x = distances->GetTuple1(i);
double t = (x - xmin)/length;
}

// Evaluate every 50 distance units along the line
std::cout << "Spline interpolation:" << std::endl;
double dt = .25;
for( double t = dt ; t <= 1. - dt; t += dt )
{
std::cout << "t: " << t << " value = " << spline->Evaluate(t) << std::endl;
}

return EXIT_SUCCESS;
}


### CMakeLists.txt¶

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)

project(CardinalSpline)

find_package(VTK COMPONENTS
vtkCommonComputationalGeometry
vtkCommonCore QUIET)
if (NOT VTK_FOUND)
message("Skipping CardinalSpline: ${VTK_NOT_FOUND_MESSAGE}") return () endif() message (STATUS "VTK_VERSION:${VTK_VERSION}")
if (VTK_VERSION VERSION_LESS "8.90.0")
# old system
include(${VTK_USE_FILE}) add_executable(CardinalSpline MACOSX_BUNDLE CardinalSpline.cxx ) target_link_libraries(CardinalSpline PRIVATE${VTK_LIBRARIES})
else ()
# include all components
target_link_libraries(CardinalSpline PRIVATE ${VTK_LIBRARIES}) # vtk_module_autoinit is needed vtk_module_autoinit( TARGETS CardinalSpline MODULES${VTK_LIBRARIES}
)
endif ()


cd CardinalSpline/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:

./CardinalSpline


WINDOWS USERS

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