<commit_before>/*
    kopetefileconfirmdialog.cpp

    Copyright (c) 2003-2004 by Olivier Goffart       <ogoffart @ kde.org>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include <qtextedit.h>

#include <klineedit.h>
#include <kconfig.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kpushbutton.h>
#include <kmessagebox.h>

//#include "kopetetransfermanager.h"
#include "fileconfirmbase.h"
#include "kopetefileconfirmdialog.h"

#include "kopetemetacontact.h"
#include "kopetecontact.h"

KopeteFileConfirmDialog::KopeteFileConfirmDialog(const Kopete::FileTransferInfo &info,const QString& description,QWidget *parent, const char *name )
: KDialogBase( parent, name, false, i18n( "A User Would Like to Send You a File" ),
	KDialogBase::User1 | KDialogBase::User2, KDialogBase::User1, true, i18n( "&Refuse" ), i18n( "&Accept" ) ),
	m_info( info )
{
	setWFlags( WDestructiveClose );
	m_emited=false;

	m_view=new FileConfirmBase(this, "FileConfirmView");
	m_view->m_from->setText( info.contact()->metaContact()->displayName() + QString::fromLatin1( " <" ) +
			info.contact()->contactId() + QString::fromLatin1( "> " ) );
	m_view->m_size->setText( KGlobal::locale()->formatNumber( long( info.size() ) ) );
	m_view->m_description->setText( description );
	m_view->m_filename->setText( info.file() );

	KGlobal::config()->setGroup("File Transfer");
	const QString defaultPath=KGlobal::config()->readEntry("defaultPath" , QDir::homeDirPath() );
	m_view->m_saveto->setText(defaultPath  + QString::fromLatin1( "/" ) + info.file() );

	setMainWidget(m_view);

	connect(m_view->cmdBrowse, SIGNAL(pressed()), this, SLOT(slotBrowsePressed()));
}

KopeteFileConfirmDialog::~KopeteFileConfirmDialog()
{
}

void KopeteFileConfirmDialog::slotBrowsePressed()
{
	QString saveFileName = KFileDialog::getSaveFileName( m_view->m_saveto->text(), QString::fromLatin1( "*" ), 0L , i18n( "File Transfer" ) );
	if ( !saveFileName.isNull())
	{
		m_view->m_saveto->setText(saveFileName);
	}
}

void KopeteFileConfirmDialog::slotUser2()
{
	m_emited=true;
	KURL url(m_view->m_saveto->text());
	if(url.isValid() && url.isLocalFile() )
	{
		const QString directory=url.directory();
		if(!directory.isEmpty())
		{
			KGlobal::config()->setGroup("File Transfer");
			KGlobal::config()->writeEntry("defaultPath" , directory );
		}

		if(QFile(m_view->m_saveto->text()).exists())
		{
			int ret=KMessageBox::warningContinueCancel(this,  i18n("The file '%1' already exists.\nDo you want to overwrite it ?").arg(m_view->m_saveto->text()) ,
					 i18n("Overwrite File") , KStdGuiItem::save());
			if(ret==KMessageBox::Cancel)
				return;
		}

		emit accepted(m_info,m_view->m_saveto->text());
		close();
	}
	else
		KMessageBox::queuedMessageBox (this, KMessageBox::Sorry, i18n("You must provide a valid local filename") );
}

void KopeteFileConfirmDialog::slotUser1()
{
	m_emited=true;
	emit refused(m_info);
	close();
}

void KopeteFileConfirmDialog::closeEvent( QCloseEvent *e)
{
	if(!m_emited)
	{
		m_emited=true;
		emit refused(m_info);
	}
	KDialogBase::closeEvent(e);
}

#include "kopetefileconfirmdialog.moc"

<commit_msg>the file size is a whole number (port from 3.5 branch, revision 490969)<commit_after>/*
    kopetefileconfirmdialog.cpp

    Copyright (c) 2003-2004 by Olivier Goffart       <ogoffart @ kde.org>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include <qtextedit.h>

#include <klineedit.h>
#include <kconfig.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kpushbutton.h>
#include <kmessagebox.h>

//#include "kopetetransfermanager.h"
#include "fileconfirmbase.h"
#include "kopetefileconfirmdialog.h"

#include "kopetemetacontact.h"
#include "kopetecontact.h"

KopeteFileConfirmDialog::KopeteFileConfirmDialog(const Kopete::FileTransferInfo &info,const QString& description,QWidget *parent, const char *name )
: KDialogBase( parent, name, false, i18n( "A User Would Like to Send You a File" ),
	KDialogBase::User1 | KDialogBase::User2, KDialogBase::User1, true, i18n( "&Refuse" ), i18n( "&Accept" ) ),
	m_info( info )
{
	setWFlags( WDestructiveClose );
	m_emited=false;

	m_view=new FileConfirmBase(this, "FileConfirmView");
	m_view->m_from->setText( info.contact()->metaContact()->displayName() + QString::fromLatin1( " <" ) +
			info.contact()->contactId() + QString::fromLatin1( "> " ) );
	m_view->m_size->setText( KGlobal::locale()->formatNumber( long( info.size() ), 0 ) );
	m_view->m_description->setText( description );
	m_view->m_filename->setText( info.file() );

	KGlobal::config()->setGroup("File Transfer");
	const QString defaultPath=KGlobal::config()->readEntry("defaultPath" , QDir::homeDirPath() );
	m_view->m_saveto->setText(defaultPath  + QString::fromLatin1( "/" ) + info.file() );

	setMainWidget(m_view);

	connect(m_view->cmdBrowse, SIGNAL(pressed()), this, SLOT(slotBrowsePressed()));
}

KopeteFileConfirmDialog::~KopeteFileConfirmDialog()
{
}

void KopeteFileConfirmDialog::slotBrowsePressed()
{
	QString saveFileName = KFileDialog::getSaveFileName( m_view->m_saveto->text(), QString::fromLatin1( "*" ), 0L , i18n( "File Transfer" ) );
	if ( !saveFileName.isNull())
	{
		m_view->m_saveto->setText(saveFileName);
	}
}

void KopeteFileConfirmDialog::slotUser2()
{
	m_emited=true;
	KURL url(m_view->m_saveto->text());
	if(url.isValid() && url.isLocalFile() )
	{
		const QString directory=url.directory();
		if(!directory.isEmpty())
		{
			KGlobal::config()->setGroup("File Transfer");
			KGlobal::config()->writeEntry("defaultPath" , directory );
		}

		if(QFile(m_view->m_saveto->text()).exists())
		{
			int ret=KMessageBox::warningContinueCancel(this,  i18n("The file '%1' already exists.\nDo you want to overwrite it ?").arg(m_view->m_saveto->text()) ,
					 i18n("Overwrite File") , KStdGuiItem::save());
			if(ret==KMessageBox::Cancel)
				return;
		}

		emit accepted(m_info,m_view->m_saveto->text());
		close();
	}
	else
		KMessageBox::queuedMessageBox (this, KMessageBox::Sorry, i18n("You must provide a valid local filename") );
}

void KopeteFileConfirmDialog::slotUser1()
{
	m_emited=true;
	emit refused(m_info);
	close();
}

void KopeteFileConfirmDialog::closeEvent( QCloseEvent *e)
{
	if(!m_emited)
	{
		m_emited=true;
		emit refused(m_info);
	}
	KDialogBase::closeEvent(e);
}

#include "kopetefileconfirmdialog.moc"

<|endoftext|>


<commit_before>//
// Created by everettjf on 2017/8/4.
//

#include "LoadCommandViewNode.h"

#include "../node/loadcmd/LoadCommand_SEGMENT.h"
#include "../node/loadcmd/LoadCommand_DYLIB.h"
#include "../node/loadcmd/LoadCommand_DYLD_INFO.h"
#include "../node/loadcmd/LoadCommand_SYMTAB.h"
#include "../node/loadcmd/LoadCommand_DYSYMTAB.h"
#include "../node/loadcmd/LoadCommand_LOAD_DYLINKER.h"
#include "../node/loadcmd/LoadCommand_UUID.h"
#include "../node/loadcmd/LoadCommand_VERSION_MIN.h"
#include "../node/loadcmd/LoadCommand_SOURCE_VERSION.h"
#include "../node/loadcmd/LoadCommand_MAIN.h"
#include "../node/loadcmd/LoadCommand_ENCRYPTION_INFO.h"
#include "../node/loadcmd/LoadCommand_LINKEDIT_DATA.h"

/*
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_64)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_DYLIB, DYLIB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_WEAK_DYLIB, DYLIB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_REEXPORT_DYLIB, DYLIB)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO, DYLD_INFO)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO_ONLY, DYLD_INFO)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SYMTAB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYSYMTAB)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LOAD_DYLINKER)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_UUID)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_IPHONEOS, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_MACOSX, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_TVOS, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_WATCHOS, VERSION_MIN)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SOURCE_VERSION)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_MAIN)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO_64)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_CODE_SIGNATURE, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_SEGMENT_SPLIT_INFO, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_FUNCTION_STARTS, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DATA_IN_CODE, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLIB_CODE_SIGN_DRS, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LINKER_OPTIMIZATION_HINT, LINKEDIT_DATA)
 */

MOEX_NAMESPACE_BEGIN

std::string LoadCommandViewNode::GetDisplayName(){
    std::string charact = d_->GetShortCharacteristicDescription();
    if(charact.length() > 0){
        return boost::str(boost::format("%1%(%2%)")%d_->GetLoadCommandTypeString()%charact);
    }else{
        return d_->GetLoadCommandTypeString();
    }
}

#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN_CLASS(segment,classname) \
class LoadCommandViewNode_##segment : public LoadCommandViewNode{ \
public:\
    void InitViewDatas()override{\
        auto t = CreateTableViewDataPtr();\
        auto b = CreateBinaryViewDataPtr();\
        LoadCommand_##classname *cmd = static_cast<LoadCommand_##classname*>(d_.get());

#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN(segment) \
class LoadCommandViewNode_##segment : public LoadCommandViewNode{ \
public:\
    void InitViewDatas()override{\
        auto t = CreateTableViewDataPtr();\
        auto b = CreateBinaryViewDataPtr();\
        LoadCommand_##segment *cmd = static_cast<LoadCommand_##segment*>(d_.get());

#define IMPL_LOADCOMMAND_VIEWNODE_END\
        if(!t->IsEmpty()) AddViewData(t);\
        if(!b->IsEmpty()) AddViewData(b);\
    }\
};

#define CASE_LOADCOMMAND_VIEWNODE(segment) \
        case segment: { \
            res = std::make_shared<LoadCommandViewNode_##segment>();\
            break;\
        }

IMPL_LOADCOMMAND_VIEWNODE_BEGIN(LC_SEGMENT)

IMPL_LOADCOMMAND_VIEWNODE_END

LoadCommandViewNodePtr LoadCommandViewNodeFactory::Create(LoadCommandPtr d){
    LoadCommandViewNodePtr res;
    switch(d->GetCommand()){
        CASE_LOADCOMMAND_VIEWNODE(LC_SEGMENT)
        default:{
            res = std::make_shared<LoadCommandViewNode>();
            break;
        }
    }
    res->Init(d);
    return res;
}

MOEX_NAMESPACE_END<commit_msg>ready one<commit_after>//
// Created by everettjf on 2017/8/4.
//

#include "LoadCommandViewNode.h"

#include "../node/loadcmd/LoadCommand_SEGMENT.h"
#include "../node/loadcmd/LoadCommand_DYLIB.h"
#include "../node/loadcmd/LoadCommand_DYLD_INFO.h"
#include "../node/loadcmd/LoadCommand_SYMTAB.h"
#include "../node/loadcmd/LoadCommand_DYSYMTAB.h"
#include "../node/loadcmd/LoadCommand_LOAD_DYLINKER.h"
#include "../node/loadcmd/LoadCommand_UUID.h"
#include "../node/loadcmd/LoadCommand_VERSION_MIN.h"
#include "../node/loadcmd/LoadCommand_SOURCE_VERSION.h"
#include "../node/loadcmd/LoadCommand_MAIN.h"
#include "../node/loadcmd/LoadCommand_ENCRYPTION_INFO.h"
#include "../node/loadcmd/LoadCommand_LINKEDIT_DATA.h"

/*
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_64)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_DYLIB, DYLIB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_WEAK_DYLIB, DYLIB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_REEXPORT_DYLIB, DYLIB)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO, DYLD_INFO)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO_ONLY, DYLD_INFO)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SYMTAB)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYSYMTAB)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LOAD_DYLINKER)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_UUID)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_IPHONEOS, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_MACOSX, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_TVOS, VERSION_MIN)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_WATCHOS, VERSION_MIN)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SOURCE_VERSION)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_MAIN)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO_64)

        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_CODE_SIGNATURE, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_SEGMENT_SPLIT_INFO, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_FUNCTION_STARTS, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DATA_IN_CODE, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLIB_CODE_SIGN_DRS, LINKEDIT_DATA)
        DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LINKER_OPTIMIZATION_HINT, LINKEDIT_DATA)
 */

MOEX_NAMESPACE_BEGIN

std::string LoadCommandViewNode::GetDisplayName(){
    std::string charact = d_->GetShortCharacteristicDescription();
    if(charact.length() > 0){
        return boost::str(boost::format("%1%(%2%)")%d_->GetLoadCommandTypeString()%charact);
    }else{
        return d_->GetLoadCommandTypeString();
    }
}

#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN_CLASS(segment,classname) \
class LoadCommandViewNode_##segment : public LoadCommandViewNode{ \
public:\
    void InitViewDatas()override{\
        using namespace moex::util;\
        auto t = CreateTableViewDataPtr();\
        auto b = CreateBinaryViewDataPtr();\
        LoadCommand_##classname *c = static_cast<LoadCommand_##classname*>(d_.get());\
        t->AddRow(c->GetRAW(&(c->cmd()->cmd)),c->cmd()->cmd,"Command",c->GetLoadCommandTypeString());\
        t->AddRow(c->GetRAW(&(c->cmd()->cmdsize)),c->cmd()->cmdsize,"Command Size",AsString(c->cmd()->cmdsize));\
        t->AddSeparator();

#define IMPL_LOADCOMMAND_VIEWNODE_BEGIN(segment)\
class LoadCommandViewNode_##segment : public LoadCommandViewNode{ \
public:\
    void InitViewDatas()override{\
        using namespace moex::util;\
        auto t = CreateTableViewDataPtr();\
        auto b = CreateBinaryViewDataPtr();\
        LoadCommand_##segment *c = static_cast<LoadCommand_##segment*>(d_.get());\
        t->AddRow(c->GetRAW(&(c->cmd()->cmd)),c->cmd()->cmd,"Command",c->GetLoadCommandTypeString());\
        t->AddRow(c->GetRAW(&(c->cmd()->cmdsize)),c->cmd()->cmdsize,"Command Size",AsString(c->cmd()->cmdsize));\
        t->AddSeparator();

#define IMPL_LOADCOMMAND_VIEWNODE_END\
        if(!t->IsEmpty()) AddViewData(t);\
        if(!b->IsEmpty()) AddViewData(b);\
    }\
};

#define CASE_LOADCOMMAND_VIEWNODE(segment) \
        case segment: { \
            res = std::make_shared<LoadCommandViewNode_##segment>();\
            break;\
        }

IMPL_LOADCOMMAND_VIEWNODE_BEGIN(LC_SEGMENT)

IMPL_LOADCOMMAND_VIEWNODE_END

LoadCommandViewNodePtr LoadCommandViewNodeFactory::Create(LoadCommandPtr d){
    LoadCommandViewNodePtr res;
    switch(d->GetCommand()){
        CASE_LOADCOMMAND_VIEWNODE(LC_SEGMENT)
        default:{
            res = std::make_shared<LoadCommandViewNode>();
            break;
        }
    }
    res->Init(d);
    return res;
}

MOEX_NAMESPACE_END<|endoftext|>


<commit_before>#pragma once

#define BTS_NET_PROTOCOL_VERSION 104 // protocol version to be used in testnet3

/**
 * Define this to enable debugging code in the p2p network interface.
 * This is code that would never be executed in normal operation, but is
 * used for automated testing (creating artificial net splits,
 * tracking where messages came from and when)
 */
#define ENABLE_P2P_DEBUGGING_API 1

/**
 * 512 kb
 */
#define MAX_MESSAGE_SIZE (512*1024)
#define BTS_NET_DEFAULT_PEER_CONNECTION_RETRY_TIME  (30) // seconds

/**
 * AFter trying all peers, how long to wait before we check to
 * see if there are peers we can try again.
 */
#define BTS_PEER_DATABASE_RETRY_DELAY  (15) // seconds

#define BTS_NET_PEER_HANDSHAKE_INACTIVITY_TIMEOUT (5)

#define BTS_NET_PEER_DISCONNECT_TIMEOUT (20)

#define BTS_NETWORK_DEFAULT_P2P_PORT          8601
#define BTS_NET_DEFAULT_DESIRED_CONNECTIONS   12
#define BTS_NET_DEFAULT_MAX_CONNECTIONS       200
<commit_msg>reducing desired connection count to 8<commit_after>#pragma once

#define BTS_NET_PROTOCOL_VERSION 104 // protocol version to be used in testnet3

/**
 * Define this to enable debugging code in the p2p network interface.
 * This is code that would never be executed in normal operation, but is
 * used for automated testing (creating artificial net splits,
 * tracking where messages came from and when)
 */
#define ENABLE_P2P_DEBUGGING_API 1

/**
 * 512 kb
 */
#define MAX_MESSAGE_SIZE (512*1024)
#define BTS_NET_DEFAULT_PEER_CONNECTION_RETRY_TIME  (30) // seconds

/**
 * AFter trying all peers, how long to wait before we check to
 * see if there are peers we can try again.
 */
#define BTS_PEER_DATABASE_RETRY_DELAY  (15) // seconds

#define BTS_NET_PEER_HANDSHAKE_INACTIVITY_TIMEOUT (5)

#define BTS_NET_PEER_DISCONNECT_TIMEOUT (20)

#define BTS_NETWORK_DEFAULT_P2P_PORT          8701
#define BTS_NET_DEFAULT_DESIRED_CONNECTIONS   8
#define BTS_NET_DEFAULT_MAX_CONNECTIONS       200
<|endoftext|>


<commit_before>/**
 * @file
 * @author Alexander Sherikov
 */

#include <cmath> // sqrt

#include "WMG.h"
#include "footstep.h"

/**
 * @brief Returns index of the next SS.
 *
 * @param[in] start_ind start search from this index.
 * @param[in] type search for a footstep of certain type,
 *                 by default (FS_TYPE_AUTO) both left and right
 *                 are searched.
 *
 * @return index of the next SS.
 */
int WMG::getNextSS(const int start_ind, const fs_type type)
{
    int index = start_ind + 1;
    for (; index < (int) FS.size(); index++)
    {
        if (FS[index].type != FS_TYPE_DS)
        {
            if (type == FS_TYPE_AUTO)
            {
                break;
            }
            else
            {
                if (FS[index].type == type)
                {
                    break;
                }
            }
        }
    }
    return (index);
}

/**
 * @brief Returns index of the previous SS.
 *
 * @param[in] start_ind start search from this index.
 * @param[in] type search for a footstep of certain type,
 *                 by default (FS_TYPE_AUTO) both left and right
 *                 are searched.
 *
 * @return index of the previous SS.
 */
int WMG::getPrevSS(const int start_ind, const fs_type type)
{
    int index = start_ind - 1;
    for (; index >= 0; index--)
    {
        if (FS[index].type != FS_TYPE_DS)
        {
            if (type == FS_TYPE_AUTO)
            {
                break;
            }
            else
            {
                if (FS[index].type == type)
                {
                    break;
                }
            }
        }
    }
    return (index);
}

/**
 * @brief Determine position and orientation of feet in DS
 *
 * @param[in] support_number number of the support
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getDSFeetPositions (
        const int support_number,
        double *left_foot_pos,
        double *right_foot_pos)
{
    int left_ind, right_ind;

    left_ind = getNextSS (support_number);
    if (FS[left_ind].type == FS_TYPE_SS_L)
    {
        right_ind = getPrevSS (support_number);
    }
    else
    {
        right_ind = left_ind;
        left_ind = getPrevSS (support_number);
    }

    Matrix4d::Map(left_foot_pos) = FS[left_ind].posture->matrix();
    Matrix4d::Map(right_foot_pos) = FS[right_ind].posture->matrix();
}

/**
 * @brief Determine position and orientation of feet (parabolic trajectory)
 *
 * @param[in] support_number number of the support
 * @param[in] theta a number between 0 and 1, a fraction of support time that have passed
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getSSFeetPositions (
        const int support_number,
        const double theta,
        double *left_foot_pos,
        double *right_foot_pos)
{
    double *swing_foot_pos, *ref_foot_pos;
    int next_swing_ind, prev_swing_ind;
    footstep& current_step = FS[support_number];

    if (current_step.type == FS_TYPE_SS_L)
    {
        ref_foot_pos = left_foot_pos;
        swing_foot_pos = right_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);
    }
    else
    {
        ref_foot_pos = right_foot_pos;
        swing_foot_pos = left_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);
    }

    Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();

    double dx = FS[next_swing_ind].x() - FS[prev_swing_ind].x();
    double dy = FS[next_swing_ind].y() - FS[prev_swing_ind].y();
    double l = sqrt(dx*dx + dy*dy);

    double x[3] = {0.0, l/2, l};
    double b_coef = - (x[2]*x[2] /*- x[0]*x[0]*/)/(x[2] /*- x[0]*/);
    double a = step_height / (x[1]*x[1] /*- x[0]*x[0]*/ + b_coef*(x[1] /*- x[0]*/));
    double b = a * b_coef;
    //double c = - a*x[0]*x[0] - b*x[0];

    double dl = /*(1-theta)*x[0] +*/ theta * l;

    Matrix4d::Map(swing_foot_pos) = (
            (*FS[prev_swing_ind].posture)
          * Translation<double, 3>(theta * dx, theta * dy, a*dl*dl + b*dl)
          * AngleAxisd(FS[next_swing_ind].angle - FS[prev_swing_ind].angle, Vector3d::UnitZ())
            ).matrix();
}

/**
 * @brief Determine position and orientation of feet (using cubic Bezier curves)
 *
 * @param[in] support_number number of the support
 * @param[in] theta a number between 0 and 1, a fraction of support time that have passed
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getSSFeetPositionsBezier (
        const int support_number,
        const double theta,
        double *left_foot_pos,
        double *right_foot_pos)
{
    double *swing_foot_pos, *ref_foot_pos;
    int next_swing_ind, prev_swing_ind;
    int inclination_sign = 0;
    footstep& current_step = FS[support_number];

    if (current_step.type == FS_TYPE_SS_L)
    {
        inclination_sign = -1;

        ref_foot_pos = left_foot_pos;
        swing_foot_pos = right_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);
    }
    else
    {
        inclination_sign = 1;

        ref_foot_pos = right_foot_pos;
        swing_foot_pos = left_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);
    }

    Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();

    Vector4d weighted_binomial_coef;
    // Note, that since we want to obtain a curve of a certain height (see below),
    // the weights have a rather limited impact. They may be useful in future, though.
    double w1 = 1.0;
    double w2 = 2.5;
    // first number is the weight
    weighted_binomial_coef(0) = 1  * (1-theta)*(1-theta)*(1-theta);
    weighted_binomial_coef(1) = w1 * 3*(1-theta)*(1-theta)*theta;
    weighted_binomial_coef(2) = w2 * 3*(1-theta)*theta*theta;
    weighted_binomial_coef(3) = 1  * theta*theta*theta;

    Matrix<double, 3, 4> control_points;
    control_points.col(0) = FS[prev_swing_ind].posture->translation();
    control_points.col(3) = FS[next_swing_ind].posture->translation();

    // In order to reach step_height on z axis in the middle of trajectory,
    // z coordinates for these  two points are derived as follows:
    //
    // S = sum of weighted binomial coefficients
    // 0.5^3 * w0*z0  +  3*0.5^3 * w1*z1  +  3*0.5^3 * w2*z2  +  0.5^3 * w3*z3 = step_height * S
    //           =0                                                      =0
    // 3*0.5^3 * (w1*z1 + w2*z2) = step_height * S
    //
    // lets take z1=z2=z, then:
    //
    // z = step_height * S / (3*0.5^3 * (w1+w2))
    control_points.col(1)      = control_points.col(0);
    control_points.col(1).y() += inclination_sign * step_height/2;
    control_points.col(1).z()  = step_height*weighted_binomial_coef.sum() / (3*0.5*0.5*0.5 * (w1+w2));
    control_points.col(2)      = control_points.col(3);
    control_points.col(2).z()  = control_points.col(1).z();

    Transform<double, 3> swing_posture =
        Translation<double,3>(
                control_points * weighted_binomial_coef / weighted_binomial_coef.sum())
        *
        Quaterniond (AngleAxisd (FS[prev_swing_ind].angle,Vector3d::UnitZ())).slerp (
                theta,
                Quaterniond (AngleAxisd (FS[next_swing_ind].angle,Vector3d::UnitZ())));

    Matrix4d::Map(swing_foot_pos) = swing_posture.matrix();
}
<commit_msg>Foot trajectory: changed parameters of Bezier curve.<commit_after>/**
 * @file
 * @author Alexander Sherikov
 */

#include <cmath> // sqrt

#include "WMG.h"
#include "footstep.h"

/**
 * @brief Returns index of the next SS.
 *
 * @param[in] start_ind start search from this index.
 * @param[in] type search for a footstep of certain type,
 *                 by default (FS_TYPE_AUTO) both left and right
 *                 are searched.
 *
 * @return index of the next SS.
 */
int WMG::getNextSS(const int start_ind, const fs_type type)
{
    int index = start_ind + 1;
    for (; index < (int) FS.size(); index++)
    {
        if (FS[index].type != FS_TYPE_DS)
        {
            if (type == FS_TYPE_AUTO)
            {
                break;
            }
            else
            {
                if (FS[index].type == type)
                {
                    break;
                }
            }
        }
    }
    return (index);
}

/**
 * @brief Returns index of the previous SS.
 *
 * @param[in] start_ind start search from this index.
 * @param[in] type search for a footstep of certain type,
 *                 by default (FS_TYPE_AUTO) both left and right
 *                 are searched.
 *
 * @return index of the previous SS.
 */
int WMG::getPrevSS(const int start_ind, const fs_type type)
{
    int index = start_ind - 1;
    for (; index >= 0; index--)
    {
        if (FS[index].type != FS_TYPE_DS)
        {
            if (type == FS_TYPE_AUTO)
            {
                break;
            }
            else
            {
                if (FS[index].type == type)
                {
                    break;
                }
            }
        }
    }
    return (index);
}

/**
 * @brief Determine position and orientation of feet in DS
 *
 * @param[in] support_number number of the support
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getDSFeetPositions (
        const int support_number,
        double *left_foot_pos,
        double *right_foot_pos)
{
    int left_ind, right_ind;

    left_ind = getNextSS (support_number);
    if (FS[left_ind].type == FS_TYPE_SS_L)
    {
        right_ind = getPrevSS (support_number);
    }
    else
    {
        right_ind = left_ind;
        left_ind = getPrevSS (support_number);
    }

    Matrix4d::Map(left_foot_pos) = FS[left_ind].posture->matrix();
    Matrix4d::Map(right_foot_pos) = FS[right_ind].posture->matrix();
}

/**
 * @brief Determine position and orientation of feet (parabolic trajectory)
 *
 * @param[in] support_number number of the support
 * @param[in] theta a number between 0 and 1, a fraction of support time that have passed
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getSSFeetPositions (
        const int support_number,
        const double theta,
        double *left_foot_pos,
        double *right_foot_pos)
{
    double *swing_foot_pos, *ref_foot_pos;
    int next_swing_ind, prev_swing_ind;
    footstep& current_step = FS[support_number];

    if (current_step.type == FS_TYPE_SS_L)
    {
        ref_foot_pos = left_foot_pos;
        swing_foot_pos = right_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);
    }
    else
    {
        ref_foot_pos = right_foot_pos;
        swing_foot_pos = left_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);
    }

    Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();

    double dx = FS[next_swing_ind].x() - FS[prev_swing_ind].x();
    double dy = FS[next_swing_ind].y() - FS[prev_swing_ind].y();
    double l = sqrt(dx*dx + dy*dy);

    double x[3] = {0.0, l/2, l};
    double b_coef = - (x[2]*x[2] /*- x[0]*x[0]*/)/(x[2] /*- x[0]*/);
    double a = step_height / (x[1]*x[1] /*- x[0]*x[0]*/ + b_coef*(x[1] /*- x[0]*/));
    double b = a * b_coef;
    //double c = - a*x[0]*x[0] - b*x[0];

    double dl = /*(1-theta)*x[0] +*/ theta * l;

    Matrix4d::Map(swing_foot_pos) = (
            (*FS[prev_swing_ind].posture)
          * Translation<double, 3>(theta * dx, theta * dy, a*dl*dl + b*dl)
          * AngleAxisd(FS[next_swing_ind].angle - FS[prev_swing_ind].angle, Vector3d::UnitZ())
            ).matrix();
}

/**
 * @brief Determine position and orientation of feet (using cubic Bezier curves)
 *
 * @param[in] support_number number of the support
 * @param[in] theta a number between 0 and 1, a fraction of support time that have passed
 * @param[out] left_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 * @param[out] right_foot_pos 4x4 homogeneous matrix, which represents position and orientation
 */
void WMG::getSSFeetPositionsBezier (
        const int support_number,
        const double theta,
        double *left_foot_pos,
        double *right_foot_pos)
{
    double *swing_foot_pos, *ref_foot_pos;
    int next_swing_ind, prev_swing_ind;
    int inclination_sign = 0;
    footstep& current_step = FS[support_number];

    if (current_step.type == FS_TYPE_SS_L)
    {
        inclination_sign = -1;

        ref_foot_pos = left_foot_pos;
        swing_foot_pos = right_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_R);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_R);
    }
    else
    {
        inclination_sign = 1;

        ref_foot_pos = right_foot_pos;
        swing_foot_pos = left_foot_pos;

        prev_swing_ind = getPrevSS (support_number, FS_TYPE_SS_L);
        next_swing_ind = getNextSS (support_number, FS_TYPE_SS_L);
    }

    Matrix4d::Map(ref_foot_pos) = current_step.posture->matrix();

    Vector4d weighted_binomial_coef;
    // Note, that since we want to obtain a curve of a certain height (see below),
    // the weights have a rather limited impact. They may be useful in future, though.
    double w1 = 1.0;
    double w2 = 2.0;
    // first number is the weight
    weighted_binomial_coef(0) = 1  * (1-theta)*(1-theta)*(1-theta);
    weighted_binomial_coef(1) = w1 * 3*(1-theta)*(1-theta)*theta;
    weighted_binomial_coef(2) = w2 * 3*(1-theta)*theta*theta;
    weighted_binomial_coef(3) = 1  * theta*theta*theta;

    Matrix<double, 3, 4> control_points;
    control_points.col(0) = FS[prev_swing_ind].posture->translation();
    control_points.col(3) = FS[next_swing_ind].posture->translation();

    // In order to reach step_height on z axis in the middle of trajectory,
    // z coordinates for these  two points are derived as follows:
    //
    // S = sum of weighted binomial coefficients
    // 0.5^3 * w0*z0  +  3*0.5^3 * w1*z1  +  3*0.5^3 * w2*z2  +  0.5^3 * w3*z3 = step_height * S
    //           =0                                                      =0
    // 3*0.5^3 * (w1*z1 + w2*z2) = step_height * S
    //
    // lets take z1=z2=z, then:
    //
    // z = step_height * S / (3*0.5^3 * (w1+w2))
    control_points.col(1)      = control_points.col(0);
    control_points.col(1).y() += inclination_sign * step_height/1.5;
    control_points.col(1).z()  = step_height*weighted_binomial_coef.sum() / (3*0.5*0.5*0.5 * (w1+w2));
    control_points.col(2)      = control_points.col(3);
    control_points.col(2).z()  = control_points.col(1).z();

    Transform<double, 3> swing_posture =
        Translation<double,3>(
                control_points * weighted_binomial_coef / weighted_binomial_coef.sum())
        *
        Quaterniond (AngleAxisd (FS[prev_swing_ind].angle,Vector3d::UnitZ())).slerp (
                theta,
                Quaterniond (AngleAxisd (FS[next_swing_ind].angle,Vector3d::UnitZ())));

    Matrix4d::Map(swing_foot_pos) = swing_posture.matrix();
}
<|endoftext|>


<commit_before>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include "SunCamera.h"
#include <lua.hpp>
#include <selene.h>

SunCamera::SunCamera() {

}

SunCamera::SunCamera(GLfloat _FOV) {
    SunCamera();
    FOV = _FOV;
}

SunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position) {
    SunCamera();
    FOV = _FOV;
    position = _position;
}

SunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position, glm::vec3 _direction) {
    SunCamera();
    FOV = _FOV;
    position = _position;
    direction = _direction;
}

void SunCamera::init() {
    //loadFile("../../Engine/Scripts/SunCamera.lua");
	setIgnoreTags(true);
	addAction("update", &SunCamera::update);
	addAction("uniform", &SunCamera::uniform);
}

void SunCamera::uniform(SunAction action) {
	passPerFrameUniforms(action.getParameterPointer<SunShader>("shader"));
}

void SunCamera::update(SunAction action) {
	double delta = ((SunWindowManager *)getService("window_manager"))->getDelta();

	glm::vec2 mouse = ((SunCursorManager *)getService("cursor_manager"))->getCursorPosition();
    static glm::vec2 oldMouse;
    glm::vec2 offset = glm::vec2(mouse.x - oldMouse.x, oldMouse.y - mouse.y);
    oldMouse = mouse;

    const float sensitivity = 0.1f;
    offset *= sensitivity;
    yaw += offset.x;
    pitch += offset.y;

    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;

    float speed = 5.0f;
    float finalSpeed = speed * delta;
	SunKeyboardManager *keyboard = (SunKeyboardManager *)getService("keyboard_manager");
    if (keyboard->pollKey(GLFW_KEY_UP) == SunButtonStateDown)
        position += finalSpeed * direction;
    if (keyboard->pollKey(GLFW_KEY_DOWN) == SunButtonStateDown)
        position += finalSpeed * -direction;
    if (keyboard->pollKey(GLFW_KEY_RIGHT) == SunButtonStateDown)
        position += finalSpeed * glm::normalize(glm::cross(direction, cameraUp));
    if (keyboard->pollKey(GLFW_KEY_LEFT) == SunButtonStateDown)
        position += finalSpeed * -glm::normalize(glm::cross(direction, cameraUp));
    if (keyboard->pollKey(GLFW_KEY_SPACE) == SunButtonStateDown)
        position += finalSpeed * glm::vec3(0.0f, 1.0f, 0.0f);
    if (keyboard->pollKey(GLFW_KEY_LEFT_SHIFT) == SunButtonStateDown)
        position += finalSpeed * -glm::vec3(0.0f, 1.0f, 0.0f);

    direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));
    direction.y = sin(glm::radians(pitch));
    direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
}

glm::mat4 SunCamera::viewMatrix() {
    // Recalculate the camera's right and the camera's up
    cameraRight = glm::normalize(glm::cross(up, direction));
    cameraUp = glm::normalize(glm::cross(direction, cameraRight));

    // Create the view matrix for the camera's position and direction
    glm::mat4 matrix = glm::lookAt(position, position + direction, cameraUp);
    return matrix;
}

glm::mat4 SunCamera::projectionMatrix(GLfloat _aspectRatio) {
    // Create the projection matrix
    glm::mat4 matrix;

    // Check the type of projection
    matrix = glm::perspective(FOV, _aspectRatio, 0.01f, 100.0f);

    return matrix;
}

void SunCamera::passPerFrameUniforms(SunShader *_shader) {
    glUniform3f(_shader->getUniformLocation("viewPosition"), position.x, position.y, position.z);

    // Pass the view and projection matrices to the shader
    GLint viewMatrixLocation = _shader->getUniformLocation("view");
    glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix()));

    GLint projectionMatrixLocation = _shader->getUniformLocation("projection");
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix(800.0f / 600.0f)));
    GLint FOVlocation = _shader->getUniformLocation("camera.FOV");
    GLint nearPlaneLocation = _shader->getUniformLocation("camera.nearPlane");
    GLint farPlaneLocation = _shader->getUniformLocation("camera.farPlane");

    glUniform1f(FOVlocation, FOV);
    glUniform1f(nearPlaneLocation, 0.01f);
    glUniform1f(farPlaneLocation, 100.0f);
}
<commit_msg>Removed an include to selene<commit_after>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include "SunCamera.h"
#include <lua.hpp>

SunCamera::SunCamera() {

}

SunCamera::SunCamera(GLfloat _FOV) {
    SunCamera();
    FOV = _FOV;
}

SunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position) {
    SunCamera();
    FOV = _FOV;
    position = _position;
}

SunCamera::SunCamera(GLfloat _FOV, glm::vec3 _position, glm::vec3 _direction) {
    SunCamera();
    FOV = _FOV;
    position = _position;
    direction = _direction;
}

void SunCamera::init() {
    //loadFile("../../Engine/Scripts/SunCamera.lua");
	setIgnoreTags(true);
	addAction("update", &SunCamera::update);
	addAction("uniform", &SunCamera::uniform);
}

void SunCamera::uniform(SunAction action) {
	passPerFrameUniforms(action.getParameterPointer<SunShader>("shader"));
}

void SunCamera::update(SunAction action) {
	double delta = ((SunWindowManager *)getService("window_manager"))->getDelta();

	glm::vec2 mouse = ((SunCursorManager *)getService("cursor_manager"))->getCursorPosition();
    static glm::vec2 oldMouse;
    glm::vec2 offset = glm::vec2(mouse.x - oldMouse.x, oldMouse.y - mouse.y);
    oldMouse = mouse;

    const float sensitivity = 0.1f;
    offset *= sensitivity;
    yaw += offset.x;
    pitch += offset.y;

    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;

    float speed = 5.0f;
    float finalSpeed = speed * delta;
	SunKeyboardManager *keyboard = (SunKeyboardManager *)getService("keyboard_manager");
    if (keyboard->pollKey(GLFW_KEY_UP) == SunButtonStateDown)
        position += finalSpeed * direction;
    if (keyboard->pollKey(GLFW_KEY_DOWN) == SunButtonStateDown)
        position += finalSpeed * -direction;
    if (keyboard->pollKey(GLFW_KEY_RIGHT) == SunButtonStateDown)
        position += finalSpeed * glm::normalize(glm::cross(direction, cameraUp));
    if (keyboard->pollKey(GLFW_KEY_LEFT) == SunButtonStateDown)
        position += finalSpeed * -glm::normalize(glm::cross(direction, cameraUp));
    if (keyboard->pollKey(GLFW_KEY_SPACE) == SunButtonStateDown)
        position += finalSpeed * glm::vec3(0.0f, 1.0f, 0.0f);
    if (keyboard->pollKey(GLFW_KEY_LEFT_SHIFT) == SunButtonStateDown)
        position += finalSpeed * -glm::vec3(0.0f, 1.0f, 0.0f);

    direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));
    direction.y = sin(glm::radians(pitch));
    direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
}

glm::mat4 SunCamera::viewMatrix() {
    // Recalculate the camera's right and the camera's up
    cameraRight = glm::normalize(glm::cross(up, direction));
    cameraUp = glm::normalize(glm::cross(direction, cameraRight));

    // Create the view matrix for the camera's position and direction
    glm::mat4 matrix = glm::lookAt(position, position + direction, cameraUp);
    return matrix;
}

glm::mat4 SunCamera::projectionMatrix(GLfloat _aspectRatio) {
    // Create the projection matrix
    glm::mat4 matrix;

    // Check the type of projection
    matrix = glm::perspective(FOV, _aspectRatio, 0.01f, 100.0f);

    return matrix;
}

void SunCamera::passPerFrameUniforms(SunShader *_shader) {
    glUniform3f(_shader->getUniformLocation("viewPosition"), position.x, position.y, position.z);

    // Pass the view and projection matrices to the shader
    GLint viewMatrixLocation = _shader->getUniformLocation("view");
    glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix()));

    GLint projectionMatrixLocation = _shader->getUniformLocation("projection");
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix(800.0f / 600.0f)));
    GLint FOVlocation = _shader->getUniformLocation("camera.FOV");
    GLint nearPlaneLocation = _shader->getUniformLocation("camera.nearPlane");
    GLint farPlaneLocation = _shader->getUniformLocation("camera.farPlane");

    glUniform1f(FOVlocation, FOV);
    glUniform1f(nearPlaneLocation, 0.01f);
    glUniform1f(farPlaneLocation, 100.0f);
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include <stdarg.h>

#include "core/strings/stringFunctions.h"
#include "console/console.h"

//-------------------------------------- STATIC Declaration
PlatformAssert *PlatformAssert::platformAssert = NULL;

//--------------------------------------
PlatformAssert::PlatformAssert()
{
   processing = false;
   ignoreAll = false;
}

//--------------------------------------
PlatformAssert::~PlatformAssert()
{
}

//--------------------------------------
void PlatformAssert::create( PlatformAssert* newAssertClass )
{
   if (!platformAssert)
      platformAssert = newAssertClass ? newAssertClass : new PlatformAssert;
}

//--------------------------------------
void PlatformAssert::destroy()
{
   if (platformAssert)
      delete platformAssert;
   platformAssert = NULL;
}

//--------------------------------------
bool PlatformAssert::displayMessageBox(const char *title, const char *message, bool retry)
{
   if (retry)
      return Platform::AlertRetry(title, message);

   Platform::AlertOK(title, message);
   return false;
}

static const char *typeName[] = { "Unknown", "Fatal-ISV", "Fatal", "Warning" };
//------------------------------------------------------------------------------
static bool askToEnterDebugger(const char* message )
{
   static bool haveAsked = false;
   static bool useDebugger = true;
   if(!haveAsked )
   {
      static char tempBuff[1024];
      dSprintf( tempBuff, 1024, "Torque has encountered an assertion with message\n\n"
         "%s\n\n"
         "Would you like to use the debugger? If you cancel, you won't be asked"
         " again until you restart Torque.", message);

      useDebugger = Platform::AlertOKCancel("Use debugger?", tempBuff );
      haveAsked = true;
   }
   return useDebugger;
}

//--------------------------------------

bool PlatformAssert::process(Type         assertType,
                             const char  *filename,
                             U32          lineNumber,
                             const char  *message)
{
    // If we're somehow recursing, just die.
    if(processing)
        Platform::debugBreak();

    processing = true;
    bool ret = false;

    // always dump to the Assert to the Console
    if (Con::isActive())
    {
        if (assertType == Warning)
            Con::warnf(ConsoleLogEntry::Assert, "%s(%ld,0): {%s} - %s", filename, lineNumber, typeName[assertType], message);
        else
            Con::errorf(ConsoleLogEntry::Assert, "%s(%ld,0): {%s} - %s", filename, lineNumber, typeName[assertType], message);
    }

    // if not a WARNING pop-up a dialog box
    if (assertType != Warning)
    {
        // used for processing navGraphs (an assert won't botch the whole build)
        if(Con::getBoolVariable("$FP::DisableAsserts", false) == true)
            Platform::forceShutdown(1);

        char buffer[2048];
        dSprintf(buffer, 2048, "%s: (%s @ %ld)", typeName[assertType], filename, lineNumber);
        if( !ignoreAll )
        {
            // Display message box with Debug, Ignore, Ignore All, and Exit options
            switch( Platform::AlertAssert(buffer, message) )
            {
                case Platform::ALERT_ASSERT_DEBUG:
                    ret = true;
                    break;
                case Platform::ALERT_ASSERT_IGNORE:
                    ret = false;
                    break;
                case Platform::ALERT_ASSERT_IGNORE_ALL:
                    ignoreAll = true;
                    ret = false;
                    break;
                default:
                case Platform::ALERT_ASSERT_EXIT:
                    Platform::forceShutdown(1);
                    break;
            }
        }
    }

    processing = false;

    return ret;
}

bool PlatformAssert::processingAssert()
{
   return platformAssert ? platformAssert->processing : false;
}

//--------------------------------------
bool PlatformAssert::processAssert(Type        assertType,
                                   const char  *filename,
                                   U32         lineNumber,
                                   const char  *message)
{
   if (platformAssert)
      return platformAssert->process(assertType, filename, lineNumber, message);
   else // when platAssert NULL (during _start/_exit) try direct output...
      dPrintf("\n%s: (%s @ %ld) %s\n", typeName[assertType], filename, lineNumber, message);

   // this could also be platform-specific: OutputDebugString on PC, DebugStr on Mac.
   // Will raw printfs do the job?  In the worst case, it's a break-pointable line of code.
   // would have preferred Con but due to race conditions, it might not be around...
   // Con::errorf(ConsoleLogEntry::Assert, "%s: (%s @ %ld) %s", typeName[assertType], filename, lineNumber, message);

   return true;
}

//--------------------------------------
const char* avar(const char *message, ...)
{
   static char buffer[4096];
   va_list args;
   va_start(args, message);
   dVsprintf(buffer, sizeof(buffer), message, args);
   return( buffer );
}

//-----------------------------------------------------------------------------

ConsoleFunction( Assert, void, 3, 3, "(condition, message) - Fatal Script Assertion" )
{
    // Process Assertion.
    AssertISV( dAtob(argv[1]), argv[2] );
}
<commit_msg>Remove dead function<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include <stdarg.h>

#include "core/strings/stringFunctions.h"
#include "console/console.h"

//-------------------------------------- STATIC Declaration
PlatformAssert *PlatformAssert::platformAssert = NULL;

//--------------------------------------
PlatformAssert::PlatformAssert()
{
   processing = false;
   ignoreAll = false;
}

//--------------------------------------
PlatformAssert::~PlatformAssert()
{
}

//--------------------------------------
void PlatformAssert::create( PlatformAssert* newAssertClass )
{
   if (!platformAssert)
      platformAssert = newAssertClass ? newAssertClass : new PlatformAssert;
}

//--------------------------------------
void PlatformAssert::destroy()
{
   if (platformAssert)
      delete platformAssert;
   platformAssert = NULL;
}

//--------------------------------------
bool PlatformAssert::displayMessageBox(const char *title, const char *message, bool retry)
{
   if (retry)
      return Platform::AlertRetry(title, message);

   Platform::AlertOK(title, message);
   return false;
}

static const char *typeName[] = { "Unknown", "Fatal-ISV", "Fatal", "Warning" };

//--------------------------------------

bool PlatformAssert::process(Type         assertType,
                             const char  *filename,
                             U32          lineNumber,
                             const char  *message)
{
    // If we're somehow recursing, just die.
    if(processing)
        Platform::debugBreak();

    processing = true;
    bool ret = false;

    // always dump to the Assert to the Console
    if (Con::isActive())
    {
        if (assertType == Warning)
            Con::warnf(ConsoleLogEntry::Assert, "%s(%ld,0): {%s} - %s", filename, lineNumber, typeName[assertType], message);
        else
            Con::errorf(ConsoleLogEntry::Assert, "%s(%ld,0): {%s} - %s", filename, lineNumber, typeName[assertType], message);
    }

    // if not a WARNING pop-up a dialog box
    if (assertType != Warning)
    {
        // used for processing navGraphs (an assert won't botch the whole build)
        if(Con::getBoolVariable("$FP::DisableAsserts", false) == true)
            Platform::forceShutdown(1);

        char buffer[2048];
        dSprintf(buffer, 2048, "%s: (%s @ %ld)", typeName[assertType], filename, lineNumber);
        if( !ignoreAll )
        {
            // Display message box with Debug, Ignore, Ignore All, and Exit options
            switch( Platform::AlertAssert(buffer, message) )
            {
                case Platform::ALERT_ASSERT_DEBUG:
                    ret = true;
                    break;
                case Platform::ALERT_ASSERT_IGNORE:
                    ret = false;
                    break;
                case Platform::ALERT_ASSERT_IGNORE_ALL:
                    ignoreAll = true;
                    ret = false;
                    break;
                default:
                case Platform::ALERT_ASSERT_EXIT:
                    Platform::forceShutdown(1);
                    break;
            }
        }
    }

    processing = false;

    return ret;
}

bool PlatformAssert::processingAssert()
{
   return platformAssert ? platformAssert->processing : false;
}

//--------------------------------------
bool PlatformAssert::processAssert(Type        assertType,
                                   const char  *filename,
                                   U32         lineNumber,
                                   const char  *message)
{
   if (platformAssert)
      return platformAssert->process(assertType, filename, lineNumber, message);
   else // when platAssert NULL (during _start/_exit) try direct output...
      dPrintf("\n%s: (%s @ %ld) %s\n", typeName[assertType], filename, lineNumber, message);

   // this could also be platform-specific: OutputDebugString on PC, DebugStr on Mac.
   // Will raw printfs do the job?  In the worst case, it's a break-pointable line of code.
   // would have preferred Con but due to race conditions, it might not be around...
   // Con::errorf(ConsoleLogEntry::Assert, "%s: (%s @ %ld) %s", typeName[assertType], filename, lineNumber, message);

   return true;
}

//--------------------------------------
const char* avar(const char *message, ...)
{
   static char buffer[4096];
   va_list args;
   va_start(args, message);
   dVsprintf(buffer, sizeof(buffer), message, args);
   return( buffer );
}

//-----------------------------------------------------------------------------

ConsoleFunction( Assert, void, 3, 3, "(condition, message) - Fatal Script Assertion" )
{
    // Process Assertion.
    AssertISV( dAtob(argv[1]), argv[2] );
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 The Regents of The University of Michigan
 * 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 holders 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.
 *
 * Authors: Korey Sewell
 *
 */

#ifndef __CPU_INORDER_RESOURCE_SKED_HH__
#define __CPU_INORDER_RESOURCE_SKED_HH__

#include <vector>
#include <list>

class ScheduleEntry {
  public:
    ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,
                  int _idx = 0) :
        stageNum(stage_num), resNum(res_num), cmd(_cmd),
        idx(_idx), priority(_priority)
    { }

    // Stage number to perform this service.
    int stageNum;

    // Resource ID to access
    int resNum;

    // See specific resource for meaning
    unsigned cmd;

    // See specific resource for meaning
    unsigned idx;

    // Some Resources May Need Priority
    int priority;
};

class ResourceSked {
  public:
    typedef std::list<ScheduleEntry*>::iterator SkedIt;

    ResourceSked();

    void init();

    int size();
    bool empty();
    ScheduleEntry* top();
    void pop();
    void push(ScheduleEntry* sked_entry);
    void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);
    void print();

  private:
    SkedIt curSkedEntry;
    std::vector<std::list<ScheduleEntry*> > sked;

    SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);
    SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,
                             int sked_cmd, int sked_cmd_idx = -1);
};

#endif //__CPU_INORDER_RESOURCE_SKED_HH__
<commit_msg>inorder: comments for resource sked class<commit_after>/*
 * Copyright (c) 2010 The Regents of The University of Michigan
 * 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 holders 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.
 *
 * Authors: Korey Sewell
 *
 */

#ifndef __CPU_INORDER_RESOURCE_SKED_HH__
#define __CPU_INORDER_RESOURCE_SKED_HH__

#include <vector>
#include <list>

/** ScheduleEntry class represents a single function that an instruction
    wants to do at any pipeline stage. For example, if an instruction
    needs to be decoded and do a branch prediction all in one stage
    then each of those tasks would need it's own ScheduleEntry.

    Each schedule entry corresponds to some resource that the instruction
    wants to interact with.

    The file pipeline_traits.cc shows how a typical instruction schedule is
    made up of these schedule entries.
*/
class ScheduleEntry {
  public:
    ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,
                  int _idx = 0) :
        stageNum(stage_num), resNum(res_num), cmd(_cmd),
        idx(_idx), priority(_priority)
    { }

    /** Stage number to perform this service. */
    int stageNum;

    /** Resource ID to access */
    int resNum;

    /** See specific resource for meaning */
    unsigned cmd;

    /** See specific resource for meaning */
    unsigned idx;

    /** Some Resources May Need Priority */
    int priority;
};

/** The ResourceSked maintains the complete schedule
    for an instruction. That schedule includes what
    resources an instruction wants to acquire at each
    pipeline stage and is represented by a collection
    of ScheduleEntry objects (described above) that
    must be executed in-order.

    In every pipeline stage, the InOrder model will
    process all entries on the resource schedule for
    that stage and then send the instruction to the next
    stage if and only if the instruction successfully
    completed each ScheduleEntry.
*/
class ResourceSked {
  public:
    typedef std::list<ScheduleEntry*>::iterator SkedIt;

    ResourceSked();

    /** Initializee the current entry pointer to
        pipeline stage 0 and the 1st schedule entry
    */
    void init();

    /** Goes through the remaining stages on the schedule
        and sums all the remaining entries left to be
        processed
    */
    int size();

    /** Is the schedule empty? */
    bool empty();

    /** What is the next task for this instruction schedule? */
    ScheduleEntry* top();

    /** Top() Task is completed, remove it from schedule */
    void pop();

    /** Add To Schedule based on stage num and priority of
        Schedule Entry
    */
    void push(ScheduleEntry* sked_entry);

    /** Add Schedule Entry to be in front of another Entry */
    void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);

    /** Print what's left on the instruction schedule */
    void print();

  private:
    /** Current Schedule Entry Pointer */
    SkedIt curSkedEntry;

    /** The Resource Schedule: Resized to Number of Stages in
        the constructor
    */
    std::vector<std::list<ScheduleEntry*> > sked;

    /** Find a place to insert the instruction using  the
        schedule entries priority
    */
    SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);

    /** Find a place to insert the instruction using a particular command
        to look for.
    */
    SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,
                             int sked_cmd, int sked_cmd_idx = -1);
};

#endif //__CPU_INORDER_RESOURCE_SKED_HH__
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.7.32); FILE MERGED 2006/01/30 16:25:41 sb 1.7.32.3: #i53898# Made code warning-free. 2006/01/25 17:32:21 sb 1.7.32.2: RESYNC: (1.7-1.8); FILE MERGED 2005/11/16 13:10:34 pl 1.7.32.1: #i55991# removed warnings<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,
        OPEN_SESS,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool isWaiting() const { return state == SYSC_FETCH; }

    bool hasStateChanged() const { return stateChanged; }

    void retryFetch() { fetched = false; }

    void start(Addr size, bool wait = true, bool resume = false)
    {
        syscallSize = size;
        state = resume ? SYSC_FETCH : SYSC_SEND;
        fetched = false;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    bool fetched;
    Addr replyAddr;
    Addr syscallSize;
};

#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<commit_msg>DtuAccel: updated syscall table.<commit_after>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPEGRP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,
        OPEN_SESS,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool isWaiting() const { return state == SYSC_FETCH; }

    bool hasStateChanged() const { return stateChanged; }

    void retryFetch() { fetched = false; }

    void start(Addr size, bool wait = true, bool resume = false)
    {
        syscallSize = size;
        state = resume ? SYSC_FETCH : SYSC_SEND;
        fetched = false;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    bool fetched;
    Addr replyAddr;
    Addr syscallSize;
};

#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<|endoftext|>


<commit_before>//
//  ofxLaserDacBase.cpp
//
//  Created by Seb Lee-Delisle on 07/11/2017.
//
//

#include "ofxLaserDacHelios.h"

using namespace ofxLaser;

DacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {
	pps = 30000;
	newPPS = 30000;

	frameMode = true;

	connected = false;
    newArmed = false;  // as in the PPS system, this knows
                            // if armed status has changed and sends
                            // signal to DAC
	deviceId = "";
	dacDevice = nullptr;

}
DacHelios:: ~DacHelios() {
	ofLogNotice("DacHelios destructor");
	//stopThread();
	close();

}

void DacHelios::close() {

	if(isThreadRunning()) {
		waitForThread(true); // also stops the thread
		if(lock()) {
			if(dacDevice!=nullptr) {
				dacDevice->SetClosed();
				dacDevice = nullptr;
			}
			unlock();
		}
		delete dacDevice;
	}
}

void DacHelios::setup(string name) {

	deviceName = name; // the parameter which shows the name

	ofLogNotice("DacHelios::setup "+name);

	connectToDevice(deviceName);

	pointBufferDisplay.set("Point Buffer", 0,0,1799);
	displayData.push_back(&deviceName);
	displayData.push_back(&pointBufferDisplay);

	startThread();

}

const vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {
	if(lock()) {

		//pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;

		//int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)/1000000.0f;

		//pointBufferDisplay = bufferedPoints.size();

		//latencyDisplay += (latencyMicros - latencyDisplay)*0.1;
		//reconnectCount = prepareSendCount;

		unlock();
	}

	return displayData;
}

bool DacHelios::connectToDevice(string name) {

	dacDevice = heliosManager.getDacDeviceForName(name);
	if(dacDevice!=nullptr) {
		deviceId = deviceName = dacDevice->nameStr;
		if(dacDevice->isClosed()) { // not sure why it should be but hey
			ofLogError("HeliosDac device is closed before it's used!"+ name);
			heliosManager.deleteDevice(dacDevice);
			connected = false;

			dacDevice = nullptr;
		} else {
			connected = true;
		}
	} else {
		connected = false;
	}

	return connected;

}

bool DacHelios:: sendFrame(const vector<Point>& points){
	if(!connected) return false;
	// get frame object

	DacHeliosFrame* frame = getFrame();

	// add all points into the frame object
	frameMode = true;
	for(ofxLaser::Point p : points) {
		frame->addPoint(p);
	}
	// add the frame object to the frame channel
	framesChannel.send(frame);

	return true;

}

bool DacHelios::sendPoints(const vector<Point>& points) {

	if(!connected) return false;
	// get frame object

	DacHeliosFrame* frame = getFrame();

	// add all points into the frame object
	frameMode = false;
	frame->addPoint(lastPoint);
	for(ofxLaser::Point p : points) {
		frame->addPoint(p);
		lastPoint = p;
	}
	// add the frame object to the frame channel
	framesChannel.send(frame);

	return true;
};

bool DacHelios::setPointsPerSecond(uint32_t newpps) {
	ofLog(OF_LOG_NOTICE, "setPointsPerSecond " + ofToString(newpps));
	while(!lock());
	newPPS = newpps;
	unlock();
	return true;

};

void DacHelios :: setActive(bool active){
    newArmed = active;

}
void DacHelios :: reset() {
    if(lock()) {
        resetFlag = true;
        unlock();
    }
}

void DacHelios :: threadedFunction(){

	DacHeliosFrame* currentFrame = nullptr;
	DacHeliosFrame* nextFrame = nullptr;
	DacHeliosFrame* newFrame = nullptr;

	while(isThreadRunning()) {

		if(connected && (newPPS!=pps)) {
			pps = newPPS;

		}
        if(connected && (newArmed!=armed)) {
            if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {
                armed = newArmed;
            }
        }

		if(connected && isThreadRunning()) {

			// is there a new frame?
			// if so, store it
			bool dacReady = false;
			int status = 0;

			while((!dacReady) && isThreadRunning())  {
				// if we're in frame mode or we don't have a next frame let's pull another frame off the buffer
				// (means that we only skip frames in frame mode)
				if( (frameMode || nextFrame==nullptr) &&
					 (framesChannel.tryReceive(newFrame)) ) {
					if(nextFrame!=nullptr) {
						nextFrame = releaseFrame(nextFrame);
					}
					nextFrame = newFrame;
				}
				yield();
				float time = ofGetElapsedTimef();
				if(dacDevice!=nullptr) status = dacDevice->GetStatus();

				yield();
				dacReady = (status == 1);

				if(!dacReady) {

					if(status<0) {
						ofLog(OF_LOG_NOTICE, "heliosDac.getStatus error: "+ ofToString(status) +" " + ofToString(ofGetElapsedTimef()-time));
					}
					usleep(100);
				}

				yield();
			}
			// if we got to here then the dac is ready but we might not have a
			// currentFrame yet...
			if(nextFrame!=nullptr) {
				if(currentFrame!=nullptr) {
					releaseFrame(currentFrame);
				}
				currentFrame = nextFrame;
				nextFrame = nullptr;
			}
			if(currentFrame!=nullptr) {
				int result =  0;
				int attempts = 0;
				if(dacDevice!=nullptr) {
					while((attempts<512) && (result!=HELIOS_SUCCESS)) {
						result = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);
						attempts++;
						yield();
					}
				}
				// if we're not in frame mode then delete the points
				if((result == HELIOS_SUCCESS) && (!frameMode) ) {
					currentFrame=releaseFrame(currentFrame);
				}

				//ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame : "+ ofToString(result));
				if(result <=-5000){ // then we have a USB connection error
					ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. LIBUSB error : "+ ofToString(result));
					//if(result!=-5007) setConnected(false); // time out error
				} else if(result!=HELIOS_SUCCESS) {
					ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. Error : "+ ofToString(result));
					//setConnected(false);
				} else {
					//setConnected(true);
				}
			} else {
				//ofLogError("DacHelios - run out of points!");
			}
		} else {

			// TODO : handle reconnection better
			// try to reconnect!

			if(isThreadRunning()) {
				if(lock()) {
					if(connectToDevice(deviceName)) {
						setConnected(true);

						unlock();
					} else {
						unlock();
						// wait half a second and try again
						for(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {
							sleep(50);
						}
					}
				}
				yield();

			}

		}
	}

}

void DacHelios :: setConnected(bool state) {
	if(connected!=state) {

		while(!lock()){};
		connected = state;
		if(!connected) {
			//heliosManager.deviceDisconnected(deviceName);
			armed = !newArmed;
			heliosManager.deleteDevice(dacDevice);
			dacDevice = nullptr;
		}
		ofLogNotice("Helios Dac changed connection state : "+ofToString(connected));
		unlock();

	}
}

DacHeliosFrame* DacHelios :: getFrame() {
	DacHeliosFrame* returnframe;

	if(spareFrames.tryReceive(returnframe)) {
		//ofLogNotice("DacHelios :: getFrame() - removed frame from channel");
		returnframe->reset();
		return returnframe;
	} else {
		//ofLogNotice("DacHelios :: getFrame() - created new frame");
		returnframe =new DacHeliosFrame();
		return returnframe;
	}

}
DacHeliosFrame* DacHelios :: releaseFrame(DacHeliosFrame* frame){
	//delete frame;
	//
	spareFrames.send(frame);
	//ofLogNotice("DacHelios :: releaseFrame() - added frame to channel "+ofToString(frame->numSamples));
	return nullptr;
}

<commit_msg>remove usleep (incompatible with windows)<commit_after>//
//  ofxLaserDacBase.cpp
//
//  Created by Seb Lee-Delisle on 07/11/2017.
//
//

#include "ofxLaserDacHelios.h"

using namespace ofxLaser;

DacHelios:: DacHelios() : heliosManager(DacHeliosManager::getInstance()) {
	pps = 30000;
	newPPS = 30000;

	frameMode = true;

	connected = false;
    newArmed = false;  // as in the PPS system, this knows
                            // if armed status has changed and sends
                            // signal to DAC
	deviceId = "";
	dacDevice = nullptr;

}
DacHelios:: ~DacHelios() {
	ofLogNotice("DacHelios destructor");
	//stopThread();
	close();

}

void DacHelios::close() {

	if(isThreadRunning()) {
		waitForThread(true); // also stops the thread
		if(lock()) {
			if(dacDevice!=nullptr) {
				dacDevice->SetClosed();
				dacDevice = nullptr;
			}
			unlock();
		}
		delete dacDevice;
	}
}

void DacHelios::setup(string name) {

	deviceName = name; // the parameter which shows the name

	ofLogNotice("DacHelios::setup "+name);

	connectToDevice(deviceName);

	pointBufferDisplay.set("Point Buffer", 0,0,1799);
	displayData.push_back(&deviceName);
	displayData.push_back(&pointBufferDisplay);

	startThread();

}

const vector<ofAbstractParameter*>& DacHelios :: getDisplayData() {
	if(lock()) {

		//pointBufferDisplay += (response.status.buffer_fullness-pointBufferDisplay)*1;

		//int pointssincelastmessage = (float)((ofGetElapsedTimeMicros()-lastMessageTimeMicros)*response.status.point_rate)/1000000.0f;

		//pointBufferDisplay = bufferedPoints.size();

		//latencyDisplay += (latencyMicros - latencyDisplay)*0.1;
		//reconnectCount = prepareSendCount;

		unlock();
	}

	return displayData;
}

bool DacHelios::connectToDevice(string name) {

	dacDevice = heliosManager.getDacDeviceForName(name);
	if(dacDevice!=nullptr) {
		deviceId = deviceName = dacDevice->nameStr;
		if(dacDevice->isClosed()) { // not sure why it should be but hey
			ofLogError("HeliosDac device is closed before it's used!"+ name);
			heliosManager.deleteDevice(dacDevice);
			connected = false;

			dacDevice = nullptr;
		} else {
			connected = true;
		}
	} else {
		connected = false;
	}

	return connected;

}

bool DacHelios:: sendFrame(const vector<Point>& points){
	if(!connected) return false;
	// get frame object

	DacHeliosFrame* frame = getFrame();

	// add all points into the frame object
	frameMode = true;
	for(ofxLaser::Point p : points) {
		frame->addPoint(p);
	}
	// add the frame object to the frame channel
	framesChannel.send(frame);

	return true;

}

bool DacHelios::sendPoints(const vector<Point>& points) {

	if(!connected) return false;
	// get frame object

	DacHeliosFrame* frame = getFrame();

	// add all points into the frame object
	frameMode = false;
	frame->addPoint(lastPoint);
	for(ofxLaser::Point p : points) {
		frame->addPoint(p);
		lastPoint = p;
	}
	// add the frame object to the frame channel
	framesChannel.send(frame);

	return true;
};

bool DacHelios::setPointsPerSecond(uint32_t newpps) {
	ofLog(OF_LOG_NOTICE, "setPointsPerSecond " + ofToString(newpps));
	while(!lock());
	newPPS = newpps;
	unlock();
	return true;

};

void DacHelios :: setActive(bool active){
    newArmed = active;

}
void DacHelios :: reset() {
    if(lock()) {
        resetFlag = true;
        unlock();
    }
}

void DacHelios :: threadedFunction(){

	DacHeliosFrame* currentFrame = nullptr;
	DacHeliosFrame* nextFrame = nullptr;
	DacHeliosFrame* newFrame = nullptr;

	while(isThreadRunning()) {

		if(connected && (newPPS!=pps)) {
			pps = newPPS;

		}
        if(connected && (newArmed!=armed)) {
            if((dacDevice!=nullptr) && (dacDevice->SetShutter(newArmed)==HELIOS_SUCCESS)) {
                armed = newArmed;
            }
        }

		if(connected && isThreadRunning()) {

			// is there a new frame?
			// if so, store it
			bool dacReady = false;
			int status = 0;

			while((!dacReady) && isThreadRunning())  {
				// if we're in frame mode or we don't have a next frame let's pull another frame off the buffer
				// (means that we only skip frames in frame mode)
				if( (frameMode || nextFrame==nullptr) &&
					 (framesChannel.tryReceive(newFrame)) ) {
					if(nextFrame!=nullptr) {
						nextFrame = releaseFrame(nextFrame);
					}
					nextFrame = newFrame;
				}
				yield();
				float time = ofGetElapsedTimef();
				if(dacDevice!=nullptr) status = dacDevice->GetStatus();

				yield();
				dacReady = (status == 1);

				if(!dacReady) {

					if(status<0) {
						ofLog(OF_LOG_NOTICE, "heliosDac.getStatus error: "+ ofToString(status) +" " + ofToString(ofGetElapsedTimef()-time));
					}
					yield();
				}

				yield();
			}
			// if we got to here then the dac is ready but we might not have a
			// currentFrame yet...
			if(nextFrame!=nullptr) {
				if(currentFrame!=nullptr) {
					releaseFrame(currentFrame);
				}
				currentFrame = nextFrame;
				nextFrame = nullptr;
			}
			if(currentFrame!=nullptr) {
				int result =  0;
				int attempts = 0;
				if(dacDevice!=nullptr) {
					while((attempts<512) && (result!=HELIOS_SUCCESS)) {
						result = dacDevice->SendFrame(pps, HELIOS_FLAGS_SINGLE_MODE, currentFrame->samples, currentFrame->numSamples);
						attempts++;
						yield();
					}
				}
				// if we're not in frame mode then delete the points
				if((result == HELIOS_SUCCESS) && (!frameMode) ) {
					currentFrame=releaseFrame(currentFrame);
				}

				//ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame : "+ ofToString(result));
				if(result <=-5000){ // then we have a USB connection error
					ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. LIBUSB error : "+ ofToString(result));
					//if(result!=-5007) setConnected(false); // time out error
				} else if(result!=HELIOS_SUCCESS) {
					ofLog(OF_LOG_NOTICE, "heliosDac.WriteFrame failed. Error : "+ ofToString(result));
					//setConnected(false);
				} else {
					//setConnected(true);
				}
			} else {
				//ofLogError("DacHelios - run out of points!");
			}
		} else {

			// TODO : handle reconnection better
			// try to reconnect!

			if(isThreadRunning()) {
				if(lock()) {
					if(connectToDevice(deviceName)) {
						setConnected(true);

						unlock();
					} else {
						unlock();
						// wait half a second and try again
						for(size_t i = 0; (i<10)&&(isThreadRunning()); i++ ) {
							sleep(50);
						}
					}
				}
				yield();

			}

		}
	}

}

void DacHelios :: setConnected(bool state) {
	if(connected!=state) {

		while(!lock()){};
		connected = state;
		if(!connected) {
			//heliosManager.deviceDisconnected(deviceName);
			armed = !newArmed;
			heliosManager.deleteDevice(dacDevice);
			dacDevice = nullptr;
		}
		ofLogNotice("Helios Dac changed connection state : "+ofToString(connected));
		unlock();

	}
}

DacHeliosFrame* DacHelios :: getFrame() {
	DacHeliosFrame* returnframe;

	if(spareFrames.tryReceive(returnframe)) {
		//ofLogNotice("DacHelios :: getFrame() - removed frame from channel");
		returnframe->reset();
		return returnframe;
	} else {
		//ofLogNotice("DacHelios :: getFrame() - created new frame");
		returnframe =new DacHeliosFrame();
		return returnframe;
	}

}
DacHeliosFrame* DacHelios :: releaseFrame(DacHeliosFrame* frame){
	//delete frame;
	//
	spareFrames.send(frame);
	//ofLogNotice("DacHelios :: releaseFrame() - added frame to channel "+ofToString(frame->numSamples));
	return nullptr;
}

<|endoftext|>


<commit_before><commit_msg>Use the full path name to the shared library when registering it, not just "libGPad".<commit_after><|endoftext|>


<commit_before>//
// Created by Dawid Drozd aka Gelldur on 03.02.16.
//

#include "Provider.h"

#include <log.h>
#include <Poco/Delegate.h>
#include <Poco/Runnable.h>
#include <Director.h>
#include <exception/Fail.h>
#include <acme/guard/ChangeOnEnd.h>
#include "Application.h"

//TODO make thread safe
class BackroundHelper : public Poco::Runnable
{
public:
	std::atomic<bool> isReady;

	BackroundHelper(std::shared_ptr<Provider>& provider)
			: isReady(false)
			, _provider(provider)
	{
		assert(_provider);
		_provider->setState(Provider::State::BEFORE_RUN);
	}

	virtual void run() override
	{
		ChangeOnEnd<std::atomic<bool>, bool> guard(isReady, true);
		try
		{
			runTask();
		}
		catch (std::exception& exception)
		{
			DLOG("Exception in background task!\nWhat: %s", exception.what());
			throw;
		}
		catch (...)
		{
			DLOG("Exception in background task!");
			throw;
		}
	}

	void runTask()
	{
		if (_provider->isCanceled())
		{
			return;
		}
		_provider->setState(Provider::State::RUNNING);
		try
		{
			_provider->onDoInBackground();
			_provider->setState(Provider::State::DONE);
		}
		catch (...)
		{
			_provider->setState(Provider::State::ERROR);
			throw;
		}
	}

private:
	std::shared_ptr<Provider> _provider;
};

Provider::Provider()
		: _state(State::IDLE)
{
}

Provider::~Provider()
{
	if (_runnable != nullptr)
	{
		Fail(__FILE__, __func__, __LINE__).add("Provider is running and you try to release it durring this operation")
				.report();
	}
}

void Provider::setReceiver(Receiver* receiver)
{
	_receiver = receiver;
}

void Provider::onRequestData(std::shared_ptr<Provider>& thisProvider)
{
	if (_runnable != nullptr)
	{
		ELOG("Already queued");
		return;
	}

	assert(thisProvider.get() == this);

	_runnable = new BackroundHelper(thisProvider);
	_receiver->onStartLoading();
	Director::getInstance().getApp()->getApiThreadPool().start(*_runnable);
	registerCheck();
}

void Provider::cancel()
{
	if (isReady())
	{
		//Skip if doing nothing
		return;
	}
	if (_state != State::CANCELED)
	{
		setState(State::CANCELED);
		onCancel();
	}
}

void Provider::onCancel()
{
	//TODO implement
	DLOG("OnCancel");
	if (_receiver != nullptr)
	{
		_receiver->onStopLoading();
	}
}

void Provider::onEvent(const void* sender, int& dummy)
{
	if (_runnable == nullptr)
	{
		Fail(__FILE__, __func__, __LINE__).report();
	}
	auto request = dynamic_cast<BackroundHelper*>(_runnable);
    assert(request != nullptr);
	if (request->isReady == false)
	{
		DLOG("WAITING!");
		return;
	}
	DLOG("Done request");

	onPostExecute();

	if (_receiver != nullptr)
	{
		if (_state == State::ERROR)
		{
			_receiver->onStopLoading();
			//TODO add catches?
			getReceiver()->onError(this);
		}
		else if (_state == State::DONE)
		{
			_receiver->onStopLoading();
			getReceiver()->onReceive(this);
		}
		else if (_state == State::CANCELED)
		{
			DLOG("Task canceled");
		}
		else
		{
			Fail(__FILE__, __func__, __LINE__).add("Wrong state:").add(static_cast<int>(_state.load())).report();
		}
	}
	else
	{
		DLOG("%s:%s:%d", __FILE__, __func__, __LINE__);
		WLOG("No one to notify!");
	}

	unregisterCheck();
	setState(State::IDLE);

	auto runnable = _runnable;
	_runnable = nullptr;
	delete runnable;
}

void Provider::registerCheck()
{
	Director::getInstance().getApp()->getUILoop().uiTick += Poco::delegate(this, &Provider::onEvent);
}

void Provider::unregisterCheck()
{
	Director::getInstance().getApp()->getUILoop().uiTick -= Poco::delegate(this, &Provider::onEvent);
}

void Provider::setState(State state)
{
	if (_state == State::CANCELED && state != State::IDLE)
	{
		return;
	}
	_state = state;
}

bool Provider::isCanceled()
{
	return _state == State::CANCELED;
}

bool Provider::isReady()
{
	return _state == State::IDLE;
}
<commit_msg>Change log level<commit_after>//
// Created by Dawid Drozd aka Gelldur on 03.02.16.
//

#include "Provider.h"

#include <log.h>
#include <Poco/Delegate.h>
#include <Poco/Runnable.h>
#include <Director.h>
#include <exception/Fail.h>
#include <acme/guard/ChangeOnEnd.h>
#include "Application.h"

//TODO make thread safe
class BackroundHelper : public Poco::Runnable
{
public:
	std::atomic<bool> isReady;

	BackroundHelper(std::shared_ptr<Provider>& provider)
			: isReady(false)
			, _provider(provider)
	{
		assert(_provider);
		_provider->setState(Provider::State::BEFORE_RUN);
	}

	virtual void run() override
	{
		ChangeOnEnd<std::atomic<bool>, bool> guard(isReady, true);
		try
		{
			runTask();
		}
		catch (std::exception& exception)
		{
			ELOG("Exception in background task!\nWhat: %s", exception.what());
			throw;
		}
		catch (...)
		{
			ELOG("Exception in background task!");
			throw;
		}
	}

	void runTask()
	{
		if (_provider->isCanceled())
		{
			return;
		}
		_provider->setState(Provider::State::RUNNING);
		try
		{
			_provider->onDoInBackground();
			_provider->setState(Provider::State::DONE);
		}
		catch (...)
		{
			_provider->setState(Provider::State::ERROR);
			throw;
		}
	}

private:
	std::shared_ptr<Provider> _provider;
};

Provider::Provider()
		: _state(State::IDLE)
{
}

Provider::~Provider()
{
	if (_runnable != nullptr)
	{
		Fail(__FILE__, __func__, __LINE__).add("Provider is running and you try to release it durring this operation")
				.report();
	}
}

void Provider::setReceiver(Receiver* receiver)
{
	_receiver = receiver;
}

void Provider::onRequestData(std::shared_ptr<Provider>& thisProvider)
{
	if (_runnable != nullptr)
	{
		ELOG("Already queued");
		return;
	}
	assert(thisProvider.get() == this);

	_runnable = new BackroundHelper(thisProvider);
	_receiver->onStartLoading();
	Director::getInstance().getApp()->getApiThreadPool().start(*_runnable);
	registerCheck();
}

void Provider::cancel()
{
	if (isReady())
	{
		//Skip if doing nothing
		return;
	}
	if (_state != State::CANCELED)
	{
		setState(State::CANCELED);
		onCancel();
	}
}

void Provider::onCancel()
{
	//TODO implement
	DLOG("OnCancel");
	if (_receiver != nullptr)
	{
		_receiver->onStopLoading();
	}
}

void Provider::onEvent(const void* sender, int& dummy)
{
	if (_runnable == nullptr)
	{
		Fail(__FILE__, __func__, __LINE__).report();
	}
	auto request = dynamic_cast<BackroundHelper*>(_runnable);
    assert(request != nullptr);
	if (request->isReady == false)
	{
		DLOG("WAITING!");
		return;
	}
	DLOG("Done request");

	onPostExecute();

	if (_receiver != nullptr)
	{
		if (_state == State::ERROR)
		{
			_receiver->onStopLoading();
			//TODO add catches?
			getReceiver()->onError(this);
		}
		else if (_state == State::DONE)
		{
			_receiver->onStopLoading();
			getReceiver()->onReceive(this);
		}
		else if (_state == State::CANCELED)
		{
			DLOG("Task canceled");
		}
		else
		{
			Fail(__FILE__, __func__, __LINE__).add("Wrong state:").add(static_cast<int>(_state.load())).report();
		}
	}
	else
	{
		DLOG("%s:%s:%d", __FILE__, __func__, __LINE__);
		WLOG("No one to notify!");
	}

	unregisterCheck();
	setState(State::IDLE);

	auto runnable = _runnable;
	_runnable = nullptr;
	delete runnable;
}

void Provider::registerCheck()
{
	Director::getInstance().getApp()->getUILoop().uiTick += Poco::delegate(this, &Provider::onEvent);
}

void Provider::unregisterCheck()
{
	Director::getInstance().getApp()->getUILoop().uiTick -= Poco::delegate(this, &Provider::onEvent);
}

void Provider::setState(State state)
{
	if (_state == State::CANCELED && state != State::IDLE)
	{
		return;
	}
	_state = state;
}

bool Provider::isCanceled()
{
	return _state == State::CANCELED;
}

bool Provider::isReady()
{
	return _state == State::IDLE;
}
<|endoftext|>