<commit_before>/*************************************************************************
 *
 *  $RCSfile: AdabasStatDlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 17:10:43 $
 *
 *  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 EXPRESS 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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
    //========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setCurrentDataSourceName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            case DST_DBASE:
            case DST_FLAT:
            case DST_MSACCESS:
            case DST_ADO:
            case DST_ODBC:
            case DST_MYSQL_ODBC:
            case DST_MYSQL_JDBC:
            case DST_LDAP:
            case DST_CALC:
            case DST_MOZILLA:
            case DST_EVOLUTION:
            case DST_OUTLOOK    :
            case DST_OUTLOOKEXP:
            case DST_JDBC:
            case DST_ORACLE_JDBC:
            case DST_USERDEFINE1:   /// first user defined driver
            case DST_USERDEFINE2:
            case DST_USERDEFINE3:
            case DST_USERDEFINE4:
            case DST_USERDEFINE5:
            case DST_USERDEFINE6:
            case DST_USERDEFINE7:
            case DST_USERDEFINE8:
            case DST_USERDEFINE9:
            case DST_USERDEFINE10:
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS mozab05 (1.2.66); FILE MERGED 2005/01/31 08:14:18 windly 1.2.66.2: RESYNC: (1.2-1.3); FILE MERGED 2004/12/03 10:26:00 windly 1.2.66.1: #i20088# add ThunderBird address book type to database wizward<commit_after>/*************************************************************************
 *
 *  $RCSfile: AdabasStatDlg.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-21 12:40:19 $
 *
 *  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 EXPRESS 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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
    //========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setCurrentDataSourceName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            case DST_DBASE:
            case DST_FLAT:
            case DST_MSACCESS:
            case DST_ADO:
            case DST_ODBC:
            case DST_MYSQL_ODBC:
            case DST_MYSQL_JDBC:
            case DST_LDAP:
            case DST_CALC:
            case DST_MOZILLA:
            case DST_THUNDERBIRD:
            case DST_EVOLUTION:
            case DST_OUTLOOK    :
            case DST_OUTLOOKEXP:
            case DST_JDBC:
            case DST_ORACLE_JDBC:
            case DST_USERDEFINE1:   /// first user defined driver
            case DST_USERDEFINE2:
            case DST_USERDEFINE3:
            case DST_USERDEFINE4:
            case DST_USERDEFINE5:
            case DST_USERDEFINE6:
            case DST_USERDEFINE7:
            case DST_USERDEFINE8:
            case DST_USERDEFINE9:
            case DST_USERDEFINE10:
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<|endoftext|>


<commit_before>#include "FTContour.h"

static const unsigned int SECOND_ORDER_CURVE = 2;
static const unsigned int THIRD_ORDER_CURVE = 3;

FTContour::FTContour( FT_Vector* contour, char* pointTags, unsigned int numberOfPoints)
:   kBSTEPSIZE( 0.2f)
{
    FTVector<ContourPoint> tempPointList;

    for( unsigned int pointIndex = 0; pointIndex < numberOfPoints; ++ pointIndex)
    {
        if( pointIndex == numberOfPoints - 1)
        {
            if( pointTags[pointIndex] == FT_Curve_Tag_Conic && pointTags[0] == FT_Curve_Tag_Conic)
            {
                tempPointList.push_back( ContourPoint( FTPoint( contour[pointIndex]), pointTags[pointIndex]));

                FTPoint implicitPoint( static_cast<float>( contour[pointIndex].x + contour[0].x) * 0.5f,
                                       static_cast<float>( contour[pointIndex].y + contour[0].y) * 0.5f,
                                       0);
                tempPointList.push_back( ContourPoint( implicitPoint, FT_Curve_Tag_On));
            }
            else
            {
                tempPointList.push_back( ContourPoint( FTPoint( contour[pointIndex]), pointTags[pointIndex]));
            }
        }
        else if( pointTags[pointIndex] == FT_Curve_Tag_Conic && pointTags[pointIndex + 1] == FT_Curve_Tag_Conic)
        {
            tempPointList.push_back( ContourPoint( FTPoint( contour[pointIndex]), pointTags[pointIndex]));

            FTPoint implicitPoint( static_cast<float>( contour[pointIndex].x + contour[pointIndex + 1].x) * 0.5f,
                                   static_cast<float>( contour[pointIndex].y + contour[pointIndex + 1].y) * 0.5f,
                                   0);
            tempPointList.push_back( ContourPoint( implicitPoint, FT_Curve_Tag_On));
        }
        else
        {
            tempPointList.push_back( ContourPoint( FTPoint( contour[pointIndex]), pointTags[pointIndex]));
        }
    }

    for( unsigned int pointIndex = 0; pointIndex < tempPointList.size();)
    {
        switch( tempPointList[pointIndex].tag)
        {
            case FT_Curve_Tag_Conic:
                EvaluateConicCurve( pointIndex, tempPointList);
                ++pointIndex;
                break;
            case FT_Curve_Tag_Cubic:
                EvaluateCubicCurve( pointIndex, tempPointList);
                pointIndex += 2;
                break;
            case FT_Curve_Tag_On:
            default:
                AddPoint( tempPointList[pointIndex].point);
                ++pointIndex;
                break;
        }
    }

}

void FTContour::AddPoint( FTPoint point)
{
    if( pointList.empty() || point != pointList[pointList.size() - 1])
    {
        pointList.push_back( point);
    }
}

void FTContour::EvaluateConicCurve( const int index, const FTVector<ContourPoint>& pointList)
{
    unsigned int controlPoint = index;
    unsigned int startPoint = index -1;
    unsigned int endPoint = index + 1;

    if( 0 == controlPoint)
    {
        startPoint = pointList.size() - 1;
    }
    else if( pointList.size() - 1 == controlPoint)
    {
        endPoint = 0;
    }

    ctrlPtArray[0][0] = pointList[startPoint].point.x;   ctrlPtArray[0][1] = pointList[startPoint].point.y;
    ctrlPtArray[1][0] = pointList[controlPoint].point.x; ctrlPtArray[1][1] = pointList[controlPoint].point.y;
    ctrlPtArray[2][0] = pointList[endPoint].point.x;     ctrlPtArray[2][1] = pointList[endPoint].point.y;

    evaluateCurve( SECOND_ORDER_CURVE);
}

void FTContour::EvaluateCubicCurve( const int index, const FTVector<ContourPoint>& pointList)
{
    unsigned int controlPointOne = index;
    unsigned int controlPointTwo = index + 1;
    unsigned int startPoint = index -1;

    if( controlPointOne == pointList.size() - 1)
    {
        controlPointTwo = 0;
    }

    unsigned int endPoint = controlPointTwo + 1;

    if( controlPointTwo == pointList.size() - 1)
    {
        endPoint = 0;
    }

    if( 0 == controlPointOne)
    {
        startPoint = pointList.size() - 1;
    }

    ctrlPtArray[0][0] = pointList[startPoint].point.x;      ctrlPtArray[0][1] = pointList[startPoint].point.y;
    ctrlPtArray[1][0] = pointList[controlPointOne].point.x; ctrlPtArray[1][1] = pointList[controlPointOne].point.y;
    ctrlPtArray[2][0] = pointList[controlPointTwo].point.x; ctrlPtArray[2][1] = pointList[controlPointTwo].point.y;
    ctrlPtArray[3][0] = pointList[endPoint].point.x;        ctrlPtArray[3][1] = pointList[endPoint].point.y;

    evaluateCurve( THIRD_ORDER_CURVE);
}

void FTContour::deCasteljau( const float t, const int n)
{
    //Calculating successive b(i)'s using de Casteljau algorithm.
    for( int i = 1; i <= n; i++)
    {
        for( int k = 0; k <= (n - i); k++)
        {
            bValues[i][k][0] = (1 - t) * bValues[i - 1][k][0] + t * bValues[i - 1][k + 1][0];
            bValues[i][k][1] = (1 - t) * bValues[i - 1][k][1] + t * bValues[i - 1][k + 1][1];
        }
    }

    //Specify next vertex to be included on curve
    AddPoint( FTPoint( bValues[n][0][0], bValues[n][0][1], 0.0f));
}

void FTContour::evaluateCurve( const int n)
{
    // setting the b(0) equal to the control points
    for( int i = 0; i <= n; i++)
    {
        bValues[0][i][0] = ctrlPtArray[i][0];
        bValues[0][i][1] = ctrlPtArray[i][1];
    }

    float t; //parameter for curve point calc. [0.0, 1.0]

    for( int m = 0; m <= ( 1 / kBSTEPSIZE); m++)
    {
        t = m * kBSTEPSIZE;
        deCasteljau( t, n);  //calls to evaluate point on curve at t.
    }
}

<commit_msg>Contour extraction is now one pass. The code is a bit ugly at this stage though.<commit_after>#include "FTContour.h"

static const unsigned int SECOND_ORDER_CURVE = 2;
static const unsigned int THIRD_ORDER_CURVE = 3;

FTContour::FTContour( FT_Vector* contour, char* pointTags, unsigned int numberOfPoints)
:   kBSTEPSIZE( 0.2f)
{
    for( unsigned int pointIndex = 0; pointIndex < numberOfPoints; ++ pointIndex)
    {
        char pointTag = pointTags[pointIndex];

        if( pointTag == FT_Curve_Tag_On)
        {
            AddPoint( FTPoint( contour[pointIndex]));
            continue;
        }

        FTPoint controlPoint( contour[pointIndex]);
        FTPoint previousPoint = ( 0 == pointIndex)
                                ? FTPoint( contour[numberOfPoints - 1])
                                : pointList[pointList.size() - 1];

        FTPoint nextPoint = ( pointIndex == numberOfPoints - 1)
                            ? pointList[0]
                            : FTPoint( contour[pointIndex + 1]);

        if( pointTag == FT_Curve_Tag_Conic)
        {
            char nextPointTag = ( pointIndex == numberOfPoints - 1)
                                ? pointTags[0]
                                : pointTags[pointIndex + 1];

            while( nextPointTag == FT_Curve_Tag_Conic)
            {
                nextPoint = FTPoint( static_cast<float>( controlPoint.x + nextPoint.x) * 0.5f,
                                     static_cast<float>( controlPoint.y + nextPoint.y) * 0.5f,
                                     0);

                ctrlPtArray[0][0] = previousPoint.x; ctrlPtArray[0][1] = previousPoint.y;
                ctrlPtArray[1][0] = controlPoint.x;  ctrlPtArray[1][1] = controlPoint.y;
                ctrlPtArray[2][0] = nextPoint.x;     ctrlPtArray[2][1] = nextPoint.y;

                evaluateCurve( SECOND_ORDER_CURVE);
                ++pointIndex;

                previousPoint = nextPoint;
                controlPoint = FTPoint( contour[pointIndex]);
                nextPoint = ( pointIndex == numberOfPoints - 1)
                            ? pointList[0]
                            : FTPoint( contour[pointIndex + 1]);
                nextPointTag = ( pointIndex == numberOfPoints - 1)
                               ? pointTags[0]
                               : pointTags[pointIndex + 1];
            }

            ctrlPtArray[0][0] = previousPoint.x; ctrlPtArray[0][1] = previousPoint.y;
            ctrlPtArray[1][0] = controlPoint.x;  ctrlPtArray[1][1] = controlPoint.y;
            ctrlPtArray[2][0] = nextPoint.x;     ctrlPtArray[2][1] = nextPoint.y;

            evaluateCurve( SECOND_ORDER_CURVE);
            continue;
        }

        if( pointTag == FT_Curve_Tag_Cubic)
        {
            FTPoint controlPoint2 = nextPoint;

            FTPoint nextPoint = ( pointIndex == numberOfPoints - 2)
                                ? pointList[0]
                                : FTPoint( contour[pointIndex + 2]);

            ctrlPtArray[0][0] = previousPoint.x; ctrlPtArray[0][1] = previousPoint.y;
            ctrlPtArray[1][0] = controlPoint.x;  ctrlPtArray[1][1] = controlPoint.y;
            ctrlPtArray[2][0] = controlPoint2.x; ctrlPtArray[2][1] = controlPoint2.y;
            ctrlPtArray[3][0] = nextPoint.x;     ctrlPtArray[3][1] = nextPoint.y;

            evaluateCurve( THIRD_ORDER_CURVE);
            ++pointIndex;
            continue;
        }
    }
}

void FTContour::AddPoint( FTPoint point)
{
    if( pointList.empty() || point != pointList[pointList.size() - 1])
    {
        pointList.push_back( point);
    }
}

void FTContour::deCasteljau( const float t, const int n)
{
    //Calculating successive b(i)'s using de Casteljau algorithm.
    for( int i = 1; i <= n; i++)
    {
        for( int k = 0; k <= (n - i); k++)
        {
            bValues[i][k][0] = (1 - t) * bValues[i - 1][k][0] + t * bValues[i - 1][k + 1][0];
            bValues[i][k][1] = (1 - t) * bValues[i - 1][k][1] + t * bValues[i - 1][k + 1][1];
        }
    }

    //Specify next vertex to be included on curve
    AddPoint( FTPoint( bValues[n][0][0], bValues[n][0][1], 0.0f));
}

void FTContour::evaluateCurve( const int n)
{
    // setting the b(0) equal to the control points
    for( int i = 0; i <= n; i++)
    {
        bValues[0][i][0] = ctrlPtArray[i][0];
        bValues[0][i][1] = ctrlPtArray[i][1];
    }

    float t; //parameter for curve point calc. [0.0, 1.0]

    for( int m = 0; m <= ( 1 / kBSTEPSIZE); m++)
    {
        t = m * kBSTEPSIZE;
        deCasteljau( t, n);  //calls to evaluate point on curve at t.
    }
}

<|endoftext|>


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

namespace dbaui
{
    class SAL_NO_VTABLE IUpdateHelper
    {
    public:
        virtual void updateString(sal_Int32 _nPos, const ::rtl::OUString& _sValue) = 0;
        virtual void updateDouble(sal_Int32 _nPos,const double& _nValue) = 0;
        virtual void updateInt(sal_Int32 _nPos,const sal_Int32& _nValue) = 0;
        virtual void updateNull(sal_Int32 _nPos, ::sal_Int32 sqlType) = 0;
        virtual void moveToInsertRow() = 0;
        virtual void insertRow() = 0;
    };
}

#endif // DBAUI_IUPDATEHELPER_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.2.334); FILE MERGED 2008/03/31 13:27:43 rt 1.2.334.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: IUpdateHelper.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef DBAUI_IUPDATEHELPER_HXX
#define DBAUI_IUPDATEHELPER_HXX

namespace dbaui
{
    class SAL_NO_VTABLE IUpdateHelper
    {
    public:
        virtual void updateString(sal_Int32 _nPos, const ::rtl::OUString& _sValue) = 0;
        virtual void updateDouble(sal_Int32 _nPos,const double& _nValue) = 0;
        virtual void updateInt(sal_Int32 _nPos,const sal_Int32& _nValue) = 0;
        virtual void updateNull(sal_Int32 _nPos, ::sal_Int32 sqlType) = 0;
        virtual void moveToInsertRow() = 0;
        virtual void insertRow() = 0;
    };
}

#endif // DBAUI_IUPDATEHELPER_HXX

<|endoftext|>


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

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif

#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

class filter_info_impl;
class XMLSourceFileDialog;

class XMLFilterTestDialog : public ModalDialog
{
public:
    XMLFilterTestDialog( Window* pParent, ResMgr& rResMgr, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxMSF  );
    virtual ~XMLFilterTestDialog();

    void test( const filter_info_impl& rFilterInfo );
    const filter_info_impl* getFilterInfo() const;

    void updateCurrentDocumentButtonState( com::sun::star::uno::Reference< com::sun::star::lang::XComponent > * pRef = NULL );

private:
    DECL_LINK(ClickHdl_Impl, PushButton * );

    void onExportBrowse();
    void onExportCurrentDocument();
    void onImportBrowse();
    void onImportRecentDocument();
    void initDialog();

    com::sun::star::uno::Reference< com::sun::star::lang::XComponent > getFrontMostDocument( const rtl::OUString& rServiceName );
    void import( const rtl::OUString& rURL );
    void displayXMLFile( const rtl::OUString& rURL );
    void doExport( com::sun::star::uno::Reference< com::sun::star::lang::XComponent > xComp );

private:
    com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;
    com::sun::star::uno::Reference< com::sun::star::document::XEventBroadcaster > mxGlobalBroadcaster;
    com::sun::star::uno::Reference< com::sun::star::document::XEventListener > mxGlobalEventListener;
    com::sun::star::uno::WeakReference< com::sun::star::lang::XComponent > mxLastFocusModel;

    ResMgr&             mrResMgr;

    rtl::OUString   maImportRecentFile;
    rtl::OUString   maExportRecentFile;

    FixedLine   maFLExport;
    FixedText   maFTExportXSLT;
    FixedText   maFTExportXSLTFile;
    FixedText   maFTTransformDocument;
    PushButton  maPBExportBrowse;
    PushButton  maPBCurrentDocument;
    FixedText   maFTNameOfCurentFile;
    FixedLine   maFLImport;
    FixedText   maFTImportXSLT;
    FixedText   maFTImportXSLTFile;
    FixedText   maFTImportTemplate;
    FixedText   maFTImportTemplateFile;
    FixedText   maFTTransformFile;
    CheckBox    maCBXDisplaySource;
    PushButton  maPBImportBrowse;
    PushButton  maPBRecentDocument;
    FixedText   maFTNameOfRecentFile;
    PushButton  maPBClose;
    HelpButton  maPBHelp;

    XMLSourceFileDialog*    mpSourceDLG;
    filter_info_impl*       mpFilterInfo;

    String maDialogTitle;

    ::rtl::OUString sDTDPath;
};

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

#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/document/XEventBroadcaster.hpp>
#include <vcl/dialog.hxx>

#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#include <vcl/fixed.hxx>
#include <svtools/poolitem.hxx>

class filter_info_impl;
class XMLSourceFileDialog;

class XMLFilterTestDialog : public ModalDialog
{
public:
    XMLFilterTestDialog( Window* pParent, ResMgr& rResMgr, const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxMSF  );
    virtual ~XMLFilterTestDialog();

    void test( const filter_info_impl& rFilterInfo );
    const filter_info_impl* getFilterInfo() const;

    void updateCurrentDocumentButtonState( com::sun::star::uno::Reference< com::sun::star::lang::XComponent > * pRef = NULL );

private:
    DECL_LINK(ClickHdl_Impl, PushButton * );

    void onExportBrowse();
    void onExportCurrentDocument();
    void onImportBrowse();
    void onImportRecentDocument();
    void initDialog();

    com::sun::star::uno::Reference< com::sun::star::lang::XComponent > getFrontMostDocument( const rtl::OUString& rServiceName );
    void import( const rtl::OUString& rURL );
    void displayXMLFile( const rtl::OUString& rURL );
    void doExport( com::sun::star::uno::Reference< com::sun::star::lang::XComponent > xComp );

private:
    com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > mxMSF;
    com::sun::star::uno::Reference< com::sun::star::document::XEventBroadcaster > mxGlobalBroadcaster;
    com::sun::star::uno::Reference< com::sun::star::document::XEventListener > mxGlobalEventListener;
    com::sun::star::uno::WeakReference< com::sun::star::lang::XComponent > mxLastFocusModel;

    ResMgr&             mrResMgr;

    rtl::OUString   maImportRecentFile;
    rtl::OUString   maExportRecentFile;

    FixedLine   maFLExport;
    FixedText   maFTExportXSLT;
    FixedText   maFTExportXSLTFile;
    FixedText   maFTTransformDocument;
    PushButton  maPBExportBrowse;
    PushButton  maPBCurrentDocument;
    FixedText   maFTNameOfCurentFile;
    FixedLine   maFLImport;
    FixedText   maFTImportXSLT;
    FixedText   maFTImportXSLTFile;
    FixedText   maFTImportTemplate;
    FixedText   maFTImportTemplateFile;
    FixedText   maFTTransformFile;
    CheckBox    maCBXDisplaySource;
    PushButton  maPBImportBrowse;
    PushButton  maPBRecentDocument;
    FixedText   maFTNameOfRecentFile;
    PushButton  maPBClose;
    HelpButton  maPBHelp;

    XMLSourceFileDialog*    mpSourceDLG;
    filter_info_impl*       mpFilterInfo;

    String maDialogTitle;

    ::rtl::OUString sDTDPath;
};

#endif
<|endoftext|>


<commit_before>#include "GridLoader.h"
#include "Grid.h"
#include "GridManager.h"
#include "GridTask.h"

#include "debugging.h"
#include "Log.h"
#include "Object.h"
#include "Server.h"
#include "ServerConfig.h"
#include "Tools.h"

#include "Poco/Observer.h"
#include "Poco/Timestamp.h"
#include "Poco/Task.h"

using Poco::Observer;
using Poco::Timestamp;

/**
 * Initializes the grid loader, which manages and handles all grids
 *
 */
GridLoader::GridLoader()
{
    // Create the GridManager and add a grid finished update callback
    _gridManager = new GridManager(sConfig.getIntConfig("MapThreads"));
    _gridManager->addObserver(Observer<GridLoader, Poco::TaskFinishedNotification>(*this, &GridLoader::gridUpdated));

    for (Poco::UInt16 x = 0; x < MAX_X; x++)
        for (Poco::UInt16 y = 0; y < MAX_Y; y++)
            _isGridLoaded[x][y] = false;

    // Set LoS range
    Grid::losRange = sConfig.getIntConfig("LoSRange");
    sLog.out(Message::PRIO_TRACE, "\t[OK] LoS Range set to: %d", Grid::losRange);
    sLog.out(Message::PRIO_TRACE, "\t[OK] Map threads set to: %d", sConfig.getIntConfig("MapThreads"));

    // Check for correct grid size
    ASSERT((MAP_MAX_X - MAP_MIN_X) / UNITS_PER_CELL < MAX_X)
    ASSERT((MAP_MAX_Z - MAP_MIN_Z) / UNITS_PER_CELL < MAX_Y)
}

/**
 * Class destructor, frees memory
 *
 */
GridLoader::~GridLoader()
{
    _gridManager->joinAll();
    delete _gridManager;
}

/**
 * Checks if a grid is loaded, and if it's not, it loads it
 *
 * @param x X position of the grid
 * @param y Y position of the grid
 * @return True if the grid is successfully added
 */
bool GridLoader::checkAndLoad(Poco::UInt16 x, Poco::UInt16 y)
{
    ASSERT(x > 0 && x <= MAX_X)
    ASSERT(y > 0 && y <= MAX_Y)

    if (_isGridLoaded[x][y])
        return true;

    Grid* grid = new Grid(x, y);
    bool inserted = _grids.insert(rde::make_pair(grid->hashCode(), grid)).second;
    _isGridLoaded[x][y] = inserted;

    sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been created (%d)", x, y, inserted);
    return inserted;
}

/**
 * Gets a Grid. Should be safe as std::set iterators are safe, but we should keep and eye to this.
 *
 * @param x Cell Position x
 * @param y Cell Position y
 */
Grid* GridLoader::GetGrid(Poco::UInt16 x, Poco::UInt16 y)
{
    Grid* grid = NULL;
    if (!_isGridLoaded[x][y])
        return grid;

    GridsMap::const_iterator itr = _grids.find((x << 16) | y);
    if (itr != _grids.end())
        grid = itr->second;

    return grid;
}

/**
 * Checks if a Grid is loaded, if not it loads it. Finally, returns the Grid
 *
 * @param x X position of the Grid
 * @param y Y position of the Grid
 * @return The grid itself
 */
Grid* GridLoader::GetGridOrLoad(Poco::UInt16 x, Poco::UInt16 y)
{
    if (checkAndLoad(x, y))
        return GetGrid(x, y);
    return NULL;
}

/**
 * Given an object, it adds it to a Grid
 *
 * @param x X position of the Grid
 * @param y Y position of the Grid
 * @param object Object to be added
 * @return Grid where the object has been added
 */
Grid* GridLoader::addObjectTo(Poco::UInt16 x, Poco::UInt16 y, SharedPtr<Object> object)
{
    if (!checkAndLoad(x, y))
        return NULL;

    Grid* grid = NULL;
    if (grid = GetGrid(x, y))
        if (!grid->addObject(object))
            grid = NULL;

    return grid;
}

/**
 * Adds an object to the Grid where it should be
 *
 * @param object Object to be added
 * @return Grid where it has been added
 */
Grid* GridLoader::addObject(SharedPtr<Object> object)
{
    Vector2D pos = object->GetPosition();
    return addObjectTo(Tools::GetXCellFromPos(pos.x), Tools::GetYCellFromPos(pos.z), object);
}

/**
 * Removes an object from the Grid where it is
 *
 * @param object Object to be removed
 * @return True if the object has been removed
 */
bool GridLoader::removeObject(Object* object)
{
    Poco::UInt16 x = Tools::GetXCellFromPos(object->GetPosition().x);
    Poco::UInt16 y = Tools::GetYCellFromPos(object->GetPosition().z);

    if (!_isGridLoaded[x][y])
        return false;

    if (Grid* grid = GetGrid(x, y))
    {
        grid->removeObject(object->GetGUID());
        object->SetGrid(NULL);
        return true;
    }

    return false;
}

/**
 * Thread where the Grids are updating
 *
 */
void GridLoader::update(Poco::UInt64 diff)
{
    // Do NOT, never, iterate the list, iterate a safe copy!
    GridsMap grids = _grids;

    _gridManager->queue(grids.size());
    for (GridsMap::const_iterator itr = grids.begin(); itr != grids.end(); )
    {
        Grid* grid = itr->second;
        itr++;

        // Start a task to update the grid
        _gridManager->start(new GridTask(grid, diff));
    }

    // Wait for all map updates to end
    _gridManager->wait();
}

void GridLoader::gridUpdated(Poco::TaskFinishedNotification* nf)
{
    GridTask* task = (GridTask*)nf->task();
    nf->release();

    // If update fails, something went really wrong, delete this grid
    // If the grid has no players in it, check for nearby grids, if they are not loaded or have no players, remove it
    if (!task->getResult())
    {
        Grid* grid = task->getGrid();
        sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been deleted (%d %d)", grid->GetPositionX(), grid->GetPositionY(), grid->hasPlayers(), grid->isForceLoaded());

        _isGridLoaded[grid->GetPositionX()][grid->GetPositionY()] = false;
        _grids.erase(grid->hashCode());
        //delete grid;
    }

    _gridManager->dequeue();
}
<commit_msg>Core/Grid: Outcomment a line, free memory<commit_after>#include "GridLoader.h"
#include "Grid.h"
#include "GridManager.h"
#include "GridTask.h"

#include "debugging.h"
#include "Log.h"
#include "Object.h"
#include "Server.h"
#include "ServerConfig.h"
#include "Tools.h"

#include "Poco/Observer.h"
#include "Poco/Timestamp.h"
#include "Poco/Task.h"

using Poco::Observer;
using Poco::Timestamp;

/**
 * Initializes the grid loader, which manages and handles all grids
 *
 */
GridLoader::GridLoader()
{
    // Create the GridManager and add a grid finished update callback
    _gridManager = new GridManager(sConfig.getIntConfig("MapThreads"));
    _gridManager->addObserver(Observer<GridLoader, Poco::TaskFinishedNotification>(*this, &GridLoader::gridUpdated));

    for (Poco::UInt16 x = 0; x < MAX_X; x++)
        for (Poco::UInt16 y = 0; y < MAX_Y; y++)
            _isGridLoaded[x][y] = false;

    // Set LoS range
    Grid::losRange = sConfig.getIntConfig("LoSRange");
    sLog.out(Message::PRIO_TRACE, "\t[OK] LoS Range set to: %d", Grid::losRange);
    sLog.out(Message::PRIO_TRACE, "\t[OK] Map threads set to: %d", sConfig.getIntConfig("MapThreads"));

    // Check for correct grid size
    ASSERT((MAP_MAX_X - MAP_MIN_X) / UNITS_PER_CELL < MAX_X)
    ASSERT((MAP_MAX_Z - MAP_MIN_Z) / UNITS_PER_CELL < MAX_Y)
}

/**
 * Class destructor, frees memory
 *
 */
GridLoader::~GridLoader()
{
    _gridManager->joinAll();
    delete _gridManager;
}

/**
 * Checks if a grid is loaded, and if it's not, it loads it
 *
 * @param x X position of the grid
 * @param y Y position of the grid
 * @return True if the grid is successfully added
 */
bool GridLoader::checkAndLoad(Poco::UInt16 x, Poco::UInt16 y)
{
    ASSERT(x > 0 && x <= MAX_X)
    ASSERT(y > 0 && y <= MAX_Y)

    if (_isGridLoaded[x][y])
        return true;

    Grid* grid = new Grid(x, y);
    bool inserted = _grids.insert(rde::make_pair(grid->hashCode(), grid)).second;
    _isGridLoaded[x][y] = inserted;

    sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been created (%d)", x, y, inserted);
    return inserted;
}

/**
 * Gets a Grid. Should be safe as std::set iterators are safe, but we should keep and eye to this.
 *
 * @param x Cell Position x
 * @param y Cell Position y
 */
Grid* GridLoader::GetGrid(Poco::UInt16 x, Poco::UInt16 y)
{
    Grid* grid = NULL;
    if (!_isGridLoaded[x][y])
        return grid;

    GridsMap::const_iterator itr = _grids.find((x << 16) | y);
    if (itr != _grids.end())
        grid = itr->second;

    return grid;
}

/**
 * Checks if a Grid is loaded, if not it loads it. Finally, returns the Grid
 *
 * @param x X position of the Grid
 * @param y Y position of the Grid
 * @return The grid itself
 */
Grid* GridLoader::GetGridOrLoad(Poco::UInt16 x, Poco::UInt16 y)
{
    if (checkAndLoad(x, y))
        return GetGrid(x, y);
    return NULL;
}

/**
 * Given an object, it adds it to a Grid
 *
 * @param x X position of the Grid
 * @param y Y position of the Grid
 * @param object Object to be added
 * @return Grid where the object has been added
 */
Grid* GridLoader::addObjectTo(Poco::UInt16 x, Poco::UInt16 y, SharedPtr<Object> object)
{
    if (!checkAndLoad(x, y))
        return NULL;

    Grid* grid = NULL;
    if (grid = GetGrid(x, y))
        if (!grid->addObject(object))
            grid = NULL;

    return grid;
}

/**
 * Adds an object to the Grid where it should be
 *
 * @param object Object to be added
 * @return Grid where it has been added
 */
Grid* GridLoader::addObject(SharedPtr<Object> object)
{
    Vector2D pos = object->GetPosition();
    return addObjectTo(Tools::GetXCellFromPos(pos.x), Tools::GetYCellFromPos(pos.z), object);
}

/**
 * Removes an object from the Grid where it is
 *
 * @param object Object to be removed
 * @return True if the object has been removed
 */
bool GridLoader::removeObject(Object* object)
{
    Poco::UInt16 x = Tools::GetXCellFromPos(object->GetPosition().x);
    Poco::UInt16 y = Tools::GetYCellFromPos(object->GetPosition().z);

    if (!_isGridLoaded[x][y])
        return false;

    if (Grid* grid = GetGrid(x, y))
    {
        grid->removeObject(object->GetGUID());
        object->SetGrid(NULL);
        return true;
    }

    return false;
}

/**
 * Thread where the Grids are updating
 *
 */
void GridLoader::update(Poco::UInt64 diff)
{
    // Do NOT, never, iterate the list, iterate a safe copy!
    GridsMap grids = _grids;

    _gridManager->queue(grids.size());
    for (GridsMap::const_iterator itr = grids.begin(); itr != grids.end(); )
    {
        Grid* grid = itr->second;
        itr++;

        // Start a task to update the grid
        _gridManager->start(new GridTask(grid, diff));
    }

    // Wait for all map updates to end
    _gridManager->wait();
}

void GridLoader::gridUpdated(Poco::TaskFinishedNotification* nf)
{
    GridTask* task = (GridTask*)nf->task();
    nf->release();

    // If update fails, something went really wrong, delete this grid
    // If the grid has no players in it, check for nearby grids, if they are not loaded or have no players, remove it
    if (!task->getResult())
    {
        Grid* grid = task->getGrid();
        sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been deleted (%d %d)", grid->GetPositionX(), grid->GetPositionY(), grid->hasPlayers(), grid->isForceLoaded());

        _isGridLoaded[grid->GetPositionX()][grid->GetPositionY()] = false;
        _grids.erase(grid->hashCode());
        delete grid;
    }

    _gridManager->dequeue();
}
<|endoftext|>


<commit_before>#include "Landmarks.hh"

Landmarks::Landmark::Landmark()
{
  this->pos[0] = 0.0;
  this->pos[1] = 0.0;
  this->id = -1;
  this->life = LIFE;
  this->totalTimeObserved = 0;
  this->range = -1;
  this->bearing = -1;
}

Landmarks::Landmark::~Landmark()
{}

Landmarks::Landmarks(double degrees)
{
  this->DBSize = 0;
  this->EKFLandmarks = 0;
  this->degreePerScan = degrees;
  this->IDtoID.reserve(MAXLANDMARKS);
  this->landmarkDB.reserve(MAXLANDMARKS);
}

Landmarks::~Landmarks()
{}

int Landmarks::getDBSize() const
{
  return (this->DBSize);
}

int Landmarks::getSLamId(int id) const
{
  for(int i = 0; i < this->EKFLandmarks; ++i)
    {
      if(IDtoID[i].first == id)
	return (IDtoID[i].second);
    }
  return (-1);
}

int Landmarks::addSlamId(int landmarkID, int slamID)
{
  std::pair<int, int> newSlamID;
  newSlamID.first = landmarkID;
  newSlamID.first = slamID;
  this->IDtoID.push_back(newSlamID);
  ++this->EKFLandmarks;
  return (0);
}

int Landmarks::getAssociation(Landmark &lm)
{
  for(int i = 0; i < this->DBSize; ++i)
    {
      if(this->distance(lm, (*landmarkDB[i])) < MAXERROR && landmarkDB[i]->id != -1)
	{
	  landmarkDB[i]->life = LIFE;
	  ++landmarkDB[i]->totalTimeObserved;
	  landmarkDB[i]->bearing = lm.bearing;
	  landmarkDB[i]->range = lm.range;
	  return (landmarkDB[i]->id);
	}
    }
  return -1;
}

double Landmarks::distance(double x1, double y1, double x2, double y2) const
{
  return (sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)));
}

double Landmarks::distance(const Landmark &lm1, const Landmark &lm2) const
{
  return (sqrt(pow(lm1.pos[0] - lm2.pos[0], 2) + pow(lm1.pos[1] - lm2.pos[1], 2)));
}

int Landmarks::addToDB(const Landmark &lm)
{
  if(static_cast<unsigned int>(DBSize + 1) < this->landmarkDB.size())
    {
      landmarkDB[DBSize]->pos[0] = lm.pos[0];
      landmarkDB[DBSize]->pos[1] = lm.pos[1];
      landmarkDB[DBSize]->life = LIFE;
      landmarkDB[DBSize]->id = DBSize;
      landmarkDB[DBSize]->totalTimeObserved = 1;
      landmarkDB[DBSize]->bearing = lm.bearing;
      landmarkDB[DBSize]->range = lm.range;
      landmarkDB[DBSize]->a = lm.a;
      landmarkDB[DBSize]->b= lm.b;
      ++DBSize;
      return (DBSize - 1);
    }
  return (-1);
}

double Landmarks::distanceToLine(double x, double y, double a, double b)
{
  double ao = -1.0 / a;
  double bo = y - ao * x;
  double px = (b - bo) / (ao - a);
  double py = ((ao * (b - bo)) / (ao - a)) + bo;
  return (this->distance(x, y, px, py));
}

std::vector<Landmarks::Landmark *>Landmarks::getLandmarkDB() const
{
  std::vector<Landmark *> res;

  for (int i = 0; i < this->DBSize; ++i)
    {
      res[i] = this->landmarkDB[i];
    }
  return (res);
}
<commit_msg>SLAM: add getClosestAssociation function<commit_after>#include "Landmarks.hh"

Landmarks::Landmark::Landmark()
{
  this->pos[0] = 0.0;
  this->pos[1] = 0.0;
  this->id = -1;
  this->life = LIFE;
  this->totalTimeObserved = 0;
  this->range = -1;
  this->bearing = -1;
}

Landmarks::Landmark::~Landmark()
{}

Landmarks::Landmarks(double degrees)
{
  this->DBSize = 0;
  this->EKFLandmarks = 0;
  this->degreePerScan = degrees;
  this->IDtoID.reserve(MAXLANDMARKS);
  this->landmarkDB.reserve(MAXLANDMARKS);
}

Landmarks::~Landmarks()
{}

int Landmarks::getDBSize() const
{
  return (this->DBSize);
}

int Landmarks::getSLamId(int id) const
{
  for(int i = 0; i < this->EKFLandmarks; ++i)
    {
      if(IDtoID[i].first == id)
	return (IDtoID[i].second);
    }
  return (-1);
}

int Landmarks::addSlamId(int landmarkID, int slamID)
{
  std::pair<int, int> newSlamID;
  newSlamID.first = landmarkID;
  newSlamID.first = slamID;
  this->IDtoID.push_back(newSlamID);
  ++this->EKFLandmarks;
  return (0);
}

int Landmarks::getAssociation(Landmark &lm)
{
  for(int i = 0; i < this->DBSize; ++i)
    {
      if(this->distance(lm, (*landmarkDB[i])) < MAXERROR && landmarkDB[i]->id != -1)
	{
	  landmarkDB[i]->life = LIFE;
	  ++landmarkDB[i]->totalTimeObserved;
	  landmarkDB[i]->bearing = lm.bearing;
	  landmarkDB[i]->range = lm.range;
	  return (landmarkDB[i]->id);
	}
    }
  return -1;
}

double Landmarks::distance(double x1, double y1, double x2, double y2) const
{
  return (sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)));
}

double Landmarks::distance(const Landmark &lm1, const Landmark &lm2) const
{
  return (sqrt(pow(lm1.pos[0] - lm2.pos[0], 2) + pow(lm1.pos[1] - lm2.pos[1], 2)));
}

int Landmarks::addToDB(const Landmark &lm)
{
  if(static_cast<unsigned int>(DBSize + 1) < this->landmarkDB.size())
    {
      landmarkDB[DBSize]->pos[0] = lm.pos[0];
      landmarkDB[DBSize]->pos[1] = lm.pos[1];
      landmarkDB[DBSize]->life = LIFE;
      landmarkDB[DBSize]->id = DBSize;
      landmarkDB[DBSize]->totalTimeObserved = 1;
      landmarkDB[DBSize]->bearing = lm.bearing;
      landmarkDB[DBSize]->range = lm.range;
      landmarkDB[DBSize]->a = lm.a;
      landmarkDB[DBSize]->b= lm.b;
      ++DBSize;
      return (DBSize - 1);
    }
  return (-1);
}

double Landmarks::distanceToLine(double x, double y, double a, double b)
{
  double ao = -1.0 / a;
  double bo = y - ao * x;
  double px = (b - bo) / (ao - a);
  double py = ((ao * (b - bo)) / (ao - a)) + bo;
  return (this->distance(x, y, px, py));
}

std::vector<Landmarks::Landmark *>Landmarks::getLandmarkDB() const
{
  std::vector<Landmark *> res;

  for (int i = 0; i < this->DBSize; ++i)
    {
      res[i] = this->landmarkDB[i];
    }
  return (res);
}

void Landmarks::getClosestAssociation(Landmark *lm, int &id, int &totalTimeObserved)
{
  int closestLandmark = 0;
  double temp;
  double leastDistance = 99999; // 100k meter, big distance

  for(int i = 0; i < DBSize; ++i)
    {
      if(static_cast<unsigned int>(landmarkDB[i]->totalTimeObserved) > MINOBSERVATIONS)
	{
	  temp = this->distance(*lm, *landmarkDB[i]);
	  if(temp < leastDistance)
	    {
	      leastDistance = temp;
	      closestLandmark = landmarkDB[i]->id;
	    }
	}
    }
  if(leastDistance == 99999)
    id = -1;
  else
    {
      id = landmarkDB[closestLandmark]->id;
      totalTimeObserved = landmarkDB[closestLandmark]->totalTimeObserved;
    }
}
<|endoftext|>


<commit_before><commit_msg>First test<commit_after><|endoftext|>


<commit_before><commit_msg>Update de_web_plugin.cpp<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/HeaderGenerator.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CompoundData.h"
#include "IECore/IECore.h"
#include <sys/utsname.h>
#include <unistd.h>
#include <pwd.h>
#include <boost/format.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>

using namespace std;
using namespace IECore;
using namespace boost::posix_time;

std::vector<HeaderGenerator::DataHeaderFn> HeaderGenerator::m_generators;

CompoundObjectPtr HeaderGenerator::header()
{
	CompoundObjectPtr newHeader = new CompoundObject();
	for ( std::vector<DataHeaderFn>::const_iterator it = m_generators.begin(); it != m_generators.end(); it++ )
	{
		(*it)( newHeader );
	}
	return newHeader;
}

bool HeaderGenerator::registerDataHeaderGenerator( DataHeaderFn generator )
{
	m_generators.push_back( generator );
	return true;
}

/*
 *
 * Standard data header functions.
 *
 */

static void ieCoreHeaderGenerator( CompoundObjectPtr header )
{
	header->members()["ieCoreVersion"] = new StringData( versionString() );
}

static void unameHeaderGenerator( CompoundObjectPtr header )
{
	struct utsname name;

	if ( !uname( &name ) )
	{
		CompoundDataPtr compound = new CompoundData();
		compound->writable()["systemName"] = new StringData( name.sysname );
		compound->writable()["nodeName"] = new StringData( name.nodename );
		compound->writable()["systemRelease"] = new StringData( name.release );
        compound->writable()["systemVersion"] = new StringData( name.version );
		compound->writable()["machineName"] = new StringData( name.machine );
		header->members()["host"] = compound;
	}
}

static void userHeaderGenerator( CompoundObjectPtr header )
{
	 uid_t uid = getuid();
	struct passwd *st = getpwuid( uid );
	if ( st )
	{
		header->members()["userName"] = new StringData( st->pw_name );
	}
	else
	{
		header->members()["userID"] = new LongData( uid );
	}
}

static void timeStampHeaderGenerator( CompoundObjectPtr header )
{
	header->members()["timeStamp"] = new StringData( to_simple_string( second_clock::local_time() ) );
}

static bool resIeCore = HeaderGenerator::registerDataHeaderGenerator( &ieCoreHeaderGenerator );
static bool resUname = HeaderGenerator::registerDataHeaderGenerator( &unameHeaderGenerator );
static bool resName = HeaderGenerator::registerDataHeaderGenerator( &userHeaderGenerator );
static bool resTime = HeaderGenerator::registerDataHeaderGenerator( &timeStampHeaderGenerator );
<commit_msg>Fixed formatting<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "IECore/HeaderGenerator.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/CompoundData.h"
#include "IECore/IECore.h"
#include <sys/utsname.h>
#include <unistd.h>
#include <pwd.h>
#include <boost/format.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>

using namespace std;
using namespace IECore;
using namespace boost::posix_time;

std::vector<HeaderGenerator::DataHeaderFn> HeaderGenerator::m_generators;

CompoundObjectPtr HeaderGenerator::header()
{
	CompoundObjectPtr newHeader = new CompoundObject();
	for ( std::vector<DataHeaderFn>::const_iterator it = m_generators.begin(); it != m_generators.end(); it++ )
	{
		(*it)( newHeader );
	}
	return newHeader;
}

bool HeaderGenerator::registerDataHeaderGenerator( DataHeaderFn generator )
{
	m_generators.push_back( generator );
	return true;
}

/*
 *
 * Standard data header functions.
 *
 */

static void ieCoreHeaderGenerator( CompoundObjectPtr header )
{
	header->members()["ieCoreVersion"] = new StringData( versionString() );
}

static void unameHeaderGenerator( CompoundObjectPtr header )
{
	struct utsname name;

	if ( !uname( &name ) )
	{
		CompoundDataPtr compound = new CompoundData();
		compound->writable()["systemName"] = new StringData( name.sysname );
		compound->writable()["nodeName"] = new StringData( name.nodename );
		compound->writable()["systemRelease"] = new StringData( name.release );
		compound->writable()["systemVersion"] = new StringData( name.version );
		compound->writable()["machineName"] = new StringData( name.machine );
		header->members()["host"] = compound;
	}
}

static void userHeaderGenerator( CompoundObjectPtr header )
{
	uid_t uid = getuid();
	struct passwd *st = getpwuid( uid );
	if ( st )
	{
		header->members()["userName"] = new StringData( st->pw_name );
	}
	else
	{
		header->members()["userID"] = new LongData( uid );
	}
}

static void timeStampHeaderGenerator( CompoundObjectPtr header )
{
	header->members()["timeStamp"] = new StringData( to_simple_string( second_clock::local_time() ) );
}

static bool resIeCore = HeaderGenerator::registerDataHeaderGenerator( &ieCoreHeaderGenerator );
static bool resUname = HeaderGenerator::registerDataHeaderGenerator( &unameHeaderGenerator );
static bool resName = HeaderGenerator::registerDataHeaderGenerator( &userHeaderGenerator );
static bool resTime = HeaderGenerator::registerDataHeaderGenerator( &timeStampHeaderGenerator );
<|endoftext|>


<commit_before>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
<commit_msg>finished the builder gui layout which seems to work properly.<commit_after>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0, 10, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "All Available Thoughts"), 0, 1)
		.Add(new BStringView(BRect(10, 10, 200, 30), NULL, "Ordered Thoughts"), 5, 1)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 2, 4, 10)
		.Add(rightButton, 4, 4)
		.Add(leftButton, 4, 5)
		.Add(topButton, 4, 6)
		.Add(upButton, 4, 7)
		.Add(downButton, 4, 8)
		.Add(bottomButton, 4, 9)
		.Add(new BScrollView("scroll_ordered", orderedThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 5, 2, 5, 10)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
<|endoftext|>


<commit_before>/**
 * \file MainFrame.cpp
 * \brief Main Windows Class
 */

#include "MainFrame.h"

#include "icons.h"

BEGIN_EVENT_TABLE(MainFrame,wxFrame)
    EVT_MENU(ID_EXIT, MainFrame::OnExit)
    EVT_MENU(ID_OPEN, MainFrame::OpenReplay)
    EVT_MENU(ID_RUN, MainFrame::RunAI)
    EVT_MENU(ID_SAVE_AISCRIPT, MainFrame::SaveToAiscript)
    EVT_MENU(ID_WEBSITE, MainFrame::Website)
    EVT_MENU(ID_ABOUT, MainFrame::About)
    EVT_BUTTON(ID_RUN_BUTTON, MainFrame::RunAI)
    EVT_CLOSE(MainFrame::OnClose)
    EVT_COMBOBOX(ID_PLAYERSELECTION, MainFrame::SelectPlayer)
END_EVENT_TABLE()

MainFrame::MainFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)
: wxFrame(parent, id, title, position, size, style) {
    /**
    *   Constructor for the Main frame.
    */
    CreateGUIControls();
    replayFilename = "";
    playerSelected = false;
    replayOpen = false;
}

MainFrame::~MainFrame() {
    /**
    *   Destructor for the Main form.
    */
}

void MainFrame::CreateGUIControls() {
    /**
    *   Creates all of the GUI controls on the main form.
    */

    // Set window properties and title bar
    SetTitle(wxT(NAME));
    SetIcon(wxNullIcon);

    // Menu Bar
    menuBar = new wxMenuBar();

    fileMenu = new wxMenu();
    fileMenu->Append(ID_OPEN, _T("&Open"));
    fileMenu->Append(ID_RUN, _T("&Run"));
    fileMenu->Append(ID_SAVE_AISCRIPT, _T("&Save to aiscript.bin"));
    fileMenu->Append(ID_EXIT, _T("&Quit"));
    menuBar->Append(fileMenu, _T("&File"));

    helpMenu = new wxMenu();
    helpMenu->Append(ID_WEBSITE, _T("&Website"));
    helpMenu->Append(ID_ABOUT, _T("&About"));
    menuBar->Append(helpMenu, _T("&Help"));

    SetMenuBar(menuBar);

    // Main Panel
    sizer = new wxBoxSizer(wxVERTICAL);
    panel = new wxPanel(this);
    panel->SetSizer(sizer);

    // Controls
    controlsSizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->Add(controlsSizer,0);

    // Player Selection
    playerSelectionLabel = new wxStaticText(panel, -1, wxT("Player:"));
    playerSelection = new wxComboBox(panel, ID_PLAYERSELECTION, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL,wxCB_READONLY|wxCB_SORT);
    playerSelection->Append(wxT("Open a Replay first"));

    controlsSizer->Add(playerSelectionLabel);
    controlsSizer->Add(playerSelection);

    // Run Button

    runButton = new wxBitmapButton(panel, ID_RUN_BUTTON, wxBitmap(controller_xpm));
    controlsSizer->Add(runButton);

    // Text Area

    text = new wxTextCtrl(panel, ID_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxVSCROLL|wxHSCROLL|wxNO_BORDER|wxTE_READONLY|wxTE_MULTILINE);
    sizer->Add(text,1,wxEXPAND|wxALL);
}

void MainFrame::OnClose(wxCloseEvent& event) {
    /**
    *   Event handler for the form closing event
    *   Exit the ChaosConnect Program
    */
    exit(0);
}

void MainFrame::OnExit( wxCommandEvent& event ) {
    /**
    *   Event handler for the form closing event
    *   Exit the ChaosConnect Program
    */
    exit(0);
}

void MainFrame::OpenReplay( wxCommandEvent& event ) {
    /**
    *   Event handler opening a replay
    */
    wxFileDialog file_dialog(this, wxT("Select a replay to open"), wxT(""), wxT(""), wxT("*.rep"), wxOPEN);
    file_dialog.ShowModal();

    replayFilename = file_dialog.GetPath();

    *text << "Opening replay " << replayFilename << "...\n";

    replay = new Replay((char*)replayFilename.c_str());

    *text << "Parsing Player List...\n";

    playerSelection->Clear();
    for(int i = 0; i < 8; i++) {
        if (replay->playerID[i] > -1 ) {
            playerSelection->Append(wxString(replay->playerName[i]));
        }
    }

    replayOpen = true;
    playerSelected = false;
}

void MainFrame::SaveToAiscript( wxCommandEvent& event ) {
    /**
    *   Event handler to save a replay to aiscript.bin
    */
    if ( replayOpen && playerSelected ) {
        wxFileDialog file_dialog(this, wxT("Select location to save to"), wxT(""), wxT("aiscript.bin"), wxT("*.bin"), wxSAVE);
        file_dialog.ShowModal();

        wxString filename = file_dialog.GetPath();

        *text << "Saving AI as " << filename << "...\n";

        rep2ai->saveToAiscript((char*)filename.c_str());
    }
}

void MainFrame::SelectPlayer( wxCommandEvent& event ) {
    /**
    *   Event handler for selecting a player
    */
	wxString player(playerSelection->GetString(playerSelection->GetCurrentSelection()));

	if(replayFilename == "") return;

	if ( rep2ai != NULL ) free(rep2ai);

    rep2ai = new Rep2AI(replay);

    *text << "Creating AI script for " << player << "...\n";

	rep2ai->findPlayer((char*)player.c_str());

    *text << "Writing aiscript.bin...\n";
	rep2ai->makeAI();

    *text << "Build Order:\n" << rep2ai->getBuildOrderAsText();

    playerSelected = true;
}

void MainFrame::RunAI( wxCommandEvent& event ) {
    /**
    *   Event handler for running the AI
    */
    if ( replayOpen && playerSelected ) {
        rep2ai->runAI();
    }
}

void MainFrame::About( wxCommandEvent& event ) {
    /**
     * Event handler for the about box
     */

     wxDialog about(this, -1, wxString("About"));
     wxBoxSizer about_sizer(wxVERTICAL);
     wxHtmlWindow about_html(&about);

     about.SetSizer(&about_sizer);

     about_html.SetPage(
         wxString("
")+wxString(NAME)+wxString("
")+
         wxString("
By: ")+wxString(AUTHOR)+wxString("
")+
         wxString("
")+wxString(WEBSITE)+wxString("
")
         );

     about_sizer.Add(&about_html,1,wxEXPAND);

     about.ShowModal();
}

void MainFrame::Website( wxCommandEvent& event ) {
    /**
     * Event handler for website
     */
     wxLaunchDefaultBrowser(WEBSITE);
}
<commit_msg>- fixed another memory leak<commit_after>/**
 * \file MainFrame.cpp
 * \brief Main Windows Class
 */

#include "MainFrame.h"

#include "icons.h"

BEGIN_EVENT_TABLE(MainFrame,wxFrame)
    EVT_MENU(ID_EXIT, MainFrame::OnExit)
    EVT_MENU(ID_OPEN, MainFrame::OpenReplay)
    EVT_MENU(ID_RUN, MainFrame::RunAI)
    EVT_MENU(ID_SAVE_AISCRIPT, MainFrame::SaveToAiscript)
    EVT_MENU(ID_WEBSITE, MainFrame::Website)
    EVT_MENU(ID_ABOUT, MainFrame::About)
    EVT_BUTTON(ID_RUN_BUTTON, MainFrame::RunAI)
    EVT_CLOSE(MainFrame::OnClose)
    EVT_COMBOBOX(ID_PLAYERSELECTION, MainFrame::SelectPlayer)
END_EVENT_TABLE()

MainFrame::MainFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)
: wxFrame(parent, id, title, position, size, style) {
    /**
    *   Constructor for the Main frame.
    */
    CreateGUIControls();
    replayFilename = "";
    playerSelected = false;
    replayOpen = false;

    replay = NULL;
    rep2ai = NULL;
}

MainFrame::~MainFrame() {
    /**
    *   Destructor for the Main form.
    */
}

void MainFrame::CreateGUIControls() {
    /**
    *   Creates all of the GUI controls on the main form.
    */

    // Set window properties and title bar
    SetTitle(wxT(NAME));
    SetIcon(wxNullIcon);

    // Menu Bar
    menuBar = new wxMenuBar();

    fileMenu = new wxMenu();
    fileMenu->Append(ID_OPEN, _T("&Open"));
    fileMenu->Append(ID_RUN, _T("&Run"));
    fileMenu->Append(ID_SAVE_AISCRIPT, _T("&Save to aiscript.bin"));
    fileMenu->Append(ID_EXIT, _T("&Quit"));
    menuBar->Append(fileMenu, _T("&File"));

    helpMenu = new wxMenu();
    helpMenu->Append(ID_WEBSITE, _T("&Website"));
    helpMenu->Append(ID_ABOUT, _T("&About"));
    menuBar->Append(helpMenu, _T("&Help"));

    SetMenuBar(menuBar);

    // Main Panel
    sizer = new wxBoxSizer(wxVERTICAL);
    panel = new wxPanel(this);
    panel->SetSizer(sizer);

    // Controls
    controlsSizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->Add(controlsSizer,0);

    // Player Selection
    playerSelectionLabel = new wxStaticText(panel, -1, wxT("Player:"));
    playerSelection = new wxComboBox(panel, ID_PLAYERSELECTION, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL,wxCB_READONLY|wxCB_SORT);
    playerSelection->Append(wxT("Open a Replay first"));

    controlsSizer->Add(playerSelectionLabel);
    controlsSizer->Add(playerSelection);

    // Run Button

    runButton = new wxBitmapButton(panel, ID_RUN_BUTTON, wxBitmap(controller_xpm));
    controlsSizer->Add(runButton);

    // Text Area

    text = new wxTextCtrl(panel, ID_TEXT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxVSCROLL|wxHSCROLL|wxNO_BORDER|wxTE_READONLY|wxTE_MULTILINE);
    sizer->Add(text,1,wxEXPAND|wxALL);
}

void MainFrame::OnClose(wxCloseEvent& event) {
    /**
    *   Event handler for the form closing event
    *   Exit the ChaosConnect Program
    */
    exit(0);
}

void MainFrame::OnExit( wxCommandEvent& event ) {
    /**
    *   Event handler for the form closing event
    *   Exit the ChaosConnect Program
    */
    exit(0);
}

void MainFrame::OpenReplay( wxCommandEvent& event ) {
    /**
    *   Event handler opening a replay
    */
    wxFileDialog file_dialog(this, wxT("Select a replay to open"), wxT(""), wxT(""), wxT("*.rep"), wxOPEN);
    file_dialog.ShowModal();

    replayFilename = file_dialog.GetPath();

    *text << "Opening replay " << replayFilename << "...\n";

    if ( replay != NULL ) free(replay);

    replay = new Replay((char*)replayFilename.c_str());

    *text << "Parsing Player List...\n";

    playerSelection->Clear();
    for(int i = 0; i < 8; i++) {
        if (replay->playerID[i] > -1 ) {
            playerSelection->Append(wxString(replay->playerName[i]));
        }
    }

    replayOpen = true;
    playerSelected = false;
}

void MainFrame::SaveToAiscript( wxCommandEvent& event ) {
    /**
    *   Event handler to save a replay to aiscript.bin
    */
    if ( replayOpen && playerSelected ) {
        wxFileDialog file_dialog(this, wxT("Select location to save to"), wxT(""), wxT("aiscript.bin"), wxT("*.bin"), wxSAVE);
        file_dialog.ShowModal();

        wxString filename = file_dialog.GetPath();

        *text << "Saving AI as " << filename << "...\n";

        rep2ai->saveToAiscript((char*)filename.c_str());
    }
}

void MainFrame::SelectPlayer( wxCommandEvent& event ) {
    /**
    *   Event handler for selecting a player
    */
	wxString player(playerSelection->GetString(playerSelection->GetCurrentSelection()));

	if(replayFilename == "") return;

	if ( rep2ai != NULL ) free(rep2ai);

    rep2ai = new Rep2AI(replay);

    *text << "Creating AI script for " << player << "...\n";

	rep2ai->findPlayer((char*)player.c_str());

    *text << "Writing aiscript.bin...\n";
	rep2ai->makeAI();

    *text << "Build Order:\n" << rep2ai->getBuildOrderAsText();

    playerSelected = true;
}

void MainFrame::RunAI( wxCommandEvent& event ) {
    /**
    *   Event handler for running the AI
    */
    if ( replayOpen && playerSelected ) {
        rep2ai->runAI();
    }
}

void MainFrame::About( wxCommandEvent& event ) {
    /**
     * Event handler for the about box
     */

     wxDialog about(this, -1, wxString("About"));
     wxBoxSizer about_sizer(wxVERTICAL);
     wxHtmlWindow about_html(&about);

     about.SetSizer(&about_sizer);

     about_html.SetPage(
         wxString("
")+wxString(NAME)+wxString("
")+
         wxString("
By: ")+wxString(AUTHOR)+wxString("
")+
         wxString("
")+wxString(WEBSITE)+wxString("
")
         );

     about_sizer.Add(&about_html,1,wxEXPAND);

     about.ShowModal();
}

void MainFrame::Website( wxCommandEvent& event ) {
    /**
     * Event handler for website
     */
     wxLaunchDefaultBrowser(WEBSITE);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <numeric>

#include "MoveCache.h"

using namespace std;

////////////////
//    変数    //
////////////////

// LGR
int tgr1_rate = 80;
int lgrf1_rate = 0;
bool use_lgrf2 = false;

// Based on Oakfoam http://oakfoam.com/

LGR::LGR()
{
  reset();
}

void
LGR::reset()
{
  tgr1.reset();
  tgr1_hash.reset();
  tgr1_count.reset();
  if (tgr1_rate > 0) {
    size_t s = 2 * pure_board_max;
    tgr1.reset(new int16_t[s * tgr_num]);
    fill_n(tgr1.get(), s * tgr_num, PASS);
    tgr1_hash.reset(new uint32_t[s * tgr_num]);
    tgr1_last.reset(new uint32_t[s * tgr_num]);
    tgr1_count.reset(new uint16_t[s]);
    fill_n(tgr1_count.get(), s, 0);
  }

  lgrf1.reset();
  if (lgrf1_rate > 0) {
    lgrf1.reset(new uint32_t[2 * pure_board_max]);
    fill_n(lgrf1.get(), 2 * pure_board_max, PASS);
    lgrf1_last.reset(new uint32_t[2 * pure_board_max]);
  }

  lgrf2.reset();
  if (use_lgrf2) {
    lgrf2.reset(new int[2 * pure_board_max * pure_board_max]);
    fill_n(lgrf2.get(), 2 * pure_board_max * pure_board_max, PASS);
  }
}

void
LGR::setTGR1(int col, int pos1, int val, uint32_t hash_last, uint32_t hash)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  //int index = (c * pure_board_max + pos1) * 0xffff + hash_last;
  int index = (c * pure_board_max + id1);
  uint16_t count = min(tgr_num, tgr1_count[index]);
  for (int i = 0; i < count; i++) {
    if (tgr1_hash[index * tgr_num + i] == hash) {
      tgr1[index * tgr_num + i] = val;
      return;
    }
  }
  uint16_t n = tgr1_count[index] ++;
  n = n % tgr_num;
  int idx = index * tgr_num + n;
  tgr1[idx] = val;
  tgr1_hash[idx] = hash;
  tgr1_last[idx] = hash_last;
}

int
LGR::getTGR1(int col, int pos1, const game_info_t* game)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  uint32_t hash_last = MD2(game->pat, pos1);
  //int index = (c * pure_board_max + pos1) * 0xffff + hash_last;
  int index = c * pure_board_max + id1;
  uint16_t count = min(tgr_num, tgr1_count[index]);
  for (int i = 0; i < count; i++) {
    int pos = tgr1[index * tgr_num + i];
    if (pos == PASS)
      continue;
    if (tgr1_last[index * tgr_num + i] != hash_last)
      continue;
    uint32_t hash = MD2(game->pat, pos);
    //PrintBoard(game);
    //cerr << FormatMove(pos1) << endl;
    //DisplayInputMD2(hash_last);
    //cerr << FormatMove(pos) << endl;
    //DisplayInputMD2(hash);
    //DisplayInputMD2(tgr1_hash[index * tgr_num + i]);
    if (tgr1_hash[index * tgr_num + i] == hash) {
      //cerr << "HIT" << endl;
      return pos;
    }
    //cerr << "MISS" << endl;
  }
  return PASS;
}

int
LGR::getLGRF1(int col, int pos1, const game_info_t* game)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  uint32_t hash_last = MD2(game->pat, pos1);
  if (lgrf1_last[c * pure_board_max + id1] != hash_last)
    return PASS;
  return lgrf1[c * pure_board_max + id1];
}

void
LGR::setLGRF1(int col, int pos1, int pos, uint32_t hash2)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  lgrf1[c * pure_board_max + id1] = pos;
  lgrf1_last[c * pure_board_max + id1] = hash2;
}

void
LGR::clearLGRF1(int col, int pos1)
{
  this->setLGRF1(col, pos1, PASS, 0);
}

int
LGR::getLGRF2(int col, int pos1, int pos2)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  pos1 = board_pos_id[pos1];
  pos2 = board_pos_id[pos2];
  int c = col - 1;
  return lgrf2[(c * pure_board_max + pos1) * pure_board_max + pos2];
}

void
LGR::setLGRF2(int col, int pos1, int pos2, int val)
{
  pos1 = board_pos_id[pos1];
  pos2 = board_pos_id[pos2];
  int c = col - 1;
  lgrf2[(c * pure_board_max + pos1) * pure_board_max + pos2] = val;
}

bool
LGR::hasLGRF2(int col, int pos1, int pos2)
{
  return (this->getLGRF2(col, pos1, pos2) != PASS);
}

void
LGR::clearLGRF2(int col, int pos1, int pos2)
{
  this->setLGRF2(col, pos1, pos2, PASS);
}

void
LGR::update(game_info_t* game, int start, int win, const LGRContext& ctx)
{
  if (tgr1_rate > 0) {
    for (int i = 1; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      unsigned int h = ctx.hash[i];
      int p1 = game->record[i - 1].pos;
      unsigned int h1 = ctx.hash_last[i];

      bool iswin = (c == win);
      if (mp == PASS || p1 == PASS)
	continue;
      if (h == 0 || h1 == 0)
	continue;
      if (i < start) {
	this->setTGR1(c, p1, mp, h1, h);
      } else {
	if (iswin) {
	  //this->setTGR1(c, p1, mp, h1, h);
	}
      }
    }
  }

  if (lgrf1_rate > 0) {
    for (int i = 1; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      //unsigned int h = ctx.hash[i];
      int p1 = game->record[i - 1].pos;
      uint32_t h1 = ctx.hash_last[i];

      bool iswin = (c == win);
      if (mp == PASS || p1 == PASS)
	continue;
      if (iswin) {
	//cerr << "adding LGRF1: " << FormatMove(p1) << " -> " << FormatMove(mp) << endl;
	this->setLGRF1(c, p1, mp, h1);
      } else {
	//cerr << "forgetting LGRF1: " << FormatMove(p1) << endl;
	this->clearLGRF1(c, p1);
      }
#if 0
      if (iswin)
      {
	//cerr << "adding LGRF1: " << FormatMove(p1) << " -> " << FormatMove(mp) << endl;
	this->setLGRF1(c, p1, mp, h1, h);
      } else {
	//cerr << "forgetting LGRF1: " << FormatMove(p1) << endl;
	//if (i > strat) this->clearLGRF1(c, p1);
	this->setLGRF1(c, p1, PASS, h1, 0);
      }
#endif
    }
  }

  if (use_lgrf2) {
    for (int i = 2; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      int p1 = game->record[i - 2].pos;
      int p2 = game->record[i - 1].pos;

      bool iswin = (c == win);

      if (iswin) {
	//cerr << "adding LGRF2: " << FormatMove(p1) << " -> " << FormatMove(p2) << " -> " << FormatMove(mp) << endl;
	this->setLGRF2(c, p1, p2, mp);
	//this->setLGRF1o(c, p1, mp);
      } else {
	//cerr << "forgetting LGRF2: " << FormatMove(p1) << " -> " << FormatMove(p2) << endl;
	if (i > start)
	  this->clearLGRF2(c, p1, p2);
	//this->clearLGRF1o(c, p1);
      }
    }
  }
}

void
LGRContext::store(const game_info_t* game, int pos) {
  if (pos == PASS) {
    hash[game->moves] = 0;
    hash_last[game->moves] = 0;
  } else {
    hash[game->moves] = MD2(game->pat, pos);
    hash_last[game->moves] = MD2(game->pat, game->record[game->moves - 1].pos);
  }
}
<commit_msg>Disable TGR<commit_after>#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <numeric>

#include "MoveCache.h"

using namespace std;

////////////////
//    変数    //
////////////////

// LGR
int tgr1_rate = 0;
int lgrf1_rate = 0;
bool use_lgrf2 = false;

// Based on Oakfoam http://oakfoam.com/

LGR::LGR()
{
  reset();
}

void
LGR::reset()
{
  tgr1.reset();
  tgr1_hash.reset();
  tgr1_count.reset();
  if (tgr1_rate > 0) {
    size_t s = 2 * pure_board_max;
    tgr1.reset(new int16_t[s * tgr_num]);
    fill_n(tgr1.get(), s * tgr_num, PASS);
    tgr1_hash.reset(new uint32_t[s * tgr_num]);
    tgr1_last.reset(new uint32_t[s * tgr_num]);
    tgr1_count.reset(new uint16_t[s]);
    fill_n(tgr1_count.get(), s, 0);
  }

  lgrf1.reset();
  if (lgrf1_rate > 0) {
    lgrf1.reset(new uint32_t[2 * pure_board_max]);
    fill_n(lgrf1.get(), 2 * pure_board_max, PASS);
    lgrf1_last.reset(new uint32_t[2 * pure_board_max]);
  }

  lgrf2.reset();
  if (use_lgrf2) {
    lgrf2.reset(new int[2 * pure_board_max * pure_board_max]);
    fill_n(lgrf2.get(), 2 * pure_board_max * pure_board_max, PASS);
  }
}

void
LGR::setTGR1(int col, int pos1, int val, uint32_t hash_last, uint32_t hash)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  //int index = (c * pure_board_max + pos1) * 0xffff + hash_last;
  int index = (c * pure_board_max + id1);
  uint16_t count = min(tgr_num, tgr1_count[index]);
  for (int i = 0; i < count; i++) {
    if (tgr1_hash[index * tgr_num + i] == hash) {
      tgr1[index * tgr_num + i] = val;
      return;
    }
  }
  uint16_t n = tgr1_count[index] ++;
  n = n % tgr_num;
  int idx = index * tgr_num + n;
  tgr1[idx] = val;
  tgr1_hash[idx] = hash;
  tgr1_last[idx] = hash_last;
}

int
LGR::getTGR1(int col, int pos1, const game_info_t* game)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  uint32_t hash_last = MD2(game->pat, pos1);
  //int index = (c * pure_board_max + pos1) * 0xffff + hash_last;
  int index = c * pure_board_max + id1;
  uint16_t count = min(tgr_num, tgr1_count[index]);
  for (int i = 0; i < count; i++) {
    int pos = tgr1[index * tgr_num + i];
    if (pos == PASS)
      continue;
    if (tgr1_last[index * tgr_num + i] != hash_last)
      continue;
    uint32_t hash = MD2(game->pat, pos);
    //PrintBoard(game);
    //cerr << FormatMove(pos1) << endl;
    //DisplayInputMD2(hash_last);
    //cerr << FormatMove(pos) << endl;
    //DisplayInputMD2(hash);
    //DisplayInputMD2(tgr1_hash[index * tgr_num + i]);
    if (tgr1_hash[index * tgr_num + i] == hash) {
      //cerr << "HIT" << endl;
      return pos;
    }
    //cerr << "MISS" << endl;
  }
  return PASS;
}

int
LGR::getLGRF1(int col, int pos1, const game_info_t* game)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  uint32_t hash_last = MD2(game->pat, pos1);
  if (lgrf1_last[c * pure_board_max + id1] != hash_last)
    return PASS;
  return lgrf1[c * pure_board_max + id1];
}

void
LGR::setLGRF1(int col, int pos1, int pos, uint32_t hash2)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  int id1 = board_pos_id[pos1];
  int c = col - 1;
  lgrf1[c * pure_board_max + id1] = pos;
  lgrf1_last[c * pure_board_max + id1] = hash2;
}

void
LGR::clearLGRF1(int col, int pos1)
{
  this->setLGRF1(col, pos1, PASS, 0);
}

int
LGR::getLGRF2(int col, int pos1, int pos2)
{
  lock_guard<mutex> lock(board_mutex[pos1]);
  pos1 = board_pos_id[pos1];
  pos2 = board_pos_id[pos2];
  int c = col - 1;
  return lgrf2[(c * pure_board_max + pos1) * pure_board_max + pos2];
}

void
LGR::setLGRF2(int col, int pos1, int pos2, int val)
{
  pos1 = board_pos_id[pos1];
  pos2 = board_pos_id[pos2];
  int c = col - 1;
  lgrf2[(c * pure_board_max + pos1) * pure_board_max + pos2] = val;
}

bool
LGR::hasLGRF2(int col, int pos1, int pos2)
{
  return (this->getLGRF2(col, pos1, pos2) != PASS);
}

void
LGR::clearLGRF2(int col, int pos1, int pos2)
{
  this->setLGRF2(col, pos1, pos2, PASS);
}

void
LGR::update(game_info_t* game, int start, int win, const LGRContext& ctx)
{
  if (tgr1_rate > 0) {
    for (int i = 1; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      unsigned int h = ctx.hash[i];
      int p1 = game->record[i - 1].pos;
      unsigned int h1 = ctx.hash_last[i];

      bool iswin = (c == win);
      if (mp == PASS || p1 == PASS)
	continue;
      if (h == 0 || h1 == 0)
	continue;
      if (i < start) {
	this->setTGR1(c, p1, mp, h1, h);
      } else {
	if (iswin) {
	  //this->setTGR1(c, p1, mp, h1, h);
	}
      }
    }
  }

  if (lgrf1_rate > 0) {
    for (int i = 1; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      //unsigned int h = ctx.hash[i];
      int p1 = game->record[i - 1].pos;
      uint32_t h1 = ctx.hash_last[i];

      bool iswin = (c == win);
      if (mp == PASS || p1 == PASS)
	continue;
      if (iswin) {
	//cerr << "adding LGRF1: " << FormatMove(p1) << " -> " << FormatMove(mp) << endl;
	this->setLGRF1(c, p1, mp, h1);
      } else {
	//cerr << "forgetting LGRF1: " << FormatMove(p1) << endl;
	this->clearLGRF1(c, p1);
      }
#if 0
      if (iswin)
      {
	//cerr << "adding LGRF1: " << FormatMove(p1) << " -> " << FormatMove(mp) << endl;
	this->setLGRF1(c, p1, mp, h1, h);
      } else {
	//cerr << "forgetting LGRF1: " << FormatMove(p1) << endl;
	//if (i > strat) this->clearLGRF1(c, p1);
	this->setLGRF1(c, p1, PASS, h1, 0);
      }
#endif
    }
  }

  if (use_lgrf2) {
    for (int i = 2; i < game->moves; i++) {
      int c = game->record[i].color;
      int mp = game->record[i].pos;
      int p1 = game->record[i - 2].pos;
      int p2 = game->record[i - 1].pos;

      bool iswin = (c == win);

      if (iswin) {
	//cerr << "adding LGRF2: " << FormatMove(p1) << " -> " << FormatMove(p2) << " -> " << FormatMove(mp) << endl;
	this->setLGRF2(c, p1, p2, mp);
	//this->setLGRF1o(c, p1, mp);
      } else {
	//cerr << "forgetting LGRF2: " << FormatMove(p1) << " -> " << FormatMove(p2) << endl;
	if (i > start)
	  this->clearLGRF2(c, p1, p2);
	//this->clearLGRF1o(c, p1);
      }
    }
  }
}

void
LGRContext::store(const game_info_t* game, int pos) {
  if (pos == PASS) {
    hash[game->moves] = 0;
    hash_last[game->moves] = 0;
  } else {
    hash[game->moves] = MD2(game->pat, pos);
    hash_last[game->moves] = MD2(game->pat, game->record[game->moves - 1].pos);
  }
}
<|endoftext|>