<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep15/host_start_stop_engine.C $             */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

//From Hostboot Directory
////Error handling and traces
#include    <errl/errlentry.H>
#include    <errl/errlmanager.H>
#include    <isteps/hwpisteperror.H>
#include    <initservice/isteps_trace.H>
#include    <errl/errluserdetails.H>
#include    <errl/errludtarget.H>

//HWP Invoker
#include    <fapi2/plat_hwp_invoker.H>

////Targeting support
#include    <fapi2/target.H>
#include    <targeting/common/utilFilter.H>

//From Import Directory (EKB Repository)
#include <p9_pm.H>
#include <p9_pm_stop_gpe_init.H>

//Namespaces
using namespace ERRORLOG;
using namespace TARGETING;
using namespace p9pm;
using namespace fapi2;

namespace ISTEP_15
{
void* host_start_stop_engine (void *io_pArgs)
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_start_stop_engine entry" );
    ISTEP_ERROR::IStepError     l_StepError;
    errlHndl_t l_errl = NULL;

    do {
#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
        uint64_t l_writeData;
        size_t l_writeSize = sizeof(l_writeData);

        TARGETING::Target* l_proc = NULL;
        TARGETING::targetService().masterProcChipTargetHandle(l_proc);

        l_errl = deviceRead(l_proc, &l_writeData, l_writeSize,
                            DEVICE_SCOM_ADDRESS(0x6C004));
        if(l_errl)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_start_stop_engine: failed to read OIMR0 interrupt mask");
            break;
        }
#endif
        //Use targeting code to get a list of all processors
        TARGETING::TargetHandleList l_procChips;
        getAllChips( l_procChips, TARGETING::TYPE_PROC   );

        for (const auto & l_procChip: l_procChips)
        {
            //Convert the TARGETING::Target into a fapi2::Target by passing
            //l_procChip into the fapi2::Target constructor
            fapi2::Target<TARGET_TYPE_PROC_CHIP>l_fapi2CpuTarget(
                                                              (l_procChip));

            //call p9_pm_stop_gpe_init.C HWP
            FAPI_INVOKE_HWP(l_errl,
                            p9_pm_stop_gpe_init,
                            l_fapi2CpuTarget,
                            PM_INIT);
            if(l_errl)
            {
                ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);
                l_StepError.addErrorDetails( l_errl );
                errlCommit( l_errl, HWPF_COMP_ID );
                TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_start_stop_engine:: failed on proc with HUID : %d",TARGETING::get_huid(l_procChip)  );
            }
        }
#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
        // Starting SGPE in istep15.4 causes OIMR0 register to be improperly
        // reset, which breaks the xstop analysis flow during IPL. A hack
        // is to write the original contents of that register back if
        // the IPL checkstop flag is enabled.
        l_errl = deviceWrite(l_proc, &l_writeData, l_writeSize,
                             DEVICE_SCOM_ADDRESS(0x6C004));
        if(l_errl)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_start_stop_engine: failed to reset OIMR0 interrupt mask");
            break;
        }
#endif
      }while (0);

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_start_stop_engine exit" );
    // end task, returning any errorlogs to IStepDisp
    return l_StepError.getErrorHandle();
}

};
<commit_msg>Skip enabling PM complex (start_stop_engine HWP) in Axone simics<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep15/host_start_stop_engine.C $             */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

//From Hostboot Directory
////Error handling and traces
#include    <errl/errlentry.H>
#include    <errl/errlmanager.H>
#include    <isteps/hwpisteperror.H>
#include    <initservice/isteps_trace.H>
#include    <errl/errluserdetails.H>
#include    <errl/errludtarget.H>

//HWP Invoker
#include    <fapi2/plat_hwp_invoker.H>

////Targeting support
#include    <fapi2/target.H>
#include    <targeting/common/utilFilter.H>

//From Import Directory (EKB Repository)
#include <p9_pm.H>
#include <p9_pm_stop_gpe_init.H>

//Namespaces
using namespace ERRORLOG;
using namespace TARGETING;
using namespace p9pm;
using namespace fapi2;

namespace ISTEP_15
{
void* host_start_stop_engine (void *io_pArgs)
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_start_stop_engine entry" );
    ISTEP_ERROR::IStepError     l_StepError;
    errlHndl_t l_errl = NULL;

    do {
#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
        uint64_t l_writeData;
        size_t l_writeSize = sizeof(l_writeData);

        TARGETING::Target* l_proc = NULL;
        TARGETING::targetService().masterProcChipTargetHandle(l_proc);

        l_errl = deviceRead(l_proc, &l_writeData, l_writeSize,
                            DEVICE_SCOM_ADDRESS(0x6C004));
        if(l_errl)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_start_stop_engine: failed to read OIMR0 interrupt mask");
            break;
        }
#endif

// Skip initializing the PM complex in axone simics for now
#ifndef CONFIG_AXONE_BRING_UP
        //Use targeting code to get a list of all processors
        TARGETING::TargetHandleList l_procChips;
        getAllChips( l_procChips, TARGETING::TYPE_PROC   );

        for (const auto & l_procChip: l_procChips)
        {
            //Convert the TARGETING::Target into a fapi2::Target by passing
            //l_procChip into the fapi2::Target constructor
            fapi2::Target<TARGET_TYPE_PROC_CHIP>l_fapi2CpuTarget(
                                                              (l_procChip));

            //call p9_pm_stop_gpe_init.C HWP
            FAPI_INVOKE_HWP(l_errl,
                            p9_pm_stop_gpe_init,
                            l_fapi2CpuTarget,
                            PM_INIT);
            if(l_errl)
            {
                ErrlUserDetailsTarget(l_procChip).addToLog(l_errl);
                l_StepError.addErrorDetails( l_errl );
                errlCommit( l_errl, HWPF_COMP_ID );
                TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "host_start_stop_engine:: failed on proc with HUID : %d",TARGETING::get_huid(l_procChip)  );
            }
        }
#endif

#ifdef CONFIG_IPLTIME_CHECKSTOP_ANALYSIS
        // Starting SGPE in istep15.4 causes OIMR0 register to be improperly
        // reset, which breaks the xstop analysis flow during IPL. A hack
        // is to write the original contents of that register back if
        // the IPL checkstop flag is enabled.
        l_errl = deviceWrite(l_proc, &l_writeData, l_writeSize,
                             DEVICE_SCOM_ADDRESS(0x6C004));
        if(l_errl)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "host_start_stop_engine: failed to reset OIMR0 interrupt mask");
            break;
        }
#endif
      }while (0);

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_start_stop_engine exit" );
    // end task, returning any errorlogs to IStepDisp
    return l_StepError.getErrorHandle();
}

};
<|endoftext|>


<commit_before>#include "Heartbeat.h"
#include "Sensors.h"
#include <DHT.h>
#include "SparkFunMPL3115A2.h"

Sensors::Sensors(void){
	// This is arduino, and changing the compilation flags
	// on a per project basis is nonexistant here, woooo!
	// Therefore, we can't use C++11, and nullptr.
	this->dht_module = NULL;
	this->pressure_sensor = NULL;
}

/**
 * @brief Just configures what pin our DH11 module uses for data.
 *
 * @param data_pin Pin used for data communication.
 */
void Sensors::init_DH11(const uint8_t data_pin){
	this->data_pin = data_pin;
	dht_module = new DHT(this->data_pin, DHT11, 2);
	dht_module->begin();
}

/**
 * @brief Sets up the MPL3115A2 module for pressure readings.
 */
void Sensors::init_MPL3115A2(void){
	this->pressure_sensor = new MPL3115A2();

	// initiate the pressure sensor
	this->pressure_sensor->begin();

	// configure the pressure sensor
	pressure_sensor->setModeBarometer();
	pressure_sensor->setOversampleRate(7);
	pressure_sensor->enableEventFlags();
}

/**
 * @brief Reads sensor data.
 *
 * @return Data from the reading in the form of a sensor_data struct.
 */
Sensor_data Sensors::read_sensors(void){
	Sensor_data sensor_data;

	// Check if this class was properly initiated.
	if (dht_module == NULL || pressure_sensor == NULL) {
		sensor_data.temperature_f = 0.0;
  		sensor_data.humidity = 0.0;
  		sensor_data.light = 0;
  		sensor_data.pressure = 0.0;

  		Heartbeat::panic();
  		Serial.println(F("Attempt to read sensors before initilization."));

  		return sensor_data;
	}

  // True means Fahrenheit. Yeah, this library is trash.
  //sensor_data.temperature_f = dht_module->readTemperature(true);
  sensor_data.temperature_f = pressure_sensor->readTempF();
  sensor_data.humidity = dht_module->readHumidity();
  sensor_data.light = analogRead(A0);
  sensor_data.pressure = pressure_sensor->readPressure();

  return sensor_data;
}

/**
 * @brief Prints the contents of sensor data nicely over uart.
 *
 * @param sensor_data The sensor data struct we will be displaying.
 */
void Sensors::print(const Sensor_data sensor_data){
	Serial.print(F("-  Humidity: "));
	Serial.println(sensor_data.humidity);
	Serial.print(F("-  Temperature: "));
	Serial.println(sensor_data.temperature_f);
	Serial.print(F("-  Light: "));
	Serial.println(sensor_data.light);
	Serial.print(F("-  Pressure: "));
	Serial.println(sensor_data.pressure);
}
<commit_msg>Cleaned up formatting for Sensors::read_sensors()<commit_after>#include "Heartbeat.h"
#include "Sensors.h"
#include <DHT.h>
#include "SparkFunMPL3115A2.h"

Sensors::Sensors(void){
	// This is arduino, and changing the compilation flags
	// on a per project basis is nonexistant here, woooo!
	// Therefore, we can't use C++11, and nullptr.
	this->dht_module = NULL;
	this->pressure_sensor = NULL;
}

/**
 * @brief Just configures what pin our DH11 module uses for data.
 *
 * @param data_pin Pin used for data communication.
 */
void Sensors::init_DH11(const uint8_t data_pin){
	this->data_pin = data_pin;
	dht_module = new DHT(this->data_pin, DHT11, 2);
	dht_module->begin();
}

/**
 * @brief Sets up the MPL3115A2 module for pressure readings.
 */
void Sensors::init_MPL3115A2(void){
	this->pressure_sensor = new MPL3115A2();

	// initiate the pressure sensor
	this->pressure_sensor->begin();

	// configure the pressure sensor
	pressure_sensor->setModeBarometer();
	pressure_sensor->setOversampleRate(7);
	pressure_sensor->enableEventFlags();
}

/**
 * @brief Reads sensor data.
 *
 * @return Data from the reading in the form of a sensor_data struct.
 */
Sensor_data Sensors::read_sensors(void){
	Sensor_data sensor_data;

	// Check if this class was properly initiated.
	if (dht_module == NULL || pressure_sensor == NULL) {
		sensor_data.temperature_f = 0.0;
		sensor_data.humidity = 0.0;
		sensor_data.light = 0;
		sensor_data.pressure = 0.0;

		Heartbeat::panic();
		Serial.println(F("Attempt to read sensors before initilization."));

		return sensor_data;
	}

	// Read all our sensors.
	sensor_data.temperature_f = pressure_sensor->readTempF();
	sensor_data.humidity = dht_module->readHumidity();
	sensor_data.light = analogRead(A0);
	sensor_data.pressure = pressure_sensor->readPressure();

	return sensor_data;
}

/**
 * @brief Prints the contents of sensor data nicely over uart.
 *
 * @param sensor_data The sensor data struct we will be displaying.
 */
void Sensors::print(const Sensor_data sensor_data){
	Serial.print(F("-  Humidity: "));
	Serial.println(sensor_data.humidity);
	Serial.print(F("-  Temperature: "));
	Serial.println(sensor_data.temperature_f);
	Serial.print(F("-  Light: "));
	Serial.println(sensor_data.light);
	Serial.print(F("-  Pressure: "));
	Serial.println(sensor_data.pressure);
}
<|endoftext|>


<commit_before>#include "PlayerLayer.h"
#include "GameManager.h"

USING_NS_CC;

bool CPlayerLayer::init()
{
	//////////////////////////////
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}

	m_CurrentPlayerId = -1;

	m_VisibleSize = CCDirector::sharedDirector()->getVisibleSize();

	//ġ  Ѵ. ġ  ̴.
	m_UIposition[0].x = DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[0].y = m_VisibleSize.height - DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[1].x = m_VisibleSize.width - DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[1].y =m_VisibleSize.height - DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[2].x = DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[2].y = DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[3].x =m_VisibleSize.width -  DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[3].y = DEFAULT_CHARACTER_MARGIN_V;

	//CCSpriteBatchNode Ͽ ҽ غѴ.
	m_pSpriteBatchNode = CCSpriteBatchNode::create("image/CharacterPlayAnimation.png");
	addChild(m_pSpriteBatchNode,0);

	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist");

	//ϴ  ÷̾ ĳͰ  ġ  Ѵ.
	for (int playerId = 0; playerId<MAX_PLAYER_NUM; ++playerId)
	{
		//  ÷̾ ѱ.
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;

		int position = CGameManager::GetInstance()->GetPlayerTurn(playerId);

		m_Player[playerId] = CCSprite::create();
		m_Player[playerId]->setPosition(m_UIposition[position]);
	}

	//ĳ ù°   UI غѴ.
	SetWaitingCharacters();

	//addChildش.
	for(int playerId=0;playerId<MAX_PLAYER_NUM;++playerId)
	{
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;

		m_pSpriteBatchNode->addChild(m_Player[playerId]);
	}

	// (ù° ) ִϸ̼   ֵ update()   ش.
	update(0);

	return true;

}

void CPlayerLayer::update( float dt )
{
	//ϴ   ̴ ִϸ̼ ϰ,  ĳ͸ ù°   ´.
	//pause Ƿ, ݵ resume ̿ؾ Ѵ.
	if(m_CurrentPlayerId != -1)
	{
		SetWaitingCharacters();
		m_Player[m_CurrentPlayerId]->pauseSchedulerAndActions();
	}

	// Ͽ شϴ ĳ ִϸ̼ Ѵ.
	//ִϸ̼ Ʈ    .
	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist");

	m_CurrentPlayerId = CGameManager::GetInstance()->GetCurrentPlayerId();

	CCLOG("currentId = %d, it's turn = %d",m_CurrentPlayerId,CGameManager::GetInstance()->GetPlayerTurn(m_CurrentPlayerId));

	m_CharacterAni = CCAnimation::create();
	m_CharacterAni->setDelayPerUnit(0.5f);

	switch(CGameManager::GetInstance()->GetCharacterId(m_CurrentPlayerId))
	{
	case 0:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_1_Ani0.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_1_Ani1.png"));
		break;
	case 1:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_2_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_2_Ani2.png"));
		break;
	case 2:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_3_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_3_Ani2.png"));
		break;
	case 3:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_4_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_4_Ani2.png"));
		break;
	}

	CCRepeatForever* repeatAction = CCRepeatForever::create(CCAnimate::create(m_CharacterAni));
	m_Player[m_CurrentPlayerId]->runAction(repeatAction);
	m_Player[m_CurrentPlayerId]->resumeSchedulerAndActions();

}

void CPlayerLayer::SetWaitingCharacters()
{
	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist","image/CharacterPlayAnimation.png");

	for(int playerId = 0; playerId<MAX_PLAYER_NUM;++playerId)
	{
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;
		switch (CGameManager::GetInstance()->GetCharacterId(playerId))
		{
		case 0:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_1_Ani0.png"));
			break;
		case 1:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_2_Ani1.png"));
			break;
		case 2:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_3_Ani1.png"));
			break;
		case 3:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_4_Ani1.png"));
			break;
		default:
			break;
		}
	}
}
<commit_msg>플레이씬> 모두들 게임맵을 바라보아요~<commit_after>#include "PlayerLayer.h"
#include "GameManager.h"

USING_NS_CC;

bool CPlayerLayer::init()
{
	//////////////////////////////
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}

	m_CurrentPlayerId = -1;

	m_VisibleSize = CCDirector::sharedDirector()->getVisibleSize();

	//ġ  Ѵ. ġ  ̴.
	m_UIposition[0].x = DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[0].y = m_VisibleSize.height - DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[1].x = m_VisibleSize.width - DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[1].y =m_VisibleSize.height - DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[2].x = DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[2].y = DEFAULT_CHARACTER_MARGIN_V;

	m_UIposition[3].x =m_VisibleSize.width -  DEFAULT_CHARACTER_MARGIN_H;
	m_UIposition[3].y = DEFAULT_CHARACTER_MARGIN_V;

	//CCSpriteBatchNode Ͽ ҽ غѴ.
	m_pSpriteBatchNode = CCSpriteBatchNode::create("image/CharacterPlayAnimation.png");
	addChild(m_pSpriteBatchNode,0);

	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist");

	//ϴ  ÷̾ ĳͰ  ġ  Ѵ.
	for (int playerId = 0; playerId<MAX_PLAYER_NUM; ++playerId)
	{
		//  ÷̾ ѱ.
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;

		int position = CGameManager::GetInstance()->GetPlayerTurn(playerId);

		m_Player[playerId] = CCSprite::create();
		m_Player[playerId]->setPosition(m_UIposition[position]);
		switch(position)
		{
		case 0:
			break;
		case 1:
			m_Player[playerId]->setFlipX(true);
			break;
		case 2:
			m_Player[playerId]->setFlipY(true);
			break;
		case 3:
			m_Player[playerId]->setRotation(180.0f);
			break;
		}
	}

	//ĳ ù°   UI غѴ.
	SetWaitingCharacters();

	//addChildش.
	for(int playerId=0;playerId<MAX_PLAYER_NUM;++playerId)
	{
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;

		m_pSpriteBatchNode->addChild(m_Player[playerId]);
	}

	// (ù° ) ִϸ̼   ֵ update()   ش.
	update(0);

	return true;

}

void CPlayerLayer::update( float dt )
{
	//ϴ   ̴ ִϸ̼ ϰ,  ĳ͸ ù°   ´.
	//pause Ƿ, ݵ resume ̿ؾ Ѵ.
	if(m_CurrentPlayerId != -1)
	{
		SetWaitingCharacters();
		m_Player[m_CurrentPlayerId]->pauseSchedulerAndActions();
	}

	// Ͽ شϴ ĳ ִϸ̼ Ѵ.
	//ִϸ̼ Ʈ    .
	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist");

	m_CurrentPlayerId = CGameManager::GetInstance()->GetCurrentPlayerId();

	CCLOG("currentId = %d, it's turn = %d",m_CurrentPlayerId,CGameManager::GetInstance()->GetPlayerTurn(m_CurrentPlayerId));

	m_CharacterAni = CCAnimation::create();
	m_CharacterAni->setDelayPerUnit(0.5f);

	switch(CGameManager::GetInstance()->GetCharacterId(m_CurrentPlayerId))
	{
	case 0:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_1_Ani0.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_1_Ani1.png"));
		break;
	case 1:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_2_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_2_Ani2.png"));
		break;
	case 2:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_3_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_3_Ani2.png"));
		break;
	case 3:
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_4_Ani1.png"));
		m_CharacterAni->addSpriteFrame(cache->spriteFrameByName("CHARACTER_4_Ani2.png"));
		break;
	}

	CCRepeatForever* repeatAction = CCRepeatForever::create(CCAnimate::create(m_CharacterAni));
	m_Player[m_CurrentPlayerId]->runAction(repeatAction);
	m_Player[m_CurrentPlayerId]->resumeSchedulerAndActions();

}

void CPlayerLayer::SetWaitingCharacters()
{
	CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("image/CharacterPlayAnimation.plist","image/CharacterPlayAnimation.png");

	for(int playerId = 0; playerId<MAX_PLAYER_NUM;++playerId)
	{
		if (CGameManager::GetInstance()->GetCharacterId(playerId)==-1)
			continue;
		switch (CGameManager::GetInstance()->GetCharacterId(playerId))
		{
		case 0:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_1_Ani0.png"));
			break;
		case 1:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_2_Ani1.png"));
			break;
		case 2:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_3_Ani1.png"));
			break;
		case 3:
			m_Player[playerId]->setDisplayFrame(cache->spriteFrameByName("CHARACTER_4_Ani1.png"));
			break;
		default:
			break;
		}
	}
}
<|endoftext|>


<commit_before>//saru95
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <complex>
#include <math.h>
#include <utility>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <cctype>
#include <queue>
#include <stdio.h>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <numeric>
#include <functional>
#include <memory.h>

#define all(a) (a).begin(),(a).end()
#define gcd __gcd
#define bitcount __builtin_popcount

using namespace std;

typedef std::vector<int> vi;
typedef std::vector<std::string> vs;
typedef std::pair<int, int> pii;
typedef std::set<int> si;
typedef std::map<std::string, int> msi;

vector< pair<int , int > > *adj ;
bool *visited ;
int d[1024] ;  // distance array

void dij(int source,int nodes) {
	priority_queue< pii , vector< pii > , greater<pii> > q ;
	int u, cost ,v , w;
	q.push(0,source) ;
	d[source] = 0 ;
	while(!q.empty()) {
		cost = q.top().first ;
		u = q.top().second ;
		q.pop() ;
		if(d[u]<cost) continue ;

		for(int i=0;i<nodes;i++) {
			v = adj[u][i].first ;
			w = adj[u][i].second ;
			if(d[v] > d[u]+w) {
				d[v] = d[u] + w ;
				q.push(make_pair (d[v], v)) ;
			}
		}
	}
}

int main(int argc, char const *argv[]) {
	int nodes, edges, sourcenode ,u , v, w;
	memset(d,0,sizeof(d)) ;
	cin >> nodes ;
	visited = new bool[nodes] ;
	adj = new vector< pair<int ,int > >[nodes] ;

	cin >> edges ;
	for(int i=0;i<edges;i++){
		cin >> u >> v >> w;
		adj[u].push_back(make_pair (v,w)) ;
	}

	cin >> sourcenode ;
	dij(sourcenode,nodes) ;
	return 0;
}<commit_msg>Decreasing Overhead<commit_after>//saru95
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <complex>
#include <math.h>
#include <utility>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <cctype>
#include <queue>
#include <stdio.h>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <numeric>
#include <functional>
#include <memory.h>

#define all(a) (a).begin(),(a).end()
#define gcd __gcd
#define bitcount __builtin_popcount

using namespace std;

typedef std::vector<int> vi;
typedef std::vector<std::string> vs;
typedef std::pair<int, int> pii;
typedef std::set<int> si;
typedef std::map<std::string, int> msi;

vector< pair<int , int > > *adj ;
int d[1024] ;  		// distance array
bool mark[1024];	//mark(visited) array
void dij(int source,int nodes) {
	priority_queue< pii , vector< pii > , greater<pii> > q ;	//STL Priority Queue
	int u, cost ,v , w;
	q.push(0,source) ;
	d[source] = 0 ;
	while(!q.empty()) {
		cost = q.top().first ;
		u = q.top().second ;
		q.pop() ;
		if(d[u]<cost) continue ;
		if(mark[u])	continue;	//For not visiting same nodes
		mark[u] = true;			//(this will decrease some overhead)
		for(int i=0;i<nodes;i++) {
			v = adj[u][i].first ;
			w = adj[u][i].second ;
			if(d[v] > d[u]+w) {
				d[v] = d[u] + w ;
				q.push(make_pair (d[v], v)) ;
			}
		}
	}
}

int main(int argc, char const *argv[]) {
	int nodes, edges, sourcenode ,u , v, w;
	memset(d,0,sizeof(d)) ;
	cin >> nodes ;
	adj = new vector< pair<int ,int > >[nodes] ;

	cin >> edges ;
	for(int i=0;i<edges;i++){
		cin >> u >> v >> w;
		adj[u].push_back(make_pair (v,w)) ;
	}

	cin >> sourcenode ;
	dij(sourcenode,nodes) ;
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2013-, Open Perception, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * 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.
 * * Neither the name of the copyright holder(s) nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 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.
 *
 * person_classifier.hpp
 * Created on: Nov 30, 2012
 * Author: Matteo Munaro
 */

#include <pcl/people/person_classifier.h>

#ifndef PCL_PEOPLE_PERSON_CLASSIFIER_HPP_
#define PCL_PEOPLE_PERSON_CLASSIFIER_HPP_

template <typename PointT>
pcl::people::PersonClassifier<PointT>::PersonClassifier () {}

template <typename PointT>
pcl::people::PersonClassifier<PointT>::~PersonClassifier () {}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::loadSVMFromFile (std::string svm_filename)
{
  std::string line;
  std::ifstream SVM_file;
  SVM_file.open(svm_filename.c_str());

  getline (SVM_file,line);      // read window_height line
  size_t tok_pos = line.find_first_of(":", 0);  // search for token ":"
  window_height_ = std::atoi(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read window_width line
  tok_pos = line.find_first_of(":", 0);  // search for token ":"
  window_width_ = std::atoi(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read SVM_offset line
  tok_pos = line.find_first_of(":", 0);  // search for token ":"
  SVM_offset_ = std::atof(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read SVM_weights line
  tok_pos = line.find_first_of("[", 0);  // search for token "["
  size_t tok_end_pos = line.find_first_of("]", 0);  // search for token "]" , end of SVM weights
  size_t prev_tok_pos;
  while (tok_pos < tok_end_pos) // while end of SVM_weights is not reached
  {
    prev_tok_pos = tok_pos;
    tok_pos = line.find_first_of(",", prev_tok_pos+1);  // search for token ","
    SVM_weights_.push_back(std::atof(line.substr(prev_tok_pos+1, tok_pos-prev_tok_pos-1).c_str()));
  }
  SVM_file.close();
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::setSVM (int window_height, int window_width, std::vector<float> SVM_weights, float SVM_offset)
{
  window_height_ = window_height;
  window_width_ = window_width;
  SVM_weights_ = SVM_weights;
  SVM_offset_ = SVM_offset;
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::getSVM (int& window_height, int& window_width, std::vector<float>& SVM_weights, float& SVM_offset)
{
  window_height = window_height_;
  window_width = window_width_;
  SVM_weights = SVM_weights_;
  SVM_offset = SVM_offset_;
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::resize (PointCloudPtr& input_image,
						  PointCloudPtr& output_image,
						  int width,
						  int height)
{
  PointT new_point;
  new_point.r = 0;
  new_point.g = 0;
  new_point.b = 0;

  // Allocate the vector of points:
  output_image->points.resize(width*height, new_point);
  output_image->height = height;
  output_image->width = width;

  // Compute scale factor:
  float scale1 = float(height) / float(input_image->height);
  float scale2 = float(width) / float(input_image->width);

  Eigen::Matrix3f T_inv;
  T_inv << 1/scale1, 0, 0,
		   0, 1/scale2, 0,
		   0,   0,   1;

  Eigen::Vector3f A;
  int c1, c2, f1, f2;
  PointT g1, g2, g3, g4;
  float w1, w2;
  for (unsigned int i = 0; i < height; i++)    // for every row
  {
	for (unsigned int j = 0; j < width; j++)  // for every column
	{
	  A = T_inv * Eigen::Vector3f(i, j, 1);
	  c1 = ceil(A(0));
	  f1 = floor(A(0));
	  c2 = ceil(A(1));
	  f2 = floor(A(1));

	  if ( (f1 < 0) ||
		   (c1 < 0) ||
		   (f1 >= input_image->height) ||
		   (c1 >= input_image->height) ||
		   (f2 < 0) ||
		   (c2 < 0) ||
		   (f2 >= input_image->width) ||
		   (c2 >= input_image->width))
	  { // if out of range, continue
		continue;
	  }

	  g1 = (*input_image)(f2, c1);
	  g3 = (*input_image)(f2, f1);
	  g4 = (*input_image)(c2, f1);
	  g2 = (*input_image)(c2, c1);

	  w1 = (A(0) - f1);
	  w2 = (A(1) - f2);
	  new_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));
	  new_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));
	  new_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));

	  // Insert the point in the output image:
	  (*output_image)(j,i) = new_point;
	}
  }
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::copyMakeBorder (PointCloudPtr& input_image,
								  PointCloudPtr& output_image,
								  int xmin,
								  int ymin,
								  int width,
								  int height)
{
  PointT black_point;
  black_point.r = 0;
  black_point.g = 0;
  black_point.b = 0;
  output_image->points.resize(height*width, black_point);
  output_image->width = width;
  output_image->height = height;

  int x_start_in = std::max(0, xmin);
  int x_end_in = std::min(int(input_image->width-1), xmin+width-1);
  int y_start_in = std::max(0, ymin);
  int y_end_in = std::min(int(input_image->height-1), ymin+height-1);

  int x_start_out = std::max(0, -xmin);
  int x_end_out = x_start_out + (x_end_in - x_start_in);
  int y_start_out = std::max(0, -ymin);
  int y_end_out = y_start_out + (y_end_in - y_start_in);

  for (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)
  {
	for (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)
	{
	  (*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);
	}
  }
}

template <typename PointT> double
pcl::people::PersonClassifier<PointT>::evaluate (float height_person,
							float xc,
							float yc,
							PointCloudPtr& image)
{
  if (SVM_weights_.size() == 0)
  {
	PCL_ERROR ("[pcl::people::PersonClassifier::evaluate] SVM has not been set!\n");
	return (-1000);
  }

  int height = floor((height_person * window_height_) / (0.75 * window_height_) + 0.5);  // floor(i+0.5) = round(i)
  int width = floor((height_person * window_width_) / (0.75 * window_height_) + 0.5);
  int xmin = floor(xc - width / 2 + 0.5);
  int ymin = floor(yc - height / 2 + 0.5);

  // If near the border, fill with black
  PointCloudPtr box(new PointCloud);
  copyMakeBorder(image, box, xmin, ymin, width, height);

  // Make the image match the correct size
  PointCloudPtr sample(new PointCloud);
  resize(box, sample, window_width_, window_height_);

  //Convert the image to Matlab format
  double* sample_double = new double[sample->width * sample->height * 3];
  int delta = sample->height * sample->width;
  for(int row = 0; row < sample->height; row++)
  {
	for(int col = 0; col < sample->width; col++)
	{
	  sample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); //ptr[col * 3 + 2];
	  sample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); //ptr[col * 3 + 1];
	  sample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); //ptr[col * 3];
	}
  }

  double *ris = new double[SVM_weights_.size()];

  //Calculate HOG descriptor
  pcl::people::HOG hog;
  hog.compute(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);

  //Calculate confidence value by dot product
  double confidence = 0.0;
  for(uint i = 0; i < SVM_weights_.size(); i++)
  {
	confidence += SVM_weights_[i] * ris[i];
  }
  //Confidence correction
  confidence -= SVM_offset_;

  delete[] ris;
  delete[] sample_double;

  return confidence;
}

template <typename PointT> double
pcl::people::PersonClassifier<PointT>::evaluate (PointCloudPtr& image,
							Eigen::Vector3f& bottom,
							Eigen::Vector3f& top,
							Eigen::Vector3f& centroid,
							Eigen::Matrix3f intrinsics_matrix,
							bool vertical)
{
  float pixel_height;
  float pixel_width;
  if (not vertical)
  {
	pixel_height = bottom(1) - top(1);
	pixel_width = pixel_height / 2.0f;
  }
  else
  {
	pixel_width = top(0) - bottom(0);
	pixel_height = pixel_width / 2.0f;
  }
  float pixel_xc = centroid(0);
  float pixel_yc = centroid(1);

  if (not vertical)
  {
	return (evaluate(pixel_height, pixel_xc, pixel_yc, image));
  }
  else
  {
	return (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));
  }
}
#endif /* PCL_PEOPLE_PERSON_CLASSIFIER_HPP_ */
<commit_msg>pcl_people: minor fix.<commit_after>/*
 * Software License Agreement (BSD License)
 *
 * Point Cloud Library (PCL) - www.pointclouds.org
 * Copyright (c) 2013-, Open Perception, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * 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.
 * * Neither the name of the copyright holder(s) nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 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.
 *
 * person_classifier.hpp
 * Created on: Nov 30, 2012
 * Author: Matteo Munaro
 */

#include <pcl/people/person_classifier.h>

#ifndef PCL_PEOPLE_PERSON_CLASSIFIER_HPP_
#define PCL_PEOPLE_PERSON_CLASSIFIER_HPP_

template <typename PointT>
pcl::people::PersonClassifier<PointT>::PersonClassifier () {}

template <typename PointT>
pcl::people::PersonClassifier<PointT>::~PersonClassifier () {}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::loadSVMFromFile (std::string svm_filename)
{
  std::string line;
  std::ifstream SVM_file;
  SVM_file.open(svm_filename.c_str());

  getline (SVM_file,line);      // read window_height line
  size_t tok_pos = line.find_first_of(":", 0);  // search for token ":"
  window_height_ = std::atoi(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read window_width line
  tok_pos = line.find_first_of(":", 0);  // search for token ":"
  window_width_ = std::atoi(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read SVM_offset line
  tok_pos = line.find_first_of(":", 0);  // search for token ":"
  SVM_offset_ = std::atof(line.substr(tok_pos+1, line.npos - tok_pos-1).c_str());

  getline (SVM_file,line);      // read SVM_weights line
  tok_pos = line.find_first_of("[", 0);  // search for token "["
  size_t tok_end_pos = line.find_first_of("]", 0);  // search for token "]" , end of SVM weights
  size_t prev_tok_pos;
  while (tok_pos < tok_end_pos) // while end of SVM_weights is not reached
  {
    prev_tok_pos = tok_pos;
    tok_pos = line.find_first_of(",", prev_tok_pos+1);  // search for token ","
    SVM_weights_.push_back(std::atof(line.substr(prev_tok_pos+1, tok_pos-prev_tok_pos-1).c_str()));
  }
  SVM_file.close();
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::setSVM (int window_height, int window_width, std::vector<float> SVM_weights, float SVM_offset)
{
  window_height_ = window_height;
  window_width_ = window_width;
  SVM_weights_ = SVM_weights;
  SVM_offset_ = SVM_offset;
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::getSVM (int& window_height, int& window_width, std::vector<float>& SVM_weights, float& SVM_offset)
{
  window_height = window_height_;
  window_width = window_width_;
  SVM_weights = SVM_weights_;
  SVM_offset = SVM_offset_;
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::resize (PointCloudPtr& input_image,
              PointCloudPtr& output_image,
              int width,
              int height)
{
  PointT new_point;
  new_point.r = 0;
  new_point.g = 0;
  new_point.b = 0;

  // Allocate the vector of points:
  output_image->points.resize(width*height, new_point);
  output_image->height = height;
  output_image->width = width;

  // Compute scale factor:
  float scale1 = float(height) / float(input_image->height);
  float scale2 = float(width) / float(input_image->width);

  Eigen::Matrix3f T_inv;
  T_inv << 1/scale1, 0, 0,
       0, 1/scale2, 0,
       0,   0,   1;

  Eigen::Vector3f A;
  int c1, c2, f1, f2;
  PointT g1, g2, g3, g4;
  float w1, w2;
  for (unsigned int i = 0; i < height; i++)    // for every row
  {
  for (unsigned int j = 0; j < width; j++)  // for every column
  {
    A = T_inv * Eigen::Vector3f(i, j, 1);
    c1 = ceil(A(0));
    f1 = floor(A(0));
    c2 = ceil(A(1));
    f2 = floor(A(1));

    if ( (f1 < 0) ||
       (c1 < 0) ||
       (f1 >= input_image->height) ||
       (c1 >= input_image->height) ||
       (f2 < 0) ||
       (c2 < 0) ||
       (f2 >= input_image->width) ||
       (c2 >= input_image->width))
    { // if out of range, continue
    continue;
    }

    g1 = (*input_image)(f2, c1);
    g3 = (*input_image)(f2, f1);
    g4 = (*input_image)(c2, f1);
    g2 = (*input_image)(c2, c1);

    w1 = (A(0) - f1);
    w2 = (A(1) - f2);
    new_point.r = int((1 - w1) * ((1 - w2) * g1.r + w2 * g4.r) + w1 * ((1 - w2) * g3.r + w2 * g4.r));
    new_point.g = int((1 - w1) * ((1 - w2) * g1.g + w2 * g4.g) + w1 * ((1 - w2) * g3.g + w2 * g4.g));
    new_point.b = int((1 - w1) * ((1 - w2) * g1.b + w2 * g4.b) + w1 * ((1 - w2) * g3.b + w2 * g4.b));

    // Insert the point in the output image:
    (*output_image)(j,i) = new_point;
  }
  }
}

template <typename PointT> void
pcl::people::PersonClassifier<PointT>::copyMakeBorder (PointCloudPtr& input_image,
                  PointCloudPtr& output_image,
                  int xmin,
                  int ymin,
                  int width,
                  int height)
{
  PointT black_point;
  black_point.r = 0;
  black_point.g = 0;
  black_point.b = 0;
  output_image->points.resize(height*width, black_point);
  output_image->width = width;
  output_image->height = height;

  int x_start_in = std::max(0, xmin);
  int x_end_in = std::min(int(input_image->width-1), xmin+width-1);
  int y_start_in = std::max(0, ymin);
  int y_end_in = std::min(int(input_image->height-1), ymin+height-1);

  int x_start_out = std::max(0, -xmin);
  int x_end_out = x_start_out + (x_end_in - x_start_in);
  int y_start_out = std::max(0, -ymin);
  int y_end_out = y_start_out + (y_end_in - y_start_in);

  for (unsigned int i = 0; i < (y_end_in - y_start_in + 1); i++)
  {
  for (unsigned int j = 0; j < (x_end_in - x_start_in + 1); j++)
  {
    (*output_image)(x_start_out + j, y_start_out + i) = (*input_image)(x_start_in + j, y_start_in + i);
  }
  }
}

template <typename PointT> double
pcl::people::PersonClassifier<PointT>::evaluate (float height_person,
              float xc,
              float yc,
              PointCloudPtr& image)
{
  if (SVM_weights_.size() == 0)
  {
  PCL_ERROR ("[pcl::people::PersonClassifier::evaluate] SVM has not been set!\n");
  return (-1000);
  }

  int height = floor((height_person * window_height_) / (0.75 * window_height_) + 0.5);  // floor(i+0.5) = round(i)
  int width = floor((height_person * window_width_) / (0.75 * window_height_) + 0.5);
  int xmin = floor(xc - width / 2 + 0.5);
  int ymin = floor(yc - height / 2 + 0.5);
  double confidence;

  if (height > 0)
  {
    // If near the border, fill with black
    PointCloudPtr box(new PointCloud);
    copyMakeBorder(image, box, xmin, ymin, width, height);

    // Make the image match the correct size
    PointCloudPtr sample(new PointCloud);
    resize(box, sample, window_width_, window_height_);

    //Convert the image to Matlab format
    double* sample_double = new double[sample->width * sample->height * 3];
    int delta = sample->height * sample->width;
    for(int row = 0; row < sample->height; row++)
    {
      for(int col = 0; col < sample->width; col++)
      {
        sample_double[row + sample->height * col] = (double) ((*sample)(col, row).r); //ptr[col * 3 + 2];
        sample_double[row + sample->height * col + delta] = (double) ((*sample)(col, row).g); //ptr[col * 3 + 1];
        sample_double[row + sample->height * col + delta * 2] = (double) ((*sample)(col, row).b); //ptr[col * 3];
      }
    }

    double *ris = new double[SVM_weights_.size()];

    //Calculate HOG descriptor
    pcl::people::HOG hog;
    hog.compute(sample_double, sample->height, sample->width, 3, 8, 9, 10, ris);

    //Calculate confidence value by dot product
    confidence = 0.0;
    for(uint i = 0; i < SVM_weights_.size(); i++)
    {
    confidence += SVM_weights_[i] * ris[i];
    }
    //Confidence correction
    confidence -= SVM_offset_;

    delete[] ris;
    delete[] sample_double;
  }
  else
  {
    confidence = std::numeric_limits<double>::quiet_NaN();
  }

  return confidence;
}

template <typename PointT> double
pcl::people::PersonClassifier<PointT>::evaluate (PointCloudPtr& image,
              Eigen::Vector3f& bottom,
              Eigen::Vector3f& top,
              Eigen::Vector3f& centroid,
              Eigen::Matrix3f intrinsics_matrix,
              bool vertical)
{
  float pixel_height;
  float pixel_width;
  if (not vertical)
  {
  pixel_height = bottom(1) - top(1);
  pixel_width = pixel_height / 2.0f;
  }
  else
  {
  pixel_width = top(0) - bottom(0);
  pixel_height = pixel_width / 2.0f;
  }
  float pixel_xc = centroid(0);
  float pixel_yc = centroid(1);

  if (not vertical)
  {
  return (evaluate(pixel_height, pixel_xc, pixel_yc, image));
  }
  else
  {
  return (evaluate(pixel_width, pixel_yc, image->height-pixel_xc+1, image));
  }
}
#endif /* PCL_PEOPLE_PERSON_CLASSIFIER_HPP_ */
<|endoftext|>


<commit_before>/*****************************************************************************
 * File.cxx
 *****************************************************************************
 * Implementation of class File.
 *****************************************************************************/

// STL includes.
#include <string>

// System includes.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

// Class include.
#include "File.hxx"

// Namespaces used.
using namespace std;

// Namespace wrapper.
namespace DAC {

  /***************************************************************************/
  // Function members.

  // Constructor names the file.
  File::File (string const& filename) {

    // Do standard init.
    clear();

    // Set the filename.
    Filename(filename);

  }

  // Reset to just-constructed defaults.
  void File::clear () {

    _cachevalid = false;

    _stat.st_dev     = 0;
    _stat.st_ino     = 0;
    _stat.st_mode    = 0;
    _stat.st_nlink   = 0;
    _stat.st_uid     = 0;
    _stat.st_gid     = 0;
    _stat.st_rdev    = 0;
    _stat.st_size    = 0;
    _stat.st_blksize = 0;
    _stat.st_blocks  = 0;
    _stat.st_atime   = 0;
    _stat.st_mtime   = 0;
    _stat.st_ctime   = 0;

    _filename.clear();

  }

  // Copy a given File. Does not copy the file itself.
  void File::copy (File const& source) {

    // Prepare for the new file if necessary.
    if (!_filename.empty() && _filename != source._filename) {
      clear();
    }

    // Copy.
    _filename = source._filename;

  }

  // Update the cache.
  void File::_update_cache () const {

  }

}

<commit_msg>Renaming File to be more specific.<commit_after>/*****************************************************************************
 * File.cxx
 *****************************************************************************
 * Implementation of class File.
 *****************************************************************************/

// STL includes.
#include <string>

// System includes.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

// Class include.
#include "File.hxx"

// Namespaces used.
using namespace std;

// Namespace wrapper.
namespace DAC {

  /***************************************************************************/
  // Function members.

  // Constructor names the file.
  File::File (string const& filename) {

    // Do standard init.
    clear();

    // Set the filename.
    Filename(filename);

  }

  // Reset to just-constructed defaults.
  void File::clear () {

    _cachevalid = false;

    _stat.st_dev     = 0;
    _stat.st_ino     = 0;
    _stat.st_mode    = 0;
    _stat.st_nlink   = 0;
    _stat.st_uid     = 0;
    _stat.st_gid     = 0;
    _stat.st_rdev    = 0;
    _stat.st_size    = 0;
    _stat.st_blksize = 0;
    _stat.st_blocks  = 0;
    _stat.st_atime   = 0;
    _stat.st_mtime   = 0;
    _stat.st_ctime   = 0;

    _filename.clear();

  }

  // Copy a given File. Does not copy the file itself.
  void File::copy (File const& source) {

    // Prepare for the new file if necessary.
    if (!_filename.empty() && _filename != source._filename) {
      clear();
    }

    // Copy.
    _filename = source._filename;

  }

  // Update the cache.
  void File::_update_cache () const {

    // Call correct stat() or fstat() if the file is already open.

  }

}

<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                      OpenSim:  ToyReflexController.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-2013 Stanford University and the Authors                *
 * Author(s): Ajay Seth                                                       *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "ToyReflexController.h"
#include <OpenSim/Simulation/Model/Muscle.h>

// This allows us to use OpenSim functions, classes, etc., without having to
// prefix the names of those things with "OpenSim::".
using namespace OpenSim;
using namespace std;
using namespace SimTK;

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/* Default constructor. */
ToyReflexController::ToyReflexController()
{
    constructProperties();
}

/* Convenience constructor. */
ToyReflexController::ToyReflexController(double gain)
{
    constructProperties();
    set_gain(gain);
}

/*
 * Construct Properties
 */
void ToyReflexController::constructProperties()
{
    constructProperty_gain(1.0);
}

void ToyReflexController::extendConnectToModel(Model &model)
{
    Super::extendConnectToModel(model);

    // get the list of actuators assigned to the reflex controller
    Set<Actuator>& actuators = updActuators();

    int cnt=0;

    while(cnt < actuators.getSize()){
        Muscle *musc = dynamic_cast<Muscle*>(&actuators[cnt]);
        // control muscles only
        if(!musc){
            cout << "ToyReflexController:: WARNING- controller assigned a non-muscle actuator ";
            cout << actuators[cnt].getName() << " which will be ignored." << endl;
            actuators.remove(cnt);
        }else
            cnt++;
    }
}

//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
/**
 * Compute the controls for muscles under influence of this reflex controller
 *
 * @param s         current state of the system
 * @param controls  system wide controls to which this controller can add
 */
void ToyReflexController::computeControls(const State& s, Vector &controls) const
{
    // get time
    double time = s.getTime();

    // get the list of actuators assigned to the reflex controller
    const Set<Actuator>& actuators = getActuatorSet();

    // muscle lengthening speed
    double speed = 0;
    // max muscle lengthening (stretch) speed
    double max_speed = 0;
    //reflex control
    double control = 0;

    for(int i=0; i<actuators.getSize(); ++i){
        const Muscle *musc = dynamic_cast<const Muscle*>(&actuators[i]);
        speed = musc->getLengtheningSpeed(s);
        // un-normalize muscle's maximum contraction velocity (fib_lengths/sec)
        max_speed = musc->getOptimalFiberLength()*musc->getMaxContractionVelocity();
        control = 0.5*get_gain()*(fabs(speed)+speed)/max_speed;

        SimTK::Vector actControls(1,control);
        // add reflex controls to whatever controls are already in place.
        musc->addInControls(actControls, controls);
    }
}

<commit_msg>Unused variable.<commit_after>/* -------------------------------------------------------------------------- *
 *                      OpenSim:  ToyReflexController.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-2013 Stanford University and the Authors                *
 * Author(s): Ajay Seth                                                       *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "ToyReflexController.h"
#include <OpenSim/Simulation/Model/Muscle.h>

// This allows us to use OpenSim functions, classes, etc., without having to
// prefix the names of those things with "OpenSim::".
using namespace OpenSim;
using namespace std;
using namespace SimTK;

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/* Default constructor. */
ToyReflexController::ToyReflexController()
{
    constructProperties();
}

/* Convenience constructor. */
ToyReflexController::ToyReflexController(double gain)
{
    constructProperties();
    set_gain(gain);
}

/*
 * Construct Properties
 */
void ToyReflexController::constructProperties()
{
    constructProperty_gain(1.0);
}

void ToyReflexController::extendConnectToModel(Model &model)
{
    Super::extendConnectToModel(model);

    // get the list of actuators assigned to the reflex controller
    Set<Actuator>& actuators = updActuators();

    int cnt=0;

    while(cnt < actuators.getSize()){
        Muscle *musc = dynamic_cast<Muscle*>(&actuators[cnt]);
        // control muscles only
        if(!musc){
            cout << "ToyReflexController:: WARNING- controller assigned a non-muscle actuator ";
            cout << actuators[cnt].getName() << " which will be ignored." << endl;
            actuators.remove(cnt);
        }else
            cnt++;
    }
}

//=============================================================================
// COMPUTATIONS
//=============================================================================
//_____________________________________________________________________________
/**
 * Compute the controls for muscles under influence of this reflex controller
 *
 * @param s         current state of the system
 * @param controls  system wide controls to which this controller can add
 */
void ToyReflexController::computeControls(const State& s, Vector &controls) const
{
    // get time
    s.getTime();

    // get the list of actuators assigned to the reflex controller
    const Set<Actuator>& actuators = getActuatorSet();

    // muscle lengthening speed
    double speed = 0;
    // max muscle lengthening (stretch) speed
    double max_speed = 0;
    //reflex control
    double control = 0;

    for(int i=0; i<actuators.getSize(); ++i){
        const Muscle *musc = dynamic_cast<const Muscle*>(&actuators[i]);
        speed = musc->getLengtheningSpeed(s);
        // un-normalize muscle's maximum contraction velocity (fib_lengths/sec)
        max_speed = musc->getOptimalFiberLength()*musc->getMaxContractionVelocity();
        control = 0.5*get_gain()*(fabs(speed)+speed)/max_speed;

        SimTK::Vector actControls(1,control);
        // add reflex controls to whatever controls are already in place.
        musc->addInControls(actControls, controls);
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
> File Name: CreateAccountScene.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Create account scene of Hearthstone++ GUI program.
> Created Time: 2018/06/06
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
#include <Manager/NetworkManager.h>
#include <Manager/SoundManager.h>
#include <Scenes/CreateAccountScene.h>
#include <Utils/ImGuiUtils.h>

#include <SFML/Window/Keyboard.hpp>

#include <regex>

namespace Hearthstonepp
{
void CreateAccountScene::Start()
{
    GameManager::GetInstance()->SetBackground("Background_Login.png");
    SoundManager::GetInstance()->PlayMusic("BGM_Login.ogg");

    m_flags |= ImGuiWindowFlags_NoResize;
    m_flags |= ImGuiWindowFlags_NoMove;
    m_flags |= ImGuiWindowFlags_NoCollapse;
    m_flags |= ImGuiWindowFlags_NoTitleBar;

    m_popupFlags |= ImGuiWindowFlags_AlwaysAutoResize;
    m_popupFlags |= ImGuiWindowFlags_NoTitleBar;

    m_width = GameManager::GetInstance()->GetWindowWidth() * 0.3f;
    m_height = GameManager::GetInstance()->GetWindowHeight() * 0.52f;

    m_positionX =
        GameManager::GetInstance()->GetWindowWidth() * 0.5f - m_width * 0.5f;
    m_positionY =
        GameManager::GetInstance()->GetWindowHeight() * 0.5f - m_height * 0.5f;

    memset(m_email, 0, sizeof(m_email));
    memset(m_nickname, 0, sizeof(m_nickname));
    memset(m_password1, 0, sizeof(m_password1));
    memset(m_password2, 0, sizeof(m_password2));
}

void CreateAccountScene::Input()
{
    if (GameManager::GetInstance()->HasWindowFocus())
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
        {
            SceneManager::GetInstance()->ChangeScene("Login");
        }
    }
}

void CreateAccountScene::Update()
{
    ImGui::SetNextWindowPos(ImVec2(m_positionX, m_positionY));
    ImGui::SetNextWindowPosCenter(true);

    ImGui::Begin("CreateAccount", &m_isOpened, ImVec2(m_width, m_height), 0.5f,
                 m_flags);
    {
        ImGui::PushItemWidth(-1);

        ImGui::SetWindowFontScale(SceneManager::GetInstance()->GetFontScale());

        // Email
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Email:");
        ImGui::InputText("##Email", m_email, IM_ARRAYSIZE(m_email));

        ImGui::NewLine();

        // Nickname
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Nickname:");
        ImGui::InputText("##Nickname", m_nickname, IM_ARRAYSIZE(m_nickname));

        ImGui::NewLine();

        // Password 1
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Password:");
        ImGui::InputText("##Password1", m_password1, IM_ARRAYSIZE(m_password1),
                         ImGuiInputTextFlags_Password);

        ImGui::NewLine();

        // Password 2
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Confirm Password:");
        ImGui::InputText("##Password2", m_password2, IM_ARRAYSIZE(m_password2),
                         ImGuiInputTextFlags_Password);

        ImGui::NewLine();

        // Create Account
        SetAlignmentHorizontalCenter("Create Account", true);
        if (ImGui::Button("Create Account"))
        {
            if (IsValidAccountInfo())
            {
                if (NetworkManager::GetInstance()->CreateAccount(
                        m_email, m_nickname, m_password1))
                {
                    ImGui::OpenPopup("CreateAccountSuccess");
                }
                else
                {
                    ImGui::OpenPopup("CreateAccountFail");
                }
            }
            else
            {
                ImGui::OpenPopup("CreateAccountFail");
            }
        }

        ImGui::NewLine();

        // Back
        SetAlignmentHorizontalCenter("Back", true);
        if (ImGui::Button("Back"))
        {
            SceneManager::GetInstance()->ChangeScene("Login");
        }

        // Popup notifying create account is success
        ImGui::SetNextWindowPosCenter(true);

        ImGui::SetWindowFontScale(SceneManager::GetInstance()->GetFontScale());

        if (ImGui::BeginPopup("CreateAccountSuccess", m_popupFlags))
        {
            ImGui::SetWindowFontScale(
                SceneManager::GetInstance()->GetFontScale());

            SetAlignmentHorizontalCenter("Create account is success.", false);
            ImGui::Text("Create account is success.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Close", true);
            if (ImGui::Button("Close"))
            {
                ImGui::CloseCurrentPopup();
                SceneManager::GetInstance()->ChangeScene("Login");
            }

            ImGui::EndPopup();
        }

        // Popup notifying why create account is not possible
        ImGui::SetNextWindowPosCenter(true);

        if (ImGui::BeginPopup("CreateAccountFail", m_popupFlags))
        {
            ImGui::SetWindowFontScale(
                SceneManager::GetInstance()->GetFontScale());

            SetAlignmentHorizontalCenter("Create account is failed.", false);
            ImGui::Text("Create account is failed.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Try again.", false);
            ImGui::Text("Try again.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Close", true);
            if (ImGui::Button("Close"))
            {
                ImGui::CloseCurrentPopup();
            }

            ImGui::EndPopup();
        }
    }
    ImGui::End();
}

void CreateAccountScene::Finish()
{
    // Do nothing
}

bool CreateAccountScene::IsValidAccountInfo() const
{
    // Check email is not empty and has valid format
    const std::string email = m_email;
    const std::regex emailPattern(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    if (!std::regex_match(email, emailPattern))
    {
        return false;
    }

    // Check Nickname is not empty
    if (std::strlen(m_nickname) == 0)
    {
        return false;
    }

    // Check two passwords are not empty
    if (std::strlen(m_password1) == 0 || std::strlen(m_password2) == 0)
    {
        return false;
    }

    // Check two passwords are same
    if (std::strlen(m_password1) != std::strlen(m_password2) ||
        std::strcmp(m_password1, m_password2) != 0)
    {
        return false;
    }

    return true;
}
}<commit_msg>Fix comment<commit_after>/*************************************************************************
> File Name: CreateAccountScene.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Create account scene of Hearthstone++ GUI program.
> Created Time: 2018/06/06
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
#include <Manager/NetworkManager.h>
#include <Manager/SoundManager.h>
#include <Scenes/CreateAccountScene.h>
#include <Utils/ImGuiUtils.h>

#include <SFML/Window/Keyboard.hpp>

#include <regex>

namespace Hearthstonepp
{
void CreateAccountScene::Start()
{
    GameManager::GetInstance()->SetBackground("Background_Login.png");
    SoundManager::GetInstance()->PlayMusic("BGM_Login.ogg");

    m_flags |= ImGuiWindowFlags_NoResize;
    m_flags |= ImGuiWindowFlags_NoMove;
    m_flags |= ImGuiWindowFlags_NoCollapse;
    m_flags |= ImGuiWindowFlags_NoTitleBar;

    m_popupFlags |= ImGuiWindowFlags_AlwaysAutoResize;
    m_popupFlags |= ImGuiWindowFlags_NoTitleBar;

    m_width = GameManager::GetInstance()->GetWindowWidth() * 0.3f;
    m_height = GameManager::GetInstance()->GetWindowHeight() * 0.52f;

    m_positionX =
        GameManager::GetInstance()->GetWindowWidth() * 0.5f - m_width * 0.5f;
    m_positionY =
        GameManager::GetInstance()->GetWindowHeight() * 0.5f - m_height * 0.5f;

    memset(m_email, 0, sizeof(m_email));
    memset(m_nickname, 0, sizeof(m_nickname));
    memset(m_password1, 0, sizeof(m_password1));
    memset(m_password2, 0, sizeof(m_password2));
}

void CreateAccountScene::Input()
{
    if (GameManager::GetInstance()->HasWindowFocus())
    {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
        {
            SceneManager::GetInstance()->ChangeScene("Login");
        }
    }
}

void CreateAccountScene::Update()
{
    ImGui::SetNextWindowPos(ImVec2(m_positionX, m_positionY));
    ImGui::SetNextWindowPosCenter(true);

    ImGui::Begin("CreateAccount", &m_isOpened, ImVec2(m_width, m_height), 0.5f,
                 m_flags);
    {
        ImGui::PushItemWidth(-1);

        ImGui::SetWindowFontScale(SceneManager::GetInstance()->GetFontScale());

        // Email
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Email:");
        ImGui::InputText("##Email", m_email, IM_ARRAYSIZE(m_email));

        ImGui::NewLine();

        // Nickname
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Nickname:");
        ImGui::InputText("##Nickname", m_nickname, IM_ARRAYSIZE(m_nickname));

        ImGui::NewLine();

        // Password 1
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Password:");
        ImGui::InputText("##Password1", m_password1, IM_ARRAYSIZE(m_password1),
                         ImGuiInputTextFlags_Password);

        ImGui::NewLine();

        // Password 2
        ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), "Confirm Password:");
        ImGui::InputText("##Password2", m_password2, IM_ARRAYSIZE(m_password2),
                         ImGuiInputTextFlags_Password);

        ImGui::NewLine();

        // Create Account
        SetAlignmentHorizontalCenter("Create Account", true);
        if (ImGui::Button("Create Account"))
        {
            if (IsValidAccountInfo())
            {
                if (NetworkManager::GetInstance()->CreateAccount(
                        m_email, m_nickname, m_password1))
                {
                    ImGui::OpenPopup("CreateAccountSuccess");
                }
                else
                {
                    ImGui::OpenPopup("CreateAccountFail");
                }
            }
            else
            {
                ImGui::OpenPopup("CreateAccountFail");
            }
        }

        ImGui::NewLine();

        // Back
        SetAlignmentHorizontalCenter("Back", true);
        if (ImGui::Button("Back"))
        {
            SceneManager::GetInstance()->ChangeScene("Login");
        }

        // Popup notifying create account is success
        ImGui::SetNextWindowPosCenter(true);

        ImGui::SetWindowFontScale(SceneManager::GetInstance()->GetFontScale());

        if (ImGui::BeginPopup("CreateAccountSuccess", m_popupFlags))
        {
            ImGui::SetWindowFontScale(
                SceneManager::GetInstance()->GetFontScale());

            SetAlignmentHorizontalCenter("Create account is success.", false);
            ImGui::Text("Create account is success.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Close", true);
            if (ImGui::Button("Close"))
            {
                ImGui::CloseCurrentPopup();
                SceneManager::GetInstance()->ChangeScene("Login");
            }

            ImGui::EndPopup();
        }

        // Popup notifying create account is fail
        ImGui::SetNextWindowPosCenter(true);

        if (ImGui::BeginPopup("CreateAccountFail", m_popupFlags))
        {
            ImGui::SetWindowFontScale(
                SceneManager::GetInstance()->GetFontScale());

            SetAlignmentHorizontalCenter("Create account is failed.", false);
            ImGui::Text("Create account is failed.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Try again.", false);
            ImGui::Text("Try again.");

            ImGui::NewLine();

            SetAlignmentHorizontalCenter("Close", true);
            if (ImGui::Button("Close"))
            {
                ImGui::CloseCurrentPopup();
            }

            ImGui::EndPopup();
        }
    }
    ImGui::End();
}

void CreateAccountScene::Finish()
{
    // Do nothing
}

bool CreateAccountScene::IsValidAccountInfo() const
{
    // Check email is not empty and has valid format
    const std::string email = m_email;
    const std::regex emailPattern(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    if (!std::regex_match(email, emailPattern))
    {
        return false;
    }

    // Check Nickname is not empty
    if (std::strlen(m_nickname) == 0)
    {
        return false;
    }

    // Check two passwords are not empty
    if (std::strlen(m_password1) == 0 || std::strlen(m_password2) == 0)
    {
        return false;
    }

    // Check two passwords are same
    if (std::strlen(m_password1) != std::strlen(m_password2) ||
        std::strcmp(m_password1, m_password2) != 0)
    {
        return false;
    }

    return true;
}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VKeyColumn.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:12:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_SDBCX_KEYCOLUMN_HXX_
#include "connectivity/sdbcx/VKeyColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace cppu;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKeyColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKeyColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyColumnDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyColumn");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OKeyColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OKeyColumn::OKeyColumn(sal_Bool _bCase) : OColumn(_bCase)
{
    construct();
}
// -------------------------------------------------------------------------
OKeyColumn::OKeyColumn( const ::rtl::OUString&  _ReferencedColumn,
                        const ::rtl::OUString&  _Name,
                        const ::rtl::OUString&  _TypeName,
                        const ::rtl::OUString&  _DefaultValue,
                        sal_Int32               _IsNullable,
                        sal_Int32               _Precision,
                        sal_Int32               _Scale,
                        sal_Int32               _Type,
                        sal_Bool                _IsAutoIncrement,
                        sal_Bool                _IsRowVersion,
                        sal_Bool                _IsCurrency,
                        sal_Bool                _bCase
                        ) : OColumn(_Name,
                            _TypeName,
                            _DefaultValue,
                            _IsNullable,
                            _Precision,
                            _Scale,
                            _Type,
                            _IsAutoIncrement,
                            _IsRowVersion,
                            _IsCurrency,
                            _bCase)
                        ,   m_ReferencedColumn(_ReferencedColumn)
{
    construct();
}
// -------------------------------------------------------------------------
OKeyColumn::~OKeyColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OKeyColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
    return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OKeyColumn::getInfoHelper()
{
    return *OKeyColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OKeyColumn::construct()
{
    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RELATEDCOLUMN),   PROPERTY_ID_RELATEDCOLUMN,  nAttrib,&m_ReferencedColumn,    ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS changefileheader (1.12.216); FILE MERGED 2008/04/01 10:53:47 thb 1.12.216.2: #i85898# Stripping all external header guards 2008/03/28 15:24:40 rt 1.12.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: VKeyColumn.cxx,v $
 * $Revision: 1.13 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "connectivity/sdbcx/VKeyColumn.hxx"
#include "TConnection.hxx"

using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace cppu;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKeyColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKeyColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyColumnDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyColumn");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OKeyColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OKeyColumn::OKeyColumn(sal_Bool _bCase) : OColumn(_bCase)
{
    construct();
}
// -------------------------------------------------------------------------
OKeyColumn::OKeyColumn( const ::rtl::OUString&  _ReferencedColumn,
                        const ::rtl::OUString&  _Name,
                        const ::rtl::OUString&  _TypeName,
                        const ::rtl::OUString&  _DefaultValue,
                        sal_Int32               _IsNullable,
                        sal_Int32               _Precision,
                        sal_Int32               _Scale,
                        sal_Int32               _Type,
                        sal_Bool                _IsAutoIncrement,
                        sal_Bool                _IsRowVersion,
                        sal_Bool                _IsCurrency,
                        sal_Bool                _bCase
                        ) : OColumn(_Name,
                            _TypeName,
                            _DefaultValue,
                            _IsNullable,
                            _Precision,
                            _Scale,
                            _Type,
                            _IsAutoIncrement,
                            _IsRowVersion,
                            _IsCurrency,
                            _bCase)
                        ,   m_ReferencedColumn(_ReferencedColumn)
{
    construct();
}
// -------------------------------------------------------------------------
OKeyColumn::~OKeyColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OKeyColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
    return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OKeyColumn::getInfoHelper()
{
    return *OKeyColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OKeyColumn::construct()
{
    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RELATEDCOLUMN),   PROPERTY_ID_RELATEDCOLUMN,  nAttrib,&m_ReferencedColumn,    ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "EffekseerRenderer.PngTextureLoader.h"

#if _WIN32
#define __PNG_DDI 1
#else
#define __PNG_DDI 0
#endif

#if __PNG_DDI
#define WINVER          0x0501
#define _WIN32_WINNT    0x0501
#include <windows.h>
#include <gdiplus.h>
#else
#include <png.h>
#endif

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace EffekseerRenderer
{
#if __PNG_DDI
static Gdiplus::GdiplusStartupInput		gdiplusStartupInput;
static ULONG_PTR						gdiplusToken;
#else
static void PngReadData(png_structp png_ptr, png_bytep data, png_size_t length)
{
	(uint8_t**) d = (uint8_t**) png_get_io_ptr(png_ptr);
	memcpy(data, *d, length);
	(*d) += length;
}
#endif

std::vector<uint8_t> PngTextureLoader::textureData;
int32_t PngTextureLoader::textureWidth;
int32_t PngTextureLoader::textureHeight;

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
bool PngTextureLoader::Load(void* data, int32_t size, bool rev)
{
#if __PNG_DDI
	auto global = GlobalAlloc(GMEM_MOVEABLE,size);
	auto buf = GlobalLock(global);
	CopyMemory(buf, data, size);
	GlobalUnlock(global);
	LPSTREAM stream = NULL;
	CreateStreamOnHGlobal( global, false, &stream);
	Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromStream(stream);
	ES_SAFE_RELEASE(stream);
	GlobalFree(global);

	if( bmp != NULL && bmp->GetLastStatus() == Gdiplus::Ok )
	{
		textureWidth = bmp->GetWidth();
		textureHeight = bmp->GetHeight();
		textureData.resize(textureWidth * textureHeight * 4);

		if(rev)
		{
			for(auto y = 0; y < textureHeight; y++ )
			{
				for(auto x = 0; x < textureWidth; x++ )
				{
					Gdiplus::Color  color;
					bmp->GetPixel(x, textureHeight - y - 1, &color);

					textureData[(x + y * textureWidth) * 4 + 0] = color.GetR();
					textureData[(x + y * textureWidth) * 4 + 1] = color.GetG();
					textureData[(x + y * textureWidth) * 4 + 2] = color.GetB();
					textureData[(x + y * textureWidth) * 4 + 3] = color.GetA();
				}
			}
		}
		else
		{
			for(auto y = 0; y < textureHeight; y++ )
			{
				for(auto x = 0; x < textureWidth; x++ )
				{
					Gdiplus::Color  color;
					bmp->GetPixel(x, y, &color);

					textureData[(x + y * textureWidth) * 4 + 0] = color.GetR();
					textureData[(x + y * textureWidth) * 4 + 1] = color.GetG();
					textureData[(x + y * textureWidth) * 4 + 2] = color.GetB();
					textureData[(x + y * textureWidth) * 4 + 3] = color.GetA();
				}
			}
		}

		return true;
	}
	else
	{
		ES_SAFE_DELETE(bmp);
		return false;
	}
#else
	uint8_t* data_ = (uint8_t*) data;

	/* pngANZX\̂쐬 */
	png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	/* [hR[obN֐w */
	png_set_read_fn(png, &data_, &PngReadData);

	/* png摜\̂쐬 */
	png_infop png_info = png_create_info_struct(png);

	/* G[nhO */
	if (setjmp(png_jmpbuf(png)))
	{
		png_destroy_read_struct(&png, &png_info, NULL);
		return false;
	}

	/* IHDR`N擾 */
	png_read_info(png, png_info);

	/* RGBA8888tH[}bgɕϊ */
	if (png_info->bit_depth < 8)
	{
		png_set_packing(png);
	}
	else if (png_info->bit_depth == 16)
	{
		png_set_strip_16(png);
	}

	uint32_t pixelBytes = 4;
	switch (png_info->color_type)
	{
	case PNG_COLOR_TYPE_PALETTE:
		png_set_palette_to_rgb(png);
		pixelBytes = 4;
		break;
	case PNG_COLOR_TYPE_GRAY:
		png_set_expand_gray_1_2_4_to_8(png);
		pixelBytes = 3;
		break;
	case PNG_COLOR_TYPE_RGB:
		pixelBytes = 3;
		break;
	case PNG_COLOR_TYPE_RGBA:
		break;
	}

	uint8_t* image = new uint8_t[png_info->width * png_info->height * pixelBytes];
	uint32_t pitch = png_info->width * pixelBytes;

	/* C[Wf[^ǂݍ */

	textureWidth = png_info->width;
	textureHeight = png_info->height;
	textureData.resize(textureWidth * textureHeight * 4);

	if (rev)
	{
		for (uint32_t i = 0; i < png_info->height; i++)
		{
			png_read_row(png, &image[(png_info->height - 1 - i) * pitch], NULL);
		}
	}
	else
	{
		for (uint32_t i = 0; i < png_info->height; i++)
		{
			png_read_row(png, &image[i * pitch], NULL);
		}
	}

	if (pixelBytes == 4)
	{
		memcpy(textureData.data(), image, png_info->width * png_info->height * pixelBytes);
	}
	else
	{
		for (int32_t y = 0; y < png_info->height; y++)
		{
			for (int32_t x = 0; x < png_info->width; x++)
			{
				int32_t src = (x + y * png_info->width) * 3;
				int32_t dst = (x + y * png_info->width) * 4;
				textureData[dst + 0] = image[src + 0];
				textureData[dst + 1] = image[src + 1];
				textureData[dst + 2] = image[src + 2];
				textureData[dst + 3] = 255;
			}
		}
	}

	delete [] image;
	png_destroy_read_struct(&png, &png_info, NULL);

	return true;
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Unload()
{
	textureData.clear();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Initialize()
{
#if __PNG_DDI
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL );
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Finalize()
{
#if __PNG_DDI
	Gdiplus::GdiplusShutdown(gdiplusToken);
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
<commit_msg>コンパイルが通らなかった不具合を修正<commit_after>
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "EffekseerRenderer.PngTextureLoader.h"

#if _WIN32
#define __PNG_DDI 1
#else
#define __PNG_DDI 0
#endif

#if __PNG_DDI
#define WINVER          0x0501
#define _WIN32_WINNT    0x0501
#include <windows.h>
#include <gdiplus.h>
#else
#include <png.h>
#endif

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace EffekseerRenderer
{
#if __PNG_DDI
static Gdiplus::GdiplusStartupInput		gdiplusStartupInput;
static ULONG_PTR						gdiplusToken;
#else
static void PngReadData(png_structp png_ptr, png_bytep data, png_size_t length)
{
	uint8_t** d = (uint8_t**) png_get_io_ptr(png_ptr);
	memcpy(data, *d, length);
	(*d) += length;
}
#endif

std::vector<uint8_t> PngTextureLoader::textureData;
int32_t PngTextureLoader::textureWidth;
int32_t PngTextureLoader::textureHeight;

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
bool PngTextureLoader::Load(void* data, int32_t size, bool rev)
{
#if __PNG_DDI
	auto global = GlobalAlloc(GMEM_MOVEABLE,size);
	auto buf = GlobalLock(global);
	CopyMemory(buf, data, size);
	GlobalUnlock(global);
	LPSTREAM stream = NULL;
	CreateStreamOnHGlobal( global, false, &stream);
	Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromStream(stream);
	ES_SAFE_RELEASE(stream);
	GlobalFree(global);

	if( bmp != NULL && bmp->GetLastStatus() == Gdiplus::Ok )
	{
		textureWidth = bmp->GetWidth();
		textureHeight = bmp->GetHeight();
		textureData.resize(textureWidth * textureHeight * 4);

		if(rev)
		{
			for(auto y = 0; y < textureHeight; y++ )
			{
				for(auto x = 0; x < textureWidth; x++ )
				{
					Gdiplus::Color  color;
					bmp->GetPixel(x, textureHeight - y - 1, &color);

					textureData[(x + y * textureWidth) * 4 + 0] = color.GetR();
					textureData[(x + y * textureWidth) * 4 + 1] = color.GetG();
					textureData[(x + y * textureWidth) * 4 + 2] = color.GetB();
					textureData[(x + y * textureWidth) * 4 + 3] = color.GetA();
				}
			}
		}
		else
		{
			for(auto y = 0; y < textureHeight; y++ )
			{
				for(auto x = 0; x < textureWidth; x++ )
				{
					Gdiplus::Color  color;
					bmp->GetPixel(x, y, &color);

					textureData[(x + y * textureWidth) * 4 + 0] = color.GetR();
					textureData[(x + y * textureWidth) * 4 + 1] = color.GetG();
					textureData[(x + y * textureWidth) * 4 + 2] = color.GetB();
					textureData[(x + y * textureWidth) * 4 + 3] = color.GetA();
				}
			}
		}

		return true;
	}
	else
	{
		ES_SAFE_DELETE(bmp);
		return false;
	}
#else
	uint8_t* data_ = (uint8_t*) data;

	/* pngANZX\̂쐬 */
	png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	/* [hR[obN֐w */
	png_set_read_fn(png, &data_, &PngReadData);

	/* png摜\̂쐬 */
	png_infop png_info = png_create_info_struct(png);

	/* G[nhO */
	if (setjmp(png_jmpbuf(png)))
	{
		png_destroy_read_struct(&png, &png_info, NULL);
		return false;
	}

	/* IHDR`N擾 */
	png_read_info(png, png_info);

	/* RGBA8888tH[}bgɕϊ */
	if (png_info->bit_depth < 8)
	{
		png_set_packing(png);
	}
	else if (png_info->bit_depth == 16)
	{
		png_set_strip_16(png);
	}

	uint32_t pixelBytes = 4;
	switch (png_info->color_type)
	{
	case PNG_COLOR_TYPE_PALETTE:
		png_set_palette_to_rgb(png);
		pixelBytes = 4;
		break;
	case PNG_COLOR_TYPE_GRAY:
		png_set_expand_gray_1_2_4_to_8(png);
		pixelBytes = 3;
		break;
	case PNG_COLOR_TYPE_RGB:
		pixelBytes = 3;
		break;
	case PNG_COLOR_TYPE_RGBA:
		break;
	}

	uint8_t* image = new uint8_t[png_info->width * png_info->height * pixelBytes];
	uint32_t pitch = png_info->width * pixelBytes;

	/* C[Wf[^ǂݍ */

	textureWidth = png_info->width;
	textureHeight = png_info->height;
	textureData.resize(textureWidth * textureHeight * 4);

	if (rev)
	{
		for (uint32_t i = 0; i < png_info->height; i++)
		{
			png_read_row(png, &image[(png_info->height - 1 - i) * pitch], NULL);
		}
	}
	else
	{
		for (uint32_t i = 0; i < png_info->height; i++)
		{
			png_read_row(png, &image[i * pitch], NULL);
		}
	}

	if (pixelBytes == 4)
	{
		memcpy(textureData.data(), image, png_info->width * png_info->height * pixelBytes);
	}
	else
	{
		for (int32_t y = 0; y < png_info->height; y++)
		{
			for (int32_t x = 0; x < png_info->width; x++)
			{
				int32_t src = (x + y * png_info->width) * 3;
				int32_t dst = (x + y * png_info->width) * 4;
				textureData[dst + 0] = image[src + 0];
				textureData[dst + 1] = image[src + 1];
				textureData[dst + 2] = image[src + 2];
				textureData[dst + 3] = 255;
			}
		}
	}

	delete [] image;
	png_destroy_read_struct(&png, &png_info, NULL);

	return true;
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Unload()
{
	textureData.clear();
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Initialize()
{
#if __PNG_DDI
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL );
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void PngTextureLoader::Finalize()
{
#if __PNG_DDI
	Gdiplus::GdiplusShutdown(gdiplusToken);
#endif
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
<|endoftext|>