<commit_before>//
//  GameplayScene.cpp
//  MasmorraDados
//
//  Created by Marlon Andrade on 16/02/2015.
//
//

#include "GameplayScene.h"

#include "Events.h"
#include "NodeNames.h"

#include "DungeonLayer.h"
#include "HudLayer.h"
#include "PlayerTurnLayer.h"
#include "ScrollableDungeonLayer.h"
#include "TurnChangeLayer.h"

#include "DungeonTurn.h"
#include "PlayerTurn.h"

#include "NodeUtil.h"
#include "PositionUtil.h"

USING_NS_CC;

#pragma mark - Public Interface

bool GameplayScene::init() {
  if (!Scene::init()) {
    return false;
  }

  this->_setupChildren();
  this->_setupEventHandlers();

  Game::getInstance()->start();

  return true;
}

DungeonLayer* GameplayScene::getDungeonLayer() {
  auto layer = this->getChildByName<ScrollableDungeonLayer*>(SCROLLABLE_LAYER_NAME);
  return layer->getChildByName<DungeonLayer*>(DUNGEON_LAYER_NAME);
}

#pragma mark - Private Interface

void GameplayScene::_setupChildren() {
  this->addChild(ScrollableDungeonLayer::create(), 0);
  this->addChild(PlayerTurnLayer::create(), 1);
  this->addChild(TurnChangeLayer::create(), 2);
  this->addChild(HudLayer::create(), 3);
}

void GameplayScene::_setupEventHandlers() {
  auto dispatcher = Director::getInstance()->getEventDispatcher();

  auto actionDicesRolledCallback = CC_CALLBACK_1(GameplayScene::_handleActionDicesRolled, this);
  this->setActionDicesRolledListener(
    dispatcher->addCustomEventListener(EVT_ACTION_DICES_ROLLED, actionDicesRolledCallback)
  );

  auto levelAdvancedCallback = CC_CALLBACK_1(GameplayScene::_handleLevelAdvanced, this);
  this->setLevelAdvancedListener(
    dispatcher->addCustomEventListener(EVT_LEVEL_ADVANCED, levelAdvancedCallback)
  );

  auto experienceChangedCallback = CC_CALLBACK_1(GameplayScene::_handleExperienceChanged, this);
  this->setExperienceChangedListener(
    dispatcher->addCustomEventListener(EVT_EXPERIENCE_CHANGED, experienceChangedCallback)
  );

  auto coinsChangedCallback = CC_CALLBACK_1(GameplayScene::_handleCoinsChanged, this);
  this->setCoinsChangedListener(
    dispatcher->addCustomEventListener(EVT_COINS_CHANGED, coinsChangedCallback)
  );

  auto turnHasStartedCallback = CC_CALLBACK_1(GameplayScene::_handleTurnHasStarted, this);
  this->setTurnHasStartedListener(
    dispatcher->addCustomEventListener(EVT_TURN_HAS_STARTED, turnHasStartedCallback)
  );

  auto turnHasEndedCallback = CC_CALLBACK_1(GameplayScene::_handleTurnHasEnded, this);
  this->setTurnHasEndedListener(
    dispatcher->addCustomEventListener(EVT_TURN_HAS_ENDED, turnHasEndedCallback)
  );
}

HudLayer* GameplayScene::_getHudLayer() {
  return (HudLayer*) this->getChildByName(HUD_LAYER_NAME);
}

PlayerTurnLayer* GameplayScene::_getPlayerTurnLayer() {
  return (PlayerTurnLayer*) this->getChildByName(PLAYER_TURN_LAYER);
}

TurnChangeLayer* GameplayScene::_getTurnChangeLayer() {
  return (TurnChangeLayer*) this->getChildByName(TURN_CHANGE_LAYER_NAME);
}

#pragma mark - Event Handlers

void GameplayScene::_handleActionDicesRolled(EventCustom* event) {
  this->_getPlayerTurnLayer()->showGameplayLayer();
}

void GameplayScene::_handleLevelAdvanced(EventCustom* event) {
  this->_getHudLayer()->adjustLevel(Game::getInstance()->getLevel());

  NodeUtil::stopAllActionsRecursive(this);
  auto layer = this->getChildByName<ScrollableDungeonLayer*>(SCROLLABLE_LAYER_NAME);
  layer->resetDungeonLayer();
}

void GameplayScene::_handleExperienceChanged(EventCustom* event) {
  this->_getHudLayer()->adjustXp(Game::getInstance()->getExperience());
}

void GameplayScene::_handleCoinsChanged(EventCustom* event) {
  this->_getHudLayer()->adjustCoins(Game::getInstance()->getCoins());
}

void GameplayScene::_handleTurnHasStarted(EventCustom* event) {
  log("turn has started");

  auto turn = (Turn*) event->getUserData();

  if (IS(turn, PlayerTurn)) {
    Game::getInstance()->resetForPlayerTurn();

    this->_getPlayerTurnLayer()->playerTurnHasStarted();
    this->_getTurnChangeLayer()->showPlayerTurnInfo();
  } else if (IS(turn, DungeonTurn)) {
    this->_getTurnChangeLayer()->showDungeonTurnInfo();

    auto delay = DelayTime::create(TURN_INFO_DURATION);
    auto executeTurn = CallFunc::create([&] {
      Game::getInstance()->executeCurrentTurn();
    });
    this->runAction(Sequence::create(delay, executeTurn, NULL));
  }
}

void GameplayScene::_handleTurnHasEnded(EventCustom* event) {
  log("turn has ended");

  auto turn = (Turn*) event->getUserData();

  if (IS(turn, PlayerTurn)) {
    this->_getPlayerTurnLayer()->runAction(Hide::create());
  }
}
<commit_msg>Causando dano no jogador quando o turno for finalizar<commit_after>//
//  GameplayScene.cpp
//  MasmorraDados
//
//  Created by Marlon Andrade on 16/02/2015.
//
//

#include "GameplayScene.h"

#include "Events.h"
#include "NodeNames.h"

#include "DungeonLayer.h"
#include "HudLayer.h"
#include "PlayerTurnLayer.h"
#include "ScrollableDungeonLayer.h"
#include "TurnChangeLayer.h"

#include "DungeonTurn.h"
#include "PlayerTurn.h"

#include "NodeUtil.h"
#include "PositionUtil.h"

USING_NS_CC;

#pragma mark - Public Interface

bool GameplayScene::init() {
  if (!Scene::init()) {
    return false;
  }

  this->_setupChildren();
  this->_setupEventHandlers();

  Game::getInstance()->start();

  return true;
}

DungeonLayer* GameplayScene::getDungeonLayer() {
  auto layer = this->getChildByName<ScrollableDungeonLayer*>(SCROLLABLE_LAYER_NAME);
  return layer->getChildByName<DungeonLayer*>(DUNGEON_LAYER_NAME);
}

#pragma mark - Private Interface

void GameplayScene::_setupChildren() {
  this->addChild(ScrollableDungeonLayer::create(), 0);
  this->addChild(PlayerTurnLayer::create(), 1);
  this->addChild(TurnChangeLayer::create(), 2);
  this->addChild(HudLayer::create(), 3);
}

void GameplayScene::_setupEventHandlers() {
  auto dispatcher = Director::getInstance()->getEventDispatcher();

  auto actionDicesRolledCallback = CC_CALLBACK_1(GameplayScene::_handleActionDicesRolled, this);
  this->setActionDicesRolledListener(
    dispatcher->addCustomEventListener(EVT_ACTION_DICES_ROLLED, actionDicesRolledCallback)
  );

  auto levelAdvancedCallback = CC_CALLBACK_1(GameplayScene::_handleLevelAdvanced, this);
  this->setLevelAdvancedListener(
    dispatcher->addCustomEventListener(EVT_LEVEL_ADVANCED, levelAdvancedCallback)
  );

  auto experienceChangedCallback = CC_CALLBACK_1(GameplayScene::_handleExperienceChanged, this);
  this->setExperienceChangedListener(
    dispatcher->addCustomEventListener(EVT_EXPERIENCE_CHANGED, experienceChangedCallback)
  );

  auto coinsChangedCallback = CC_CALLBACK_1(GameplayScene::_handleCoinsChanged, this);
  this->setCoinsChangedListener(
    dispatcher->addCustomEventListener(EVT_COINS_CHANGED, coinsChangedCallback)
  );

  auto turnHasStartedCallback = CC_CALLBACK_1(GameplayScene::_handleTurnHasStarted, this);
  this->setTurnHasStartedListener(
    dispatcher->addCustomEventListener(EVT_TURN_HAS_STARTED, turnHasStartedCallback)
  );

  auto turnHasEndedCallback = CC_CALLBACK_1(GameplayScene::_handleTurnHasEnded, this);
  this->setTurnHasEndedListener(
    dispatcher->addCustomEventListener(EVT_TURN_HAS_ENDED, turnHasEndedCallback)
  );
}

HudLayer* GameplayScene::_getHudLayer() {
  return (HudLayer*) this->getChildByName(HUD_LAYER_NAME);
}

PlayerTurnLayer* GameplayScene::_getPlayerTurnLayer() {
  return (PlayerTurnLayer*) this->getChildByName(PLAYER_TURN_LAYER);
}

TurnChangeLayer* GameplayScene::_getTurnChangeLayer() {
  return (TurnChangeLayer*) this->getChildByName(TURN_CHANGE_LAYER_NAME);
}

#pragma mark - Event Handlers

void GameplayScene::_handleActionDicesRolled(EventCustom* event) {
  this->_getPlayerTurnLayer()->showGameplayLayer();
}

void GameplayScene::_handleLevelAdvanced(EventCustom* event) {
  this->_getHudLayer()->adjustLevel(Game::getInstance()->getLevel());

  NodeUtil::stopAllActionsRecursive(this);
  auto layer = this->getChildByName<ScrollableDungeonLayer*>(SCROLLABLE_LAYER_NAME);
  layer->resetDungeonLayer();
}

void GameplayScene::_handleExperienceChanged(EventCustom* event) {
  this->_getHudLayer()->adjustXp(Game::getInstance()->getExperience());
}

void GameplayScene::_handleCoinsChanged(EventCustom* event) {
  this->_getHudLayer()->adjustCoins(Game::getInstance()->getCoins());
}

void GameplayScene::_handleTurnHasStarted(EventCustom* event) {
  log("turn has started");

  auto turn = (Turn*) event->getUserData();

  if (IS(turn, PlayerTurn)) {
    Game::getInstance()->resetForPlayerTurn();

    this->_getPlayerTurnLayer()->playerTurnHasStarted();
    this->_getTurnChangeLayer()->showPlayerTurnInfo();
  } else if (IS(turn, DungeonTurn)) {
    this->_getTurnChangeLayer()->showDungeonTurnInfo();

    auto delay = DelayTime::create(TURN_INFO_DURATION);
    auto executeTurn = CallFunc::create([&] {
      Game::getInstance()->executeCurrentTurn();
    });
    this->runAction(Sequence::create(delay, executeTurn, NULL));
  }
}

void GameplayScene::_handleTurnHasEnded(EventCustom* event) {
  log("turn has ended");

  auto turn = (Turn*) event->getUserData();

  if (IS(turn, PlayerTurn)) {
    auto game = Game::getInstance();
    auto character = game->getPlayer()->getCharacter();
    character->takeDamage(game->getDamageTaken());
    game->setDamageTaken(0);

    this->_getPlayerTurnLayer()->runAction(Hide::create());
  }
}
<|endoftext|>


<commit_before>#ifndef Blueprint_cxx
#define Blueprint_cxx

#include "boost/graph/graphviz.hpp"

#include "selxBlueprint.h"

namespace selx {

Blueprint::ComponentIndexType
Blueprint
::AddComponent( void )
{
  this->Modified();

  ComponentIndexType index = boost::add_vertex( this->m_Graph );

  // Return component index so component can retrieved at a later time
  return index;
}

Blueprint::ComponentIndexType
Blueprint
::AddComponent( ParameterMapType parameterMap )
{
  this->Modified();

  ComponentIndexType index = boost::add_vertex( this->m_Graph );
  this->m_Graph[index].parameterMap = parameterMap;

  // Return component index so component can retrieved at a later time
  return index;
}

Blueprint::ParameterMapType
Blueprint
::GetComponent( ComponentIndexType index )
{
  this->Modified();

  return this->m_Graph[ index ].parameterMap;
}

void
Blueprint
::SetComponent( ComponentIndexType index, ParameterMapType parameterMap )
{
  this->Modified();
  this->m_Graph[ index ].parameterMap = parameterMap;
}

// TODO: See explanation in selxBlueprint.h
// void
// Blueprint
// ::DeleteComponent( const ComponentIndexType index )
// {
//   this->Modified();
//
//   clear_vertex( index, this->m_Graph );
//   remove_vertex( index, this->m_Graph );
// }

bool
Blueprint
::AddConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  if( this->ConnectionExists( upstream, downstream) ) {
    return false;
  }

  // Adds directed connection from upstream component to downstream component
  return boost::add_edge( upstream, downstream, this->m_Graph ).second;
}

bool
Blueprint
::AddConnection( ComponentIndexType upstream, ComponentIndexType downstream, ParameterMapType parameterMap )
{
  this->Modified();

  if( !this->ConnectionExists( upstream, downstream ) ) {
    ConnectionIndexType index = boost::add_edge( upstream, downstream, this->m_Graph ).first;
    this->m_Graph[ index ].parameterMap = parameterMap;
    return true;
  }

  // If the connection does not exist don't do anything because previous settings
  // will be overwritten.  If the user do want to overwrite current settings,
  // she should use SetConnection() instead where the intent is explicit.
  return false;
}

Blueprint::ParameterMapType
Blueprint
::GetConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  return this->m_Graph[ this->GetConnectionIndex( upstream, downstream ) ].parameterMap;
}

bool
Blueprint
::SetConnection( ComponentIndexType upstream, ComponentIndexType downstream, ParameterMapType parameterMap )
{
  this->Modified();

  if( !this->ConnectionExists( upstream, downstream ) ) {
    return this->AddConnection( upstream, downstream, parameterMap );
  } else {
    this->m_Graph[ this->GetConnectionIndex( upstream, downstream ) ].parameterMap = parameterMap;
    return true;
  }
}

bool
Blueprint
::DeleteConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  if( this->ConnectionExists( upstream, downstream ) ) {
    this->m_Graph.remove_edge( this->GetConnectionIndex( upstream, downstream ) );
  }

  return !this->ConnectionExists( upstream, downstream );
}

bool
Blueprint
::ConnectionExists( ComponentIndexType upstream, ComponentIndexType downstream )
{
  return boost::edge( upstream, downstream, this->m_Graph).second;
}

Blueprint::ConnectionIndexType
Blueprint
::GetConnectionIndex( ComponentIndexType upstream, ComponentIndexType downstream )
{
  // This function is part of the internal API and should fail hard if we use it incorrectly
  if( !this->ConnectionExists( upstream, downstream ) ) {
    itkExceptionMacro( "Blueprint does not contain connection from component " << upstream << " to " << downstream );
  }

  return boost::edge( upstream, downstream, this->m_Graph).first;
}

void
Blueprint
::WriteBlueprint( const std::string filename )
{
  std::ofstream dotfile( filename.c_str() );
  boost::write_graphviz( dotfile, this->m_Graph );
}

} // namespace selx

#endif // Blueprint_cxx
<commit_msg>ENH: Vertex and edge ParameterMaps at blueprint output for graphviz<commit_after>#ifndef Blueprint_cxx
#define Blueprint_cxx

#include "boost/graph/graphviz.hpp"

#include "selxBlueprint.h"

namespace selx {

  // Declared outside of the class body, so it is a free function
  std::ostream& operator<<(std::ostream& out, const Blueprint::ParameterMapType& val){
    for (auto const & mapPair : val)
    {
      out << mapPair.first << " : [ ";
      for (auto const & value : mapPair.second)
      {
        out << value << " ";
      }
      out << "]\\n";
    }
    return out;
  }

  template <class ParameterMapType>
  class parameterMaplabel_writer {

  public:
    parameterMaplabel_writer(ParameterMapType _parameterMap) : parameterMap(_parameterMap) {}
    template <class VertexOrEdge>
    void operator()(std::ostream& out, const VertexOrEdge& v) const {
      out << "[label=\"" << parameterMap[v] << "\"]";
    }
  private:
    ParameterMapType parameterMap;
  };

  template <class ParameterMapType>
  inline parameterMaplabel_writer<ParameterMapType>
    make_parameterMaplabel_writer(ParameterMapType n) {
    return parameterMaplabel_writer<ParameterMapType>(n);
  }

Blueprint::ComponentIndexType
Blueprint
::AddComponent( void )
{
  this->Modified();

  ComponentIndexType index = boost::add_vertex( this->m_Graph );

  // Return component index so component can retrieved at a later time
  return index;
}

Blueprint::ComponentIndexType
Blueprint
::AddComponent( ParameterMapType parameterMap )
{
  this->Modified();

  ComponentIndexType index = boost::add_vertex( this->m_Graph );
  this->m_Graph[index].parameterMap = parameterMap;

  // Return component index so component can retrieved at a later time
  return index;
}

Blueprint::ParameterMapType
Blueprint
::GetComponent( ComponentIndexType index )
{
  this->Modified();

  return this->m_Graph[ index ].parameterMap;
}

void
Blueprint
::SetComponent( ComponentIndexType index, ParameterMapType parameterMap )
{
  this->Modified();
  this->m_Graph[ index ].parameterMap = parameterMap;
}

// TODO: See explanation in selxBlueprint.h
// void
// Blueprint
// ::DeleteComponent( const ComponentIndexType index )
// {
//   this->Modified();
//
//   clear_vertex( index, this->m_Graph );
//   remove_vertex( index, this->m_Graph );
// }

bool
Blueprint
::AddConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  if( this->ConnectionExists( upstream, downstream) ) {
    return false;
  }

  // Adds directed connection from upstream component to downstream component
  return boost::add_edge( upstream, downstream, this->m_Graph ).second;
}

bool
Blueprint
::AddConnection( ComponentIndexType upstream, ComponentIndexType downstream, ParameterMapType parameterMap )
{
  this->Modified();

  if( !this->ConnectionExists( upstream, downstream ) ) {
    ConnectionIndexType index = boost::add_edge( upstream, downstream, this->m_Graph ).first;
    this->m_Graph[ index ].parameterMap = parameterMap;
    return true;
  }

  // If the connection does not exist don't do anything because previous settings
  // will be overwritten.  If the user do want to overwrite current settings,
  // she should use SetConnection() instead where the intent is explicit.
  return false;
}

Blueprint::ParameterMapType
Blueprint
::GetConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  return this->m_Graph[ this->GetConnectionIndex( upstream, downstream ) ].parameterMap;
}

bool
Blueprint
::SetConnection( ComponentIndexType upstream, ComponentIndexType downstream, ParameterMapType parameterMap )
{
  this->Modified();

  if( !this->ConnectionExists( upstream, downstream ) ) {
    return this->AddConnection( upstream, downstream, parameterMap );
  } else {
    this->m_Graph[ this->GetConnectionIndex( upstream, downstream ) ].parameterMap = parameterMap;
    return true;
  }
}

bool
Blueprint
::DeleteConnection( ComponentIndexType upstream, ComponentIndexType downstream )
{
  this->Modified();

  if( this->ConnectionExists( upstream, downstream ) ) {
    this->m_Graph.remove_edge( this->GetConnectionIndex( upstream, downstream ) );
  }

  return !this->ConnectionExists( upstream, downstream );
}

bool
Blueprint
::ConnectionExists( ComponentIndexType upstream, ComponentIndexType downstream )
{
  return boost::edge( upstream, downstream, this->m_Graph).second;
}

Blueprint::ConnectionIndexType
Blueprint
::GetConnectionIndex( ComponentIndexType upstream, ComponentIndexType downstream )
{
  // This function is part of the internal API and should fail hard if we use it incorrectly
  if( !this->ConnectionExists( upstream, downstream ) ) {
    itkExceptionMacro( "Blueprint does not contain connection from component " << upstream << " to " << downstream );
  }

  return boost::edge( upstream, downstream, this->m_Graph).first;
}

void
Blueprint
::WriteBlueprint( const std::string filename )
{
  std::ofstream dotfile( filename.c_str() );
  boost::write_graphviz(dotfile, this->m_Graph, make_parameterMaplabel_writer(boost::get(&ComponentPropertyType::parameterMap, this->m_Graph)), make_parameterMaplabel_writer(boost::get(&ConnectionPropertyType::parameterMap, this->m_Graph)));
}

} // namespace selx

#endif // Blueprint_cxx
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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 "itkIOCommon.h"
#include <cstring>
#include "itksys/SystemTools.hxx"

bool CheckFileNameParsing(const std::string & fileName,
                          const std::string & correctNameOnly,
                          const std::string & correctExtension,
                          const std::string & correctPath)
{
  // the current kwsys way...
  std::cout << "(kwsys) Extracting...file name...";
  std::string fileNameString =
    itksys::SystemTools::GetFilenameWithoutLastExtension
    (itksys::SystemTools::GetFilenameName(fileName));
  char* nameOnly = new char[fileNameString.size() + 1];
  std::strncpy(nameOnly, fileNameString.c_str(),fileNameString.size() + 1);
  std::cout << "extension...";
  std::string extensionString =
    itksys::SystemTools::GetFilenameLastExtension(fileName);
  // NB: remove the period (kwsys leaves it on, ITK precedent was to
  // remove it)
  char* extension = new char[extensionString.size()+1];
  if (extensionString.length()>0)
    {
    std::strncpy(extension, extensionString.c_str()+1,extensionString.size()+1);
    }
  else
    {
    extension[0]=0;
    }
  std::cout << "path...";
  std::string pathString = itksys::SystemTools::GetFilenamePath(fileName);
#ifdef _WIN32
  for (size_t i = 0; i < pathString.size(); i++)
    {
    if (pathString[i] == '/')
      {
      pathString[i] = '\\';
      }
    }
#endif
  // NB: add trailing slash iff the result is non-empty (kwsys always
  // removes it, ITK precedent was to keep it)
  if (pathString.size() > 1)
  {
#if defined(_WIN32)
    pathString = pathString + "\\";
#else
    pathString = pathString + "/";
#endif
  }
  char* path = new char[pathString.size() + 1];
  std::strncpy(path, pathString.c_str(),pathString.size() + 1);
  std::cout << "DONE" << std::endl;

  std::cout << "Comparing...file name...";
  bool nameMatches;
  if (nameOnly == NULL)
    {
    nameMatches = correctNameOnly.size() == 0;
    }
  else
    {
    nameMatches = correctNameOnly.compare(nameOnly) == 0;
    }

  std::cout << "extension...";
  bool extensionMatches;
  if (extension == NULL)
    {
    extensionMatches = correctExtension.size() == 0;
    }
  else
    {
    extensionMatches = correctExtension.compare(extension) == 0;
    }

  std::cout << "path...";
  bool pathMatches;
  if (path == NULL)
    {
    pathMatches = correctPath.size() == 0;
    }
  else
    {
    pathMatches = correctPath.compare(path) == 0;
    }
  std::cout << "DONE" << std::endl;

  std::cout << "FullFileName: \"" << fileName << "\"" << std::endl;
  std::cout << "FileName: (expected) \"" << correctNameOnly
            << "\" (actual) \"" << (nameOnly != NULL ? static_cast<const char *>(nameOnly) : "(null)")
            << "\""
            << " (correct) " << nameMatches << std::endl;
  std::cout << "Extension: (expected) \"" << correctExtension
            << "\" (actual) \"" << (extension != NULL ? static_cast<const char *>(extension) : "(null)")
            << "\""
            << " (correct) " << extensionMatches << std::endl;
  std::cout << "Path: (expected) \"" << correctPath
            << "\" (actual) \"" << (path != NULL ? static_cast<const char *>(path) : "(null)")
            << "\""
            << " (correct) " << pathMatches << std::endl;

  bool correctParse = nameMatches && extensionMatches && pathMatches;
  std::cout << "Parsing is " << (correctParse ? "correct" : "incorrect")
            << std::endl;

  // clean up
  std::cout << "Cleaning up...";
  delete[] nameOnly;
  delete[] extension;
  delete[] path;
  std::cout << "DONE" << std::endl;

  return correctParse;
}

int itkIOCommonTest(int , char* [])
{
  bool success = true;

  //
  // reasonable cases
  //

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("c:\\dir1\\dir2\\myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "c:\\dir1\\dir2\\");
  success = success &&
    CheckFileNameParsing("\\\\sambaserver\\dir1\\dir2\\myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "\\\\sambaserver\\dir1\\dir2\\");
#else
  success = success &&
    CheckFileNameParsing("/dir1/dir2/myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "/dir1/dir2/");
#endif

  //
  // less reasonable cases
  //
  success = success &&
    CheckFileNameParsing(".", "", "", "");

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\", "", "", "\\");
  success = success &&
    CheckFileNameParsing("\\.tar.gz", ".tar", "gz", "\\");
#else
  success = success &&
    CheckFileNameParsing("/", "", "", "/");
  success = success &&
    CheckFileNameParsing("/.tar.gz", ".tar", "gz", "/");
#endif

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\.tar.gz", ".tar", "gz", "\\");
#endif

  success = success &&
    CheckFileNameParsing(".tar.gz", ".tar", "gz", "");

  success = success &&
    CheckFileNameParsing("myfile", "myfile", "", "");

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\myfile", "myfile", "", "\\");
#else
  success = success &&
    CheckFileNameParsing("/myfile", "myfile", "", "/");
#endif

  success = success &&
    CheckFileNameParsing("", "", "", "");

  return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>BUG: Coverity 1081129: Dereference before null check in itkIOCommonTest<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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 "itkIOCommon.h"
#include <cstring>
#include "itksys/SystemTools.hxx"

bool CheckFileNameParsing(const std::string & fileName,
                          const std::string & correctNameOnly,
                          const std::string & correctExtension,
                          const std::string & correctPath)
{
  // the current kwsys way...
  std::cout << "(kwsys) Extracting...file name...";
  char* nameOnly;
  {
    std::string fileNameString =
      itksys::SystemTools::GetFilenameWithoutLastExtension(
        itksys::SystemTools::GetFilenameName(fileName));
    nameOnly = new char[fileNameString.size() + 1];
    std::strncpy(nameOnly, fileNameString.c_str(), fileNameString.size() + 1);
  }

  std::cout << "extension...";
  char* extension;
  {
    std::string extensionString =
      itksys::SystemTools::GetFilenameLastExtension(fileName);
    // NB: remove the period (kwsys leaves it on, ITK precedent was to
    // remove it)
    extension = new char[extensionString.size()+1];
    if ( !extensionString.empty() )
      {
      std::strncpy(extension, extensionString.c_str()+1, extensionString.size()+1);
      }
    else
      {
      extension[0] = '\0';
      }
  }

  std::cout << "path...";
  char* path;
  {
    std::string pathString = itksys::SystemTools::GetFilenamePath(fileName);
#ifdef _WIN32
    for (size_t i = 0; i < pathString.size(); i++)
      {
      if (pathString[i] == '/')
        {
        pathString[i] = '\\';
        }
      }
#endif
    // NB: add trailing slash iff the result is non-empty (kwsys always
    // removes it, ITK precedent was to keep it)
    if (pathString.size() > 1)
    {
  #if defined(_WIN32)
      pathString = pathString + "\\";
  #else
      pathString = pathString + "/";
  #endif
    }
    path = new char[pathString.size() + 1];
    std::strncpy(path, pathString.c_str(),pathString.size() + 1);
  }

  std::cout << "DONE" << std::endl;

  std::cout << "Comparing...file name...";
  bool nameMatches;
  if ( strlen(nameOnly) == 0 )
    {
    nameMatches = correctNameOnly.size() == 0;
    }
  else
    {
    nameMatches = correctNameOnly.compare(nameOnly) == 0;
    }

  std::cout << "extension...";
  bool extensionMatches;
  if ( strlen(extension) == 0 )
    {
    extensionMatches = correctExtension.size() == 0;
    }
  else
    {
    extensionMatches = correctExtension.compare(extension) == 0;
    }

  std::cout << "path...";
  bool pathMatches;
  if ( strlen(path) == 0 )
    {
    pathMatches = correctPath.size() == 0;
    }
  else
    {
    pathMatches = correctPath.compare(path) == 0;
    }
  std::cout << "DONE" << std::endl;

  std::cout << "FullFileName: \"" << fileName << "\"" << std::endl;
  std::cout << "FileName: (expected) \"" << correctNameOnly
            << "\" (actual) \"" << (nameOnly != NULL ? static_cast<const char *>(nameOnly) : "(null)")
            << "\""
            << " (correct) " << nameMatches << std::endl;
  std::cout << "Extension: (expected) \"" << correctExtension
            << "\" (actual) \"" << (extension != NULL ? static_cast<const char *>(extension) : "(null)")
            << "\""
            << " (correct) " << extensionMatches << std::endl;
  std::cout << "Path: (expected) \"" << correctPath
            << "\" (actual) \"" << (path != NULL ? static_cast<const char *>(path) : "(null)")
            << "\""
            << " (correct) " << pathMatches << std::endl;

  bool correctParse = nameMatches && extensionMatches && pathMatches;
  std::cout << "Parsing is " << (correctParse ? "correct" : "incorrect")
            << std::endl;

  // clean up
  std::cout << "Cleaning up...";
  delete[] nameOnly;
  delete[] extension;
  delete[] path;
  std::cout << "DONE" << std::endl;

  return correctParse;
}

int itkIOCommonTest(int , char* [])
{
  bool success = true;

  //
  // reasonable cases
  //

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("c:\\dir1\\dir2\\myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "c:\\dir1\\dir2\\");
  success = success &&
    CheckFileNameParsing("\\\\sambaserver\\dir1\\dir2\\myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "\\\\sambaserver\\dir1\\dir2\\");
#else
  success = success &&
    CheckFileNameParsing("/dir1/dir2/myfile.tar.gz",
                         "myfile.tar",
                         "gz",
                         "/dir1/dir2/");
#endif

  //
  // less reasonable cases
  //
  success = success &&
    CheckFileNameParsing(".", "", "", "");

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\", "", "", "\\");
  success = success &&
    CheckFileNameParsing("\\.tar.gz", ".tar", "gz", "\\");
#else
  success = success &&
    CheckFileNameParsing("/", "", "", "/");
  success = success &&
    CheckFileNameParsing("/.tar.gz", ".tar", "gz", "/");
#endif

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\.tar.gz", ".tar", "gz", "\\");
#endif

  success = success &&
    CheckFileNameParsing(".tar.gz", ".tar", "gz", "");

  success = success &&
    CheckFileNameParsing("myfile", "myfile", "", "");

#if defined(_WIN32)
  success = success &&
    CheckFileNameParsing("\\myfile", "myfile", "", "\\");
#else
  success = success &&
    CheckFileNameParsing("/myfile", "myfile", "", "/");
#endif

  success = success &&
    CheckFileNameParsing("", "", "", "");

  return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "net_deserializer.h"

static const auto test_data = std::string(
    "\x00\x01\x00\x00\x00\xFF\xFF\xFF\xFF\x01\x00\x00\x00\x00\x00\x00"
    "\x00\x15\x14\x00\x00\x00\x12\x0B\x53\x65\x6E\x64\x41\x64\x64\x72"
    "\x65\x73\x73\x12\x6F\x44\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67"
    "\x4D\x65\x74\x61\x64\x61\x74\x61\x2E\x4D\x79\x53\x65\x72\x76\x65"
    "\x72\x2C\x20\x44\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67\x4D\x65"
    "\x74\x61\x64\x61\x74\x61\x2C\x20\x56\x65\x72\x73\x69\x6F\x6E\x3D"
    "\x31\x2E\x30\x2E\x32\x36\x32\x32\x2E\x33\x31\x33\x32\x36\x2C\x20"
    "\x43\x75\x6C\x74\x75\x72\x65\x3D\x6E\x65\x75\x74\x72\x61\x6C\x2C"
    "\x20\x50\x75\x62\x6C\x69\x63\x4B\x65\x79\x54\x6F\x6B\x65\x6E\x3D"
    "\x6E\x75\x6C\x6C\x10\x01\x00\x00\x00\x01\x00\x00\x00\x09\x02\x00"
    "\x00\x00\x0C\x03\x00\x00\x00\x51\x44\x4F\x4A\x52\x65\x6D\x6F\x74"
    "\x69\x6E\x67\x4D\x65\x74\x61\x64\x61\x74\x61\x2C\x20\x56\x65\x72"
    "\x73\x69\x6F\x6E\x3D\x31\x2E\x30\x2E\x32\x36\x32\x32\x2E\x33\x31"
    "\x33\x32\x36\x2C\x20\x43\x75\x6C\x74\x75\x72\x65\x3D\x6E\x65\x75"
    "\x74\x72\x61\x6C\x2C\x20\x50\x75\x62\x6C\x69\x63\x4B\x65\x79\x54"
    "\x6F\x6B\x65\x6E\x3D\x6E\x75\x6C\x6C\x05\x02\x00\x00\x00\x1B\x44"
    "\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67\x4D\x65\x74\x61\x64\x61"
    "\x74\x61\x2E\x41\x64\x64\x72\x65\x73\x73\x04\x00\x00\x00\x06\x53"
    "\x74\x72\x65\x65\x74\x04\x43\x69\x74\x79\x05\x53\x74\x61\x74\x65"
    "\x03\x5A\x69\x70\x01\x01\x01\x01\x03\x00\x00\x00\x06\x04\x00\x00"
    "\x00\x11\x4F\x6E\x65\x20\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x20"
    "\x57\x61\x79\x06\x05\x00\x00\x00\x07\x52\x65\x64\x6D\x6F\x6E\x64"
    "\x06\x06\x00\x00\x00\x02\x57\x41\x06\x07\x00\x00\x00\x05\x39\x38"
    "\x30\x35\x34\x0B", 372);

int main(void)
{
    try
    {
        auto root_node = net_deserializer::deserialize(test_data);
        std::cout << root_node->as_xml();
        std::cerr << "Finished" << std::endl;
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}
<commit_msg>cli: explicitly state errors as errors<commit_after>#include <iostream>
#include "net_deserializer.h"

static const auto test_data = std::string(
    "\x00\x01\x00\x00\x00\xFF\xFF\xFF\xFF\x01\x00\x00\x00\x00\x00\x00"
    "\x00\x15\x14\x00\x00\x00\x12\x0B\x53\x65\x6E\x64\x41\x64\x64\x72"
    "\x65\x73\x73\x12\x6F\x44\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67"
    "\x4D\x65\x74\x61\x64\x61\x74\x61\x2E\x4D\x79\x53\x65\x72\x76\x65"
    "\x72\x2C\x20\x44\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67\x4D\x65"
    "\x74\x61\x64\x61\x74\x61\x2C\x20\x56\x65\x72\x73\x69\x6F\x6E\x3D"
    "\x31\x2E\x30\x2E\x32\x36\x32\x32\x2E\x33\x31\x33\x32\x36\x2C\x20"
    "\x43\x75\x6C\x74\x75\x72\x65\x3D\x6E\x65\x75\x74\x72\x61\x6C\x2C"
    "\x20\x50\x75\x62\x6C\x69\x63\x4B\x65\x79\x54\x6F\x6B\x65\x6E\x3D"
    "\x6E\x75\x6C\x6C\x10\x01\x00\x00\x00\x01\x00\x00\x00\x09\x02\x00"
    "\x00\x00\x0C\x03\x00\x00\x00\x51\x44\x4F\x4A\x52\x65\x6D\x6F\x74"
    "\x69\x6E\x67\x4D\x65\x74\x61\x64\x61\x74\x61\x2C\x20\x56\x65\x72"
    "\x73\x69\x6F\x6E\x3D\x31\x2E\x30\x2E\x32\x36\x32\x32\x2E\x33\x31"
    "\x33\x32\x36\x2C\x20\x43\x75\x6C\x74\x75\x72\x65\x3D\x6E\x65\x75"
    "\x74\x72\x61\x6C\x2C\x20\x50\x75\x62\x6C\x69\x63\x4B\x65\x79\x54"
    "\x6F\x6B\x65\x6E\x3D\x6E\x75\x6C\x6C\x05\x02\x00\x00\x00\x1B\x44"
    "\x4F\x4A\x52\x65\x6D\x6F\x74\x69\x6E\x67\x4D\x65\x74\x61\x64\x61"
    "\x74\x61\x2E\x41\x64\x64\x72\x65\x73\x73\x04\x00\x00\x00\x06\x53"
    "\x74\x72\x65\x65\x74\x04\x43\x69\x74\x79\x05\x53\x74\x61\x74\x65"
    "\x03\x5A\x69\x70\x01\x01\x01\x01\x03\x00\x00\x00\x06\x04\x00\x00"
    "\x00\x11\x4F\x6E\x65\x20\x4D\x69\x63\x72\x6F\x73\x6F\x66\x74\x20"
    "\x57\x61\x79\x06\x05\x00\x00\x00\x07\x52\x65\x64\x6D\x6F\x6E\x64"
    "\x06\x06\x00\x00\x00\x02\x57\x41\x06\x07\x00\x00\x00\x05\x39\x38"
    "\x30\x35\x34\x0B", 372);

int main(void)
{
    try
    {
        auto root_node = net_deserializer::deserialize(test_data);
        std::cerr << "Finished" << std::endl;
        std::cout << root_node->as_xml();
    }
    catch (std::exception &e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}
<|endoftext|>


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

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkProbabilisticAtlas.h>

irtkProbabilisticAtlas::irtkProbabilisticAtlas()
{
  _number_of_voxels=0;
  _number_of_tissues=0;
}

void irtkProbabilisticAtlas::AddImage(irtkRealImage image)
{
  if (_images.size() == 0) {
    _number_of_voxels = image.GetNumberOfVoxels();
  } else {
    if (_number_of_voxels != image.GetNumberOfVoxels()) {
      cerr << "Image sizes mismatch" << endl;
      exit(1);
    }
  }
  _images.push_back(image);
  _pointers.push_back(image.GetPointerToVoxels());
  _number_of_tissues = _images.size();
}

void irtkProbabilisticAtlas::NormalizeAtlas(irtkRealImage background)
{
  int i, j;
  irtkRealPixel norm;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::NormalizeAtlas: No probability maps found" << endl;
    exit(1);
  } else {
    this->AddImage(background);
    _number_of_tissues = _images.size();

  }

  // normalize atlas to 0 to 1
  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues; j++) {
      norm += *(_pointers[j]);
    }
    if (norm>0) {
      for (j = 0; j < _number_of_tissues; j++)
        *(_pointers[j]) = *(_pointers[j])/norm;
    } else {
      for (j = 0; j < _number_of_tissues-1; j++)
        *(_pointers[j]) = 0;
      *(_pointers[_number_of_tissues-1]) = 1;
    }
    this->Next();
  }
}

void irtkProbabilisticAtlas::NormalizeAtlas()
{
  int i, j;
  irtkRealPixel norm;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::NormalizeAtlas: No probability maps found" << endl;
    exit(1);
  }
  _number_of_tissues = _images.size();

  // normalize atlas to 0 to 1
  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues; j++) {
      norm += *(_pointers[j]);
    }
    if (norm>0) {
      for (j = 0; j < _number_of_tissues; j++)
        *(_pointers[j]) = *(_pointers[j])/norm;
    } else {
      for (j = 0; j < _number_of_tissues-1; j++)
        *(_pointers[j]) = 0;
      *(_pointers[_number_of_tissues-1]) = 1;
    }
    this->Next();
  }
}

void irtkProbabilisticAtlas::AddBackground()
{
  int i, j;
  irtkRealPixel norm, min, max;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::AddBackground: No probability maps found" << endl;
    exit(1);
  } else {
    this->AddImage(_images[0]);
    _number_of_tissues = _images.size();

  }

  // normalize atlas to 0 to 1
  irtkRealImage other;
  other = _images[0];
  for (i = 1; i < _number_of_tissues-1; i++) {
    cerr<<i<<endl;
    other += _images[i];
  }
  other.GetMinMax(&min, &max);

  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues-1; j++) {
      *(_pointers[j]) = (*(_pointers[j]) - min) / (max - min);
      norm += *(_pointers[j]);
    }
    double value = 1 - norm;
    if (value < 0) value = 0;
    if (value > 1) value = 1;
    *(_pointers[_number_of_tissues-1]) = value;
    this->Next();
  }
}

void irtkProbabilisticAtlas::AddProbabilityMaps(int n, irtkRealImage **atlas)
{
  int i;

  for (i = 0; i < n; i++) {
    this->AddImage(*(atlas[i]));
  }
};

void irtkProbabilisticAtlas::Write(int i, const char *filename)
{
  if  (i < _number_of_tissues) {
    _images[i] *= 255;
    _images[i].Write(filename);
    _images[i] /= 255;
  } else {
    cerr << "irtkProbabilisticAtlas::Write: No such probability map" << endl;
    exit(1);
  }
}

irtkRealImage irtkProbabilisticAtlas::ComputeHardSegmentation()
{
  cerr<<"irtkProbabilisticAtlas::ComputeHardSegmentation"<<endl;
  int i, tissue, j=0;
  double max = 0;
  _segmentation = _images[0];
  First();
  irtkRealPixel *ptr = _segmentation.GetPointerToVoxels();

  for (i = 0; i < _number_of_voxels; i++) {
    max=0;
    tissue = -1;
    for (j=0; j< GetNumberOfTissues(); j++) {
      if (GetValue(j) > max) {
        tissue = j;
        max = GetValue(j);
      }
    }

    /*    switch (tissue)
        {
          case 0: *ptr = -1; break;
          case 1: *ptr = 45; break;
          case 2: *ptr = 75; break;
          case 3: *ptr = 80; break;
          case 4: *ptr = 82; break;
          case 5: *ptr = 85; break;
          case 6: *ptr = 81; break;
          case 7: *ptr = 87; break;
          case 8: *ptr = 89; break;
          case 9: *ptr = 94; break;
          case 10: *ptr = 100; break;
          case 11: *ptr = 100; break;

          default: cerr << "Tissue identificator out of range." <<endl;
        }
    */
    *ptr = tissue;
    Next();
    ptr++;

    /*switch (tissue)
    {
      case WHITE: *ptr = white_value; break;
      case GREY:  *ptr = grey_value;  break;
      case CSF:   *ptr = csf_value;   break;
      case OTHER: *ptr = 0; break;

      default: cerr << "Tissue identificator out of range." <<endl;
    */
  }
  return _segmentation;
}

irtkRealImage irtkProbabilisticAtlas::GetImage(int i)
{
  return _images[i];
}

void irtkProbabilisticAtlas::ExtractLabel(int label, irtkRealImage& image)
{
  cerr<<"irtkProbabilisticAtlas::ExtractLabel"<<endl;
  int i;
  //ComputeHardSegmentation();

  irtkRealPixel *ptr = _segmentation.GetPointerToVoxels();
  irtkRealPixel *ptr_im = image.GetPointerToVoxels();

  for (i = 0; i < _number_of_voxels; i++) {
    if (*ptr == label) *ptr_im = 1;
    else *ptr_im = 0;
    ptr++;
    ptr_im++;
  }
}

void irtkProbabilisticAtlas::WriteHardSegmentation(const char *filename)
{
  _segmentation.Write(filename);
}
<commit_msg>added "SwapImages"<commit_after>/*=========================================================================

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

=========================================================================*/

#include <irtkImage.h>

#include <irtkProbabilisticAtlas.h>

irtkProbabilisticAtlas::irtkProbabilisticAtlas()
{
  _number_of_voxels=0;
  _number_of_tissues=0;
}

void irtkProbabilisticAtlas::SwapImages(int a, int b)
{
	if( a < 0 || b < 0 || a >= _number_of_tissues || b >= _number_of_tissues )
	{
		cerr << "cannot swap images, index out of bounds!" << endl;
		return;
	}
	irtkRealImage tmpimage = _images[a];
	_images[a] = _images[b];
	_images[b] = tmpimage;
	irtkRealPixel* tmpptr = _pointers[a];
	_pointers[a] = _pointers[b];
	_pointers[a] = tmpptr;
}

void irtkProbabilisticAtlas::AddImage(irtkRealImage image)
{
  if (_images.size() == 0) {
    _number_of_voxels = image.GetNumberOfVoxels();
  } else {
    if (_number_of_voxels != image.GetNumberOfVoxels()) {
      cerr << "Image sizes mismatch" << endl;
      exit(1);
    }
  }
  _images.push_back(image);
  _pointers.push_back(image.GetPointerToVoxels());
  _number_of_tissues = _images.size();
}

void irtkProbabilisticAtlas::NormalizeAtlas(irtkRealImage background)
{
  int i, j;
  irtkRealPixel norm;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::NormalizeAtlas: No probability maps found" << endl;
    exit(1);
  } else {
    this->AddImage(background);
    _number_of_tissues = _images.size();

  }

  // normalize atlas to 0 to 1
  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues; j++) {
      norm += *(_pointers[j]);
    }
    if (norm>0) {
      for (j = 0; j < _number_of_tissues; j++)
        *(_pointers[j]) = *(_pointers[j])/norm;
    } else {
      for (j = 0; j < _number_of_tissues-1; j++)
        *(_pointers[j]) = 0;
      *(_pointers[_number_of_tissues-1]) = 1;
    }
    this->Next();
  }
}

void irtkProbabilisticAtlas::NormalizeAtlas()
{
  int i, j;
  irtkRealPixel norm;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::NormalizeAtlas: No probability maps found" << endl;
    exit(1);
  }
  _number_of_tissues = _images.size();

  // normalize atlas to 0 to 1
  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues; j++) {
      norm += *(_pointers[j]);
    }
    if (norm>0) {
      for (j = 0; j < _number_of_tissues; j++)
        *(_pointers[j]) = *(_pointers[j])/norm;
    } else {
      for (j = 0; j < _number_of_tissues-1; j++)
        *(_pointers[j]) = 0;
      *(_pointers[_number_of_tissues-1]) = 1;
    }
    this->Next();
  }
}

void irtkProbabilisticAtlas::AddBackground()
{
  int i, j;
  irtkRealPixel norm, min, max;

  // Add extra image
  if (_number_of_tissues == 0) {
    cerr << "irtkProbabilisticAtlas::AddBackground: No probability maps found" << endl;
    exit(1);
  } else {
    this->AddImage(_images[0]);
    _number_of_tissues = _images.size();

  }

  // normalize atlas to 0 to 1
  irtkRealImage other;
  other = _images[0];
  for (i = 1; i < _number_of_tissues-1; i++) {
    cerr<<i<<endl;
    other += _images[i];
  }
  other.GetMinMax(&min, &max);

  this->First();
  for (i = 0; i < _number_of_voxels; i++) {
    norm = 0;
    for (j = 0; j < _number_of_tissues-1; j++) {
      *(_pointers[j]) = (*(_pointers[j]) - min) / (max - min);
      norm += *(_pointers[j]);
    }
    double value = 1 - norm;
    if (value < 0) value = 0;
    if (value > 1) value = 1;
    *(_pointers[_number_of_tissues-1]) = value;
    this->Next();
  }
}

void irtkProbabilisticAtlas::AddProbabilityMaps(int n, irtkRealImage **atlas)
{
  int i;

  for (i = 0; i < n; i++) {
    this->AddImage(*(atlas[i]));
  }
};

void irtkProbabilisticAtlas::Write(int i, const char *filename)
{
  if  (i < _number_of_tissues) {
    _images[i] *= 255;
    _images[i].Write(filename);
    _images[i] /= 255;
  } else {
    cerr << "irtkProbabilisticAtlas::Write: No such probability map" << endl;
    exit(1);
  }
}

irtkRealImage irtkProbabilisticAtlas::ComputeHardSegmentation()
{
  cerr<<"irtkProbabilisticAtlas::ComputeHardSegmentation"<<endl;
  int i, tissue, j=0;
  double max = 0;
  _segmentation = _images[0];
  First();
  irtkRealPixel *ptr = _segmentation.GetPointerToVoxels();

  for (i = 0; i < _number_of_voxels; i++) {
    max=0;
    tissue = -1;
    for (j=0; j< GetNumberOfTissues(); j++) {
      if (GetValue(j) > max) {
        tissue = j;
        max = GetValue(j);
      }
    }

    /*    switch (tissue)
        {
          case 0: *ptr = -1; break;
          case 1: *ptr = 45; break;
          case 2: *ptr = 75; break;
          case 3: *ptr = 80; break;
          case 4: *ptr = 82; break;
          case 5: *ptr = 85; break;
          case 6: *ptr = 81; break;
          case 7: *ptr = 87; break;
          case 8: *ptr = 89; break;
          case 9: *ptr = 94; break;
          case 10: *ptr = 100; break;
          case 11: *ptr = 100; break;

          default: cerr << "Tissue identificator out of range." <<endl;
        }
    */
    *ptr = tissue;
    Next();
    ptr++;

    /*switch (tissue)
    {
      case WHITE: *ptr = white_value; break;
      case GREY:  *ptr = grey_value;  break;
      case CSF:   *ptr = csf_value;   break;
      case OTHER: *ptr = 0; break;

      default: cerr << "Tissue identificator out of range." <<endl;
    */
  }
  return _segmentation;
}

irtkRealImage irtkProbabilisticAtlas::GetImage(int i)
{
  return _images[i];
}

void irtkProbabilisticAtlas::ExtractLabel(int label, irtkRealImage& image)
{
  cerr<<"irtkProbabilisticAtlas::ExtractLabel"<<endl;
  int i;
  //ComputeHardSegmentation();

  irtkRealPixel *ptr = _segmentation.GetPointerToVoxels();
  irtkRealPixel *ptr_im = image.GetPointerToVoxels();

  for (i = 0; i < _number_of_voxels; i++) {
    if (*ptr == label) *ptr_im = 1;
    else *ptr_im = 0;
    ptr++;
    ptr_im++;
  }
}

void irtkProbabilisticAtlas::WriteHardSegmentation(const char *filename)
{
  _segmentation.Write(filename);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdio>

#include "shell.h"
#include "dump.h"
#include "ansi_color.h"

extern std::string current_dict_name;
extern bool verbose_mode;

int main(int argc, char **argv)
{
  std::cout << ANSI_UNDERLINE_ON "PDIC CUI Search ver 0.6 (c)2012 @naoya_t. All Rights Reserved." ANSI_UNDERLINE_OFF << std::endl;
  std::cout << "読み込み中..." << std::endl;
  shell_init();

  if (argc >= 2) {
    std::string filename = argv[1];
    do_load(filename);
  }

  // REPL
  for (bool looping=true; looping; ) {
    std::cout << current_dict_name << "> ";
    char line[256];
    if (!fgets(line, 256, stdin)) { newline(); break; }
    int linelen = strlen(line); line[--linelen] = 0;
    if (linelen == 0) continue;

    switch (line[0]) {
      case '?':
        // help...
        break;

      case '.': // command mode
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[COMMAND] %s\n", line+1);
          }
          looping = do_command(line+1);
        }
        break;

      case '!': // external shell mode
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[EXTERNAL] %s\n", line+1);
          }
          system(line+1);
        }
        break;

      case '*':
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[LOOKUP<sarray>] %s\n", line+1);
          }
          do_sarray_lookup(line+1, linelen-1);
        }
        break;

      case '/':
        if (linelen >= 3) {
          if (strchr(line+1,'/') == line + linelen - 1)  {
            line[linelen-1] = 0;
            if (verbose_mode) {
              //printf("[LOOKUP<regexp>] /%s/\n", line+1);
            }
            do_regexp_lookup(line+1, linelen-2);
            break;
          }
        }
        // else fall thru

      default:
        if (verbose_mode) {
          //printf("[LOOKUP<normal>] %s\n", line);
        }
        do_normal_lookup(line, linelen);
        break;
    }
  }

  shell_destroy();

  std::cout << "bye!" << std::endl;
  return 0;
}
<commit_msg>シェルで+1文字を入力すると(?i)+無理ぽとか言われるので予約コマンドにしておく<commit_after>#include <iostream>
#include <string>
#include <cstdio>

#include "shell.h"
#include "dump.h"
#include "ansi_color.h"

extern std::string current_dict_name;
extern bool verbose_mode;

int main(int argc, char **argv)
{
  std::cout << ANSI_UNDERLINE_ON "PDIC CUI Search ver 0.6 (c)2012 @naoya_t. All Rights Reserved." ANSI_UNDERLINE_OFF << std::endl;
  std::cout << "読み込み中..." << std::endl;
  shell_init();

  if (argc >= 2) {
    std::string filename = argv[1];
    do_load(filename);
  }

  // REPL
  for (bool looping=true; looping; ) {
    std::cout << current_dict_name << "> ";
    char line[256];
    if (!fgets(line, 256, stdin)) { newline(); break; }
    int linelen = strlen(line); line[--linelen] = 0;
    if (linelen == 0) continue;

    switch (line[0]) {
      case '?': // reserved (help)
        break;
      case '+': // reserved
        break;

      case '.': // command mode
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[COMMAND] %s\n", line+1);
          }
          looping = do_command(line+1);
        }
        break;

      case '!': // external shell mode
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[EXTERNAL] %s\n", line+1);
          }
          system(line+1);
        }
        break;

      case '*':
        if (linelen > 1) {
          if (verbose_mode) {
            //printf("[LOOKUP<sarray>] %s\n", line+1);
          }
          do_sarray_lookup(line+1, linelen-1);
        }
        break;

      case '/':
        if (linelen >= 3) {
          if (strchr(line+1,'/') == line + linelen - 1)  {
            line[linelen-1] = 0;
            if (verbose_mode) {
              //printf("[LOOKUP<regexp>] /%s/\n", line+1);
            }
            do_regexp_lookup(line+1, linelen-2);
            break;
          }
        }
        // else fall thru

      default:
        if (verbose_mode) {
          //printf("[LOOKUP<normal>] %s\n", line);
        }
        do_normal_lookup(line, linelen);
        break;
    }
  }

  shell_destroy();

  std::cout << "bye!" << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "directshowglobal.h"
#include "directshowrenderthread.h"

DirectShowRenderThread::DirectShowRenderThread(QObject *parent)
    : QThread(parent)
    , m_pendingTasks(0)
    , m_executingTask(0)
    , m_executedTasks(0)
    , m_graph(0)
    , m_builder(0)
    , m_source(0)
    , m_audioOutput(0)
    , m_videoOutput(0)
    , m_rate(1.0)
    , m_position(0)
{
    start();
}

DirectShowRenderThread::~DirectShowRenderThread()
{
    if (m_audioOutput)
        m_audioOutput->Release();

    if (m_videoOutput)
        m_videoOutput->Release();
}

void DirectShowRenderThread::shutdown()
{
    {
        QMutexLocker locker(&m_mutex);
        m_pendingTasks = Shutdown;

        if (m_graph)
            m_graph->Abort();

        m_wait.wakeAll();
    }

    wait();

    if (m_builder) {
        m_builder->Release();
        m_builder = 0;
    }

    if (m_graph) {
        m_graph->Release();
        m_graph = 0;
    }

    if (m_source) {
        m_source->Release();
        m_source = 0;
    }
}

void DirectShowRenderThread::load(const QUrl &url, IGraphBuilder *graph)
{
    QMutexLocker locker(&m_mutex);

    if (m_graph) {
        if (m_source) {
            m_source->Release();
            m_source = 0;
        }

        if (m_executingTask != 0) {
            m_graph->Abort();
            m_pendingTasks = Stop;

            m_wait.wait(&m_mutex);
        }

        m_graph->Release();
    }

    m_url = url;
    m_graph = graph;

    if (m_graph) {
        m_graph->AddRef();

        m_pendingTasks = Load;

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::setAudioOutput(IBaseFilter *filter)
{
    QMutexLocker locker(&m_mutex);

    if (m_audioOutput) {
        if (m_executedTasks & SetAudioOutput) {
            m_graph->RemoveFilter(m_audioOutput);
        }
        m_audioOutput->Release();
    }

    m_audioOutput = filter;

    if (m_audioOutput) {
        m_audioOutput->AddRef();

        if (m_executedTasks & Load) {
            m_pendingTasks |= SetAudioOutput;

            m_wait.wakeAll();
        }
    }
}

void DirectShowRenderThread::setVideoOutput(IBaseFilter *filter)
{
    QMutexLocker locker(&m_mutex);

    if (m_videoOutput) {
        if (m_executedTasks & SetVideoOutput) {
            m_graph->RemoveFilter(m_videoOutput);
        }
        m_videoOutput->Release();
    }

    m_videoOutput = filter;

    if (m_videoOutput) {
        m_videoOutput->AddRef();

        if (m_executedTasks & Load) {
            m_pendingTasks |= SetVideoOutput;

            m_wait.wakeAll();
        }
    }
}

void DirectShowRenderThread::setRate(qreal rate)
{
    QMutexLocker locker(&m_mutex);

    m_rate = rate;

    m_pendingTasks |= SetRate;

    if (m_executedTasks & Load)
        m_wait.wakeAll();
}

void DirectShowRenderThread::seek(qint64 position)
{
    QMutexLocker locker(&m_mutex);

    m_position = position;

    m_pendingTasks |= Seek;

    if (m_executedTasks & Load)
        m_wait.wakeAll();
}

void DirectShowRenderThread::play()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~Pause;
    m_pendingTasks |= Play;

    if (m_executedTasks & Load) {
        if (m_executedTasks & Stop) {
            m_position = 0;
            m_pendingTasks |= Seek;
        }

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::pause()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~Play;
    m_pendingTasks |= Pause;

    if (m_executedTasks & Load) {
        if (m_executedTasks & Stop) {
            m_position = 0;
            m_pendingTasks |= Seek;
        }

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::stop()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~(Play | Pause | Seek);

    if (m_executedTasks & Load) {
        if (m_executingTask & (Play | Pause | Seek)) {
            m_pendingTasks |= Stop;

            m_wait.wait(&m_mutex);
        }

        if (m_executedTasks & (Play | Pause)) {
            if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
                control->Stop();
                control->Release();
            }
            m_executedTasks &= ~(Play | Pause);
            m_executedTasks |= Stop;
        }
    }
}

void DirectShowRenderThread::run()
{
    QMutexLocker locker(&m_mutex);

    while (!(m_pendingTasks & Shutdown)) {
        if (m_pendingTasks & Load) {
            m_pendingTasks ^= Load;
            m_executingTask = Load;

            doLoad(&locker);
        } else if (m_pendingTasks & SetAudioOutput) {
            m_pendingTasks ^= SetAudioOutput;
            m_executingTask = SetAudioOutput;

            doSetAudioOutput(&locker);
        } else if (m_pendingTasks & SetVideoOutput) {
            m_pendingTasks ^= SetVideoOutput;
            m_executingTask = SetVideoOutput;

            doSetVideoOutput(&locker);
        } else if (m_pendingTasks & SetRate) {
            m_pendingTasks ^= SetRate;
            m_executingTask = SetRate;

            doSetRate(&locker);
        } else if (m_pendingTasks & Stop) {
            m_pendingTasks ^= Stop;

            m_wait.wakeAll();
        } else if (m_pendingTasks & Pause) {
            m_pendingTasks ^= Pause;
            m_executingTask = Pause;

            doPause(&locker);
        } else if (m_pendingTasks & Seek) {
            m_pendingTasks ^= Seek;
            m_executingTask = Seek;

            doSeek(&locker);
        } else if (m_pendingTasks & Play) {
            m_pendingTasks ^= Play;
            m_executingTask = Play;

            doPlay(&locker);
        }
        m_executingTask = 0;

        if (m_pendingTasks == 0)
            m_wait.wait(&m_mutex);
    }
}

void DirectShowRenderThread::doLoad(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    m_executedTasks = 0;

    if (m_builder)
        m_builder->Release();

    m_builder = com_new<ICaptureGraphBuilder2>(CLSID_CaptureGraphBuilder2);

    if (!m_builder) {
        qWarning("failed to create capture graph builder object");
    } else if (!SUCCEEDED(m_builder->SetFiltergraph(m_graph))) {
        qWarning("failed to set filter graph on capture builder");

        m_builder->Release();
        m_builder = 0;
    } else {
        IBaseFilter *source = 0;
        QUrl url = m_url;

        // This is potentially time consuming so unlock the mutex, and give the
        // caller an opportunity to abort.
        locker->unlock();
        HRESULT hr = m_graph->AddSourceFilter(url.toString().utf16(), L"Source", &source);
        locker->relock();

        if (SUCCEEDED(hr)) {
            m_executedTasks = Load;

            m_source = source;

            if (m_audioOutput)
                m_pendingTasks |= SetAudioOutput;

            if (m_videoOutput)
                m_pendingTasks |= SetVideoOutput;

            if (m_rate != 1.0)
                m_pendingTasks |= SetRate;

            emit loaded();
        }
    }
}

void DirectShowRenderThread::doSetAudioOutput(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    IGraphBuilder *graph = m_graph;
    graph->AddRef();

    IBaseFilter *source = m_source;
    source->AddRef();

    IBaseFilter *audioOutput = m_audioOutput;
    audioOutput->AddRef();

    if (!SUCCEEDED(graph->AddFilter(m_audioOutput, L"AudioOutput"))) {
        qWarning("Failed to add audio output to filter graph.");
    } else {
        locker->unlock();
        HRESULT hr = m_builder->RenderStream(0, &MEDIATYPE_Audio, source, 0, audioOutput);
        locker->relock();

        if (!SUCCEEDED(hr)) {
            m_graph->RemoveFilter(audioOutput);
        } else {
            m_executedTasks |= SetAudioOutput;
        }
    }

    audioOutput->Release();
    source->Release();
    graph->Release();
}

void DirectShowRenderThread::doSetVideoOutput(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    IGraphBuilder *graph = m_graph;
    graph->AddRef();

    IBaseFilter *source = m_source;
    source->AddRef();

    IBaseFilter *videoOutput = m_videoOutput;
    videoOutput->AddRef();

    if (!SUCCEEDED(graph->AddFilter(m_videoOutput, L"VideoOutput"))) {
        qWarning("Failed to add video output to filter graph.");
    } else {
        locker->unlock();
        HRESULT hr = m_builder->RenderStream(0, &MEDIATYPE_Video, source, 0, videoOutput);
        locker->relock();

        if (!SUCCEEDED(hr)) {
            m_graph->RemoveFilter(videoOutput);
        } else {
            m_executedTasks |= SetVideoOutput;
        }
    }

    videoOutput->Release();
    source->Release();
    graph->Release();
}

void DirectShowRenderThread::doSetRate(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaSeeking *seeking = com_cast<IMediaSeeking>(m_graph)) {
        locker->unlock();
        seeking->SetRate(m_rate);
        locker->relock();

        seeking->Release();
    }
}

void DirectShowRenderThread::doSeek(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaSeeking *seeking = com_cast<IMediaSeeking>(m_graph)) {
        LONGLONG pos = LONGLONG(m_position) * 10;

        locker->unlock();
        seeking->SetPositions(&pos, AM_SEEKING_AbsolutePositioning, 0, AM_SEEKING_NoPositioning);
        locker->relock();

        seeking->Release();
    }
}

void DirectShowRenderThread::doPlay(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
        locker->unlock();
        HRESULT hr = control->Run();
        locker->relock();

        control->Release();

        if (SUCCEEDED(hr))
            m_executedTasks |= Play;
    }
}

void DirectShowRenderThread::doPause(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
        locker->unlock();
        HRESULT hr = control->Pause();
        locker->relock();

        control->Release();

        if (SUCCEEDED(hr))
            m_executedTasks |= Pause;
    }
}
<commit_msg>Enable basic audio renderering.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "directshowglobal.h"
#include "directshowrenderthread.h"

DirectShowRenderThread::DirectShowRenderThread(QObject *parent)
    : QThread(parent)
    , m_pendingTasks(0)
    , m_executingTask(0)
    , m_executedTasks(0)
    , m_graph(0)
    , m_builder(0)
    , m_source(0)
    , m_audioOutput(0)
    , m_videoOutput(0)
    , m_rate(1.0)
    , m_position(0)
{
    start();
}

DirectShowRenderThread::~DirectShowRenderThread()
{
    if (m_audioOutput)
        m_audioOutput->Release();

    if (m_videoOutput)
        m_videoOutput->Release();
}

void DirectShowRenderThread::shutdown()
{
    {
        QMutexLocker locker(&m_mutex);
        m_pendingTasks = Shutdown;

        if (m_graph)
            m_graph->Abort();

        m_wait.wakeAll();
    }

    wait();

    if (m_builder) {
        m_builder->Release();
        m_builder = 0;
    }

    if (m_graph) {
        m_graph->Release();
        m_graph = 0;
    }

    if (m_source) {
        m_source->Release();
        m_source = 0;
    }
}

void DirectShowRenderThread::load(const QUrl &url, IGraphBuilder *graph)
{
    QMutexLocker locker(&m_mutex);

    if (m_graph) {
        if (m_source) {
            m_source->Release();
            m_source = 0;
        }

        if (m_executingTask != 0) {
            m_graph->Abort();
            m_pendingTasks = Stop;

            m_wait.wait(&m_mutex);
        }

        m_graph->Release();
    }

    m_url = url;
    m_graph = graph;

    if (m_graph) {
        m_graph->AddRef();

        m_pendingTasks = Load;

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::setAudioOutput(IBaseFilter *filter)
{
    QMutexLocker locker(&m_mutex);

    if (m_audioOutput) {
        if (m_executedTasks & SetAudioOutput) {
            m_graph->RemoveFilter(m_audioOutput);
        }
        m_audioOutput->Release();
    }

    m_audioOutput = filter;

    if (m_audioOutput) {
        m_audioOutput->AddRef();

        if (m_executedTasks & Load) {
            m_pendingTasks |= SetAudioOutput;

            m_wait.wakeAll();
        }
    }
}

void DirectShowRenderThread::setVideoOutput(IBaseFilter *filter)
{
    QMutexLocker locker(&m_mutex);

    if (m_videoOutput) {
        if (m_executedTasks & SetVideoOutput) {
            m_graph->RemoveFilter(m_videoOutput);
        }
        m_videoOutput->Release();
    }

    m_videoOutput = filter;

    if (m_videoOutput) {
        m_videoOutput->AddRef();

        if (m_executedTasks & Load) {
            m_pendingTasks |= SetVideoOutput;

            m_wait.wakeAll();
        }
    }
}

void DirectShowRenderThread::setRate(qreal rate)
{
    QMutexLocker locker(&m_mutex);

    m_rate = rate;

    m_pendingTasks |= SetRate;

    if (m_executedTasks & Load)
        m_wait.wakeAll();
}

void DirectShowRenderThread::seek(qint64 position)
{
    QMutexLocker locker(&m_mutex);

    m_position = position;

    m_pendingTasks |= Seek;

    if (m_executedTasks & Load)
        m_wait.wakeAll();
}

void DirectShowRenderThread::play()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~Pause;
    m_pendingTasks |= Play;

    if (m_executedTasks & Load) {
        if (m_executedTasks & Stop) {
            m_position = 0;
            m_pendingTasks |= Seek;
        }

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::pause()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~Play;
    m_pendingTasks |= Pause;

    if (m_executedTasks & Load) {
        if (m_executedTasks & Stop) {
            m_position = 0;
            m_pendingTasks |= Seek;
        }

        m_wait.wakeAll();
    }
}

void DirectShowRenderThread::stop()
{
    QMutexLocker locker(&m_mutex);

    m_pendingTasks &= ~(Play | Pause | Seek);

    if (m_executedTasks & Load) {
        if (m_executingTask & (Play | Pause | Seek)) {
            m_pendingTasks |= Stop;

            m_wait.wait(&m_mutex);
        }

        if (m_executedTasks & (Play | Pause)) {
            if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
                control->Stop();
                control->Release();
            }
            m_executedTasks &= ~(Play | Pause);
            m_executedTasks |= Stop;
        }
    }
}

void DirectShowRenderThread::run()
{
    QMutexLocker locker(&m_mutex);

    while (!(m_pendingTasks & Shutdown)) {
        if (m_pendingTasks & Load) {
            m_pendingTasks ^= Load;
            m_executingTask = Load;

            doLoad(&locker);
        } else if (m_pendingTasks & SetAudioOutput) {
            m_pendingTasks ^= SetAudioOutput;
            m_executingTask = SetAudioOutput;

            doSetAudioOutput(&locker);
        } else if (m_pendingTasks & SetVideoOutput) {
            m_pendingTasks ^= SetVideoOutput;
            m_executingTask = SetVideoOutput;

            doSetVideoOutput(&locker);
        } else if (m_pendingTasks & SetRate) {
            m_pendingTasks ^= SetRate;
            m_executingTask = SetRate;

            doSetRate(&locker);
        } else if (m_pendingTasks & Stop) {
            m_pendingTasks ^= Stop;

            m_wait.wakeAll();
        } else if (m_pendingTasks & Pause) {
            m_pendingTasks ^= Pause;
            m_executingTask = Pause;

            doPause(&locker);
        } else if (m_pendingTasks & Seek) {
            m_pendingTasks ^= Seek;
            m_executingTask = Seek;

            doSeek(&locker);
        } else if (m_pendingTasks & Play) {
            m_pendingTasks ^= Play;
            m_executingTask = Play;

            doPlay(&locker);
        }
        m_executingTask = 0;

        if (m_pendingTasks == 0)
            m_wait.wait(&m_mutex);
    }
}

void DirectShowRenderThread::doLoad(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    m_executedTasks = 0;

    if (m_builder)
        m_builder->Release();

    m_builder = com_new<ICaptureGraphBuilder2>(CLSID_CaptureGraphBuilder2);

    if (!m_builder) {
        qWarning("failed to create capture graph builder object");
    } else if (!SUCCEEDED(m_builder->SetFiltergraph(m_graph))) {
        qWarning("failed to set filter graph on capture builder");

        m_builder->Release();
        m_builder = 0;
    } else {
        IBaseFilter *source = 0;
        QUrl url = m_url;

        // This is potentially time consuming so unlock the mutex, and give the
        // caller an opportunity to abort.
        locker->unlock();
        HRESULT hr = m_graph->AddSourceFilter(url.toString().utf16(), L"Source", &source);

        // As a temporary measure render to the default audio device.
        m_builder->RenderStream(0, &MEDIATYPE_Audio, source, 0, 0);

        locker->relock();

        if (SUCCEEDED(hr)) {
            m_executedTasks = Load;

            m_source = source;

            if (m_audioOutput)
                m_pendingTasks |= SetAudioOutput;

            if (m_videoOutput)
                m_pendingTasks |= SetVideoOutput;

            if (m_rate != 1.0)
                m_pendingTasks |= SetRate;

            emit loaded();
        }
    }
}

void DirectShowRenderThread::doSetAudioOutput(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    IGraphBuilder *graph = m_graph;
    graph->AddRef();

    IBaseFilter *source = m_source;
    source->AddRef();

    IBaseFilter *audioOutput = m_audioOutput;
    audioOutput->AddRef();

    if (!SUCCEEDED(graph->AddFilter(m_audioOutput, L"AudioOutput"))) {
        qWarning("Failed to add audio output to filter graph.");
    } else {
        locker->unlock();
        HRESULT hr = m_builder->RenderStream(0, &MEDIATYPE_Audio, source, 0, audioOutput);

        locker->relock();

        if (!SUCCEEDED(hr)) {
            m_graph->RemoveFilter(audioOutput);
        } else {
            m_executedTasks |= SetAudioOutput;
        }
    }

    audioOutput->Release();
    source->Release();
    graph->Release();
}

void DirectShowRenderThread::doSetVideoOutput(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    IGraphBuilder *graph = m_graph;
    graph->AddRef();

    IBaseFilter *source = m_source;
    source->AddRef();

    IBaseFilter *videoOutput = m_videoOutput;
    videoOutput->AddRef();

    if (!SUCCEEDED(graph->AddFilter(m_videoOutput, L"VideoOutput"))) {
        qWarning("Failed to add video output to filter graph.");
    } else {
        locker->unlock();
        HRESULT hr = m_builder->RenderStream(0, &MEDIATYPE_Video, source, 0, videoOutput);
        locker->relock();

        if (!SUCCEEDED(hr)) {
            m_graph->RemoveFilter(videoOutput);
        } else {
            m_executedTasks |= SetVideoOutput;
        }
    }

    videoOutput->Release();
    source->Release();
    graph->Release();
}

void DirectShowRenderThread::doSetRate(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaSeeking *seeking = com_cast<IMediaSeeking>(m_graph)) {
        locker->unlock();
        seeking->SetRate(m_rate);
        locker->relock();

        seeking->Release();
    }
}

void DirectShowRenderThread::doSeek(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaSeeking *seeking = com_cast<IMediaSeeking>(m_graph)) {
        LONGLONG pos = LONGLONG(m_position) * 10;

        locker->unlock();
        seeking->SetPositions(&pos, AM_SEEKING_AbsolutePositioning, 0, AM_SEEKING_NoPositioning);
        locker->relock();

        seeking->Release();
    }
}

void DirectShowRenderThread::doPlay(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
        locker->unlock();
        HRESULT hr = control->Run();
        locker->relock();

        control->Release();

        if (SUCCEEDED(hr))
            m_executedTasks |= Play;
    }
}

void DirectShowRenderThread::doPause(QMutexLocker *locker)
{
    qDebug(Q_FUNC_INFO);
    if (IMediaControl *control = com_cast<IMediaControl>(m_graph)) {
        locker->unlock();
        HRESULT hr = control->Pause();
        locker->relock();

        control->Release();

        if (SUCCEEDED(hr))
            m_executedTasks |= Pause;
    }
}
<|endoftext|>


<commit_before>#include "Logger.h"

#include "AGE/Engine.h"

int main()
{
  AGE::Engine engine;

  Logger::instance().log(Logger::INFO, "Initializing...\n");
  if (!engine.init())
  {
    printf("Advanced Game Engine failed to initialize. Exiting.\n");
    exit(1);
  }

  Logger::instance().log(Logger::INFO, "Initialization complete.\nLoading the media...\n");
  if (!engine.loadMedia())
  {
    Logger::instance().log(Logger::WARNING, "Warning: some media files failed to load!\n");
  }
  Logger::instance().log(Logger::INFO, "Media loded.\n");

  engine.startLoop();

  // Destroys the window and quits the SDL system:
  engine.close();
  return 0;
}
<commit_msg>Fix main method to utilize the Logger properly<commit_after>#include "Logger.h"

#include "AGE/Engine.h"

int main()
{
  AGE::Engine engine;

  Logger::instance().log(Logger::INFO, "Initializing...");
  if (!engine.init())
  {
    Logger::instance().log(Logger::CRITICAL,
        "Advanced Game Engine failed to initialize. Exiting.");
    exit(1);
  }

  Logger::instance().log(Logger::INFO, "Initialization complete.");
  Logger::instance().log(Logger::INFO, "Loading the media...");
  if (!engine.loadMedia())
  {
    Logger::instance().log(Logger::WARNING,
        "Warning: some media files failed to load!");
  }
  Logger::instance().log(Logger::INFO, "Media loded.");

  engine.startLoop();

  // Destroys the window and quits the SDL system:
  engine.close();
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_RX_SUBJECT_HPP)
#define RXCPP_RX_SUBJECT_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace subjects {

namespace detail {

template<class T>
class multicast_observer
{
    typedef subscriber<T> observer_type;
    typedef std::vector<observer_type> list_type;

    struct mode
    {
        enum type {
            Invalid = 0,
            Casting,
            Disposed,
            Completed,
            Errored
        };
    };

    struct state_type
        : public std::enable_shared_from_this<state_type>
    {
        explicit state_type(composite_subscription cs)
            : generation(0)
            , current(mode::Casting)
            , lifetime(cs)
        {
        }
        std::atomic<int> generation;
        std::mutex lock;
        typename mode::type current;
        std::exception_ptr error;
        composite_subscription lifetime;
    };

    struct completer_type
        : public std::enable_shared_from_this<completer_type>
    {
        ~completer_type()
        {
        }
        completer_type(std::shared_ptr<state_type> s, const std::shared_ptr<completer_type>& old, observer_type o)
            : state(s)
        {
            if (old) {
                observers.reserve(old->observers.size() + 1);
                std::copy_if(
                    old->observers.begin(), old->observers.end(),
                    std::inserter(observers, observers.end()),
                    [](const observer_type& o){
                        return o.is_subscribed();
                    });
            }
            observers.push_back(o);
        }
        std::shared_ptr<state_type> state;
        list_type observers;
    };

    // this type prevents a circular ref between state and completer
    struct binder_type
        : public std::enable_shared_from_this<binder_type>
    {
        explicit binder_type(composite_subscription cs)
            : state(std::make_shared<state_type>(cs))
            , id(trace_id::make_next_id_subscriber())
            , current_generation(0)
        {
        }

        std::shared_ptr<state_type> state;

        trace_id id;

        // used to avoid taking lock in on_next
        mutable int current_generation;
        mutable std::shared_ptr<completer_type> current_completer;

        // must only be accessed under state->lock
        mutable std::shared_ptr<completer_type> completer;
    };

    std::shared_ptr<binder_type> b;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> input_subscriber_type;

    explicit multicast_observer(composite_subscription cs)
        : b(std::make_shared<binder_type>(cs))
    {
        std::weak_ptr<binder_type> binder = b;
        b->state->lifetime.add([binder](){
            auto b = binder.lock();
            if (b && b->state->current == mode::Casting){
                b->state->current = mode::Disposed;
                b->current_completer.reset();
                b->completer.reset();
                ++b->state->generation;
            }
        });
    }
    trace_id get_id() const {
        return b->id;
    }
    composite_subscription get_subscription() const {
        return b->state->lifetime;
    }
    input_subscriber_type get_subscriber() const {
        return make_subscriber<T>(get_id(), get_subscription(), observer<T, detail::multicast_observer<T>>(*this));
    }
    bool has_observers() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        return b->current_completer && !b->current_completer->observers.empty();
    }
    template<class SubscriberFrom>
    void add(const SubscriberFrom& sf, observer_type o) const {
        trace_activity().connect(sf, o);
        std::unique_lock<std::mutex> guard(b->state->lock);
        switch (b->state->current) {
        case mode::Casting:
            {
                if (o.is_subscribed()) {
                    b->completer = std::make_shared<completer_type>(b->state, b->completer, o);
                    ++b->state->generation;
                }
            }
            break;
        case mode::Completed:
            {
                guard.unlock();
                o.on_completed();
                return;
            }
            break;
        case mode::Errored:
            {
                auto e = b->state->error;
                guard.unlock();
                o.on_error(e);
                return;
            }
            break;
        case mode::Disposed:
            {
                guard.unlock();
                o.unsubscribe();
                return;
            }
            break;
        default:
            abort();
        }
    }
    template<class V>
    void on_next(V v) const {
        if (b->current_generation != b->state->generation) {
            std::unique_lock<std::mutex> guard(b->state->lock);
            b->current_generation = b->state->generation;
            b->current_completer = b->completer;
        }

        auto current_completer = b->current_completer;
        if (!current_completer || current_completer->observers.empty()) {
            return;
        }
        for (auto& o : current_completer->observers) {
            if (o.is_subscribed()) {
                o.on_next(v);
            }
        }
    }
    void on_error(std::exception_ptr e) const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->error = e;
            b->state->current = mode::Errored;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_error(e);
                    }
                }
            }
            s.unsubscribe();
        }
    }
    void on_completed() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->current = mode::Completed;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_completed();
                    }
                }
            }
            s.unsubscribe();
        }
    }
};

}

template<class T>
class subject
{
    detail::multicast_observer<T> s;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> subscriber_type;
    typedef observable<T> observable_type;
    subject()
        : s(composite_subscription())
    {
    }
    explicit subject(composite_subscription cs)
        : s(cs)
    {
    }

    bool has_observers() const {
        return s.has_observers();
    }

    subscriber_type get_subscriber() const {
        return s.get_subscriber();
    }

    observable<T> get_observable() const {
        auto keepAlive = s;
        return make_observable_dynamic<T>([=](subscriber<T> o){
            keepAlive.add(keepAlive.get_subscriber(), std::move(o));
        });
    }
};

}

}

#endif
<commit_msg>fix lifetime issue in subject<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

#if !defined(RXCPP_RX_SUBJECT_HPP)
#define RXCPP_RX_SUBJECT_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace subjects {

namespace detail {

template<class T>
class multicast_observer
{
    typedef subscriber<T> observer_type;
    typedef std::vector<observer_type> list_type;

    struct mode
    {
        enum type {
            Invalid = 0,
            Casting,
            Disposed,
            Completed,
            Errored
        };
    };

    struct state_type
        : public std::enable_shared_from_this<state_type>
    {
        explicit state_type(composite_subscription cs)
            : generation(0)
            , current(mode::Casting)
            , lifetime(cs)
        {
        }
        std::atomic<int> generation;
        std::mutex lock;
        typename mode::type current;
        std::exception_ptr error;
        composite_subscription lifetime;
    };

    struct completer_type
        : public std::enable_shared_from_this<completer_type>
    {
        ~completer_type()
        {
        }
        completer_type(std::shared_ptr<state_type> s, const std::shared_ptr<completer_type>& old, observer_type o)
            : state(s)
        {
            retain(old);
            observers.push_back(o);
        }
        completer_type(std::shared_ptr<state_type> s, const std::shared_ptr<completer_type>& old)
            : state(s)
        {
            retain(old);
        }
        void retain(const std::shared_ptr<completer_type>& old) {
            if (old) {
                observers.reserve(old->observers.size() + 1);
                std::copy_if(
                    old->observers.begin(), old->observers.end(),
                    std::inserter(observers, observers.end()),
                    [](const observer_type& o){
                        return o.is_subscribed();
                    });
            }
        }
        std::shared_ptr<state_type> state;
        list_type observers;
    };

    // this type prevents a circular ref between state and completer
    struct binder_type
        : public std::enable_shared_from_this<binder_type>
    {
        explicit binder_type(composite_subscription cs)
            : state(std::make_shared<state_type>(cs))
            , id(trace_id::make_next_id_subscriber())
            , current_generation(0)
        {
        }

        std::shared_ptr<state_type> state;

        trace_id id;

        // used to avoid taking lock in on_next
        mutable int current_generation;
        mutable std::shared_ptr<completer_type> current_completer;

        // must only be accessed under state->lock
        mutable std::shared_ptr<completer_type> completer;
    };

    std::shared_ptr<binder_type> b;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> input_subscriber_type;

    explicit multicast_observer(composite_subscription cs)
        : b(std::make_shared<binder_type>(cs))
    {
        std::weak_ptr<binder_type> binder = b;
        b->state->lifetime.add([binder](){
            auto b = binder.lock();
            if (b && b->state->current == mode::Casting){
                b->state->current = mode::Disposed;
                b->current_completer.reset();
                b->completer.reset();
                ++b->state->generation;
            }
        });
    }
    trace_id get_id() const {
        return b->id;
    }
    composite_subscription get_subscription() const {
        return b->state->lifetime;
    }
    input_subscriber_type get_subscriber() const {
        return make_subscriber<T>(get_id(), get_subscription(), observer<T, detail::multicast_observer<T>>(*this));
    }
    bool has_observers() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        return b->current_completer && !b->current_completer->observers.empty();
    }
    template<class SubscriberFrom>
    void add(const SubscriberFrom& sf, observer_type o) const {
        trace_activity().connect(sf, o);
        std::unique_lock<std::mutex> guard(b->state->lock);
        switch (b->state->current) {
        case mode::Casting:
            {
                if (o.is_subscribed()) {
                    std::weak_ptr<binder_type> binder = b;
                    o.add([=](){
                        auto b = binder.lock();
                        if (b) {
                            std::unique_lock<std::mutex> guard(b->state->lock);
                            b->completer = std::make_shared<completer_type>(b->state, b->completer);
                            ++b->state->generation;
                        }
                    });
                    b->completer = std::make_shared<completer_type>(b->state, b->completer, o);
                    ++b->state->generation;
                }
            }
            break;
        case mode::Completed:
            {
                guard.unlock();
                o.on_completed();
                return;
            }
            break;
        case mode::Errored:
            {
                auto e = b->state->error;
                guard.unlock();
                o.on_error(e);
                return;
            }
            break;
        case mode::Disposed:
            {
                guard.unlock();
                o.unsubscribe();
                return;
            }
            break;
        default:
            abort();
        }
    }
    template<class V>
    void on_next(V v) const {
        if (b->current_generation != b->state->generation) {
            std::unique_lock<std::mutex> guard(b->state->lock);
            b->current_generation = b->state->generation;
            b->current_completer = b->completer;
        }

        auto current_completer = b->current_completer;
        if (!current_completer || current_completer->observers.empty()) {
            return;
        }
        for (auto& o : current_completer->observers) {
            if (o.is_subscribed()) {
                o.on_next(v);
            }
        }
    }
    void on_error(std::exception_ptr e) const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->error = e;
            b->state->current = mode::Errored;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_error(e);
                    }
                }
            }
            s.unsubscribe();
        }
    }
    void on_completed() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->current = mode::Completed;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_completed();
                    }
                }
            }
            s.unsubscribe();
        }
    }
};

}

template<class T>
class subject
{
    detail::multicast_observer<T> s;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> subscriber_type;
    typedef observable<T> observable_type;
    subject()
        : s(composite_subscription())
    {
    }
    explicit subject(composite_subscription cs)
        : s(cs)
    {
    }

    bool has_observers() const {
        return s.has_observers();
    }

    subscriber_type get_subscriber() const {
        return s.get_subscriber();
    }

    observable<T> get_observable() const {
        auto keepAlive = s;
        return make_observable_dynamic<T>([=](subscriber<T> o){
            keepAlive.add(keepAlive.get_subscriber(), std::move(o));
        });
    }
};

}

}

#endif
<|endoftext|>