Skip to content

GradientBackground

Repository source: GradientBackground


Description

Demonstrates the gradient backgrounds available in VTK.

The gradient background modes are:

  • Vertical
  • Horizontal
  • Radial Farthest Side
  • Radial Farthest Corner

The user can also edit the code to change the stop colors marking the beginning and end points in a gradient.

An option is provided for the user to read in a data file so that more interesting objects can be viewed.

The viewport border can also be set and colored.

For more information, see New in VTK 9.3: Radial Gradient Background

!!! note VTK 9.3 or later is required.

!!! note The C++ version requires C++ 17 or later as std::filesystem is used.

Other languages

See (Python), (PythonicAPI)

Question

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

Code

GradientBackground.cxx

// Based on:
//  https://gitlab.kitware.com/vtk/vtk/-/blob/master/Rendering/Core/Testing/Cxx/TestGradientBackground.cxx?ref_type=heads
// See:
//  [New in VTK 9.3: Radial Gradient
//  Background](https://www.kitware.com/new-in-vtk-9-3-radial-gradient-background/)

#include <vtkActor.h>
#include <vtkActor2D.h>
#include <vtkColor.h>
#include <vtkConeSource.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSphereSource.h>
#include <vtkTextActor.h>
#include <vtkTextMapper.h>
#include <vtkTextProperty.h>
#include <vtkTextRepresentation.h>
#include <vtkTextWidget.h>
#include <vtkViewport.h>
#include <vtk_cli11.h>

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

#include <algorithm>
#include <array>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <string>

namespace fs = std::filesystem;

namespace {

/**
 * @brief ReadPolyData Read from a file containing vtkPolyData.
 *
 * ReadPolyData
 *    If the path is empty a cone is returned.
 *    If the extension is unknown a sphere is returned.
 *
 * @param path - The std::filesystem path to the file.
 * @return The vtkPolyData.
 */
vtkNew<vtkPolyData> ReadPolyData(fs::path const& path);

/** Specify the rules for drawing the borders around a viewport.
 *
 * Here the borders for the viewports are defined in the order
 *  [top, left, bottom, right].
 *
 * Names for adjacent sides reflect anticlockwise ordering.
 */
static constexpr struct ViewportBorderSpecifier
{
  std::array<bool, 4> t{true, false, false, false};
  std::array<bool, 4> l{false, true, false, false};
  std::array<bool, 4> b{false, false, true, false};
  std::array<bool, 4> r{false, false, false, true};
  std::array<bool, 4> lb{false, true, true, false};
  std::array<bool, 4> lbr{false, true, true, true};
  std::array<bool, 4> tlb{true, true, true, false};
  std::array<bool, 4> tlbr{true, true, true, true};
  std::array<bool, 4> rtl{true, true, false, true};
  std::array<bool, 4> tl{true, true, false, false};
} viewportBorderSpecifier;

/** Draw a border around a viewport.
 *
 * @param renderer: The renderer corresponding to the viewport.
 * @param sides: An array of boolean corresponding to [top, left, bottom, right]
 * @param border_color: The color of the border.
 * @param border_width: The width of the border.
 * @return The border actor.
 */
vtkNew<vtkActor2D> DrawViewportBorder(std::array<bool, 4> const& sides,
                                      std::string const& border_color,
                                      unsigned int const& border_width);

typedef std::map<std::string, std::array<double, 2>> TTextPosition;
typedef std::map<std::string, TTextPosition> TTextPositions;

/** Get viewport positioning information for a vector of names.
 *
 * Note: You must include vtkSystemIncludes.h to get these defines:
 *  VTK_TEXT_LEFT 0, VTK_TEXT_CENTERED 1, VTK_TEXT_RIGHT 2,
 *  VTK_TEXT_BOTTOM 0, VTK_TEXT_TOP 2
 *
 *  @param names - The vector of names.
 *  @param justification - Horizontal justification of the text.
 *  @param vertical_justification - Vertical justification of the text.
 *  @param width - Width of the bounding_box of the text in screen coordinates.
 *  @param height - Height of the bounding_box of the text in screen
 *                  coordinates.
 *  @return A map of positioning information for exch name in names.
 */
TTextPositions
GetTextPositions(std::vector<std::string> const& names,
                 int const justification = VTK_TEXT_LEFT,
                 int const vertical_justification = VTK_TEXT_BOTTOM,
                 double const width = 0.96, double const height = 0.1);

} // namespace

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

  CLI::App app{"Demonstrates the background shading options."};

  // Define options
  std::string fileName{""};
  app.add_option("fileName", fileName,
                 "A optional path to a file that contains vtkPolyData e.g. "
                 "star-wars-vader-tie-fighter.obj");
  CLI11_PARSE(app, argc, argv);

  auto path = fs::path(fileName);
  if (!path.empty())
  {
    if (!fs::is_regular_file(path))
    {
      std::cerr << "Unable to find: " << path << std::endl;
      return EXIT_FAILURE;
    }
  }

  vtkNew<vtkNamedColors> colors;

  // This defaults to a cone if the path is empty.
  auto pd = ReadPolyData(path);

  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputData(pd);

  vtkNew<vtkActor> actor;
  actor->SetMapper(mapper);
  actor->GetProperty()->SetColor(colors->GetColor3d("Honeydew").GetData());
  actor->GetProperty()->SetSpecular(0.3);
  actor->GetProperty()->SetSpecularPower(60.0);

  // Here we select and name the colors.
  // Feel free to change colors.
  const auto bottomColor = colors->GetColor3d("Gold");
  const auto topColor = colors->GetColor3d("OrangeRed");
  const auto leftColor = colors->GetColor3d("Gold");
  const auto rightColor = colors->GetColor3d("OrangeRed");
  const auto centerColor = colors->GetColor3d("Gold");
  const auto sideColor = colors->GetColor3d("OrangeRed");
  const auto cornerColor = colors->GetColor3d("OrangeRed");

  // For each gradient specify the mode.
  vtkViewport::GradientModes gradientModes[4] = {
      vtkViewport::GradientModes::VTK_GRADIENT_VERTICAL,
      vtkViewport::GradientModes::VTK_GRADIENT_HORIZONTAL,
      vtkViewport::GradientModes::VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_SIDE,
      vtkViewport::GradientModes::VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_CORNER,
  };

  const std::vector<std::string> viewportTitles{"Vertical", "Horizontal",
                                                "Radial Farthest Side",
                                                "Radial Farthest Corner"};

  // Position text according to its length and centered in the viewport.
  auto textPositions = GetTextPositions(viewportTitles, VTK_TEXT_CENTERED);

  // Setup viewports for the renderers.
  size_t xGridDimensions = 2;
  size_t yGridDimensions = 2;
  size_t width = 640;
  size_t height = 480;

  auto lastCol{false};
  auto lastRow{false};
  auto blank = viewportTitles.size();

  // Specify what borders will be drawn around each viewport.
  struct VP
  {
    std::string name{""};
    // Viewport dimensions [xmin, ymin, xmax, ymax].
    std::array<double, 4> viewport{0.0, 0.0, 0.0, 0.0};
    // What borders will be drawn around the viewport.
    std::array<bool, 4> border{false, false, false, false};
  };
  std::map<unsigned int, VP> viewports;

  for (unsigned int row = 0; row < yGridDimensions; ++row)
  {
    if (row == yGridDimensions - 1)
    {
      lastRow = true;
    }
    for (unsigned int col = 0; col < xGridDimensions; ++col)
    {
      if (col == xGridDimensions - 1)
      {
        lastCol = true;
      }
      auto index = row * xGridDimensions + col;

      // (xmin, ymin, xmax, ymax)
      std::array<double, 4> viewport{
          static_cast<double>(col) / xGridDimensions,
          static_cast<double>(yGridDimensions - (row + 1)) / yGridDimensions,
          static_cast<double>(col + 1) / xGridDimensions,
          static_cast<double>(yGridDimensions - row) / yGridDimensions};

      // Decide what borders will be drawn around the viewport.
      std::array<bool, 4> border;
      if (lastRow && lastCol)
      {
        border = viewportBorderSpecifier.tlbr;
        lastRow = false;
        lastCol = false;
      }
      else if (lastCol)
      {
        border = viewportBorderSpecifier.rtl;
        lastCol = false;
      }
      else if (lastRow)
      {
        border = viewportBorderSpecifier.tlb;
      }
      else
      {
        border = viewportBorderSpecifier.tl;
      }
      if (index < blank)
      {
        viewports[index] = {viewportTitles[index], viewport, border};
      }
      else
      {
        viewports[index] = {"", viewport, border};
      }
    }
  }

  vtkNew<vtkRenderWindow> renWin;
  renWin->SetWindowName("GradientBackground");
  renWin->SetSize(width, height);

  vtkNew<vtkRenderWindowInteractor> iRen;
  iRen->SetRenderWindow(renWin);
  vtkNew<vtkInteractorStyleTrackballCamera> style;
  iRen->SetInteractorStyle(style);

  // Create a common text property for all.
  vtkNew<vtkTextProperty> textProperty;
  textProperty->SetColor(colors->GetColor3d("MidnightBlue").GetData());
  textProperty->BoldOff();
  textProperty->ItalicOff();
  textProperty->ShadowOff();
  textProperty->SetFontFamilyAsString("Courier");
  textProperty->SetFontSize(12);
  textProperty->SetJustificationToCentered();
  textProperty->SetVerticalJustificationToCentered();

  std::string borderColor = "DarkGreen";
  auto borderWidth = 4.0;

  std::vector<vtkSmartPointer<vtkTextWidget>> textWidgets;

  // Create and link the mappers actors and renderers together.
  for (unsigned int index = 0; index < viewports.size(); ++index)
  {

    auto name = viewports[index].name;
    auto viewport = viewports[index].viewport;
    auto border = viewports[index].border;

    vtkNew<vtkRenderer> renderer;
    renderer->SetViewport(viewport.data());
    renderer->SetBackground(bottomColor.GetData());
    auto borderActor = DrawViewportBorder(border, "Black", borderWidth);
    renderer->AddViewProp(borderActor);
    if (name.empty())
    {
      // Add a renderer even if the border is the only actor.
      // This makes the render window backgrounds all the same color.
      renWin->AddRenderer(renderer);
      continue;
    }
    renderer->GradientBackgroundOn();
    renderer->SetGradientMode(gradientModes[index]);

    switch (index)
    {
    case 1:
      renderer->SetBackground(leftColor.GetData());
      renderer->SetBackground2(rightColor.GetData());
      break;
    case 2:
      renderer->SetBackground(centerColor.GetData());
      renderer->SetBackground2(sideColor.GetData());
      break;
    case 3:
      renderer->SetBackground(centerColor.GetData());
      renderer->SetBackground2(cornerColor.GetData());
      break;
    default:
      // Vertical
      renderer->SetBackground(bottomColor.GetData());
      renderer->SetBackground2(topColor.GetData());
      break;
    }

    renderer->AddActor(actor);

    // Create the text actor and representation.
    vtkNew<vtkTextActor> textActor;
    textActor->SetInput(name.c_str());
    textActor->SetTextScaleModeToNone();
    textActor->SetTextProperty(textProperty);

    // Create the text representation. Used for positioning the text actor.
    vtkNew<vtkTextRepresentation> textRepresentation;
    textRepresentation->EnforceNormalizedViewportBoundsOn();
    textRepresentation->GetPositionCoordinate()->SetValue(
        textPositions[name]["p"].data());
    textRepresentation->GetPosition2Coordinate()->SetValue(
        textPositions[name]["p2"].data());

    // Create the text widget, setting the default renderer and interactor.
    vtkNew<vtkTextWidget> textWidget;
    textWidget->SetRepresentation(textRepresentation);
    textWidget->SetDefaultRenderer(renderer);
    textWidget->SetInteractor(iRen);
    textWidget->SetTextActor(textActor);
    textWidget->SelectableOff();
    textWidget->ResizableOn();

    textWidgets.push_back(textWidget);
    renWin->AddRenderer(renderer);
  }

  for (auto& tw : textWidgets)
  {
    tw->On();
  }

  // renWin->SetInteractor(iRen);
  renWin->Render();

  // iRen->Initialize();
  iRen->UpdateSize(width * 2, height * 2);
  iRen->Start();

  return EXIT_SUCCESS;
}

namespace {

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

  vtkNew<vtkPolyData> polyData;

  if (path.empty())
  {
    // Default to a cone if the path is empty.
    vtkNew<vtkConeSource> source;
    source->SetResolution(25);
    source->SetDirection(0, 1, 0);
    source->SetHeight(1);
    source->Update();
    polyData->DeepCopy(source->GetOutput());
    return 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;
}

vtkNew<vtkActor2D> DrawViewportBorder(std::array<bool, 4> const& sides,
                                      std::string const& border_color,
                                      unsigned int const& border_width)
{
  vtkNew<vtkNamedColors> colors;

  // Points start at upper right and proceed anti-clockwise.
  vtkNew<vtkPoints> points;
  points->InsertPoint(0, 1, 1, 0);
  points->InsertPoint(1, 0, 1, 0);
  points->InsertPoint(2, 0, 0, 0);
  points->InsertPoint(3, 1, 0, 0);

  vtkNew<vtkCellArray> cells;

  if (sides[0])
  {
    // Top
    vtkNew<vtkPolyLine> top;
    top->GetPointIds()->SetNumberOfIds(2);
    top->GetPointIds()->SetId(0, 0);
    top->GetPointIds()->SetId(1, 1);
    cells->InsertNextCell(top);
  }
  if (sides[1])
  {
    // Left
    vtkNew<vtkPolyLine> left;
    left->GetPointIds()->SetNumberOfIds(2);
    left->GetPointIds()->SetId(0, 1);
    left->GetPointIds()->SetId(1, 2);
    cells->InsertNextCell(left);
  }
  if (sides[2])
  {
    // Bottom
    vtkNew<vtkPolyLine> bottom;
    bottom->GetPointIds()->SetNumberOfIds(2);
    bottom->GetPointIds()->SetId(0, 2);
    bottom->GetPointIds()->SetId(1, 3);
    cells->InsertNextCell(bottom);
  }
  if (sides[3])
  {
    // Right
    vtkNew<vtkPolyLine> right;
    right->GetPointIds()->SetNumberOfIds(2);
    right->GetPointIds()->SetId(0, 3);
    right->GetPointIds()->SetId(1, 0);
    cells->InsertNextCell(right);
  }

  // Now make the polydata and display it.
  vtkNew<vtkPolyData> poly;
  poly->SetPoints(points);
  poly->SetLines(cells);

  // Use normalized viewport coordinates since
  // they are independent of window size.
  vtkNew<vtkCoordinate> coordinate;
  coordinate->SetCoordinateSystemToNormalizedViewport();

  vtkNew<vtkPolyDataMapper2D> mapper;
  mapper->SetInputData(poly);
  mapper->SetTransformCoordinate(coordinate);

  vtkNew<vtkActor2D> actor;
  actor->SetMapper(mapper);
  actor->GetProperty()->SetColor(colors->GetColor3d(border_color).GetData());
  // Line width should be at least 2 to be visible at extremes.
  actor->GetProperty()->SetLineWidth(border_width);

  return actor;
}

TTextPositions GetTextPositions(std::vector<std::string> const& names,
                                int const justification,
                                int const vertical_justification,
                                double const width, double const height)
{
  // The gap between the left or right edge of the screen and the text.
  auto dx = 0.02;
  auto w = abs(width);
  if (w > 0.96)
  {
    w = 0.96;
  }

  auto y0 = 0.01;
  auto h = abs(height);
  if (h > 0.9)
  {
    h = 0.9;
  }
  auto dy = h;
  if (vertical_justification == VTK_TEXT_TOP)
  {
    y0 = 1.0 - (dy + y0);
  }
  if (vertical_justification == VTK_TEXT_CENTERED)
  {
    y0 = 0.5 - (dy / 2.0 + y0);
  }

  auto minmaxIt =
      std::minmax_element(names.begin(), names.end(),
                          [](const std::string& a, const std::string& b) {
                            return a.length() < b.length();
                          });

  // auto nameLenMin = minmaxIt.first->size();
  auto nameLenMax = minmaxIt.second->size();

  TTextPositions textPositions;
  for (const auto& k : names)
  {
    auto sz = k.size();
    auto delta_sz = w * sz / nameLenMax;
    if (delta_sz > w)
    {
      delta_sz = w;
    }

    double x0 = 0;
    if (justification == VTK_TEXT_CENTERED)
    {
      x0 = 0.5 - delta_sz / 2.0;
    }
    else if (justification == VTK_TEXT_RIGHT)
    {
      x0 = 1.0 - dx - delta_sz;
    }
    else
    {
      // Default is left justification.
      x0 = dx;
    }
    textPositions[k] = {{"p", {x0, y0}}, {"p2", {delta_sz, dy}}};
    // For testing.
    // std::cout << k << std::endl;
    // std::cout << "  p: " << textPositions[k]["p"][0] << ", "
    //           << textPositions[k]["p"][1] << std::endl;
    // std::cout << " p2: " << textPositions[k]["p2"][0] << ", "
    //           << textPositions[k]["p2"][1] << std::endl;
  }
  return textPositions;
}

} // namespace

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(GradientBackground)

find_package(VTK COMPONENTS 
  CommonColor
  CommonCore
  CommonDataModel
  FiltersSources
  IOGeometry
  IOLegacy
  IOPLY
  IOXML
  InteractionStyle
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
  cli11
)

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

Download and Build GradientBackground

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

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

./GradientBackground

WINDOWS USERS

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