<commit_before>/*************************************************************************
 *
 *  $RCSfile: logfile.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: cd $ $Date: 2001-07-27 18:54:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2001 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _RTL_LOGFILE_HXX_
#define _RTL_LOGFILE_HXX_

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#ifndef _RTL_LOGFILE_H_
#include <rtl/logfile.h>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace rtl
{
/**
@descr  The intended use for class Logfile is to write time stamp information
        for profiling purposes.

        Profiling output should only be generated for a special product version of OpenOffice
        which is compiled with a defined preprocessor symbol 'TIMELOG'.
        Therefore we have provided a set of macros that uses the class Logfile only if
        this symbol is defined.  If the macros are not sufficient, i.e. you need more
        then three arguments for a printf style message, then you have to insert an
        #ifdef TIMELOG/#endif brace yourself.

        Additionally the environment variable RTL_LOGFILE has to be defined in order to generate
        logging information. If the variable is not empty, it creates a file with the name
        $(RTL_LOGFILE)_$(PID).log, where $(PID) is the process id of the running process.
        It can be used as a run time switch for enabling or disabling the logging.
        Note that this variable is evaluated only once at the first attempt to write a message.

        The class LogFile collects runtime data within its constructor and destructor. It can be
        used for timing whole functions.
        If you want to write timing data without context you can use the RTL_LOGFILE_TRACE-macros
        which are defined inside <rtl/logfile.h>.

        The class LogFile should not be used directly, instead use the RTL_LOGFILE_CONTEXT/
        RTL_LOGFILE_TRACE-macros.

        Macro usage:
        ------------
        RTL_LOGFILE_CONTEXT( instance, name );
        This macro creates an instance of class LogFile with the name "instance" and writes the current time,
        thread id and "name" to the log file.

        Example: RTL_LOGFILE_CONTEXT( aLog, "Timing for foo-method" );

        RTL_LOGFILE_CONTEXT_TRACE( instance, mesage );
        RTL_LOGFILE_CONTEXT_TRACEn( instance, frmt, arg1, .., arg3 );
        These macros can be used to log information in a "instance" context. The "instance" object
        is used to log message informations. All macros with "frmt" uses printf notation to log timing infos.

        Example: RTL_LOGFILE_CONTEXT_TRACE( aLog, "Now we call an expensive function" );
                 RTL_LOGFIlE_CONTEXT_TRACE1( aLog, "Config entries read: %u", (unsigned short)i );

        RTL_LOGFILE_TRACE( string );
        RTL_LOGFILE_TRACEn( frmt, arg1, .., arg3 );
        These macros can be used to log information outside a context. The macro directly calls
        rtl_logfile_trace to write the info to the log file. All macros with "frmt" uses printf
        notation to log timing infos.

        Example: RTL_LOGFILE_TRACE( "Timing for loading a file" );
                 RTL_LOGFILE_TRACE1( aLog, "Timing for loading file: %s", aFileName );

        The lines written to the log file consist of the following space separated elements:
        1.  The time relative to the start of the global timer in milliseconds.  The times is
            started typically for the first logged line.
        2.  Thread id.  It's absolut value is probably of less interest than providing a way to
            distinguish different threads.
        3.  a.  An opening or closing curly brace indicating the start or end of a scope.
                4a. Function name or general scope identifier.
            b.  A vertical line indicating an arbitrary message.
                4b optional function name or general scope identifier.
                5b A colon followed by a space and a free form message terminated by a newline.

        There is a second version of creating a context. RTL_LOGFILE_CONTEXT_AUTHOR takes
        two more arguments, the name of the project and the author's sign who is responsible
        for the code in which the macro is used.
*/
    class Logfile
    {
    public:
        inline Logfile( const sal_Char *name );
        /** @descr  Create a log file context where the message field consists of a project
                name, the author's shortcut, and the actual message.  These three strings
                are written in a format that is understood by script that later parses the
                log file and that so can extract the three strings.
            @param  project Short name of the project, like sw for writer or sc for calc.
            @param  author  The sign of the person responsible for the code.
            @param  name    The actual message, typically a method name.
        */
        inline Logfile( const sal_Char *project, const sal_Char *author, const sal_Char *name );
        inline ~Logfile();
        inline const sal_Char *getName();
    private:
        ::rtl::OString m_sName;
    };

    inline Logfile::Logfile( const sal_Char *name )
        : m_sName( name )
    {
        rtl_logfile_trace( "%06lu %lu { %s\n",
                           osl_getGlobalTimer(),
                           osl_getThreadIdentifier( 0 ),
                           name );
    }

    inline Logfile::Logfile( const sal_Char *project, const sal_Char *author, const sal_Char *name )
        : m_sName( project)
    {
        m_sName += " (";
        m_sName += author;
        m_sName += ") ";
        m_sName += name;
        rtl_logfile_trace( "%06lu %lu { %s\n",
                           osl_getGlobalTimer(),
                           osl_getThreadIdentifier( 0 ),
                           m_sName.pData->buffer );
    }

    inline Logfile::~Logfile()
    {
        rtl_logfile_trace( "%06lu %lu } %s\n",
                           osl_getGlobalTimer(),
                           osl_getThreadIdentifier(0),
                           m_sName.pData->buffer );
    }

    inline const sal_Char * Logfile::getName()
    {
        return m_sName.getStr();
    }
}

#ifdef TIMELOG
#define RTL_LOGFILE_CONTEXT( instance, name ) ::rtl::Logfile instance( name )
#define RTL_LOGFILE_CONTEXT_AUTHOR( instance, project, author, name ) ::rtl::Logfile instance(project, author, name )
#define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) \
        rtl_logfile_trace( "%06lu %lu | %s : %s\n", \
                           osl_getGlobalTimer(),  \
                           osl_getThreadIdentifier( 0 ), \
                           instance.getName(), \
                           message )
#define RTL_LOGFILE_CONTEXT_TRACE1( instance , frmt, arg1 ) \
        rtl_logfile_trace( "%06lu %lu | %s : ", \
                           osl_getGlobalTimer(),  \
                           osl_getThreadIdentifier( 0 ), \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 ); \
        rtl_logfile_trace( "\n" )
#define RTL_LOGFILE_CONTEXT_TRACE2( instance , frmt, arg1 , arg2 ) \
        rtl_logfile_trace( "%06lu %lu | %s : ", \
                           osl_getGlobalTimer(),  \
                           osl_getThreadIdentifier( 0 ), \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 , arg2 ); \
        rtl_logfile_trace( "\n" )
#define RTL_LOGFILE_CONTEXT_TRACE3( instance , frmt, arg1 , arg2 , arg3 ) \
        rtl_logfile_trace( "%06lu %lu | %s : ", \
                           osl_getGlobalTimer(),  \
                           osl_getThreadIdentifier( 0 ), \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 , arg2 , arg3 ); \
        rtl_logfile_trace( "\n" )

#else
#define RTL_LOGFILE_CONTEXT( instance, name )  ((void)0)
#define RTL_LOGFILE_CONTEXT_AUTHOR( instance, project, author, name )  ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE( instance, message )  ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE1( instance, frmt, arg1 ) ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE2( instance, frmt, arg1, arg2 ) ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE3( instance, frmt, arg1, arg2 , arg3 ) ((void)0)
#endif

#endif
<commit_msg>INTEGRATION: CWS cd02 (1.5.350); FILE MERGED 2004/11/08 15:46:17 sb 1.5.350.1: #i36858# Added rtl_logfile_longTrace to improve performance (no unnecessary calls to osl_getGlobalTimer).<commit_after>/*************************************************************************
 *
 *  $RCSfile: logfile.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 19:10:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2001 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _RTL_LOGFILE_HXX_
#define _RTL_LOGFILE_HXX_

#ifndef _RTL_LOGFILE_H_
#include <rtl/logfile.h>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace rtl
{
/**
@descr  The intended use for class Logfile is to write time stamp information
        for profiling purposes.

        Profiling output should only be generated for a special product version of OpenOffice
        which is compiled with a defined preprocessor symbol 'TIMELOG'.
        Therefore we have provided a set of macros that uses the class Logfile only if
        this symbol is defined.  If the macros are not sufficient, i.e. you need more
        then three arguments for a printf style message, then you have to insert an
        #ifdef TIMELOG/#endif brace yourself.

        Additionally the environment variable RTL_LOGFILE has to be defined in order to generate
        logging information. If the variable is not empty, it creates a file with the name
        $(RTL_LOGFILE)_$(PID).log, where $(PID) is the process id of the running process.
        It can be used as a run time switch for enabling or disabling the logging.
        Note that this variable is evaluated only once at the first attempt to write a message.

        The class LogFile collects runtime data within its constructor and destructor. It can be
        used for timing whole functions.
        If you want to write timing data without context you can use the RTL_LOGFILE_TRACE-macros
        which are defined inside <rtl/logfile.h>.

        The class LogFile should not be used directly, instead use the RTL_LOGFILE_CONTEXT/
        RTL_LOGFILE_TRACE-macros.

        Macro usage:
        ------------
        RTL_LOGFILE_CONTEXT( instance, name );
        This macro creates an instance of class LogFile with the name "instance" and writes the current time,
        thread id and "name" to the log file.

        Example: RTL_LOGFILE_CONTEXT( aLog, "Timing for foo-method" );

        RTL_LOGFILE_CONTEXT_TRACE( instance, mesage );
        RTL_LOGFILE_CONTEXT_TRACEn( instance, frmt, arg1, .., arg3 );
        These macros can be used to log information in a "instance" context. The "instance" object
        is used to log message informations. All macros with "frmt" uses printf notation to log timing infos.

        Example: RTL_LOGFILE_CONTEXT_TRACE( aLog, "Now we call an expensive function" );
                 RTL_LOGFIlE_CONTEXT_TRACE1( aLog, "Config entries read: %u", (unsigned short)i );

        RTL_LOGFILE_TRACE( string );
        RTL_LOGFILE_TRACEn( frmt, arg1, .., arg3 );
        These macros can be used to log information outside a context. The macro directly calls
        rtl_logfile_trace to write the info to the log file. All macros with "frmt" uses printf
        notation to log timing infos.

        Example: RTL_LOGFILE_TRACE( "Timing for loading a file" );
                 RTL_LOGFILE_TRACE1( aLog, "Timing for loading file: %s", aFileName );

        The lines written to the log file consist of the following space separated elements:
        1.  The time relative to the start of the global timer in milliseconds.  The times is
            started typically for the first logged line.
        2.  Thread id.  It's absolut value is probably of less interest than providing a way to
            distinguish different threads.
        3.  a.  An opening or closing curly brace indicating the start or end of a scope.
                4a. Function name or general scope identifier.
            b.  A vertical line indicating an arbitrary message.
                4b optional function name or general scope identifier.
                5b A colon followed by a space and a free form message terminated by a newline.

        There is a second version of creating a context. RTL_LOGFILE_CONTEXT_AUTHOR takes
        two more arguments, the name of the project and the author's sign who is responsible
        for the code in which the macro is used.
*/
    class Logfile
    {
    public:
        inline Logfile( const sal_Char *name );
        /** @descr  Create a log file context where the message field consists of a project
                name, the author's shortcut, and the actual message.  These three strings
                are written in a format that is understood by script that later parses the
                log file and that so can extract the three strings.
            @param  project Short name of the project, like sw for writer or sc for calc.
            @param  author  The sign of the person responsible for the code.
            @param  name    The actual message, typically a method name.
        */
        inline Logfile( const sal_Char *project, const sal_Char *author, const sal_Char *name );
        inline ~Logfile();
        inline const sal_Char *getName();
    private:
        ::rtl::OString m_sName;
    };

    inline Logfile::Logfile( const sal_Char *name )
        : m_sName( name )
    {
        rtl_logfile_longTrace( "{ %s\n", name );
    }

    inline Logfile::Logfile( const sal_Char *project, const sal_Char *author, const sal_Char *name )
        : m_sName( project)
    {
        m_sName += " (";
        m_sName += author;
        m_sName += ") ";
        m_sName += name;
        rtl_logfile_longTrace( "{ %s\n", m_sName.pData->buffer );
    }

    inline Logfile::~Logfile()
    {
        rtl_logfile_longTrace( "} %s\n", m_sName.pData->buffer );
    }

    inline const sal_Char * Logfile::getName()
    {
        return m_sName.getStr();
    }
}

#ifdef TIMELOG
#define RTL_LOGFILE_CONTEXT( instance, name ) ::rtl::Logfile instance( name )
#define RTL_LOGFILE_CONTEXT_AUTHOR( instance, project, author, name ) ::rtl::Logfile instance(project, author, name )
#define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) \
        rtl_logfile_longTrace( "| %s : %s\n", \
                           instance.getName(), \
                           message )
#define RTL_LOGFILE_CONTEXT_TRACE1( instance , frmt, arg1 ) \
        rtl_logfile_longTrace( "| %s : ", \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 ); \
        rtl_logfile_trace( "\n" )
#define RTL_LOGFILE_CONTEXT_TRACE2( instance , frmt, arg1 , arg2 ) \
        rtl_logfile_longTrace( "| %s : ", \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 , arg2 ); \
        rtl_logfile_trace( "\n" )
#define RTL_LOGFILE_CONTEXT_TRACE3( instance , frmt, arg1 , arg2 , arg3 ) \
        rtl_logfile_longTrace( "| %s : ", \
                           instance.getName() ); \
        rtl_logfile_trace( frmt , arg1 , arg2 , arg3 ); \
        rtl_logfile_trace( "\n" )

#else
#define RTL_LOGFILE_CONTEXT( instance, name )  ((void)0)
#define RTL_LOGFILE_CONTEXT_AUTHOR( instance, project, author, name )  ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE( instance, message )  ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE1( instance, frmt, arg1 ) ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE2( instance, frmt, arg1, arg2 ) ((void)0)
#define RTL_LOGFILE_CONTEXT_TRACE3( instance, frmt, arg1, arg2 , arg3 ) ((void)0)
#endif

#endif
<|endoftext|>


<commit_before><commit_msg>integrated and tested more reliable odd/even frame sync, I think it's an improvement on 4dB poor channel<commit_after><|endoftext|>


<commit_before><commit_msg>Use time derivatives for the diffusion and production terms in the calculation of the time derivative for the convection term so that a proper estimate of drho/dt can be made. This makes the steady-state solution independent of the global timestep.<commit_after><|endoftext|>


<commit_before>/*
 * BlueprintEntry.cpp
 *
 *  Created on: Apr 3, 2011
 *      Author: kyle
 */

#include "BlueprintEntry.h"
#include "server/zone/objects/resource/ResourceContainer.h"
#include "server/zone/objects/installation/factory/FactoryObject.h"
#include "server/zone/packets/tangible/TangibleObjectDeltaMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h"

BlueprintEntry::BlueprintEntry() : Serializable() {
	serialNumber = "";
	addSerializableVariables();
}

BlueprintEntry::BlueprintEntry(const BlueprintEntry& entry) : Object(), Serializable() {

	type = entry.type;
	key = entry.key;
	displayedName = entry.displayedName;
	serialNumber = entry.serialNumber;
	identical = entry.identical;
	quantity = entry.quantity;

	addSerializableVariables();
}

BlueprintEntry::~BlueprintEntry() {

}

BlueprintEntry& BlueprintEntry::operator=(const BlueprintEntry& entry) {
	if (this == &entry)
		return *this;

	type = entry.type;
	key = entry.key;
	displayedName = entry.displayedName;
	serialNumber = entry.serialNumber;
	identical = entry.identical;
	quantity = entry.quantity;

	return *this;
}

bool BlueprintEntry::operator==(const BlueprintEntry& entry) {
	if (this == &entry)
		return true;

	return((type == entry.type) &&
			(key == entry.key) &&
			(displayedName == entry.displayedName) &&
			(serialNumber == entry.serialNumber) &&
			(identical == entry.identical));
}

bool BlueprintEntry::equals(BlueprintEntry* entry) {

	return((type == entry->type) &&
			(key == entry->key) &&
			(serialNumber == entry->serialNumber) &&
			(identical == entry->identical));
}

void BlueprintEntry::addSerializableVariables() {
	addSerializableVariable("type", &type);
	addSerializableVariable("key", &key);
	addSerializableVariable("displayedName", &displayedName);
	addSerializableVariable("serialNumber", &serialNumber);
	addSerializableVariable("identical", &identical);
	addSerializableVariable("quantity", &quantity);
}

void BlueprintEntry::insertSchematicAttribute(AttributeListMessage* alm) {

	String name = "cat_manf_schem_ing_resource.\"" + displayedName;
	StringBuffer value;
	value << quantity;

	if(type == "component")
		value << "\n" << serialNumber;

	alm->insertAttribute(name, value);
}

void BlueprintEntry::insertFactoryIngredient(SuiListBox* ingredientList) {

	StringBuffer sendstring;
	sendstring << displayedName;

	if(type == "component")
		sendstring  << " " << serialNumber;

	sendstring << ":\\>200" << quantity;

	ingredientList->addMenuItem(sendstring.toString(), 0);
}

void BlueprintEntry::clearMatches() {
	matchingHopperItems.removeAll();
}

bool BlueprintEntry::hasEnoughResources() {

	if(inputHopper == NULL)
		return false;

	int count = 0;

	for(int i = 0; i < matchingHopperItems.size(); ++i) {
		TangibleObject* object = matchingHopperItems.get(i);

		if (object == NULL) {
			matchingHopperItems.remove(i);
			--i;
			continue;
		}

		if(object->getParentID() != inputHopper->getObjectID()) {
			continue;
		}

		count += object->getUseCount();
	}

	if(count >= quantity)
		return true;

	return false;
}

void BlueprintEntry::removeResources(FactoryObject* factory) {

	int count = 0;

	while(matchingHopperItems.size() > 0) {
		TangibleObject* object = matchingHopperItems.get(0);

		if(object->getUseCount() < quantity) {
			count += object->getUseCount();
			matchingHopperItems.removeElement(object);

			object->setUseCount(0, true);
			continue;
		}

		object->setUseCount(object->getUseCount() - (quantity - count), false);

		if(!object->isResourceContainer()) {
			TangibleObjectDeltaMessage3* dtano3 = new TangibleObjectDeltaMessage3(object);
			dtano3->updateCountdownTimer();
			dtano3->close();

			factory->broadcastToOperators(dtano3);
		} else {

			ResourceContainer* container = cast<ResourceContainer*>(object);

			ResourceContainerObjectDeltaMessage3* rcnod3 =
					new ResourceContainerObjectDeltaMessage3(container);

			rcnod3->updateQuantity();
			rcnod3->close();

			factory->broadcastToOperators(rcnod3);
		}

		if(object->getUseCount() == 0)
			matchingHopperItems.removeElement(object);

		break;
	}
}

void BlueprintEntry::print() {
	System::out << "****** Entry ******" << endl;

	System::out << "Type: " << type << endl;
	System::out << "Key: " << key << endl;
	System::out << "Displayed Name: " << displayedName << endl;
	System::out << "Serial Number: " << serialNumber << endl;
	System::out << "Identical: " << identical << endl;
	System::out << "Quantity: " << quantity << endl;

	System::out << "Matching Items:" << endl;
	for(int i = 0; i < matchingHopperItems.size(); ++i) {
		TangibleObject* object = matchingHopperItems.get(i);
		System::out << object->getObjectID() << " " << object->getDisplayedName() << " " << object->getUseCount() << endl;
	}

	System::out << "*******************" << endl;
}
<commit_msg>[fixed] stability issue<commit_after>/*
 * BlueprintEntry.cpp
 *
 *  Created on: Apr 3, 2011
 *      Author: kyle
 */

#include "BlueprintEntry.h"
#include "server/zone/objects/resource/ResourceContainer.h"
#include "server/zone/objects/installation/factory/FactoryObject.h"
#include "server/zone/packets/tangible/TangibleObjectDeltaMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h"

BlueprintEntry::BlueprintEntry() : Serializable() {
	serialNumber = "";
	addSerializableVariables();
}

BlueprintEntry::BlueprintEntry(const BlueprintEntry& entry) : Object(), Serializable() {

	type = entry.type;
	key = entry.key;
	displayedName = entry.displayedName;
	serialNumber = entry.serialNumber;
	identical = entry.identical;
	quantity = entry.quantity;

	addSerializableVariables();
}

BlueprintEntry::~BlueprintEntry() {

}

BlueprintEntry& BlueprintEntry::operator=(const BlueprintEntry& entry) {
	if (this == &entry)
		return *this;

	type = entry.type;
	key = entry.key;
	displayedName = entry.displayedName;
	serialNumber = entry.serialNumber;
	identical = entry.identical;
	quantity = entry.quantity;

	return *this;
}

bool BlueprintEntry::operator==(const BlueprintEntry& entry) {
	if (this == &entry)
		return true;

	return((type == entry.type) &&
			(key == entry.key) &&
			(displayedName == entry.displayedName) &&
			(serialNumber == entry.serialNumber) &&
			(identical == entry.identical));
}

bool BlueprintEntry::equals(BlueprintEntry* entry) {

	return((type == entry->type) &&
			(key == entry->key) &&
			(serialNumber == entry->serialNumber) &&
			(identical == entry->identical));
}

void BlueprintEntry::addSerializableVariables() {
	addSerializableVariable("type", &type);
	addSerializableVariable("key", &key);
	addSerializableVariable("displayedName", &displayedName);
	addSerializableVariable("serialNumber", &serialNumber);
	addSerializableVariable("identical", &identical);
	addSerializableVariable("quantity", &quantity);
}

void BlueprintEntry::insertSchematicAttribute(AttributeListMessage* alm) {

	String name = "cat_manf_schem_ing_resource.\"" + displayedName;
	StringBuffer value;
	value << quantity;

	if(type == "component")
		value << "\n" << serialNumber;

	alm->insertAttribute(name, value);
}

void BlueprintEntry::insertFactoryIngredient(SuiListBox* ingredientList) {

	StringBuffer sendstring;
	sendstring << displayedName;

	if(type == "component")
		sendstring  << " " << serialNumber;

	sendstring << ":\\>200" << quantity;

	ingredientList->addMenuItem(sendstring.toString(), 0);
}

void BlueprintEntry::clearMatches() {
	matchingHopperItems.removeAll();
}

bool BlueprintEntry::hasEnoughResources() {

	if(inputHopper == NULL)
		return false;

	int count = 0;

	for(int i = 0; i < matchingHopperItems.size(); ++i) {
		TangibleObject* object = matchingHopperItems.get(i);

		if (object == NULL) {
			matchingHopperItems.remove(i);
			--i;
			continue;
		}

		if(object->getParentID() != inputHopper->getObjectID()) {
			continue;
		}

		count += object->getUseCount();
	}

	if(count >= quantity)
		return true;

	return false;
}

void BlueprintEntry::removeResources(FactoryObject* factory) {

	int count = 0;

	while(matchingHopperItems.size() > 0) {
		Locker locker(object);

		TangibleObject* object = matchingHopperItems.get(0);

		if(object->getUseCount() < quantity) {
			count += object->getUseCount();
			matchingHopperItems.removeElement(object);

			object->setUseCount(0, true);
			continue;
		}

		object->setUseCount(object->getUseCount() - (quantity - count), false);

		if(!object->isResourceContainer()) {
			TangibleObjectDeltaMessage3* dtano3 = new TangibleObjectDeltaMessage3(object);
			dtano3->updateCountdownTimer();
			dtano3->close();

			factory->broadcastToOperators(dtano3);
		} else {

			ResourceContainer* container = cast<ResourceContainer*>(object);

			ResourceContainerObjectDeltaMessage3* rcnod3 =
					new ResourceContainerObjectDeltaMessage3(container);

			rcnod3->updateQuantity();
			rcnod3->close();

			factory->broadcastToOperators(rcnod3);
		}

		if(object->getUseCount() == 0)
			matchingHopperItems.removeElement(object);

		break;
	}
}

void BlueprintEntry::print() {
	System::out << "****** Entry ******" << endl;

	System::out << "Type: " << type << endl;
	System::out << "Key: " << key << endl;
	System::out << "Displayed Name: " << displayedName << endl;
	System::out << "Serial Number: " << serialNumber << endl;
	System::out << "Identical: " << identical << endl;
	System::out << "Quantity: " << quantity << endl;

	System::out << "Matching Items:" << endl;
	for(int i = 0; i < matchingHopperItems.size(); ++i) {
		TangibleObject* object = matchingHopperItems.get(i);
		System::out << object->getObjectID() << " " << object->getDisplayedName() << " " << object->getUseCount() << endl;
	}

	System::out << "*******************" << endl;
}
<|endoftext|>


<commit_before>#ifndef MATRIX_ALGORITHM_HPP_
#define MATRIX_ALGORITHM_HPP_

#include "matrix_basic_math.hpp"

template<typename T, std::size_t I, std::size_t J>
void print(const Matrix<T, I, J>& A)
{
  for (std::size_t i = 0; i < I; i++)
  {
    for (std::size_t j = 0; j < J; j++)
    {
      std::cout << A[i][j] << " ";
    }
    std::cout << std::endl;
  }
}

/**
 * @brief LU decomposition
 *
 * Usage: The result of function is pair of matrices where L matrix is first
 *        element of pair, the second element is U matrix
 * @param [in] Square Matrix A
 *
 * @return Two matrices L and U
 */
template<typename T, std::size_t n>
std::pair<Matrix<T,n,n>, Matrix<T,n,n>>lu(const Matrix<T,n,n>& A)
{
  auto L = eye<T, n>();
  auto U = zeros<T, n, n>();
  T sum;

  for(std::size_t j = 0; j < n; j++)
  {
    for(std::size_t i = 0; i <= j; i++)
    {
      sum = 0.0;
      for(std::size_t p = 0; p < i; p++)
      {
        sum += U[p][j] * L[i][p];
      }
      U[i][j] = A[i][j] - sum;
    }
    for(std::size_t i = j; i < n; i++)
    {
      sum = 0.0;
      for(std::size_t p = 0; p < i; p++)
      {
        sum += U[p][j] * L[i][p];
      }

      if(U[j][j] == 0)
        throw;
      else
        L[i][j] = (A[i][j] - sum) / U[j][j];
    }
  }
  return std::pair<Matrix<T,n,n>, Matrix<T,n,n>>{L, U};
}

/**
 * @brief Determinant of matrix 1x1
 *
 * @param [in] Square Matrix A with 1x1 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 1, 1>& A)
{
  return A[0][0];
}

/**
 * @brief Determinant of matrix 2x2
 *
 * @param [in] Square Matrix A with 2x2 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 2, 2>& A)
{
  auto&& a = A[0][0]; auto&& b = A[0][1];
  auto&& c = A[1][0]; auto&& d = A[1][1];

  return a*d - b*c;
}

/**
 * @brief Determinant of matrix 3x3
 *
 * @param [in] Square Matrix A with 3x3 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 3, 3>& A)
{
  auto&& a = A[0][0]; auto&& b = A[0][1]; auto&& c = A[0][2];
  auto&& d = A[1][0]; auto&& e = A[1][1]; auto&& f = A[1][2];
  auto&& g = A[2][0]; auto&& h = A[2][1]; auto&& i = A[2][2];

  return a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h;
}

template<typename T, std::size_t n>
void swap_rows(Matrix<T, n, n>& data, size_t a, size_t b)
{
  if (a != b)
  {
    for (size_t k = 0; k < n; ++k)
    {
      std::swap(data[a], data[b]);
    }
  }
}

/**
 * @brief Determinant of matrix nxn
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Determinant of matrix A
 */
template<typename T, std::size_t n>
T det(Matrix<T, n, n> data)
{
  auto tmp = data;

  T factor{1};
  std::size_t pivot{0};

  auto prod = [&]()
  {
    T prod{1};

    for (std::size_t i = 0; i < n; ++i)
    {
      prod *= tmp[i][i];
    }
    return prod / factor;
  };

  for (size_t r = 0; r < n; ++r)
  {
    if (n <= pivot)
    {
      return prod();
    }

    std::size_t i = r;

    while (tmp[i][pivot] == 0)
    {
      ++i;
      if (n == i)
      {
        i = r;
        ++pivot;
        if (n == pivot)
        {
          return prod();
        }
      }
    }

    if (i != r)
    {
      swap_rows(tmp, i, r);
      factor *= -1;
    }

    for (std::size_t i = pivot + 1; i < n; ++i)
    {
      if (i != r)
      {
        T val = tmp[i][pivot];
        for (std::size_t j = pivot; j < n; ++j)
        {
          tmp[i][j] -= val * tmp[r][j] / tmp[r][pivot];
        }

      }
    }
    pivot++;
  }

  return prod();

}

/**
 * @brief Minor of A - A with crossed-out i-th column and j-th row
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Minor of A matrix
 */
template<typename T, std::size_t n>
Matrix<T, (n-1), (n-1)> getminor(const Matrix<T, n, n>& A, std::size_t i, std::size_t j)
{
  Matrix<T, (n-1), (n-1)> minor{};
  std::size_t colCount = 0,rowCount=0;
  for(std::size_t k = 0; k < n; k++)
  {
    if (k != i)
    {
      colCount = 0;
      for(std::size_t l = 0; l < n; l++)
      {
        if (l != j)
        {
          minor[rowCount][colCount] = A[k][l];
          colCount++;
        }
      }
      rowCount++;
    }
  }
  return minor;
}

/**
 * @brief Transpose of matrix nxm
 *
 * @param [in] Matrix A with nxm size
 *
 * @return Transpose of matrix A
 */
template<typename T, std::size_t n, std::size_t m>
Matrix<T, m, n> trans(const Matrix<T, n, m>& A)
{
  Matrix<T, m, n> transA{};

  for (std::size_t i = 0; i < n; i++)
  {
    for (std::size_t j = 0; j < m; j++)
    {
      transA[j][i] = A[i][j];
    }
  }
  return transA;
}

/**
 * @brief Inverse of matrix 1x1
 *
 * @param [in] Square Matrix A with 1x1 size
 *
 * @return Inverse of matrix A
 */
template<typename T>
Matrix<T, 1, 1> inv(const Matrix<T, 1, 1>& A)
{
  return Matrix<T, 1, 1>{ 1/det(A) };
}

/**
 * @brief Inverse of matrix 2x2
 *
 * @param [in] Square Matrix A with 2x2 size
 *
 * @return Inverse of matrix A
 *         error with the A is zero
 */
template<typename T>
Matrix<T, 2, 2> inv(const Matrix<T, 2, 2>& A)
{
  Matrix<T, 2, 2> invA{};
  auto detA = det(A);
  if (detA == 0)
  {
    throw;
  }
  invA = {A[1][1], -A[0][1],
         -A[1][0],  A[0][0]};
  invA = invA / detA;
  return invA;
}

/**
 * @brief Inverse of matrix 3x3
 *
 * @param [in] Square Matrix A with 3x3 size
 *
 * @return Inverse of matrix A
 *         error with the A is zero
 */
template<typename T>
Matrix<T, 3, 3> inv(const Matrix<T, 3, 3>& A)
{
  auto detA = det(A);
  if (detA == 0)
  {
    throw;
  }

  auto&& a = A[0][0]; auto&& b = A[0][1]; auto&& c = A[0][2];
  auto&& d = A[1][0]; auto&& e = A[1][1]; auto&& f = A[1][2];
  auto&& g = A[2][0]; auto&& h = A[2][1]; auto&& i = A[2][2];

  Matrix<T, 3, 3> invA
  { e*i - f*h, c*h - b*i, b*f - c*e,
    f*g - d*i, a*i - c*g, c*d - a*f,
    d*h - e*g, b*g - a*h, a*e - b*d };

  return invA / detA;
}

/**
 * @brief Inverse of matrix nxn
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Inverse of matrix A
 */
template<typename T, std::size_t n>
Matrix<T, n, n> inv(const Matrix<T, n, n>& A)
{
  Matrix<T, n, n> invA{};
  const auto detA = det(A);
  for(std::size_t i = 0; i < n; i++)
  {
    for(std::size_t j = 0; j < n; j++)
    {
      invA[i][j] = (((i+j) % 2) ? -1 : 1) * det(getminor(A,i,j));
    }
  }
  return trans(invA)/ detA;
}

/**
 * @brief Power of A matrix to p
 *
 * @param [in] Matrix A with nxn size
 * @param [in] Power number
 *
 * @return Matrix A power by p
 */
template<typename T, typename P, std::size_t n>
Matrix<T, n, n> pow(Matrix<T, n, n>A, P p)
{
  if(p == 0)
  {
    return eye<T, n>();
  }

  else if(p == 1)
  {
    return A;
  }

  else
  {
    if(p < 0)
    {
      A = inv(A);
      p = std::abs(p);
    }

    auto powA = ones<T, n, n>();

    powA = pow(A, p/2);
    if ((p % 2) == 0)
    {
      return powA * powA;
    }
    else
    {
      return powA * powA * A;
    }
  }
}

/**
 * @brief Check if the matrix A is identity
 *
 * @param [in] Matrix A with nxn size
 *
 * @return true - if A matrix is identity
 *         false - if A matrix is not identity
 */
template<typename T, std::size_t n>
bool isIdentity(const Matrix<T, n, n>& A)
{
  auto identity = eye<unsigned int, n>();
  auto uiA = static_cast<Matrix<unsigned int, n, n>>(A);
  return (uiA == identity);
}

/**
 * @brief
 *
 * @param [in] Matrix A ixj
 * @param [in] Matrix V ixj
 *
 * @return
 */
template<typename T, std::size_t i, std::size_t j>
Matrix<T, i, j> conv2(const Matrix<T, i, j>& A, const Matrix<T, 3, 3>& kernel)
{
  Matrix<T, i, j> result{};

  for(std::size_t it = 1; it < i-1; it++)
  {
    for(std::size_t jt = 1; jt < j-1; jt++)
    {
      result[it][jt] = kernel[0][0] * A[it-1][jt-1] +
      kernel[0][1] * A[it-1][jt] +
      kernel[0][2] * A[it-1][jt+1] +
      kernel[1][0] * A[it][jt-1] +
      kernel[1][1] * A[it][jt] +
      kernel[1][2] * A[it][jt+1] +
      kernel[2][0] * A[it+1][jt-1] +
      kernel[2][1] * A[it+1][jt] +
      kernel[2][2] * A[it+1][jt+1];
    }
  }

  return result;
}

#endif // MATRIX_ALGORITHM_HPP_
<commit_msg>update types<commit_after>#ifndef MATRIX_ALGORITHM_HPP_
#define MATRIX_ALGORITHM_HPP_

#include "matrix_basic_math.hpp"

template<typename T, std::size_t I, std::size_t J>
void print(const Matrix<T, I, J>& A)
{
  for (std::size_t i = 0; i < I; i++)
  {
    for (std::size_t j = 0; j < J; j++)
    {
      std::cout << A[i][j] << " ";
    }
    std::cout << std::endl;
  }
}

/**
 * @brief LU decomposition
 *
 * Usage: The result of function is pair of matrices where L matrix is first
 *        element of pair, the second element is U matrix
 * @param [in] Square Matrix A
 *
 * @return Two matrices L and U
 */
template<typename T, std::size_t n>
std::pair<Matrix<T,n,n>, Matrix<T,n,n>>lu(const Matrix<T,n,n>& A)
{
  auto L = eye<T, n>();
  auto U = zeros<T, n, n>();
  T sum;

  for(std::size_t j = 0; j < n; j++)
  {
    for(std::size_t i = 0; i <= j; i++)
    {
      sum = 0.0;
      for(std::size_t p = 0; p < i; p++)
      {
        sum += U[p][j] * L[i][p];
      }
      U[i][j] = A[i][j] - sum;
    }
    for(std::size_t i = j; i < n; i++)
    {
      sum = 0.0;
      for(std::size_t p = 0; p < i; p++)
      {
        sum += U[p][j] * L[i][p];
      }

      if(U[j][j] == 0)
        throw;
      else
        L[i][j] = (A[i][j] - sum) / U[j][j];
    }
  }
  return std::pair<Matrix<T,n,n>, Matrix<T,n,n>>{L, U};
}

/**
 * @brief Determinant of matrix 1x1
 *
 * @param [in] Square Matrix A with 1x1 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 1, 1>& A)
{
  return A[0][0];
}

/**
 * @brief Determinant of matrix 2x2
 *
 * @param [in] Square Matrix A with 2x2 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 2, 2>& A)
{
  auto&& a = A[0][0]; auto&& b = A[0][1];
  auto&& c = A[1][0]; auto&& d = A[1][1];

  return a*d - b*c;
}

/**
 * @brief Determinant of matrix 3x3
 *
 * @param [in] Square Matrix A with 3x3 size
 *
 * @return Determinant of matrix A
 */
template<typename T>
T det(const Matrix<T, 3, 3>& A)
{
  auto&& a = A[0][0]; auto&& b = A[0][1]; auto&& c = A[0][2];
  auto&& d = A[1][0]; auto&& e = A[1][1]; auto&& f = A[1][2];
  auto&& g = A[2][0]; auto&& h = A[2][1]; auto&& i = A[2][2];

  return a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h;
}

template<typename T, std::size_t n>
void swap_rows(Matrix<T, n, n>& data, size_t a, size_t b)
{
  if (a != b)
  {
    for (size_t k = 0; k < n; ++k)
    {
      std::swap(data[a], data[b]);
    }
  }
}

/**
 * @brief Determinant of matrix nxn
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Determinant of matrix A
 */
template<typename T, std::size_t n>
T det(Matrix<T, n, n> data)
{
  auto tmp = data;

  T factor{1};
  std::size_t pivot{0};

  auto prod = [&]()
  {
    T prod{1};

    for (std::size_t i = 0; i < n; ++i)
    {
      prod *= tmp[i][i];
    }
    return prod / factor;
  };

  for (std::size_t r = 0; r < n; ++r)
  {
    if (n <= pivot)
    {
      return prod();
    }

    std::size_t i = r;

    while (tmp[i][pivot] == 0)
    {
      ++i;
      if (n == i)
      {
        i = r;
        ++pivot;
        if (n == pivot)
        {
          return prod();
        }
      }
    }

    if (i != r)
    {
      swap_rows(tmp, i, r);
      factor *= -1;
    }

    for (std::size_t i = pivot + 1; i < n; ++i)
    {
      if (i != r)
      {
        T val = tmp[i][pivot];
        for (std::size_t j = pivot; j < n; ++j)
        {
          tmp[i][j] -= val * tmp[r][j] / tmp[r][pivot];
        }

      }
    }
    pivot++;
  }

  return prod();

}

/**
 * @brief Minor of A - A with crossed-out i-th column and j-th row
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Minor of A matrix
 */
template<typename T, std::size_t n>
Matrix<T, (n-1), (n-1)> getminor(const Matrix<T, n, n>& A, std::size_t i, std::size_t j)
{
  Matrix<T, (n-1), (n-1)> minor{};
  std::size_t colCount = 0,rowCount=0;
  for(std::size_t k = 0; k < n; k++)
  {
    if (k != i)
    {
      colCount = 0;
      for(std::size_t l = 0; l < n; l++)
      {
        if (l != j)
        {
          minor[rowCount][colCount] = A[k][l];
          colCount++;
        }
      }
      rowCount++;
    }
  }
  return minor;
}

/**
 * @brief Transpose of matrix nxm
 *
 * @param [in] Matrix A with nxm size
 *
 * @return Transpose of matrix A
 */
template<typename T, std::size_t n, std::size_t m>
Matrix<T, m, n> trans(const Matrix<T, n, m>& A)
{
  Matrix<T, m, n> transA{};

  for (std::size_t i = 0; i < n; i++)
  {
    for (std::size_t j = 0; j < m; j++)
    {
      transA[j][i] = A[i][j];
    }
  }
  return transA;
}

/**
 * @brief Inverse of matrix 1x1
 *
 * @param [in] Square Matrix A with 1x1 size
 *
 * @return Inverse of matrix A
 */
template<typename T>
Matrix<T, 1, 1> inv(const Matrix<T, 1, 1>& A)
{
  return Matrix<T, 1, 1>{ 1/det(A) };
}

/**
 * @brief Inverse of matrix 2x2
 *
 * @param [in] Square Matrix A with 2x2 size
 *
 * @return Inverse of matrix A
 *         error with the A is zero
 */
template<typename T>
Matrix<T, 2, 2> inv(const Matrix<T, 2, 2>& A)
{
  Matrix<T, 2, 2> invA{};
  auto detA = det(A);
  if (detA == 0)
  {
    throw;
  }
  invA = {A[1][1], -A[0][1],
         -A[1][0],  A[0][0]};
  invA = invA / detA;
  return invA;
}

/**
 * @brief Inverse of matrix 3x3
 *
 * @param [in] Square Matrix A with 3x3 size
 *
 * @return Inverse of matrix A
 *         error with the A is zero
 */
template<typename T>
Matrix<T, 3, 3> inv(const Matrix<T, 3, 3>& A)
{
  auto detA = det(A);
  if (detA == 0)
  {
    throw;
  }

  auto&& a = A[0][0]; auto&& b = A[0][1]; auto&& c = A[0][2];
  auto&& d = A[1][0]; auto&& e = A[1][1]; auto&& f = A[1][2];
  auto&& g = A[2][0]; auto&& h = A[2][1]; auto&& i = A[2][2];

  Matrix<T, 3, 3> invA
  { e*i - f*h, c*h - b*i, b*f - c*e,
    f*g - d*i, a*i - c*g, c*d - a*f,
    d*h - e*g, b*g - a*h, a*e - b*d };

  return invA / detA;
}

/**
 * @brief Inverse of matrix nxn
 *
 * @param [in] Square Matrix A with nxn size
 *
 * @return Inverse of matrix A
 */
template<typename T, std::size_t n>
Matrix<T, n, n> inv(const Matrix<T, n, n>& A)
{
  Matrix<T, n, n> invA{};
  const auto detA = det(A);
  for(std::size_t i = 0; i < n; i++)
  {
    for(std::size_t j = 0; j < n; j++)
    {
      invA[i][j] = (((i+j) % 2) ? -1 : 1) * det(getminor(A,i,j));
    }
  }
  return trans(invA)/ detA;
}

/**
 * @brief Power of A matrix to p
 *
 * @param [in] Matrix A with nxn size
 * @param [in] Power number
 *
 * @return Matrix A power by p
 */
template<typename T, typename P, std::size_t n>
Matrix<T, n, n> pow(Matrix<T, n, n>A, P p)
{
  if(p == 0)
  {
    return eye<T, n>();
  }

  else if(p == 1)
  {
    return A;
  }

  else
  {
    if(p < 0)
    {
      A = inv(A);
      p = std::abs(p);
    }

    auto powA = ones<T, n, n>();

    powA = pow(A, p/2);
    if ((p % 2) == 0)
    {
      return powA * powA;
    }
    else
    {
      return powA * powA * A;
    }
  }
}

/**
 * @brief Check if the matrix A is identity
 *
 * @param [in] Matrix A with nxn size
 *
 * @return true - if A matrix is identity
 *         false - if A matrix is not identity
 */
template<typename T, std::size_t n>
bool isIdentity(const Matrix<T, n, n>& A)
{
  auto identity = eye<unsigned int, n>();
  auto uiA = static_cast<Matrix<unsigned int, n, n>>(A);
  return (uiA == identity);
}

/**
 * @brief
 *
 * @param [in] Matrix A ixj
 * @param [in] Matrix V ixj
 *
 * @return
 */
template<typename T, std::size_t i, std::size_t j>
Matrix<T, i, j> conv2(const Matrix<T, i, j>& A, const Matrix<T, 3, 3>& kernel)
{
  Matrix<T, i, j> result{};

  for(std::size_t it = 1; it < i-1; it++)
  {
    for(std::size_t jt = 1; jt < j-1; jt++)
    {
      result[it][jt] = kernel[0][0] * A[it-1][jt-1] +
      kernel[0][1] * A[it-1][jt] +
      kernel[0][2] * A[it-1][jt+1] +
      kernel[1][0] * A[it][jt-1] +
      kernel[1][1] * A[it][jt] +
      kernel[1][2] * A[it][jt+1] +
      kernel[2][0] * A[it+1][jt-1] +
      kernel[2][1] * A[it+1][jt] +
      kernel[2][2] * A[it+1][jt+1];
    }
  }

  return result;
}

#endif // MATRIX_ALGORITHM_HPP_
<|endoftext|>


<commit_before><commit_msg>reciprocity variable<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2017 InversePalindrome
Nihil - EntityEvents.hpp
InversePalindrome.com
*/

#pragma once

#include "Direction.hpp"

struct DirectionChanged
{
	Direction direction;
};<commit_msg>Delete EntityEvents.hpp<commit_after><|endoftext|>


<commit_before>/* vim: set sw=4 ts=4: */
/*
 * BindingConverter.cpp
 * Implements an AST Consumer that outputs clay bindings
 *
 */

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/Triple.h"

#include "BindingsConverter.h"

using namespace clang;
using namespace llvm;

BindingsConverter::BindingsConverter(
    ostream& out,
    clang::DiagnosticOptions const &diagOpts,
    std::string const &lang,
    std::vector<string> const &match,
    std::vector<string> const &import
)   :   TextDiagnosticPrinter(llvm::errs(), diagOpts),
        out(out), succeeded(true),
        language(lang), matchNames(match), importNames(import),
        ast(NULL)
{ }

string BindingsConverter::allocateName(const string &base)
{
    if (!allocatedNames.count(base)) {
        allocatedNames.insert(base);
        return base;
    }
    unsigned i = 2;
    string s;
    while (true) {
        ostringstream out;
        out << base << i;
        s = out.str();
        if (!allocatedNames.count(s))
            break;
        ++i;
    }
    allocatedNames.insert(s);
    return s;
}

string BindingsConverter::convertBuiltinType(const BuiltinType *type) {
    switch (type->getKind()) {
    case BuiltinType::Void : return "Void";

    case BuiltinType::Bool : return "Bool";

    case BuiltinType::Char_U : return "CUChar";
    case BuiltinType::UChar : return "CUChar";
    case BuiltinType::UShort : return "UShort";
    case BuiltinType::UInt : return "UInt";
    case BuiltinType::ULong : return "CULong";
    case BuiltinType::ULongLong : return "UInt64";

    case BuiltinType::Char_S : return "CChar";
    case BuiltinType::SChar : return "CChar";
    case BuiltinType::Short : return "Short";
    case BuiltinType::Int : return "Int";
    case BuiltinType::Long : return "CLong";
    case BuiltinType::LongLong : return "Int64";

    case BuiltinType::Float : return "Float";
    case BuiltinType::Double : return "Double";

    default : {
        ostringstream out;
        out << type->getKind();
        return "UnsupportedCBuiltinType" + out.str();
    }
    }
}

static const char *getCodePointerConstructor(const FunctionType *ft)
{
    switch (ft->getCallConv()) {
    case CC_X86StdCall : return "StdCallCodePointer";
    case CC_X86FastCall : return "FastCallCodePointer";
    default : return "CCodePointer";
    }
}

string BindingsConverter::convertFPType(const FunctionNoProtoType *type)
{
    const Type *rt = type->getResultType().getTypePtr();
    ostringstream sout;
    sout << getCodePointerConstructor(type);
    sout << "[(),";
    string s = convertType(rt);
    if (s == "Void")
        s = "";
    sout << "(" << s << ")]";
    return sout.str();
}

string BindingsConverter::convertFPType(const FunctionProtoType *type)
{
    ostringstream sout;
    sout << getCodePointerConstructor(type);
    sout << "[(";
    FunctionProtoType::arg_type_iterator i, e;
    bool first = true;
    for (i = type->arg_type_begin(), e = type->arg_type_end(); i != e; ++i) {
        if (!first)
            sout << ",";
        else
            first = false;
        const Type *argType = i->getTypePtr();
        sout << convertType(argType);
    }
    sout << "),";
    const Type *rt = type->getResultType().getTypePtr();
    string s = convertType(rt);
    if (s == "Void")
        s = "";
    sout << "(" << s << ")]";
    return sout.str();
}

string BindingsConverter::convertType(const Type *type)
{
    const Type *ctype = type->getCanonicalTypeUnqualified().getTypePtr();
    if (ctype->getTypeClass() == Type::Builtin)
        return convertBuiltinType((const BuiltinType *)ctype);

    switch (type->getTypeClass()) {
    case Type::Typedef : {
        const TypedefType *t = (const TypedefType *)type;
        TypedefDecl *decl = t->getDecl();
        string name = decl->getName().str();
        const string &outName = typedefNames[name];
        assert(!outName.empty());
        return outName;
    }
    case Type::Record : {
        const RecordType *t = (const RecordType *)type;
        RecordDecl *decl = t->getDecl();
        if (decl->isUnion())
            return "AUnionType";
        string name = decl->getName().str();
        if (name.empty()) {
            if (!anonRecordNames.count(decl)) {
                pendingAnonRecords.push_back(decl);
                string outName = allocateName("UnnamedRecord");
                anonRecordNames[decl] = outName;
            }
            return anonRecordNames[decl];
        }
        if (recordBodies.count(name)) {
            return recordNames[name];
        }
        return "Opaque";
    }
    case Type::Enum :
        return "Int";
    case Type::Pointer : {
        const PointerType *t = (const PointerType *)type;
        const Type *pt = t->getPointeeType().getTypePtr();
        const Type *pt2 = pt->getCanonicalTypeUnqualified().getTypePtr();
        switch (pt2->getTypeClass()) {
        case Type::FunctionNoProto :
            return convertFPType((const FunctionNoProtoType *)pt2);
        case Type::FunctionProto :
            return convertFPType((const FunctionProtoType *)pt2);
        default :
            break;
        }
        if (pt->getTypeClass() == Type::Record) {
            const RecordType *rt = (const RecordType *)pt;
            const RecordDecl *decl = rt->getDecl();
            string name = decl->getName().str();
            if (!name.empty() && !recordBodies.count(name))
                return "OpaquePointer";
        }
        string inner = convertType(pt);
        if (inner == "Void")
            return "RawPointer";
        return "Pointer[" + inner + "]";
    }
    case Type::ConstantArray : {
        const ConstantArrayType *t = (const ConstantArrayType *)type;
        ostringstream sout;
        sout << "Array[" << convertType(t->getElementType().getTypePtr());
        sout << "," << t->getSize().getZExtValue() << "]";
        return sout.str();
    }
    case Type::IncompleteArray : {
        const IncompleteArrayType *t = (const IncompleteArrayType *)type;
        const Type *et = t->getElementType().getTypePtr();
        return "Array[" + convertType(et) + ",0]";
    }
    default : {
        string str = type->getCanonicalTypeInternal().getAsString();
        cerr << "unknown type: " << str << '\n';
        return "UnknownType";
    }
    }
}

void BindingsConverter::Initialize(ASTContext &astc) {
    ast = &astc;
}

bool BindingsConverter::declMatches(Decl *decl)
{
    if (matchNames.empty())
        return true;

    clang::SourceLocation sloc = decl->getLocation();
    clang::PresumedLoc ploc = ast->getSourceManager().getPresumedLoc(sloc);
    string filename = ploc.getFilename();

    for (vector<string>::const_iterator i = matchNames.begin();
         i != matchNames.end();
         ++i) {
        if (filename.find(*i) != string::npos)
            return true;
    }
    return false;
}

// Handle top level declarations observed in the program
void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG)
{
    for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) {
        Decl *decl = *it;

        bool matches = declMatches(decl);

        if (matches)
            decls.push_back(decl);

        switch (decl->getKind()) {
        case Decl::Record : {
            RecordDecl *x = (RecordDecl *)decl;
            string name = x->getName().str();
            if (!x->isUnion() &&
                x->isDefinition())
            {
                if (name.empty()) {
                    string outName = allocateName("UnnamedStruct");
                    anonRecordNames[x] = outName;
                }
                else {
                    assert(!recordBodies.count(name));
                    recordBodies[name] = x;
                    string outName = allocateName("Struct_" + name);
                    recordNames[name] = outName;
                }
            }
            break;
        }
        case Decl::Typedef : {
            TypedefDecl *x = (TypedefDecl *)decl;
            const Type *t = x->getTypeSourceInfo()->getType().getTypePtr();
            if (!t->isFunctionType()) {
                string name = x->getName().str();
                string outName = allocateName(name);
                typedefNames[name] = outName;
            }
            break;
        }
        default :
            break;
        }
    }
}

void BindingsConverter::generate()
{
    if (!succeeded)
        return;

    generateHeader();
    unsigned i = 0;
    while ((pendingAnonRecords.size() > 0) || (i < decls.size())) {
        if (pendingAnonRecords.size() > 0) {
            vector<RecordDecl*> pending = pendingAnonRecords;
            pendingAnonRecords.clear();
            for (unsigned j = 0; j < pending.size(); ++j)
                generateDecl(pending[j]);
        }
        else if (i < decls.size()) {
            generateDecl(decls[i]);
            ++i;
        }
    }
}

void BindingsConverter::generateDecl(Decl *decl)
{
    switch (decl->getKind()) {
    case Decl::Typedef : {
        TypedefDecl *x = (TypedefDecl *)decl;
        string name = x->getName().str();
        const Type *t = x->getTypeSourceInfo()->getType().getTypePtr();
        if (!t->isFunctionType()) {
            string type = convertType(t);
            out << '\n';
            out << "alias " << typedefNames[name] << " = "
                << convertType(t) << ";" << '\n';
        }
        break;
    }
    case Decl::Enum : {
        EnumDecl *x = (EnumDecl *)decl;
        EnumDecl::enumerator_iterator i = x->enumerator_begin();
        EnumDecl::enumerator_iterator e = x->enumerator_end();
        out << '\n';
        for (; i != e; ++i) {
            EnumConstantDecl *y = *i;
            out << "alias " << y->getName().str() << " = "
                << y->getInitVal().getZExtValue() << ";\n";
        }
        break;
    }
    case Decl::Record : {
        RecordDecl *x = (RecordDecl *)decl;
        string name = x->getName().str();
        if (!x->isUnion() &&
            x->isDefinition())
        {
            string outName = name.empty() ?
                anonRecordNames[x] : recordNames[name];
            out << '\n';
            out << "record " << outName << " (\n";
            RecordDecl::field_iterator i, e;
            int index = 0;
            for (i = x->field_begin(), e = x->field_end(); i != e; ++i) {
                FieldDecl *y = *i;
                string fname = y->getName().str();
                const Type *t = y->getType().getTypePtr();
                out << "    ";
                if (fname.empty())
                    out << "unnamed_field" << index;
                else
                    out << fname;
                out << " : " << convertType(t) << ",\n";
                ++index;
            }
            out << ");\n";
        }
        break;
    }
    case Decl::Function : {
        FunctionDecl *x = (FunctionDecl *)decl;
        string name = x->getName().str();
        if (!x->isThisDeclarationADefinition() &&
            !x->isInlineSpecified() &&
            (x->getStorageClass() == SC_Extern ||
             x->getStorageClass() == SC_None) &&
            !externsDeclared.count(name))
        {
            externsDeclared.insert(name);
            out << '\n';
            out << "external ";
            vector<string> attributes;
            if (x->hasAttr<DLLImportAttr>())
                attributes.push_back("dllimport");
            if (x->hasAttr<DLLExportAttr>())
                attributes.push_back("dllexport");
            const Type *t = x->getType().getTypePtr();
            assert(t->isFunctionType());
            const FunctionType *ft = (const FunctionType *)t;
            if (ft->getCallConv() == CC_X86StdCall)
                attributes.push_back("stdcall");
            if (ft->getCallConv() == CC_X86FastCall)
                attributes.push_back("fastcall");
            if (x->hasAttr<AsmLabelAttr>()) {
                const AsmLabelAttr *attr = x->getAttr<AsmLabelAttr>();
                string asmLabel(attr->getLabel());
                attributes.push_back("\"" + asmLabel + "\"");
            }
            if (!attributes.empty()) {
                out << "(";
                for (unsigned i = 0; i < attributes.size(); ++i) {
                    if (i != 0)
                        out << ", ";
                    out << attributes[i];
                }
                out << ") ";
            }
            out << name << "(";
            FunctionDecl::param_iterator i, e;
            int index = 0;
            for (i = x->param_begin(), e = x->param_end(); i != e; ++i) {
                ParmVarDecl *y = *i;
                string pname = y->getName().str();
                if (index != 0)
                    out << ",";
                out << "\n    ";
                if (pname.empty())
                    out << "argument" << index;
                else
                    out << pname;
                const Type *t = y->getType().getTypePtr();
                out << " : " << convertType(t);
                ++index;
            }
            if (ft->getTypeClass() == Type::FunctionProto) {
                const FunctionProtoType *fpt = (const FunctionProtoType *)ft;
                if (fpt->isVariadic()) {
                    if (index != 0)
                        out << ",";
                    out << "\n    ";
                    out << "...";
                }
            }
            out << ")";
            const Type *rt = x->getResultType().getTypePtr();
            string s = convertType(rt);
            if (s != "Void")
                out << " " << s;
            out << ";\n";
        }
        break;
    }
    case Decl::Var : {
        VarDecl *x = (VarDecl *)decl;
        string name = x->getName().str();
        if ((x->getStorageClass() == SC_Extern) &&
            !x->hasInit() &&
            !externsDeclared.count(name))
        {
            externsDeclared.insert(name);
            const Type *t = x->getType().getTypePtr();
            out << '\n';
            out << "external ";
            vector<string> attributes;
            if (x->hasAttr<DLLImportAttr>())
                attributes.push_back("dllimport");
            if (x->hasAttr<DLLExportAttr>())
                attributes.push_back("dllexport");
            if (!attributes.empty()) {
                out << "(";
                for (unsigned i = 0; i < attributes.size(); ++i) {
                    if (i != 0)
                        out << ", ";
                    out << attributes[i];
                }
                out << ") ";
            }
            out << name << " : " << convertType(t) << ";\n";
        }
        break;
    }
    default :
        break;
    }
}

void BindingsConverter::generateHeader()
{
    out << "// Automatically generated by clay-bindgen\n";
    out << "// language: " << language << "\n";
    out << '\n';
    if (language == "objective-c") {
        out << "import cocoa.objc.*;\n";
        out << '\n';
    }
    if (!importNames.empty()) {
        for (vector<string>::const_iterator i = importNames.begin();
             i != importNames.end();
             ++i) {
            out << "import " << *i << ".*;\n";
        }
        out << '\n';
    }
    out << "private alias OpaquePointer = RawPointer;\n";
    out << "private alias UnknownType = Int;\n";
    out << "private alias AUnionType = Int;\n";
    out << '\n';
}

/*
void BindingsConverter::HandleDiagnostic(clang::Diagnostic::Level level, const clang::DiagnosticInfo &info)
{
    if (level == Diagnostic::Error || level == Diagnostic::Fatal)
        succeeded = false;
    this->TextDiagnosticPrinter::HandleDiagnostic(level, info);
}
*/

<commit_msg>bindgen: make it clear the "unknown type" diagnostic is only a warning<commit_after>/* vim: set sw=4 ts=4: */
/*
 * BindingConverter.cpp
 * Implements an AST Consumer that outputs clay bindings
 *
 */

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/Triple.h"

#include "BindingsConverter.h"

using namespace clang;
using namespace llvm;

BindingsConverter::BindingsConverter(
    ostream& out,
    clang::DiagnosticOptions const &diagOpts,
    std::string const &lang,
    std::vector<string> const &match,
    std::vector<string> const &import
)   :   TextDiagnosticPrinter(llvm::errs(), diagOpts),
        out(out), succeeded(true),
        language(lang), matchNames(match), importNames(import),
        ast(NULL)
{ }

string BindingsConverter::allocateName(const string &base)
{
    if (!allocatedNames.count(base)) {
        allocatedNames.insert(base);
        return base;
    }
    unsigned i = 2;
    string s;
    while (true) {
        ostringstream out;
        out << base << i;
        s = out.str();
        if (!allocatedNames.count(s))
            break;
        ++i;
    }
    allocatedNames.insert(s);
    return s;
}

string BindingsConverter::convertBuiltinType(const BuiltinType *type) {
    switch (type->getKind()) {
    case BuiltinType::Void : return "Void";

    case BuiltinType::Bool : return "Bool";

    case BuiltinType::Char_U : return "CUChar";
    case BuiltinType::UChar : return "CUChar";
    case BuiltinType::UShort : return "UShort";
    case BuiltinType::UInt : return "UInt";
    case BuiltinType::ULong : return "CULong";
    case BuiltinType::ULongLong : return "UInt64";

    case BuiltinType::Char_S : return "CChar";
    case BuiltinType::SChar : return "CChar";
    case BuiltinType::Short : return "Short";
    case BuiltinType::Int : return "Int";
    case BuiltinType::Long : return "CLong";
    case BuiltinType::LongLong : return "Int64";

    case BuiltinType::Float : return "Float";
    case BuiltinType::Double : return "Double";

    default : {
        ostringstream out;
        out << type->getKind();
        return "UnsupportedCBuiltinType" + out.str();
    }
    }
}

static const char *getCodePointerConstructor(const FunctionType *ft)
{
    switch (ft->getCallConv()) {
    case CC_X86StdCall : return "StdCallCodePointer";
    case CC_X86FastCall : return "FastCallCodePointer";
    default : return "CCodePointer";
    }
}

string BindingsConverter::convertFPType(const FunctionNoProtoType *type)
{
    const Type *rt = type->getResultType().getTypePtr();
    ostringstream sout;
    sout << getCodePointerConstructor(type);
    sout << "[(),";
    string s = convertType(rt);
    if (s == "Void")
        s = "";
    sout << "(" << s << ")]";
    return sout.str();
}

string BindingsConverter::convertFPType(const FunctionProtoType *type)
{
    ostringstream sout;
    sout << getCodePointerConstructor(type);
    sout << "[(";
    FunctionProtoType::arg_type_iterator i, e;
    bool first = true;
    for (i = type->arg_type_begin(), e = type->arg_type_end(); i != e; ++i) {
        if (!first)
            sout << ",";
        else
            first = false;
        const Type *argType = i->getTypePtr();
        sout << convertType(argType);
    }
    sout << "),";
    const Type *rt = type->getResultType().getTypePtr();
    string s = convertType(rt);
    if (s == "Void")
        s = "";
    sout << "(" << s << ")]";
    return sout.str();
}

string BindingsConverter::convertType(const Type *type)
{
    const Type *ctype = type->getCanonicalTypeUnqualified().getTypePtr();
    if (ctype->getTypeClass() == Type::Builtin)
        return convertBuiltinType((const BuiltinType *)ctype);

    switch (type->getTypeClass()) {
    case Type::Typedef : {
        const TypedefType *t = (const TypedefType *)type;
        TypedefDecl *decl = t->getDecl();
        string name = decl->getName().str();
        const string &outName = typedefNames[name];
        assert(!outName.empty());
        return outName;
    }
    case Type::Record : {
        const RecordType *t = (const RecordType *)type;
        RecordDecl *decl = t->getDecl();
        if (decl->isUnion())
            return "AUnionType";
        string name = decl->getName().str();
        if (name.empty()) {
            if (!anonRecordNames.count(decl)) {
                pendingAnonRecords.push_back(decl);
                string outName = allocateName("UnnamedRecord");
                anonRecordNames[decl] = outName;
            }
            return anonRecordNames[decl];
        }
        if (recordBodies.count(name)) {
            return recordNames[name];
        }
        return "Opaque";
    }
    case Type::Enum :
        return "Int";
    case Type::Pointer : {
        const PointerType *t = (const PointerType *)type;
        const Type *pt = t->getPointeeType().getTypePtr();
        const Type *pt2 = pt->getCanonicalTypeUnqualified().getTypePtr();
        switch (pt2->getTypeClass()) {
        case Type::FunctionNoProto :
            return convertFPType((const FunctionNoProtoType *)pt2);
        case Type::FunctionProto :
            return convertFPType((const FunctionProtoType *)pt2);
        default :
            break;
        }
        if (pt->getTypeClass() == Type::Record) {
            const RecordType *rt = (const RecordType *)pt;
            const RecordDecl *decl = rt->getDecl();
            string name = decl->getName().str();
            if (!name.empty() && !recordBodies.count(name))
                return "OpaquePointer";
        }
        string inner = convertType(pt);
        if (inner == "Void")
            return "RawPointer";
        return "Pointer[" + inner + "]";
    }
    case Type::ConstantArray : {
        const ConstantArrayType *t = (const ConstantArrayType *)type;
        ostringstream sout;
        sout << "Array[" << convertType(t->getElementType().getTypePtr());
        sout << "," << t->getSize().getZExtValue() << "]";
        return sout.str();
    }
    case Type::IncompleteArray : {
        const IncompleteArrayType *t = (const IncompleteArrayType *)type;
        const Type *et = t->getElementType().getTypePtr();
        return "Array[" + convertType(et) + ",0]";
    }
    default : {
        string str = type->getCanonicalTypeInternal().getAsString();
        cerr << "warning: unknown type: " << str << '\n';
        return "UnknownType";
    }
    }
}

void BindingsConverter::Initialize(ASTContext &astc) {
    ast = &astc;
}

bool BindingsConverter::declMatches(Decl *decl)
{
    if (matchNames.empty())
        return true;

    clang::SourceLocation sloc = decl->getLocation();
    clang::PresumedLoc ploc = ast->getSourceManager().getPresumedLoc(sloc);
    string filename = ploc.getFilename();

    for (vector<string>::const_iterator i = matchNames.begin();
         i != matchNames.end();
         ++i) {
        if (filename.find(*i) != string::npos)
            return true;
    }
    return false;
}

// Handle top level declarations observed in the program
void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG)
{
    for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) {
        Decl *decl = *it;

        bool matches = declMatches(decl);

        if (matches)
            decls.push_back(decl);

        switch (decl->getKind()) {
        case Decl::Record : {
            RecordDecl *x = (RecordDecl *)decl;
            string name = x->getName().str();
            if (!x->isUnion() &&
                x->isDefinition())
            {
                if (name.empty()) {
                    string outName = allocateName("UnnamedStruct");
                    anonRecordNames[x] = outName;
                }
                else {
                    assert(!recordBodies.count(name));
                    recordBodies[name] = x;
                    string outName = allocateName("Struct_" + name);
                    recordNames[name] = outName;
                }
            }
            break;
        }
        case Decl::Typedef : {
            TypedefDecl *x = (TypedefDecl *)decl;
            const Type *t = x->getTypeSourceInfo()->getType().getTypePtr();
            if (!t->isFunctionType()) {
                string name = x->getName().str();
                string outName = allocateName(name);
                typedefNames[name] = outName;
            }
            break;
        }
        default :
            break;
        }
    }
}

void BindingsConverter::generate()
{
    if (!succeeded)
        return;

    generateHeader();
    unsigned i = 0;
    while ((pendingAnonRecords.size() > 0) || (i < decls.size())) {
        if (pendingAnonRecords.size() > 0) {
            vector<RecordDecl*> pending = pendingAnonRecords;
            pendingAnonRecords.clear();
            for (unsigned j = 0; j < pending.size(); ++j)
                generateDecl(pending[j]);
        }
        else if (i < decls.size()) {
            generateDecl(decls[i]);
            ++i;
        }
    }
}

void BindingsConverter::generateDecl(Decl *decl)
{
    switch (decl->getKind()) {
    case Decl::Typedef : {
        TypedefDecl *x = (TypedefDecl *)decl;
        string name = x->getName().str();
        const Type *t = x->getTypeSourceInfo()->getType().getTypePtr();
        if (!t->isFunctionType()) {
            string type = convertType(t);
            out << '\n';
            out << "alias " << typedefNames[name] << " = "
                << convertType(t) << ";" << '\n';
        }
        break;
    }
    case Decl::Enum : {
        EnumDecl *x = (EnumDecl *)decl;
        EnumDecl::enumerator_iterator i = x->enumerator_begin();
        EnumDecl::enumerator_iterator e = x->enumerator_end();
        out << '\n';
        for (; i != e; ++i) {
            EnumConstantDecl *y = *i;
            out << "alias " << y->getName().str() << " = "
                << y->getInitVal().getZExtValue() << ";\n";
        }
        break;
    }
    case Decl::Record : {
        RecordDecl *x = (RecordDecl *)decl;
        string name = x->getName().str();
        if (!x->isUnion() &&
            x->isDefinition())
        {
            string outName = name.empty() ?
                anonRecordNames[x] : recordNames[name];
            out << '\n';
            out << "record " << outName << " (\n";
            RecordDecl::field_iterator i, e;
            int index = 0;
            for (i = x->field_begin(), e = x->field_end(); i != e; ++i) {
                FieldDecl *y = *i;
                string fname = y->getName().str();
                const Type *t = y->getType().getTypePtr();
                out << "    ";
                if (fname.empty())
                    out << "unnamed_field" << index;
                else
                    out << fname;
                out << " : " << convertType(t) << ",\n";
                ++index;
            }
            out << ");\n";
        }
        break;
    }
    case Decl::Function : {
        FunctionDecl *x = (FunctionDecl *)decl;
        string name = x->getName().str();
        if (!x->isThisDeclarationADefinition() &&
            !x->isInlineSpecified() &&
            (x->getStorageClass() == SC_Extern ||
             x->getStorageClass() == SC_None) &&
            !externsDeclared.count(name))
        {
            externsDeclared.insert(name);
            out << '\n';
            out << "external ";
            vector<string> attributes;
            if (x->hasAttr<DLLImportAttr>())
                attributes.push_back("dllimport");
            if (x->hasAttr<DLLExportAttr>())
                attributes.push_back("dllexport");
            const Type *t = x->getType().getTypePtr();
            assert(t->isFunctionType());
            const FunctionType *ft = (const FunctionType *)t;
            if (ft->getCallConv() == CC_X86StdCall)
                attributes.push_back("stdcall");
            if (ft->getCallConv() == CC_X86FastCall)
                attributes.push_back("fastcall");
            if (x->hasAttr<AsmLabelAttr>()) {
                const AsmLabelAttr *attr = x->getAttr<AsmLabelAttr>();
                string asmLabel(attr->getLabel());
                attributes.push_back("\"" + asmLabel + "\"");
            }
            if (!attributes.empty()) {
                out << "(";
                for (unsigned i = 0; i < attributes.size(); ++i) {
                    if (i != 0)
                        out << ", ";
                    out << attributes[i];
                }
                out << ") ";
            }
            out << name << "(";
            FunctionDecl::param_iterator i, e;
            int index = 0;
            for (i = x->param_begin(), e = x->param_end(); i != e; ++i) {
                ParmVarDecl *y = *i;
                string pname = y->getName().str();
                if (index != 0)
                    out << ",";
                out << "\n    ";
                if (pname.empty())
                    out << "argument" << index;
                else
                    out << pname;
                const Type *t = y->getType().getTypePtr();
                out << " : " << convertType(t);
                ++index;
            }
            if (ft->getTypeClass() == Type::FunctionProto) {
                const FunctionProtoType *fpt = (const FunctionProtoType *)ft;
                if (fpt->isVariadic()) {
                    if (index != 0)
                        out << ",";
                    out << "\n    ";
                    out << "...";
                }
            }
            out << ")";
            const Type *rt = x->getResultType().getTypePtr();
            string s = convertType(rt);
            if (s != "Void")
                out << " " << s;
            out << ";\n";
        }
        break;
    }
    case Decl::Var : {
        VarDecl *x = (VarDecl *)decl;
        string name = x->getName().str();
        if ((x->getStorageClass() == SC_Extern) &&
            !x->hasInit() &&
            !externsDeclared.count(name))
        {
            externsDeclared.insert(name);
            const Type *t = x->getType().getTypePtr();
            out << '\n';
            out << "external ";
            vector<string> attributes;
            if (x->hasAttr<DLLImportAttr>())
                attributes.push_back("dllimport");
            if (x->hasAttr<DLLExportAttr>())
                attributes.push_back("dllexport");
            if (!attributes.empty()) {
                out << "(";
                for (unsigned i = 0; i < attributes.size(); ++i) {
                    if (i != 0)
                        out << ", ";
                    out << attributes[i];
                }
                out << ") ";
            }
            out << name << " : " << convertType(t) << ";\n";
        }
        break;
    }
    default :
        break;
    }
}

void BindingsConverter::generateHeader()
{
    out << "// Automatically generated by clay-bindgen\n";
    out << "// language: " << language << "\n";
    out << '\n';
    if (language == "objective-c") {
        out << "import cocoa.objc.*;\n";
        out << '\n';
    }
    if (!importNames.empty()) {
        for (vector<string>::const_iterator i = importNames.begin();
             i != importNames.end();
             ++i) {
            out << "import " << *i << ".*;\n";
        }
        out << '\n';
    }
    out << "private alias OpaquePointer = RawPointer;\n";
    out << "private alias UnknownType = Int;\n";
    out << "private alias AUnionType = Int;\n";
    out << '\n';
}

/*
void BindingsConverter::HandleDiagnostic(clang::Diagnostic::Level level, const clang::DiagnosticInfo &info)
{
    if (level == Diagnostic::Error || level == Diagnostic::Fatal)
        succeeded = false;
    this->TextDiagnosticPrinter::HandleDiagnostic(level, info);
}
*/

<|endoftext|>


<commit_before>#ifndef MODULE_HPP
#define MODULE_HPP

#include <ace-c/Scope.hpp>
#include <ace-c/SourceLocation.hpp>
#include <ace-c/Tree.hpp>
#include <ace-c/SymbolType.hpp>

#include <vector>
#include <string>
#include <functional>

class Module {
public:
    Module(const std::string &name, const SourceLocation &location);
    Module(const Module &other) = delete;

    inline const std::string &GetName() const { return m_name; }
    inline const SourceLocation &GetLocation() const { return m_location; }

    inline TreeNode<Module*> *GetImportTreeLink() { return m_tree_link; }
    inline const TreeNode<Module*> *GetImportTreeLink() const { return m_tree_link; }
    inline void SetImportTreeLink(TreeNode<Module*> *tree_link) { m_tree_link = tree_link; }

    /** Check to see if the identifier exists in multiple scopes, starting
        from the currently opened scope.
        If this_scope_only is set to true, only the current scope will be
        searched.
    */
    Identifier *LookUpIdentifier(const std::string &name, bool this_scope_only);

    /** Check to see if the identifier exists in this scope or above this one.
        Will only search the number of depth levels it is given.
        Pass `1` for this scope only.
    */
    Identifier *LookUpIdentifierDepth(const std::string &name, int depth_level);

    /** Look up a symbol in this module by name */
    SymbolTypePtr_t LookupSymbolType(const std::string &name);
    /** Look up an instance of a generic type with the given parameters */
    SymbolTypePtr_t LookupGenericInstance(const SymbolTypePtr_t &base,
        const std::vector<SymbolTypePtr_t> &params);

    Tree<Scope> m_scopes;

private:
    std::string m_name;
    SourceLocation m_location;

    /** A link to where this module exists in the import tree */
    TreeNode<Module*> *m_tree_link;

    SymbolTypePtr_t PerformLookup(
        std::function<SymbolTypePtr_t(TreeNode<Scope>*)>,
        std::function<SymbolTypePtr_t(Module *mod)>);
};

#endif
<commit_msg>Delete module.hpp<commit_after><|endoftext|>