Skip to content

CameraOrientationWidget

Repository source: CameraOrientationWidget


Description

This example demonstrates the usage and versatility of the vtkCameraOrientationWidget, also, for comparison, a vtkOrientationMarkerWidget is provided.

The ability to automatically change axes labels and colors depending upon the object being viewed is demonstrated. To do this, just load any one of the following files from the vtk-examples testing data.

"Human.vtp", "Torso.vtp", "cow.vtp", "cowHead.vtp", "horse.vtp", "Bunny.vtp"

These files are found in vtk-examples/src/Testing/Data.

If no file name is entered, a cone is rendered.

The option -r will move the camera orientation marker to upper left and the orientation marker widget to upper right.

The vtkCameraOrientationWidget has shafts and little spheres with text on them. The spheres always follow the camera.

The widget representation's orientation is synchronized with the camera of the parent renderer.

To look down on any particular axis, simply click on a handle.

To rotate the camera and get a feel of the camera orientation, either move the mouse in the render window or click on a handle and move it around.

Some history:

  • The vtkCameraOrientationWidget was introduced in the MR: !8156, 18 July, 2021.
  • Labelling of the vertices was introduced in the MR: !11665, 16 November, 2024.
  • Coloring of the vertices was introduced in the MR: !12489, 01 October, 2025

Other languages

See (Python), (PythonicAPI)

Question

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

Code

CameraOrientationWidget.cxx

#include <vtkActor.h>
#include <vtkAxesActor.h>
#include <vtkBYUReader.h>
#include <vtkCamera.h>
#include <vtkCameraOrientationRepresentation.h>
#include <vtkCameraOrientationWidget.h>
#include <vtkConeSource.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkOBJReader.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkPLYReader.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataReader.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSTLReader.h>
#include <vtkSphereSource.h>
#include <vtkTransform.h>
#include <vtkTransformFilter.h>
#include <vtkXMLPolyDataReader.h>

#include <vtk_cli11.h>
#include <vtk_fmt.h>
// clang-format off
#include VTK_FMT(fmt/format.h)
// clang-format on

// #include <algorithm> // For transform() and std::set_union
// #include <array>
// #include <cctype> // For to_lower
// #include <cmath>
// #include <filesystem>
// #include <map>
// #include <set>
// #include <string> // For find_last_of()
// #include <vector>

namespace fs = std::filesystem;

namespace {

typedef std::map<std::string, std::string> TAxisParams;
typedef std::map<std::string, TAxisParams> TAxesParams;

/**
 * Use a vtk file reader to get the polydata.
 *
 * @param path The filesystem path to the file.
 *
 * @return The polydata
 */
vtkSmartPointer<vtkPolyData> ReadPolyData(fs::path const& path);

TAxesParams SetAxesLabels();

TAxesParams SetAxesColors(vtkNamedColors* colors);

/**
 * Gather the axes labels and colors into a map.
 *
 * @param colors A reference to the vtkNamedColors object.
 *
 * @return The map of axes labels and colors.
 */
std::map<std::string, std::pair<TAxisParams, TAxisParams>>
GetAxesParams(vtkNamedColors* colors);

/**
 * Make a camera orientation widget for a given renderer.
 *
 * @param ren The renderer.
 * @param alc A map of labels and colors for the axes.
 * @param colors A reference to the vtkNamedColors object.
 * @param reposition Move the camera orientation widget to upper left.
 *
 * @return The camera orientation widget.
 */
vtkSmartPointer<vtkCameraOrientationWidget> MakeCameraOrientationWidget(
    vtkRenderer* ren, std::pair<TAxisParams, TAxisParams>& alc,
    vtkNamedColors* colors, bool const& reposition = false);

/**
 * Make an axis actor.
 *
 * @param alc A map of labels and colors for the axes.
 * @param colors A reference to the vtkNamedColors object.
 *
 * @return The camera orientation widget.
 */
vtkSmartPointer<vtkAxesActor>
MakeAxesActor(std::pair<TAxisParams, TAxisParams>& alc, vtkNamedColors* colors);

/**
 * Make an orientation marker for a given renderer.
 *
 * @param ren The renderer.
 * @param iren The interactor.
 * @param alc A map of labels and colors for the axes.
 * @param colors A reference to the vtkNamedColors object.
 * @param reposition Move the orientation marker widget to upper right.
 *
 * @return: The orientation marker widget.
 */
vtkSmartPointer<vtkOrientationMarkerWidget> MakeOrientationMarkerWidget(
    vtkRenderer* renderer, vtkRenderWindowInteractor* iren,
    std::pair<TAxisParams, TAxisParams>& alc, vtkNamedColors* colors,
    bool const& reposition = false);

} // namespace

int main(int argc, char* argv[])
{

  vtkNew<vtkNamedColors> colors;
  colors->SetColor("ParaViewBlueGrayBkg",
                   std::array<unsigned char, 4>{84, 89, 109, 255}.data());
  colors->SetColor("ParaViewWarmGrayBkg",
                   std::array<unsigned char, 4>{98, 93, 90, 255}.data());

  CLI::App app{"Demonstrates the use of the Camera Orientation Widget."};

  // Define options.
  std::string fileName{""};
  app.add_option("fileName", fileName,
                 "A optional path to a file that contains vtkPolyData e.g. "
                 "Human.vtp");
  auto reposition{false};
  app.add_flag("-r, --reposition", reposition,
               "Move the camera orientation widget to upper left"
               " and the orientation marker widget to upper right.");

  CLI11_PARSE(app, argc, argv);

  auto path = fs::path(fileName);
  if (!path.empty())
  {
    if (!fs::is_regular_file(path))
    {
      std::cerr << fmt::format("Unable to find: {:s}", path.string())
                << std::endl;
      return EXIT_FAILURE;
    }
  }
  auto polyData = ReadPolyData(path);

  // Assign a category for the labels and colors.
  std::string category = "xyz";
  if (fs::is_regular_file(path))
  {
    auto isIn = [](std::string const& a, std::vector<std::string> const& v) {
      auto it = std::find(v.cbegin(), v.cend(), a);
      return it != v.cend();
    };
    auto pth = path.filename().string();
    typedef std::vector<std::string> Tvs;
    if (isIn(pth, Tvs{"Human.vtp", "Torso.vtp"}))
    {
      category = "lrsiap";
    }
    else if (isIn(pth, Tvs{"horse.vtp", "Bunny.vtp"}))
    {
      category = "padvlr";
    }
    else if (isIn(pth, Tvs{"cow.vtp", "cowHead.vtp"}))
    {
      category = "apdvrl";
    }
  }

  // The labels and colors for the various axes.
  auto alc = GetAxesParams(colors);

  vtkNew<vtkTransform> tran;
  tran->Identity();

  if (!path.empty())
  {
    auto pth = path.filename().string();
    if (pth == "Human.vtp")
    {
      tran->RotateY(180);
      tran->RotateX(-90);
    }
    if (pth == "Torso.vtp")
    {
      tran->RotateX(-90);
    }
    if (pth == "horse.vtp")
    {
      tran->RotateX(-90);
      tran->RotateZ(90);
    }
  }
  vtkNew<vtkTransformFilter> tf;
  tf->SetTransform(tran);
  tf->SetInputData(polyData);

  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputConnection(tf->GetOutputPort());

  vtkNew<vtkActor> actor;
  actor->GetProperty()->SetColor(colors->GetColor3d("Tan").GetData());
  actor->SetMapper(mapper);

  vtkNew<vtkRenderer> ren;
  vtkNew<vtkRenderWindow> renWin;
  vtkNew<vtkRenderWindowInteractor> iRen;
  renWin->AddRenderer(ren);
  renWin->SetSize(600, 600);
  auto appFn = fs::path((app.get_name())).stem().string();
  if (path.empty())
  {
    renWin->SetWindowName(appFn.c_str());
  }
  else
  {
    auto winName = fmt::format("{:s} {:s}", appFn, path.filename().string());
    renWin->SetWindowName(winName.c_str());
  }

  // Important: The interactor must be set prior
  //  to enabling the Camera Orientation Widget.
  iRen->SetRenderWindow(renWin);

  ren->AddActor(actor);
  ren->SetBackground(colors->GetColor3d("ParaViewBLueGrayBkg").GetData());

  auto cow =
      MakeCameraOrientationWidget(ren, alc[category], colors, reposition);
  auto omw =
      MakeOrientationMarkerWidget(ren, iRen, alc[category], colors, reposition);
  ren->ResetCamera();
  renWin->Render();
  iRen->Initialize();
  iRen->Start();

  return EXIT_SUCCESS;
}

namespace {
vtkSmartPointer<vtkPolyData> ReadPolyData(fs::path const& path)
{
  auto pth = path.string();
  auto fp = pth.c_str();
  auto extension = path.extension().string();
  vtkSmartPointer<vtkPolyData> polyData;
  if (extension == ".ply")
  {
    vtkNew<vtkPLYReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtp")
  {
    vtkNew<vtkXMLPolyDataReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".obj")
  {
    vtkNew<vtkOBJReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".stl")
  {
    vtkNew<vtkSTLReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".vtk")
  {
    vtkNew<vtkPolyDataReader> reader;
    reader->SetFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else if (extension == ".g")
  {
    vtkNew<vtkBYUReader> reader;
    reader->SetGeometryFileName(fp);
    reader->Update();
    polyData = reader->GetOutput();
  }
  else
  {
    // Use a cone as a source with the golden ratio (φ) for the height.
    // Because we can!
    // If the short side is one then φ = 2 × sin(54°) or φ = 1/2 + √5 / 2
    vtkNew<vtkConeSource> source;
    source->SetCenter(0, 0, 0);
    source->SetRadius(1);
    source->SetHeight((1.0 + std::sqrt(5.0)) / 2.0);
    source->SetResolution(64);
    source->SetDirection(0, 1, 0);
    source->Update();
    polyData = source->GetOutput();
  }
  return polyData;
}

TAxesParams SetAxesLabels()
{
  TAxesParams axesLabels = {
      // Labels are: Anterior, Posterior, Dorsal, Ventral, Left, Right
      {"apdvlr",
       {{"+X", "A"},
        {"-X", "P"},
        {"+Y", "D"},
        {"-Y", "V"},
        {"+Z", "L"},
        {"-Z", "R"}}},
      {"apdvrl",
       {{"+X", "A"},
        {"-X", "P"},
        {"+Y", "D"},
        {"-Y", "V"},
        {"+Z", "R"},
        {"-Z", "L"}}},
      {"padvlr",
       {{"+X", "P"},
        {"-X", "A"},
        {"+Y", "D"},
        {"-Y", "V"},
        {"+Z", "L"},
        {"-Z", "R"}}},
      // Labels are: Left, Right, Superior, Inferior, Anterior, Posterior
      {"lrsiap",
       {{"+X", "L"},
        {"-X", "R"},
        {"+Y", "S"},
        {"-Y", "I"},
        {"+Z", "A"},
        {"-Z", "P"}}},
      // Default labels.
      {"xyz", {}},
  };
  return axesLabels;
}

TAxesParams SetAxesColors(vtkNamedColors* colors)
{
  TAxesParams axesColors = {
      {"apdvlr",
       {{"+X", "IndianRed"},
        {"-X", "FireBrick"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "Blue"},
        {"-Z", "SteelBlue"}}},
      {"apdvrl",
       {{"+X", "IndianRed"},
        {"-X", "FireBrick"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "Blue"},
        {"-Z", "SteelBlue"}}},
      {"padvlr",
       {{"+X", "IndianRed"},
        {"-X", "FireBrick"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "Blue"},
        {"-Z", "SteelBlue"}}},
      {"lrsiap",
       {{"+X", "Blue"},
        {"-X", "SteelBlue"},
        {"+Y", "LimeGreen"},
        {"-Y", "DarkGreen"},
        {"+Z", "IndianRed"},
        {"-Z", "FireBrick"}}},
      // Default colors.
      {"xyz", {}},
  };
  return axesColors;
}

std::map<std::string, std::pair<TAxisParams, TAxisParams>>
GetAxesParams(vtkNamedColors* colors)
{
  // The keys must be the same.
  auto axesLabels = SetAxesLabels();
  auto axesColors = SetAxesColors(colors);
  // Get the keys.
  std::set<std::string> labelKeys;
  for (auto&& label : axesLabels)
  {
    labelKeys.insert(label.first);
  }
  std::set<std::string> colorKeys;
  for (auto&& label : axesLabels)
  {
    colorKeys.insert(label.first);
  }
  std::vector<std::string> commonKeys;
  std::set_intersection(labelKeys.begin(), labelKeys.end(), colorKeys.begin(),
                        colorKeys.end(), std::back_inserter(commonKeys));
  std::map<std::string, std::pair<TAxisParams, TAxisParams>> alc;
  for (auto&& k : commonKeys)
  {
    alc[k] = std::pair<TAxisParams, TAxisParams>{axesLabels[k], axesColors[k]};
  }

  return alc;
};

vtkSmartPointer<vtkCameraOrientationWidget>
MakeCameraOrientationWidget(vtkRenderer* ren,
                            std::pair<TAxisParams, TAxisParams>& alc,
                            vtkNamedColors* colors, bool const& reposition)
{

  vtkNew<vtkCameraOrientationWidget> cow;
  cow->SetParentRenderer(ren);
  cow->EnabledOn();
  cow->On();

  vtkNew<vtkCameraOrientationRepresentation> rep;

  if (reposition)
  {
    // Position upper left in the viewport.
    rep->AnchorToUpperLeft();
  }

  if (!alc.first.empty())
  {
    rep->SetXPlusLabelText(alc.first["+X"]);
    rep->SetXMinusLabelText(alc.first["-X"]);
    rep->SetYPlusLabelText(alc.first["+Y"]);
    rep->SetYMinusLabelText(alc.first["-Y"]);
    rep->SetZPlusLabelText(alc.first["+Z"]);
    rep->SetZMinusLabelText(alc.first["-Z"]);

    rep->SetXAxisColor(colors->GetColor3d(alc.second["+X"]).GetData());
    rep->SetYAxisColor(colors->GetColor3d(alc.second["+Y"]).GetData());
    rep->SetZAxisColor(colors->GetColor3d(alc.second["+Z"]).GetData());
  }

  cow->SetRepresentation(rep);

  return cow;
}

vtkSmartPointer<vtkAxesActor>
MakeAxesActor(std::pair<TAxisParams, TAxisParams>& alc, vtkNamedColors* colors)
{
  vtkNew<vtkAxesActor> axes;

  if (alc.first.empty())
  {
    // Use the default vtkOrientationMarkerWidget
    return axes;
  }

  axes->SetXAxisLabelText(alc.first["+X"].c_str());
  axes->SetYAxisLabelText(alc.first["+Y"].c_str());
  axes->SetZAxisLabelText(alc.first["+Z"].c_str());

  auto xShaftProp = axes->GetXAxisShaftProperty();
  xShaftProp->SetColor(colors->GetColor3d(alc.second["+X"]).GetData());
  auto xTipProp = axes->GetXAxisTipProperty();
  xTipProp->SetColor(colors->GetColor3d(alc.second["+X"]).GetData());

  auto yShaftProp = axes->GetYAxisShaftProperty();
  yShaftProp->SetColor(colors->GetColor3d(alc.second["+Y"]).GetData());
  auto yTipProp = axes->GetYAxisTipProperty();
  yTipProp->SetColor(colors->GetColor3d(alc.second["+Y"]).GetData());

  auto zShaftProp = axes->GetZAxisShaftProperty();
  zShaftProp->SetColor(colors->GetColor3d(alc.second["+Z"]).GetData());
  auto zTipProp = axes->GetZAxisTipProperty();
  zTipProp->SetColor(colors->GetColor3d(alc.second["+Z"]).GetData());
  return axes;
}

vtkSmartPointer<vtkOrientationMarkerWidget>
MakeOrientationMarkerWidget(vtkRenderer* ren, vtkRenderWindowInteractor* iren,
                            std::pair<TAxisParams, TAxisParams>& alc,
                            vtkNamedColors* colors, bool const& reposition)
{
  vtkNew<vtkOrientationMarkerWidget> om;
  auto axesActor = MakeAxesActor(alc, colors);
  om->SetOrientationMarker(axesActor);
  if (reposition)
  {
    // Position upper right in the viewport.
    om->SetViewport(0.8, 0.8, 1.0, 1.0);
  }
  else
  {
    std::cout << "Lower left." << std::endl;
    // Position lower left in the viewport.
    om->SetViewport(0, 0, 0.2, 0.2);
  }
  om->SetInteractor(iren);
  om->SetDefaultRenderer(ren);
  om->EnabledOn();
  om->InteractiveOn();

  return om;
}

} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(CameraOrientationWidget)

find_package(VTK COMPONENTS 
  CommonColor
  CommonCore
  IOXML
  InteractionStyle
  InteractionWidgets
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "CameraOrientationWidget: 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(CameraOrientationWidget MACOSX_BUNDLE CameraOrientationWidget.cxx )
  target_link_libraries(CameraOrientationWidget PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS CameraOrientationWidget
  MODULES ${VTK_LIBRARIES}
)

Download and Build CameraOrientationWidget

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

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

./CameraOrientationWidget

WINDOWS USERS

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