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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif

#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32) || defined(SAL_OS2)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<commit_msg>INTEGRATION: CWS os2port02 (1.21.4); FILE MERGED 2007/10/04 19:44:40 ydario 1.21.4.1: Issue number: i82034 Submitted by: ydario Reviewed by:  ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlccompile.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 12:26:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif

#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2_00
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<|endoftext|>


<commit_before><commit_msg>Troubleshooting<commit_after><|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "Chapter.h"

#include "database/SqliteTools.h"
#include "database/SqliteQuery.h"
#include "Media.h"

namespace medialibrary
{

const std::string Chapter::Table::Name = "Chapter";
const std::string Chapter::Table::PrimaryKeyColumn = "id_chapter";
int64_t Chapter::* const Chapter::Table::PrimaryKey = &Chapter::m_id;

void Chapter::createTable( sqlite::Connection* dbConn )
{
    return sqlite::Tools::executeRequest( dbConn,
                                          schema( Table::Name, Settings::DbModelVersion ) );
}

std::string Chapter::schema( const std::string& tableName, uint32_t )
{
    assert( tableName == Table::Name );
    return "CREATE TABLE IF NOT EXISTS " + Table::Name +
    "("
        + Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        "offset INTEGER NOT NULL,"
        "duration INTEGER NOT NULL,"
        "name TEXT,"
        "media_id INTEGER,"
        "FOREIGN KEY(media_id) REFERENCES " +
            Media::Table::Name + "(" + Media::Table::PrimaryKeyColumn + ")"
            " ON DELETE CASCADE"
    ")";
}

std::shared_ptr<Chapter> Chapter::create( MediaLibraryPtr ml, int64_t offset,
                                          int64_t duration, std::string name,
                                          int64_t mediaId )
{
    static const std::string req = "INSERT INTO " + Table::Name +
            "(offset, duration, name, media_id) VALUES(?, ?, ?, ?)";
    auto self = std::make_shared<Chapter>( ml, offset, duration,
                                           std::move( name ) );
    if ( insert( ml, self, req, offset, duration, self->m_name, mediaId ) == false )
        return nullptr;
    return self;
}

Query<IChapter> Chapter::fromMedia( MediaLibraryPtr ml, int64_t mediaId,
                                    const QueryParameters* params )
{
    std::string req = "FROM " + Table::Name + " WHERE media_id = ?";
    std::string orderBy = "ORDER BY ";
    auto desc = params != nullptr ? params->desc : false;
    auto sort = params != nullptr ? params->sort : SortingCriteria::Default;

    switch ( sort )
    {
        case SortingCriteria::Alpha:
            orderBy += "name";
            break;
        case SortingCriteria::Duration:
            orderBy += "duration";
            desc = !desc;
            break;
        default:
            LOG_WARN( "Unsupported sorting criteria ",
                      static_cast<std::underlying_type<SortingCriteria>::type>( sort ),
                      " falling back to default (by offset)" );
            /* fall-through */
        case SortingCriteria::Default:
            orderBy += "offset";
            break;
    }
    if ( desc == true )
        orderBy += " DESC";

    return make_query<Chapter, IChapter>( ml, "*", req, orderBy, mediaId );
}

Chapter::Chapter( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
    , m_id( row.extract<decltype(m_id)>() )
    , m_offset( row.extract<decltype(m_offset)>() )
    , m_duration( row.extract<decltype(m_offset)>() )
    , m_name( row.extract<decltype(m_name)>() )
{
    // Simply check that the media_id row is present, until we eventually store it
    assert( row.extract<int64_t>() );
    assert( row.hasRemainingColumns() == false );
}

Chapter::Chapter( MediaLibraryPtr ml, int64_t offset, int64_t duration,
                  std::string name )
    : m_ml( ml )
    , m_id( 0 )
    , m_offset( offset )
    , m_duration( duration )
    , m_name( std::move( name ) )
{
}

const std::string& Chapter::name() const
{
    return m_name;
}

int64_t Chapter::offset() const
{
    return m_offset;
}

int64_t Chapter::duration() const
{
    return m_duration;
}

}
<commit_msg>Chapter: Remove IF NOT EXISTS from the table creation request<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "Chapter.h"

#include "database/SqliteTools.h"
#include "database/SqliteQuery.h"
#include "Media.h"

namespace medialibrary
{

const std::string Chapter::Table::Name = "Chapter";
const std::string Chapter::Table::PrimaryKeyColumn = "id_chapter";
int64_t Chapter::* const Chapter::Table::PrimaryKey = &Chapter::m_id;

void Chapter::createTable( sqlite::Connection* dbConn )
{
    return sqlite::Tools::executeRequest( dbConn,
                                          schema( Table::Name, Settings::DbModelVersion ) );
}

std::string Chapter::schema( const std::string& tableName, uint32_t )
{
    assert( tableName == Table::Name );
    return "CREATE TABLE " + Table::Name +
    "("
        + Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        "offset INTEGER NOT NULL,"
        "duration INTEGER NOT NULL,"
        "name TEXT,"
        "media_id INTEGER,"
        "FOREIGN KEY(media_id) REFERENCES " +
            Media::Table::Name + "(" + Media::Table::PrimaryKeyColumn + ")"
            " ON DELETE CASCADE"
    ")";
}

std::shared_ptr<Chapter> Chapter::create( MediaLibraryPtr ml, int64_t offset,
                                          int64_t duration, std::string name,
                                          int64_t mediaId )
{
    static const std::string req = "INSERT INTO " + Table::Name +
            "(offset, duration, name, media_id) VALUES(?, ?, ?, ?)";
    auto self = std::make_shared<Chapter>( ml, offset, duration,
                                           std::move( name ) );
    if ( insert( ml, self, req, offset, duration, self->m_name, mediaId ) == false )
        return nullptr;
    return self;
}

Query<IChapter> Chapter::fromMedia( MediaLibraryPtr ml, int64_t mediaId,
                                    const QueryParameters* params )
{
    std::string req = "FROM " + Table::Name + " WHERE media_id = ?";
    std::string orderBy = "ORDER BY ";
    auto desc = params != nullptr ? params->desc : false;
    auto sort = params != nullptr ? params->sort : SortingCriteria::Default;

    switch ( sort )
    {
        case SortingCriteria::Alpha:
            orderBy += "name";
            break;
        case SortingCriteria::Duration:
            orderBy += "duration";
            desc = !desc;
            break;
        default:
            LOG_WARN( "Unsupported sorting criteria ",
                      static_cast<std::underlying_type<SortingCriteria>::type>( sort ),
                      " falling back to default (by offset)" );
            /* fall-through */
        case SortingCriteria::Default:
            orderBy += "offset";
            break;
    }
    if ( desc == true )
        orderBy += " DESC";

    return make_query<Chapter, IChapter>( ml, "*", req, orderBy, mediaId );
}

Chapter::Chapter( MediaLibraryPtr ml, sqlite::Row& row )
    : m_ml( ml )
    , m_id( row.extract<decltype(m_id)>() )
    , m_offset( row.extract<decltype(m_offset)>() )
    , m_duration( row.extract<decltype(m_offset)>() )
    , m_name( row.extract<decltype(m_name)>() )
{
    // Simply check that the media_id row is present, until we eventually store it
    assert( row.extract<int64_t>() );
    assert( row.hasRemainingColumns() == false );
}

Chapter::Chapter( MediaLibraryPtr ml, int64_t offset, int64_t duration,
                  std::string name )
    : m_ml( ml )
    , m_id( 0 )
    , m_offset( offset )
    , m_duration( duration )
    , m_name( std::move( name ) )
{
}

const std::string& Chapter::name() const
{
    return m_name;
}

int64_t Chapter::offset() const
{
    return m_offset;
}

int64_t Chapter::duration() const
{
    return m_duration;
}

}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Miroslaw Opoka <mirek@opoki.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <stdarg.h>
#include <Arduino.h>
#include "Display.hpp"
#include "Const.hpp"

namespace MO
{
    Display::Display():
        the_lcd(Const::PIN_RS, Const::PIN_ENABLE,
                Const::PIN_D4, Const::PIN_D5, Const::PIN_D6, Const::PIN_D7)
    {
        for (uint8_t i = 0; i < MAX_LINES; ++i)
            memset(the_old_line[i], 0, BUF_SIZE);
    }

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

    void Display::Setup()
    {
        the_lcd.begin(MAX_CHARS, MAX_LINES);   // 16x2 format
        pinMode(MO::Const::PIN_LCD_BRIGHTNESS, OUTPUT); // uses PWM pin
        pinMode(MO::Const::PIN_LCD_CONTRAST, OUTPUT); // uses PWM pin

        // delivers 80/255 duty cycle PWM
        analogWrite(MO::Const::PIN_LCD_BRIGHTNESS, 80);

        // for contrast we should deliver real analog signal.
        // Putting PWM instead may work, but sometimes the result is
        // flickering. To prevent that some simple RC filter needs to be added.
        // Alternatively just R will do, however it is a waste of energy.
        //
        // If you want try PWM uncomment the line below and replace resistor
        // with RC (another R in serie and a capacitor parallel).
        // analogWrite(MO::Const::PIN_LCD_CONTRAST, 128);
    }

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

    void Display::Setup_Char(uint8_t a_char, uint8_t *a_matrix)
    {
        the_lcd.createChar(a_char, a_matrix);
    }

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

    void Display::Write(uint8_t a_x, uint8_t a_y, const char *a_format, ...)
    {
        va_list vl;
        va_start(vl, a_format);
        write(a_x, a_y, a_format, vl);
        va_end(vl);
    }

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

    void Display::Write(uint8_t a_y, const char *a_format, ...)
    {
        va_list vl;
        va_start(vl, a_format);
        write(0, a_y, a_format, vl);
        va_end(vl);
    }

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

    void Display::write(uint8_t a_x, uint8_t a_y, const char *a_format, va_list &a_vl)
    {
        if (a_y >= MAX_LINES)
            return;

        int written = vsnprintf(the_buf, BUF_SIZE, a_format, a_vl);

        if (written >= 0) // even if we don't write chars - we still clean the line
        {
            // fill up the rest with spaces
            for (int i = written; i < MAX_CHARS; ++i)
                the_buf[i] = ' ';
            the_buf[MAX_CHARS] = 0;
        }
        else
        {
            memset(the_buf, 0, BUF_SIZE);
        }

        if (strcmp(the_buf, the_old_line[a_y]) != 0)
        {
            the_lcd.setCursor(0, a_y);
            the_lcd.print(the_buf);
            memcpy(the_old_line[a_y], the_buf, BUF_SIZE);
        }
    }
}

<commit_msg>using a condensator for contrast<commit_after>/*
Copyright (c) 2016 Miroslaw Opoka <mirek@opoki.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <stdarg.h>
#include <Arduino.h>
#include "Display.hpp"
#include "Const.hpp"

namespace MO
{
    Display::Display():
        the_lcd(Const::PIN_RS, Const::PIN_ENABLE,
                Const::PIN_D4, Const::PIN_D5, Const::PIN_D6, Const::PIN_D7)
    {
        for (uint8_t i = 0; i < MAX_LINES; ++i)
            memset(the_old_line[i], 0, BUF_SIZE);
    }

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

    void Display::Setup()
    {
        the_lcd.begin(MAX_CHARS, MAX_LINES);   // 16x2 format
        pinMode(MO::Const::PIN_LCD_BRIGHTNESS, OUTPUT); // uses PWM pin
        pinMode(MO::Const::PIN_LCD_CONTRAST, OUTPUT); // uses PWM pin

        // delivers 80/255 duty cycle PWM
        analogWrite(MO::Const::PIN_LCD_BRIGHTNESS, 80);

        // there is a condesator 22uF between this pin and GND
        analogWrite(MO::Const::PIN_LCD_CONTRAST, 80);
    }

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

    void Display::Setup_Char(uint8_t a_char, uint8_t *a_matrix)
    {
        the_lcd.createChar(a_char, a_matrix);
    }

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

    void Display::Write(uint8_t a_x, uint8_t a_y, const char *a_format, ...)
    {
        va_list vl;
        va_start(vl, a_format);
        write(a_x, a_y, a_format, vl);
        va_end(vl);
    }

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

    void Display::Write(uint8_t a_y, const char *a_format, ...)
    {
        va_list vl;
        va_start(vl, a_format);
        write(0, a_y, a_format, vl);
        va_end(vl);
    }

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

    void Display::write(uint8_t a_x, uint8_t a_y, const char *a_format, va_list &a_vl)
    {
        if (a_y >= MAX_LINES)
            return;

        int written = vsnprintf(the_buf, BUF_SIZE, a_format, a_vl);

        if (written >= 0) // even if we don't write chars - we still clean the line
        {
            // fill up the rest with spaces
            for (int i = written; i < MAX_CHARS; ++i)
                the_buf[i] = ' ';
            the_buf[MAX_CHARS] = 0;
        }
        else
        {
            memset(the_buf, 0, BUF_SIZE);
        }

        if (strcmp(the_buf, the_old_line[a_y]) != 0)
        {
            the_lcd.setCursor(0, a_y);
            the_lcd.print(the_buf);
            memcpy(the_old_line[a_y], the_buf, BUF_SIZE);
        }
    }
}

<|endoftext|>


<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGState.cpp
 Author:       Jon Berndt
 Date started: 11/17/98
 Called by:    FGFDMExec and accessed by all models.

 ------------- Copyright (C) 1999  Jon S. Berndt (jsb@hal-pc.org) -------------

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

 This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
See header file.

HISTORY
--------------------------------------------------------------------------------
11/17/98   JSB   Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <cmath>

#include "FGState.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGState.cpp,v 1.12 2009/02/05 04:59:53 jberndt Exp $";
static const char *IdHdr = ID_STATE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MACROS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGState::FGState(FGFDMExec* fdex)
{
  FDMExec = fdex;

  sim_time = 0.0;
  //dt = 1.0/120.0;

  Aircraft     = FDMExec->GetAircraft();
  Propagate    = FDMExec->GetPropagate();
  Auxiliary    = FDMExec->GetAuxiliary();
  FCS          = FDMExec->GetFCS();
  Atmosphere   = FDMExec->GetAtmosphere();
  Aerodynamics = FDMExec->GetAerodynamics();
  GroundReactions = FDMExec->GetGroundReactions();
  Propulsion      = FDMExec->GetPropulsion();
  PropertyManager = FDMExec->GetPropertyManager();

  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGState::~FGState()
{
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGState::Initialize(FGInitialCondition *FGIC)
{
  sim_time = 0.0;

  Propagate->SetInitialState( FGIC );

  Atmosphere->Run();
  Atmosphere->SetWindNED( FGIC->GetWindNFpsIC(),
                          FGIC->GetWindEFpsIC(),
                          FGIC->GetWindDFpsIC() );

  FGColumnVector3 vAeroUVW;
  vAeroUVW = Propagate->GetUVW() + Propagate->GetTl2b()*Atmosphere->GetTotalWindNED();

  double alpha, beta;
  if (vAeroUVW(eW) != 0.0)
    alpha = vAeroUVW(eU)*vAeroUVW(eU) > 0.0 ? atan2(vAeroUVW(eW), vAeroUVW(eU)) : 0.0;
  else
    alpha = 0.0;
  if (vAeroUVW(eV) != 0.0)
    beta = vAeroUVW(eU)*vAeroUVW(eU)+vAeroUVW(eW)*vAeroUVW(eW) > 0.0 ? atan2(vAeroUVW(eV), (fabs(vAeroUVW(eU))/vAeroUVW(eU))*sqrt(vAeroUVW(eU)*vAeroUVW(eU) + vAeroUVW(eW)*vAeroUVW(eW))) : 0.0;
  else
    beta = 0.0;

  Auxiliary->SetAB(alpha, beta);

  double Vt = vAeroUVW.Magnitude();
  Auxiliary->SetVt(Vt);

  Auxiliary->SetMach(Vt/Atmosphere->GetSoundSpeed());

  double qbar = 0.5*Vt*Vt*Atmosphere->GetDensity();
  Auxiliary->Setqbar(qbar);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGState::bind(void)
{
  PropertyManager->Tie("sim-time-sec", this, &FGState::Getsim_time);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGState::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGState" << endl;
    if (from == 1) cout << "Destroyed:    FGState" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<commit_msg>Fixed a nasty error where the time step size (FGState::dt) was set to 0.0 when running JSBSim Standalone without a script<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGState.cpp
 Author:       Jon Berndt
 Date started: 11/17/98
 Called by:    FGFDMExec and accessed by all models.

 ------------- Copyright (C) 1999  Jon S. Berndt (jsb@hal-pc.org) -------------

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

 This program 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 program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
See header file.

HISTORY
--------------------------------------------------------------------------------
11/17/98   JSB   Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <cmath>

#include "FGState.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGState.cpp,v 1.13 2009/07/01 11:59:30 jberndt Exp $";
static const char *IdHdr = ID_STATE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MACROS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGState::FGState(FGFDMExec* fdex)
{
  FDMExec = fdex;

  sim_time = 0.0;
  dt = 1.0/120.0; // a default timestep size. This is needed for when JSBSim is
                  // run in standalone mode with no initialization file.

  Aircraft     = FDMExec->GetAircraft();
  Propagate    = FDMExec->GetPropagate();
  Auxiliary    = FDMExec->GetAuxiliary();
  FCS          = FDMExec->GetFCS();
  Atmosphere   = FDMExec->GetAtmosphere();
  Aerodynamics = FDMExec->GetAerodynamics();
  GroundReactions = FDMExec->GetGroundReactions();
  Propulsion      = FDMExec->GetPropulsion();
  PropertyManager = FDMExec->GetPropertyManager();

  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGState::~FGState()
{
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGState::Initialize(FGInitialCondition *FGIC)
{
  sim_time = 0.0;

  Propagate->SetInitialState( FGIC );

  Atmosphere->Run();
  Atmosphere->SetWindNED( FGIC->GetWindNFpsIC(),
                          FGIC->GetWindEFpsIC(),
                          FGIC->GetWindDFpsIC() );

  FGColumnVector3 vAeroUVW;
  vAeroUVW = Propagate->GetUVW() + Propagate->GetTl2b()*Atmosphere->GetTotalWindNED();

  double alpha, beta;
  if (vAeroUVW(eW) != 0.0)
    alpha = vAeroUVW(eU)*vAeroUVW(eU) > 0.0 ? atan2(vAeroUVW(eW), vAeroUVW(eU)) : 0.0;
  else
    alpha = 0.0;
  if (vAeroUVW(eV) != 0.0)
    beta = vAeroUVW(eU)*vAeroUVW(eU)+vAeroUVW(eW)*vAeroUVW(eW) > 0.0 ? atan2(vAeroUVW(eV), (fabs(vAeroUVW(eU))/vAeroUVW(eU))*sqrt(vAeroUVW(eU)*vAeroUVW(eU) + vAeroUVW(eW)*vAeroUVW(eW))) : 0.0;
  else
    beta = 0.0;

  Auxiliary->SetAB(alpha, beta);

  double Vt = vAeroUVW.Magnitude();
  Auxiliary->SetVt(Vt);

  Auxiliary->SetMach(Vt/Atmosphere->GetSoundSpeed());

  double qbar = 0.5*Vt*Vt*Atmosphere->GetDensity();
  Auxiliary->Setqbar(qbar);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGState::bind(void)
{
  PropertyManager->Tie("sim-time-sec", this, &FGState::Getsim_time);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGState::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGState" << endl;
    if (from == 1) cout << "Destroyed:    FGState" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<|endoftext|>


<commit_before>#pragma once

#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include <GL/glew.h>

#include <SDL_image.h>
#include <SDL_ttf.h>

#if defined (__linux__) && defined (__INSTALL)
#define PATH std::string("/usr/share/Labirintus/")
#else
#define PATH
#endif

/*

According to http://www.opengl-tutorial.org/

*/
GLuint loadShader(GLenum _shaderType, const char* _fileName)
{
	GLuint loadedShader = glCreateShader( _shaderType );

	if ( loadedShader == 0 )
	{
		fprintf(stderr, "Error while initalizing %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string shaderCode = "";

	std::ifstream shaderStream(_fileName);

	if ( !shaderStream.is_open() )
	{
		fprintf(stderr, "Error while loading %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string line = "";
	while ( std::getline(shaderStream, line) )
	{
		shaderCode += line + "\n";
	}

	shaderStream.close();

	const char* sourcePointer = shaderCode.c_str();
	glShaderSource( loadedShader, 1, &sourcePointer, NULL );

	glCompileShader( loadedShader );

	GLint result = GL_FALSE;
    int infoLogLength;

	glGetShaderiv(loadedShader, GL_COMPILE_STATUS, &result);
	glGetShaderiv(loadedShader, GL_INFO_LOG_LENGTH, &infoLogLength);

	if ( GL_FALSE == result )
	{
		std::vector<char> VertexShaderErrorMessage(infoLogLength);
		glGetShaderInfoLog(loadedShader, infoLogLength, NULL, &VertexShaderErrorMessage[0]);

		fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
	}

	return loadedShader;
}

GLuint loadProgramVSGSFS(const char* _fileNameVS, const char* _fileNameGS, const char* _fileNameFS)
{
	GLuint vs_ID = loadShader(GL_VERTEX_SHADER,		_fileNameVS);
	GLuint gs_ID = loadShader(GL_GEOMETRY_SHADER,	_fileNameGS);
	GLuint fs_ID = loadShader(GL_FRAGMENT_SHADER,	_fileNameFS);

	if ( vs_ID == 0 || gs_ID == 0 || fs_ID == 0 )
	{
		return 0;
	}

	GLuint program_ID = glCreateProgram();

	fprintf(stdout, "Linking program\n");
	glAttachShader(program_ID, vs_ID);
	glAttachShader(program_ID, gs_ID);
	glAttachShader(program_ID, fs_ID);

	glLinkProgram(program_ID);

	GLint infoLogLength = 0, result = 0;

	glGetProgramiv(program_ID, GL_LINK_STATUS, &result);
	glGetProgramiv(program_ID, GL_INFO_LOG_LENGTH, &infoLogLength);
	if ( GL_FALSE == result)
	{
		std::vector<char> ProgramErrorMessage( infoLogLength );
		glGetProgramInfoLog(program_ID, infoLogLength, NULL, &ProgramErrorMessage[0]);
		fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
	}

	glDeleteShader( vs_ID );
	glDeleteShader( gs_ID );
	glDeleteShader( fs_ID );

	return program_ID;
}

GLuint TextureFromFile(const std::string& filename)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}
	// TODO: fix this (can't be determined compile time)
	#if SDL_BYTEORDER == SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}

GLuint PointtableFromFile(const std::string& filename, int coins, int diamonds)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}

	#if SDL_BYTEORDER != SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

	std::string fontfile = PATH+"textures/font.ttf";
	TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 50);
	SDL_Surface* text1 = TTF_RenderText_Solid(font, std::to_string(coins).c_str(), {0,0,0});
	SDL_Surface* text2 = TTF_RenderText_Solid(font, std::to_string(diamonds).c_str(), {0,0,0});

	SDL_Rect renderQuad = { 100, 17, 40, 40 };
	SDL_BlitSurface(text1, 0, loaded_img, &renderQuad);
	renderQuad = { 100, 77, 40, 40 };
	SDL_BlitSurface(text2, 0, loaded_img, &renderQuad);

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}
<commit_msg>Minor change in filepath<commit_after>#pragma once

#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include <GL/glew.h>

#include <SDL_image.h>
#include <SDL_ttf.h>

#if defined (__linux__) && defined (__INSTALL)
#define PATH std::string("/usr/share/labirintus/")
#else
#define PATH
#endif

/*

According to http://www.opengl-tutorial.org/

*/
GLuint loadShader(GLenum _shaderType, const char* _fileName)
{
	GLuint loadedShader = glCreateShader( _shaderType );

	if ( loadedShader == 0 )
	{
		fprintf(stderr, "Error while initalizing %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string shaderCode = "";

	std::ifstream shaderStream(_fileName);

	if ( !shaderStream.is_open() )
	{
		fprintf(stderr, "Error while loading %s shader (glCreateShader)!", _fileName);
		return 0;
	}

	std::string line = "";
	while ( std::getline(shaderStream, line) )
	{
		shaderCode += line + "\n";
	}

	shaderStream.close();

	const char* sourcePointer = shaderCode.c_str();
	glShaderSource( loadedShader, 1, &sourcePointer, NULL );

	glCompileShader( loadedShader );

	GLint result = GL_FALSE;
    int infoLogLength;

	glGetShaderiv(loadedShader, GL_COMPILE_STATUS, &result);
	glGetShaderiv(loadedShader, GL_INFO_LOG_LENGTH, &infoLogLength);

	if ( GL_FALSE == result )
	{
		std::vector<char> VertexShaderErrorMessage(infoLogLength);
		glGetShaderInfoLog(loadedShader, infoLogLength, NULL, &VertexShaderErrorMessage[0]);

		fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
	}

	return loadedShader;
}

GLuint loadProgramVSGSFS(const char* _fileNameVS, const char* _fileNameGS, const char* _fileNameFS)
{
	GLuint vs_ID = loadShader(GL_VERTEX_SHADER,		_fileNameVS);
	GLuint gs_ID = loadShader(GL_GEOMETRY_SHADER,	_fileNameGS);
	GLuint fs_ID = loadShader(GL_FRAGMENT_SHADER,	_fileNameFS);

	if ( vs_ID == 0 || gs_ID == 0 || fs_ID == 0 )
	{
		return 0;
	}

	GLuint program_ID = glCreateProgram();

	fprintf(stdout, "Linking program\n");
	glAttachShader(program_ID, vs_ID);
	glAttachShader(program_ID, gs_ID);
	glAttachShader(program_ID, fs_ID);

	glLinkProgram(program_ID);

	GLint infoLogLength = 0, result = 0;

	glGetProgramiv(program_ID, GL_LINK_STATUS, &result);
	glGetProgramiv(program_ID, GL_INFO_LOG_LENGTH, &infoLogLength);
	if ( GL_FALSE == result)
	{
		std::vector<char> ProgramErrorMessage( infoLogLength );
		glGetProgramInfoLog(program_ID, infoLogLength, NULL, &ProgramErrorMessage[0]);
		fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
	}

	glDeleteShader( vs_ID );
	glDeleteShader( gs_ID );
	glDeleteShader( fs_ID );

	return program_ID;
}

GLuint TextureFromFile(const std::string& filename)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}
	// TODO: fix this (can't be determined compile time)
	#if SDL_BYTEORDER == SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}

GLuint PointtableFromFile(const std::string& filename, int coins, int diamonds)
{
	SDL_Surface* loaded_img = IMG_Load(filename.c_str());

	int img_mode = 0;

	if ( loaded_img == 0 )
	{
		std::cout << "[TextureFromFile] Error while loading image: " << filename << std::endl;
		return 0;
	}

	#if SDL_BYTEORDER != SDL_LIL_ENDIAN
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_BGRA;
		else
			img_mode = GL_BGR;
	#else
		if ( loaded_img->format->BytesPerPixel == 4 )
			img_mode = GL_RGBA;
		else
			img_mode = GL_RGB;
	#endif

	std::string fontfile = PATH+"textures/font.ttf";
	TTF_Font* font = TTF_OpenFont(fontfile.c_str(), 50);
	SDL_Surface* text1 = TTF_RenderText_Solid(font, std::to_string(coins).c_str(), {0,0,0});
	SDL_Surface* text2 = TTF_RenderText_Solid(font, std::to_string(diamonds).c_str(), {0,0,0});

	SDL_Rect renderQuad = { 100, 17, 40, 40 };
	SDL_BlitSurface(text1, 0, loaded_img, &renderQuad);
	renderQuad = { 100, 77, 40, 40 };
	SDL_BlitSurface(text2, 0, loaded_img, &renderQuad);

    GLuint tex;
    glGenTextures(1, &tex);

    glBindTexture(GL_TEXTURE_2D, tex);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, loaded_img->w, loaded_img->h, img_mode, GL_UNSIGNED_BYTE, loaded_img->pixels);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	SDL_FreeSurface( loaded_img );

    return tex;
}
<|endoftext|>


<commit_before>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// 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.

#ifndef GUID_HPP_
#define GUID_HPP_

#include <dds_dcps.h>

#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

// TODO(ross-desmond): This should all be in opensplice
typedef char octet;

/**
 * Structure to hold GUID information for DDS instances.
 * http://www.eprosima.com/docs/fast-rtps/1.6.0/html/_guid_8h_source.html
 *
 */
struct GuidPrefix_t
{
  static constexpr unsigned int kSize = 12;
  octet value[kSize];

  GuidPrefix_t()
  {
    memset(value, 0, kSize);
  }

  explicit GuidPrefix_t(octet guid[kSize])
  {
    memcpy(value, guid, kSize);
  }

  GuidPrefix_t(const GuidPrefix_t & g)
  {
    memcpy(value, g.value, kSize);
  }

  GuidPrefix_t(GuidPrefix_t && g)
  {
    memmove(value, g.value, kSize);
  }

  GuidPrefix_t & operator=(const GuidPrefix_t & guidpre)
  {
    memcpy(value, guidpre.value, kSize);
    return *this;
  }

  GuidPrefix_t & operator=(GuidPrefix_t && guidpre)
  {
    memmove(value, guidpre.value, kSize);
    return *this;
  }

#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC

  bool operator==(const GuidPrefix_t & prefix) const
  {
    return memcmp(value, prefix.value, kSize) == 0;
  }

  bool operator!=(const GuidPrefix_t & prefix) const
  {
    return memcmp(value, prefix.value, kSize) != 0;
  }

#endif
};

inline bool operator<(const GuidPrefix_t & g1, const GuidPrefix_t & g2)
{
  for (uint8_t i = 0; i < GuidPrefix_t::kSize; ++i) {
    if (g1.value[i] < g2.value[i]) {
      return true;
    } else if (g1.value[i] > g2.value[i]) {
      return false;
    }
  }
  return false;
}

inline std::ostream & operator<<(std::ostream & output, const GuidPrefix_t & guiP)
{
  output << std::hex;
  for (uint8_t i = 0; i < GuidPrefix_t::kSize - 1; ++i) {
    output << static_cast<int>(guiP.value[i]) << ".";
  }
  output << static_cast<int>(guiP.value[GuidPrefix_t::kSize - 1]);
  return output << std::dec;
}

// TODO(ross-desmond): check this with opensplice source code to ensure compatibility
/**
 * Convert an instance handle to a guid.
 *
 * @param guid [out] the resulting guid
 * @param domain_id to prepend to the guid
 * @param instance_handle to append to the guid
 */
inline void DDS_InstanceHandle_to_GUID(
  struct GuidPrefix_t * guid,
  DDS::DomainId_t domain_id,
  DDS::InstanceHandle_t instance_handle)
{
  memcpy(guid->value, reinterpret_cast<char *>(&domain_id), sizeof(DDS::DomainId_t));
  memcpy(guid->value + sizeof(DDS::DomainId_t),
    reinterpret_cast<char *>(&instance_handle), sizeof(DDS::InstanceHandle_t));
}

inline void DDS_BuiltinTopicKey_to_GUID(
  struct GuidPrefix_t * guid,
  DDS::BuiltinTopicKey_t buitinTopicKey)
{
#if BIG_ENDIAN
  /* Big Endian */
  memcpy(guid->value, reinterpret_cast<octet *>(buitinTopicKey), GuidPrefix_t::kSize);
#else
  /* Little Endian */
  int i;
  octet * guidElement;
  octet * topicKeyBuffer = reinterpret_cast<octet *>(buitinTopicKey);
  octet * keyBufferElement;
  for (i = 0; i < 3; ++i) {
    octet * guidElement = &guid->value[i * 3];
    octet * keyBufferElement = reinterpret_cast<octet *>(&buitinTopicKey[i * 3]);
    guidElement[0] = keyBufferElement[2];
    guidElement[1] = keyBufferElement[1];
    guidElement[2] = keyBufferElement[0];
  }

#endif
}

#endif  // GUID_HPP_
<commit_msg>fix compiler warnings on Windows introduced in #251 (#252)<commit_after>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// 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.

#ifndef GUID_HPP_
#define GUID_HPP_

#include <dds_dcps.h>

#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

// TODO(ross-desmond): This should all be in opensplice
typedef char octet;

/**
 * Structure to hold GUID information for DDS instances.
 * http://www.eprosima.com/docs/fast-rtps/1.6.0/html/_guid_8h_source.html
 *
 */
struct GuidPrefix_t
{
  static constexpr unsigned int kSize = 12;
  octet value[kSize];

  GuidPrefix_t()
  {
    memset(value, 0, kSize);
  }

  explicit GuidPrefix_t(octet guid[kSize])
  {
    memcpy(value, guid, kSize);
  }

  GuidPrefix_t(const GuidPrefix_t & g)
  {
    memcpy(value, g.value, kSize);
  }

  GuidPrefix_t(GuidPrefix_t && g)
  {
    memmove(value, g.value, kSize);
  }

  GuidPrefix_t & operator=(const GuidPrefix_t & guidpre)
  {
    memcpy(value, guidpre.value, kSize);
    return *this;
  }

  GuidPrefix_t & operator=(GuidPrefix_t && guidpre)
  {
    memmove(value, guidpre.value, kSize);
    return *this;
  }

#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC

  bool operator==(const GuidPrefix_t & prefix) const
  {
    return memcmp(value, prefix.value, kSize) == 0;
  }

  bool operator!=(const GuidPrefix_t & prefix) const
  {
    return memcmp(value, prefix.value, kSize) != 0;
  }

#endif
};

inline bool operator<(const GuidPrefix_t & g1, const GuidPrefix_t & g2)
{
  for (uint8_t i = 0; i < GuidPrefix_t::kSize; ++i) {
    if (g1.value[i] < g2.value[i]) {
      return true;
    } else if (g1.value[i] > g2.value[i]) {
      return false;
    }
  }
  return false;
}

inline std::ostream & operator<<(std::ostream & output, const GuidPrefix_t & guiP)
{
  output << std::hex;
  for (uint8_t i = 0; i < GuidPrefix_t::kSize - 1; ++i) {
    output << static_cast<int>(guiP.value[i]) << ".";
  }
  output << static_cast<int>(guiP.value[GuidPrefix_t::kSize - 1]);
  return output << std::dec;
}

// TODO(ross-desmond): check this with opensplice source code to ensure compatibility
/**
 * Convert an instance handle to a guid.
 *
 * @param guid [out] the resulting guid
 * @param domain_id to prepend to the guid
 * @param instance_handle to append to the guid
 */
inline void DDS_InstanceHandle_to_GUID(
  struct GuidPrefix_t * guid,
  DDS::DomainId_t domain_id,
  DDS::InstanceHandle_t instance_handle)
{
  memcpy(guid->value, reinterpret_cast<char *>(&domain_id), sizeof(DDS::DomainId_t));
  memcpy(guid->value + sizeof(DDS::DomainId_t),
    reinterpret_cast<char *>(&instance_handle), sizeof(DDS::InstanceHandle_t));
}

inline void DDS_BuiltinTopicKey_to_GUID(
  struct GuidPrefix_t * guid,
  DDS::BuiltinTopicKey_t buitinTopicKey)
{
#if BIG_ENDIAN
  /* Big Endian */
  memcpy(guid->value, reinterpret_cast<octet *>(buitinTopicKey), GuidPrefix_t::kSize);
#else
  /* Little Endian */
  int i;
  octet * topicKeyBuffer = reinterpret_cast<octet *>(buitinTopicKey);
  for (i = 0; i < 3; ++i) {
    octet * guidElement = &guid->value[i * 3];
    octet * keyBufferElement = reinterpret_cast<octet *>(&buitinTopicKey[i * 3]);
    guidElement[0] = keyBufferElement[2];
    guidElement[1] = keyBufferElement[1];
    guidElement[2] = keyBufferElement[0];
  }

#endif
}

#endif  // GUID_HPP_
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
char russian_letters[6];
size_t russianLetterI(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
	if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
	else {
		if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
			return 7;
		}
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
}
size_t russianLetterI2(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
	if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
	else {
		if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
			return 7;
		}
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
}
size_t letterI(const char letter, const bool is_capital) {
        int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
	size_t result = static_cast<int>(letter) - first_letter_code + 1;
}
struct person {
	std::string surname;
	std::string name;
	size_t year;
	size_t i(size_t sort_i) const {
		if (sort_i < surname.length()) {
			return letterI(surname[sort_i], sort_i == 0);
		}
		else {
			return 0;
		}
	}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
	output << _person.surname << " ";
	output << _person.name << " ";
	output << _person.year;
	return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
	input >> _person.surname;
	input >> _person.name;
	input >> _person.year;
	return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	bool is_empty;
	size_t file_size;
	std::fstream stream;
	void openNew(std::string _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
	void addToSize(person _person) {
		file_size += _person.surname.size();
		file_size += _person.name.size();
		file_size += sizeof(_person.year);
		file_size += 1 + 1 + 2;
	}
};
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_file_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
		: database_file_name(database_file_name),
		database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount * 1024 * 1024),
		is_database_empty(true)
	{
		vault_file_name = "F:\\1\\temp_files\\";
	}
	void sortDatabase() {
		sortFile(database_file, database_file_name, RAM_amount + 1, 0);
	}

	~Database_Sorter() {
		database_file.close();
		output_file.close();
	}
private:
	void outputFile(std::ifstream & file) {
		while(!file.eof()){
			person _person;
			file >> _person;
			output_file << _person;
		}
	}
	void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {
			RAMsort(file, sort_i);
		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (persons_files[i].file_size != 0) {
					std::ifstream temp_file(persons_files[i].file_name);
					sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					temp_file.close();
				}
			}
		}
	}

	void RAMsort(std::ifstream & file, size_t sort_i) {
		persons_outputted = 0;
		persons.clear();
		readFileIntoRAM(file);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::ifstream & file) {
		while (!file.eof()) {
			person current_person;
			file >> current_person;
			persons.push_back(current_person);
		}
	}
	void sortPersons(Persons const & entered_persons, size_t sort_i) {
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
		if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
			outputBucket(entered_persons, output_file);
		}
		else {
			sortBuckets(buckets, sort_i + 1);
		}
	}
	Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
		Buckets buckets(34);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			buckets[currentI].push_back(person);
		}
		return buckets;
	}
	bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
		size_t first_bucket_i = persons[0].i(sort_i);
		return buckets[first_bucket_i].size() == persons.size();
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person;
		persons_outputted++;
	}
	void sortBuckets(Buckets const & buckets, size_t sort_i) {
		for (auto bucket : buckets) {
			if (!bucket.empty()) {
				sortPersons(bucket, sort_i);
			}
		}
	}

	std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
		std::vector<Persons_File> files = createDerivedFiles(base_file_name);
		while (!base_file.eof()) {
			person current_person;
			base_file >> current_person;
			size_t currentI = current_person.i(sort_i);
			if (files[currentI].is_empty) {
				files[currentI].is_empty = false;
			}
			else {
				files[currentI].stream << std::endl;
			}
			files[currentI].stream << current_person;
			files[currentI].addToSize(current_person);
		}
		for (size_t i = 0; i < files.size(); i++) {
			files[i].stream.close();
		}
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
		std::vector<Persons_File> files(34);
		for (size_t i = 0; i < files.size(); i++) {
			std::stringstream string_stream;
			std::string str;
			if (base_file_name == database_file_name) {
				string_stream << vault_file_name << i << ".txt";
			}
			else {
				string_stream << base_file_name << "_" << i << ".txt";
			}
			string_stream >> str;
			files[i].openNew(str);
		}
		return files;
	}
	std::vector<person> persons;
	size_t persons_outputted;
	std::ifstream database_file;
	std::ofstream output_file;
	size_t RAM_amount;
};
<commit_msg>Update Database_Sorter.hpp<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <vector>
char russian_letters[6];
size_t russianLetterI(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
	if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
	else {
		if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
			return 7;
		}
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
}
size_t russianLetterI2(const char letter, const bool is_capital) {
	int first_letter_code = static_cast<int>(is_capital ? russian_letters[0] : russian_letters[1]);
	if (letter > (is_capital ? russian_letters[2] : russian_letters[3])) {
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
	else {
		if (letter == (is_capital ? russian_letters[4] : russian_letters[5])) {
			return 7;
		}
		size_t result = static_cast<int>(letter) - first_letter_code + 2;
		return result;
	}
}
size_t letterI(const char letter, const bool is_capital) {
        int first_letter_code = static_cast<int>(is_capital ? 'A' : 'a');
	size_t result = static_cast<int>(letter) - first_letter_code + 1;
}
struct person {
	std::string surname;
	std::string name;
	size_t year;
	size_t i(size_t sort_i) const {
		if (sort_i < surname.length()) {
			return letterI(surname[sort_i], sort_i == 0);
		}
		else {
			return 0;
		}
	}
};
std::ostream & operator<<(std::ostream & output, person const & _person)
{
	output << _person.surname << " ";
	output << _person.name << " ";
	output << _person.year;
	return output;
}
std::istream & operator>>(std::istream & input, person & _person)
{
	input >> _person.surname;
	input >> _person.name;
	input >> _person.year;
	return input;
}
using Buckets = std::vector<std::vector<person>>;
using Persons = std::vector<person>;
class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	bool is_empty;
	size_t file_size;
	std::fstream stream;
	void openNew(std::string _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
	void addToSize(person _person) {
		file_size += _person.surname.size();
		file_size += _person.name.size();
		file_size += sizeof(_person.year);
		file_size += 1 + 1 + 2;
	}
};
using Output_Files = std::vector<std::ofstream>;

class Database_Sorter {
	bool is_database_empty;
	std::string database_file_name;
	std::string vault_file_name;
public:
	Database_Sorter(std::string database_file_name, std::string output_file_name, size_t _RAM_amount)
		: database_file_name(database_file_name),
		database_file(database_file_name),
		output_file(output_file_name),
		RAM_amount(_RAM_amount * 1024 * 1024),
		is_database_empty(true)
	{
		vault_file_name = "F:\\1\\temp_files\\";
	}
	void sortDatabase() {
		sortFile(database_file, database_file_name, RAM_amount + 1, 0);
	}

	~Database_Sorter() {
		database_file.close();
		output_file.close();
	}
private:
	void outputFile(std::ifstream & file) {
		while(!file.eof()){
			person _person;
			file >> _person;
			output_file << _person;
		}
	}
	void sortFile(std::ifstream & file, std::string file_name, size_t file_size, size_t sort_i) {
		if (file_size < RAM_amount) {
			RAMsort(file, sort_i);
		}
		else {
			std::vector<Persons_File> persons_files = stuffPersonsToFiles(file, file_name, sort_i);
			for (size_t i = 0; i < persons_files.size(); i++) {
				if (persons_files[i].file_size != 0) {
					if (file_size == persons_files[i].file_size){
						outputFile(file);
					} else{

					std::ifstream temp_file(persons_files[i].file_name);
					sortFile(temp_file, persons_files[i].file_name, persons_files[i].file_size, sort_i + 1);
					temp_file.close();
					}
				}
			}
		}
	}

	void RAMsort(std::ifstream & file, size_t sort_i) {
		persons_outputted = 0;
		persons.clear();
		readFileIntoRAM(file);
		sortPersons(persons, sort_i);
	}
	void readFileIntoRAM(std::ifstream & file) {
		while (!file.eof()) {
			person current_person;
			file >> current_person;
			persons.push_back(current_person);
		}
	}
	void sortPersons(Persons const & entered_persons, size_t sort_i) {
		Buckets buckets = stuffPersonsToBuckets(entered_persons, sort_i);
		if (isOnlyOneBucketFull(buckets, entered_persons, sort_i)) {
			outputBucket(entered_persons, output_file);
		}
		else {
			sortBuckets(buckets, sort_i + 1);
		}
	}
	Buckets stuffPersonsToBuckets(Persons const & persons, size_t sort_i) {
		Buckets buckets(34);
		for (auto person : persons) {
			size_t currentI = person.i(sort_i);
			buckets[currentI].push_back(person);
		}
		return buckets;
	}
	bool isOnlyOneBucketFull(Buckets const & buckets, Persons const & persons, size_t sort_i) {
		size_t first_bucket_i = persons[0].i(sort_i);
		return buckets[first_bucket_i].size() == persons.size();
	}
	void outputBucket(Persons const & bucket, std::ofstream & sorted_persons_file) {
		for (auto person : bucket) {
			outputPerson(person);
		}
	}
	void outputPerson(person _person) {
		if (is_database_empty) {
			is_database_empty = false;
		}
		else {
			output_file << std::endl;
		}
		output_file << _person;
		persons_outputted++;
	}
	void sortBuckets(Buckets const & buckets, size_t sort_i) {
		for (auto bucket : buckets) {
			if (!bucket.empty()) {
				sortPersons(bucket, sort_i);
			}
		}
	}

	std::vector<Persons_File> stuffPersonsToFiles(std::ifstream & base_file, std::string base_file_name, size_t sort_i) {
		std::vector<Persons_File> files = createDerivedFiles(base_file_name);
		while (!base_file.eof()) {
			person current_person;
			base_file >> current_person;
			size_t currentI = current_person.i(sort_i);
			if (files[currentI].is_empty) {
				files[currentI].is_empty = false;
			}
			else {
				files[currentI].stream << std::endl;
			}
			files[currentI].stream << current_person;
			files[currentI].addToSize(current_person);
		}
		for (size_t i = 0; i < files.size(); i++) {
			files[i].stream.close();
		}
		return files;
	}
	std::vector<Persons_File> createDerivedFiles(std::string base_file_name) {
		std::vector<Persons_File> files(34);
		for (size_t i = 0; i < files.size(); i++) {
			std::stringstream string_stream;
			std::string str;
			if (base_file_name == database_file_name) {
				string_stream << vault_file_name << i << ".txt";
			}
			else {
				string_stream << base_file_name << "_" << i << ".txt";
			}
			string_stream >> str;
			files[i].openNew(str);
		}
		return files;
	}
	std::vector<person> persons;
	size_t persons_outputted;
	std::ifstream database_file;
	std::ofstream output_file;
	size_t RAM_amount;
};
<|endoftext|>