<commit_before>#include "SphericalInterpolator.h"

SphericalInterpolator::SphericalInterpolator()
{

}

SphericalInterpolator::~SphericalInterpolator()
{

}

//the vectors must be in the order of xyz 000,100,010,001,101,011,110,111
float* SphericalInterpolator::Build(float vectorInput[8][3], float relativePos[3])
{
	float vectorFinal[3];
	int i;
	for (i = 0; i < 3; i++) {
		vectorFinal[i] =	vectorInput[0][i] *  (1 - relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +
							vectorInput[1][i] * (relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +
							vectorInput[2][i] * (1 - relativePos[0]) * relativePos[1] * (1 - relativePos[2]) +
							vectorInput[3][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * relativePos[2] +
							vectorInput[4][i] * relativePos[0] * (1 - relativePos[1]) * relativePos[2] +
							vectorInput[5][i] * (1 - relativePos[0]) * relativePos[1] * relativePos[2] +
							vectorInput[6][i] * relativePos[0] * relativePos[1] * (1 - relativePos[2]) +
							vectorInput[7][i] * relativePos[0] * relativePos[1] * relativePos[2];
	}
	return vectorFinal;
}<commit_msg>Fixed returning a local, temporary variable.<commit_after>#include "SphericalInterpolator.h"

SphericalInterpolator::SphericalInterpolator()
{

}

SphericalInterpolator::~SphericalInterpolator()
{

}

//the vectors must be in the order of xyz 000,100,010,001,101,011,110,111
float* SphericalInterpolator::Build(float vectorInput[8][3], float relativePos[3])
{
	float* vectorFinal = new float[3];
	int i;
	for (i = 0; i < 3; i++) {
		vectorFinal[i] =	vectorInput[0][i] *  (1 - relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +
							vectorInput[1][i] * (relativePos[0]) * (1 - relativePos[1]) * (1 - relativePos[2]) +
							vectorInput[2][i] * (1 - relativePos[0]) * relativePos[1] * (1 - relativePos[2]) +
							vectorInput[3][i] * (1 - relativePos[0]) * (1 - relativePos[1]) * relativePos[2] +
							vectorInput[4][i] * relativePos[0] * (1 - relativePos[1]) * relativePos[2] +
							vectorInput[5][i] * (1 - relativePos[0]) * relativePos[1] * relativePos[2] +
							vectorInput[6][i] * relativePos[0] * relativePos[1] * (1 - relativePos[2]) +
							vectorInput[7][i] * relativePos[0] * relativePos[1] * relativePos[2];
	}
	return vectorFinal;
}<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/support/signal_handler.cpp                                                 */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

// include i/f header

#include "hugh/support/signal_handler.hpp"

// includes, system

#include <array>         // std::array<>
#include <csignal>       // ::sigfillset, ::pthread_sigmask
#include <cstdlib>       // std::abort, std::exit
#include <cstring>       // ::strsignal
#include <iomanip>       // std::boolalpha
#include <iostream>      // std::cerr
#include <thread>        // std::thread
#include <unordered_map> // std::unordered_map<>

// includes, project

//#include <>

#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>

// internal unnamed namespace

namespace {

  // types, internal (class, enum, struct, union, typedef)

  using handler_map_type = std::unordered_map<signed,
                                              hugh::support::signal_handler::handler_function_type>;

  // variables, internal

  bool                         initialized(false);
  handler_map_type             handler_map;
  std::unique_ptr<std::thread> handler_thread(nullptr);

  // functions, internal

  void
  default_handler_indirect(int /* signo */, ::siginfo_t* value, void* /* user_data */)
  {
    TRACE("hugh::support::signal_handler::<unnamed>::default_handler_indirect");

    handler_map[value->si_signo](value->si_signo);
  }

  void
  default_handler(signed signo)
  {
    TRACE("hugh::support::signal_handler::<unnamed>::default_handler");

    volatile bool ignore_signal(false);
    volatile bool create_core(false);
    volatile bool fatal_exit(false);

    switch (signo) {
    case SIGUSR1:
    case SIGUSR2:
    case SIGCHLD:
    case SIGTSTP:
    case SIGCONT:
    case SIGTTIN:
    case SIGTTOU:
    case SIGPROF:
    case SIGURG:
    case SIGVTALRM:
      // case SIGCLD:
    case SIGWINCH:
      ignore_signal = true;
      break;
    }

    switch (signo) {
    case SIGQUIT:
    case SIGILL:
    case SIGABRT:
    case SIGFPE:
    case SIGSEGV:
    case SIGBUS:
    case SIGSYS:
    case SIGTRAP:
    case SIGXCPU:
    case SIGXFSZ:
      // case SIGIOT:
      // case SIGLOST:
      create_core = true;
      break;

    case SIGALRM:
    case SIGPIPE:
      fatal_exit = true;
      break;

    case SIGHUP:
    case SIGINT:
    case SIGTERM:
    case SIGPOLL:
      // case SIGEMT:
    case SIGSTKFLT:
      // case SIGIO:
    case SIGPWR:
      break;

    default:
      break;
    }

#if 0
    {
      std::cerr << '\n'
                << "support::signal_handler::<unnamed>::default_handler: "
                << "caught signal '" << ::strsignal(signo)              << "'; "
                << "ignore:"         << std::boolalpha << ignore_signal << ", "
                << "core:"           << std::boolalpha << create_core   << ", "
                << "fatal:"          << std::boolalpha << fatal_exit    << ", "
                << '\n';
    }
#endif

    if (ignore_signal) {
      return;
    }

    if (create_core) {
      std::abort();
    }

    if (fatal_exit) {
      std::exit(EXIT_FAILURE);
    }

    std::exit(EXIT_SUCCESS);
  }

  void
  signal_thread_function()
  {
    TRACE("hugh::support::signal_handler::<unnamed>::signal_thread_function");

    bool done(false);

    while (!done) {
      TRACE_NEVER("hugh::support::signal_handler::<unnamed>::signal_thread_function[loop]");

      ::sigset_t signal_mask;

      // unblock all signals and refill the mask for signals to be handled

      ::sigfillset     (&signal_mask);
      ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);

      ::siginfo_t value;

      // wait for signal

      bool evaluate(true);

      if (-1 == ::sigwaitinfo(&signal_mask, &value)) {
        if (EINTR != errno)
          std::abort();
        else
          evaluate = false;
      }

      // block all signal and handle current one

      ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);

#if 0
      {
        std::cerr << '\n'
                  << "support::signal_handler::<unnamed>::signal_thread_function: "
                  << ((evaluate) ? "" : "!") << "evaluating signal "
                  << ::strsignal(value.si_signo)
                  << '\n';
      }
#endif

      if (evaluate) {
        handler_map[value.si_signo](value.si_signo);
      }
    }
  }

  void
  initialize()
  {
    TRACE("hugh::support::signal_handler::<unnamed>::initialize");

    if (!initialized) {
      static std::array<signed const, 3> const sync_signals = {
        {
          SIGSEGV, SIGFPE, SIGILL,
        }
      };

      ::sigset_t signal_mask;

      ::sigfillset(&signal_mask);

      for (unsigned i(0); i < sync_signals.size(); ++i) {
        ::sigdelset(&signal_mask, sync_signals[i]);
      }

      for (unsigned i(1); i < _NSIG; ++i) {
        handler_map[i] = default_handler;
      }

      struct sigaction sa;

      sa.sa_sigaction = default_handler_indirect;
      sa.sa_flags     = SA_SIGINFO;

      ::sigemptyset(&sa.sa_mask);

      for (unsigned i(0); i < sync_signals.size(); ++i) {
        ::sigaction(sync_signals[i], &sa, 0);
      }

      ::sigfillset     (&signal_mask);
      ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);
      {
        handler_thread.reset(new std::thread(signal_thread_function));
      }
      ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);

      // avoid exception when 'handler_thread' is destructed
      handler_thread->detach();

      initialized = true;
    }
  }

} // namespace {

namespace hugh {

  namespace support {

    // variables, exported

    // functions, exported

    signal_handler::~signal_handler()
    {
      TRACE("hugh::support::signal_handler::signal_handler");
    }

    signal_handler::handler_function_type
    signal_handler::handler(signed signo)
    {
      TRACE("hugh::support::signal_handler::handler(get)");

      return handler_map[signo];
    }

    signal_handler::handler_function_type
    signal_handler::handler(signed signo, handler_function_type new_handler)
    {
      TRACE("hugh::support::signal_handler::handler(set)");

      handler_function_type old_handler(handler_map[signo]);

      if (new_handler) {
        handler_map[signo] = new_handler;
      }

      return old_handler;
    }

    /* explicit */
    signal_handler::signal_handler(boost::restricted)
    {
      TRACE("hugh::support::signal_handler::signal_handler");

      initialize();
    }

    std::string
    signal_name(signed signo)
    {
      TRACE("hugh::support::signal_name");

      std::string result("UNKNOWN SIGNAL");

      if ((0 < signo) && (_NSIG > signo)) {
        result = sys_siglist[signo];
      }

      return result;
    }

  } // namespace support {

} // namespace hugh {
<commit_msg>added: some tracing decoration<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/support/signal_handler.cpp                                                 */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

// include i/f header

#include "hugh/support/signal_handler.hpp"

// includes, system

#include <array>         // std::array<>
#include <csignal>       // ::sigfillset, ::pthread_sigmask
#include <cstdlib>       // std::abort, std::exit
#include <cstring>       // ::strsignal
#include <iomanip>       // std::boolalpha
#include <iostream>      // std::cerr
#include <thread>        // std::thread
#include <unordered_map> // std::unordered_map<>

// includes, project

//#include <>

#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>

// internal unnamed namespace

namespace {

  // types, internal (class, enum, struct, union, typedef)

  using handler_map_type = std::unordered_map<signed,
                                              hugh::support::signal_handler::handler_function_type>;

  // variables, internal

  bool                         initialized(false);
  handler_map_type             handler_map;
  std::unique_ptr<std::thread> handler_thread(nullptr);

  // functions, internal

  void
  default_handler_indirect(int /* signo */, ::siginfo_t* value, void* /* user_data */)
  {
    TRACE("hugh::support::signal_handler::<unnamed>::default_handler_indirect");

    handler_map[value->si_signo](value->si_signo);
  }

  void
  default_handler(signed signo)
  {
    TRACE("hugh::support::signal_handler::<unnamed>::default_handler(" + std::to_string(signo) +
          ") [" + hugh::support::signal_name(signo) + "]");

    volatile bool ignore_signal(false);
    volatile bool create_core(false);
    volatile bool fatal_exit(false);

    switch (signo) {
    case SIGUSR1:
    case SIGUSR2:
    case SIGCHLD:
    case SIGTSTP:
    case SIGCONT:
    case SIGTTIN:
    case SIGTTOU:
    case SIGPROF:
    case SIGURG:
    case SIGVTALRM:
      // case SIGCLD:
    case SIGWINCH:
      ignore_signal = true;
      break;
    }

    switch (signo) {
    case SIGQUIT:
    case SIGILL:
    case SIGABRT:
    case SIGFPE:
    case SIGSEGV:
    case SIGBUS:
    case SIGSYS:
    case SIGTRAP:
    case SIGXCPU:
    case SIGXFSZ:
      // case SIGIOT:
      // case SIGLOST:
      create_core = true;
      break;

    case SIGALRM:
    case SIGPIPE:
      fatal_exit = true;
      break;

    case SIGHUP:
    case SIGINT:
    case SIGTERM:
    case SIGPOLL:
      // case SIGEMT:
    case SIGSTKFLT:
      // case SIGIO:
    case SIGPWR:
      break;

    default:
      break;
    }

#if 0
    {
      std::cerr << '\n'
                << "support::signal_handler::<unnamed>::default_handler: "
                << "caught signal '" << ::strsignal(signo)              << "'; "
                << "ignore:"         << std::boolalpha << ignore_signal << ", "
                << "core:"           << std::boolalpha << create_core   << ", "
                << "fatal:"          << std::boolalpha << fatal_exit    << ", "
                << '\n';
    }
#endif

    if (ignore_signal) {
      return;
    }

    if (create_core) {
      std::abort();
    }

    if (fatal_exit) {
      std::exit(EXIT_FAILURE);
    }

    std::exit(EXIT_SUCCESS);
  }

  void
  signal_thread_function()
  {
    TRACE("hugh::support::signal_handler::<unnamed>::signal_thread_function");

    bool done(false);

    while (!done) {
      TRACE_NEVER("hugh::support::signal_handler::<unnamed>::signal_thread_function[loop]");

      ::sigset_t signal_mask;

      // unblock all signals and refill the mask for signals to be handled

      ::sigfillset     (&signal_mask);
      ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);

      ::siginfo_t value;

      // wait for signal

      bool evaluate(true);

      if (-1 == ::sigwaitinfo(&signal_mask, &value)) {
        if (EINTR != errno)
          std::abort();
        else
          evaluate = false;
      }

      // block all signal and handle current one

      ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);

#if 0
      {
        std::cerr << '\n'
                  << "support::signal_handler::<unnamed>::signal_thread_function: "
                  << ((evaluate) ? "" : "!") << "evaluating signal "
                  << ::strsignal(value.si_signo)
                  << '\n';
      }
#endif

      if (evaluate) {
        handler_map[value.si_signo](value.si_signo);
      }
    }
  }

  void
  initialize()
  {
    TRACE("hugh::support::signal_handler::<unnamed>::initialize");

    if (!initialized) {
      static std::array<signed const, 3> const sync_signals = {
        {
          SIGSEGV, SIGFPE, SIGILL,
        }
      };

      ::sigset_t signal_mask;

      ::sigfillset(&signal_mask);

      for (unsigned i(0); i < sync_signals.size(); ++i) {
        ::sigdelset(&signal_mask, sync_signals[i]);
      }

      for (unsigned i(1); i < _NSIG; ++i) {
        handler_map[i] = default_handler;
      }

      struct sigaction sa;

      sa.sa_sigaction = default_handler_indirect;
      sa.sa_flags     = SA_SIGINFO;

      ::sigemptyset(&sa.sa_mask);

      for (unsigned i(0); i < sync_signals.size(); ++i) {
        ::sigaction(sync_signals[i], &sa, 0);
      }

      ::sigfillset     (&signal_mask);
      ::pthread_sigmask(SIG_SETMASK, &signal_mask, 0);
      {
        handler_thread.reset(new std::thread(signal_thread_function));
      }
      ::pthread_sigmask(SIG_BLOCK, &signal_mask, 0);

      // avoid exception when 'handler_thread' is destructed
      handler_thread->detach();

      initialized = true;
    }
  }

} // namespace {

namespace hugh {

  namespace support {

    // variables, exported

    // functions, exported

    signal_handler::~signal_handler()
    {
      TRACE("hugh::support::signal_handler::signal_handler");
    }

    signal_handler::handler_function_type
    signal_handler::handler(signed signo)
    {
      TRACE("hugh::support::signal_handler::handler(get)");

      return handler_map[signo];
    }

    signal_handler::handler_function_type
    signal_handler::handler(signed signo, handler_function_type new_handler)
    {
      TRACE("hugh::support::signal_handler::handler(set)");

      handler_function_type old_handler(handler_map[signo]);

      if (new_handler) {
        handler_map[signo] = new_handler;
      }

      return old_handler;
    }

    /* explicit */
    signal_handler::signal_handler(boost::restricted)
    {
      TRACE("hugh::support::signal_handler::signal_handler");

      initialize();
    }

    std::string
    signal_name(signed signo)
    {
      TRACE("hugh::support::signal_name");

      std::string result("UNKNOWN SIGNAL");

      if ((0 < signo) && (_NSIG > signo)) {
        result = sys_siglist[signo];
      }

      return result;
    }

  } // namespace support {

} // namespace hugh {
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    RGrid.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This example shows how to create a rectilinear grid.
//

#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkFloatArray.h"
#include "vtkRectilinearGrid.h"
#include "vtkRectilinearGridGeometryFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkCamera.h"

int main()
{
  int i;
  static float x[47]={
         -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542,
         -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042,
         -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542,
         -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042,
          0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458,
          0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958,
          0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458,
          0.963542, 1.01562, 1.06771, 1.11979, 1.17188};
  static float y[33]={-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375,
         -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625,
         -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125,
          0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875,
          0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562,
          1.09375, 1.17188, 1.25};
  static float z[44]={0, 0.1, 0.2, 0.3, 0.4, 0.5,
         0.6, 0.7, 0.75, 0.8, 0.9, 1,
         1.1, 1.2, 1.3, 1.4, 1.5, 1.6,
         1.7, 1.75, 1.8, 1.9, 2, 2.1,
         2.2, 2.3, 2.4, 2.5, 2.6, 2.7,
         2.75, 2.8, 2.9, 3, 3.1, 3.2,
         3.3, 3.4, 3.5, 3.6, 3.7, 3.75,
         3.8, 3.9};

  // Create a rectilinear grid by defining three arrays specifying the
  // coordinates in the x-y-z directions.
  vtkFloatArray *xCoords = vtkFloatArray::New();
  for (i=0; i<47; i++) xCoords->InsertNextValue(x[i]);

  vtkFloatArray *yCoords = vtkFloatArray::New();
  for (i=0; i<33; i++) yCoords->InsertNextValue(y[i]);

  vtkFloatArray *zCoords = vtkFloatArray::New();
  for (i=0; i<44; i++) zCoords->InsertNextValue(z[i]);

  // The coordinates are assigned to the rectilinear grid. Make sure that
  // the number of values in each of the XCoordinates, YCoordinates,
  // and ZCoordinates is equal to what is defined in SetDimensions().
  //
  vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New();
    rgrid->SetDimensions(47,33,44);
    rgrid->SetXCoordinates(xCoords);
    rgrid->SetYCoordinates(yCoords);
    rgrid->SetZCoordinates(zCoords);

    // Extract a plane from the grid to see what we've got.
  vtkRectilinearGridGeometryFilter *plane = vtkRectilinearGridGeometryFilter::New();
    plane->SetInput(rgrid);
    plane->SetExtent(0,46, 16,16, 0,43);

  vtkPolyDataMapper *rgridMapper = vtkPolyDataMapper::New();
      rgridMapper->SetInput(plane->GetOutput());

  vtkActor *wireActor = vtkActor::New();
      wireActor->SetMapper(rgridMapper);
      wireActor->GetProperty()->SetRepresentationToWireframe();
      wireActor->GetProperty()->SetColor(0,0,0);

  // Create the usual rendering stuff.
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  renderer->AddActor(wireActor);
  renderer->SetBackground(1,1,1);
  renderer->ResetCamera();
  renderer->GetActiveCamera()->Elevation(60.0);
  renderer->GetActiveCamera()->Azimuth(30.0);
  renderer->GetActiveCamera()->Zoom(1.0);

  renWin->SetSize(300,300);

  // interact with data
  renWin->Render();
  iren->Start();

  // Clean up
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  xCoords->Delete();
  yCoords->Delete();
  zCoords->Delete();
  rgrid->Delete();
  rgridMapper->Delete();
  wireActor->Delete();

  return 0;
}
<commit_msg>COMP: add missing Delete<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    RGrid.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This example shows how to create a rectilinear grid.
//

#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkFloatArray.h"
#include "vtkRectilinearGrid.h"
#include "vtkRectilinearGridGeometryFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkCamera.h"

int main()
{
  int i;
  static float x[47]={
         -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542,
         -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042,
         -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542,
         -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042,
          0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458,
          0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958,
          0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458,
          0.963542, 1.01562, 1.06771, 1.11979, 1.17188};
  static float y[33]={-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375,
         -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625,
         -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125,
          0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875,
          0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562,
          1.09375, 1.17188, 1.25};
  static float z[44]={0, 0.1, 0.2, 0.3, 0.4, 0.5,
         0.6, 0.7, 0.75, 0.8, 0.9, 1,
         1.1, 1.2, 1.3, 1.4, 1.5, 1.6,
         1.7, 1.75, 1.8, 1.9, 2, 2.1,
         2.2, 2.3, 2.4, 2.5, 2.6, 2.7,
         2.75, 2.8, 2.9, 3, 3.1, 3.2,
         3.3, 3.4, 3.5, 3.6, 3.7, 3.75,
         3.8, 3.9};

  // Create a rectilinear grid by defining three arrays specifying the
  // coordinates in the x-y-z directions.
  vtkFloatArray *xCoords = vtkFloatArray::New();
  for (i=0; i<47; i++) xCoords->InsertNextValue(x[i]);

  vtkFloatArray *yCoords = vtkFloatArray::New();
  for (i=0; i<33; i++) yCoords->InsertNextValue(y[i]);

  vtkFloatArray *zCoords = vtkFloatArray::New();
  for (i=0; i<44; i++) zCoords->InsertNextValue(z[i]);

  // The coordinates are assigned to the rectilinear grid. Make sure that
  // the number of values in each of the XCoordinates, YCoordinates,
  // and ZCoordinates is equal to what is defined in SetDimensions().
  //
  vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New();
    rgrid->SetDimensions(47,33,44);
    rgrid->SetXCoordinates(xCoords);
    rgrid->SetYCoordinates(yCoords);
    rgrid->SetZCoordinates(zCoords);

    // Extract a plane from the grid to see what we've got.
  vtkRectilinearGridGeometryFilter *plane = vtkRectilinearGridGeometryFilter::New();
    plane->SetInput(rgrid);
    plane->SetExtent(0,46, 16,16, 0,43);

  vtkPolyDataMapper *rgridMapper = vtkPolyDataMapper::New();
      rgridMapper->SetInput(plane->GetOutput());

  vtkActor *wireActor = vtkActor::New();
      wireActor->SetMapper(rgridMapper);
      wireActor->GetProperty()->SetRepresentationToWireframe();
      wireActor->GetProperty()->SetColor(0,0,0);

  // Create the usual rendering stuff.
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  renderer->AddActor(wireActor);
  renderer->SetBackground(1,1,1);
  renderer->ResetCamera();
  renderer->GetActiveCamera()->Elevation(60.0);
  renderer->GetActiveCamera()->Azimuth(30.0);
  renderer->GetActiveCamera()->Zoom(1.0);

  renWin->SetSize(300,300);

  // interact with data
  renWin->Render();
  iren->Start();

  // Clean up
  plane->Delete();
  renderer->Delete();
  renWin->Delete();
  iren->Delete();
  xCoords->Delete();
  yCoords->Delete();
  zCoords->Delete();
  rgrid->Delete();
  rgridMapper->Delete();
  wireActor->Delete();

  return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Petar Perisin <petar.perisin@gmail.com>
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "ansiescapecodehandler.h"
#include <utils/qtcassert.h>

namespace Utils {

/*!
    \class Utils::AnsiEscapeCodeHandler

    \brief The AnsiEscapeCodeHandler class parses text and extracts ANSI escape codes from it.

    In order to preserve color information across text segments, an instance of this class
    must be stored for the lifetime of a stream.
    Also, one instance of this class should not handle multiple streams (at least not
    at the same time).

    Its main function is parseText(), which accepts text and default QTextCharFormat.
    This function is designed to parse text and split colored text to smaller strings,
    with their appropriate formatting information set inside QTextCharFormat.

    Usage:
    \list
    \li Create new instance of AnsiEscapeCodeHandler for a stream.
    \li To add new text, call parseText() with the text and a default QTextCharFormat.
        The result of this function is a list of strings with formats set in appropriate
        QTextCharFormat.
    \endlist
*/

AnsiEscapeCodeHandler::AnsiEscapeCodeHandler() :
    m_previousFormatClosed(true)
{
}

static QColor ansiColor(uint code)
{
    QTC_ASSERT(code < 8, return QColor());

    const int red   = code & 1 ? 170 : 0;
    const int green = code & 2 ? 170 : 0;
    const int blue  = code & 4 ? 170 : 0;
    return QColor(red, green, blue);
}

QList<FormattedText> AnsiEscapeCodeHandler::parseText(const FormattedText &input)
{
    enum AnsiEscapeCodes {
        ResetFormat            =  0,
        BoldText               =  1,
        TextColorStart         = 30,
        TextColorEnd           = 37,
        RgbTextColor           = 38,
        DefaultTextColor       = 39,
        BackgroundColorStart   = 40,
        BackgroundColorEnd     = 47,
        RgbBackgroundColor     = 48,
        DefaultBackgroundColor = 49
    };

    QList<FormattedText> outputData;

    QTextCharFormat charFormat = m_previousFormatClosed ? input.format : m_previousFormat;

    const QString escape = QLatin1String("\x1b[");
    if (!input.text.contains(escape)) {
        outputData << FormattedText(input.text, charFormat);
        return outputData;
    } else if (!input.text.startsWith(escape)) {
        outputData << FormattedText(input.text.left(input.text.indexOf(escape)), charFormat);
    }

    const QChar semicolon       = QLatin1Char(';');
    const QChar colorTerminator = QLatin1Char('m');
    // strippedText always starts with "\e["
    QString strippedText = input.text.mid(input.text.indexOf(escape));
    while (!strippedText.isEmpty()) {
        while (strippedText.startsWith(escape)) {
            strippedText.remove(0, 2);

            // get the number
            QString strNumber;
            QStringList numbers;
            while (strippedText.at(0).isDigit() || strippedText.at(0) == semicolon) {
                if (strippedText.at(0).isDigit()) {
                    strNumber += strippedText.at(0);
                } else {
                    numbers << strNumber;
                    strNumber.clear();
                }
                strippedText.remove(0, 1);
            }
            if (!strNumber.isEmpty())
                numbers << strNumber;

            // remove terminating char
            if (!strippedText.startsWith(colorTerminator)) {
                strippedText.remove(0, 1);
                continue;
            }
            strippedText.remove(0, 1);

            if (numbers.isEmpty()) {
                charFormat = input.format;
                endFormatScope();
            }

            for (int i = 0; i < numbers.size(); ++i) {
                const int code = numbers.at(i).toInt();

                if (code >= TextColorStart && code <= TextColorEnd) {
                    charFormat.setForeground(ansiColor(code - TextColorStart));
                    setFormatScope(charFormat);
                } else if (code >= BackgroundColorStart && code <= BackgroundColorEnd) {
                    charFormat.setBackground(ansiColor(code - BackgroundColorStart));
                    setFormatScope(charFormat);
                } else {
                    switch (code) {
                    case ResetFormat:
                        charFormat = input.format;
                        endFormatScope();
                        break;
                    case BoldText:
                        charFormat.setFontWeight(QFont::Bold);
                        setFormatScope(charFormat);
                        break;
                    case DefaultTextColor:
                        charFormat.setForeground(input.format.foreground());
                        setFormatScope(charFormat);
                        break;
                    case DefaultBackgroundColor:
                        charFormat.setBackground(input.format.background());
                        setFormatScope(charFormat);
                        break;
                    case RgbTextColor:
                    case RgbBackgroundColor:
                        if (++i >= numbers.size())
                            break;
                        if (numbers.at(i).toInt() == 2) {
                            // RGB set with format: 38;2;<r>;<g>;<b>
                            if ((i + 3) < numbers.size()) {
                                (code == RgbTextColor) ?
                                      charFormat.setForeground(QColor(numbers.at(i + 1).toInt(),
                                                                      numbers.at(i + 2).toInt(),
                                                                      numbers.at(i + 3).toInt())) :
                                      charFormat.setBackground(QColor(numbers.at(i + 1).toInt(),
                                                                      numbers.at(i + 2).toInt(),
                                                                      numbers.at(i + 3).toInt()));
                                setFormatScope(charFormat);
                            }
                            i += 3;
                        } else if (numbers.at(i).toInt() == 5) {
                            // rgb set with format: 38;5;<i>
                            // unsupported because of unclear documentation, so we just skip <i>
                            ++i;
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        }

        if (strippedText.isEmpty())
            break;
        int index = strippedText.indexOf(escape);
        if (index > 0) {
            outputData << FormattedText(strippedText.left(index), charFormat);
            strippedText.remove(0, index);
        } else if (index == -1) {
            outputData << FormattedText(strippedText, charFormat);
            break;
        }
    }
    return outputData;
}

void AnsiEscapeCodeHandler::endFormatScope()
{
    m_previousFormatClosed = true;
}

void AnsiEscapeCodeHandler::setFormatScope(const QTextCharFormat &charFormat)
{
    m_previousFormat = charFormat;
    m_previousFormatClosed = false;
}

} // namespace Utils
<commit_msg>AnsiEscapeHandler: Avoid some iterations over the string<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Petar Perisin <petar.perisin@gmail.com>
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "ansiescapecodehandler.h"
#include <utils/qtcassert.h>

namespace Utils {

/*!
    \class Utils::AnsiEscapeCodeHandler

    \brief The AnsiEscapeCodeHandler class parses text and extracts ANSI escape codes from it.

    In order to preserve color information across text segments, an instance of this class
    must be stored for the lifetime of a stream.
    Also, one instance of this class should not handle multiple streams (at least not
    at the same time).

    Its main function is parseText(), which accepts text and default QTextCharFormat.
    This function is designed to parse text and split colored text to smaller strings,
    with their appropriate formatting information set inside QTextCharFormat.

    Usage:
    \list
    \li Create new instance of AnsiEscapeCodeHandler for a stream.
    \li To add new text, call parseText() with the text and a default QTextCharFormat.
        The result of this function is a list of strings with formats set in appropriate
        QTextCharFormat.
    \endlist
*/

AnsiEscapeCodeHandler::AnsiEscapeCodeHandler() :
    m_previousFormatClosed(true)
{
}

static QColor ansiColor(uint code)
{
    QTC_ASSERT(code < 8, return QColor());

    const int red   = code & 1 ? 170 : 0;
    const int green = code & 2 ? 170 : 0;
    const int blue  = code & 4 ? 170 : 0;
    return QColor(red, green, blue);
}

QList<FormattedText> AnsiEscapeCodeHandler::parseText(const FormattedText &input)
{
    enum AnsiEscapeCodes {
        ResetFormat            =  0,
        BoldText               =  1,
        TextColorStart         = 30,
        TextColorEnd           = 37,
        RgbTextColor           = 38,
        DefaultTextColor       = 39,
        BackgroundColorStart   = 40,
        BackgroundColorEnd     = 47,
        RgbBackgroundColor     = 48,
        DefaultBackgroundColor = 49
    };

    QList<FormattedText> outputData;

    QTextCharFormat charFormat = m_previousFormatClosed ? input.format : m_previousFormat;

    const QString escape = QLatin1String("\x1b[");
    const int escapePos = input.text.indexOf(escape);
    if (escapePos < 0) {
        outputData << FormattedText(input.text, charFormat);
        return outputData;
    } else if (escapePos != 0) {
        outputData << FormattedText(input.text.left(escapePos), charFormat);
    }

    const QChar semicolon       = QLatin1Char(';');
    const QChar colorTerminator = QLatin1Char('m');
    // strippedText always starts with "\e["
    QString strippedText = input.text.mid(escapePos);
    while (!strippedText.isEmpty()) {
        while (strippedText.startsWith(escape)) {
            strippedText.remove(0, 2);

            // get the number
            QString strNumber;
            QStringList numbers;
            while (strippedText.at(0).isDigit() || strippedText.at(0) == semicolon) {
                if (strippedText.at(0).isDigit()) {
                    strNumber += strippedText.at(0);
                } else {
                    numbers << strNumber;
                    strNumber.clear();
                }
                strippedText.remove(0, 1);
            }
            if (!strNumber.isEmpty())
                numbers << strNumber;

            // remove terminating char
            if (!strippedText.startsWith(colorTerminator)) {
                strippedText.remove(0, 1);
                continue;
            }
            strippedText.remove(0, 1);

            if (numbers.isEmpty()) {
                charFormat = input.format;
                endFormatScope();
            }

            for (int i = 0; i < numbers.size(); ++i) {
                const int code = numbers.at(i).toInt();

                if (code >= TextColorStart && code <= TextColorEnd) {
                    charFormat.setForeground(ansiColor(code - TextColorStart));
                    setFormatScope(charFormat);
                } else if (code >= BackgroundColorStart && code <= BackgroundColorEnd) {
                    charFormat.setBackground(ansiColor(code - BackgroundColorStart));
                    setFormatScope(charFormat);
                } else {
                    switch (code) {
                    case ResetFormat:
                        charFormat = input.format;
                        endFormatScope();
                        break;
                    case BoldText:
                        charFormat.setFontWeight(QFont::Bold);
                        setFormatScope(charFormat);
                        break;
                    case DefaultTextColor:
                        charFormat.setForeground(input.format.foreground());
                        setFormatScope(charFormat);
                        break;
                    case DefaultBackgroundColor:
                        charFormat.setBackground(input.format.background());
                        setFormatScope(charFormat);
                        break;
                    case RgbTextColor:
                    case RgbBackgroundColor:
                        if (++i >= numbers.size())
                            break;
                        if (numbers.at(i).toInt() == 2) {
                            // RGB set with format: 38;2;<r>;<g>;<b>
                            if ((i + 3) < numbers.size()) {
                                (code == RgbTextColor) ?
                                      charFormat.setForeground(QColor(numbers.at(i + 1).toInt(),
                                                                      numbers.at(i + 2).toInt(),
                                                                      numbers.at(i + 3).toInt())) :
                                      charFormat.setBackground(QColor(numbers.at(i + 1).toInt(),
                                                                      numbers.at(i + 2).toInt(),
                                                                      numbers.at(i + 3).toInt()));
                                setFormatScope(charFormat);
                            }
                            i += 3;
                        } else if (numbers.at(i).toInt() == 5) {
                            // rgb set with format: 38;5;<i>
                            // unsupported because of unclear documentation, so we just skip <i>
                            ++i;
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
        }

        if (strippedText.isEmpty())
            break;
        int index = strippedText.indexOf(escape);
        if (index > 0) {
            outputData << FormattedText(strippedText.left(index), charFormat);
            strippedText.remove(0, index);
        } else if (index == -1) {
            outputData << FormattedText(strippedText, charFormat);
            break;
        }
    }
    return outputData;
}

void AnsiEscapeCodeHandler::endFormatScope()
{
    m_previousFormatClosed = true;
}

void AnsiEscapeCodeHandler::setFormatScope(const QTextCharFormat &charFormat)
{
    m_previousFormat = charFormat;
    m_previousFormatClosed = false;
}

} // namespace Utils
<|endoftext|>


<commit_before>// $Id$
// splitted from AliHLTConfiguration.cxx,v 1.25 2007/10/12 13:24:47
/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTConfigurationHandler.cxx
    @author Matthias Richter
    @date
    @brief  Implementation of HLT tasks.
*/

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#if __GNUC__>= 3
using namespace std;
#endif

#include <cerrno>
#include <iostream>
#include <string>
#include "AliHLTConfigurationHandler.h"
#include "AliHLTConfiguration.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTConfigurationHandler)

AliHLTConfigurationHandler::AliHLTConfigurationHandler()
  :
  fgListConfigurations()
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
  SetLocalLoggingLevel(kHLTLogInfo);
}

AliHLTConfigurationHandler::~AliHLTConfigurationHandler()
{
  // see header file for function documentation
  TObjLink* lnk=NULL;
  while ((lnk=fgListConfigurations.FirstLink())!=NULL) {
    AliHLTConfiguration* pConf=(AliHLTConfiguration*)lnk->GetObject();
    HLTDebug("delete configuration \"%s\"", pConf->GetName());
    fgListConfigurations.Remove(lnk);
    delete pConf;
  }
}

AliHLTConfigurationHandler* AliHLTConfigurationHandler::fgpInstance=NULL;
int AliHLTConfigurationHandler::fgNofInstances=0;

AliHLTConfigurationHandler* AliHLTConfigurationHandler::CreateHandler()
{
  // see header file for class documentation
  if (!fgpInstance) fgpInstance=new AliHLTConfigurationHandler;
  fgNofInstances++;
  return fgpInstance;
}

int AliHLTConfigurationHandler::Destroy()
{
  // see header file for class documentation
  int nofInstances=0;
  if (fgpInstance==this) {
    nofInstances=fgNofInstances--;
  }
  if (nofInstances==0) delete this;
  return nofInstances;
}

int AliHLTConfigurationHandler::RegisterConfiguration(AliHLTConfiguration* pConf)
{
  // see header file for function documentation
  int iResult=0;
  if (pConf) {
    AliHLTConfiguration* pExisting=NULL;
    if ((pExisting=FindConfiguration(pConf->GetName())) == NULL) {
      AliHLTConfiguration* pClone=new AliHLTConfiguration(*pConf);
      fgListConfigurations.Add(pClone);
      HLTDebug("configuration \"%s\" (%p) registered from %p", pClone->GetName(), pClone, pConf);

      // mark all configurations with unresolved dependencies for re-evaluation
      TObjLink* lnk=fgListConfigurations.FirstLink();
      while (lnk) {
	AliHLTConfiguration* pSrc=(AliHLTConfiguration*)lnk->GetObject();
	if (pSrc && pSrc!=pClone && pSrc->SourcesResolved()!=1) {
	  pSrc->InvalidateSources();
	}
	lnk=lnk->Next();
      }
    } else {
      if ((*pExisting)!=(*pConf)) {
      iResult=-EEXIST;
      HLTWarning("configuration \"%s\" already registered with different properties", pConf->GetName());
      }
    }
  } else {
    iResult=-EINVAL;
  }
  return iResult;
}

int AliHLTConfigurationHandler::CreateConfiguration(const char* id, const char* component, const char* sources, const char* arguments)
{
  // see header file for function documentation
  int iResult=0;
  AliHLTConfiguration* pConf= new AliHLTConfiguration(id, component, sources, arguments);
  if (pConf) {
    // the configuration will be registered automatically, if this failes the configuration
    // is missing -> delete it
    if (FindConfiguration(id)==NULL) {
      delete pConf;
      pConf=NULL;
      iResult=-EEXIST;
    }
  } else {
    HLTError("system error: object allocation failed");
    iResult=-ENOMEM;
  }
  return iResult;
}

void AliHLTConfigurationHandler::PrintConfigurations()
{
  // see header file for function documentation
  HLTLogKeyword("configuration listing");
  HLTMessage("registered configurations:");
  TObjLink *lnk = fgListConfigurations.FirstLink();
  while (lnk) {
    TObject *obj = lnk->GetObject();
    HLTMessage("  %s", obj->GetName());
    lnk = lnk->Next();
  }
}

int AliHLTConfigurationHandler::RemoveConfiguration(const char* id)
{
  // see header file for function documentation
  int iResult=0;
  if (id) {
    AliHLTConfiguration* pConf=NULL;
    if ((pConf=FindConfiguration(id))!=NULL) {
      iResult=RemoveConfiguration(pConf);
      delete pConf;
      pConf=NULL;
    } else {
      HLTWarning("can not find configuration \"%s\"", id);
      iResult=-ENOENT;
    }
  } else {
    iResult=-EINVAL;
  }
  return iResult;
}

int AliHLTConfigurationHandler::RemoveConfiguration(AliHLTConfiguration* pConf)
{
  // see header file for function documentation
  int iResult=0;
  if (pConf) {
    // remove the configuration from the list
    HLTDebug("remove configuration \"%s\"", pConf->GetName());
    fgListConfigurations.Remove(pConf);
    // remove cross links in the remaining configurations
    TObjLink* lnk=fgListConfigurations.FirstLink();
    while (lnk && iResult>=0) {
      AliHLTConfiguration* pRem=(AliHLTConfiguration*)lnk->GetObject();
      if (pRem) {
	pRem->InvalidateSource(pConf);
      } else {
	iResult=-EFAULT;
      }
      lnk=lnk->Next();
    }
  }
  return iResult;
}

AliHLTConfiguration* AliHLTConfigurationHandler::FindConfiguration(const char* id)
{
  // see header file for function documentation
  AliHLTConfiguration* pConf=NULL;
  if (id) {
    pConf=(AliHLTConfiguration*)fgListConfigurations.FindObject(id);
  }
  return pConf;
}

<commit_msg>Fixing bug in destruction of global instance.<commit_after>// $Id$
// splitted from AliHLTConfiguration.cxx,v 1.25 2007/10/12 13:24:47
/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTConfigurationHandler.cxx
    @author Matthias Richter
    @date
    @brief  Implementation of HLT tasks.
*/

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#if __GNUC__>= 3
using namespace std;
#endif

#include <cerrno>
#include <iostream>
#include <string>
#include "AliHLTConfigurationHandler.h"
#include "AliHLTConfiguration.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTConfigurationHandler)

AliHLTConfigurationHandler::AliHLTConfigurationHandler()
  :
  fgListConfigurations()
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
  SetLocalLoggingLevel(kHLTLogInfo);
}

AliHLTConfigurationHandler::~AliHLTConfigurationHandler()
{
  // see header file for function documentation
  TObjLink* lnk=NULL;
  while ((lnk=fgListConfigurations.FirstLink())!=NULL) {
    AliHLTConfiguration* pConf=(AliHLTConfiguration*)lnk->GetObject();
    HLTDebug("delete configuration \"%s\"", pConf->GetName());
    fgListConfigurations.Remove(lnk);
    delete pConf;
  }
}

AliHLTConfigurationHandler* AliHLTConfigurationHandler::fgpInstance=NULL;
int AliHLTConfigurationHandler::fgNofInstances=0;

AliHLTConfigurationHandler* AliHLTConfigurationHandler::CreateHandler()
{
  // see header file for class documentation
  if (!fgpInstance) fgpInstance=new AliHLTConfigurationHandler;
  fgNofInstances++;
  return fgpInstance;
}

int AliHLTConfigurationHandler::Destroy()
{
  // see header file for class documentation
  int nofInstances=0;
  if (fgpInstance==this) {
    nofInstances=fgNofInstances--;
  }
  if (fgNofInstances==0) {
    delete fgpInstance;
    fgpInstance = NULL;
  }
  return nofInstances;
}

int AliHLTConfigurationHandler::RegisterConfiguration(AliHLTConfiguration* pConf)
{
  // see header file for function documentation
  int iResult=0;
  if (pConf) {
    AliHLTConfiguration* pExisting=NULL;
    if ((pExisting=FindConfiguration(pConf->GetName())) == NULL) {
      AliHLTConfiguration* pClone=new AliHLTConfiguration(*pConf);
      fgListConfigurations.Add(pClone);
      HLTDebug("configuration \"%s\" (%p) registered from %p", pClone->GetName(), pClone, pConf);

      // mark all configurations with unresolved dependencies for re-evaluation
      TObjLink* lnk=fgListConfigurations.FirstLink();
      while (lnk) {
	AliHLTConfiguration* pSrc=(AliHLTConfiguration*)lnk->GetObject();
	if (pSrc && pSrc!=pClone && pSrc->SourcesResolved()!=1) {
	  pSrc->InvalidateSources();
	}
	lnk=lnk->Next();
      }
    } else {
      if ((*pExisting)!=(*pConf)) {
      iResult=-EEXIST;
      HLTWarning("configuration \"%s\" already registered with different properties", pConf->GetName());
      }
    }
  } else {
    iResult=-EINVAL;
  }
  return iResult;
}

int AliHLTConfigurationHandler::CreateConfiguration(const char* id, const char* component, const char* sources, const char* arguments)
{
  // see header file for function documentation
  int iResult=0;
  AliHLTConfiguration* pConf= new AliHLTConfiguration(id, component, sources, arguments);
  if (pConf) {
    // the configuration will be registered automatically, if this failes the configuration
    // is missing -> delete it
    if (FindConfiguration(id)==NULL) {
      delete pConf;
      pConf=NULL;
      iResult=-EEXIST;
    }
  } else {
    HLTError("system error: object allocation failed");
    iResult=-ENOMEM;
  }
  return iResult;
}

void AliHLTConfigurationHandler::PrintConfigurations()
{
  // see header file for function documentation
  HLTLogKeyword("configuration listing");
  HLTMessage("registered configurations:");
  TObjLink *lnk = fgListConfigurations.FirstLink();
  while (lnk) {
    TObject *obj = lnk->GetObject();
    HLTMessage("  %s", obj->GetName());
    lnk = lnk->Next();
  }
}

int AliHLTConfigurationHandler::RemoveConfiguration(const char* id)
{
  // see header file for function documentation
  int iResult=0;
  if (id) {
    AliHLTConfiguration* pConf=NULL;
    if ((pConf=FindConfiguration(id))!=NULL) {
      iResult=RemoveConfiguration(pConf);
      delete pConf;
      pConf=NULL;
    } else {
      HLTWarning("can not find configuration \"%s\"", id);
      iResult=-ENOENT;
    }
  } else {
    iResult=-EINVAL;
  }
  return iResult;
}

int AliHLTConfigurationHandler::RemoveConfiguration(AliHLTConfiguration* pConf)
{
  // see header file for function documentation
  int iResult=0;
  if (pConf) {
    // remove the configuration from the list
    HLTDebug("remove configuration \"%s\"", pConf->GetName());
    fgListConfigurations.Remove(pConf);
    // remove cross links in the remaining configurations
    TObjLink* lnk=fgListConfigurations.FirstLink();
    while (lnk && iResult>=0) {
      AliHLTConfiguration* pRem=(AliHLTConfiguration*)lnk->GetObject();
      if (pRem) {
	pRem->InvalidateSource(pConf);
      } else {
	iResult=-EFAULT;
      }
      lnk=lnk->Next();
    }
  }
  return iResult;
}

AliHLTConfiguration* AliHLTConfigurationHandler::FindConfiguration(const char* id)
{
  // see header file for function documentation
  AliHLTConfiguration* pConf=NULL;
  if (id) {
    pConf=(AliHLTConfiguration*)fgListConfigurations.FindObject(id);
  }
  return pConf;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    ImagePlaneWidget.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkActor.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkCellPicker.h"
#include "vtkCommand.h"
#include "vtkImageActor.h"
#include "vtkImageMapToColors.h"
#include "vtkImagePlaneWidget.h"
#include "vtkImageReader.h"
#include "vtkLookupTable.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkTextMapper.h"
#include "vtkVolume16Reader.h"

#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"

// Callback for the interaction
class vtkMyCallback : public vtkCommand
{
public:
  static vtkMyCallback *New()
    { return new vtkMyCallback; }
  void Delete()
    { delete this; }
  virtual void Execute(vtkObject *caller, unsigned long, void*)
    {
      vtkImagePlaneWidget *planeWidget = reinterpret_cast<vtkImagePlaneWidget*>(caller);

      sprintf(this->buffer,"%.2f, %d",planeWidget->GetSlicePosition(),planeWidget->GetSliceIndex());
      this->Mapper->SetInput(buffer);
      this->Mapper->Modified();
    }
  vtkMyCallback():Mapper(0){};
  vtkTextMapper* Mapper;
  char buffer[128];
};

int main( int argc, char *argv[] )
{
  vtkDebugLeaks::PromptUserOff();

  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");

  vtkVolume16Reader* v16 =  vtkVolume16Reader::New();
    v16->SetDataDimensions( 64, 64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetImageRange( 1, 93);
    v16->SetDataSpacing( 3.2, 3.2, 1.5);
    v16->SetFilePrefix( fname );
    v16->SetDataMask( 0x7fff);
    v16->Update();

  delete[] fname;

  vtkOutlineFilter* outline = vtkOutlineFilter::New();
    outline->SetInput(v16->GetOutput());

  vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();
    outlineMapper->SetInput(outline->GetOutput());

  vtkActor* outlineActor =  vtkActor::New();
    outlineActor->SetMapper( outlineMapper);

  vtkRenderer* ren1 = vtkRenderer::New();
  vtkRenderer* ren2 = vtkRenderer::New();

  vtkRenderWindow* renWin = vtkRenderWindow::New();
    renWin->AddRenderer(ren2);
    renWin->AddRenderer(ren1);

  vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  vtkCellPicker* picker = vtkCellPicker::New();
    picker->SetTolerance(0.005);

  vtkImagePlaneWidget* planeWidgetX = vtkImagePlaneWidget::New();
    planeWidgetX->SetInteractor( iren);
    planeWidgetX->SetKeyPressActivationValue('x');
    planeWidgetX->SetPicker(picker);
    planeWidgetX->GetPlaneProperty()->SetColor(1,0,0);
    planeWidgetX->TextureInterpolateOff();
    planeWidgetX->SetResliceInterpolateToNearestNeighbour();
    planeWidgetX->SetInput(v16->GetOutput());
    planeWidgetX->SetPlaneOrientationToXAxes();
    planeWidgetX->SetSliceIndex(32);
    planeWidgetX->On();

  vtkImagePlaneWidget* planeWidgetY = vtkImagePlaneWidget::New();
    planeWidgetY->SetInteractor( iren);
    planeWidgetY->SetKeyPressActivationValue('y');
    planeWidgetY->SetPicker(picker);
    planeWidgetY->GetPlaneProperty()->SetColor(1,1,0);
    planeWidgetY->TextureInterpolateOn();
    planeWidgetY->SetResliceInterpolateToLinear();
    planeWidgetY->SetInput(v16->GetOutput());
    planeWidgetY->SetPlaneOrientationToYAxes();
    planeWidgetY->SetSlicePosition(102.4);
    planeWidgetY->SetLookupTable( planeWidgetX->GetLookupTable());
    planeWidgetY->On();

  vtkImagePlaneWidget* planeWidgetZ = vtkImagePlaneWidget::New();
    planeWidgetZ->SetInteractor( iren);
    planeWidgetZ->SetKeyPressActivationValue('z');
    planeWidgetZ->SetPicker(picker);
    planeWidgetZ->GetPlaneProperty()->SetColor(0,0,1);
    planeWidgetZ->TextureInterpolateOn();
    planeWidgetZ->SetResliceInterpolateToCubic();
    planeWidgetZ->SetInput(v16->GetOutput());
    planeWidgetZ->SetPlaneOrientationToZAxes();
    planeWidgetZ->SetSliceIndex(25);
    planeWidgetZ->SetLookupTable( planeWidgetX->GetLookupTable());
    planeWidgetZ->On();

  // add text display of planeWidgetZ's slice position and slice index to ren2
  vtkTextMapper* textMapper = vtkTextMapper::New();
    textMapper->SetInput("NA");
    textMapper->SetFontSize(18);
    textMapper->SetFontFamilyToArial();
    textMapper->SetJustificationToLeft();
    textMapper->BoldOn();
    textMapper->ItalicOff();
    textMapper->ShadowOff();

  vtkActor2D* textActor = vtkActor2D::New();
    textActor->SetMapper(textMapper);
    textActor->GetProperty()->SetColor(0,1,1);

  // link the widget to the text by callback
  vtkMyCallback *myCallback = vtkMyCallback::New();
    myCallback->Mapper = textMapper;

  planeWidgetZ->AddObserver(vtkCommand::InteractionEvent,myCallback);

  // add a 2D image to test the GetReslice method
  vtkImageMapToColors* colorMap = vtkImageMapToColors::New();
    colorMap->PassAlphaToOutputOff();
    colorMap->SetActiveComponent(0);
    colorMap->SetOutputFormatToLuminance();
    colorMap->SetInput(planeWidgetZ->GetResliceOutput());
    colorMap->SetLookupTable(planeWidgetX->GetLookupTable());

  vtkImageActor* imageActor = vtkImageActor::New();
    imageActor->PickableOff();
    imageActor->SetInput(colorMap->GetOutput());

  // add the actors
  ren1->AddActor( outlineActor);
  ren2->AddActor( imageActor);
  ren2->AddActor( textActor);

  ren1->SetBackground( 0.1, 0.1, 0.2);
  ren2->SetBackground( 0.2, 0.1, 0.2);

  renWin->SetSize( 600, 350);

  ren1->SetViewport(0,0,0.58333,1);
  ren2->SetViewport(0.58333,0,1,1);

  // set the actors' postions
  renWin->Render();
  iren->SetEventPosition( 175,175);
  iren->SetKeyCode('r');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  iren->SetEventPosition( 475,175);
  iren->SetKeyCode('r');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  int *o = ren2->GetOrigin();
  textActor->SetDisplayPosition(o[0] + 5, o[1] + 5);
  renWin->Render();

  // test SetKeyPressActivationValue for one of the widgets
  iren->SetKeyCode('z');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  iren->SetKeyCode('z');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);

  ren1->GetActiveCamera()->Elevation(110);
  ren1->GetActiveCamera()->SetViewUp(0, 0, -1);
  ren1->GetActiveCamera()->Azimuth(45);
  ren1->GetActiveCamera()->Dolly(1.15);
  ren1->ResetCameraClippingRange();

  // make the window level work
  int pos1[2] = { 193,187};
  iren->SetEventPosition(pos1);
  iren->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);
  int pos2[2] = { 105,197};
  iren->SetEventPosition(pos2);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);

  int retVal = vtkRegressionTestImage( renWin );

  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  planeWidgetX->Delete();
  planeWidgetY->Delete();
  planeWidgetZ->Delete();
  colorMap->Delete();
  imageActor->Delete();
  picker->Delete();
  outlineActor->Delete();
  outlineMapper->Delete();
  outline->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  ren2->Delete();
  v16->Delete();
  textMapper->Delete();
  textActor->Delete();
  myCallback->Delete();

  return !retVal;
}
<commit_msg>FIX: remove vtkTextMapper from test's pipeline<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    ImagePlaneWidget.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCellPicker.h"
#include "vtkCommand.h"
#include "vtkImageActor.h"
#include "vtkImageMapToColors.h"
#include "vtkImagePlaneWidget.h"
#include "vtkImageReader.h"
#include "vtkLookupTable.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkVolume16Reader.h"

#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"

int main( int argc, char *argv[] )
{
  vtkDebugLeaks::PromptUserOff();

  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");

  vtkVolume16Reader* v16 =  vtkVolume16Reader::New();
    v16->SetDataDimensions( 64, 64);
    v16->SetDataByteOrderToLittleEndian();
    v16->SetImageRange( 1, 93);
    v16->SetDataSpacing( 3.2, 3.2, 1.5);
    v16->SetFilePrefix( fname );
    v16->SetDataMask( 0x7fff);
    v16->Update();

  delete[] fname;

  vtkOutlineFilter* outline = vtkOutlineFilter::New();
    outline->SetInput(v16->GetOutput());

  vtkPolyDataMapper* outlineMapper = vtkPolyDataMapper::New();
    outlineMapper->SetInput(outline->GetOutput());

  vtkActor* outlineActor =  vtkActor::New();
    outlineActor->SetMapper( outlineMapper);

  vtkRenderer* ren1 = vtkRenderer::New();
  vtkRenderer* ren2 = vtkRenderer::New();

  vtkRenderWindow* renWin = vtkRenderWindow::New();
    renWin->AddRenderer(ren2);
    renWin->AddRenderer(ren1);

  vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);

  vtkCellPicker* picker = vtkCellPicker::New();
    picker->SetTolerance(0.005);

  vtkImagePlaneWidget* planeWidgetX = vtkImagePlaneWidget::New();
    planeWidgetX->SetInteractor( iren);
    planeWidgetX->SetKeyPressActivationValue('x');
    planeWidgetX->SetPicker(picker);
    planeWidgetX->GetPlaneProperty()->SetColor(1,0,0);
    planeWidgetX->TextureInterpolateOff();
    planeWidgetX->SetResliceInterpolateToNearestNeighbour();
    planeWidgetX->SetInput(v16->GetOutput());
    planeWidgetX->SetPlaneOrientationToXAxes();
    planeWidgetX->SetSliceIndex(32);
    planeWidgetX->On();

  vtkImagePlaneWidget* planeWidgetY = vtkImagePlaneWidget::New();
    planeWidgetY->SetInteractor( iren);
    planeWidgetY->SetKeyPressActivationValue('y');
    planeWidgetY->SetPicker(picker);
    planeWidgetY->GetPlaneProperty()->SetColor(1,1,0);
    planeWidgetY->TextureInterpolateOn();
    planeWidgetY->SetResliceInterpolateToLinear();
    planeWidgetY->SetInput(v16->GetOutput());
    planeWidgetY->SetPlaneOrientationToYAxes();
    planeWidgetY->SetSlicePosition(102.4);
    planeWidgetY->SetLookupTable( planeWidgetX->GetLookupTable());
    planeWidgetY->On();

  vtkImagePlaneWidget* planeWidgetZ = vtkImagePlaneWidget::New();
    planeWidgetZ->SetInteractor( iren);
    planeWidgetZ->SetKeyPressActivationValue('z');
    planeWidgetZ->SetPicker(picker);
    planeWidgetZ->GetPlaneProperty()->SetColor(0,0,1);
    planeWidgetZ->TextureInterpolateOn();
    planeWidgetZ->SetResliceInterpolateToCubic();
    planeWidgetZ->SetInput(v16->GetOutput());
    planeWidgetZ->SetPlaneOrientationToZAxes();
    planeWidgetZ->SetSliceIndex(25);
    planeWidgetZ->SetLookupTable( planeWidgetX->GetLookupTable());
    planeWidgetZ->On();

  // add a 2D image to test the GetReslice method
  vtkImageMapToColors* colorMap = vtkImageMapToColors::New();
    colorMap->PassAlphaToOutputOff();
    colorMap->SetActiveComponent(0);
    colorMap->SetOutputFormatToLuminance();
    colorMap->SetInput(planeWidgetZ->GetResliceOutput());
    colorMap->SetLookupTable(planeWidgetX->GetLookupTable());

  vtkImageActor* imageActor = vtkImageActor::New();
    imageActor->PickableOff();
    imageActor->SetInput(colorMap->GetOutput());

  // add the actors
  ren1->AddActor( outlineActor);
  ren2->AddActor( imageActor);

  ren1->SetBackground( 0.1, 0.1, 0.2);
  ren2->SetBackground( 0.2, 0.1, 0.2);

  renWin->SetSize( 600, 350);

  ren1->SetViewport(0,0,0.58333,1);
  ren2->SetViewport(0.58333,0,1,1);

  // set the actors' postions
  renWin->Render();
  iren->SetEventPosition( 175,175);
  iren->SetKeyCode('r');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  iren->SetEventPosition( 475,175);
  iren->SetKeyCode('r');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  renWin->Render();

  // test SetKeyPressActivationValue for one of the widgets
  iren->SetKeyCode('z');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);
  iren->SetKeyCode('z');
  iren->InvokeEvent(vtkCommand::CharEvent,NULL);

  ren1->GetActiveCamera()->Elevation(110);
  ren1->GetActiveCamera()->SetViewUp(0, 0, -1);
  ren1->GetActiveCamera()->Azimuth(45);
  ren1->GetActiveCamera()->Dolly(1.15);
  ren1->ResetCameraClippingRange();

  // make the window level work
  int pos1[2] = { 193,187};
  iren->SetEventPosition(pos1);
  iren->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);
  int pos2[2] = { 105,197};
  iren->SetEventPosition(pos2);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);

  // make the plane pushing work by left button
  int pos3[2] = { 244,225};
  iren->SetEventPosition(pos3);
  iren->InvokeEvent(vtkCommand::LeftButtonPressEvent, NULL);
  int pos4[2] = { 196,200};
  iren->SetEventPosition(pos4);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->SetEventPosition(pos3);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL);

  // make the plane pushing work by middle button
  int pos5[2] = { 140,219};
  iren->SetEventPosition(pos5);
  iren->InvokeEvent(vtkCommand::MiddleButtonPressEvent, NULL);
  int pos6[2] = { 202,196};
  iren->SetEventPosition(pos6);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->SetEventPosition(pos5);
  iren->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
  iren->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent, NULL);

  int retVal = vtkRegressionTestImage( renWin );

  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  planeWidgetX->Delete();
  planeWidgetY->Delete();
  planeWidgetZ->Delete();
  colorMap->Delete();
  imageActor->Delete();
  picker->Delete();
  outlineActor->Delete();
  outlineMapper->Delete();
  outline->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  ren2->Delete();
  v16->Delete();

  return !retVal;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    ImageAccumulate.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkImageData.h"
#include "vtkImageSinusoidSource.h"
#include "vtkImageAccumulate.h"
#include "vtkImageViewer.h"
#include "vtkRenderWindowInteractor.h"

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include <math.h>

int ImageAccumulate(int , char *[])
{
  int rval = 0;

  // Create a blank image
  vtkImageSinusoidSource *sinus = vtkImageSinusoidSource::New();
  sinus->SetWholeExtent(0,512-1,0,512-1,0,64-1);
  sinus->SetAmplitude( 0 );
  sinus->Update();

  // Set some value
  sinus->GetOutput()->SetScalarComponentFromDouble (  0,   0,  0, 0, 1);
  sinus->GetOutput()->SetScalarComponentFromDouble ( 10,  10, 10, 0, 2);
  sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 100, 20, 0, 3);
  sinus->GetOutput()->SetScalarComponentFromDouble (100,  10, 30, 0, 4);
  sinus->GetOutput()->SetScalarComponentFromDouble (100, 100, 40, 0, 5);

  vtkImageAccumulate *acc = vtkImageAccumulate::New();
  acc->SetInputConnection( sinus->GetOutputPort() );
  //acc->IgnoreZeroOn();
  //acc->Update();

  acc->Print(cout);
  double min[3], max[3];
  acc->GetMin(min);
  acc->GetMax(max);
  if( min[0] != 0 )
    {
    cerr << "Min: " << min[0] << endl;
    rval++;
    }
  if( max[0] != 5 )
    {
    cerr << "Max: " << max[0] << endl;
    rval++;
    }
  double mean[3];
  long int voxcount = acc->GetVoxelCount();
  acc->GetMean(mean);
  double m = double(1+2+3+4+5)/voxcount;
  if( fabs(mean[0] - m) > 1e-10 )
    {
    cerr << "Mean: " << mean[0] << endl;
    rval++;
    }

  acc->IgnoreZeroOn();
  acc->Update();
  acc->Print( cout );

  sinus->Delete();
  acc->Delete();

  return rval;
}

<commit_msg>ENH: more testing<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    ImageAccumulate.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkImageData.h"
#include "vtkImageSinusoidSource.h"
#include "vtkImageAccumulate.h"
#include "vtkImageViewer.h"
#include "vtkRenderWindowInteractor.h"

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include <math.h>

int ImageAccumulate(int , char *[])
{
  int rval = 0;

  // Create a blank image
  vtkImageSinusoidSource *sinus = vtkImageSinusoidSource::New();
  sinus->SetWholeExtent(0,512-1,0,512-1,0,64-1);
  sinus->SetAmplitude( 0 );
  sinus->Update();

  // Set some value
  sinus->GetOutput()->SetScalarComponentFromDouble (  0,   0,  0, 0, 1);
  sinus->GetOutput()->SetScalarComponentFromDouble ( 10,  10, 10, 0, 2);
  sinus->GetOutput()->SetScalarComponentFromDouble ( 10, 100, 20, 0, 3);
  sinus->GetOutput()->SetScalarComponentFromDouble (100,  10, 30, 0, 4);
  sinus->GetOutput()->SetScalarComponentFromDouble (100, 100, 40, 0, 5);

  vtkImageAccumulate *acc = vtkImageAccumulate::New();
  acc->SetInputConnection( sinus->GetOutputPort() );
  //acc->IgnoreZeroOn();
  acc->Update();

  acc->Print(cout);
  double min[3], max[3];
  acc->GetMin(min);
  acc->GetMax(max);
  if( min[0] != 0 )
    {
    cerr << "Min: " << min[0] << endl;
    rval++;
    }
  if( max[0] != 5 )
    {
    cerr << "Max: " << max[0] << endl;
    rval++;
    }
  double mean[3];
  long int voxcount;
  voxcount = acc->GetVoxelCount();
  acc->GetMean(mean);
  double m = double(1+2+3+4+5)/voxcount;
  if( fabs(mean[0] - m) > 1e-10 )
    {
    cerr << "Mean: " << mean[0] << endl;
    rval++;
    }

  // Test IgnoreZero option
  acc->IgnoreZeroOn();
  acc->Update();
  acc->Print( cout );

  // Simple test
  acc->GetMin(min);
  acc->GetMax(max);
  if( min[0] != 1 )
    {
    cerr << "Min: " << min[0] << endl;
    rval++;
    }
  if( max[0] != 5 )
    {
    cerr << "Max: " << max[0] << endl;
    rval++;
    }
  acc->GetMean(mean);
  if( mean[0] != double(1+2+3+4+5)/5  )
    {
    cerr << "Mean: " << mean[0] << endl;
    rval++;
    }

  sinus->Delete();
  acc->Delete();

  return rval;
}

<|endoftext|>


<commit_before>/*
 * $Id$
 *
 * Copyright (c) 2011 Surfnet
 * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).
 * Copyright (c) 2011 OpenDNSSEC AB (svb)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "config.h"

/* On MacOSX arc4random is only available when we
   undef _ANSI_SOURCE and define _DARWIN_C_SOURCE. */
#ifdef __APPLE__
#undef _ANSI_SOURCE
#define _DARWIN_C_SOURCE 1
#include <stdlib.h>
#endif

#include "resalt.h"

#include "shared/duration.h"

int PolicyUpdateSalt(::ods::kasp::Policy &policy)
{
    /* This will be the salt that we create
     * salt never longer than 255 so 512 can
     * hold a hex encoded version of the salt.
    */
    char salt[512];
    /* for mapping random numbers in range 0..15 to hex characters */
    const char *hex_chars = "0123456789abcdef";
    /* Number of hex characters */
    unsigned int nhex_chars = strlen(hex_chars);

    if (!policy.denial().has_nsec3()) {
        // no nsec3 present so no need to resalt either.
        return 0;
    }

    const ::ods::kasp::NSEC3 &nsec3 = policy.denial().nsec3();
    if ( nsec3.has_salt() && nsec3.has_salt_last_change() ) {
        if (time_now() < nsec3.salt_last_change()+nsec3.resalt() ) {
            // Current time is within resalt period since last change.
            return 0;
        }
    }

    // Seems we have a nsec3 section that needs a salt generated

    // required uint32 resalt = 3 [(xml).path="Resalt", (xml).type=duration]; // re-salting interval
    // required uint32 saltlength = 6 [(xml).path="Hash/Salt/@length"];// nsec3 salt length 0..255
    // optional string salt = 7 [(xml).path="Hash/Salt"];// the actual salt is generated by the enforcer e.g. 0438eb9a93a6d6c5
    // optional uint32 salt_last_change = 8 [(xml).path="Hash/Salt/@lastchanged"]; // timestamp for when the last resalt took place

    unsigned int saltlength = nsec3.saltlength();
    if (saltlength <= 0 || saltlength > 255) {
        // error, saltlength out of range..
        return -3;
    }

#ifdef HAVE_ARC4RANDOM
    for (int i = 0; i < 2*saltlength; ++i) {
        salt[i] = hex_chars[ arc4random() % nhex_chars ];
    }
#else
   srand( time(NULL) );
    for (int i = 0; i < 2*saltlength; ++i) {
        salt[i] = hex_chars[rand()%nhex_chars];

    }
#endif

    policy.mutable_denial()->mutable_nsec3()->set_salt(&salt[0],2*saltlength);
    policy.mutable_denial()->mutable_nsec3()->set_salt_last_change(time_now());
    return 1;
}
<commit_msg>Always include stdlib.h<commit_after>/*
 * $Id$
 *
 * Copyright (c) 2011 Surfnet
 * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).
 * Copyright (c) 2011 OpenDNSSEC AB (svb)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "config.h"

/* On MacOSX arc4random is only available when we
   undef _ANSI_SOURCE and define _DARWIN_C_SOURCE. */
#ifdef __APPLE__
#undef _ANSI_SOURCE
#define _DARWIN_C_SOURCE 1
#endif
#include <stdlib.h>

#include "resalt.h"

#include "shared/duration.h"

int PolicyUpdateSalt(::ods::kasp::Policy &policy)
{
    /* This will be the salt that we create
     * salt never longer than 255 so 512 can
     * hold a hex encoded version of the salt.
    */
    char salt[512];
    /* for mapping random numbers in range 0..15 to hex characters */
    const char *hex_chars = "0123456789abcdef";
    /* Number of hex characters */
    unsigned int nhex_chars = strlen(hex_chars);

    if (!policy.denial().has_nsec3()) {
        // no nsec3 present so no need to resalt either.
        return 0;
    }

    const ::ods::kasp::NSEC3 &nsec3 = policy.denial().nsec3();
    if ( nsec3.has_salt() && nsec3.has_salt_last_change() ) {
        if (time_now() < nsec3.salt_last_change()+nsec3.resalt() ) {
            // Current time is within resalt period since last change.
            return 0;
        }
    }

    // Seems we have a nsec3 section that needs a salt generated

    // required uint32 resalt = 3 [(xml).path="Resalt", (xml).type=duration]; // re-salting interval
    // required uint32 saltlength = 6 [(xml).path="Hash/Salt/@length"];// nsec3 salt length 0..255
    // optional string salt = 7 [(xml).path="Hash/Salt"];// the actual salt is generated by the enforcer e.g. 0438eb9a93a6d6c5
    // optional uint32 salt_last_change = 8 [(xml).path="Hash/Salt/@lastchanged"]; // timestamp for when the last resalt took place

    unsigned int saltlength = nsec3.saltlength();
    if (saltlength <= 0 || saltlength > 255) {
        // error, saltlength out of range..
        return -3;
    }

#ifdef HAVE_ARC4RANDOM
    for (int i = 0; i < 2*saltlength; ++i) {
        salt[i] = hex_chars[ arc4random() % nhex_chars ];
    }
#else
   srand( time(NULL) );
    for (int i = 0; i < 2*saltlength; ++i) {
        salt[i] = hex_chars[rand()%nhex_chars];

    }
#endif

    policy.mutable_denial()->mutable_nsec3()->set_salt(&salt[0],2*saltlength);
    policy.mutable_denial()->mutable_nsec3()->set_salt_last_change(time_now());
    return 1;
}
<|endoftext|>


<commit_before>#ifndef OPCODE_BASE_H
#define OPCODE_BASE_H
#ifndef MSVC
#include "csdl.h"
#include <cstdarg>
#else
#include <cmath>
#include "csdl.h"
#endif

/**
 * Template base class, or pseudo-virtual base class,
 * for writing Csound opcodes in C++.
 * Derive opcode implementation classes like this:
 *
 * DerivedClass : public OpcodeBase<DerivedClass>
 * {
 * public:
 *     // All output fields must be declared first as MYFLT *:
 *     MYFLT *aret1;
 *     // All input fields must be declared next as MYFLT *:
 *     MYFLT *iarg1;
 *     MYFLT *karg2;
 *     MYFLT *aarg3;
 *     // All internal state variables must be declared after that:
 *     size_t state1;
 *     double state2;
 *     MYFLT state3;
 *     // Declare and implement only whichever of these are required:
 *     void init();
 *     void kontrol();
 *     void audio;
 *     void noteoff();
 *     void deinit();
 * };
 */
template<typename T>
class OpcodeBase
{
public:
  int init(CSOUND *csound)
  {
    return NOTOK;
  }
  static int init_(CSOUND *csound, void *opcode_)
  {
    T *opcode = reinterpret_cast<T *>(opcode_);
    if (!csound->reinitflag && !csound->tieflag)
      csound->RegisterDeinitCallback(csound,
                                     &opcode->h, OpcodeBase<T>::noteoff_);
    return opcode->init(csound);
  }
  int kontrol(CSOUND *csound)
  {
    return NOTOK;
  }
  static int kontrol_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast<T *>(opcode)->kontrol(csound);
  }
  int audio(CSOUND *csound)
  {
    return NOTOK;
  }
  static int audio_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast<T *>(opcode)->audio(csound);
  }
  int noteoff(CSOUND *csound)
  {
    return OK;
  }
  static int noteoff_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast< OpcodeBase<T> *>(opcode)->noteoff(csound);
  }
  void log(CSOUND *csound, const char *format,...)
  {
    va_list args;
    va_start(args, format);
    if(csound) {
      csound->MessageV(csound, 0, format, args);
    }
    else {
      vfprintf(stdout, format, args);
    }
    va_end(args);
  }
  void warn(CSOUND *csound, const char *format,...)
  {
    va_list args;
    va_start(args, format);
    if(csound) {
      if(csound->GetMessageLevel(csound) & WARNMSG ||
         csound->GetDebug(csound)) {
        csound->MessageV(csound, CSOUNDMSG_WARNING, format, args);
      }
    }
    else {
      vfprintf(stdout, format, args);
    }
    va_end(args);
  }
  OPDS h;
};

#endif

<commit_msg>Updated to reflect more conformant compilers.<commit_after>#ifndef OPCODE_BASE_H
#define OPCODE_BASE_H
#ifndef MSVC
#include "csdl.h"
#include <cstdarg>
#else
#include <cmath>
#include "csdl.h"
#endif

/**
 * Template base class, or pseudo-virtual base class,
 * for writing Csound opcodes in C++.
 * Derive opcode implementation classes like this:
 *
 * DerivedClass : public OpcodeBase<DerivedClass>
 * {
 * public:
 *     // All output fields must be declared first as MYFLT *:
 *     MYFLT *aret1;
 *     // All input fields must be declared next as MYFLT *:
 *     MYFLT *iarg1;
 *     MYFLT *karg2;
 *     MYFLT *aarg3;
 *     // All internal state variables must be declared after that:
 *     size_t state1;
 *     double state2;
 *     MYFLT state3;
 *     // Declare and implement only whichever of these are required:
 *     void init();
 *     void kontrol();
 *     void audio;
 *     void noteoff();
 *     void deinit();
 * };
 */
template<typename T>
class OpcodeBase
{
public:
  int init(CSOUND *csound)
  {
    return NOTOK;
  }
  static int init_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast<T *>(opcode)->init(csound);
  }
  int kontrol(CSOUND *csound)
  {
    return NOTOK;
  }
  static int kontrol_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast<T *>(opcode)->kontrol(csound);
  }
  int audio(CSOUND *csound)
  {
    return NOTOK;
  }
  static int audio_(CSOUND *csound, void *opcode)
  {
    return reinterpret_cast<T *>(opcode)->audio(csound);
  }
  void log(CSOUND *csound, const char *format,...)
  {
    va_list args;
    va_start(args, format);
    if(csound) {
      csound->MessageV(csound, 0, format, args);
    }
    else {
      vfprintf(stdout, format, args);
    }
    va_end(args);
  }
  void warn(CSOUND *csound, const char *format,...)
  {
    va_list args;
    va_start(args, format);
    if(csound) {
      if(csound->GetMessageLevel(csound) & WARNMSG ||
         csound->GetDebug(csound)) {
        csound->MessageV(csound, CSOUNDMSG_WARNING, format, args);
      }
    }
    else {
      vfprintf(stdout, format, args);
    }
    va_end(args);
  }
  OPDS h;
};

#endif

<|endoftext|>


<commit_before>
#include <togo/image/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/image/pixmap/pixmap.hpp>

#include <togo/support/test.hpp>

#include <cstring>

using namespace togo;

signed main() {
	memory_init();

	Color c_init{0x01, 0x02, 0x03, 0x04};
	Color c_fill1{0xAA, 0xBB, 0xCC, 0xDD};
	Color c_fill2{0xDD, 0xCC, 0xBB, 0xAA};
	auto cp_init = c_init.packed();
	auto cp_fill1 = c_fill1.packed();
	// auto cp_fill2 = c_fill2.packed();

	Pixmap p{PixelFormatID::rgba8};
	pixmap::resize(p, UVec2{1, 1}, c_init);
	TOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 1*1 * 4);
	auto data = reinterpret_cast<u32*>(p.data);
	TOGO_ASSERTE(data[0] == cp_init);

	pixmap::resize(p, UVec2{4, 4}, c_fill1);
	TOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 4*4 * 4);
	data = reinterpret_cast<u32*>(p.data);
	TOGO_ASSERTE(data[0] == cp_init);
	{auto end = pointer_add(data, p.data_size);
	for (auto check = data + 1; check != end; ++check) {
		TOGO_ASSERTE(*check == cp_fill1);
	}}

	{Pixmap copy{p.format};
	pixmap::copy(copy, p);
	TOGO_ASSERTE(
		copy.data_size == p.data_size &&
		std::memcmp(copy.data, p.data, p.data_size) == 0
	);}

	{Pixmap blit{p.format};
	pixmap::resize(blit, UVec2{4, 4}, c_fill2);
	pixmap::blit(blit, p, UVec2{0, 0});
	TOGO_ASSERTE(
		blit.data_size == p.data_size &&
		std::memcmp(blit.data, p.data, p.data_size) == 0
	);}

	return 0;
}
<commit_msg>lib/image/test/pixmap/general: URC.<commit_after>
#include <togo/image/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/image/pixmap/pixmap.hpp>

#include <togo/support/test.hpp>

#include <cstring>

using namespace togo;

signed main() {
	memory_init();

	PixelFormat format{PixelFormatID::rgba};
	auto ps = pixel_format::pixel_size(format);
	Color c_init{0x01, 0x02, 0x03, 0x04};
	Color c_fill1{0xAA, 0xBB, 0xCC, 0xDD};
	Color c_fill2{0xDD, 0xCC, 0xBB, 0xAA};
	auto cp_init = pixel_format::pack(format, c_init);
	auto cp_fill1 = pixel_format::pack(format, c_fill1);
	// auto cp_fill2 = pixel_format::pack(format, c_fill2);

	Pixmap p{format};
	pixmap::resize(p, UVec2{1, 1}, c_init);
	TOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 1*1 * ps);
	auto data = reinterpret_cast<u32*>(p.data);
	TOGO_ASSERTE(data[0] == cp_init);

	pixmap::resize(p, UVec2{4, 4}, c_fill1);
	TOGO_ASSERTE(p.data && p.data_size == p.data_capacity && p.data_size == 4*4 * ps);
	data = reinterpret_cast<u32*>(p.data);
	TOGO_ASSERTE(data[0] == cp_init);
	{auto end = pointer_add(data, p.data_size);
	for (auto check = data + 1; check != end; ++check) {
		TOGO_ASSERTE(*check == cp_fill1);
	}}

	{Pixmap copy{PixelFormatID::xrgb};
	pixmap::copy(copy, p);
	TOGO_ASSERTE(
		copy.data_size == p.data_size &&
		std::memcmp(copy.data, p.data, p.data_size) == 0
	);}

	{Pixmap blit{format};
	pixmap::resize(blit, UVec2{4, 4}, c_fill2);
	pixmap::blit(blit, p, UVec2{0, 0});
	TOGO_ASSERTE(
		blit.data_size == p.data_size &&
		std::memcmp(blit.data, p.data, p.data_size) == 0
	);}

	return 0;
}
<|endoftext|>