<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.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/

#include "itkTestDriverIncludeRequiredIOFactories.h"

/* Select the environment variable holding the shared library runtime
   search path for this platform.  */

/* Linux */
#if defined(__linux) || defined(__FreeBSD__) || defined(__OpenBSD__)
# define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* OSX */
#elif defined(__APPLE__)
# define ITK_TEST_DRIVER_LDPATH "DYLD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* AIX */
#elif defined(_AIX)
# define ITK_TEST_DRIVER_LDPATH "LIBPATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* SUN */
#elif defined(__sun)
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH_64"

/* HP-UX */
#elif defined(__hpux)
#  define ITK_TEST_DRIVER_LDPATH "SHLIB_PATH"
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH"

/* SGI MIPS */
#elif defined(__sgi) && defined(_MIPS_SIM)
# if _MIPS_SIM == _ABIO32
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# elif _MIPS_SIM == _ABIN32
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARYN32_PATH"
# endif
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY64_PATH"

/* Cygwin */
#elif defined(__CYGWIN__)
# define ITK_TEST_DRIVER_LDPATH "PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* Windows */
#elif defined(_WIN32)
# define ITK_TEST_DRIVER_LDPATH "PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* Guess on this unknown system.  */
#else
# define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH
#endif

#if defined(_WIN32) && !defined(__CYGWIN__)
# define ITK_TEST_DRIVER_PATH_SEP ';'
# define ITK_TEST_DRIVER_PATH_SLASH '\\'
#else
# define ITK_TEST_DRIVER_PATH_SEP ':'
# define ITK_TEST_DRIVER_PATH_SLASH '/'
#endif

void AddEntriesBeforeLibraryPath( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string libpath = ITK_TEST_DRIVER_LDPATH;
    libpath += "=";
    libpath += args[i];
    char *oldenv = getenv(ITK_TEST_DRIVER_LDPATH);
    if ( oldenv )
      {
      libpath += ITK_TEST_DRIVER_PATH_SEP;
      libpath += oldenv;
      }
    itksys::SystemTools::PutEnv( libpath.c_str() );
    // on some 64 bit systems, LD_LIBRARY_PATH_64 is used before
    // LD_LIBRARY_PATH if it is set. It can lead the test to load
    // the system library instead of the expected one, so this
    // var must also be set
    if ( std::string(ITK_TEST_DRIVER_LDPATH) != ITK_TEST_DRIVER_LDPATH64 )
      {
      std::string libpath64 = ITK_TEST_DRIVER_LDPATH64;
      libpath64 += "=";
      libpath64 += args[i];
      char *oldenv64 = getenv(ITK_TEST_DRIVER_LDPATH64);
      if ( oldenv64 )
        {
        libpath64 += ITK_TEST_DRIVER_PATH_SEP;
        libpath64 += oldenv64;
        }
      itksys::SystemTools::PutEnv( libpath64.c_str() );
      }

    i++;
    }
}

void AddEntriesBeforeEnvironment( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string env = args[i];
    env += "=";
    env += args[i+1];
    char *oldenv = getenv( args[i] );
    if ( oldenv )
      {
      env += ITK_TEST_DRIVER_PATH_SEP;
      env += oldenv;
      }
    itksys::SystemTools::PutEnv( env.c_str() );

    i += 2;
    }
}

void AddEntriesBeforeEnvironmentWithSeparator( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string env = args[i];
    env += "=";
    env += args[i+1];
    char *oldenv = getenv( args[i] );
    if ( oldenv )
      {
      env += args[i+2];
      env += oldenv;
      }
    itksys::SystemTools::PutEnv( env.c_str() );

    i += 3;
    }
}

int TestDriverInvokeProcess( const ArgumentsList & args )
{
  // a NULL is required at the end of the table
  char ** argv = new char *[args.size() + 1];
  for ( unsigned int i = 0; i < args.size(); i++ )
    {
    argv[i] = args[i];
    }
  argv[args.size()] = NULL;

  itksysProcess *process = itksysProcess_New();
  itksysProcess_SetCommand(process, argv);
  itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDOUT, true);
  itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDERR, true);
  itksysProcess_Execute(process);
  itksysProcess_WaitForExit(process, NULL);

  delete[] argv;

  int state = itksysProcess_GetState(process);
  switch( state )
    {
    case itksysProcess_State_Error:
      {
      std::cerr << "itkTestDriver: Process error: " << itksysProcess_GetErrorString(process) << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Exception:
      {
      std::cerr << "itkTestDriver: Process exception: " << itksysProcess_GetExceptionString(process) << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Executing:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: process can't be in Executing State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Exited:
      {
      // this is the normal case - it is treated later
      break;
      }
    case itksysProcess_State_Expired:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: process can't be in Expired State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Killed:
      {
      std::cerr << "itkTestDriver: The process has been killed." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Disowned:
      {
      std::cerr << "itkTestDriver: Process disowned." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    default:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: unknown State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    }

  int retCode = itksysProcess_GetExitValue(process);
  if ( retCode != 0 )
    {
    std::cerr << "itkTestDriver: Process exited with return value: " << retCode << std::endl;
    }
  itksysProcess_Delete(process);
return retCode;
}

int main(int ac, char *av[])
{
  RegisterRequiredFactories();

  ProcessedOutputType po;

  int result = 0;

  result = ProcessArguments(&ac, &av, &po);

  if ( po.externalProcessMustBeCalled && po.args.empty() )
    {
    usage();
    return 1;
    }

  if ( !po.externalProcessMustBeCalled && !po.args.empty() )
    {
    usage();
    return 1;
    }

  if ( !result && po.externalProcessMustBeCalled )
    {
    AddEntriesBeforeLibraryPath( po.add_before_libpath );

    AddEntriesBeforeEnvironment( po.add_before_env );

    AddEntriesBeforeEnvironmentWithSeparator( po.add_before_env_with_sep );

    result = TestDriverInvokeProcess( po.args );
    }

  if (result == 0)
    {
    #include "itkTestDriverBeforeTest.inc"
    #include "itkTestDriverAfterTest.inc"
    }

  return result;
}
<commit_msg>BUG: itkTestDriver should only print usage once<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.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/

#include "itkTestDriverIncludeRequiredIOFactories.h"

/* Select the environment variable holding the shared library runtime
   search path for this platform.  */

/* Linux */
#if defined(__linux) || defined(__FreeBSD__) || defined(__OpenBSD__)
# define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* OSX */
#elif defined(__APPLE__)
# define ITK_TEST_DRIVER_LDPATH "DYLD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* AIX */
#elif defined(_AIX)
# define ITK_TEST_DRIVER_LDPATH "LIBPATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* SUN */
#elif defined(__sun)
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH_64"

/* HP-UX */
#elif defined(__hpux)
#  define ITK_TEST_DRIVER_LDPATH "SHLIB_PATH"
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH"

/* SGI MIPS */
#elif defined(__sgi) && defined(_MIPS_SIM)
# if _MIPS_SIM == _ABIO32
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# elif _MIPS_SIM == _ABIN32
#  define ITK_TEST_DRIVER_LDPATH "LD_LIBRARYN32_PATH"
# endif
#  define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY64_PATH"

/* Cygwin */
#elif defined(__CYGWIN__)
# define ITK_TEST_DRIVER_LDPATH "PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* Windows */
#elif defined(_WIN32)
# define ITK_TEST_DRIVER_LDPATH "PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH

/* Guess on this unknown system.  */
#else
# define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH"
# define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH
#endif

#if defined(_WIN32) && !defined(__CYGWIN__)
# define ITK_TEST_DRIVER_PATH_SEP ';'
# define ITK_TEST_DRIVER_PATH_SLASH '\\'
#else
# define ITK_TEST_DRIVER_PATH_SEP ':'
# define ITK_TEST_DRIVER_PATH_SLASH '/'
#endif

void AddEntriesBeforeLibraryPath( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string libpath = ITK_TEST_DRIVER_LDPATH;
    libpath += "=";
    libpath += args[i];
    char *oldenv = getenv(ITK_TEST_DRIVER_LDPATH);
    if ( oldenv )
      {
      libpath += ITK_TEST_DRIVER_PATH_SEP;
      libpath += oldenv;
      }
    itksys::SystemTools::PutEnv( libpath.c_str() );
    // on some 64 bit systems, LD_LIBRARY_PATH_64 is used before
    // LD_LIBRARY_PATH if it is set. It can lead the test to load
    // the system library instead of the expected one, so this
    // var must also be set
    if ( std::string(ITK_TEST_DRIVER_LDPATH) != ITK_TEST_DRIVER_LDPATH64 )
      {
      std::string libpath64 = ITK_TEST_DRIVER_LDPATH64;
      libpath64 += "=";
      libpath64 += args[i];
      char *oldenv64 = getenv(ITK_TEST_DRIVER_LDPATH64);
      if ( oldenv64 )
        {
        libpath64 += ITK_TEST_DRIVER_PATH_SEP;
        libpath64 += oldenv64;
        }
      itksys::SystemTools::PutEnv( libpath64.c_str() );
      }

    i++;
    }
}

void AddEntriesBeforeEnvironment( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string env = args[i];
    env += "=";
    env += args[i+1];
    char *oldenv = getenv( args[i] );
    if ( oldenv )
      {
      env += ITK_TEST_DRIVER_PATH_SEP;
      env += oldenv;
      }
    itksys::SystemTools::PutEnv( env.c_str() );

    i += 2;
    }
}

void AddEntriesBeforeEnvironmentWithSeparator( const ArgumentsList & args )
{
  unsigned int i = 0;

  while( i < args.size() )
    {
    std::string env = args[i];
    env += "=";
    env += args[i+1];
    char *oldenv = getenv( args[i] );
    if ( oldenv )
      {
      env += args[i+2];
      env += oldenv;
      }
    itksys::SystemTools::PutEnv( env.c_str() );

    i += 3;
    }
}

int TestDriverInvokeProcess( const ArgumentsList & args )
{
  // a NULL is required at the end of the table
  char ** argv = new char *[args.size() + 1];
  for ( unsigned int i = 0; i < args.size(); i++ )
    {
    argv[i] = args[i];
    }
  argv[args.size()] = NULL;

  itksysProcess *process = itksysProcess_New();
  itksysProcess_SetCommand(process, argv);
  itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDOUT, true);
  itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDERR, true);
  itksysProcess_Execute(process);
  itksysProcess_WaitForExit(process, NULL);

  delete[] argv;

  int state = itksysProcess_GetState(process);
  switch( state )
    {
    case itksysProcess_State_Error:
      {
      std::cerr << "itkTestDriver: Process error: " << itksysProcess_GetErrorString(process) << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Exception:
      {
      std::cerr << "itkTestDriver: Process exception: " << itksysProcess_GetExceptionString(process) << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Executing:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: process can't be in Executing State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Exited:
      {
      // this is the normal case - it is treated later
      break;
      }
    case itksysProcess_State_Expired:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: process can't be in Expired State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Killed:
      {
      std::cerr << "itkTestDriver: The process has been killed." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    case itksysProcess_State_Disowned:
      {
      std::cerr << "itkTestDriver: Process disowned." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    default:
      {
      // this is not a possible state after itksysProcess_WaitForExit
      std::cerr << "itkTestDriver: Internal error: unknown State." << std::endl;
      itksysProcess_Delete(process);
      return 1;
      }
    }

  int retCode = itksysProcess_GetExitValue(process);
  if ( retCode != 0 )
    {
    std::cerr << "itkTestDriver: Process exited with return value: " << retCode << std::endl;
    }
  itksysProcess_Delete(process);
return retCode;
}

int main(int ac, char *av[])
{
  RegisterRequiredFactories();

  ProcessedOutputType po;

  int result = 0;

  result = ProcessArguments(&ac, &av, &po);

  if( result )
    {
    // There was a problem parsing the arguments, so usage has already
    // been printed, just return
    return 1;
    }

  if ( po.externalProcessMustBeCalled && po.args.empty() )
    {
    usage();
    return 1;
    }

  if ( !po.externalProcessMustBeCalled && !po.args.empty() )
    {
    usage();
    return 1;
    }

  if ( !result && po.externalProcessMustBeCalled )
    {
    AddEntriesBeforeLibraryPath( po.add_before_libpath );

    AddEntriesBeforeEnvironment( po.add_before_env );

    AddEntriesBeforeEnvironmentWithSeparator( po.add_before_env_with_sep );

    result = TestDriverInvokeProcess( po.args );
    }

  if (result == 0)
    {
    #include "itkTestDriverBeforeTest.inc"
    #include "itkTestDriverAfterTest.inc"
    }

  return result;
}
<|endoftext|>


<commit_before>#include "Character.h"
#include "PlayScene.h"

CCharacter::CCharacter(void)
{
}

CCharacter::~CCharacter(void)
{
}

void CCharacter::initStatus( void )
{

}

/*
Լ : DetermineAttackTarget
 :  ü attack_target ϴ Լ ϸ ȴ.
Ŀ GoAttackTarget Լ ϸ
ֿ  : ̱  Scene ִ  Police迭 鼭 NNPoint Լ ̿
Ÿ ϰ   Ÿ Ͽ شϴ idx  Ÿ ȯѴ.

  : 2013/11/03
  : 2013/11/04

ISSUE : 1 . switch ݺǴ For ϳ   ãƾ .
 .
*/
void  CCharacter::DetermineAttackTarget()
{
	float return_distnace = 1000000.0f;
	float next_distance;
	CZombie *tmp_closer_target_zombie = NULL;
	CPolice *tmp_closer_target_police = NULL;
	CCharacter *return_target = NULL;

	switch(this->GetIdentity())
	{
	case Zombie:
		for(const auto& child : CPlayScene::GetInstance()->GetPoliceList())
		{
			next_distance = this->GetPosition().GetDistance(child->GetPosition());
			 	if(return_distnace > next_distance)
			 	{
			 		return_distnace = next_distance;
			 		m_AttackTarget = child;
			 	}
		}
		if(m_AttackTarget == NULL)
			m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase();
		break;

	case Police:
		for(const auto& child : CPlayScene::GetInstance()->GetZombieList())
		{
			next_distance= this->GetPosition().GetDistance(child->GetPosition());
			 	if(return_distnace > next_distance)
			 	{
			 		return_distnace = next_distance;
			 		m_AttackTarget = child;
			 	}
		}
		if(m_AttackTarget == NULL)
			m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase();
		break;
	default:
		break;
	}

}

void CCharacter::InitSprite( std::wstring imagePath )
{
	m_Sprite = NNSprite::Create(imagePath);

	// θ  ġ  ޱ
	// θ ĳ  ġ ϰ
	// ڽ sprite (0, 0) ʱȭѴ.
	// ̰Ͷ ѽð   Ф

	m_Sprite->SetPosition(0.0f, 0.0f);
	AddChild(m_Sprite, 1);
}

void CCharacter::SetRandomPositionAroundBase()
{
	NNPoint baseLocation;

	switch (m_Identity)
	{
	case Zombie:
		baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition();
		baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X);
		baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y);
		break;
	case Police:
		baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition();
		baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X);
		break;
	default:
		break;
	}

	int random_location_x = rand() % TILE_SIZE_X;
	int random_location_y = rand() % TILE_SIZE_Y;

	SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y));
}

void CCharacter::Render()
{
	NNObject::Render();
}

void CCharacter::Update( float dTime )
{
	DetermineAttackTarget();
	if(IsAttack())
		Attack();
	else
		GoToAttackTarget(dTime);
}

void CCharacter::Attack()
{
	CCharacter* target = this->m_AttackTarget;

	if(this->m_AttackTarget){
		int damage = this->GetAttackPower() - target->GetDefensivePower();
		target->SetHP(target->GetHP()-damage) ;
	}
}

void CCharacter::GoToAttackTarget(float dTime)
{
	float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX();
	float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY();
	float t_x = (gap_x) / (gap_x+gap_y);
	float t_y = (gap_y) / (gap_x+gap_y);

	this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime);

}

bool CCharacter::IsAttack()
{
	float distance_attacktarget;

	distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());

	if(distance_attacktarget <= m_AttackRange)
		return true;
	else
		return false;

}
<commit_msg>주석 추가. 일부 코드 리팩토링<commit_after>#include "Character.h"
#include "PlayScene.h"

CCharacter::CCharacter(void)
{
}

CCharacter::~CCharacter(void)
{
}

void CCharacter::initStatus( void )
{

}

/*
Լ : DetermineAttackTarget
 :  ü attack_target ϴ Լ ϸ ȴ.
Ŀ GoAttackTarget Լ ϸ
ֿ  : ̱  Scene ִ  Police迭 鼭 NNPoint Լ ̿
Ÿ ϰ   Ÿ Ͽ شϴ idx  Ÿ ȯѴ.

  : 2013/11/03
  : 2013/11/14

ISSUE : 1 . switch ݺǴ For ϳ   ãƾ .
 .

11/14 : Enemy   (NULL) attackTarget  Base ϵ
*/
void  CCharacter::DetermineAttackTarget()
{
	float return_distnace = 1000000.0f;
	float next_distance;
	CZombie *tmp_closer_target_zombie = NULL;
	CPolice *tmp_closer_target_police = NULL;
	CCharacter *return_target = NULL;

	switch(this->GetIdentity())
	{
	case Zombie:
		for(const auto& child : CPlayScene::GetInstance()->GetPoliceList())
		{
			next_distance = this->GetPosition().GetDistance(child->GetPosition());
			 	if(return_distnace > next_distance)
			 	{
			 		return_distnace = next_distance;
			 		m_AttackTarget = child;
			 	}
		}
		if(m_AttackTarget == NULL)
			m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase();
		break;

	case Police:
		for(const auto& child : CPlayScene::GetInstance()->GetZombieList())
		{
			next_distance= this->GetPosition().GetDistance(child->GetPosition());
			 	if(return_distnace > next_distance)
			 	{
			 		return_distnace = next_distance;
			 		m_AttackTarget = child;
			 	}
		}
		if(m_AttackTarget == NULL)
			m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase();
		break;
	default:
		break;
	}
}

void CCharacter::InitSprite( std::wstring imagePath )
{
	m_Sprite = NNSprite::Create(imagePath);

	// θ  ġ  ޱ
	// θ ĳ  ġ ϰ
	// ڽ sprite (0, 0) ʱȭѴ.
	// ̰Ͷ ѽð   Ф

	m_Sprite->SetPosition(0.0f, 0.0f);
	AddChild(m_Sprite, 1);
}

void CCharacter::SetRandomPositionAroundBase()
{
	NNPoint baseLocation;

	switch (m_Identity)
	{
	case Zombie:
		baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition();
		baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X);
		baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y);
		break;
	case Police:
		baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition();
		baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X);
		break;
	default:
		break;
	}

	int random_location_x = rand() % TILE_SIZE_X;
	int random_location_y = rand() % TILE_SIZE_Y;

	SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y));
}

void CCharacter::Render()
{
	NNObject::Render();
}

void CCharacter::Update( float dTime )
{
	//AttackTarget ϰ Attack ϸ(Ÿ üũ)
	//ϰ ׷  Attack Target
	DetermineAttackTarget();
	if(IsAttack())
		Attack();
	else
		GoToAttackTarget(dTime);
}

void CCharacter::Attack()
{
	CCharacter* target = this->m_AttackTarget;

	if(this->m_AttackTarget){
		int damage = this->GetAttackPower() - target->GetDefensivePower();
		target->SetHP(target->GetHP()-damage) ;
	}
}

/*
ȣ. 11/14
Attack_target Ÿ Ͽ   ϵ .
Issue :  ϴ MakeCharacterWalk 
*/
void CCharacter::GoToAttackTarget(float dTime)
{
	float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX();
	float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY();
	float t_x = (gap_x) / (gap_x+gap_y);
	float t_y = (gap_y) / (gap_x+gap_y);

	this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime);
}

/*
ȣ. 11/14
 Ȳ AttackTarget  Ÿ ȿ ִ üũ.
 ϸ True,  (־) False
*/
bool CCharacter::IsAttack()
{
	float distance_attacktarget;

	distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());

	if(distance_attacktarget <= m_AttackRange)
		return true;
	else
		return false;

}
<|endoftext|>


<commit_before>#include "SystemUtils.h"
#include "PlatformSpecificUtils.h"
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <stdio.h>
#include <iostream>
#include <signal.h>
#include <string.h>
#include <sys/stat.h>

#ifdef _MSC_VER
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
	// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
	static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);

	SYSTEMTIME  system_time;
	FILETIME    file_time;
	uint64_t    time;

	GetSystemTime(&system_time);
	SystemTimeToFileTime(&system_time, &file_time);
	time = ((uint64_t)file_time.dwLowDateTime);
	time += ((uint64_t)file_time.dwHighDateTime) << 32;

	tp->tv_sec = (long)((time - EPOCH) / 10000000L);
	tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
	return 0;
}
#endif

namespace pcpp
{

const SystemCore SystemCores::Core0 = { 0x01, 0 };
const SystemCore SystemCores::Core1 = { 0x02, 1 };
const SystemCore SystemCores::Core2 = { 0x04, 2 };
const SystemCore SystemCores::Core3 = { 0x08, 3 };
const SystemCore SystemCores::Core4 = { 0x10, 4 };
const SystemCore SystemCores::Core5 = { 0x20, 5 };
const SystemCore SystemCores::Core6 = { 0x40, 6 };
const SystemCore SystemCores::Core7 = { 0x80, 7 };
const SystemCore SystemCores::Core8 = { 0x100, 8 };
const SystemCore SystemCores::Core9 = { 0x200, 9 };
const SystemCore SystemCores::Core10 = { 0x400, 10 };
const SystemCore SystemCores::Core11 = { 0x800, 11 };
const SystemCore SystemCores::Core12 = { 0x1000, 12 };
const SystemCore SystemCores::Core13 = { 0x2000, 13 };
const SystemCore SystemCores::Core14 = { 0x4000, 14 };
const SystemCore SystemCores::Core15 = { 0x8000, 15 };
const SystemCore SystemCores::Core16 = { 0x10000, 16 };
const SystemCore SystemCores::Core17 = { 0x20000, 17 };
const SystemCore SystemCores::Core18 = { 0x40000, 18 };
const SystemCore SystemCores::Core19 = { 0x80000, 19 };
const SystemCore SystemCores::Core20 = { 0x100000, 20 };
const SystemCore SystemCores::Core21 = { 0x200000, 21 };
const SystemCore SystemCores::Core22 = { 0x400000, 22 };
const SystemCore SystemCores::Core23 = { 0x800000, 23 };
const SystemCore SystemCores::Core24 = { 0x1000000, 24 };
const SystemCore SystemCores::Core25 = { 0x2000000, 25 };
const SystemCore SystemCores::Core26 = { 0x4000000, 26 };
const SystemCore SystemCores::Core27 = { 0x8000000, 27 };
const SystemCore SystemCores::Core28 = { 0x10000000, 28 };
const SystemCore SystemCores::Core29 = { 0x20000000, 29 };
const SystemCore SystemCores::Core30 = { 0x40000000, 30 };
const SystemCore SystemCores::Core31 = { 0x80000000, 31 };

const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] =
{
	SystemCores::Core0,
	SystemCores::Core1,
	SystemCores::Core2,
	SystemCores::Core3,
	SystemCores::Core4,
	SystemCores::Core5,
	SystemCores::Core6,
	SystemCores::Core7,
	SystemCores::Core8,
	SystemCores::Core9,
	SystemCores::Core10,
	SystemCores::Core11,
	SystemCores::Core12,
	SystemCores::Core13,
	SystemCores::Core14,
	SystemCores::Core15,
	SystemCores::Core16,
	SystemCores::Core17,
	SystemCores::Core18,
	SystemCores::Core19,
	SystemCores::Core20,
	SystemCores::Core21,
	SystemCores::Core22,
	SystemCores::Core23,
	SystemCores::Core24,
	SystemCores::Core25,
	SystemCores::Core26,
	SystemCores::Core27,
	SystemCores::Core28,
	SystemCores::Core29,
	SystemCores::Core30,
	SystemCores::Core31
};

int getNumOfCores()
{
#ifdef WIN32
	SYSTEM_INFO sysinfo;
	GetSystemInfo( &sysinfo );
	return sysinfo.dwNumberOfProcessors;
#else
	return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

CoreMask getCoreMaskForAllMachineCores()
{
	int numOfCores = getNumOfCores();
	CoreMask result = 0;
	for (int i = 0; i < numOfCores; i++)
	{
		result = result | SystemCores::IdToSystemCore[i].Mask;
	}

	return result;
}

CoreMask createCoreMaskFromCoreVector(std::vector<SystemCore> cores)
{
	CoreMask result = 0;
	for (std::vector<SystemCore>::iterator iter = cores.begin(); iter != cores.end(); iter++)
	{
		result |= iter->Mask;
	}

	return result;
}

CoreMask createCoreMaskFromCoreIds(std::vector<int> coreIds)
{
	CoreMask result = 0;
	for (std::vector<int>::iterator iter = coreIds.begin(); iter != coreIds.end(); iter++)
	{
		result |= SystemCores::IdToSystemCore[*iter].Mask;
	}

	return result;
}

void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector<SystemCore>& resultVec)
{
	int i = 0;
	while (coreMask != 0)
	{
		if (1 & coreMask)
		{
			resultVec.push_back(SystemCores::IdToSystemCore[i]);
		}

		coreMask = coreMask >> 1;
		i++;
	}
}

std::string executeShellCommand(const std::string command)
{
    FILE* pipe = POPEN(command.c_str(), "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
    	if(fgets(buffer, 128, pipe) != NULL)
    		result += buffer;
    }
    PCLOSE(pipe);
    return result;
}

bool directoryExists(std::string dirPath)
{
    struct stat info;

    if (stat(dirPath.c_str(), &info) != 0)
        return false;
    else if(info.st_mode & S_IFDIR)
        return true;
    else
        return false;
}

std::string AppName::m_AppName;

#ifdef WIN32
BOOL WINAPI ApplicationEventHandler::handlerRoutine(DWORD fdwCtrlType)
{
	switch (fdwCtrlType)
	{
		case CTRL_C_EVENT:
		case CTRL_BREAK_EVENT:
		{
			if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL)
				ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie);
			return TRUE;
		}

		default:
			return FALSE;
	}

}
#else

void ApplicationEventHandler::handlerRoutine(int signum)
{
	switch (signum)
	{
	case SIGINT:
	{
		// Most calls are unsafe in a signal handler, and this includes printf(). In particular,
		// if the signal is caught while inside printf() it may be called twice at the same time which might not be a good idea
		// The way to make sure the signal is called only once is using this lock and putting NULL in m_ApplicationInterruptedHandler
		pthread_mutex_lock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex);

		if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL)
			ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie);

		ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = NULL;

		pthread_mutex_unlock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex);
		return;
	}
	default:
	{
		return;
	}
	}
}
#endif

ApplicationEventHandler::ApplicationEventHandler() :
		 m_ApplicationInterruptedHandler(NULL), m_ApplicationInterruptedCookie(NULL)
{
#ifndef WIN32
	pthread_mutex_init(&m_HandlerRoutineMutex, 0);
#endif
}

void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie)
{
	m_ApplicationInterruptedHandler = handler;
	m_ApplicationInterruptedCookie = cookie;

#ifdef WIN32
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE);
#else
	struct sigaction action;
	memset(&action, 0, sizeof(struct sigaction));
	action.sa_handler = handlerRoutine;
	sigemptyset(&action.sa_mask);
	sigaction(SIGINT, &action, NULL);
#endif
}

} // namespace pcpp
<commit_msg>Bugfix #117 - Limit the number of cores, no more than 32.<commit_after>#include "SystemUtils.h"
#include "PlatformSpecificUtils.h"
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <stdio.h>
#include <iostream>
#include <signal.h>
#include <string.h>
#include <sys/stat.h>

#ifdef _MSC_VER
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
	// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
	static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);

	SYSTEMTIME  system_time;
	FILETIME    file_time;
	uint64_t    time;

	GetSystemTime(&system_time);
	SystemTimeToFileTime(&system_time, &file_time);
	time = ((uint64_t)file_time.dwLowDateTime);
	time += ((uint64_t)file_time.dwHighDateTime) << 32;

	tp->tv_sec = (long)((time - EPOCH) / 10000000L);
	tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
	return 0;
}
#endif

namespace pcpp
{

const SystemCore SystemCores::Core0 = { 0x01, 0 };
const SystemCore SystemCores::Core1 = { 0x02, 1 };
const SystemCore SystemCores::Core2 = { 0x04, 2 };
const SystemCore SystemCores::Core3 = { 0x08, 3 };
const SystemCore SystemCores::Core4 = { 0x10, 4 };
const SystemCore SystemCores::Core5 = { 0x20, 5 };
const SystemCore SystemCores::Core6 = { 0x40, 6 };
const SystemCore SystemCores::Core7 = { 0x80, 7 };
const SystemCore SystemCores::Core8 = { 0x100, 8 };
const SystemCore SystemCores::Core9 = { 0x200, 9 };
const SystemCore SystemCores::Core10 = { 0x400, 10 };
const SystemCore SystemCores::Core11 = { 0x800, 11 };
const SystemCore SystemCores::Core12 = { 0x1000, 12 };
const SystemCore SystemCores::Core13 = { 0x2000, 13 };
const SystemCore SystemCores::Core14 = { 0x4000, 14 };
const SystemCore SystemCores::Core15 = { 0x8000, 15 };
const SystemCore SystemCores::Core16 = { 0x10000, 16 };
const SystemCore SystemCores::Core17 = { 0x20000, 17 };
const SystemCore SystemCores::Core18 = { 0x40000, 18 };
const SystemCore SystemCores::Core19 = { 0x80000, 19 };
const SystemCore SystemCores::Core20 = { 0x100000, 20 };
const SystemCore SystemCores::Core21 = { 0x200000, 21 };
const SystemCore SystemCores::Core22 = { 0x400000, 22 };
const SystemCore SystemCores::Core23 = { 0x800000, 23 };
const SystemCore SystemCores::Core24 = { 0x1000000, 24 };
const SystemCore SystemCores::Core25 = { 0x2000000, 25 };
const SystemCore SystemCores::Core26 = { 0x4000000, 26 };
const SystemCore SystemCores::Core27 = { 0x8000000, 27 };
const SystemCore SystemCores::Core28 = { 0x10000000, 28 };
const SystemCore SystemCores::Core29 = { 0x20000000, 29 };
const SystemCore SystemCores::Core30 = { 0x40000000, 30 };
const SystemCore SystemCores::Core31 = { 0x80000000, 31 };

const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] =
{
	SystemCores::Core0,
	SystemCores::Core1,
	SystemCores::Core2,
	SystemCores::Core3,
	SystemCores::Core4,
	SystemCores::Core5,
	SystemCores::Core6,
	SystemCores::Core7,
	SystemCores::Core8,
	SystemCores::Core9,
	SystemCores::Core10,
	SystemCores::Core11,
	SystemCores::Core12,
	SystemCores::Core13,
	SystemCores::Core14,
	SystemCores::Core15,
	SystemCores::Core16,
	SystemCores::Core17,
	SystemCores::Core18,
	SystemCores::Core19,
	SystemCores::Core20,
	SystemCores::Core21,
	SystemCores::Core22,
	SystemCores::Core23,
	SystemCores::Core24,
	SystemCores::Core25,
	SystemCores::Core26,
	SystemCores::Core27,
	SystemCores::Core28,
	SystemCores::Core29,
	SystemCores::Core30,
	SystemCores::Core31
};

int getNumOfCores()
{
#ifdef WIN32
	SYSTEM_INFO sysinfo;
	GetSystemInfo( &sysinfo );
	return sysinfo.dwNumberOfProcessors;
#else
	return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}

CoreMask getCoreMaskForAllMachineCores()
{
	int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32;
	CoreMask result = 0;
	for (int i = 0; i < numOfCores; i++)
	{
		result = result | SystemCores::IdToSystemCore[i].Mask;
	}

	return result;
}

CoreMask createCoreMaskFromCoreVector(std::vector<SystemCore> cores)
{
	CoreMask result = 0;
	for (std::vector<SystemCore>::iterator iter = cores.begin(); iter != cores.end(); iter++)
	{
		result |= iter->Mask;
	}

	return result;
}

CoreMask createCoreMaskFromCoreIds(std::vector<int> coreIds)
{
	CoreMask result = 0;
	for (std::vector<int>::iterator iter = coreIds.begin(); iter != coreIds.end(); iter++)
	{
		result |= SystemCores::IdToSystemCore[*iter].Mask;
	}

	return result;
}

void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector<SystemCore>& resultVec)
{
	int i = 0;
	while (coreMask != 0)
	{
		if (1 & coreMask)
		{
			resultVec.push_back(SystemCores::IdToSystemCore[i]);
		}

		coreMask = coreMask >> 1;
		i++;
	}
}

std::string executeShellCommand(const std::string command)
{
    FILE* pipe = POPEN(command.c_str(), "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
    	if(fgets(buffer, 128, pipe) != NULL)
    		result += buffer;
    }
    PCLOSE(pipe);
    return result;
}

bool directoryExists(std::string dirPath)
{
    struct stat info;

    if (stat(dirPath.c_str(), &info) != 0)
        return false;
    else if(info.st_mode & S_IFDIR)
        return true;
    else
        return false;
}

std::string AppName::m_AppName;

#ifdef WIN32
BOOL WINAPI ApplicationEventHandler::handlerRoutine(DWORD fdwCtrlType)
{
	switch (fdwCtrlType)
	{
		case CTRL_C_EVENT:
		case CTRL_BREAK_EVENT:
		{
			if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL)
				ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie);
			return TRUE;
		}

		default:
			return FALSE;
	}

}
#else

void ApplicationEventHandler::handlerRoutine(int signum)
{
	switch (signum)
	{
	case SIGINT:
	{
		// Most calls are unsafe in a signal handler, and this includes printf(). In particular,
		// if the signal is caught while inside printf() it may be called twice at the same time which might not be a good idea
		// The way to make sure the signal is called only once is using this lock and putting NULL in m_ApplicationInterruptedHandler
		pthread_mutex_lock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex);

		if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL)
			ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie);

		ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = NULL;

		pthread_mutex_unlock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex);
		return;
	}
	default:
	{
		return;
	}
	}
}
#endif

ApplicationEventHandler::ApplicationEventHandler() :
		 m_ApplicationInterruptedHandler(NULL), m_ApplicationInterruptedCookie(NULL)
{
#ifndef WIN32
	pthread_mutex_init(&m_HandlerRoutineMutex, 0);
#endif
}

void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie)
{
	m_ApplicationInterruptedHandler = handler;
	m_ApplicationInterruptedCookie = cookie;

#ifdef WIN32
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE);
#else
	struct sigaction action;
	memset(&action, 0, sizeof(struct sigaction));
	action.sa_handler = handlerRoutine;
	sigemptyset(&action.sa_mask);
	sigaction(SIGINT, &action, NULL);
#endif
}

} // namespace pcpp
<|endoftext|>


<commit_before>//DEFINITION OF A FEW CONSTANTS
const Int_t    numberOfSigmasPID  = 3;
// ANALYSIS TYPE
const Bool_t anaType   = 1;//0 HD; 1 UU;
const Bool_t usePID = kTRUE;
//----------------------------------------------------

AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Bool_t theMCon=kFALSE)
{

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskDStarSpectra", "No analysis manager to connect to.");
    return NULL;
  }

  TString cutobjname="Dstar";

  // D0 daughters pre-selections
  //
  AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi();
  RDHFDStartoKpipi->SetName("DstartoKpipi");
  RDHFDStartoKpipi->SetTitle("cuts for D* analysis");

  AliESDtrackCuts* esdTrackCuts=new AliESDtrackCuts();
  esdTrackCuts->SetRequireSigmaToVertex(kFALSE);
  //default
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  esdTrackCuts->SetMinNClustersITS(4); // default is 5
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
  					 AliESDtrackCuts::kAny); //test d0 asimmetry
                                                                 // default is kBoth, otherwise kAny
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.1,1.e10);

  //
  // soft pion pre-selections
  //
  AliESDtrackCuts* esdSoftPicuts=new AliESDtrackCuts();
  esdSoftPicuts->SetRequireSigmaToVertex(kFALSE);
  //default
  esdSoftPicuts->SetRequireTPCRefit(kFALSE);
  esdSoftPicuts->SetRequireITSRefit(kFALSE);
  esdSoftPicuts->SetMinNClustersITS(4); // default is 4
  esdSoftPicuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					  AliESDtrackCuts::kAny); //test d0 asimmetry
  esdSoftPicuts->SetPtRange(0.0,1.e10);

  // set pre selections
  RDHFDStartoKpipi->AddTrackCuts(esdTrackCuts);
  RDHFDStartoKpipi->AddTrackCutsSoftPi(esdSoftPicuts);

  const Int_t nvars=14;

  const Int_t nptbins=7;
  Float_t* ptbins;
  ptbins=new Float_t[nptbins+1];
  ptbins[0]=0.7;
  ptbins[1]=1.;
  ptbins[2]=2.;
  ptbins[3]=3.;
  ptbins[4]=5.;
  ptbins[5]=8.;
  ptbins[6]=12.;
  ptbins[7]=18.;

  RDHFDStartoKpipi->SetPtBins(nptbins+1,ptbins);

  Float_t** rdcutsvalmine;
  rdcutsvalmine=new Float_t*[nvars];
  for(Int_t iv=0;iv<nvars;iv++){
    rdcutsvalmine[iv]=new Float_t[nptbins];
  }

  if(anaType==1){ // UU cuts

    rdcutsvalmine[0][0]=0.7;
    rdcutsvalmine[1][0]=0.022;
    rdcutsvalmine[2][0]=0.7;
    rdcutsvalmine[3][0]=0.21;
    rdcutsvalmine[4][0]=0.21;
    rdcutsvalmine[5][0]=0.05;
    rdcutsvalmine[6][0]=0.05;
    rdcutsvalmine[7][0]=-0.00005;
    rdcutsvalmine[8][0]=0.85;
    rdcutsvalmine[9][0]=0.3.;
    rdcutsvalmine[10][0]=0.1;
    rdcutsvalmine[11][0]=0.05;
    rdcutsvalmine[12][0]=100.;
    rdcutsvalmine[13][0]=0.5;

    rdcutsvalmine[0][1]=0.7;
    rdcutsvalmine[1][1]=0.03;
    rdcutsvalmine[2][1]=0.8;
    rdcutsvalmine[3][1]=0.45;
    rdcutsvalmine[4][1]=0.45;
    rdcutsvalmine[5][1]=0.09;
    rdcutsvalmine[6][1]=0.09;
    rdcutsvalmine[7][1]=-0.00029;
    rdcutsvalmine[8][1]=0.8;
    rdcutsvalmine[9][1]=0.3;
    rdcutsvalmine[10][1]=0.1;
    rdcutsvalmine[11][1]=0.05;
    rdcutsvalmine[12][1]=100.;
    rdcutsvalmine[13][1]=1.0;

    rdcutsvalmine[0][2]=0.7;
    rdcutsvalmine[1][2]=0.02;
    rdcutsvalmine[2][2]=0.8;
    rdcutsvalmine[3][2]=0.7;
    rdcutsvalmine[4][2]=0.7;
    rdcutsvalmine[5][2]=0.08;
    rdcutsvalmine[6][2]=0.08;
    rdcutsvalmine[7][2]=-0.00018;
    rdcutsvalmine[8][2]=0.90;
    rdcutsvalmine[9][2]=0.3;
    rdcutsvalmine[10][2]=0.1;
    rdcutsvalmine[11][2]=0.05;
    rdcutsvalmine[12][2]=100.;
    rdcutsvalmine[13][2]=0.5;

    rdcutsvalmine[0][3]=0.7;
    rdcutsvalmine[1][3]=0.05;
    rdcutsvalmine[2][3]=0.8;
    rdcutsvalmine[3][3]=1.;
    rdcutsvalmine[4][3]=1.;
    rdcutsvalmine[5][3]=0.042;
    rdcutsvalmine[6][3]=0.056;
    rdcutsvalmine[7][3]=-0.000065;
    rdcutsvalmine[8][3]=0.9;
    rdcutsvalmine[9][3]=0.3;
    rdcutsvalmine[10][3]=0.1;
    rdcutsvalmine[11][3]=0.05;
    rdcutsvalmine[12][3]=100.;
    rdcutsvalmine[13][3]=0.5;

    rdcutsvalmine[0][4]=0.7;
    rdcutsvalmine[1][4]=0.08;
    rdcutsvalmine[2][4]=0.9;
    rdcutsvalmine[3][4]=1.2;
    rdcutsvalmine[4][4]=1.2;
    rdcutsvalmine[5][4]=0.07;
    rdcutsvalmine[6][4]=0.07;
    rdcutsvalmine[7][4]=0.0001;
    rdcutsvalmine[8][4]=0.9;
    rdcutsvalmine[9][4]=0.3;
    rdcutsvalmine[10][4]=0.1;
    rdcutsvalmine[11][4]=0.05;
    rdcutsvalmine[12][4]=100.;
    rdcutsvalmine[13][4]=0.5;

    rdcutsvalmine[0][5]=0.7;
    rdcutsvalmine[1][5]=0.1;
    rdcutsvalmine[2][5]=1.0;
    rdcutsvalmine[3][5]=1.;
    rdcutsvalmine[4][5]=1.;
    rdcutsvalmine[5][5]=0.08;
    rdcutsvalmine[6][5]=0.08;
    rdcutsvalmine[7][5]=0.0004;
    rdcutsvalmine[8][5]=0.9;
    rdcutsvalmine[9][5]=0.3;
    rdcutsvalmine[10][5]=0.1;
    rdcutsvalmine[11][5]=0.05;
    rdcutsvalmine[12][5]=100000.;
    rdcutsvalmine[13][5]=0.5;

    rdcutsvalmine[0][6]=0.7;
    rdcutsvalmine[1][6]=0.1;
    rdcutsvalmine[2][6]=1.0;
    rdcutsvalmine[3][6]=1.;
    rdcutsvalmine[4][6]=1.;
    rdcutsvalmine[5][6]=0.1;
    rdcutsvalmine[6][6]=0.1;
    rdcutsvalmine[7][6]=0.0005;
    rdcutsvalmine[8][6]=0.9;
    rdcutsvalmine[9][6]=0.3;
    rdcutsvalmine[10][6]=0.1;
    rdcutsvalmine[11][6]=0.05;
    rdcutsvalmine[12][6]=100.;
    rdcutsvalmine[13][6]=0.5;

    rdcutsvalmine[0][7]=0.7;
    rdcutsvalmine[1][7]=0.1;
    rdcutsvalmine[2][7]=1.0;
    rdcutsvalmine[3][7]=1.;
    rdcutsvalmine[4][7]=1.;
    rdcutsvalmine[5][7]=0.1;
    rdcutsvalmine[6][7]=0.1;
    rdcutsvalmine[7][7]=0.001;
    rdcutsvalmine[8][7]=0.9;
    rdcutsvalmine[9][7]=0.3;
    rdcutsvalmine[10][7]=0.1;
    rdcutsvalmine[11][7]=0.05;
    rdcutsvalmine[12][7]=100.;
    rdcutsvalmine[13][7]=0.5;

  }else{ // HD cuts - To be setted

    rdcutsvalmine[0][0]=0.450;
    rdcutsvalmine[1][0]=0.02;
    rdcutsvalmine[2][0]=0.7;
    rdcutsvalmine[3][0]=0.8;
    rdcutsvalmine[4][0]=0.8;
    rdcutsvalmine[5][0]=0.1;
    rdcutsvalmine[6][0]=0.1;
    rdcutsvalmine[7][0]=0.000002;
    rdcutsvalmine[8][0]=0.9;
    rdcutsvalmine[9][0]=200.;
    rdcutsvalmine[10][0]=200.;
    rdcutsvalmine[11][0]=0.021;
    rdcutsvalmine[12][0]=100.;
    rdcutsvalmine[13][0]=0.5;

    rdcutsvalmine[0][1]=0.45;
    rdcutsvalmine[1][1]=0.03;
    rdcutsvalmine[2][1]=0.7;
    rdcutsvalmine[3][1]=0.8;
    rdcutsvalmine[4][1]=0.8;
    rdcutsvalmine[5][1]=0.1;
    rdcutsvalmine[6][1]=0.1;
    rdcutsvalmine[7][1]=-0.00002;
    rdcutsvalmine[8][1]=0.9;
    rdcutsvalmine[9][1]=200.;
    rdcutsvalmine[10][1]=200.;
    rdcutsvalmine[11][1]=0.021;
    rdcutsvalmine[12][1]=100.;
    rdcutsvalmine[13][1]=0.5;

    rdcutsvalmine[0][2]=0.450;
    rdcutsvalmine[1][2]=0.03;
    rdcutsvalmine[2][2]=0.7;
    rdcutsvalmine[3][2]=0.8;
    rdcutsvalmine[4][2]=0.8;
    rdcutsvalmine[5][2]=0.1;
    rdcutsvalmine[6][2]=0.1;
    rdcutsvalmine[7][2]=-0.00002;
    rdcutsvalmine[8][2]=0.9;
    rdcutsvalmine[9][2]=200.;
    rdcutsvalmine[10][2]=200.;
    rdcutsvalmine[11][2]=0.021;
    rdcutsvalmine[12][2]=100.;
    rdcutsvalmine[13][2]=0.5;

    rdcutsvalmine[0][3]=0.45;
    rdcutsvalmine[1][3]=0.03;
    rdcutsvalmine[2][3]=0.7;
    rdcutsvalmine[3][3]=0.9;
    rdcutsvalmine[4][3]=0.9;
    rdcutsvalmine[5][3]=0.1;
    rdcutsvalmine[6][3]=0.1;
    rdcutsvalmine[7][3]=0.000002;
    rdcutsvalmine[8][3]=0.8;
    rdcutsvalmine[9][3]=200.;
    rdcutsvalmine[10][3]=200.;
    rdcutsvalmine[11][3]=0.021;
    rdcutsvalmine[12][3]=100.;
    rdcutsvalmine[13][3]=0.5;

    rdcutsvalmine[0][4]=0.45;
    rdcutsvalmine[1][4]=0.03;
    rdcutsvalmine[2][4]=0.7;
    rdcutsvalmine[3][4]=1.;
    rdcutsvalmine[4][4]=1.;
    rdcutsvalmine[5][4]=0.1;
    rdcutsvalmine[6][4]=0.1;
    rdcutsvalmine[7][4]=0.000002;
    rdcutsvalmine[8][4]=0.8;
    rdcutsvalmine[9][4]=200.;
    rdcutsvalmine[10][4]=200.;
    rdcutsvalmine[11][4]=0.021;
    rdcutsvalmine[12][4]=100.;
    rdcutsvalmine[13][4]=0.5;

    rdcutsvalmine[0][5]=0.45;
    rdcutsvalmine[1][5]=0.03;
    rdcutsvalmine[2][5]=0.7;
    rdcutsvalmine[3][5]=1.;
    rdcutsvalmine[4][5]=1.;
    rdcutsvalmine[5][5]=0.1;
    rdcutsvalmine[6][5]=0.1;
    rdcutsvalmine[7][5]=0.000002;
    rdcutsvalmine[8][5]=0.8;
    rdcutsvalmine[9][5]=200.;
    rdcutsvalmine[10][5]=200.;
    rdcutsvalmine[11][5]=0.021;
    rdcutsvalmine[12][5]=100.;
    rdcutsvalmine[13][5]=0.5;

    rdcutsvalmine[0][6]=0.45;
    rdcutsvalmine[1][6]=0.03;
    rdcutsvalmine[2][6]=0.7;
    rdcutsvalmine[3][6]=1.;
    rdcutsvalmine[4][6]=1.;
    rdcutsvalmine[5][6]=0.1;
    rdcutsvalmine[6][6]=0.1;
    rdcutsvalmine[7][6]=0.000002;
    rdcutsvalmine[8][6]=0.8;
    rdcutsvalmine[9][6]=200.;
    rdcutsvalmine[10][6]=200.;
    rdcutsvalmine[11][6]=0.021;
    rdcutsvalmine[12][6]=100.;
    rdcutsvalmine[13][6]=0.5;

    rdcutsvalmine[0][7]=0.45;
    rdcutsvalmine[1][7]=0.03;
    rdcutsvalmine[2][7]=0.7;
    rdcutsvalmine[3][7]=1.;
    rdcutsvalmine[4][7]=1.;
    rdcutsvalmine[5][7]=0.1;
    rdcutsvalmine[6][7]=0.1;
    rdcutsvalmine[7][7]=0.000002;
    rdcutsvalmine[8][7]=0.8;
    rdcutsvalmine[9][7]=200.;
    rdcutsvalmine[10][7]=200.;
    rdcutsvalmine[11][7]=0.021;
    rdcutsvalmine[12][7]=100.;
    rdcutsvalmine[13][7]=0.5;

  }

  RDHFDStartoKpipi->SetCuts(nvars,nptbins,rdcutsvalmine);
  RDHFDStartoKpipi->PrintAll();

  //CREATE THE TASK
  printf("CREATE TASK\n");
  // create the task
  AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi);
  task->SetAnalysisType(anaType);
  task->SetNSigmasPID(numberOfSigmasPID);
  task->SetMC(theMCon);
  task->SetPID(usePID);
  task->SetDebugLevel(0);

  mgr->AddTask(task);

  // Create and connect containers for input/output

  TString outputfile = AliAnalysisManager::GetCommonFileName();
  if (anaType == 0) outputfile += ":PWG3_D2H_DStarSpectraHD";
  if (anaType == 1) outputfile += ":PWG3_D2H_DStarSpectraUU";

  // ------ input data ------

  //AliAnalysisDataContainer *cinput0  = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *cinput0  =  mgr->CreateContainer("indstar",TChain::Class(),
							     AliAnalysisManager::kInputContainer);
  // ----- output data -----

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer("DStarSpectrum",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer("DStarAll",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer("DStarPID3",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar4 = mgr->CreateContainer("DStarPID2",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar5 = mgr->CreateContainer("DStarPID1",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar6 = mgr->CreateContainer("cuts",AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts

  mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());

  mgr->ConnectOutput(task,1,coutput1);
  mgr->ConnectOutput(task,2,coutputDStar1);
  mgr->ConnectOutput(task,3,coutputDStar2);
  mgr->ConnectOutput(task,4,coutputDStar3);
  mgr->ConnectOutput(task,5,coutputDStar4);
  mgr->ConnectOutput(task,6,coutputDStar5);
  mgr->ConnectOutput(task,7,coutputDStar6);

  return task;
}

<commit_msg>update (Alessandro)<commit_after>//if like define a different number of signal for TPC PID
//by default the task is anyway computing 1, 2 and 3 sigmas
const Int_t    numberOfSigmasPID  = 3;
// option to switch on and off the TPC PID.
const Bool_t usePID = kTRUE;
// analysis type... TO BE REMOVED!!!
const Bool_t anaType   = 1;//0 HD; 1 UU;
//----------------------------------------------------

AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Bool_t theMCon=kFALSE)
{

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskDStarSpectra", "No analysis manager to connect to.");
    return NULL;
  }

  // cuts are stored in a TFile generated by makeTFile4CutsDStartoKpipi.C in ./macros/
  // set there the cuts!!!!!
  TFile* filecuts=new TFile("DStartoKpipiCuts.root");
  if(!filecuts->IsOpen()){
    cout<<"Input file not found: exit"<<endl;
    return;
  }

  AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi();
  RDHFDStartoKpipi = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts");
  RDHFDStartoKpipi->SetName("DStartoKpipiCuts");

  // mm let's see if everything is ok
  if(!RDHFDStartoKpipi){
    cout<<"Specific AliRDHFCuts not found"<<endl;
    return;
  }

  //CREATE THE TASK
  printf("CREATE TASK\n");
  // create the task
  AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi);
  task->SetAnalysisType(anaType);
  task->SetNSigmasPID(numberOfSigmasPID);
  task->SetMC(theMCon);
  task->SetPID(usePID);
  task->SetDebugLevel(0);

  mgr->AddTask(task);

  // Create and connect containers for input/output

  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG3_D2H_DStarSpectra";

  // ------ input data ------

  //AliAnalysisDataContainer *cinput0  = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *cinput0  =  mgr->CreateContainer("indstar",TChain::Class(),
							     AliAnalysisManager::kInputContainer);
  // ----- output data -----

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer("DStarSpectrum",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer("DStarAll",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer("DStarPID3",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar4 = mgr->CreateContainer("DStarPID2",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputDStar5 = mgr->CreateContainer("DStarPID1",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data());
  AliAnalysisDataContainer *coutputDStar6 = mgr->CreateContainer("cuts",AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts

  mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());

  mgr->ConnectOutput(task,1,coutput1);
  mgr->ConnectOutput(task,2,coutputDStar1);
  mgr->ConnectOutput(task,3,coutputDStar2);
  mgr->ConnectOutput(task,4,coutputDStar3);
  mgr->ConnectOutput(task,5,coutputDStar4);
  mgr->ConnectOutput(task,6,coutputDStar5);
  mgr->ConnectOutput(task,7,coutputDStar6);

  return task;
}

<|endoftext|>


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

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/gui/Button.hpp"

namespace nom {

Button::Button  (
                  UIWidget* parent,
                  int64 id,
                  const Point2i& pos,
                  const Size2i& size
                ) :
  UIWidget( parent, id, pos, size )   // Base class
{
  // NOM_LOG_TRACE( NOM );

  // Use explicitly set coordinates as the widget's minimum size requirements.
  //
  // Note that if size is invalid (NULL), the minimum size returned will be
  // Size2i(0,0)
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  this->set_minimum_size( size );

  // Set the size policy of the widget to use explicitly set size dimensions.
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  if( size != Size2i::null )
  {
    this->set_size_policy( UILayoutPolicy::Policy::Minimum, UILayoutPolicy::Policy::Fixed );
  }

  // Set the size policy of the widget to use dimensions that are calculated
  // with respect to the text label string, font, point size, etc.
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  else
  {
    this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed );
  }

  // Widget's focus type.
  this->set_focus_policy( FocusPolicy::StrongFocus );

  // Auto-generate a name tag for our widget.
  this->set_name( "button" );

  // Default state
  this->set_button_state( Button::State::Default );

  // Initialize the default event listeners for the widget.
  NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed );

  NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update );
}

// Button::Button( UIWidget* parent ) :
//   UIWidget( parent, parent->id(), parent->position(), parent->size() ) // Base class
// {
//   // NOM_LOG_TRACE( NOM );

//   // Use explicitly set coordinates for our minimum widget size
//   this->set_minimum_size( parent->size() );

//   this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed );

//   // Auto-generate a name tag for our widget.
//   this->set_name( "button" );

//   // Default state
//   this->set_button_state( Button::State::Default );

//   // Initialize the default event listeners for the widget.
//   NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed );

//   NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update );

//   // Widget's focus type.
//   this->set_focus_policy( FocusPolicy::StrongFocus );
// }

Button::~Button( void )
{
  // NOM_LOG_TRACE( NOM );
}

const Size2i Button::minimum_size( void ) const
{
  // Our preferred size will always be two times what is actually required
  return Size2i( this->size_hint().w / 2, this->size_hint().h / 2 );
}

const Size2i Button::size_hint( void ) const
{
  // Maximum text width requirements for the label (with respect to font).
  //
  // We dedicate two times the width required in order to: a) help account for
  // dynamic length text labels that are set after initialization of the
  // layout -- the layout manager *should* catch this early enough, but just
  // in case; b) Simple, minimal approach to getting the look of the button
  // to *feel* right in terms of size dimensions (in comparison to standard GUI
  // elements).
  int total_text_width = this->label_.width() * 2;

  // Total text height requirements for the label (with respect to font).
  //
  // Note that this variable will be scaled up by a factor of two as well; see
  // the above note regarding total_text_width for my reasoning logic on
  // requesting this.
  sint total_text_height = 0;

  uint point_size = nom::DEFAULT_FONT_SIZE;

  FontMetrics face = this->label_.font()->metrics();

  // NOM_DUMP( this->name() );
  // NOM_DUMP( face.name );
  // NOM_DUMP( this->label_->text() );

  // Use the point size of the widget's style, if one has been set:
  if( this->style() != nullptr )
  {
    point_size = this->style()->font_size();
  }

  total_text_height += this->label_.font()->newline( point_size ) * 2;

  return Size2i( total_text_width, total_text_height );

  // Err
  return Size2i( 0, 0 );
}

ObjectTypeInfo Button::type( void ) const
{
  return NOM_OBJECT_TYPE_INFO( self_type );
}

void Button::draw( RenderTarget& target ) const
{
  // UIWidget::draw( target );

  if( this->label_.valid() == true )
  {
    this->label_.draw( target );
  }
}

Button::State Button::button_state( void ) const
{
  return this->button_state_;
}

const std::string& Button::label_text( void ) const
{
  return this->label_.text();
}

void Button::set_label( const std::string& text )
{
  this->text_ = text;

  NOM_ASSERT( this->style() != nullptr );

  this->label_.set_font( this->font() );
  this->label_.set_text_size( this->style()->font_size() );
  this->label_.set_text( this->text_ );
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );
  this->label_.set_alignment( this->style()->text_alignment() );
  this->label_.set_style( this->style()->font_style() );
  this->label_.set_color( this->style()->font_color() );

  this->update_bounds();
  this->update();
}

void Button::set_button_state( Button::State state )
{
  this->button_state_ = state;
}

// Protected scope

void Button::update_bounds( void )
{
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );
}

void Button::on_update( const UIWidgetEvent& ev )
{
  // NOM_LOG_TRACE( NOM );

  Event evt = ev.event();

  if( evt.type != UIEvent::ON_WIDGET_UPDATE )
  {
    return;
  }

  this->label_.set_font( this->font() );

  this->update_bounds();
  this->update();
}

void Button::on_size_changed( const UIWidgetEvent& ev )
{
  Event evt = ev.event();

  if( evt.type != SDL_WINDOWEVENT_SIZE_CHANGED )
  {
    return;
  }

  if( this->decorator() )
  {
    // Update the attached decorator (border & possibly a background)
    this->decorator()->set_bounds( ev.resized_bounds_ );
  }

  // Update ourselves with the new rendering coordinates
  this->set_bounds( ev.resized_bounds_ );

  // Updating the text label's coordinates and dimensions also ensures that its
  // alignment is recalculated.
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );

  this->update_bounds();

  this->update();
}

void Button::on_mouse_down( const UIWidgetEvent& ev )
{
  this->set_button_state( Button::State::Pressed );

  UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt );
}

void Button::on_mouse_up( const UIWidgetEvent& ev )
{
  this->set_button_state( Button::State::Default );

  UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt );
}

void Button::on_mouse_enter( const UIWidgetEvent& ev )
{
  // this->set_button_state( Button::State::Pressed );

  // Send the button state and text string of the set label at the time of
  // the event.
  UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_ENTER, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_MOTION_ENTER, evt );
}

void Button::on_mouse_leave( const UIWidgetEvent& ev )
{
  // this->set_button_state( Button::State::Default );

  // Send the button state and text string of the set label at the time of
  // the event.
  UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_LEAVE, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_MOTION_LEAVE, evt );
}

// Private scope

void Button::update( void )
{
  // Nothing to do
}

} // namespace nom
<commit_msg>Fix bug in Button::on_mouse_up (wrong event emission)<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/gui/Button.hpp"

namespace nom {

Button::Button  (
                  UIWidget* parent,
                  int64 id,
                  const Point2i& pos,
                  const Size2i& size
                ) :
  UIWidget( parent, id, pos, size )   // Base class
{
  // NOM_LOG_TRACE( NOM );

  // Use explicitly set coordinates as the widget's minimum size requirements.
  //
  // Note that if size is invalid (NULL), the minimum size returned will be
  // Size2i(0,0)
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  this->set_minimum_size( size );

  // Set the size policy of the widget to use explicitly set size dimensions.
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  if( size != Size2i::null )
  {
    this->set_size_policy( UILayoutPolicy::Policy::Minimum, UILayoutPolicy::Policy::Fixed );
  }

  // Set the size policy of the widget to use dimensions that are calculated
  // with respect to the text label string, font, point size, etc.
  //
  // Note that the size policy is only used when the widget is used inside a
  // layout.
  else
  {
    this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed );
  }

  // Widget's focus type.
  this->set_focus_policy( FocusPolicy::StrongFocus );

  // Auto-generate a name tag for our widget.
  this->set_name( "button" );

  // Default state
  this->set_button_state( Button::State::Default );

  // Initialize the default event listeners for the widget.
  NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed );

  NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update );
}

// Button::Button( UIWidget* parent ) :
//   UIWidget( parent, parent->id(), parent->position(), parent->size() ) // Base class
// {
//   // NOM_LOG_TRACE( NOM );

//   // Use explicitly set coordinates for our minimum widget size
//   this->set_minimum_size( parent->size() );

//   this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed );

//   // Auto-generate a name tag for our widget.
//   this->set_name( "button" );

//   // Default state
//   this->set_button_state( Button::State::Default );

//   // Initialize the default event listeners for the widget.
//   NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed );

//   NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update );

//   // Widget's focus type.
//   this->set_focus_policy( FocusPolicy::StrongFocus );
// }

Button::~Button( void )
{
  // NOM_LOG_TRACE( NOM );
}

const Size2i Button::minimum_size( void ) const
{
  // Our preferred size will always be two times what is actually required
  return Size2i( this->size_hint().w / 2, this->size_hint().h / 2 );
}

const Size2i Button::size_hint( void ) const
{
  // Maximum text width requirements for the label (with respect to font).
  //
  // We dedicate two times the width required in order to: a) help account for
  // dynamic length text labels that are set after initialization of the
  // layout -- the layout manager *should* catch this early enough, but just
  // in case; b) Simple, minimal approach to getting the look of the button
  // to *feel* right in terms of size dimensions (in comparison to standard GUI
  // elements).
  int total_text_width = this->label_.width() * 2;

  // Total text height requirements for the label (with respect to font).
  //
  // Note that this variable will be scaled up by a factor of two as well; see
  // the above note regarding total_text_width for my reasoning logic on
  // requesting this.
  sint total_text_height = 0;

  uint point_size = nom::DEFAULT_FONT_SIZE;

  FontMetrics face = this->label_.font()->metrics();

  // NOM_DUMP( this->name() );
  // NOM_DUMP( face.name );
  // NOM_DUMP( this->label_->text() );

  // Use the point size of the widget's style, if one has been set:
  if( this->style() != nullptr )
  {
    point_size = this->style()->font_size();
  }

  total_text_height += this->label_.font()->newline( point_size ) * 2;

  return Size2i( total_text_width, total_text_height );

  // Err
  return Size2i( 0, 0 );
}

ObjectTypeInfo Button::type( void ) const
{
  return NOM_OBJECT_TYPE_INFO( self_type );
}

void Button::draw( RenderTarget& target ) const
{
  // UIWidget::draw( target );

  if( this->label_.valid() == true )
  {
    this->label_.draw( target );
  }
}

Button::State Button::button_state( void ) const
{
  return this->button_state_;
}

const std::string& Button::label_text( void ) const
{
  return this->label_.text();
}

void Button::set_label( const std::string& text )
{
  this->text_ = text;

  NOM_ASSERT( this->style() != nullptr );

  this->label_.set_font( this->font() );
  this->label_.set_text_size( this->style()->font_size() );
  this->label_.set_text( this->text_ );
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );
  this->label_.set_alignment( this->style()->text_alignment() );
  this->label_.set_style( this->style()->font_style() );
  this->label_.set_color( this->style()->font_color() );

  this->update_bounds();
  this->update();
}

void Button::set_button_state( Button::State state )
{
  this->button_state_ = state;
}

// Protected scope

void Button::update_bounds( void )
{
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );
}

void Button::on_update( const UIWidgetEvent& ev )
{
  // NOM_LOG_TRACE( NOM );

  Event evt = ev.event();

  if( evt.type != UIEvent::ON_WIDGET_UPDATE )
  {
    return;
  }

  this->label_.set_font( this->font() );

  this->update_bounds();
  this->update();
}

void Button::on_size_changed( const UIWidgetEvent& ev )
{
  Event evt = ev.event();

  if( evt.type != SDL_WINDOWEVENT_SIZE_CHANGED )
  {
    return;
  }

  if( this->decorator() )
  {
    // Update the attached decorator (border & possibly a background)
    this->decorator()->set_bounds( ev.resized_bounds_ );
  }

  // Update ourselves with the new rendering coordinates
  this->set_bounds( ev.resized_bounds_ );

  // Updating the text label's coordinates and dimensions also ensures that its
  // alignment is recalculated.
  this->label_.set_position( this->position() );
  this->label_.set_size( this->size() );

  this->update_bounds();

  this->update();
}

void Button::on_mouse_down( const UIWidgetEvent& ev )
{
  this->set_button_state( Button::State::Pressed );

  UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt );
}

void Button::on_mouse_up( const UIWidgetEvent& ev )
{
  this->set_button_state( Button::State::Default );

  UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_UP, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_UP, evt );
}

void Button::on_mouse_enter( const UIWidgetEvent& ev )
{
  // this->set_button_state( Button::State::Pressed );

  // Send the button state and text string of the set label at the time of
  // the event.
  UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_ENTER, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_MOTION_ENTER, evt );
}

void Button::on_mouse_leave( const UIWidgetEvent& ev )
{
  // this->set_button_state( Button::State::Default );

  // Send the button state and text string of the set label at the time of
  // the event.
  UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() );

  // Send the UI event object to the registered private event callback.
  this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_LEAVE, evt );

  // Send the UI event object to the registered public event callback.
  this->dispatcher()->emit( UIEvent::MOUSE_MOTION_LEAVE, evt );
}

// Private scope

void Button::update( void )
{
  // Nothing to do
}

} // namespace nom
<|endoftext|>


<commit_before><commit_msg>refactor(Scripts/Event): convert pilgrims_bounty into new system (#9608)<commit_after><|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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
//
// 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 <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <limits>
#include <cctype>
#include <CImg.h>

#include <ArgumentList.hpp>
#include <ColorMap.hpp>
#include <utils.hpp>

int main(int argc, char * argv[]) {
  bool gray = false;
  unsigned int nrDMs = 0;
  unsigned int nrPeriods = 0;
  float minSNR = std::numeric_limits< float >::max();
  float maxSNR = std::numeric_limits< float >::min();
  float snrSpaceDim = 0.0f;
  float * snrSpace = 0;
  std::string outFilename;
  std::ifstream searchFile;

  isa::utils::ArgumentList args(argc, argv);
  try {
    gray = args.getSwitch("-gray");
    outFilename = args.getSwitchArgument< std::string >("-output");
    nrDMs = args.getSwitchArgument< unsigned int >("-dms");
    nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  snrSpace = new float [nrDMs * nrPeriods];

  try {
    while ( true ) {
      searchFile.open(args.getFirst< std::string >());

      while ( ! searchFile.eof() ) {
        std::string temp;
        unsigned int splitPoint = 0;
        unsigned int DM = 0;
        unsigned int period = 0;
        float snr = 0.0f;

        std::getline(searchFile, temp);
        if ( ! std::isdigit(temp[0]) ) {
          continue;
        }
        splitPoint = temp.find(" ");
        period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        snr = isa::utils::castToType< std::string, float >(temp);

        if ( snr > maxSNR ) {
          maxSNR = snr;
        }
        if ( snr < minSNR ) {
          minSNR = snr;
        }

        snrSpace[(period * nrDMs) + DM] = snr;
      }
      searchFile.close();
    }
  } catch ( isa::utils::EmptyCommandLine & err ) {
    snrSpaceDim = maxSNR - minSNR;
  }

  cimg_library::CImg< unsigned char > searchImage;
  AstroData::Color * colorMap;
  if ( gray ) {
    searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1);
  } else {
    searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3);
    colorMap = AstroData::getColorMap();
  }
  for ( unsigned int period = 0; period < nrPeriods; period++ ) {
    for ( unsigned int DM = 0; DM < nrDMs; DM++ ) {
      float snr = snrSpace[(period * nrDMs) + DM];
      if ( gray ) {
        searchImage(DM, (nrPeriods - 1) - period, 0, 0) = static_cast< unsigned char >(((snr - minSNR) * 256.0) / snrSpaceDim);
      } else {
        searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR();
        searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG();
        searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB();
      }
    }
  }
  searchImage.save(outFilename.c_str());

  delete [] snrSpace;
  return 0;
}

<commit_msg>Small fix for the gray values.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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
//
// 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 <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <limits>
#include <cctype>
#include <CImg.h>

#include <ArgumentList.hpp>
#include <ColorMap.hpp>
#include <utils.hpp>

int main(int argc, char * argv[]) {
  bool gray = false;
  unsigned int nrDMs = 0;
  unsigned int nrPeriods = 0;
  float minSNR = std::numeric_limits< float >::max();
  float maxSNR = std::numeric_limits< float >::min();
  float snrSpaceDim = 0.0f;
  float * snrSpace = 0;
  std::string outFilename;
  std::ifstream searchFile;

  isa::utils::ArgumentList args(argc, argv);
  try {
    gray = args.getSwitch("-gray");
    outFilename = args.getSwitchArgument< std::string >("-output");
    nrDMs = args.getSwitchArgument< unsigned int >("-dms");
    nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  snrSpace = new float [nrDMs * nrPeriods];

  try {
    while ( true ) {
      searchFile.open(args.getFirst< std::string >());

      while ( ! searchFile.eof() ) {
        std::string temp;
        unsigned int splitPoint = 0;
        unsigned int DM = 0;
        unsigned int period = 0;
        float snr = 0.0f;

        std::getline(searchFile, temp);
        if ( ! std::isdigit(temp[0]) ) {
          continue;
        }
        splitPoint = temp.find(" ");
        period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        snr = isa::utils::castToType< std::string, float >(temp);

        if ( snr > maxSNR ) {
          maxSNR = snr;
        }
        if ( snr < minSNR ) {
          minSNR = snr;
        }

        snrSpace[(period * nrDMs) + DM] = snr;
      }
      searchFile.close();
    }
  } catch ( isa::utils::EmptyCommandLine & err ) {
    snrSpaceDim = maxSNR - minSNR;
  }

  cimg_library::CImg< unsigned char > searchImage;
  AstroData::Color * colorMap;
  if ( gray ) {
    searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1);
  } else {
    searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3);
    colorMap = AstroData::getColorMap();
  }
  for ( unsigned int period = 0; period < nrPeriods; period++ ) {
    for ( unsigned int DM = 0; DM < nrDMs; DM++ ) {
      float snr = snrSpace[(period * nrDMs) + DM];
      if ( gray ) {
        searchImage(DM, (nrPeriods - 1) - period, 0, 0) = static_cast< unsigned char >(((snr - minSNR) * 255.0) / snrSpaceDim);
      } else {
        searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR();
        searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG();
        searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB();
      }
    }
  }
  searchImage.save(outFilename.c_str());

  delete [] snrSpace;
  return 0;
}

<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                   OpenSim:  RegisterTypes_osimCommon.cpp                   *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Frank C. Anderson                                               *
 *                                                                            *
 * 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.         *
 *                                                                            *
 * 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 "Object.h"
#include "Component.h"
#include "RegisterTypes_osimCommon.h"
#include "FunctionSet.h"
#include "GCVSplineSet.h"
#include "ScaleSet.h"
#include "GCVSpline.h"

#include "Scale.h"
#include "SimmSpline.h"
#include "Constant.h"
#include "Sine.h"
#include "StepFunction.h"
#include "LinearFunction.h"
#include "PiecewiseLinearFunction.h"
#include "PiecewiseConstantFunction.h"
#include "MultiplierFunction.h"
#include "PolynomialFunction.h"

#include "ObjectGroup.h"

#include "Reporter.h"

#include <string>
#include <iostream>
#include <exception>

using namespace OpenSim;
using namespace std;

//_____________________________________________________________________________
/**
 * The purpose of this routine is to register all class types exported by
 * the osimCommon library.
 */
OSIMCOMMON_API void RegisterTypes_osimCommon()
{
  try {

    Object::registerType(Connector<Component>());

    // Register commonly used Inputs for de/serialization
    Object::registerType(Input<double>());
    Object::registerType(Input<SimTK::Vec3>());
    Object::registerType(Input<SimTK::Vector>());
    Object::registerType(Input<SimTK::SpatialVec>());

    //SimTK::Xml::setXmlCondenseWhiteSpace(false);
    Object::registerType( FunctionSet() );
    Object::registerType( GCVSplineSet() );
    Object::registerType( ScaleSet() );

    Object::registerType( GCVSpline() );

    Object::registerType( Scale() );
    Object::registerType( SimmSpline() );
    Object::registerType( Constant() );
    Object::registerType( Sine() );
    Object::registerType( StepFunction() );
    Object::registerType( LinearFunction() );
    Object::registerType( PiecewiseLinearFunction() );
    Object::registerType( PiecewiseConstantFunction() );
    Object::registerType( MultiplierFunction() );
    Object::registerType(PolynomialFunction());
    Object::registerType( ObjectGroup() );

    Object::registerType( TableReporter() );
    Object::registerType( TableReporterVec3() );
    Object::registerType( TableReporterVector() );
    Object::registerType( ConsoleReporter() );
    Object::registerType( ConsoleReporterVec3() );

    // TODO: temporarily map old NaturalCubicSpline (which wasn't a
    // natural cubic spline) to renamed SimmSpline class. Later we
    // will replace this with an actual natural cubic spline.
    Object::renameType("NaturalCubicSpline", "SimmSpline");
    // To support older type name of "natCubicSpline"
    Object::renameType("natCubicSpline", "SimmSpline");

  } catch (const std::exception& e) {
    std::cerr
        << "ERROR during osimCommon Object registration:\n"
        << e.what() << "\n";
  }
}

<commit_msg>Register TableSource and TableSourceVec3.<commit_after>/* -------------------------------------------------------------------------- *
 *                   OpenSim:  RegisterTypes_osimCommon.cpp                   *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Frank C. Anderson                                               *
 *                                                                            *
 * 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.         *
 *                                                                            *
 * 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 "Object.h"
#include "Component.h"
#include "RegisterTypes_osimCommon.h"
#include "FunctionSet.h"
#include "GCVSplineSet.h"
#include "ScaleSet.h"
#include "GCVSpline.h"

#include "Scale.h"
#include "SimmSpline.h"
#include "Constant.h"
#include "Sine.h"
#include "StepFunction.h"
#include "LinearFunction.h"
#include "PiecewiseLinearFunction.h"
#include "PiecewiseConstantFunction.h"
#include "MultiplierFunction.h"
#include "PolynomialFunction.h"

#include "ObjectGroup.h"

#include "Reporter.h"
#include "TableSource.h"

#include <string>
#include <iostream>
#include <exception>

using namespace OpenSim;
using namespace std;

//_____________________________________________________________________________
/**
 * The purpose of this routine is to register all class types exported by
 * the osimCommon library.
 */
OSIMCOMMON_API void RegisterTypes_osimCommon()
{
  try {

    Object::registerType(Connector<Component>());

    // Register commonly used Inputs for de/serialization
    Object::registerType(Input<double>());
    Object::registerType(Input<SimTK::Vec3>());
    Object::registerType(Input<SimTK::Vector>());
    Object::registerType(Input<SimTK::SpatialVec>());

    //SimTK::Xml::setXmlCondenseWhiteSpace(false);
    Object::registerType( FunctionSet() );
    Object::registerType( GCVSplineSet() );
    Object::registerType( ScaleSet() );

    Object::registerType( GCVSpline() );

    Object::registerType( Scale() );
    Object::registerType( SimmSpline() );
    Object::registerType( Constant() );
    Object::registerType( Sine() );
    Object::registerType( StepFunction() );
    Object::registerType( LinearFunction() );
    Object::registerType( PiecewiseLinearFunction() );
    Object::registerType( PiecewiseConstantFunction() );
    Object::registerType( MultiplierFunction() );
    Object::registerType(PolynomialFunction());
    Object::registerType( ObjectGroup() );

    Object::registerType( TableSource() );
    Object::registerType( TableSourceVec3() );
    Object::registerType( TableReporter() );
    Object::registerType( TableReporterVec3() );
    Object::registerType( TableReporterVector() );
    Object::registerType( ConsoleReporter() );
    Object::registerType( ConsoleReporterVec3() );

    // TODO: temporarily map old NaturalCubicSpline (which wasn't a
    // natural cubic spline) to renamed SimmSpline class. Later we
    // will replace this with an actual natural cubic spline.
    Object::renameType("NaturalCubicSpline", "SimmSpline");
    // To support older type name of "natCubicSpline"
    Object::renameType("natCubicSpline", "SimmSpline");

  } catch (const std::exception& e) {
    std::cerr
        << "ERROR during osimCommon Object registration:\n"
        << e.what() << "\n";
  }
}

<|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include <pistache/optional.h>

using Pistache::Optional;

TEST(optional, constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());

    EXPECT_TRUE(value.get());
}

TEST(optional, copy_constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> copy_constructed(value);
    ASSERT_FALSE(copy_constructed.isEmpty());
    EXPECT_TRUE(copy_constructed.get());
}

TEST(optional, assignment_operator) {
    Optional<bool> value;
    EXPECT_TRUE(value.isEmpty());

    value = Pistache::Some(true);
    ASSERT_FALSE(value.isEmpty());

    EXPECT_TRUE(value.get());
}

TEST(optional, copy_assignment_operator) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());

    Optional<bool> other;
    EXPECT_TRUE(other.isEmpty());

    other = value;
    ASSERT_FALSE(other.isEmpty());

    EXPECT_TRUE(other.get());
}

TEST(optional, move_constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> value_from_move(std::move(value));
    ASSERT_FALSE(value_from_move.isEmpty());
    EXPECT_TRUE(value_from_move.get());
}

TEST(optional, move_assignment_operator) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> move_assigned = std::move(value);
    ASSERT_FALSE(move_assigned.isEmpty());
    EXPECT_TRUE(move_assigned.get());
}

TEST(optional, constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());
}

TEST(optional, copy_constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> copy_constructed(value);
    EXPECT_TRUE(value.isEmpty());
}

TEST(optional, assignment_operator_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> assigned = Pistache::None();
    EXPECT_TRUE(assigned.isEmpty());
}

TEST(optional, move_constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> move_constructed(std::move(value));
    EXPECT_TRUE(move_constructed.isEmpty());
}

TEST(optional, move_assignment_operator_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> move_assigned(std::move(value));
    EXPECT_TRUE(move_assigned.isEmpty());
}
<commit_msg>explicitly state "copy" for tests of the copy assignment operator<commit_after>#include "gtest/gtest.h"

#include <pistache/optional.h>

using Pistache::Optional;

TEST(optional, constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());

    EXPECT_TRUE(value.get());
}

TEST(optional, copy_constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> copy_constructed(value);
    ASSERT_FALSE(copy_constructed.isEmpty());
    EXPECT_TRUE(copy_constructed.get());
}

TEST(optional, copy_assignment_operator_for_convertible_type) {
    Optional<bool> value;
    EXPECT_TRUE(value.isEmpty());

    value = Pistache::Some(true);
    ASSERT_FALSE(value.isEmpty());

    EXPECT_TRUE(value.get());
}

TEST(optional, copy_assignment_operator) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());

    Optional<bool> other;
    EXPECT_TRUE(other.isEmpty());

    other = value;
    ASSERT_FALSE(other.isEmpty());

    EXPECT_TRUE(other.get());
}

TEST(optional, move_constructor) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> value_from_move(std::move(value));
    ASSERT_FALSE(value_from_move.isEmpty());
    EXPECT_TRUE(value_from_move.get());
}

TEST(optional, move_assignment_operator) {
    Optional<bool> value(Pistache::Some(true));
    ASSERT_FALSE(value.isEmpty());
    EXPECT_TRUE(value.get());

    Optional<bool> move_assigned = std::move(value);
    ASSERT_FALSE(move_assigned.isEmpty());
    EXPECT_TRUE(move_assigned.get());
}

TEST(optional, constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());
}

TEST(optional, copy_constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> copy_constructed(value);
    EXPECT_TRUE(value.isEmpty());
}

TEST(optional, copy_assignment_operator_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> assigned = Pistache::None();
    EXPECT_TRUE(assigned.isEmpty());
}

TEST(optional, move_constructor_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> move_constructed(std::move(value));
    EXPECT_TRUE(move_constructed.isEmpty());
}

TEST(optional, move_assignment_operator_none) {
    Optional<bool> value(Pistache::None());
    EXPECT_TRUE(value.isEmpty());

    Optional<bool> move_assigned(std::move(value));
    EXPECT_TRUE(move_assigned.isEmpty());
}
<|endoftext|>