Skip to content

ReadPolyData

Description

Given a filename, uses the appropriate vtkPolyData reader to read any vtkPolyData file.

To use the snippet, click the Copy to clipboard at the upper right of the code blocks.

Declaration Section

// Readers
#include <vtkBYUReader.h>
#include <vtkOBJReader.h>
#include <vtkPLYReader.h>
#include <vtkPolyDataReader.h>
#include <vtkSTLReader.h>
#include <vtkXMLPolyDataReader.h>

#include <vtkPolyData.h>
#include <vtkSphereSource.h>

#include <algorithm>  // For transform()
#include <cctype>     // For to_lower
#include <iostream>   // For std::err
#include <filesystem> // For extracting parts of the filename
#include <string>     // For find_last_of()

namespace fs = std::filesystem;

namespace {

vtkSmartPointer<vtkPolyData> ReadPolyData(std::string const& fileName);

}

Implementation Section

namespace {

vtkNew<vtkPolyData> ReadPolyData(fs::path const& path)
{

  vtkNew<vtkPolyData> polyData;

  std::string extension = path.extension().generic_string();
  std::transform(extension.begin(), extension.end(), extension.begin(),
                 [](char c) { return std::tolower(c); });

  if (extension == ".ply")
  {
    vtkNew<vtkPLYReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".vtp")
  {
    vtkNew<vtkXMLPolyDataReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".obj")
  {
    vtkNew<vtkOBJReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".stl")
  {
    vtkNew<vtkSTLReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".vtk")
  {
    vtkNew<vtkPolyDataReader> reader;
    reader->SetFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else if (extension == ".g")
  {
    vtkNew<vtkBYUReader> reader;
    reader->SetGeometryFileName(path.generic_string().c_str());
    reader->Update();
    polyData->DeepCopy(reader->GetOutput());
  }
  else
  {
    std::cerr << "Warning: " << path
              << " unknown extension, using a sphere instead." << std::endl;
    vtkNew<vtkSphereSource> source;
    source->SetPhiResolution(50);
    source->SetThetaResolution(50);
    source->Update();
    polyData->DeepCopy(source->GetOutput());
  }
  return polyData;
}


} // namespace