<commit_before>/*
 Copyright 2015 Nervana Systems Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

#pragma once

#include <time.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <sstream>

#include "streams.hpp"
#include "buffer.hpp"

#define FORMAT_VERSION  1
#define WRITER_VERSION  1
#define MAGIC_STRING    "MACR"
#define CPIO_FOOTER     "TRAILER!!!"

typedef std::vector<std::string> LineList;
typedef std::vector<char> ByteVect;
typedef std::pair<std::shared_ptr<ByteVect>,std::shared_ptr<ByteVect>> DataPair;

static_assert(sizeof(int) == 4, "int is not 4 bytes");
static_assert(sizeof(uint) == 4, "uint is not 4 bytes");
static_assert(sizeof(short) == 2, "short is not 2 bytes");

/*

The data is stored as a cpio archive and may be unpacked using the
GNU cpio utility.

    https://www.gnu.org/software/cpio/

Individual items are packed into a macrobatch file as follows:
    - header
    - datum 1
    - target 1
    - datum 2
    - target 2
      ...
    - trailer

Each of these items comprises of a cpio header record followed by data.

*/

class RecordHeader {
public:
    RecordHeader();
    void loadDoubleShort(uint* dst, ushort src[2]);

    void saveDoubleShort(ushort* dst, uint src);

    void read(IfStream& ifs, uint* fileSize);

    void write(OfStream& ofs, uint fileSize, const char* fileName);

public:
    ushort                      _magic;
    ushort                      _dev;
    ushort                      _ino;
    ushort                      _mode;
    ushort                      _uid;
    ushort                      _gid;
    ushort                      _nlink;
    ushort                      _rdev;
    ushort                      _mtime[2];
    ushort                      _namesize;
    ushort                      _filesize[2];
};

class BatchFileHeader {
friend class BatchFileReader;
friend class BatchFileWriter;
public:
    BatchFileHeader();
    void read(IfStream& ifs);
    void write(OfStream& ofs);

private:
#pragma pack(1)
    char                        _magic[4];
    uint                        _formatVersion;
    uint                        _writerVersion;
    char                        _dataType[8];
    uint                        _itemCount;
    uint                        _maxDatumSize;
    uint                        _maxTargetSize;
    uint                        _totalDataSize;
    uint                        _totalTargetsSize;
    char                        _unused[24];
#pragma pack()
};

class BatchFileTrailer {
public:
    BatchFileTrailer() ;
    void write(OfStream& ofs);
    void read(IfStream& ifs);

private:
    uint                        _unused[4];
};

class BatchFileReader {
public:
    BatchFileReader();
    BatchFileReader(const std::string& fileName);
    ~BatchFileReader() ;

    bool open(const std::string& fileName);
    void close();

    void readToBuffer(Buffer& dest);
    // TODO: still need this read?
    std::shared_ptr<ByteVect> read();

    int itemCount() ;

    int totalDataSize() ;

    int totalTargetsSize();

    int maxDatumSize() ;

    int maxTargetSize();

private:
    IfStream                    _ifs;
    BatchFileHeader             _fileHeader;
    BatchFileTrailer            _fileTrailer;
    RecordHeader                _recordHeader;
    std::string                 _fileName;
    std::string                 _tempName;
};

class BatchFileWriter {
public:
    ~BatchFileWriter();

    void open(const std::string& fileName, const std::string& dataType = "");
    void close();

    void writeItem(char* datum, char* target,
                   uint datumSize, uint targetSize);

    void writeItem(ByteVect &datum, ByteVect &target);

private:
    OfStream                    _ofs;
    BatchFileHeader             _fileHeader;
    BatchFileTrailer            _fileTrailer;
    RecordHeader                _recordHeader;
    int                         _fileHeaderOffset;
    std::string                 _fileName;
    std::string                 _tempName;
};
extern int readFileLines(const std::string &filn, LineList &ll);
extern int readFileBytes(const std::string &filn, ByteVect &b);

<commit_msg>remove unused method BatchFileReader::read<commit_after>/*
 Copyright 2015 Nervana Systems Inc.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

#pragma once

#include <time.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <sstream>

#include "streams.hpp"
#include "buffer.hpp"

#define FORMAT_VERSION  1
#define WRITER_VERSION  1
#define MAGIC_STRING    "MACR"
#define CPIO_FOOTER     "TRAILER!!!"

typedef std::vector<std::string> LineList;
typedef std::vector<char> ByteVect;
typedef std::pair<std::shared_ptr<ByteVect>,std::shared_ptr<ByteVect>> DataPair;

static_assert(sizeof(int) == 4, "int is not 4 bytes");
static_assert(sizeof(uint) == 4, "uint is not 4 bytes");
static_assert(sizeof(short) == 2, "short is not 2 bytes");

/*

The data is stored as a cpio archive and may be unpacked using the
GNU cpio utility.

    https://www.gnu.org/software/cpio/

Individual items are packed into a macrobatch file as follows:
    - header
    - datum 1
    - target 1
    - datum 2
    - target 2
      ...
    - trailer

Each of these items comprises of a cpio header record followed by data.

*/

class RecordHeader {
public:
    RecordHeader();
    void loadDoubleShort(uint* dst, ushort src[2]);

    void saveDoubleShort(ushort* dst, uint src);

    void read(IfStream& ifs, uint* fileSize);

    void write(OfStream& ofs, uint fileSize, const char* fileName);

public:
    ushort                      _magic;
    ushort                      _dev;
    ushort                      _ino;
    ushort                      _mode;
    ushort                      _uid;
    ushort                      _gid;
    ushort                      _nlink;
    ushort                      _rdev;
    ushort                      _mtime[2];
    ushort                      _namesize;
    ushort                      _filesize[2];
};

class BatchFileHeader {
friend class BatchFileReader;
friend class BatchFileWriter;
public:
    BatchFileHeader();
    void read(IfStream& ifs);
    void write(OfStream& ofs);

private:
#pragma pack(1)
    char                        _magic[4];
    uint                        _formatVersion;
    uint                        _writerVersion;
    char                        _dataType[8];
    uint                        _itemCount;
    uint                        _maxDatumSize;
    uint                        _maxTargetSize;
    uint                        _totalDataSize;
    uint                        _totalTargetsSize;
    char                        _unused[24];
#pragma pack()
};

class BatchFileTrailer {
public:
    BatchFileTrailer() ;
    void write(OfStream& ofs);
    void read(IfStream& ifs);

private:
    uint                        _unused[4];
};

class BatchFileReader {
public:
    BatchFileReader();
    BatchFileReader(const std::string& fileName);
    ~BatchFileReader() ;

    bool open(const std::string& fileName);
    void close();

    void readToBuffer(Buffer& dest);

    int itemCount() ;

    int totalDataSize() ;

    int totalTargetsSize();

    int maxDatumSize() ;

    int maxTargetSize();

private:
    IfStream                    _ifs;
    BatchFileHeader             _fileHeader;
    BatchFileTrailer            _fileTrailer;
    RecordHeader                _recordHeader;
    std::string                 _fileName;
    std::string                 _tempName;
};

class BatchFileWriter {
public:
    ~BatchFileWriter();

    void open(const std::string& fileName, const std::string& dataType = "");
    void close();

    void writeItem(char* datum, char* target,
                   uint datumSize, uint targetSize);

    void writeItem(ByteVect &datum, ByteVect &target);

private:
    OfStream                    _ofs;
    BatchFileHeader             _fileHeader;
    BatchFileTrailer            _fileTrailer;
    RecordHeader                _recordHeader;
    int                         _fileHeaderOffset;
    std::string                 _fileName;
    std::string                 _tempName;
};
extern int readFileLines(const std::string &filn, LineList &ll);
extern int readFileBytes(const std::string &filn, ByteVect &b);

<|endoftext|>


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

#include "wrdtrans.hxx"

// NOT FULLY DECLARED SERVICES
#include <vector>
#include <vos/macros.hxx>

#include <tools/stream.hxx>
#include "wtratree.hxx"

#include <tools/string.hxx>

//**************   Declaration WordTrans_ErrorList   ******************//
typedef NAMESPACE_STD(vector)<ByteString> Stl_ByteStringList;

class WordTrans_ErrorList
{
  public:
    // OPERATIONS
    void                AddError(
                            WordTransformer::E_Error
                                                i_eType,
                            const char *        i_sErrorDescription );
    void                Clear();                /// Empties the list.

    // INQUIRY
    USHORT              NrOfErrors() const;
    WordTransformer::E_Error
                        GetError(
                            USHORT              i_nNr,                   /// [0 .. NrOfErrors()-1], other values return an empty error.
                            ByteString *        o_pErrorText ) const;    /// If o_pErrorText != 0, the String is filled with the description of the error.
  private:
    // DATA
    Stl_ByteStringList      aErrors;
};

//**************   Implementation WordTransformer     ******************//

WordTransformer::WordTransformer()
    :   dpTransformer(0),
        dpErrors(new WordTrans_ErrorList)
{
}

WordTransformer::~WordTransformer()
{
    if (dpTransformer != 0)
        delete dpTransformer;
    delete dpErrors;
}

BOOL
WordTransformer::LoadWordlist( const ByteString &  i_sWordlist_Filepath,
                               CharSet         i_nWorkingCharSet,
                               CharSet         i_nFileCharSet )
{
    if (dpTransformer != 0)
        return FALSE;

    SvFileStream    aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ);
    if (! aFile.IsOpen())
        return FALSE;
    aFile.SetStreamCharSet( i_nFileCharSet ) ;
//  aFile.SetTargetCharSet( i_nWorkingCharSet );

    dpTransformer = new WordTransTree;

    ByteString sTrans;
    while ( aFile.ReadLine(sTrans) )
    {
        dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';'));
    }

    aFile.Close();
    return TRUE;
}

USHORT
WordTransformer::Transform(ByteString & io_sText)
{
    // Initialization and precondition testing:
    dpErrors->Clear();
    if (dpTransformer == 0)
    {
        dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded.");
        return dpErrors->NrOfErrors();
    }
    else if (io_sText.Len() > 63 * 1024)
    {
        dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB).");
        return dpErrors->NrOfErrors();
    }
    else if (io_sText.Len() == 0)
    {
        return 0;
    }

    // Transform:
    dpTransformer->InitTransformation(
                            io_sText.GetBuffer(),
                            io_sText.Len() );

    for ( ; !dpTransformer->TextEndReached(); )
    {
        if (dpTransformer->TransformNextToken() != WordTransTree::OK)
        {
            CreateError();
        }
    }
    io_sText = dpTransformer->Output();
    return dpErrors->NrOfErrors();
}

USHORT
WordTransformer::NrOfErrors() const
{
    return dpErrors->NrOfErrors();
}

WordTransformer::E_Error
WordTransformer::GetError( USHORT   i_nNr,
                           ByteString * o_pErrorText) const
{
    return dpErrors->GetError(i_nNr,o_pErrorText);
}

void
WordTransformer::CreateError()
{
    ByteString sErr;

    switch (dpTransformer->CurResult())
    {
        case WordTransTree::OK:
            break;
        case WordTransTree::HOTKEY_LOST:
                sErr = ByteString("Error: By replacement of string ");
                sErr += dpTransformer->CurReplacedString();
                sErr += " by ";
                sErr += dpTransformer->CurReplacingString();
                sErr += "the hotkey at char '";
                sErr += dpTransformer->CurHotkey();
                sErr += "' was lost.";
            dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess());
            sErr.ReleaseBufferAccess();
            break;
        case WordTransTree::OUTPUT_OVERFLOW:
            dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow.");
            break;
        default:
            dpErrors->AddError(OTHER_ERROR,"Error: Unknown error.");
    }
}

//**************   Implementation WordTrans_ErrorList   ******************//

void
WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType,
                               const char *             i_sErrorDescription )
{
    ByteString sErrorType = "xxx";
    char * pErrorChars = sErrorType.GetBufferAccess();
    pErrorChars[0] = char(i_eType / 100 + '0');
    pErrorChars[1] = char( (i_eType % 100) / 10 + '0');
    pErrorChars[2] = char(i_eType % 10 + '0');
    sErrorType += i_sErrorDescription;

    aErrors.push_back(sErrorType);
    sErrorType.ReleaseBufferAccess();
}

void
WordTrans_ErrorList::Clear()
{
     aErrors.erase(aErrors.begin(),aErrors.end());
}

USHORT
WordTrans_ErrorList::NrOfErrors() const
{
    return aErrors.size();
}

WordTransformer::E_Error
WordTrans_ErrorList::GetError( USHORT       i_nNr,
                               ByteString * o_pErrorText ) const
{
    if (0 <= i_nNr && i_nNr < aErrors.size() )
    {
        const ByteString & rError = aErrors[i_nNr];
        const char * pErrorChars = rError.GetBuffer();

        USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100
                    +   (pErrorChars[1] - '0') * 10
                    +   pErrorChars[2] - '0';

        if (o_pErrorText != 0)
            *o_pErrorText = pErrorChars+3;

        return WordTransformer::E_Error(nError);
    }
    else
    {
        if (o_pErrorText != 0)
            *o_pErrorText = "";
        return WordTransformer::OK;
    }
}

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

#include "wrdtrans.hxx"

// NOT FULLY DECLARED SERVICES
#include <vector>
#include <vos/macros.hxx>

#include <tools/stream.hxx>
#include "wtratree.hxx"

#include <tools/string.hxx>

//**************   Declaration WordTrans_ErrorList   ******************//
typedef NAMESPACE_STD(vector)<ByteString> Stl_ByteStringList;

class WordTrans_ErrorList
{
  public:
    // OPERATIONS
    void                AddError(
                            WordTransformer::E_Error
                                                i_eType,
                            const char *        i_sErrorDescription );
    void                Clear();                /// Empties the list.

    // INQUIRY
    USHORT              NrOfErrors() const;
    WordTransformer::E_Error
                        GetError(
                            USHORT              i_nNr,                   /// [0 .. NrOfErrors()-1], other values return an empty error.
                            ByteString *        o_pErrorText ) const;    /// If o_pErrorText != 0, the String is filled with the description of the error.
  private:
    // DATA
    Stl_ByteStringList      aErrors;
};

//**************   Implementation WordTransformer     ******************//

WordTransformer::WordTransformer()
    :   dpTransformer(0),
        dpErrors(new WordTrans_ErrorList)
{
}

WordTransformer::~WordTransformer()
{
    if (dpTransformer != 0)
        delete dpTransformer;
    delete dpErrors;
}

BOOL
WordTransformer::LoadWordlist( const ByteString &  i_sWordlist_Filepath,
                               CharSet         i_nWorkingCharSet,
                               CharSet         i_nFileCharSet )
{
    if (dpTransformer != 0)
        return FALSE;

    SvFileStream    aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ);
    if (! aFile.IsOpen())
        return FALSE;
    aFile.SetStreamCharSet( i_nFileCharSet ) ;
//  aFile.SetTargetCharSet( i_nWorkingCharSet );

    dpTransformer = new WordTransTree;

    ByteString sTrans;
    while ( aFile.ReadLine(sTrans) )
    {
        dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';'));
    }

    aFile.Close();
    return TRUE;
}

USHORT
WordTransformer::Transform(ByteString & io_sText)
{
    // Initialization and precondition testing:
    dpErrors->Clear();
    if (dpTransformer == 0)
    {
        dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded.");
        return dpErrors->NrOfErrors();
    }
    else if (io_sText.Len() > 63 * 1024)
    {
        dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB).");
        return dpErrors->NrOfErrors();
    }
    else if (io_sText.Len() == 0)
    {
        return 0;
    }

    // Transform:
    dpTransformer->InitTransformation(
                            io_sText.GetBuffer(),
                            io_sText.Len() );

    for ( ; !dpTransformer->TextEndReached(); )
    {
        if (dpTransformer->TransformNextToken() != WordTransTree::OK)
        {
            CreateError();
        }
    }
    io_sText = dpTransformer->Output();
    return dpErrors->NrOfErrors();
}

USHORT
WordTransformer::NrOfErrors() const
{
    return dpErrors->NrOfErrors();
}

WordTransformer::E_Error
WordTransformer::GetError( USHORT   i_nNr,
                           ByteString * o_pErrorText) const
{
    return dpErrors->GetError(i_nNr,o_pErrorText);
}

void
WordTransformer::CreateError()
{
    ByteString sErr;

    switch (dpTransformer->CurResult())
    {
        case WordTransTree::OK:
            break;
        case WordTransTree::HOTKEY_LOST:
                sErr = ByteString("Error: By replacement of string ");
                sErr += dpTransformer->CurReplacedString();
                sErr += " by ";
                sErr += dpTransformer->CurReplacingString();
                sErr += "the hotkey at char '";
                sErr += dpTransformer->CurHotkey();
                sErr += "' was lost.";
            dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess());
            sErr.ReleaseBufferAccess();
            break;
        case WordTransTree::OUTPUT_OVERFLOW:
            dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow.");
            break;
        default:
            dpErrors->AddError(OTHER_ERROR,"Error: Unknown error.");
    }
}

//**************   Implementation WordTrans_ErrorList   ******************//

void
WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType,
                               const char *             i_sErrorDescription )
{
    ByteString sErrorType = "xxx";
    char * pErrorChars = sErrorType.GetBufferAccess();
    pErrorChars[0] = char(i_eType / 100 + '0');
    pErrorChars[1] = char( (i_eType % 100) / 10 + '0');
    pErrorChars[2] = char(i_eType % 10 + '0');
    sErrorType += i_sErrorDescription;

    aErrors.push_back(sErrorType);
    sErrorType.ReleaseBufferAccess();
}

void
WordTrans_ErrorList::Clear()
{
     aErrors.erase(aErrors.begin(),aErrors.end());
}

USHORT
WordTrans_ErrorList::NrOfErrors() const
{
    return aErrors.size();
}

WordTransformer::E_Error
WordTrans_ErrorList::GetError( USHORT       i_nNr,
                               ByteString * o_pErrorText ) const
{
    if ( i_nNr < aErrors.size() )
    {
        const ByteString & rError = aErrors[i_nNr];
        const char * pErrorChars = rError.GetBuffer();

        USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100
                    +   (pErrorChars[1] - '0') * 10
                    +   pErrorChars[2] - '0';

        if (o_pErrorText != 0)
            *o_pErrorText = pErrorChars+3;

        return WordTransformer::E_Error(nError);
    }
    else
    {
        if (o_pErrorText != 0)
            *o_pErrorText = "";
        return WordTransformer::OK;
    }
}

<|endoftext|>


<commit_before>Bool_t gIsAnalysisLoaded = kFALSE ;

//______________________________________________________________________
Bool_t LoadLib( const char* pararchivename)
{
  // Loads the AliRoot required libraries from a tar file

  Bool_t rv = kTRUE ;

  char cdir[1024] ;
  sprintf(cdir, "%s", gSystem->WorkingDirectory() ) ;

  // Setup par File
  if (pararchivename) {
    char processline[1024];
    sprintf(processline,".! tar xvzf %s.par",pararchivename);
    gROOT->ProcessLine(processline);
    gSystem->ChangeDirectory(pararchivename);

    // check for BUILD.sh and execute
    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
      printf("*** Building PAR archive  %s  ***\n", pararchivename);

      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
	AliError(Form("Cannot Build the PAR Archive %s! - Abort!", pararchivename) );

        return kFALSE ;
      }
    }

    // check for SETUP.C and execute
    if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
      printf("*** Setup PAR archive  %s     ***\n", pararchivename);
      gROOT->Macro("PROOF-INF/SETUP.C");
    }
  }

  if ( strstr(pararchivename, "ESD") ) {
    //gSystem->Load("libVMC.so");
    //gSystem->Load("libRAliEn.so");
    gSystem->Load("libESD.so") ;
    //gSystem->Load("libProof.so") ;
  }

  if ( strstr(pararchivename, "AnalysisCheck") ) {
    gSystem->Load("libSpectrum.so");
  }

  printf("lib%s done\n", pararchivename);

  gSystem->ChangeDirectory(cdir);

  gIsAnalysisLoaded = kTRUE ;
  return rv ;
}

//______________________________________________________________________
void ana()
{
  if (! gIsAnalysisLoaded ) {
    LoadLib("ESD") ;
    LoadLib("ANALYSIS") ;
    LoadLib("AnalysisCheck") ;
  }

  // create the analysis goodies object
  AliAnalysisGoodies * ag = new AliAnalysisGoodies() ;

  // definition of analysis tasks

  const Int_t knumberOfTasks = 10 ;
  AliAnalysisTask * taskList[knumberOfTasks] ;
  TClass * taskInputList[knumberOfTasks]  ;
  TClass * taskOutputList[knumberOfTasks] ;

  taskList[0]       = new AliPHOSQATask("PHOS") ;
  taskInputList[0]  = TChain::Class() ;
  taskOutputList[0] = TObjArray::Class() ;

  taskList[1]       = new AliEMCALQATask("EMCal") ;
  taskInputList[1]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[1] = TObjArray::Class() ;

  taskList[2]       = new AliPMDQATask("PMD") ;
  taskInputList[2]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[2] = TObjArray::Class() ;

  taskList[3]       = new AliAnalysisTaskPt("Pt") ;
  taskInputList[3]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[3] = TObjArray::Class() ;

  taskList[4]       = new AliHMPIDQATask("HMPID") ;
  taskInputList[4]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[4] = TObjArray::Class() ;

  taskList[5]       = new AliT0QATask("T0") ;
  taskInputList[5]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[5] = TObjArray::Class() ;

  taskList[6]       = new AliMUONQATask("MUON") ;
  taskInputList[6]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[6] = TObjArray::Class() ;

  taskList[7]       = new AliTRDQATask("TRD") ;
  taskInputList[7]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[7] = TObjArray::Class() ;

  taskList[8]       = new AliTOFQATask("TOF") ;
  taskInputList[8]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[8] = TObjArray::Class() ;

  taskList[9]       = new AliVZEROQATask("VZERO") ;
  taskInputList[9]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[9] = TObjArray::Class() ;

//   taskList[8]       = new AliFMDQATask("FMD") ;
//   taskInputList[8]  = taskInputList[0] ; // only one top input container allowed
//   taskOutputList[8] = TObjArray::Class() ;

  ag->SetTasks(knumberOfTasks, taskList, taskInputList, taskOutputList) ;

  // get the data to analyze

  // definition of Tag cuts
  const char * runCuts = 0x0 ;
  const char * evtCuts = 0x0 ;
  const char * lhcCuts = 0x0 ;
  const char * detCuts = 0x0 ;

//"fEventTag.fNPHOSClustersMin == 1 && fEventTag.fNEMCALClustersMin == 1" ;

  TString input = gSystem->Getenv("ANA_INPUT") ;
  if ( input != "") {
    char argument[1024] ;
    if ( input.Contains("tag?") ) {
      //create the ESD collection from the tag collection
      input.ReplaceAll("tag?", "") ;
      const char * collESD = "esdCollection.xml" ;
      ag->MakeEsdCollectionFromTagCollection(runCuts, lhcCuts, detCuts, evtCuts, input.Data(), collESD) ;
      sprintf(argument, "esd?%s", collESD) ;
    } else if ( input.Contains("esd?") )
      sprintf(argument, "%s", input.Data()) ;
    ag->Process(argument) ;

  } else {

    TChain* analysisChain = new TChain("esdTree") ;
    //   input = "alien:///alice/cern.ch/user/a/aliprod/prod2006_2/output_pp/105/411/AliESDs.root" ;
    //   analysisChain->AddFile(input);
    input = "AliESDs.root" ;
    analysisChain->AddFile(input);
    ag->Process(analysisChain) ;
  }
  return ;
}

//______________________________________________________________________
void Merge(const char * xml, const char * sub, const char * out)
{
  if (! gIsAnalysisLoaded )
    LoadLib("ESD") ;

  AliAnalysisGoodies * ag = new AliAnalysisGoodies() ;
  ag->Merge(xml, sub, out) ;
}

<commit_msg>Adding reation of par file (Yves)<commit_after>Bool_t gIsAnalysisLoaded = kFALSE ;

//______________________________________________________________________
Bool_t LoadLib( const char* pararchivename)
{
  // Loads the AliRoot required libraries from a tar file

  Bool_t rv = kTRUE ;

  char cdir[1024] ;
  sprintf(cdir, "%s", gSystem->WorkingDirectory() ) ;

  // Setup par File
  if (pararchivename) {
   char parpar[80] ;
   sprintf(parpar, "%s.par", pararchivename) ;
   if ( gSystem->AccessPathName(parpar) ) {
    gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ;
    char processline[1024];
    sprintf(processline, ".! make %s", parpar) ;
    cout << processline << endl ;
    gROOT->ProcessLine(processline) ;
    gSystem->ChangeDirectory(cdir) ;
    sprintf(processline, ".! mv %s/%s .", gSystem->Getenv("ALICE_ROOT"), parpar) ;
    gROOT->ProcessLine(processline) ;
    sprintf(processline,".! tar xvzf %s",parpar);
    gROOT->ProcessLine(processline);
   }
   gSystem->ChangeDirectory(pararchivename);

    // check for BUILD.sh and execute
    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
      printf("*** Building PAR archive  %s  ***\n", pararchivename);

      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
	AliError(Form("Cannot Build the PAR Archive %s! - Abort!", pararchivename) );

        return kFALSE ;
      }
    }

    // check for SETUP.C and execute
    if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
      printf("*** Setup PAR archive  %s     ***\n", pararchivename);
      gROOT->Macro("PROOF-INF/SETUP.C");
    }
  }

  if ( strstr(pararchivename, "ESD") ) {
    //gSystem->Load("libVMC.so");
    //gSystem->Load("libRAliEn.so");
    gSystem->Load("libESD.so") ;
    //gSystem->Load("libProof.so") ;
  }

  if ( strstr(pararchivename, "AnalysisCheck") ) {
    gSystem->Load("libSpectrum.so");
  }

  printf("lib%s done\n", pararchivename);

  gSystem->ChangeDirectory(cdir);

  gIsAnalysisLoaded = kTRUE ;
  return rv ;
}

//______________________________________________________________________
void ana(const Int_t kEvent=100)
{
  if (! gIsAnalysisLoaded ) {
    LoadLib("ESD") ;
    LoadLib("ANALYSIS") ;
    LoadLib("AnalysisCheck") ;
  }

  // create the analysis goodies object
  AliAnalysisGoodies * ag = new AliAnalysisGoodies() ;

  // definition of analysis tasks

  const Int_t knumberOfTasks = 10 ;
  AliAnalysisTask * taskList[knumberOfTasks] ;
  TClass * taskInputList[knumberOfTasks]  ;
  TClass * taskOutputList[knumberOfTasks] ;

  taskList[0]       = new AliPHOSQATask("PHOS") ;
  taskInputList[0]  = TChain::Class() ;
  taskOutputList[0] = TObjArray::Class() ;

  taskList[1]       = new AliEMCALQATask("EMCal") ;
  taskInputList[1]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[1] = TObjArray::Class() ;

  taskList[2]       = new AliPMDQATask("PMD") ;
  taskInputList[2]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[2] = TObjArray::Class() ;

  taskList[3]       = new AliAnalysisTaskPt("Pt") ;
  taskInputList[3]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[3] = TObjArray::Class() ;

  taskList[4]       = new AliHMPIDQATask("HMPID") ;
  taskInputList[4]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[4] = TObjArray::Class() ;

  taskList[5]       = new AliT0QATask("T0") ;
  taskInputList[5]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[5] = TObjArray::Class() ;

  taskList[6]       = new AliMUONQATask("MUON") ;
  taskInputList[6]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[6] = TObjArray::Class() ;

  taskList[7]       = new AliTRDQATask("TRD") ;
  taskInputList[7]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[7] = TObjArray::Class() ;

  taskList[8]       = new AliTOFQATask("TOF") ;
  taskInputList[8]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[8] = TObjArray::Class() ;

  taskList[9]       = new AliVZEROQATask("VZERO") ;
  taskInputList[9]  = taskInputList[0] ; // only one top input container allowed
  taskOutputList[9] = TObjArray::Class() ;

//   taskList[8]       = new AliFMDQATask("FMD") ;
//   taskInputList[8]  = taskInputList[0] ; // only one top input container allowed
//   taskOutputList[8] = TObjArray::Class() ;

  ag->SetTasks(knumberOfTasks, taskList, taskInputList, taskOutputList) ;

  // get the data to analyze

  // definition of Tag cuts
  const char * runCuts = 0x0 ;
  const char * evtCuts = 0x0 ;
  const char * lhcCuts = 0x0 ;
  const char * detCuts = 0x0 ;

//"fEventTag.fNPHOSClustersMin == 1 && fEventTag.fNEMCALClustersMin == 1" ;

  TString input = gSystem->Getenv("ANA_INPUT") ;
  if ( input != "") {
    char argument[1024] ;
    if ( input.Contains("tag?") ) {
      //create the ESD collection from the tag collection
      input.ReplaceAll("tag?", "") ;
      const char * collESD = "esdCollection.xml" ;
      ag->MakeEsdCollectionFromTagCollection(runCuts, lhcCuts, detCuts, evtCuts, input.Data(), collESD) ;
      sprintf(argument, "esd?%s", collESD) ;
    } else if ( input.Contains("esd?") )
      sprintf(argument, "%s", input.Data()) ;
    ag->Process(argument) ;

  } else {

    TChain* analysisChain = new TChain("esdTree") ;
    //   input = "alien:///alice/cern.ch/user/a/aliprod/prod2006_2/output_pp/105/411/AliESDs.root" ;
    //   analysisChain->AddFile(input);
    input = "AliESDs.root" ;
    const char * kInDir = gSystem->Getenv("OUTDIR") ;
    if ( kInDir ) {
      if ( ! gSystem->cd(kInDir) ) {
	printf("%s does not exist\n", kInDir) ;
	return ;
      }
      Int_t event, skipped=0 ;
      char file[120] ;
      for (event = 0 ; event < kEvent ; event++) {
        sprintf(file, "%s/%d/AliESDs.root", kInDir,event) ;
	TFile * fESD = 0 ;
	if ( fESD = TFile::Open(file))
	  if ( fESD->Get("esdTree") ) {
            printf("++++ Adding %s\n", file) ;
            analysisChain->AddFile(file);
	  }
	  else {
            printf("---- Skipping %s\n", file) ;
            skipped++ ;
	  }
      }
      printf("number of entries # %lld, skipped %d\n", analysisChain->GetEntries(), skipped*100) ;
    }
    else
      analysisChain->AddFile(input);

    ag->Process(analysisChain) ;
  }
  return ;
}

//______________________________________________________________________
void Merge(const char * xml, const char * sub, const char * out)
{
  if (! gIsAnalysisLoaded )
    LoadLib("ESD") ;

  AliAnalysisGoodies * ag = new AliAnalysisGoodies() ;
  ag->Merge(xml, sub, out) ;
}

<|endoftext|>


<commit_before>#include "ESP8266_AT.h"

ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) :
    m_rxPin(rxPin), m_txPin(txPin)
{
    SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin);
    serial->begin(baud);
    m_serial = serial;
}

ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) :
    m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}

ESP8266_AT::ESP8266_AT(HardwareSerial &serial) :
    m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}

ESP8266_AT::~ESP8266_AT() {
    disconnect();
    if(m_rxPin != 0 && m_txPin !=0) delete m_serial;
}

void ESP8266_AT::rxClear() {
    while(m_serial->available() > 0) m_serial->read();
}

bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) {
    *buf = "";
    char c;
    unsigned long start = millis();
    while (millis() - start < timeout) {
        while(m_serial->available() > 0) {
            c = m_serial->read(); // 1 byte
            if(c == '\0') continue;
            *buf += c;
        }
        if (buf->indexOf(target) != -1) return true;
    }
    return false;
}

bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) {
    String buf;
    return checkATResponse(&buf, target, timeout);
}

bool ESP8266_AT::statusAT() {
    rxClear();
    m_serial->println("AT");
    return checkATResponse();
}

bool ESP8266_AT::restart() {
    rxClear();
    m_serial->println("AT+RST");
    if(!checkATResponse()) return false;
    delay(2000);
    unsigned long start = millis();
    while(millis() - start < 3000) {
        if(statusAT()) {
            delay(1500);
            return true;
        }
        delay(100);
    }
    return false;
}

bool ESP8266_AT::connect(String ssid, String password) {
    rxClear();
    m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2
    if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart

    // Connect to an AP
    rxClear();
    m_serial->print("AT+CWJAP_DEF=\"");
    m_serial->print(ssid);
    m_serial->print("\",\"");
    m_serial->print(password);
    m_serial->println("\"");
    return checkATResponse("OK", 10000);
}

bool ESP8266_AT::disconnect() {
    rxClear();
    m_serial->println("AT+CWQAP");
    return checkATResponse();
}

bool ESP8266_AT::statusWiFi() {
    String buf;
    rxClear();
    m_serial->println("AT+CIPSTATUS");
    checkATResponse(&buf, "S:", 10000);
    uint32_t index = buf.indexOf(":");
    uint8_t stat = buf.substring(index + 1, index + 2).toInt();
    return (stat != 5); // 5: ESP8266 station is NOT connected to an AP
}

int ESP8266_AT::connect(const char *host, uint16_t port) {
    if(connected()) stop();
    String buf;
    uint8_t retry = 10;
    while(retry--) {
        rxClear();
        m_serial->print("AT+CIPSTART=\"TCP\",\"");
        m_serial->print(host);
        m_serial->print("\",");
        m_serial->println(port);
        checkATResponse(&buf, "OK", 2000);
        if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) {
            return 1; // SUCCESS
        }
        delay(500);
    }
    return -1; // TIMED_OUT
}

int ESP8266_AT::connect(IPAddress ip, uint16_t port) {
    String host = "";
    for(uint8_t i = 0; i < 4;) {
        host += String(ip[i]);
        if(++i < 4) host += ".";
    }
    return connect(host.c_str(), port);
}

void ESP8266_AT::stop() {
    // TODO
}

uint8_t ESP8266_AT::connected() {
    return 1; // TODO
}

size_t ESP8266_AT::write(const uint8_t *buf, size_t size) {
    return 0; // TODO
}

size_t ESP8266_AT::write(uint8_t) {
    return 0; // TODO
}

int ESP8266_AT::available() {
    return 0; // TODO
}

int ESP8266_AT::read() {
    return 0; // TODO
}

int ESP8266_AT::read(uint8_t *buf, size_t size) {
    return 0; // TODO
}

int ESP8266_AT::peek() {
    return 0; // TODO
}

void ESP8266_AT::flush() {
    // TODO
}

ESP8266_AT::operator bool() {
    // TODO
}
<commit_msg>Implemented ESP8266_AT::stop<commit_after>#include "ESP8266_AT.h"

ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) :
    m_rxPin(rxPin), m_txPin(txPin)
{
    SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin);
    serial->begin(baud);
    m_serial = serial;
}

ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) :
    m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}

ESP8266_AT::ESP8266_AT(HardwareSerial &serial) :
    m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}

ESP8266_AT::~ESP8266_AT() {
    disconnect();
    if(m_rxPin != 0 && m_txPin !=0) delete m_serial;
}

void ESP8266_AT::rxClear() {
    while(m_serial->available() > 0) m_serial->read();
}

bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) {
    *buf = "";
    char c;
    unsigned long start = millis();
    while (millis() - start < timeout) {
        while(m_serial->available() > 0) {
            c = m_serial->read(); // 1 byte
            if(c == '\0') continue;
            *buf += c;
        }
        if (buf->indexOf(target) != -1) return true;
    }
    return false;
}

bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) {
    String buf;
    return checkATResponse(&buf, target, timeout);
}

bool ESP8266_AT::statusAT() {
    rxClear();
    m_serial->println("AT");
    return checkATResponse();
}

bool ESP8266_AT::restart() {
    rxClear();
    m_serial->println("AT+RST");
    if(!checkATResponse()) return false;
    delay(2000);
    unsigned long start = millis();
    while(millis() - start < 3000) {
        if(statusAT()) {
            delay(1500);
            return true;
        }
        delay(100);
    }
    return false;
}

bool ESP8266_AT::connect(String ssid, String password) {
    rxClear();
    m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2
    if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart

    // Connect to an AP
    rxClear();
    m_serial->print("AT+CWJAP_DEF=\"");
    m_serial->print(ssid);
    m_serial->print("\",\"");
    m_serial->print(password);
    m_serial->println("\"");
    return checkATResponse("OK", 10000);
}

bool ESP8266_AT::disconnect() {
    rxClear();
    m_serial->println("AT+CWQAP");
    return checkATResponse();
}

bool ESP8266_AT::statusWiFi() {
    String buf;
    rxClear();
    m_serial->println("AT+CIPSTATUS");
    checkATResponse(&buf, "S:", 10000);
    uint32_t index = buf.indexOf(":");
    uint8_t stat = buf.substring(index + 1, index + 2).toInt();
    return (stat != 5); // 5: ESP8266 station is NOT connected to an AP
}

int ESP8266_AT::connect(const char *host, uint16_t port) {
    if(connected()) stop();
    String buf;
    uint8_t retry = 10;
    while(retry--) {
        rxClear();
        m_serial->print("AT+CIPSTART=\"TCP\",\"");
        m_serial->print(host);
        m_serial->print("\",");
        m_serial->println(port);
        checkATResponse(&buf, "OK", 2000);
        if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) {
            return 1; // SUCCESS
        }
        delay(500);
    }
    return -1; // TIMED_OUT
}

int ESP8266_AT::connect(IPAddress ip, uint16_t port) {
    String host = "";
    for(uint8_t i = 0; i < 4;) {
        host += String(ip[i]);
        if(++i < 4) host += ".";
    }
    return connect(host.c_str(), port);
}

void ESP8266_AT::stop() {
    rxClear();
    m_serial->println("AT+CIPCLOSE");
    checkATResponse("OK", 5000);
}

uint8_t ESP8266_AT::connected() {
    return 1; // TODO
}

size_t ESP8266_AT::write(const uint8_t *buf, size_t size) {
    return 0; // TODO
}

size_t ESP8266_AT::write(uint8_t) {
    return 0; // TODO
}

int ESP8266_AT::available() {
    return 0; // TODO
}

int ESP8266_AT::read() {
    return 0; // TODO
}

int ESP8266_AT::read(uint8_t *buf, size_t size) {
    return 0; // TODO
}

int ESP8266_AT::peek() {
    return 0; // TODO
}

void ESP8266_AT::flush() {
    // TODO
}

ESP8266_AT::operator bool() {
    // TODO
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Client.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Client.h"

#include <chrono>
#include <thread>
#include "Common.h"
#include "Defaults.h"
using namespace std;
using namespace eth;

Client::Client(std::string const& _clientVersion, Address _us, std::string const& _dbPath):
	m_clientVersion(_clientVersion),
	m_bc(_dbPath),
	m_stateDB(State::openDB(_dbPath)),
	m_s(_us, m_stateDB),
	m_mined(_us, m_stateDB)
{
	Defaults::setDBPath(_dbPath);

	// Synchronise the state according to the block chain - i.e. replay all transactions in block chain, in order.
	// In practise this won't need to be done since the State DB will contain the keys for the tries for most recent (and many old) blocks.
	// TODO: currently it contains keys for *all* blocks. Make it remove old ones.
	m_s.sync(m_bc);
	m_s.sync(m_tq);
	m_mined = m_s;
	m_changed = true;

	static const char* c_threadName = "eth";

	m_work = new thread([&](){
		setThreadName(c_threadName);

		while (m_workState != Deleting) work(); m_workState = Deleted;
	});
}

Client::~Client()
{
	if (m_workState == Active)
		m_workState = Deleting;
	while (m_workState != Deleted)
		this_thread::sleep_for(chrono::milliseconds(10));
}

void Client::startNetwork(short _listenPort, std::string const& _seedHost, short _port, NodeMode _mode, unsigned _peers, string const& _publicIP, bool _upnp)
{
	if (m_net)
		return;
	m_net = new PeerServer(m_clientVersion, m_bc, 0, _listenPort, _mode, _publicIP, _upnp);
	m_net->setIdealPeerCount(_peers);
	if (_seedHost.size())
		connect(_seedHost, _port);
}

void Client::connect(std::string const& _seedHost, short _port)
{
	if (!m_net)
		return;
	m_net->connect(_seedHost, _port);
}

void Client::stopNetwork()
{
	delete m_net;
	m_net = nullptr;
}

void Client::startMining()
{
	m_doMine = true;
	m_miningStarted = true;
}

void Client::stopMining()
{
	m_doMine = false;
}

void Client::transact(Secret _secret, Address _dest, u256 _amount, u256s _data)
{
	lock_guard<mutex> l(m_lock);
	Transaction t;
	t.nonce = m_mined.transactionsFrom(toAddress(_secret));
	t.receiveAddress = _dest;
	t.value = _amount;
	t.data = _data;
	t.sign(_secret);
	cnote << "New transaction " << t;
	m_tq.attemptImport(t.rlp());
	m_changed = true;
}

void Client::work()
{
	bool changed = false;

	// Process network events.
	// Synchronise block chain with network.
	// Will broadcast any of our (new) transactions and blocks, and collect & add any of their (new) transactions and blocks.
	if (m_net)
	{
		m_net->process();

		lock_guard<mutex> l(m_lock);
		if (m_net->sync(m_bc, m_tq, m_stateDB))
			changed = true;
	}

	// Synchronise state to block chain.
	// This should remove any transactions on our queue that are included within our state.
	// It also guarantees that the state reflects the longest (valid!) chain on the block chain.
	//   This might mean reverting to an earlier state and replaying some blocks, or, (worst-case:
	//   if there are no checkpoints before our fork) reverting to the genesis block and replaying
	//   all blocks.
	// Resynchronise state with block chain & trans
	{
		lock_guard<mutex> l(m_lock);
		if (m_s.sync(m_bc))
		{
			cnote << "Externally mined block: Restarting mining operation.";
			changed = true;
			m_miningStarted = true;	// need to re-commit to mine.
			m_mined = m_s;
		}
		if (m_mined.sync(m_tq))
		{
			cnote << "Additional transaction ready: Restarting mining operation.";
			changed = true;
			m_miningStarted = true;
		}
	}

	if (m_doMine)
	{
		if (m_miningStarted)
		{
			lock_guard<mutex> l(m_lock);
			m_mined.commitToMine(m_bc);
		}

		m_miningStarted = false;

		// Mine for a while.
		MineInfo mineInfo = m_mined.mine(100);
		m_mineProgress.best = max(m_mineProgress.best, mineInfo.best);
		m_mineProgress.current = mineInfo.best;
		m_mineProgress.requirement = mineInfo.requirement;

		if (mineInfo.completed)
		{
			// Import block.
			lock_guard<mutex> l(m_lock);
			m_bc.attemptImport(m_mined.blockData(), m_stateDB);
			m_mineProgress.best = 0;
			m_changed = true;
			m_miningStarted = true;	// need to re-commit to mine.
		}
	}
	else
		this_thread::sleep_for(chrono::milliseconds(100));

	m_changed = m_changed || changed;
}

void Client::lock()
{
	m_lock.lock();
}

void Client::unlock()
{
	m_lock.unlock();
}
<commit_msg>Avoid unnecessesasry mining messages.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Client.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "Client.h"

#include <chrono>
#include <thread>
#include "Common.h"
#include "Defaults.h"
using namespace std;
using namespace eth;

Client::Client(std::string const& _clientVersion, Address _us, std::string const& _dbPath):
	m_clientVersion(_clientVersion),
	m_bc(_dbPath),
	m_stateDB(State::openDB(_dbPath)),
	m_s(_us, m_stateDB),
	m_mined(_us, m_stateDB)
{
	Defaults::setDBPath(_dbPath);

	// Synchronise the state according to the block chain - i.e. replay all transactions in block chain, in order.
	// In practise this won't need to be done since the State DB will contain the keys for the tries for most recent (and many old) blocks.
	// TODO: currently it contains keys for *all* blocks. Make it remove old ones.
	m_s.sync(m_bc);
	m_s.sync(m_tq);
	m_mined = m_s;
	m_changed = true;

	static const char* c_threadName = "eth";

	m_work = new thread([&](){
		setThreadName(c_threadName);

		while (m_workState != Deleting) work(); m_workState = Deleted;
	});
}

Client::~Client()
{
	if (m_workState == Active)
		m_workState = Deleting;
	while (m_workState != Deleted)
		this_thread::sleep_for(chrono::milliseconds(10));
}

void Client::startNetwork(short _listenPort, std::string const& _seedHost, short _port, NodeMode _mode, unsigned _peers, string const& _publicIP, bool _upnp)
{
	if (m_net)
		return;
	m_net = new PeerServer(m_clientVersion, m_bc, 0, _listenPort, _mode, _publicIP, _upnp);
	m_net->setIdealPeerCount(_peers);
	if (_seedHost.size())
		connect(_seedHost, _port);
}

void Client::connect(std::string const& _seedHost, short _port)
{
	if (!m_net)
		return;
	m_net->connect(_seedHost, _port);
}

void Client::stopNetwork()
{
	delete m_net;
	m_net = nullptr;
}

void Client::startMining()
{
	m_doMine = true;
	m_miningStarted = true;
}

void Client::stopMining()
{
	m_doMine = false;
}

void Client::transact(Secret _secret, Address _dest, u256 _amount, u256s _data)
{
	lock_guard<mutex> l(m_lock);
	Transaction t;
	t.nonce = m_mined.transactionsFrom(toAddress(_secret));
	t.receiveAddress = _dest;
	t.value = _amount;
	t.data = _data;
	t.sign(_secret);
	cnote << "New transaction " << t;
	m_tq.attemptImport(t.rlp());
	m_changed = true;
}

void Client::work()
{
	bool changed = false;

	// Process network events.
	// Synchronise block chain with network.
	// Will broadcast any of our (new) transactions and blocks, and collect & add any of their (new) transactions and blocks.
	if (m_net)
	{
		m_net->process();

		lock_guard<mutex> l(m_lock);
		if (m_net->sync(m_bc, m_tq, m_stateDB))
			changed = true;
	}

	// Synchronise state to block chain.
	// This should remove any transactions on our queue that are included within our state.
	// It also guarantees that the state reflects the longest (valid!) chain on the block chain.
	//   This might mean reverting to an earlier state and replaying some blocks, or, (worst-case:
	//   if there are no checkpoints before our fork) reverting to the genesis block and replaying
	//   all blocks.
	// Resynchronise state with block chain & trans
	{
		lock_guard<mutex> l(m_lock);
		if (m_s.sync(m_bc))
		{
			if (m_doMine)
				cnote << "Externally mined block: Restarting mining operation.";
			changed = true;
			m_miningStarted = true;	// need to re-commit to mine.
			m_mined = m_s;
		}
		if (m_mined.sync(m_tq))
		{
			if (m_doMine)
				cnote << "Additional transaction ready: Restarting mining operation.";
			changed = true;
			m_miningStarted = true;
		}
	}

	if (m_doMine)
	{
		if (m_miningStarted)
		{
			lock_guard<mutex> l(m_lock);
			m_mined.commitToMine(m_bc);
		}

		m_miningStarted = false;

		// Mine for a while.
		MineInfo mineInfo = m_mined.mine(100);
		m_mineProgress.best = max(m_mineProgress.best, mineInfo.best);
		m_mineProgress.current = mineInfo.best;
		m_mineProgress.requirement = mineInfo.requirement;

		if (mineInfo.completed)
		{
			// Import block.
			lock_guard<mutex> l(m_lock);
			m_bc.attemptImport(m_mined.blockData(), m_stateDB);
			m_mineProgress.best = 0;
			m_changed = true;
			m_miningStarted = true;	// need to re-commit to mine.
		}
	}
	else
		this_thread::sleep_for(chrono::milliseconds(100));

	m_changed = m_changed || changed;
}

void Client::lock()
{
	m_lock.lock();
}

void Client::unlock()
{
	m_lock.unlock();
}
<|endoftext|>


<commit_before>
#include "GasMeter.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

#include <libevmface/Instruction.h>
#include <libevm/FeeStructure.h>

#include "Type.h"
#include "Ext.h"

namespace dev
{
namespace eth
{
namespace jit
{

namespace // Helper functions
{

uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted)
{
	switch (inst)
	{
	case Instruction::STOP:
	case Instruction::SUICIDE:
		return 0;

	case Instruction::SSTORE:
		return static_cast<uint64_t>(FeeStructure::c_sstoreGas);

	case Instruction::SLOAD:
		return static_cast<uint64_t>(FeeStructure::c_sloadGas);

	case Instruction::SHA3:
		return static_cast<uint64_t>(FeeStructure::c_sha3Gas);

	case Instruction::BALANCE:
		return static_cast<uint64_t>(FeeStructure::c_sha3Gas);

	case Instruction::CALL:
	case Instruction::CALLCODE:
		return static_cast<uint64_t>(FeeStructure::c_callGas);

	case Instruction::CREATE:
		return static_cast<uint64_t>(FeeStructure::c_createGas);

	default: // Assumes instruction code is valid
		return static_cast<uint64_t>(FeeStructure::c_stepGas);
	}
}

bool isCostBlockEnd(Instruction _inst)
{
	// Basic block terminators like STOP are not needed on the list
	// as cost will be commited at the end of basic block

	// CALL & CALLCODE are commited manually

	switch (_inst)
	{
	case Instruction::CALLDATACOPY:
	case Instruction::CODECOPY:
	case Instruction::MLOAD:
	case Instruction::MSTORE:
	case Instruction::MSTORE8:
	case Instruction::SSTORE:
	case Instruction::GAS:
	case Instruction::CREATE:
		return true;

	default:
		return false;
	}
}

}

GasMeter::GasMeter(llvm::IRBuilder<>& _builder) :
	CompilerHelper(_builder)
{
	auto module = getModule();
	m_gas = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas");
	m_gas->setUnnamedAddr(true); // Address is not important

	m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module);
	InsertPointGuard guard(m_builder);

	auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
	auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
	auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);

	m_builder.SetInsertPoint(checkBB);
	llvm::Value* cost = m_gasCheckFunc->arg_begin();
	cost->setName("cost");
	llvm::Value* gas = m_builder.CreateLoad(m_gas, "gas");
	auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas");
	m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);

	m_builder.SetInsertPoint(outOfGasBB);

	//auto longjmpFunc = llvm::Intrinsic::getDeclaration(_module, llvm::Intrinsic::eh_sjlj_longjmp);
	auto extJmpBuf = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "rt_jmpBuf");
	llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()};
	auto longjmpNative = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", module);
	m_builder.CreateCall2(longjmpNative, m_builder.CreateLoad(extJmpBuf), Constant::get(ReturnCode::OutOfGas));
	m_builder.CreateUnreachable();

	m_builder.SetInsertPoint(updateBB);
	gas = m_builder.CreateSub(gas, cost);
	m_builder.CreateStore(gas, m_gas);
	m_builder.CreateRetVoid();
}

void GasMeter::count(Instruction _inst)
{
	if (!m_checkCall)
	{
		// Create gas check call with mocked block cost at begining of current cost-block
		m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));
	}

	if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore()
		m_blockCost += getStepCost(_inst);

	if (isCostBlockEnd(_inst))
		commitCostBlock();
}

void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
	assert(!m_checkCall); // Everything should've been commited before

	static const auto sstoreCost = static_cast<uint64_t>(FeeStructure::c_sstoreGas);

	// [ADD] if oldValue == 0 and newValue != 0  =>  2*cost
	// [DEL] if oldValue != 0 and newValue == 0  =>  0

	auto oldValue = _ext.store(_index);
	auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
	auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
	auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
	auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
	auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd");
	auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel");
	auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost");
	cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost");
	m_builder.CreateCall(m_gasCheckFunc, cost);
}

void GasMeter::giveBack(llvm::Value* _gas)
{
	llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas");
	gasCounter = m_builder.CreateAdd(gasCounter, _gas);
	m_builder.CreateStore(gasCounter, m_gas);
}

void GasMeter::commitCostBlock(llvm::Value* _additionalCost)
{
	assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block

	// If any uncommited block
	if (m_checkCall)
	{
		if (m_blockCost == 0 && !_additionalCost) // Do not check 0
		{
			m_checkCall->eraseFromParent(); // Remove the gas check call
			return;
		}

		llvm::Value* cost = Constant::get(m_blockCost);
		if (_additionalCost)
			cost = m_builder.CreateAdd(cost, _additionalCost);

		m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call
		m_checkCall = nullptr; // End cost-block
		m_blockCost = 0;
	}
	assert(m_blockCost == 0);
}

void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)
{
	// Memory uses other builder, but that can be changes later
	auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(FeeStructure::c_memoryGas)), "memcost");
	_builder.CreateCall(m_gasCheckFunc, cost);
}

llvm::Value* GasMeter::getGas()
{
	return m_builder.CreateLoad(m_gas, "gas");
}

}
}
}

<commit_msg>Fix GasMeter not nulling cost call<commit_after>
#include "GasMeter.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

#include <libevmface/Instruction.h>
#include <libevm/FeeStructure.h>

#include "Type.h"
#include "Ext.h"

namespace dev
{
namespace eth
{
namespace jit
{

namespace // Helper functions
{

uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted)
{
	switch (inst)
	{
	case Instruction::STOP:
	case Instruction::SUICIDE:
		return 0;

	case Instruction::SSTORE:
		return static_cast<uint64_t>(FeeStructure::c_sstoreGas);

	case Instruction::SLOAD:
		return static_cast<uint64_t>(FeeStructure::c_sloadGas);

	case Instruction::SHA3:
		return static_cast<uint64_t>(FeeStructure::c_sha3Gas);

	case Instruction::BALANCE:
		return static_cast<uint64_t>(FeeStructure::c_sha3Gas);

	case Instruction::CALL:
	case Instruction::CALLCODE:
		return static_cast<uint64_t>(FeeStructure::c_callGas);

	case Instruction::CREATE:
		return static_cast<uint64_t>(FeeStructure::c_createGas);

	default: // Assumes instruction code is valid
		return static_cast<uint64_t>(FeeStructure::c_stepGas);
	}
}

bool isCostBlockEnd(Instruction _inst)
{
	// Basic block terminators like STOP are not needed on the list
	// as cost will be commited at the end of basic block

	// CALL & CALLCODE are commited manually

	switch (_inst)
	{
	case Instruction::CALLDATACOPY:
	case Instruction::CODECOPY:
	case Instruction::MLOAD:
	case Instruction::MSTORE:
	case Instruction::MSTORE8:
	case Instruction::SSTORE:
	case Instruction::GAS:
	case Instruction::CREATE:
		return true;

	default:
		return false;
	}
}

}

GasMeter::GasMeter(llvm::IRBuilder<>& _builder) :
	CompilerHelper(_builder)
{
	auto module = getModule();
	m_gas = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas");
	m_gas->setUnnamedAddr(true); // Address is not important

	m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module);
	InsertPointGuard guard(m_builder);

	auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc);
	auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc);
	auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc);

	m_builder.SetInsertPoint(checkBB);
	llvm::Value* cost = m_gasCheckFunc->arg_begin();
	cost->setName("cost");
	llvm::Value* gas = m_builder.CreateLoad(m_gas, "gas");
	auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas");
	m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);

	m_builder.SetInsertPoint(outOfGasBB);

	//auto longjmpFunc = llvm::Intrinsic::getDeclaration(_module, llvm::Intrinsic::eh_sjlj_longjmp);
	auto extJmpBuf = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "rt_jmpBuf");
	llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()};
	auto longjmpNative = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", module);
	m_builder.CreateCall2(longjmpNative, m_builder.CreateLoad(extJmpBuf), Constant::get(ReturnCode::OutOfGas));
	m_builder.CreateUnreachable();

	m_builder.SetInsertPoint(updateBB);
	gas = m_builder.CreateSub(gas, cost);
	m_builder.CreateStore(gas, m_gas);
	m_builder.CreateRetVoid();
}

void GasMeter::count(Instruction _inst)
{
	if (!m_checkCall)
	{
		// Create gas check call with mocked block cost at begining of current cost-block
		m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));
	}

	if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore()
		m_blockCost += getStepCost(_inst);

	if (isCostBlockEnd(_inst))
		commitCostBlock();
}

void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
	assert(!m_checkCall); // Everything should've been commited before

	static const auto sstoreCost = static_cast<uint64_t>(FeeStructure::c_sstoreGas);

	// [ADD] if oldValue == 0 and newValue != 0  =>  2*cost
	// [DEL] if oldValue != 0 and newValue == 0  =>  0

	auto oldValue = _ext.store(_index);
	auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
	auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
	auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
	auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
	auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd");
	auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel");
	auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost");
	cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost");
	m_builder.CreateCall(m_gasCheckFunc, cost);
}

void GasMeter::giveBack(llvm::Value* _gas)
{
	llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas");
	gasCounter = m_builder.CreateAdd(gasCounter, _gas);
	m_builder.CreateStore(gasCounter, m_gas);
}

void GasMeter::commitCostBlock(llvm::Value* _additionalCost)
{
	assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block

	// If any uncommited block
	if (m_checkCall)
	{
		if (m_blockCost == 0 && !_additionalCost) // Do not check 0
		{
			m_checkCall->eraseFromParent(); // Remove the gas check call
			m_checkCall = nullptr;
			return;
		}

		llvm::Value* cost = Constant::get(m_blockCost);
		if (_additionalCost)
			cost = m_builder.CreateAdd(cost, _additionalCost);

		m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call
		m_checkCall = nullptr; // End cost-block
		m_blockCost = 0;
	}
	assert(m_blockCost == 0);
}

void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)
{
	// Memory uses other builder, but that can be changes later
	auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(FeeStructure::c_memoryGas)), "memcost");
	_builder.CreateCall(m_gasCheckFunc, cost);
}

llvm::Value* GasMeter::getGas()
{
	return m_builder.CreateLoad(m_gas, "gas");
}

}
}
}

<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Serge Bazanski <q3k@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "quadtree.h"
#include "gtest/gtest.h"
#include "nextpnr.h"

USING_NEXTPNR_NAMESPACE

using QT = QuadTree<int, int>;

class QuadTreeTest : public ::testing::Test
{
  protected:
    virtual void SetUp() { qt_ = new QT(QT::BoundingBox(0, 0, width_, height_)); }
    virtual void TearDown() { delete qt_; }

    int width_ = 100;
    int height_ = 100;
    QT *qt_;
};

// Test that we're doing bound checking correctly.
TEST_F(QuadTreeTest, insert_bound_checking)
{
    ASSERT_TRUE(qt_->insert(QT::BoundingBox(10, 10, 20, 20), 10));
    ASSERT_TRUE(qt_->insert(QT::BoundingBox(0, 0, 100, 100), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(10, 10, 101, 20), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, 10, 101, 20), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, -1, 20, 20), 10));
}

// Test whether we are not losing any elements.
TEST_F(QuadTreeTest, insert_count)
{
    auto rng = NEXTPNR_NAMESPACE::DeterministicRNG();

    // Add 10000 random rectangles.
    for (unsigned int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w;
        int y1 = y0 + h;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
        ASSERT_EQ(qt_->size(), i + 1);
    }
    // Add 100000 random points.
    for (unsigned int i = 0; i < 100000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int x1 = x0;
        int y1 = y0;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
        ASSERT_EQ(qt_->size(), i + 10001);
    }
}

// Test that we can insert and retrieve the same element.
TEST_F(QuadTreeTest, insert_retrieve_same)
{
    auto rng = NEXTPNR_NAMESPACE::DeterministicRNG();

    // Add 10000 small random rectangles.
    rng.rngseed(0);
    for (int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w / 4;
        int y1 = y0 + h / 4;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
    }

    // Restart RNG, make sure we get the same rectangles back.
    rng.rngseed(0);
    for (int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w / 4;
        int y1 = y0 + h / 4;

        // try to find something in the middle of the square
        int x = (x1 - x0) / 2 + x0;
        int y = (y1 - y0) / 2 + y0;

        auto res = qt_->get(x, y);
        // Somewhat arbirary test to make sure we don't return obscene
        // amounts of data.
        ASSERT_LT(res.size(), 200UL);
        bool found = false;
        for (auto elem : res) {
            // Is this what we're looking for?
            if (elem == i) {
                found = true;
                break;
            }
        }
        ASSERT_TRUE(found);
    }
}
<commit_msg>gui: fix quadtree test<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Serge Bazanski <q3k@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "gtest/gtest.h"
#include "nextpnr.h"
#include "quadtree.h"

USING_NEXTPNR_NAMESPACE

using QT = QuadTree<int, int>;

class QuadTreeTest : public ::testing::Test
{
  protected:
    virtual void SetUp() { qt_ = new QT(QT::BoundingBox(0, 0, width_, height_)); }
    virtual void TearDown() { delete qt_; }

    int width_ = 100;
    int height_ = 100;
    QT *qt_;
};

// Test that we're doing bound checking correctly.
TEST_F(QuadTreeTest, insert_bound_checking)
{
    ASSERT_TRUE(qt_->insert(QT::BoundingBox(10, 10, 20, 20), 10));
    ASSERT_TRUE(qt_->insert(QT::BoundingBox(0, 0, 100, 100), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(10, 10, 101, 20), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, 10, 101, 20), 10));
    ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, -1, 20, 20), 10));
}

// Test whether we are not losing any elements.
TEST_F(QuadTreeTest, insert_count)
{
    auto rng = NEXTPNR_NAMESPACE::DeterministicRNG();

    // Add 10000 random rectangles.
    for (unsigned int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w;
        int y1 = y0 + h;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
        ASSERT_EQ(qt_->size(), i + 1);
    }
    // Add 100000 random points.
    for (unsigned int i = 0; i < 100000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int x1 = x0;
        int y1 = y0;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
        ASSERT_EQ(qt_->size(), i + 10001);
    }
}

// Test that we can insert and retrieve the same element.
TEST_F(QuadTreeTest, insert_retrieve_same)
{
    auto rng = NEXTPNR_NAMESPACE::DeterministicRNG();

    // Add 10000 small random rectangles.
    rng.rngseed(0);
    for (int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w / 4;
        int y1 = y0 + h / 4;
        ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i));
    }

    // Restart RNG, make sure we get the same rectangles back.
    rng.rngseed(0);
    for (int i = 0; i < 10000; i++) {
        int x0 = rng.rng(width_);
        int y0 = rng.rng(height_);
        int w = rng.rng(width_ - x0);
        int h = rng.rng(width_ - y0);
        int x1 = x0 + w / 4;
        int y1 = y0 + h / 4;

        // try to find something in the middle of the square
        int x = (x1 - x0) / 2 + x0;
        int y = (y1 - y0) / 2 + y0;

        auto res = qt_->get(x, y);
        // Somewhat arbirary test to make sure we don't return obscene
        // amounts of data.
        ASSERT_LT(res.size(), 200UL);
        bool found = false;
        for (auto elem : res) {
            // Is this what we're looking for?
            if (elem == i) {
                found = true;
                break;
            }
        }
        ASSERT_TRUE(found);
    }
}
<|endoftext|>


<commit_before>#include <Game.h>

Game::Game(const std::string& _name) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Initialization"
    INFO("Initializing new Game: %s", _name.c_str());
    config.name = _name;

    readConfig();

    INFO("Creating %dx%d render target", renderWidth, renderHeight);
    screen.create(renderWidth, renderHeight);

    createWindow(config.fullscreen);

    INFO("Creating gameplay entities");
    spritesMutex.lock();
    player = new GamePlayer;
    player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4);
    sprites.push_back(player);
    spritesMutex.unlock();
    INFO("Created player");

    isReady = true;
    INFO("Initialization Complete");
}

Game& Game::getGame(const std::string& _name) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Initialization"
    static Game* instance = new Game(_name);
    INFO("Getting Game instance");
    return *instance;
}

bool Game::ready() {
    return isReady;
}

void Game::run() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Loop"
    releaseWindow();
    sf::Thread renderThread(&Game::renderLoop, this);
    renderThread.launch();

    INFO("Initializing eventLoop");
    sf::Clock gameClock;
    sf::Time elapsedTime;
    sf::Int32 lastUpdateTime;
    sf::Int32 totalUpdateTime = 0;
    sf::Int32 averageUpdateTime;
    sf::Int32 updateCount = 0;
    INFO("Starting eventLoop");
    while (window.isOpen()) {
        elapsedTime = gameClock.restart();
        processEvents();
        updateControls();
        updateWorld(elapsedTime);
        lastUpdateTime = gameClock.getElapsedTime().asMilliseconds();
        totalUpdateTime += lastUpdateTime;
        averageUpdateTime = totalUpdateTime / ++updateCount;
        // log the average time per update every seconds
        if (updateCount % (60 * 1) == 0) {
            DBUG("Average update time: %d ms", averageUpdateTime);
        }
        // update at approximately 60 Hz
        sf::sleep(sf::milliseconds(16));
    }
    INFO("Stopped eventLoop");
}

void inline Game::lockWindow(bool log) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Control"
    if (log) DBUG("Grabbing window lock");
    windowMutex.lock();
    window.setActive(true);
}

void inline Game::releaseWindow(bool log) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Control"
    if (log) DBUG("Releasing window lock");
    window.setActive(false);
    windowMutex.unlock();
}

void Game::readConfig() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Configuration"
    std::__cxx11::string iniFilename = config.name;
    iniFilename.append(".ini");

    INIReader reader(iniFilename);
    INFO("Reading config from '%s'", iniFilename.c_str());
    if (reader.ParseError() < 0) {
        ERR("Can't load '%s', using defaults", iniFilename.c_str());
    } else {
        // 1200x675 is a 16:9 window that fits inside a 1366x768 screen on most systems
        config.width = (unsigned int) std::abs(reader.GetInteger("game", "width", (long) config.width));
        config.height = (unsigned int) std::abs(reader.GetInteger("game", "height", (long) config.height));
        config.fullscreen = reader.GetBoolean("game", "fullscreen", config.fullscreen);
        config.useDesktopSize = reader.GetBoolean("game", "useDesktopSize", config.useDesktopSize);
        config.vsync = reader.GetBoolean("game", "vsync", config.useDesktopSize);
        config.deadZone = static_cast<float>(reader.GetReal("game", "deadZone", config.deadZone));
        config.keySpeed = static_cast<float>(reader.GetReal("game", "keySpeed", config.keySpeed));
    }
    INFO("Current settings:");
    INFO("\twidth = %d", config.width);
    INFO("\theight = %d", config.height);
    INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false"));
    INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false"));
    INFO("\tvsync = %s", (config.vsync ? "true" : "false"));
    INFO("\tdeadZone = %f", config.deadZone);
    INFO("\tkeySpeed = %f", config.keySpeed);
}

void Game::createWindow(bool shouldFullscreen) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Creation"
    unsigned int flags = 0;

    lockWindow();

    INFO("Reading config");
    sf::VideoMode mode;
    config.fullscreen = shouldFullscreen;
    if (config.fullscreen) {
        INFO("Going fullscreen");
        window.setMouseCursorVisible(false);
        if (config.useDesktopSize) {
            INFO("Setting fullscreen mode (using desktop size): %dx%d",
                 sf::VideoMode::getDesktopMode().width,
                 sf::VideoMode::getDesktopMode().height);
            mode = sf::VideoMode::getDesktopMode();
        } else {
            INFO("Setting fullscreen mode: %dx%d", config.width, config.height);
            mode = sf::VideoMode(config.width, config.height);
        }
        flags = sf::Style::Fullscreen;
    } else {
        INFO("Setting windowed mode: %dx%d", config.width, config.height);
        window.setMouseCursorVisible(true);
        mode = sf::VideoMode(config.width, config.height);
        flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize;
    }
    INFO("Creating the main window");
    window.create(mode, config.name, flags);
    if (!window.isOpen()) {
        ERR("Could not create main window");
        exit(EXIT_FAILURE);
    }
    sf::ContextSettings settings = window.getSettings();
    INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion);

    // initialize the view
    INFO("Setting window view");
    view = window.getDefaultView();
    view.setSize(renderWidth, renderHeight);
    view.setCenter(renderWidth / 2, renderHeight / 2);
    window.setView(view);
    if (config.vsync) {
        INFO("Enabling V-sync");
        window.setVerticalSyncEnabled(true);
    }

    releaseWindow();

    // scale the viewport to maintain good aspect
    adjustAspect(window.getSize());
}

void Game::adjustAspect(sf::Event::SizeEvent newSize) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Aspect Adjustment"
    // save the new window size since this came from a resize event
    // not from a window creation event (initialization or fullscreen toggle)
    config.width = newSize.width;
    config.height = newSize.height;
    INFO("Window resized to: %dx%d", config.width, config.height);
    // do the calculation
    adjustAspect(sf::Vector2u(newSize.width, newSize.height));
}

void Game::adjustAspect(sf::Vector2u newSize) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Aspect Adjustment"
    INFO("Adjusting aspect for window size ", newSize.x, newSize.y);
    // compute the current aspect
    float currentRatio = (float) newSize.x / (float) newSize.y;
    // used to offset and scale the viewport to maintain 16:9 aspect
    float widthScale = 1.0f;
    float widthOffset = 0.0f;
    float heightScale = 1.0f;
    float heightOffset = 0.0f;
    // used to compare and compute aspect ratios
    // for logging
    std::string isSixteenNine = "16:9";
    if (currentRatio > 16.0f / 9.0f) {
        // we are wider
        isSixteenNine = "wide";
        widthScale = newSize.y * (16.0f / 9.0f) / newSize.x;
        widthOffset = (1.0f - widthScale) / 2.0f;
    } else if (currentRatio < 16.0f / 9.0f) {
        // we are narrower
        isSixteenNine = "narrow";
        heightScale = newSize.x * (9.0f / 16.0f) / newSize.y;
        heightOffset = (1.0f - heightScale) / 2.0f;
    }
    lockWindow();
    INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(),
         widthOffset, heightOffset, widthScale, heightScale);
    view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale));
    window.setView(view);
    releaseWindow();
}

void Game::processEvents() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    static sf::Event event;

    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                INFO("Window closed");
                window.close();
                break;
            case sf::Event::Resized:
                adjustAspect(event.size);
                break;
            case sf::Event::KeyPressed:
                handleKeyPress(event);
                break;
            case sf::Event::KeyReleased:
                handleKeyRelease(event);
                break;
            default:
                break;
        }
    }
}

void Game::handleKeyPress(const sf::Event& event) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    switch (event.key.code) {
        case sf::Keyboard::Escape:
            INFO("Key: Escape: exiting");
            window.close();
            break;
        case sf::Keyboard::Return:
            if (event.key.alt) {
                createWindow(!config.fullscreen);
            }
            break;
        default:
            break;
    }
}

void Game::handleKeyRelease(const sf::Event& event) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    switch (event.key.code) {
        default:
            break;
    }
}

void Game::updateControls() {
    float x, y = 0;

    float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
    float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
    x = fabs(joy0_X) < config.deadZone ? 0 : joy0_X;
    y = fabs(joy0_y) < config.deadZone ? 0 : joy0_y;

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        y += -config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        x += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        y += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        x += -config.keySpeed;
    }
    spritesMutex.lock();
    player->moveBy(x, y);
    spritesMutex.unlock();

}

void Game::updateWorld(sf::Time elapsed) {
    spritesMutex.lock();
    const int millis = elapsed.asMilliseconds();
    for (auto sprite : sprites) {
        sprite->update(millis);
    }
    spritesMutex.unlock();
}

void Game::renderLoop() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Render Loop"
    INFO("Initializing renderLoop");
    sf::Clock frameClock;
    sf::Int32 lastFrameTime;
    sf::Int32 averageFrameTime;
    sf::Int32 totalFrameTime = 0;
    sf::Int32 frameCount = 0;
    INFO("Starting renderLoop");
    while (window.isOpen()) {
        frameClock.restart();
        // blank the render target to black
        screen.clear(sf::Color::Black);
        // render all the normal sprites
        spritesMutex.lock();
        for (const auto sprite : sprites) {
            screen.draw(*sprite);
        }
        spritesMutex.unlock();
        // update the target
        screen.display();
        lockWindow(false);
        // blank the window to gray
        window.clear(sf::Color(128, 128, 128));
        // copy render target to window
        window.draw(sf::Sprite(screen.getTexture()));
        // update thw window
        window.display();
        releaseWindow(false);
        lastFrameTime = frameClock.getElapsedTime().asMilliseconds();
        totalFrameTime += lastFrameTime;
        averageFrameTime = totalFrameTime / ++frameCount;
        // log the time per frame every 60 frames (every second if at 60 Hz)
        if (frameCount % (60 * 1) == 0) {
            DBUG("Average frame time: %d ms", averageFrameTime);
        }
    }
    INFO("Stopped renderLoop");
}<commit_msg>Fix weird __cxx11 thing from IDEA's refactoring.<commit_after>#include <Game.h>

Game::Game(const std::string& _name) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Initialization"
    INFO("Initializing new Game: %s", _name.c_str());
    config.name = _name;

    readConfig();

    INFO("Creating %dx%d render target", renderWidth, renderHeight);
    screen.create(renderWidth, renderHeight);

    createWindow(config.fullscreen);

    INFO("Creating gameplay entities");
    spritesMutex.lock();
    player = new GamePlayer;
    player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4);
    sprites.push_back(player);
    spritesMutex.unlock();
    INFO("Created player");

    isReady = true;
    INFO("Initialization Complete");
}

Game& Game::getGame(const std::string& _name) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Initialization"
    static Game* instance = new Game(_name);
    INFO("Getting Game instance");
    return *instance;
}

bool Game::ready() {
    return isReady;
}

void Game::run() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Loop"
    releaseWindow();
    sf::Thread renderThread(&Game::renderLoop, this);
    renderThread.launch();

    INFO("Initializing eventLoop");
    sf::Clock gameClock;
    sf::Time elapsedTime;
    sf::Int32 lastUpdateTime;
    sf::Int32 totalUpdateTime = 0;
    sf::Int32 averageUpdateTime;
    sf::Int32 updateCount = 0;
    INFO("Starting eventLoop");
    while (window.isOpen()) {
        elapsedTime = gameClock.restart();
        processEvents();
        updateControls();
        updateWorld(elapsedTime);
        lastUpdateTime = gameClock.getElapsedTime().asMilliseconds();
        totalUpdateTime += lastUpdateTime;
        averageUpdateTime = totalUpdateTime / ++updateCount;
        // log the average time per update every seconds
        if (updateCount % (60 * 1) == 0) {
            DBUG("Average update time: %d ms", averageUpdateTime);
        }
        // update at approximately 60 Hz
        sf::sleep(sf::milliseconds(16));
    }
    INFO("Stopped eventLoop");
}

void inline Game::lockWindow(bool log) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Control"
    if (log) DBUG("Grabbing window lock");
    windowMutex.lock();
    window.setActive(true);
}

void inline Game::releaseWindow(bool log) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Control"
    if (log) DBUG("Releasing window lock");
    window.setActive(false);
    windowMutex.unlock();
}

void Game::readConfig() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Configuration"
    std::string iniFilename = config.name;
    iniFilename.append(".ini");

    INIReader reader(iniFilename);
    INFO("Reading config from '%s'", iniFilename.c_str());
    if (reader.ParseError() < 0) {
        ERR("Can't load '%s', using defaults", iniFilename.c_str());
    } else {
        // 1200x675 is a 16:9 window that fits inside a 1366x768 screen on most systems
        config.width = (unsigned int) std::abs(reader.GetInteger("game", "width", (long) config.width));
        config.height = (unsigned int) std::abs(reader.GetInteger("game", "height", (long) config.height));
        config.fullscreen = reader.GetBoolean("game", "fullscreen", config.fullscreen);
        config.useDesktopSize = reader.GetBoolean("game", "useDesktopSize", config.useDesktopSize);
        config.vsync = reader.GetBoolean("game", "vsync", config.useDesktopSize);
        config.deadZone = static_cast<float>(reader.GetReal("game", "deadZone", config.deadZone));
        config.keySpeed = static_cast<float>(reader.GetReal("game", "keySpeed", config.keySpeed));
    }
    INFO("Current settings:");
    INFO("\twidth = %d", config.width);
    INFO("\theight = %d", config.height);
    INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false"));
    INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false"));
    INFO("\tvsync = %s", (config.vsync ? "true" : "false"));
    INFO("\tdeadZone = %f", config.deadZone);
    INFO("\tkeySpeed = %f", config.keySpeed);
}

void Game::createWindow(bool shouldFullscreen) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Window Creation"
    unsigned int flags = 0;

    lockWindow();

    INFO("Reading config");
    sf::VideoMode mode;
    config.fullscreen = shouldFullscreen;
    if (config.fullscreen) {
        INFO("Going fullscreen");
        window.setMouseCursorVisible(false);
        if (config.useDesktopSize) {
            INFO("Setting fullscreen mode (using desktop size): %dx%d",
                 sf::VideoMode::getDesktopMode().width,
                 sf::VideoMode::getDesktopMode().height);
            mode = sf::VideoMode::getDesktopMode();
        } else {
            INFO("Setting fullscreen mode: %dx%d", config.width, config.height);
            mode = sf::VideoMode(config.width, config.height);
        }
        flags = sf::Style::Fullscreen;
    } else {
        INFO("Setting windowed mode: %dx%d", config.width, config.height);
        window.setMouseCursorVisible(true);
        mode = sf::VideoMode(config.width, config.height);
        flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize;
    }
    INFO("Creating the main window");
    window.create(mode, config.name, flags);
    if (!window.isOpen()) {
        ERR("Could not create main window");
        exit(EXIT_FAILURE);
    }
    sf::ContextSettings settings = window.getSettings();
    INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion);

    // initialize the view
    INFO("Setting window view");
    view = window.getDefaultView();
    view.setSize(renderWidth, renderHeight);
    view.setCenter(renderWidth / 2, renderHeight / 2);
    window.setView(view);
    if (config.vsync) {
        INFO("Enabling V-sync");
        window.setVerticalSyncEnabled(true);
    }

    releaseWindow();

    // scale the viewport to maintain good aspect
    adjustAspect(window.getSize());
}

void Game::adjustAspect(sf::Event::SizeEvent newSize) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Aspect Adjustment"
    // save the new window size since this came from a resize event
    // not from a window creation event (initialization or fullscreen toggle)
    config.width = newSize.width;
    config.height = newSize.height;
    INFO("Window resized to: %dx%d", config.width, config.height);
    // do the calculation
    adjustAspect(sf::Vector2u(newSize.width, newSize.height));
}

void Game::adjustAspect(sf::Vector2u newSize) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Aspect Adjustment"
    INFO("Adjusting aspect for window size ", newSize.x, newSize.y);
    // compute the current aspect
    float currentRatio = (float) newSize.x / (float) newSize.y;
    // used to offset and scale the viewport to maintain 16:9 aspect
    float widthScale = 1.0f;
    float widthOffset = 0.0f;
    float heightScale = 1.0f;
    float heightOffset = 0.0f;
    // used to compare and compute aspect ratios
    // for logging
    std::string isSixteenNine = "16:9";
    if (currentRatio > 16.0f / 9.0f) {
        // we are wider
        isSixteenNine = "wide";
        widthScale = newSize.y * (16.0f / 9.0f) / newSize.x;
        widthOffset = (1.0f - widthScale) / 2.0f;
    } else if (currentRatio < 16.0f / 9.0f) {
        // we are narrower
        isSixteenNine = "narrow";
        heightScale = newSize.x * (9.0f / 16.0f) / newSize.y;
        heightOffset = (1.0f - heightScale) / 2.0f;
    }
    lockWindow();
    INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(),
         widthOffset, heightOffset, widthScale, heightScale);
    view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale));
    window.setView(view);
    releaseWindow();
}

void Game::processEvents() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    static sf::Event event;

    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                INFO("Window closed");
                window.close();
                break;
            case sf::Event::Resized:
                adjustAspect(event.size);
                break;
            case sf::Event::KeyPressed:
                handleKeyPress(event);
                break;
            case sf::Event::KeyReleased:
                handleKeyRelease(event);
                break;
            default:
                break;
        }
    }
}

void Game::handleKeyPress(const sf::Event& event) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    switch (event.key.code) {
        case sf::Keyboard::Escape:
            INFO("Key: Escape: exiting");
            window.close();
            break;
        case sf::Keyboard::Return:
            if (event.key.alt) {
                createWindow(!config.fullscreen);
            }
            break;
        default:
            break;
    }
}

void Game::handleKeyRelease(const sf::Event& event) {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Event Processing"
    switch (event.key.code) {
        default:
            break;
    }
}

void Game::updateControls() {
    float x, y = 0;

    float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
    float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
    x = fabs(joy0_X) < config.deadZone ? 0 : joy0_X;
    y = fabs(joy0_y) < config.deadZone ? 0 : joy0_y;

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
        y += -config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        x += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
        y += config.keySpeed;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        x += -config.keySpeed;
    }
    spritesMutex.lock();
    player->moveBy(x, y);
    spritesMutex.unlock();

}

void Game::updateWorld(sf::Time elapsed) {
    spritesMutex.lock();
    const int millis = elapsed.asMilliseconds();
    for (auto sprite : sprites) {
        sprite->update(millis);
    }
    spritesMutex.unlock();
}

void Game::renderLoop() {
#undef LOGOG_CATEGORY
#define LOGOG_CATEGORY  "Render Loop"
    INFO("Initializing renderLoop");
    sf::Clock frameClock;
    sf::Int32 lastFrameTime;
    sf::Int32 averageFrameTime;
    sf::Int32 totalFrameTime = 0;
    sf::Int32 frameCount = 0;
    INFO("Starting renderLoop");
    while (window.isOpen()) {
        frameClock.restart();
        // blank the render target to black
        screen.clear(sf::Color::Black);
        // render all the normal sprites
        spritesMutex.lock();
        for (const auto sprite : sprites) {
            screen.draw(*sprite);
        }
        spritesMutex.unlock();
        // update the target
        screen.display();
        lockWindow(false);
        // blank the window to gray
        window.clear(sf::Color(128, 128, 128));
        // copy render target to window
        window.draw(sf::Sprite(screen.getTexture()));
        // update thw window
        window.display();
        releaseWindow(false);
        lastFrameTime = frameClock.getElapsedTime().asMilliseconds();
        totalFrameTime += lastFrameTime;
        averageFrameTime = totalFrameTime / ++frameCount;
        // log the time per frame every 60 frames (every second if at 60 Hz)
        if (frameCount % (60 * 1) == 0) {
            DBUG("Average frame time: %d ms", averageFrameTime);
        }
    }
    INFO("Stopped renderLoop");
}<|endoftext|>