<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/gtk_util.h"

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <stdlib.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/linux_util.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "ui/gfx/rect.h"

namespace {

// A process wide singleton that manages our usage of gdk
// cursors. gdk_cursor_new() hits the disk in several places and GdkCursor
// instances can be reused throughout the process.
class GdkCursorCache {
 public:
   GdkCursorCache() {}
  ~GdkCursorCache() {
    for (std::map<GdkCursorType, GdkCursor*>::iterator it =
        cursor_cache_.begin(); it != cursor_cache_.end(); ++it) {
      gdk_cursor_unref(it->second);
    }
    cursor_cache_.clear();
  }

  GdkCursor* GetCursorImpl(GdkCursorType type) {
    std::map<GdkCursorType, GdkCursor*>::iterator it = cursor_cache_.find(type);
    GdkCursor* cursor = NULL;
    if (it == cursor_cache_.end()) {
      cursor = gdk_cursor_new(type);
      cursor_cache_.insert(std::make_pair(type, cursor));
    } else {
      cursor = it->second;
    }

    // It is not necessary to add a reference here. The callers can ref the
    // cursor if they need it for something.
    return cursor;
  }

  std::map<GdkCursorType, GdkCursor*> cursor_cache_;

  DISALLOW_COPY_AND_ASSIGN(GdkCursorCache);
};

void FreePixels(guchar* pixels, gpointer data) {
  free(data);
}

}  // namespace

namespace gfx {

void GtkInitFromCommandLine(const CommandLine& command_line) {
  const std::vector<std::string>& args = command_line.argv();
  int argc = args.size();
  scoped_array<char *> argv(new char *[argc + 1]);
  for (size_t i = 0; i < args.size(); ++i) {
    // TODO(piman@google.com): can gtk_init modify argv? Just being safe
    // here.
    argv[i] = strdup(args[i].c_str());
  }
  argv[argc] = NULL;
  char **argv_pointer = argv.get();

  gtk_init(&argc, &argv_pointer);
  for (size_t i = 0; i < args.size(); ++i) {
    free(argv[i]);
  }
}

GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) {
  if (bitmap->isNull())
    return NULL;

  bitmap->lockPixels();

  int width = bitmap->width();
  int height = bitmap->height();
  int stride = bitmap->rowBytes();

  // SkBitmaps are premultiplied, we need to unpremultiply them.
  const int kBytesPerPixel = 4;
  uint8* divided = static_cast<uint8*>(malloc(height * stride));

  for (int y = 0, i = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      uint32 pixel = bitmap->getAddr32(0, y)[x];

      int alpha = SkColorGetA(pixel);
      if (alpha != 0 && alpha != 255) {
        SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel);
        divided[i + 0] = SkColorGetR(unmultiplied);
        divided[i + 1] = SkColorGetG(unmultiplied);
        divided[i + 2] = SkColorGetB(unmultiplied);
        divided[i + 3] = alpha;
      } else {
        divided[i + 0] = SkColorGetR(pixel);
        divided[i + 1] = SkColorGetG(pixel);
        divided[i + 2] = SkColorGetB(pixel);
        divided[i + 3] = alpha;
      }
      i += kBytesPerPixel;
    }
  }

  // This pixbuf takes ownership of our malloc()ed data and will
  // free it for us when it is destroyed.
  GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(
      divided,
      GDK_COLORSPACE_RGB,  // The only colorspace gtk supports.
      true,  // There is an alpha channel.
      8,
      width, height, stride, &FreePixels, divided);

  bitmap->unlockPixels();
  return pixbuf;
}

void SubtractRectanglesFromRegion(GdkRegion* region,
                                  const std::vector<Rect>& cutouts) {
  for (size_t i = 0; i < cutouts.size(); ++i) {
    GdkRectangle rect = cutouts[i].ToGdkRectangle();
    GdkRegion* rect_region = gdk_region_rectangle(&rect);
    gdk_region_subtract(region, rect_region);
    // TODO(deanm): It would be nice to be able to reuse the GdkRegion here.
    gdk_region_destroy(rect_region);
  }
}

GdkCursor* GetCursor(int type) {
  CR_DEFINE_STATIC_LOCAL(GdkCursorCache, impl, ());
  return impl.GetCursorImpl(static_cast<GdkCursorType>(type));
}

void InitRCStyles() {
  static const char kRCText[] =
      // Make our dialogs styled like the GNOME HIG.
      //
      // TODO(evanm): content-area-spacing was introduced in a later
      // version of GTK, so we need to set that manually on all dialogs.
      // Perhaps it would make sense to have a shared FixupDialog() function.
      "style \"gnome-dialog\" {\n"
      "  xthickness = 12\n"
      "  GtkDialog::action-area-border = 0\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 12\n"
      "}\n"
      // Note we set it at the "application" priority, so users can override.
      "widget \"GtkDialog\" style : application \"gnome-dialog\"\n"

      // Make our about dialog special, so the image is flush with the edge.
      "style \"about-dialog\" {\n"
      "  GtkDialog::action-area-border = 12\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 0\n"
      "}\n"
      "widget \"about-dialog\" style : application \"about-dialog\"\n";

  gtk_rc_parse_string(kRCText);
}

}  // namespace gfx
<commit_msg>ui/gfx: Add a typedef of std::map to improve the readability of GdkCursorCache implementation.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/gtk_util.h"

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <stdlib.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "ui/gfx/rect.h"

namespace {

// A process wide singleton that manages our usage of gdk cursors.
// gdk_cursor_new() hits the disk in several places and GdkCursor instances can
// be reused throughout the process.
class GdkCursorCache {
 public:
  GdkCursorCache() {}
  ~GdkCursorCache() {
    for (GdkCursorMap::iterator i(cursors_.begin()); i != cursors_.end(); ++i) {
      gdk_cursor_unref(i->second);
    }
    cursors_.clear();
  }

  GdkCursor* GetCursorImpl(GdkCursorType type) {
    GdkCursorMap::iterator it = cursors_.find(type);
    GdkCursor* cursor = NULL;
    if (it == cursors_.end()) {
      cursor = gdk_cursor_new(type);
      cursors_.insert(std::make_pair(type, cursor));
    } else {
      cursor = it->second;
    }

    // It is not necessary to add a reference here. The callers can ref the
    // cursor if they need it for something.
    return cursor;
  }

 private:
  typedef std::map<GdkCursorType, GdkCursor*> GdkCursorMap;
  GdkCursorMap cursors_;

  DISALLOW_COPY_AND_ASSIGN(GdkCursorCache);
};

void FreePixels(guchar* pixels, gpointer data) {
  free(data);
}

}  // namespace

namespace gfx {

void GtkInitFromCommandLine(const CommandLine& command_line) {
  const std::vector<std::string>& args = command_line.argv();
  int argc = args.size();
  scoped_array<char *> argv(new char *[argc + 1]);
  for (size_t i = 0; i < args.size(); ++i) {
    // TODO(piman@google.com): can gtk_init modify argv? Just being safe
    // here.
    argv[i] = strdup(args[i].c_str());
  }
  argv[argc] = NULL;
  char **argv_pointer = argv.get();

  gtk_init(&argc, &argv_pointer);
  for (size_t i = 0; i < args.size(); ++i) {
    free(argv[i]);
  }
}

GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) {
  if (bitmap->isNull())
    return NULL;

  bitmap->lockPixels();

  int width = bitmap->width();
  int height = bitmap->height();
  int stride = bitmap->rowBytes();

  // SkBitmaps are premultiplied, we need to unpremultiply them.
  const int kBytesPerPixel = 4;
  uint8* divided = static_cast<uint8*>(malloc(height * stride));

  for (int y = 0, i = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      uint32 pixel = bitmap->getAddr32(0, y)[x];

      int alpha = SkColorGetA(pixel);
      if (alpha != 0 && alpha != 255) {
        SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel);
        divided[i + 0] = SkColorGetR(unmultiplied);
        divided[i + 1] = SkColorGetG(unmultiplied);
        divided[i + 2] = SkColorGetB(unmultiplied);
        divided[i + 3] = alpha;
      } else {
        divided[i + 0] = SkColorGetR(pixel);
        divided[i + 1] = SkColorGetG(pixel);
        divided[i + 2] = SkColorGetB(pixel);
        divided[i + 3] = alpha;
      }
      i += kBytesPerPixel;
    }
  }

  // This pixbuf takes ownership of our malloc()ed data and will
  // free it for us when it is destroyed.
  GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(
      divided,
      GDK_COLORSPACE_RGB,  // The only colorspace gtk supports.
      true,  // There is an alpha channel.
      8,
      width, height, stride, &FreePixels, divided);

  bitmap->unlockPixels();
  return pixbuf;
}

void SubtractRectanglesFromRegion(GdkRegion* region,
                                  const std::vector<Rect>& cutouts) {
  for (size_t i = 0; i < cutouts.size(); ++i) {
    GdkRectangle rect = cutouts[i].ToGdkRectangle();
    GdkRegion* rect_region = gdk_region_rectangle(&rect);
    gdk_region_subtract(region, rect_region);
    // TODO(deanm): It would be nice to be able to reuse the GdkRegion here.
    gdk_region_destroy(rect_region);
  }
}

GdkCursor* GetCursor(int type) {
  CR_DEFINE_STATIC_LOCAL(GdkCursorCache, impl, ());
  return impl.GetCursorImpl(static_cast<GdkCursorType>(type));
}

void InitRCStyles() {
  static const char kRCText[] =
      // Make our dialogs styled like the GNOME HIG.
      //
      // TODO(evanm): content-area-spacing was introduced in a later
      // version of GTK, so we need to set that manually on all dialogs.
      // Perhaps it would make sense to have a shared FixupDialog() function.
      "style \"gnome-dialog\" {\n"
      "  xthickness = 12\n"
      "  GtkDialog::action-area-border = 0\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 12\n"
      "}\n"
      // Note we set it at the "application" priority, so users can override.
      "widget \"GtkDialog\" style : application \"gnome-dialog\"\n"

      // Make our about dialog special, so the image is flush with the edge.
      "style \"about-dialog\" {\n"
      "  GtkDialog::action-area-border = 12\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 0\n"
      "}\n"
      "widget \"about-dialog\" style : application \"about-dialog\"\n";

  gtk_rc_parse_string(kRCText);
}

}  // namespace gfx
<|endoftext|>


<commit_before>/**
    @file SDLSystem.cpp
    @brief Manages the SDL functions.
    @copyright LGPL. MIT License.
*/

#include "Engine/SDLSystem.hpp"

#include "Customs/FirstBossScene.hpp"
#include "Customs/MainScene.hpp"
#include "Customs/GamePlayScene.hpp"
#include "Customs/PreMenuScene.hpp"
#include "Customs/EndScene1.hpp"
#include "Customs/EndScene2.hpp"

// Static variables initialization
SDLSystem *SDLSystem::m_instance = nullptr;

/**
    @brief Initialize the frame counter and the frame ticks counter.
*/
SDLSystem::SDLSystem() {
    m_frameCounter = 0;
    m_lastFrameTicks = 0;
}

/**
    @brief Initialize the instance, window and renderer pointers.
*/
SDLSystem::~SDLSystem() {
    m_instance = nullptr;
    m_window = nullptr;
    m_renderer = nullptr;
}

/**
    @brief Initialize all systems.
*/
void SDLSystem::Init() {
    INFO("SDLSystem::Init() initialized");

    // Check initialization fails
    if (!(InitSDL() && InitIMG() && InitMixer() && InitTTF())) {
        // Display error message
        ERROR("SDLSystem::Init() failed.");
            return;
    }

    // Check creation fails
    if (!(CreateWindow() && CreateRenderer())) {
        // Display error message
        ERROR("SDLSystem::Init() failed.");
            return;
    }

    INFO("SDLSystem::Init() completed");
}

/**
    @brief Runs the SDL library.
*/
void SDLSystem::Run() {
    INFO("Starting Run().");

    m_isRunning = true;

    LoadCommons();
    SceneManager::GetInstance()->SetCurrentScene("Pre Menu");

    SceneManager::GetInstance()->Start();

    // Update utilities while SDL System is running
    while (m_isRunning) {
        if (!FixFramerate()) {
            continue;
        }

        // Clear front buffer.
        SDL_SetRenderDrawColor(m_renderer, 0, 0, 0, 255);
        SDL_RenderClear(m_renderer);

        // Draw update changing the back buffer.
        SceneManager::GetInstance()->DrawUpdate();

        CalculateFramerate();
        InputSystem::GetInstance()->UpdateStates();

        // All updates but draw are called here.
        SceneManager::GetInstance()->Update();

        /*
            Update scene manager and collision system based on
            fixed interval of ticks.
        */
        if (SDL_GetTicks() - m_lastFixedUpdate >
            EngineGlobals::fixed_update_interval) {
            SceneManager::GetInstance()->FixedUpdate();
            CollisionSystem::GetInstance()->Update();
            m_lastFixedUpdate = SDL_GetTicks();
        }

        // Getting back buffer and sending to front buffer.
        SDL_RenderPresent(m_renderer);
    } // while -- Update utilities while SDL System is nunning

    INFO("Ending Run().");
}

/**
    @brief Shut down SDL library and its subsystems used in the game.
*/
void SDLSystem::Shutdown() {
    INFO("Shutdown() Initialized.")

    /*
        Get number of milliseconds since the SDL library initialization
        when it is being shutdown.
    */
    m_gameEndTicks = SDL_GetTicks();

    IMG_Quit();
    Mix_Quit();
    TTF_Quit();
    SDL_Quit();

    INFO("Shutdown completed.")
}

/**
    @brief Get the singleton instance of the game.
    @return The singleton instance of the game
*/
SDLSystem *SDLSystem::GetInstance() {
    // Create if there is no instance
    if (!m_instance) {
        m_instance = new SDLSystem();
    }

    return m_instance;
}

/**
    @brief Initialize the SDL library and starts its subsystems used in the game.
    @return False if the system initialization fails and true if it's succeed.
*/
bool SDLSystem::InitSDL() {
    INFO("Initializing SDL");

    // Receives 0 if the chosen flags are initialized.
    int initialize = SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO |
               SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS);

    // Check initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_ERROR("SDLSystem::InitSDL() failed.");
        return false;
    }

    INFO("SDL Initialized.")
        return true;
}

/**
    @brief Initialize image support.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitIMG() {
    INFO("Initializing IMG");

    // Receives 0 if the chosen flags are initialized
    int flags = IMG_INIT_PNG | IMG_INIT_JPG;
    int initialize = IMG_Init(flags);

    // Check image initialization fail
    if ((initialize & flags) != flags) {
        // Display error message
        SDL_IMG_ERROR("SDLSystem::InitIMG() failed.");
        return false;
    }

    INFO("IMG Initialized.");
    return true;
}

/**
    @brief Initialize the SDL's sound mixing library.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitMixer() {
    INFO("Initializing Mixer");

    // Choose frequency, Uint16 format, channels and chunksize
    int initialize = Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);

    // Check mixer initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_MIX_ERROR("SDLSystem::InitMixer() failed.");
        return false;
    }

    INFO("Mixer Initialized.");
    return true;
}

/**
    @brief Initialize the SDL's TrueType font rendering library.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitTTF() {
    INFO("Initializing TTF");

    int initialize = TTF_Init();

    // Check TTF initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_TTF_ERROR("SDLSystem::InitTTF() failed.");
        return false;
    }

    INFO("TTF Initialized.");
    return true;
}

/**
    @brief Creates a window with the specified title, position and dimensions.
    @return False if the window creation fails and true if it's succeed.
*/
bool SDLSystem::CreateWindow() {
    INFO("Creating window.");

    m_window = SDL_CreateWindow(EngineGlobals::window_title.c_str(),
                                SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                EngineGlobals::screen_width,
                                EngineGlobals::screen_height, SDL_WINDOW_SHOWN);

    // Check window creation fail
    if (!m_window) {
        // Display error message
        SDL_ERROR("SDLSystem::CreateWindow() failed.");
        return false;
    }

    INFO("Created window successfully.");
        return true;
}

/**
    @brief Creates a 2D rendering context for the window.
    @return False if the renderer creation fails and true if it's succeed.
*/
bool SDLSystem::CreateRenderer() {
    INFO("Creating renderer.");

    // Use hardware acceleration with first rendering driver that support it.
    m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);

    // Check renderer creation fail
    if (!m_renderer) {
        // Display error message
        SDL_ERROR("SDLSystem::CreateRenderer() failed.");
        return false;
    }

    SDL_SetRenderDrawBlendMode(m_renderer,SDL_BLENDMODE_BLEND);
    INFO("Created renderer successfully.");
        return true;
}

/**
    @brief Calculates the frame rate.
*/
void SDLSystem::CalculateFramerate() {
    m_currentTicks = SDL_GetTicks();

    if (m_currentTicks - m_lastFrameTicks >= 1000) {
        m_frameRate = m_frameCounter;
        m_frameCounter = 0;
        m_lastFrameTicks = m_currentTicks;
    }
    m_frameCounter++;
}

/**
    @brief Loads necessary game scenes.
*/
void SDLSystem::LoadCommons() {
    auto mainScene = new MainScene();
    auto gameplayScene = new GamePlayScene();
    auto firstBossScene = new FirstBossScene();
    auto preMenuScene = new PreMenuScene();

    auto endScene1 = new EndScene1();
    auto endScene2 = new EndScene2();

    SceneManager::GetInstance()->AddScene(std::make_pair("EndScene1",
                                                         endScene1));
    SceneManager::GetInstance()->AddScene(std::make_pair("EndScene2",
                                                         endScene2));
    SceneManager::GetInstance()->AddScene(std::make_pair("Pre Menu",
                                                         preMenuScene));
    SceneManager::GetInstance()->AddScene(std::make_pair("Main",
                                                         mainScene));
    SceneManager::GetInstance()->AddScene(std::make_pair("Gameplay",
                                                         gameplayScene));
    SceneManager::GetInstance()->AddScene(std::make_pair("FirstBossScene",
                                                         firstBossScene));

}

/**
    @brief Adjusts the Frame rate based in the update rate interval.
    @return False if the calculated interval is less than the update rate
    interval and true if it's not.
*/
bool SDLSystem::FixFramerate() {
    m_currentFix = SDL_GetTicks();
    float fixInterval = m_currentFix - m_lastFix;

    // Compare intervals to check the need to fix frame rate
    if (fixInterval < update_rate_interval){
        return false;
    }

    m_lastFix = SDL_GetTicks();
    return true;
}
<commit_msg>Second application of technique of declaring variables as late as possible - Applied in SDLSystem class<commit_after>/**
    @file SDLSystem.cpp
    @brief Manages the SDL functions.
    @copyright LGPL. MIT License.
*/

#include "Engine/SDLSystem.hpp"

#include "Customs/FirstBossScene.hpp"
#include "Customs/MainScene.hpp"
#include "Customs/GamePlayScene.hpp"
#include "Customs/PreMenuScene.hpp"
#include "Customs/EndScene1.hpp"
#include "Customs/EndScene2.hpp"

// Static variables initialization
SDLSystem *SDLSystem::m_instance = nullptr;

/**
    @brief Initialize the frame counter and the frame ticks counter.
*/
SDLSystem::SDLSystem() {
    m_frameCounter = 0;
    m_lastFrameTicks = 0;
}

/**
    @brief Initialize the instance, window and renderer pointers.
*/
SDLSystem::~SDLSystem() {
    m_instance = nullptr;
    m_window = nullptr;
    m_renderer = nullptr;
}

/**
    @brief Initialize all systems.
*/
void SDLSystem::Init() {
    INFO("SDLSystem::Init() initialized");

    // Check initialization fails
    if (!(InitSDL() && InitIMG() && InitMixer() && InitTTF())) {
        // Display error message
        ERROR("SDLSystem::Init() failed.");
            return;
    }

    // Check creation fails
    if (!(CreateWindow() && CreateRenderer())) {
        // Display error message
        ERROR("SDLSystem::Init() failed.");
            return;
    }

    INFO("SDLSystem::Init() completed");
}

/**
    @brief Runs the SDL library.
*/
void SDLSystem::Run() {
    INFO("Starting Run().");

    m_isRunning = true;

    LoadCommons();
    SceneManager::GetInstance()->SetCurrentScene("Pre Menu");

    SceneManager::GetInstance()->Start();

    // Update utilities while SDL System is running
    while (m_isRunning) {
        if (!FixFramerate()) {
            continue;
        }

        // Clear front buffer.
        SDL_SetRenderDrawColor(m_renderer, 0, 0, 0, 255);
        SDL_RenderClear(m_renderer);

        // Draw update changing the back buffer.
        SceneManager::GetInstance()->DrawUpdate();

        CalculateFramerate();
        InputSystem::GetInstance()->UpdateStates();

        // All updates but draw are called here.
        SceneManager::GetInstance()->Update();

        /*
            Update scene manager and collision system based on
            fixed interval of ticks.
        */
        if (SDL_GetTicks() - m_lastFixedUpdate >
            EngineGlobals::fixed_update_interval) {
            SceneManager::GetInstance()->FixedUpdate();
            CollisionSystem::GetInstance()->Update();
            m_lastFixedUpdate = SDL_GetTicks();
        }

        // Getting back buffer and sending to front buffer.
        SDL_RenderPresent(m_renderer);
    } // while -- Update utilities while SDL System is nunning

    INFO("Ending Run().");
}

/**
    @brief Shut down SDL library and its subsystems used in the game.
*/
void SDLSystem::Shutdown() {
    INFO("Shutdown() Initialized.")

    /*
        Get number of milliseconds since the SDL library initialization
        when it is being shutdown.
    */
    m_gameEndTicks = SDL_GetTicks();

    IMG_Quit();
    Mix_Quit();
    TTF_Quit();
    SDL_Quit();

    INFO("Shutdown completed.")
}

/**
    @brief Get the singleton instance of the game.
    @return The singleton instance of the game
*/
SDLSystem *SDLSystem::GetInstance() {
    // Create if there is no instance
    if (!m_instance) {
        m_instance = new SDLSystem();
    }

    return m_instance;
}

/**
    @brief Initialize the SDL library and starts its subsystems used in the game.
    @return False if the system initialization fails and true if it's succeed.
*/
bool SDLSystem::InitSDL() {
    INFO("Initializing SDL");

    // Receives 0 if the chosen flags are initialized.
    int initialize = SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO |
               SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS);

    // Check initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_ERROR("SDLSystem::InitSDL() failed.");
        return false;
    }

    INFO("SDL Initialized.")
        return true;
}

/**
    @brief Initialize image support.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitIMG() {
    INFO("Initializing IMG");

    // Receives 0 if the chosen flags are initialized
    int flags = IMG_INIT_PNG | IMG_INIT_JPG;
    int initialize = IMG_Init(flags);

    // Check image initialization fail
    if ((initialize & flags) != flags) {
        // Display error message
        SDL_IMG_ERROR("SDLSystem::InitIMG() failed.");
        return false;
    }

    INFO("IMG Initialized.");
    return true;
}

/**
    @brief Initialize the SDL's sound mixing library.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitMixer() {
    INFO("Initializing Mixer");

    // Choose frequency, Uint16 format, channels and chunksize
    int initialize = Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);

    // Check mixer initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_MIX_ERROR("SDLSystem::InitMixer() failed.");
        return false;
    }

    INFO("Mixer Initialized.");
    return true;
}

/**
    @brief Initialize the SDL's TrueType font rendering library.
    @return False if the initialization fails and true if it's succeed.
*/
bool SDLSystem::InitTTF() {
    INFO("Initializing TTF");

    int initialize = TTF_Init();

    // Check TTF initialization fail
    if (initialize != 0) {
        // Display error message
        SDL_TTF_ERROR("SDLSystem::InitTTF() failed.");
        return false;
    }

    INFO("TTF Initialized.");
    return true;
}

/**
    @brief Creates a window with the specified title, position and dimensions.
    @return False if the window creation fails and true if it's succeed.
*/
bool SDLSystem::CreateWindow() {
    INFO("Creating window.");

    m_window = SDL_CreateWindow(EngineGlobals::window_title.c_str(),
                                SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                EngineGlobals::screen_width,
                                EngineGlobals::screen_height, SDL_WINDOW_SHOWN);

    // Check window creation fail
    if (!m_window) {
        // Display error message
        SDL_ERROR("SDLSystem::CreateWindow() failed.");
        return false;
    }

    INFO("Created window successfully.");
        return true;
}

/**
    @brief Creates a 2D rendering context for the window.
    @return False if the renderer creation fails and true if it's succeed.
*/
bool SDLSystem::CreateRenderer() {
    INFO("Creating renderer.");

    // Use hardware acceleration with first rendering driver that support it.
    m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);

    // Check renderer creation fail
    if (!m_renderer) {
        // Display error message
        SDL_ERROR("SDLSystem::CreateRenderer() failed.");
        return false;
    }

    SDL_SetRenderDrawBlendMode(m_renderer,SDL_BLENDMODE_BLEND);
    INFO("Created renderer successfully.");
        return true;
}

/**
    @brief Calculates the frame rate.
*/
void SDLSystem::CalculateFramerate() {
    m_currentTicks = SDL_GetTicks();

    if (m_currentTicks - m_lastFrameTicks >= 1000) {
        m_frameRate = m_frameCounter;
        m_frameCounter = 0;
        m_lastFrameTicks = m_currentTicks;
    }
    m_frameCounter++;
}

/**
    @brief Loads necessary game scenes.
*/
void SDLSystem::LoadCommons() {
    // Instantiate and add multiple scenes to scene manager.
    auto endScene1 = new EndScene1();
    SceneManager::GetInstance()->AddScene(std::make_pair("EndScene1",
                                                         endScene1));
    auto endScene2 = new EndScene2();
    SceneManager::GetInstance()->AddScene(std::make_pair("EndScene2",
                                                         endScene2));
    auto preMenuScene = new PreMenuScene();
    SceneManager::GetInstance()->AddScene(std::make_pair("Pre Menu",
                                                         preMenuScene));
    auto mainScene = new MainScene();
    SceneManager::GetInstance()->AddScene(std::make_pair("Main",
                                                         mainScene));
    auto gameplayScene = new GamePlayScene();
    SceneManager::GetInstance()->AddScene(std::make_pair("Gameplay",
                                                         gameplayScene));
    auto firstBossScene = new FirstBossScene();
    SceneManager::GetInstance()->AddScene(std::make_pair("FirstBossScene",
                                                         firstBossScene));
}

/**
    @brief Adjusts the Frame rate based in the update rate interval.
    @return False if the calculated interval is less than the update rate
    interval and true if it's not.
*/
bool SDLSystem::FixFramerate() {
    m_currentFix = SDL_GetTicks();
    float fixInterval = m_currentFix - m_lastFix;

    // Compare intervals to check the need to fix frame rate
    if (fixInterval < update_rate_interval){
        return false;
    }

    m_lastFix = SDL_GetTicks();
    return true;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxSuperElastixFilter.h"

#include "elxParameterObject.h"

#include "selxElastixComponent.h"
#include "selxMonolithicElastix.h"
#include "selxMonolithicTransformix.h"
#include "selxItkImageSink.h"
#include "selxItkImageSourceFixed.h"
#include "selxItkImageSourceMoving.h"
#include "selxRegistrationController.h"

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "selxDefaultComponents.h"

#include "selxDataManager.h"
#include "gtest/gtest.h"

namespace selx
{
class ElastixComponentTest : public ::testing::Test
{
public:

  typedef std::shared_ptr< Blueprint >                        BlueprintPointer;
  typedef itk::SharedPointerDataObjectDecorator< Blueprint >  BlueprintITKType;
  typedef BlueprintITKType::Pointer                           BlueprintITKPointer;
  typedef Blueprint::ParameterMapType                         ParameterMapType;
  typedef Blueprint::ParameterValueType                       ParameterValueType;
  typedef DataManager                                         DataManagerType;

  /** Make a list of components to be registered for this test*/
  typedef TypeList< ElastixComponent< 2, float >,
    MonolithicElastixComponent< 2, float >,
    MonolithicTransformixComponent< 2, float >,
    ItkImageSinkComponent< 2, float >,
    ItkImageSourceFixedComponent< 2, float >,
    ItkImageSourceMovingComponent< 2, float >,
    ItkImageSourceFixedComponent< 3, double >,
    ItkImageSourceMovingComponent< 3, double >,
    RegistrationControllerComponent< > > RegisterComponents;

  typedef SuperElastixFilter< RegisterComponents > SuperElastixFilterType;

  typedef itk::Image< float, 2 >              Image2DType;
  typedef itk::ImageFileReader< Image2DType > ImageReader2DType;
  typedef itk::ImageFileWriter< Image2DType > ImageWriter2DType;

  virtual void SetUp()
  {
  }

  virtual void TearDown()
  {
    itk::ObjectFactoryBase::UnRegisterAllFactories();
  }

  BlueprintPointer blueprint;
};

TEST_F( ElastixComponentTest, ImagesOnly )
{
  /** make example blueprint configuration */
  blueprint = BlueprintPointer( new Blueprint() );

  ParameterMapType component0Parameters;
  component0Parameters[ "NameOfClass" ]               = { "ElastixComponent" };
  component0Parameters[ "RegistrationSettings" ]      = { "rigid" };
  component0Parameters[ "MaximumNumberOfIterations" ] = { "2" };
  component0Parameters[ "Dimensionality" ] = { "2" };
  component0Parameters[ "PixelType" ] = { "float" };
  component0Parameters[ "ResultImagePixelType" ] = { "float" };

  blueprint->SetComponent( "RegistrationMethod", component0Parameters );

  ParameterMapType component1Parameters;
  component1Parameters[ "NameOfClass" ]    = { "ItkImageSourceFixedComponent" };
  component1Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "FixedImageSource", component1Parameters );

  ParameterMapType component2Parameters;
  component2Parameters[ "NameOfClass" ]    = { "ItkImageSourceMovingComponent" };
  component2Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "MovingImageSource", component2Parameters );

  ParameterMapType component3Parameters;
  component3Parameters[ "NameOfClass" ]    = { "ItkImageSinkComponent" };
  component3Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "ResultImageSink", component3Parameters );

  blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } );

  ParameterMapType connection1Parameters;
  //connection1Parameters["NameOfInterface"] = { "itkImageFixedInterface" };
  blueprint->SetConnection( "FixedImageSource", "RegistrationMethod", connection1Parameters );

  ParameterMapType connection2Parameters;
  //connection2Parameters["NameOfInterface"] = { "itkImageMovingInterface" };
  blueprint->SetConnection( "MovingImageSource", "RegistrationMethod", connection2Parameters );

  ParameterMapType connection3Parameters;
  //connection3Parameters["NameOfInterface"] = { "GetItkImageInterface" };
  blueprint->SetConnection( "RegistrationMethod", "ResultImageSink", connection3Parameters );

  blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } ); //
  blueprint->SetConnection( "ResultImageSink", "Controller", { {} } );    //
  // Instantiate SuperElastix
  SuperElastixFilterType::Pointer superElastixFilter;
  EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() );

  // Data manager provides the paths to the input and output data for unit tests
  DataManagerType::Pointer dataManager = DataManagerType::New();

  // Set up the readers and writers
  ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New();
  fixedImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceBorder20.png" ) );

  ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New();
  movingImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceR10X13Y17.png" ) );

  ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New();
  resultImageWriter->SetFileName( dataManager->GetOutputFile( "ElastixComponentTest_BrainProtonDensity.mhd" ) );

  // Connect SuperElastix in an itk pipeline
  superElastixFilter->SetInput( "FixedImageSource", fixedImageReader->GetOutput() );
  superElastixFilter->SetInput( "MovingImageSource", movingImageReader->GetOutput() );
  resultImageWriter->SetInput( superElastixFilter->GetOutput< Image2DType >( "ResultImageSink" ) );

  BlueprintITKPointer ITKBlueprint = BlueprintITKType::New();
  ITKBlueprint->Set( blueprint );
  EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) );

  //Optional Update call
  //superElastixFilter->Update();

  // Update call on the writers triggers SuperElastix to configure and execute
  EXPECT_NO_THROW( resultImageWriter->Update() );
}
TEST_F( ElastixComponentTest, MonolithicElastixTransformix )
{
  /** make example blueprint configuration */
  blueprint = BlueprintPointer( new Blueprint() );

  blueprint->SetComponent( "RegistrationMethod", { { "NameOfClass", { "MonolithicElastixComponent" } },
                                                   { "RegistrationSettings", { "rigid" } }, { "MaximumNumberOfIterations", { "2" } } } );
  blueprint->SetComponent( "TransformDisplacementField", { { "NameOfClass", { "MonolithicTransformixComponent" } } } );

  blueprint->SetComponent( "FixedImageSource", { { "NameOfClass", { "ItkImageSourceFixedComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "MovingImageSource", { { "NameOfClass", { "ItkImageSourceMovingComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "ResultImageSink", { { "NameOfClass", { "ItkImageSinkComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } );

  blueprint->SetConnection( "FixedImageSource", "RegistrationMethod", { { "NameOfInterface", { "itkImageFixedInterface" } } } ); // ;

  blueprint->SetConnection( "MovingImageSource", "RegistrationMethod", { { "NameOfInterface", { "itkImageMovingInterface" } } } ); // ;

  blueprint->SetConnection( "RegistrationMethod", "TransformDisplacementField", { { "NameOfInterface", { "elastixTransformParameterObjectInterface" } } } ); // ;

  blueprint->SetConnection( "FixedImageSource", "TransformDisplacementField", { { "NameOfInterface", { "itkImageDomainFixedInterface" } } } ); // ;

  blueprint->SetConnection( "MovingImageSource", "TransformDisplacementField", { { "NameOfInterface", { "itkImageMovingInterface" } } } ); //;

  blueprint->SetConnection( "TransformDisplacementField", "ResultImageSink", { { "NameOfInterface", { "itkImageInterface" } } } ); // ;

  blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } );         //
  blueprint->SetConnection( "TransformDisplacementField", "Controller", { {} } ); //
  blueprint->SetConnection( "ResultImageSink", "Controller", { {} } );            //

  // Instantiate SuperElastix
  SuperElastixFilterType::Pointer superElastixFilter;
  EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() );

  // Data manager provides the paths to the input and output data for unit tests
  DataManagerType::Pointer dataManager = DataManagerType::New();

  // Set up the readers and writers
  ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New();
  fixedImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceBorder20.png" ) );

  ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New();
  movingImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceR10X13Y17.png" ) );

  ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New();
  resultImageWriter->SetFileName( dataManager->GetOutputFile( "ElastixComponentTest_BrainProtonDensity.mhd" ) );

  // Connect SuperElastix in an itk pipeline
  superElastixFilter->SetInput( "FixedImageSource", fixedImageReader->GetOutput() );
  superElastixFilter->SetInput( "MovingImageSource", movingImageReader->GetOutput() );
  resultImageWriter->SetInput( superElastixFilter->GetOutput< Image2DType >( "ResultImageSink" ) );

  BlueprintITKPointer ITKBlueprint = BlueprintITKType::New();
  ITKBlueprint->Set( blueprint );
  EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) );

  //Optional Update call
  //superElastixFilter->Update();

  // Update call on the writers triggers SuperElastix to configure and execute
  EXPECT_NO_THROW( resultImageWriter->Update() );
}
} // namespace selx
<commit_msg>BUG: need explicit ResultImagePixelType for MonolithicElastixComponent<commit_after>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxSuperElastixFilter.h"

#include "elxParameterObject.h"

#include "selxElastixComponent.h"
#include "selxMonolithicElastix.h"
#include "selxMonolithicTransformix.h"
#include "selxItkImageSink.h"
#include "selxItkImageSourceFixed.h"
#include "selxItkImageSourceMoving.h"
#include "selxRegistrationController.h"

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "selxDefaultComponents.h"

#include "selxDataManager.h"
#include "gtest/gtest.h"

namespace selx
{
class ElastixComponentTest : public ::testing::Test
{
public:

  typedef std::shared_ptr< Blueprint >                        BlueprintPointer;
  typedef itk::SharedPointerDataObjectDecorator< Blueprint >  BlueprintITKType;
  typedef BlueprintITKType::Pointer                           BlueprintITKPointer;
  typedef Blueprint::ParameterMapType                         ParameterMapType;
  typedef Blueprint::ParameterValueType                       ParameterValueType;
  typedef DataManager                                         DataManagerType;

  /** Make a list of components to be registered for this test*/
  typedef TypeList< ElastixComponent< 2, float >,
    MonolithicElastixComponent< 2, float >,
    MonolithicTransformixComponent< 2, float >,
    ItkImageSinkComponent< 2, float >,
    ItkImageSourceFixedComponent< 2, float >,
    ItkImageSourceMovingComponent< 2, float >,
    ItkImageSourceFixedComponent< 3, double >,
    ItkImageSourceMovingComponent< 3, double >,
    RegistrationControllerComponent< > > RegisterComponents;

  typedef SuperElastixFilter< RegisterComponents > SuperElastixFilterType;

  typedef itk::Image< float, 2 >              Image2DType;
  typedef itk::ImageFileReader< Image2DType > ImageReader2DType;
  typedef itk::ImageFileWriter< Image2DType > ImageWriter2DType;

  virtual void SetUp()
  {
  }

  virtual void TearDown()
  {
    itk::ObjectFactoryBase::UnRegisterAllFactories();
  }

  BlueprintPointer blueprint;
};

TEST_F( ElastixComponentTest, ImagesOnly )
{
  /** make example blueprint configuration */
  blueprint = BlueprintPointer( new Blueprint() );

  ParameterMapType component0Parameters;
  component0Parameters[ "NameOfClass" ]               = { "ElastixComponent" };
  component0Parameters[ "RegistrationSettings" ]      = { "rigid" };
  component0Parameters[ "MaximumNumberOfIterations" ] = { "2" };
  component0Parameters[ "Dimensionality" ] = { "2" };
  component0Parameters[ "PixelType" ] = { "float" };
  component0Parameters[ "ResultImagePixelType" ] = { "float" };

  blueprint->SetComponent( "RegistrationMethod", component0Parameters );

  ParameterMapType component1Parameters;
  component1Parameters[ "NameOfClass" ]    = { "ItkImageSourceFixedComponent" };
  component1Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "FixedImageSource", component1Parameters );

  ParameterMapType component2Parameters;
  component2Parameters[ "NameOfClass" ]    = { "ItkImageSourceMovingComponent" };
  component2Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "MovingImageSource", component2Parameters );

  ParameterMapType component3Parameters;
  component3Parameters[ "NameOfClass" ]    = { "ItkImageSinkComponent" };
  component3Parameters[ "Dimensionality" ] = { "2" }; // should be derived from the inputs
  blueprint->SetComponent( "ResultImageSink", component3Parameters );

  blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } );

  ParameterMapType connection1Parameters;
  //connection1Parameters["NameOfInterface"] = { "itkImageFixedInterface" };
  blueprint->SetConnection( "FixedImageSource", "RegistrationMethod", connection1Parameters );

  ParameterMapType connection2Parameters;
  //connection2Parameters["NameOfInterface"] = { "itkImageMovingInterface" };
  blueprint->SetConnection( "MovingImageSource", "RegistrationMethod", connection2Parameters );

  ParameterMapType connection3Parameters;
  //connection3Parameters["NameOfInterface"] = { "GetItkImageInterface" };
  blueprint->SetConnection( "RegistrationMethod", "ResultImageSink", connection3Parameters );

  blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } ); //
  blueprint->SetConnection( "ResultImageSink", "Controller", { {} } );    //
  // Instantiate SuperElastix
  SuperElastixFilterType::Pointer superElastixFilter;
  EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() );

  // Data manager provides the paths to the input and output data for unit tests
  DataManagerType::Pointer dataManager = DataManagerType::New();

  // Set up the readers and writers
  ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New();
  fixedImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceBorder20.png" ) );

  ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New();
  movingImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceR10X13Y17.png" ) );

  ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New();
  resultImageWriter->SetFileName( dataManager->GetOutputFile( "ElastixComponentTest_BrainProtonDensity.mhd" ) );

  // Connect SuperElastix in an itk pipeline
  superElastixFilter->SetInput( "FixedImageSource", fixedImageReader->GetOutput() );
  superElastixFilter->SetInput( "MovingImageSource", movingImageReader->GetOutput() );
  resultImageWriter->SetInput( superElastixFilter->GetOutput< Image2DType >( "ResultImageSink" ) );

  BlueprintITKPointer ITKBlueprint = BlueprintITKType::New();
  ITKBlueprint->Set( blueprint );
  EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) );

  //Optional Update call
  //superElastixFilter->Update();

  // Update call on the writers triggers SuperElastix to configure and execute
  EXPECT_NO_THROW( resultImageWriter->Update() );
}
TEST_F(ElastixComponentTest, MonolithicElastixTransformix)
{
  /** make example blueprint configuration */
  blueprint = BlueprintPointer(new Blueprint());

  blueprint->SetComponent("RegistrationMethod", { { "NameOfClass", { "MonolithicElastixComponent" } },
  { "RegistrationSettings", { "rigid" } }, { "MaximumNumberOfIterations", { "2" } },
  {"Dimensionality", { "2" } },
  { "PixelType", { "float" } },
  { "ResultImagePixelType", { "float" } }
});
  blueprint->SetComponent( "TransformDisplacementField", { { "NameOfClass", { "MonolithicTransformixComponent" } } } );

  blueprint->SetComponent( "FixedImageSource", { { "NameOfClass", { "ItkImageSourceFixedComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "MovingImageSource", { { "NameOfClass", { "ItkImageSourceMovingComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "ResultImageSink", { { "NameOfClass", { "ItkImageSinkComponent" } }, { "Dimensionality", { "2" } } } );

  blueprint->SetComponent( "Controller", { { "NameOfClass", { "RegistrationControllerComponent" } } } );

  blueprint->SetConnection( "FixedImageSource", "RegistrationMethod", { { "NameOfInterface", { "itkImageFixedInterface" } } } ); // ;

  blueprint->SetConnection( "MovingImageSource", "RegistrationMethod", { { "NameOfInterface", { "itkImageMovingInterface" } } } ); // ;

  blueprint->SetConnection( "RegistrationMethod", "TransformDisplacementField", { { "NameOfInterface", { "elastixTransformParameterObjectInterface" } } } ); // ;

  blueprint->SetConnection( "FixedImageSource", "TransformDisplacementField", { { "NameOfInterface", { "itkImageDomainFixedInterface" } } } ); // ;

  blueprint->SetConnection( "MovingImageSource", "TransformDisplacementField", { { "NameOfInterface", { "itkImageMovingInterface" } } } ); //;

  blueprint->SetConnection( "TransformDisplacementField", "ResultImageSink", { { "NameOfInterface", { "itkImageInterface" } } } ); // ;

  blueprint->SetConnection( "RegistrationMethod", "Controller", { {} } );         //
  blueprint->SetConnection( "TransformDisplacementField", "Controller", { {} } ); //
  blueprint->SetConnection( "ResultImageSink", "Controller", { {} } );            //

  // Instantiate SuperElastix
  SuperElastixFilterType::Pointer superElastixFilter;
  EXPECT_NO_THROW( superElastixFilter = SuperElastixFilterType::New() );

  // Data manager provides the paths to the input and output data for unit tests
  DataManagerType::Pointer dataManager = DataManagerType::New();

  // Set up the readers and writers
  ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New();
  fixedImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceBorder20.png" ) );

  ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New();
  movingImageReader->SetFileName( dataManager->GetInputFile( "BrainProtonDensitySliceR10X13Y17.png" ) );

  ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New();
  resultImageWriter->SetFileName( dataManager->GetOutputFile( "ElastixComponentTest_BrainProtonDensity.mhd" ) );

  // Connect SuperElastix in an itk pipeline
  superElastixFilter->SetInput( "FixedImageSource", fixedImageReader->GetOutput() );
  superElastixFilter->SetInput( "MovingImageSource", movingImageReader->GetOutput() );
  resultImageWriter->SetInput( superElastixFilter->GetOutput< Image2DType >( "ResultImageSink" ) );

  BlueprintITKPointer ITKBlueprint = BlueprintITKType::New();
  ITKBlueprint->Set( blueprint );
  EXPECT_NO_THROW( superElastixFilter->SetBlueprint( ITKBlueprint ) );

  //Optional Update call
  //superElastixFilter->Update();

  // Update call on the writers triggers SuperElastix to configure and execute
  EXPECT_NO_THROW( resultImageWriter->Update() );
}
} // namespace selx
<|endoftext|>


<commit_before>#include <bitset>
#include <vector>
#include <Refal2.h>

namespace Refal2 {

void CFunctionCompiler::removeCurrentHole()
{
	if( currentHole == firstHole ) {
		firstHole = currentHole->nextHole;
		delete currentHole;
		currentHole = firstHole;
	} else {
		CHole* i = firstHole;
		while( i->nextHole != currentHole ) {
			i = i->nextHole;
		}

		i->nextHole = currentHole->nextHole;
		delete currentHole;
		currentHole = i;
	}
}

void CFunctionCompiler::compileRule(CFunctionRule* rule)
{
	firstHole = new CHole;
	rule->leftPart.Move( &(firstHole->hole) );
	rule->variables.Move( &variables );

	do {
		// HSCH
		currentHole = firstHole;

		// HSCH 1
		do {
			CUnitNode* left = currentHole->hole.GetFirst();
			CUnitNode* right = currentHole->hole.GetLast();

			if( isMarkedVariable(left) )
			{
				// HSCH 2
				classes.push_back( CHolesTuple(
					markedStackDepth[left->Variable()], currentHole ) );
				markedVariables.reset( left->Variable() );
				break;
			} else {
				// HSCH 3
				if( left != right && isFreeVE(left) && isFreeVE(right) ) {
					currentHole = currentHole->nextHole;
				} else {
					matchElement();
					currentHole = firstHole;
				}
			}
		} while( currentHole != 0 );

		// HSCH 4
		if( firstHole == 0 ) {
			if( !classes.empty() ) {
				// TODO: EOE( stackDepth - classes.back().stackDepth );
				firstHole = classes.back().firstHole;
				classes.pop_back();
			}
		} else {
			matchVE();
		}
	} while( firstHole != 0 );
}

TVariablesMask CFunctionCompiler::makeVariablesMask(const CHole& hole) const
{
	TVariablesMask variablesMask;
	for( const CUnitNode* i = hole.hole.GetFirst(); i != 0; i = i->Next() ) {
		if( i->IsVariable() && !variables.IsSet( i->Variable() ) ) {
			variablesMask.set( i->Variable() );
		}
	}
	return variablesMask;
}

struct CHoleInfo {
	CHole* hole;
	TVariablesMask variablesMask;
	std::size_t classid;

	CHoleInfo(CHole* _hole = 0):
		hole(_hole), classid(0) {}
};

void CFunctionCompiler::splitIntoClasses(CHole* const holes)
{
	std::vector<CHoleInfo> info;
	for( CHole* i = holes; i != 0; i = i->nextHole ) {
		info.push_back( CHoleInfo(i) );
		info.back().variablesMask = makeVariablesMask(*i);
	}

	std::size_t classid = 0;
	for( std::size_t i = 0; i < info.size() - 1; i++ ) {
		if( info[i].classid == 0 ) {
			info[i].classid = ++classid;
			TVariablesMask variablesMask = info[i].variablesMask;

			for( std::size_t j = i + 1; j < info.size(); j++ ) {
				if( info[j].classid == 0 &&
					(info[j].variablesMask & variablesMask).any() )
				{
					info[j].classid = classid;
					variablesMask |= info[j].variablesMask;
					j = i;
				}
			}
		}
	}

	if( classid > 1 ) {
		for( std::size_t i = 0; i < classid; i++ ) {
			classes.push_back( CHolesTuple(stackDepth) );
		}

		std::size_t offset = classes.size() - classid - 1;
		for( std::size_t i = 0; i < info.size(); i++ ) {
			CHole*& tmp = classes[offset + info[i].classid].firstHole;
			info[i].hole->nextHole = tmp;
			tmp = info[i].hole;
		}
	} else {
		classes.push_back( CHolesTuple(stackDepth, holes) );
	}
}

void CFunctionCompiler::matchVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchVE()\n");
	currentHole = firstHole;
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchElement()
{
	//if( currentLeft != currentHole->left || currentRight != currentHole->Right ) {
		/* TODO: SB( currentHole->left, currentHole->Right ) */
	//}

	if( currentHole->hole.IsEmpty() ) {
		matchEmptyExpression();
	} else {
		CUnitNode* left = currentHole->hole.GetFirst();
		CUnitNode* right = currentHole->hole.GetLast();

		if( left == left && isFreeVE(left) ) {
			matchClosedE();
		} else if( left->IsParen() ) {
			matchLeftParens();
		} else if( left->IsSymbol() ) {
			matchLeftSymbol();
		} else if( left->IsVariable() && tryMatchLeftVariable( left ) ) {
		} else if( right->IsParen() ) {
			matchRightParens();
		} else if( right->IsSymbol() ) {
			matchRightSymbol();
		} else if( right->IsVariable() && tryMatchRightVariable( right ) ) {
		} else {
			assert( false );
		}
	}
}

bool CFunctionCompiler::tryMatchLeftVariable(CUnitNode* left)
{
	switch( variables.GetVariable( left->Variable() )->GetType() ) {
		case 's':
			matchLeftS();
			return true;
			break;
		case 'w':
			matchLeftW();
			return true;
			break;
		case 'v':
		case 'e':
			if( variables.IsSet( left->Variable() ) ) {
				matchLeftDuplicateVE();
				return true;
			}
			break;
		default:
			assert( false );
			break;
	}
	return false;
}

bool CFunctionCompiler::tryMatchRightVariable(CUnitNode* right)
{
	switch( variables.GetVariable( right->Variable() )->GetType() ) {
		case 's':
			matchRightS();
			return true;
			break;
		case 'w':
			matchRightW();
			return true;
			break;
		case 'v':
		case 'e':
			if( variables.IsSet( right->Variable() ) ) {
				matchRightDuplicateVE();
				return true;
			}
			break;
		default:
			assert( false );
			break;
	}
	return false;
}

void CFunctionCompiler::matchEmptyExpression()
{
	// TODO: action
	printf("CFunctionCompiler::matchEmptyExpression()\n");
	removeCurrentHole();
}

void CFunctionCompiler::matchClosedE()
{
	// TODO: action
	printf("CFunctionCompiler::matchClosedE()\n");
	delete detachLeftUnitInCurrentHole();
	removeCurrentHole();
}

void CFunctionCompiler::matchLeftParens()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftParens()\n");

	CUnitNode* begin = currentHole->hole.GetFirst();
	CUnitNode* end = currentHole->hole.GetLast();
	CUnitNode* beginNew = begin->PairedParen()->Next();
	CUnitNode* endNew = 0;
	if( beginNew != 0 ) {
		endNew = end;
		currentHole->hole.Detach( beginNew, endNew );
	}

	delete detachLeftUnitInCurrentHole();
	delete detachRightUnitInCurrentHole();

	CHole* tmp = new CHole;
	tmp->hole.Assign( beginNew, endNew );
	tmp->nextHole = currentHole->nextHole;
	currentHole->nextHole = tmp;
}

void CFunctionCompiler::matchRightParens()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightParens()\n");

	CUnitNode* begin = currentHole->hole.GetFirst();
	CUnitNode* end = currentHole->hole.GetLast();
	CUnitNode* beginNew = 0;
	CUnitNode* endNew = end->PairedParen()->Prev();
	if( endNew != 0 ) {
		beginNew = begin;
		currentHole->hole.Detach( beginNew, endNew );
	}

	delete detachLeftUnitInCurrentHole();
	delete detachRightUnitInCurrentHole();

	CHole* tmp = new CHole;
	tmp->hole.Assign( beginNew, endNew );
	tmp->nextHole = currentHole->nextHole;
	currentHole->nextHole = tmp;
}

void CFunctionCompiler::matchLeftSymbol()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftSymbol()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightSymbol()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightSymbol()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftS()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftS()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightS()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightS()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftW()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftW()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightW()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightW()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftDuplicateVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftDuplicateVE()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightDuplicateVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightDuplicateVE()\n");
	delete detachRightUnitInCurrentHole();
}

} // end of namespace refal2
<commit_msg>small error fixes<commit_after>#include <bitset>
#include <vector>
#include <Refal2.h>

namespace Refal2 {

void CFunctionCompiler::removeCurrentHole()
{
	if( currentHole == firstHole ) {
		firstHole = currentHole->nextHole;
		delete currentHole;
		currentHole = firstHole;
	} else {
		CHole* i = firstHole;
		while( i->nextHole != currentHole ) {
			i = i->nextHole;
		}

		i->nextHole = currentHole->nextHole;
		delete currentHole;
		currentHole = i;
	}
}

void CFunctionCompiler::compileRule(CFunctionRule* rule)
{
	firstHole = new CHole;
	rule->leftPart.Move( &(firstHole->hole) );
	rule->variables.Move( &variables );

	do {
		// HSCH
		currentHole = firstHole;

		// HSCH 1
		do {
			CUnitNode* left = currentHole->hole.GetFirst();
			CUnitNode* right = currentHole->hole.GetLast();

			if( isMarkedVariable(left) )
			{
				// HSCH 2
				classes.push_back( CHolesTuple(
					markedStackDepth[left->Variable()], currentHole ) );
				markedVariables.reset( left->Variable() );
				break;
			} else {
				// HSCH 3
				if( left != right && isFreeVE(left) && isFreeVE(right) ) {
					currentHole = currentHole->nextHole;
				} else {
					matchElement();
					currentHole = firstHole;
				}
			}
		} while( currentHole != 0 );

		// HSCH 4
		if( firstHole == 0 ) {
			if( !classes.empty() ) {
				// TODO: EOE( stackDepth - classes.back().stackDepth );
				firstHole = classes.back().firstHole;
				classes.pop_back();
			}
		} else {
			matchVE();
		}
	} while( firstHole != 0 );
}

TVariablesMask CFunctionCompiler::makeVariablesMask(const CHole& hole) const
{
	TVariablesMask variablesMask;
	for( const CUnitNode* i = hole.hole.GetFirst(); i != 0; i = i->Next() ) {
		if( i->IsVariable() && !variables.IsSet( i->Variable() ) ) {
			variablesMask.set( i->Variable() );
		}
	}
	return variablesMask;
}

struct CHoleInfo {
	CHole* hole;
	TVariablesMask variablesMask;
	std::size_t classid;

	CHoleInfo(CHole* _hole = 0):
		hole(_hole), classid(0) {}
};

void CFunctionCompiler::splitIntoClasses(CHole* const holes)
{
	std::vector<CHoleInfo> info;
	for( CHole* i = holes; i != 0; i = i->nextHole ) {
		info.push_back( CHoleInfo(i) );
		info.back().variablesMask = makeVariablesMask(*i);
	}

	std::size_t classid = 0;
	for( std::size_t i = 0; i < info.size() - 1; i++ ) {
		if( info[i].classid == 0 ) {
			info[i].classid = ++classid;
			TVariablesMask variablesMask = info[i].variablesMask;

			for( std::size_t j = i + 1; j < info.size(); j++ ) {
				if( info[j].classid == 0 &&
					(info[j].variablesMask & variablesMask).any() )
				{
					info[j].classid = classid;
					variablesMask |= info[j].variablesMask;
					j = i;
				}
			}
		}
	}

	if( classid > 1 ) {
		for( std::size_t i = 0; i < classid; i++ ) {
			classes.push_back( CHolesTuple(stackDepth) );
		}

		std::size_t offset = classes.size() - classid - 1;
		for( std::size_t i = 0; i < info.size(); i++ ) {
			CHole*& tmp = classes[offset + info[i].classid].firstHole;
			info[i].hole->nextHole = tmp;
			tmp = info[i].hole;
		}
	} else {
		classes.push_back( CHolesTuple(stackDepth, holes) );
	}
}

void CFunctionCompiler::matchVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchVE()\n");
	currentHole = firstHole;
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchElement()
{
	//if( currentLeft != currentHole->left || currentRight != currentHole->Right ) {
		/* TODO: SB( currentHole->left, currentHole->Right ) */
	//}

	if( currentHole->hole.IsEmpty() ) {
		matchEmptyExpression();
	} else {
		CUnitNode* left = currentHole->hole.GetFirst();
		CUnitNode* right = currentHole->hole.GetLast();

		if( left == right && isFreeVE(left) ) {
			matchClosedE();
		} else if( left->IsParen() ) {
			matchLeftParens();
		} else if( left->IsSymbol() ) {
			matchLeftSymbol();
		} else if( left->IsVariable() && tryMatchLeftVariable( left ) ) {
		} else if( right->IsParen() ) {
			matchRightParens();
		} else if( right->IsSymbol() ) {
			matchRightSymbol();
		} else if( right->IsVariable() && tryMatchRightVariable( right ) ) {
		} else {
			assert( false );
		}
	}
}

bool CFunctionCompiler::tryMatchLeftVariable(CUnitNode* left)
{
	switch( variables.GetVariable( left->Variable() )->GetType() ) {
		case 's':
			matchLeftS();
			return true;
			break;
		case 'w':
			matchLeftW();
			return true;
			break;
		case 'v':
		case 'e':
			if( variables.IsSet( left->Variable() ) ) {
				matchLeftDuplicateVE();
				return true;
			}
			break;
		default:
			assert( false );
			break;
	}
	return false;
}

bool CFunctionCompiler::tryMatchRightVariable(CUnitNode* right)
{
	switch( variables.GetVariable( right->Variable() )->GetType() ) {
		case 's':
			matchRightS();
			return true;
			break;
		case 'w':
			matchRightW();
			return true;
			break;
		case 'v':
		case 'e':
			if( variables.IsSet( right->Variable() ) ) {
				matchRightDuplicateVE();
				return true;
			}
			break;
		default:
			assert( false );
			break;
	}
	return false;
}

void CFunctionCompiler::matchEmptyExpression()
{
	// TODO: action
	printf("CFunctionCompiler::matchEmptyExpression()\n");
	removeCurrentHole();
}

void CFunctionCompiler::matchClosedE()
{
	// TODO: action
	printf("CFunctionCompiler::matchClosedE()\n");
	delete detachLeftUnitInCurrentHole();
	removeCurrentHole();
}

void CFunctionCompiler::matchLeftParens()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftParens()\n");

	CUnitNode* begin = currentHole->hole.GetFirst();
	CUnitNode* end = currentHole->hole.GetLast();
	CUnitNode* beginNew = begin->PairedParen()->Next();
	CUnitNode* endNew = 0;
	if( beginNew != 0 ) {
		endNew = end;
		currentHole->hole.Detach( beginNew, endNew );
	}

	delete detachLeftUnitInCurrentHole();
	delete detachRightUnitInCurrentHole();

	CHole* tmp = new CHole;
	tmp->hole.Assign( beginNew, endNew );
	tmp->nextHole = currentHole->nextHole;
	currentHole->nextHole = tmp;
}

void CFunctionCompiler::matchRightParens()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightParens()\n");

	CUnitNode* begin = currentHole->hole.GetFirst();
	CUnitNode* end = currentHole->hole.GetLast();
	CUnitNode* beginNew = 0;
	CUnitNode* endNew = end->PairedParen()->Prev();
	if( endNew != 0 ) {
		beginNew = begin;
		currentHole->hole.Detach( beginNew, endNew );
	}

	delete detachLeftUnitInCurrentHole();
	delete detachRightUnitInCurrentHole();

	CHole* tmp = new CHole;
	tmp->hole.Assign( beginNew, endNew );
	tmp->nextHole = currentHole->nextHole;
	currentHole->nextHole = tmp;
}

void CFunctionCompiler::matchLeftSymbol()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftSymbol()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightSymbol()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightSymbol()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftS()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftS()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightS()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightS()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftW()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftW()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightW()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightW()\n");
	delete detachRightUnitInCurrentHole();
}

void CFunctionCompiler::matchLeftDuplicateVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchLeftDuplicateVE()\n");
	delete detachLeftUnitInCurrentHole();
}

void CFunctionCompiler::matchRightDuplicateVE()
{
	// TODO: action
	printf("CFunctionCompiler::matchRightDuplicateVE()\n");
	delete detachRightUnitInCurrentHole();
}

} // end of namespace refal2
<|endoftext|>


<commit_before>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"

// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"

// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"

// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"

// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"

// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"

#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"

#include <iostream>
#include <cmath>

AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fMCEvent(0x0),
  fESDEvent(0x0),
  fAODEvent(0x0),
  fRunNumber(-1),
  fJetsCont(0),
  fTracksCont(0),
  fCaloClustersCont(0),
  fOutputList(0x0),
  fShortTaskId("jets_evshape")
{
  // default ctor

  SetMakeGeneralHistograms(kTRUE);

  DefineOutput(kOutputEmcal, TList::Class());
  AliInfo(Form("creating output slot #%i", kOutputTask));
  DefineOutput(kOutputTask, TList::Class());
}

AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
  // dtor
}

void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
  // create user output objects
  AliInfo("creating output objects");

  // common EMCAL framework
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  PostData(kOutputEmcal, fOutput);
  fJetsCont           = GetJetContainer(0);
  printf("setup jet container: %p, from available:\n", fJetsCont);
  fJetCollArray.Print();
  printf("end\n");
  if(fJetsCont) { //get particles and clusters connected to jets
    fTracksCont       = fJetsCont->GetParticleContainer();
    fCaloClustersCont = fJetsCont->GetClusterContainer();
  } else {        //no jets, just analysis tracks and clusters
    fTracksCont       = GetParticleContainer(0);
    fCaloClustersCont = GetClusterContainer(0);
  }
  if(fTracksCont) fTracksCont->SetClassName("AliVParticle");
  if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");

  // setup list
  OpenFile(kOutputTask);
  fOutputList = new TList();
  fOutputList->SetOwner();

  // setup histograms
  TH1 *hist;
  TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
                               kStatLast-1, .5, kStatLast-.5);
  histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
  histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
  histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
  histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));

  AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
               40, 0., 40.);
  AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
               100, 0., 400.);

  PostData(kOutputTask, fOutputList);
}

Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
  // actions to be taken upon notification about input file change

  return AliAnalysisTaskEmcalJet::Notify();
}

void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
  // actions at task termination

  AliAnalysisTaskEmcalJet::Terminate(option);
}

void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
  AliAnalysisTaskEmcalJet::PrintTask(option, indent);

  std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}

Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
  Bool_t eventGood = kTRUE;

  // check for run change
  if (fRunNumber != InputEvent()->GetRunNumber()) {
    fRunNumber = InputEvent()->GetRunNumber();
  }

  return eventGood;
}

Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::ExecOnce()
{
  AliAnalysisTaskEmcalJet::ExecOnce();
}

Bool_t AliAnalysisTaskJetsEvshape::Run()
{
  return kTRUE;
}

Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
  FillH1(kHistStat, kStatUsed);

  AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
  Int_t nTracklets = mult ? mult->GetNumberOfTracklets() : -1;
  FillH1(kHistMult, nTracklets);

  if (fJetsCont) {
    fJetsCont->ResetCurrentID();
    AliEmcalJet *jet = fJetsCont->GetNextAcceptJet();
    Int_t i = 0;
    while (jet) {
      FillH1(kHistJetPt, jet->Pt());
      jet = fJetsCont->GetNextAcceptJet();
    }
  }

  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
  // actual work

  AliAnalysisTaskEmcalJet::UserExec(option);

  // setup pointers to input data (null if unavailable)
  // mcEvent:  MC input
  // esdEvent: ESD input
  // outEvent: AOD output
  // aodEvent: AOD input if available, otherwise AOD output

  fMCEvent   = this->MCEvent();
  fESDEvent  = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
  AliAODEvent* outEvent  = this->AODEvent();
  fAODEvent  = dynamic_cast<AliAODEvent*> (this->InputEvent());
  if (!fAODEvent)
    fAODEvent = outEvent;

  if ((fDebug > 0) && fESDEvent)
    printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());

  // record number of sampled events and detect trigger contributions
  FillH1(kHistStat, kStatSeen);

  // so far, no trigger selection, we accept all
  FillH1(kHistStat, kStatTrg);

  // prepare the event
  // (make sure it is cleaned up in the end)
  if (PrepareEvent()) {
    // here we have passed the event cuts
    FillH1(kHistStat, kStatEvCuts);

    // multiplicity selection

    // event shape selection

    // InputEvent()->GetList()->ls();
  }

 stop:
  CleanUpEvent();

  PostData(kOutputEmcal, fOutput);
  PostData(kOutputTask, fOutputList);
}

// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = new TH1I(hName.Data(), title,
                 xbins, xmin, xmax);
  else
    h = new TH1F(hName.Data(), title,
                 xbins, xmin, xmax);
  GetHistogram(hist) = h;
  fOutputList->Add(h);
  return h;
}

TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH2I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  else
    h = GetHistogram(hist) = new TH2F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  fOutputList->Add(h);
  return (TH2*) h;
}

TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t zbins, Float_t zmin, Float_t zmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH3I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  else
    h = GetHistogram(hist) = new TH3F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  fOutputList->Add(h);
  return (TH3*) h;
}
<commit_msg>- adding debug output<commit_after>// ROOT
#include "TFile.h"
#include "TList.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TF1.h"
#include "TFormula.h"
#include "TRandom.h"
#include "TSpline.h"

// analysis framework
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliVEvent.h"
#include "AliVTrack.h"
#include "AliVVertex.h"
#include "AliVMultiplicity.h"

// MC stuff
#include "AliMCEvent.h"
#include "AliGenPythiaEventHeader.h"

// ESD stuff
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliESDtrack.h"
#include "AliESDtrackCuts.h"

// AOD stuff
#include "AliAODEvent.h"
#include "AliAODJet.h"
#include "AliAODTrack.h"

// EMCAL framework and jet tasks
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliEmcalJet.h"

#include "AliAnalysisTaskEmcalJet.h"
#include "AliAnalysisTaskJetsEvshape.h"

#include <iostream>
#include <cmath>

AliAnalysisTaskJetsEvshape::AliAnalysisTaskJetsEvshape(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fMCEvent(0x0),
  fESDEvent(0x0),
  fAODEvent(0x0),
  fRunNumber(-1),
  fJetsCont(0),
  fTracksCont(0),
  fCaloClustersCont(0),
  fOutputList(0x0),
  fShortTaskId("jets_evshape")
{
  // default ctor

  SetMakeGeneralHistograms(kTRUE);

  DefineOutput(kOutputEmcal, TList::Class());
  AliInfo(Form("creating output slot #%i", kOutputTask));
  DefineOutput(kOutputTask, TList::Class());
}

AliAnalysisTaskJetsEvshape::~AliAnalysisTaskJetsEvshape()
{
  // dtor
}

void AliAnalysisTaskJetsEvshape::UserCreateOutputObjects()
{
  // create user output objects
  AliInfo("creating output objects");

  // common EMCAL framework
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  PostData(kOutputEmcal, fOutput);
  fJetsCont           = GetJetContainer(0);
  printf("setup jet container: %p, from available:\n", fJetsCont);
  fJetCollArray.Print();
  printf("end\n");
  if(fJetsCont) { //get particles and clusters connected to jets
    fTracksCont       = fJetsCont->GetParticleContainer();
    fCaloClustersCont = fJetsCont->GetClusterContainer();
  } else {        //no jets, just analysis tracks and clusters
    fTracksCont       = GetParticleContainer(0);
    fCaloClustersCont = GetClusterContainer(0);
  }
  if(fTracksCont) fTracksCont->SetClassName("AliVParticle");
  if(fCaloClustersCont) fCaloClustersCont->SetClassName("AliVCluster");

  // setup list
  OpenFile(kOutputTask);
  fOutputList = new TList();
  fOutputList->SetOwner();

  // setup histograms
  TH1 *hist;
  TH1 *histStat = AddHistogram(ID(kHistStat), "event statistics;;counts",
                               kStatLast-1, .5, kStatLast-.5);
  histStat->GetXaxis()->SetBinLabel(ID(kStatSeen));
  histStat->GetXaxis()->SetBinLabel(ID(kStatTrg));
  histStat->GetXaxis()->SetBinLabel(ID(kStatUsed));
  histStat->GetXaxis()->SetBinLabel(ID(kStatEvCuts));

  AddHistogram(ID(kHistJetPt), "jet spectrum;p_{T}^{jet,ch} (GeV/#it{c});counts",
               40, 0., 40.);
  AddHistogram(ID(kHistMult), "tracklet multiplicity;N_{trkl};counts",
               100, 0., 400.);

  PostData(kOutputTask, fOutputList);
}

Bool_t AliAnalysisTaskJetsEvshape::Notify()
{
  // actions to be taken upon notification about input file change

  return AliAnalysisTaskEmcalJet::Notify();
}

void AliAnalysisTaskJetsEvshape::Terminate(const Option_t *option)
{
  // actions at task termination

  AliAnalysisTaskEmcalJet::Terminate(option);
}

void AliAnalysisTaskJetsEvshape::PrintTask(Option_t *option, Int_t indent) const
{
  AliAnalysisTaskEmcalJet::PrintTask(option, indent);

  std::cout << std::setw(indent) << " " << "nothing to say: " << std::endl;
}

Bool_t AliAnalysisTaskJetsEvshape::PrepareEvent()
{
  Bool_t eventGood = kTRUE;

  // check for run change
  if (fRunNumber != InputEvent()->GetRunNumber()) {
    fRunNumber = InputEvent()->GetRunNumber();
  }

  return eventGood;
}

Bool_t AliAnalysisTaskJetsEvshape::CleanUpEvent()
{
  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::ExecOnce()
{
  AliAnalysisTaskEmcalJet::ExecOnce();
}

Bool_t AliAnalysisTaskJetsEvshape::Run()
{
  return kTRUE;
}

Bool_t AliAnalysisTaskJetsEvshape::FillHistograms()
{
  FillH1(kHistStat, kStatUsed);

  AliVMultiplicity *mult = InputEvent()->GetMultiplicity();
  const Int_t nTracklets = mult ? mult->GetNumberOfTracklets() : -1;
  FillH1(kHistMult, nTracklets);

  if (fJetsCont) {
    const Int_t nJets         = fJetsCont->GetNJets();
    const Int_t nAcceptedJets = fJetsCont->GetNAcceptedJets();

    printf("nJets = %i, nAcceptedJets = %i\n",
           nJets, nAcceptedJets);

    fJetsCont->ResetCurrentID();
    while (AliEmcalJet *jet = fJetsCont->GetNextAcceptJet()) {
      FillH1(kHistJetPt, jet->Pt());
    }
  }

  return kTRUE;
}

void AliAnalysisTaskJetsEvshape::UserExec(Option_t *option)
{
  // actual work

  AliAnalysisTaskEmcalJet::UserExec(option);

  // setup pointers to input data (null if unavailable)
  // mcEvent:  MC input
  // esdEvent: ESD input
  // outEvent: AOD output
  // aodEvent: AOD input if available, otherwise AOD output

  fMCEvent   = this->MCEvent();
  fESDEvent  = dynamic_cast<AliESDEvent*>(this->InputEvent()); // could also be AOD input
  AliAODEvent* outEvent  = this->AODEvent();
  fAODEvent  = dynamic_cast<AliAODEvent*> (this->InputEvent());
  if (!fAODEvent)
    fAODEvent = outEvent;

  if ((fDebug > 0) && fESDEvent)
    printf("event: %s-%06i\n", CurrentFileName(), fESDEvent->GetEventNumberInFile());

  // record number of sampled events and detect trigger contributions
  FillH1(kHistStat, kStatSeen);

  // so far, no trigger selection, we accept all
  FillH1(kHistStat, kStatTrg);

  // prepare the event
  // (make sure it is cleaned up in the end)
  if (PrepareEvent()) {
    // here we have passed the event cuts
    FillH1(kHistStat, kStatEvCuts);

    // multiplicity selection

    // event shape selection

    // InputEvent()->GetList()->ls();
  }

 stop:
  CleanUpEvent();

  PostData(kOutputEmcal, fOutput);
  PostData(kOutputTask, fOutputList);
}

// ----- histogram management -----
TH1* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = new TH1I(hName.Data(), title,
                 xbins, xmin, xmax);
  else
    h = new TH1F(hName.Data(), title,
                 xbins, xmin, xmax);
  GetHistogram(hist) = h;
  fOutputList->Add(h);
  return h;
}

TH2* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH2I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  else
    h = GetHistogram(hist) = new TH2F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax);
  fOutputList->Add(h);
  return (TH2*) h;
}

TH3* AliAnalysisTaskJetsEvshape::AddHistogram(Hist_t hist, const char *hid, TString title,
						 Int_t xbins, Float_t xmin, Float_t xmax,
						 Int_t ybins, Float_t ymin, Float_t ymax,
						 Int_t zbins, Float_t zmin, Float_t zmax,
						 Int_t binType)
{
  TString hName;
  hName.Form("%s_%s", fShortTaskId, hid);
  hName.ToLower();
  TH1 *h = 0x0;
  if (binType == 0)
    h = GetHistogram(hist) = new TH3I(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  else
    h = GetHistogram(hist) = new TH3F(hName.Data(), title,
                                     xbins, xmin, xmax,
                                     ybins, ymin, ymax,
                                     zbins, zmin, zmax);
  fOutputList->Add(h);
  return (TH3*) h;
}
<|endoftext|>