<commit_before>/*************************************************************************
 *
 *  $RCSfile: objectmenucontroller.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:30:02 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
#include <helper/popupmenucontrollerbase.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

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

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_VERBDESCRIPTOR_HPP_
#include <com/sun/star/embed/VerbDescriptor.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

namespace framework
{
    class ObjectMenuController :  public PopupMenuControllerBase
    {
        public:
            ObjectMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
            virtual ~ObjectMenuController();

            // XServiceInfo
            DECLARE_XSERVICEINFO

            // XPopupMenuController
            virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException);

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XStatusListener
            virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

            // XMenuListener
            virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);

            // XEventListener
            virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        private:
            void fillPopupMenu( const com::sun::star::uno::Sequence< com::sun::star::embed::VerbDescriptor >& rVerbCommandSeq, com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );

            com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >  m_xObjectUpdateDispatch;
    };
}

#endif // __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.128); FILE MERGED 2005/09/05 13:05:33 rt 1.4.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: objectmenucontroller.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:45:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
#include <helper/popupmenucontrollerbase.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

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

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_VERBDESCRIPTOR_HPP_
#include <com/sun/star/embed/VerbDescriptor.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

namespace framework
{
    class ObjectMenuController :  public PopupMenuControllerBase
    {
        public:
            ObjectMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
            virtual ~ObjectMenuController();

            // XServiceInfo
            DECLARE_XSERVICEINFO

            // XPopupMenuController
            virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException);

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XStatusListener
            virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

            // XMenuListener
            virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);

            // XEventListener
            virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        private:
            void fillPopupMenu( const com::sun::star::uno::Sequence< com::sun::star::embed::VerbDescriptor >& rVerbCommandSeq, com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );

            com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >  m_xObjectUpdateDispatch;
    };
}

#endif // __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
<|endoftext|>


<commit_before>/*
    CsoundPerformanceSettings.cpp:
    Copyright (C) 2006 Istvan Varga

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

    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
*/

#include "CsoundGUI.hpp"
using namespace std;

CsoundPerformanceSettings::CsoundPerformanceSettings()
{
    orcName = "";
    scoName = "";
    soundFileType = "wav";
    soundSampleFormat = "short";
    enablePeakChunks = true;
    displayMode = 1;
    deferGEN1 = false;
    bufFrames_SW = 1024;
    nBuffers = 4;
    midiInFileName = "";
    midiOutFileName = "";
    midiInDevName = "";
    midiOutDevName = "";
    terminateOnMidi = false;
    heartBeatMode = 0;
    rewriteHeader = false;
    inputFileName = "";
    outputFileName = "dac";
    enableSoundOutput = true;
    beatModeTempo = -1.0;
    iTimeOnly = false;
    sampleRateOverride = -1.0;
    controlRateOverride = -1.0;
    lineInput = "";
    messageLevel = 231;
    enableExpressionOpt = false;
    sadirPath = "";
    ssdirPath = "";
    sfdirPath = "";
    incdirPath = "";
    csdocdirPath = "";
    for (int i = 0; i < 10; i++)
      strsets[i] = "";
    verbose = false;
    enableDither = false;
    pluginLibs = "";
    sndidArtist = "";
    sndidComment = "";
    sndidCopyright = "";
    sndidDate = "";
    sndidSoftware = "";
    sndidTitle = "";
    ignoreCSDOptions = true;
    jackClientName = "";
    jackInPortName = "";
    jackOutPortName = "";
    maxStrLen = 255;
    midiFileMuteTracks = "";
    midiKeyMidi = -1;
    midiKeyCps = -1;
    midiKeyOct = -1;
    midiKeyPch = -1;
    midiVelMidi = -1;
    midiVelAmp = -1;
    rawControllerMode = false;
    rtAudioModule = "PortAudio";
    rtAudioOutputDevice = "dac";
    rtAudioInputDevice = "adc";
    rtMidiModule = "PortMidi";
    scoreOffsetSeconds = 0.0;
    useThreads = true;
    scriptFileName = "";
    additionalFlags = "";
    useAdditionalFlags = false;
}

CsoundPerformanceSettings::~CsoundPerformanceSettings()
{
}

static const char *fileTypeList[] = {
    "wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac",
    (char*) 0
};

static const char *sampleFormatList[] = {
    "alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit",
    (char*) 0
};

int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType)
{
    if (fileType == (char*) 0 || fileType[0] == (char) 0)
      return -1;
    for (int i = 0; fileTypeList[i] != (char*) 0; i++) {
      if (strcmp(fileTypeList[i], fileType) == 0)
      if (strcmp(fileTypeList[i], fileType) == 0)
        return i;
    }
    return -1;
}

const char *CsoundPerformanceSettings::indexToFileType(int fileType)
{
    if (fileType < 0 ||
        fileType >= (int) (sizeof(fileTypeList) / sizeof(char*)))
      return (char*) 0;
    return fileTypeList[fileType];
}

int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat)
{
    if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0)
      return -1;
    for (int i = 0; sampleFormatList[i] != (char*) 0; i++) {
      if (strcmp(sampleFormatList[i], sampleFormat) == 0)
        return i;
    }
    return -1;
}

const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat)
{
    if (sampleFormat < 0 ||
        sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*)))
      return (char*) 0;
    return sampleFormatList[sampleFormat];
}

static bool cmdLine_addStringOpt(vector<string>& cmdLine,
                                 const char *optName, string& value)
{
    string arg;
    int         i, pos0, pos1;

    for (pos0 = 0; pos0 < (int) value.size(); pos0++) {
      char  c = value[pos0];
      if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
        break;
    }
    for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) {
      char  c = value[pos1];
      if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
        break;
    }
    if (pos0 > pos1)
      return false;
    arg = optName;
    for (i = pos0; i <= pos1; i++)
      arg += value[i];
    cmdLine.push_back(arg);

    return true;
}

static void cmdLine_addIntegerOpt(vector<string>& cmdLine,
                                  const char *optName, int value)
{
    char    buf[64];

    sprintf(&(buf[0]), "%s%d", optName, value);
    cmdLine.push_back(&(buf[0]));
}

static void cmdLine_addDoubleOpt(vector<string>& cmdLine,
                                 const char *optName, double value)
{
    char    buf[64];

    if (!(value > -10000000.0 && value < 10000000.0))
      return;
    sprintf(&(buf[0]), "%s%g", optName, value);
    cmdLine.push_back(&(buf[0]));
}

void CsoundPerformanceSettings::buildCommandLine(vector<string>&
                                                     cmdLine,
                                                 bool forceSettings)
{
    cmdLine.clear();
    cmdLine.push_back("csound");
    if (!CsoundGUIMain::isEmptyString(soundFileType) &&
        (soundFileType != "wav" || forceSettings)) {
      string arg;
      arg = "--format=";
      arg += soundFileType;
      if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
          (soundSampleFormat != "short" || forceSettings)) {
        arg += ':';
        arg += soundSampleFormat;
      }
      cmdLine.push_back(arg);
    }
    else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
             (soundSampleFormat != "short" || forceSettings)) {
      cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat);
    }
    if (!enablePeakChunks) {
      cmdLine.push_back("-K");
    }
    if (displayMode != 1 || forceSettings) {
      switch (displayMode) {    // 0: none, 1: full, 2: ASCII, 3: PS
      case 0:
        cmdLine.push_back("-d");
        break;
      case 1:
        cmdLine.push_back("--displays");
        break;
      case 2:
        if (forceSettings)
          cmdLine.push_back("--displays");
        cmdLine.push_back("-g");
        break;
      case 3:
        if (forceSettings)
          cmdLine.push_back("--displays");
        cmdLine.push_back("-G");
        break;
      }
    }
    if (deferGEN1)
      cmdLine.push_back("-D");
    if (bufFrames_SW >= 16) {
      cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW);
      cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers);
    }
    cmdLine_addStringOpt(cmdLine, "-F", midiInFileName);
    cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName);
    cmdLine_addStringOpt(cmdLine, "-M", midiInDevName);
    cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName);
    if (terminateOnMidi)
      cmdLine.push_back("-T");
    if (heartBeatMode != 0 || forceSettings)
      cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode);
    if (rewriteHeader)
      cmdLine.push_back("-R");
    if (runRealtime)
      cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice);
    else
      cmdLine_addStringOpt(cmdLine, "-i", inputFileName);
    if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) {
      cmdLine_addStringOpt(cmdLine, "-o", outputFileName);
    }
    else if (forceSettings && !disableDiskOutput)
      cmdLine.push_back("-n");
    if (disableDiskOutput && !runRealtime)
      cmdLine.push_back("-n");
    if (beatModeTempo > 0.0)
      cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo);
    if (iTimeOnly)
      cmdLine.push_back("-I");
    if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) {
      cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride);
      cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride);
    }
    cmdLine_addStringOpt(cmdLine, "-L", lineInput);
    if (messageLevel != 135 || forceSettings)
      cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel);
    if (enableExpressionOpt)
      cmdLine.push_back("--expression-opt");
    else if (forceSettings)
      cmdLine.push_back("--no-expression-opt");
    cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath);
    cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath);
    cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath);
    cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath);
//     cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath);
    for (int i = 0; i < 10; i++) {
      if (!CsoundGUIMain::isEmptyString(strsets[i])) {
        char  buf[16];
        sprintf(&(buf[0]), "--strset%d=", i);
        cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]);
      }
    }
    if (verbose)
      cmdLine.push_back("-v");
    if (enableDither)
      cmdLine.push_back("-Z");
    cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs);
    cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist);
    cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment);
    cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright);
    cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate);
    cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware);
    cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle);
    if (ignoreCSDOptions)
      cmdLine.push_back("-+ignore_csopts=1");
    else if (forceSettings)
      cmdLine.push_back("-+ignore_csopts=0");
    cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName);
    cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName);
    cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName);
    if ((maxStrLen >= 9 && maxStrLen <= 9999) &&
        (maxStrLen != 255 || forceSettings)) {
      cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1);
    }
    if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) {
      if (forceSettings)
        cmdLine.push_back("-+mute_tracks=");
    }
    if (midiKeyMidi > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi);
    if (midiKeyCps > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps);
    if (midiKeyOct > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct);
    if (midiKeyPch > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch);
    if (midiVelMidi > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi);
    if (midiVelAmp > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp);
    if (rawControllerMode)
      cmdLine.push_back("-+raw_controller_mode=1");
    else if (forceSettings)
      cmdLine.push_back("-+raw_controller_mode=0");
    if (runRealtime)
      cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule);
    cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule);
    if (scoreOffsetSeconds > 0.0)
      cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds);
    else if (forceSettings && scoreOffsetSeconds == 0.0)
      cmdLine.push_back("-+skip_seconds=0");
    if (!CsoundGUIMain::isEmptyString(orcName)) {
      cmdLine.push_back(orcName);
      if (!CsoundGUIMain::isCSDFile(orcName) &&
          !CsoundGUIMain::isEmptyString(scoName))
        cmdLine.push_back(scoName);
    }
    if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags))
      cmdLine.push_back(additionalFlags);
}
<commit_msg>no message<commit_after>/*
    CsoundPerformanceSettings.cpp:
    Copyright (C) 2006 Istvan Varga

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

    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
*/

#include "CsoundGUI.hpp"
#include "cs_glue.h"

using namespace std;

CsoundPerformanceSettings::CsoundPerformanceSettings()
{
    orcName = "";
    scoName = "";
    soundFileType = "wav";
    soundSampleFormat = "short";
    enablePeakChunks = true;
    displayMode = 1;
    deferGEN1 = false;
    bufFrames_SW = 1024;
    nBuffers = 4;
    midiInFileName = "";
    midiOutFileName = "";
    midiInDevName = "";
    midiOutDevName = "";
    terminateOnMidi = false;
    heartBeatMode = 0;
    rewriteHeader = false;
    inputFileName = "";
    outputFileName = "dac";
    enableSoundOutput = true;
    beatModeTempo = -1.0;
    iTimeOnly = false;
    sampleRateOverride = -1.0;
    controlRateOverride = -1.0;
    lineInput = "";
    messageLevel = 231;
    enableExpressionOpt = false;
    sadirPath = "";
    ssdirPath = "";
    sfdirPath = "";
    incdirPath = "";
    csdocdirPath = "";
    for (int i = 0; i < 10; i++)
      strsets[i] = "";
    verbose = false;
    enableDither = false;
    pluginLibs = "";
    sndidArtist = "";
    sndidComment = "";
    sndidCopyright = "";
    sndidDate = "";
    sndidSoftware = "";
    sndidTitle = "";
    ignoreCSDOptions = true;
    jackClientName = "";
    jackInPortName = "";
    jackOutPortName = "";
    maxStrLen = 255;
    midiFileMuteTracks = "";
    midiKeyMidi = -1;
    midiKeyCps = -1;
    midiKeyOct = -1;
    midiKeyPch = -1;
    midiVelMidi = -1;
    midiVelAmp = -1;
    rawControllerMode = false;
    rtAudioModule = "PortAudio";
    rtAudioOutputDevice = "dac";
    rtAudioInputDevice = "adc";
    rtMidiModule = "PortMidi";
    scoreOffsetSeconds = 0.0;
    useThreads = true;
    scriptFileName = "";
    additionalFlags = "";
    useAdditionalFlags = false;
}

CsoundPerformanceSettings::~CsoundPerformanceSettings()
{
}

static const char *fileTypeList[] = {
    "wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac",
    (char*) 0
};

static const char *sampleFormatList[] = {
    "alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit",
    (char*) 0
};

int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType)
{
    if (fileType == (char*) 0 || fileType[0] == (char) 0)
      return -1;
    for (int i = 0; fileTypeList[i] != (char*) 0; i++) {
      if (strcmp(fileTypeList[i], fileType) == 0)
      if (strcmp(fileTypeList[i], fileType) == 0)
        return i;
    }
    return -1;
}

const char *CsoundPerformanceSettings::indexToFileType(int fileType)
{
    if (fileType < 0 ||
        fileType >= (int) (sizeof(fileTypeList) / sizeof(char*)))
      return (char*) 0;
    return fileTypeList[fileType];
}

int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat)
{
    if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0)
      return -1;
    for (int i = 0; sampleFormatList[i] != (char*) 0; i++) {
      if (strcmp(sampleFormatList[i], sampleFormat) == 0)
        return i;
    }
    return -1;
}

const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat)
{
    if (sampleFormat < 0 ||
        sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*)))
      return (char*) 0;
    return sampleFormatList[sampleFormat];
}

static bool cmdLine_addStringOpt(vector<string>& cmdLine,
                                 const char *optName, string& value)
{
    string arg;
    int         i, pos0, pos1;

    for (pos0 = 0; pos0 < (int) value.size(); pos0++) {
      char  c = value[pos0];
      if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
        break;
    }
    for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) {
      char  c = value[pos1];
      if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
        break;
    }
    if (pos0 > pos1)
      return false;
    arg = optName;
    for (i = pos0; i <= pos1; i++)
      arg += value[i];
    cmdLine.push_back(arg);

    return true;
}

static void cmdLine_addIntegerOpt(vector<string>& cmdLine,
                                  const char *optName, int value)
{
    char    buf[64];

    sprintf(&(buf[0]), "%s%d", optName, value);
    cmdLine.push_back(&(buf[0]));
}

static void cmdLine_addDoubleOpt(vector<string>& cmdLine,
                                 const char *optName, double value)
{
    char    buf[64];

    if (!(value > -10000000.0 && value < 10000000.0))
      return;
    sprintf(&(buf[0]), "%s%g", optName, value);
    cmdLine.push_back(&(buf[0]));
}

void CsoundPerformanceSettings::buildCommandLine(vector<string>&
                                                     cmdLine,
                                                 bool forceSettings)
{
    cmdLine.clear();
    cmdLine.push_back("csound");
    if (!CsoundGUIMain::isEmptyString(soundFileType) &&
        (soundFileType != "wav" || forceSettings)) {
      string arg;
      arg = "--format=";
      arg += soundFileType;
      if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
          (soundSampleFormat != "short" || forceSettings)) {
        arg += ':';
        arg += soundSampleFormat;
      }
      cmdLine.push_back(arg);
    }
    else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
             (soundSampleFormat != "short" || forceSettings)) {
      cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat);
    }
    if (!enablePeakChunks) {
      cmdLine.push_back("-K");
    }
    if (displayMode != 1 || forceSettings) {
      switch (displayMode) {    // 0: none, 1: full, 2: ASCII, 3: PS
      case 0:
        cmdLine.push_back("-d");
        break;
      case 1:
        cmdLine.push_back("--displays");
        break;
      case 2:
        if (forceSettings)
          cmdLine.push_back("--displays");
        cmdLine.push_back("-g");
        break;
      case 3:
        if (forceSettings)
          cmdLine.push_back("--displays");
        cmdLine.push_back("-G");
        break;
      }
    }
    if (deferGEN1)
      cmdLine.push_back("-D");
    if (bufFrames_SW >= 16) {
      cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW);
      cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers);
    }
    cmdLine_addStringOpt(cmdLine, "-F", midiInFileName);
    cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName);
    cmdLine_addStringOpt(cmdLine, "-M", midiInDevName);
    cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName);
    if (terminateOnMidi)
      cmdLine.push_back("-T");
    if (heartBeatMode != 0 || forceSettings)
      cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode);
    if (rewriteHeader)
      cmdLine.push_back("-R");
    if (runRealtime)
      cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice);
    else
      cmdLine_addStringOpt(cmdLine, "-i", inputFileName);
    if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) {
      cmdLine_addStringOpt(cmdLine, "-o", outputFileName);
    }
    else if (forceSettings && !disableDiskOutput)
      cmdLine.push_back("-n");
    if (disableDiskOutput && !runRealtime)
      cmdLine.push_back("-n");
    if (beatModeTempo > 0.0)
      cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo);
    if (iTimeOnly)
      cmdLine.push_back("-I");
    if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) {
      cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride);
      cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride);
    }
    cmdLine_addStringOpt(cmdLine, "-L", lineInput);
    if (messageLevel != 135 || forceSettings)
      cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel);
    if (enableExpressionOpt)
      cmdLine.push_back("--expression-opt");
    else if (forceSettings)
      cmdLine.push_back("--no-expression-opt");
    cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath);
    cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath);
    cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath);
    cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath);
//     cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath);
    for (int i = 0; i < 10; i++) {
      if (!CsoundGUIMain::isEmptyString(strsets[i])) {
        char  buf[16];
        sprintf(&(buf[0]), "--strset%d=", i);
        cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]);
      }
    }
    if (verbose)
      cmdLine.push_back("-v");
    if (enableDither)
      cmdLine.push_back("-Z");
    cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs);
    cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist);
    cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment);
    cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright);
    cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate);
    cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware);
    cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle);
    if (ignoreCSDOptions)
      cmdLine.push_back("-+ignore_csopts=1");
    else if (forceSettings)
      cmdLine.push_back("-+ignore_csopts=0");
    cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName);
    cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName);
    cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName);
    if ((maxStrLen >= 9 && maxStrLen <= 9999) &&
        (maxStrLen != 255 || forceSettings)) {
      cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1);
    }
    if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) {
      if (forceSettings)
        cmdLine.push_back("-+mute_tracks=");
    }
    if (midiKeyMidi > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi);
    if (midiKeyCps > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps);
    if (midiKeyOct > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct);
    if (midiKeyPch > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch);
    if (midiVelMidi > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi);
    if (midiVelAmp > 0)
      cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp);
    if (rawControllerMode)
      cmdLine.push_back("-+raw_controller_mode=1");
    else if (forceSettings)
      cmdLine.push_back("-+raw_controller_mode=0");
    if (runRealtime)
      cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule);
    cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule);
    if (scoreOffsetSeconds > 0.0)
      cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds);
    else if (forceSettings && scoreOffsetSeconds == 0.0)
      cmdLine.push_back("-+skip_seconds=0");
    if (!CsoundGUIMain::isEmptyString(orcName)) {
      cmdLine.push_back(orcName);
      if (!CsoundGUIMain::isCSDFile(orcName) &&
          !CsoundGUIMain::isEmptyString(scoName))
        cmdLine.push_back(scoName);
    }
    if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags))
      cmdLine.push_back(additionalFlags);
}
<|endoftext|>


<commit_before>//https://code.google.com/p/nya-engine/

#include <stdio.h>
#include <string.h>
#include "log/log.h"
#include "render/shader_code_parser.h"
#include <D3Dcompiler.h>
#include <io.h>
#include <fcntl.h>

#pragma comment(lib, "D3DCompiler.lib")
#pragma warning(disable: 4996)

const char *help="Usage: shader_compiler mode\n"
                 "accepts shader's code from stdin\n"
                 "stderr output begins with Error: if something goes wrong\n"
                 "outputs compiled shader/text assembly to stdout\n"
                 "modes:\n"
                 "hlsl - compiles hlsl shader\n"
                 "hlsl2asm - compiles hlsl shader and returns text assembly\n"
                 "glsl - compiles glsl shader\n"
                 "glsl2hlsl - converts glsl shader to hlsl\n"
                 //"nshvs - compiles vertex shader from nsh\n"
                 //"nshps - compiles pixel shader from nsh\n"
                 "\n";

                 //ToDo: allow sampler index assignment

bool compile_hlsl_code(const char *code,bool text_asm)
{
    if(!code)
        return false;

    const bool is_ps=strstr(code,"SV_TARGET")!=0;
    const char *profile=is_ps?"ps_4_0_level_9_3":"vs_4_0_level_9_3";
    ID3D10Blob *compiled=0, *error=0;
    D3DCompile(code,strlen(code),0,0,0,"main",profile,0,0,&compiled,&error);
    if(error)
    {
        fprintf(stderr,"Error: can`t compile shader with profile %s\n",profile);
        std::string error_text((const char *)error->GetBufferPointer(),error->GetBufferSize());
        fprintf(stderr,"%s\n",error_text.c_str());
        error->Release();
        return false;
    }

    if(!compiled)
    {
        fprintf(stderr,"Error: unknown compile error\n");
        return false;
    }

    if(text_asm)
    {
        ID3D10Blob *asm_blob;
        D3DDisassemble(compiled->GetBufferPointer(),compiled->GetBufferSize(),
                       D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING,"",&asm_blob);
        if(!asm_blob)
            return false;

        fwrite(asm_blob->GetBufferPointer(),1,asm_blob->GetBufferSize(),stdout);
        asm_blob->Release();
    }
    else
        fwrite(compiled->GetBufferPointer(),1,compiled->GetBufferSize(),stdout);

    compiled->Release();
    return true;
}

bool nsh2hlsl(bool fragment,std::string &result)
{
    return false;
}

int main(int argc, char* argv[])
{
    if(argc<2)
    {
        fprintf(stderr,"Error: no arguments\n");
        printf("%s",help);
        return 0;
    }

    setmode(fileno(stdout),O_BINARY);
    setmode(fileno(stdin),O_BINARY);

    nya_log::set_log(&nya_log::no_log());

    std::string shader_code;
    char buf[512];
    for(size_t size=fread(buf,1,sizeof(buf),stdin);size>0;size=fread(buf,1,sizeof(buf),stdin))
        shader_code.append(buf,size);

    if(shader_code.empty())
    {
        fprintf(stderr,"Error: empty stdin\n");
        printf("%s",help);
        return 0;
    }

    if(strcmp(argv[1],"hlsl")==0)
        return compile_hlsl_code(shader_code.c_str(),false)?0:-1;

    if(strcmp(argv[1],"hlsl2asm")==0)
        return compile_hlsl_code(shader_code.c_str(),true)?0:-1;

    const bool is_glsl2hlsl=strcmp(argv[1],"glsl2hlsl")==0;
    if(is_glsl2hlsl || strcmp(argv[1],"glsl")==0)
    {
        nya_render::shader_code_parser parser(shader_code.c_str());
        if(!parser.convert_to_hlsl())
        {
            fprintf(stderr,"Error: cannot convert to hlsl\n");
            return -1;
        }

        if(is_glsl2hlsl)
        {
            fwrite(parser.get_code(),1,strlen(parser.get_code()),stdout);
            return 0;
        }
        else
            return compile_hlsl_code(parser.get_code(),false)?0:-1;
    }

    const bool is_nshvs=strcmp(argv[1],"nshvs")==0;
    if(is_nshvs || strcmp(argv[1],"nshps")==0)
    {
        std::string hlsl_code;
        if(!nsh2hlsl(is_nshvs,hlsl_code))
        {
            fprintf(stderr,"Error: cannot convert to hlsl\n");
            return -1;
        }

        return compile_hlsl_code(hlsl_code.c_str(),false)?0:-1;
    }

    fprintf(stderr,"Error: invalid compile mode: %s\n",argv[1]);
	return -1;
}
<commit_msg>shader_compiler for dx11 cache<commit_after>//https://code.google.com/p/nya-engine/

#include <stdio.h>
#include <string.h>
#include "log/log.h"
#include "render/shader_code_parser.h"
#include "formats/text_parser.h"
#include <D3Dcompiler.h>
#include <io.h>
#include <fcntl.h>

#pragma comment(lib, "D3DCompiler.lib")
#pragma warning(disable: 4996)

const char *help="Usage: shader_compiler \%mode\%\n"
                 "accepts shader's code from stdin\n"
                 "stderr output begins with Error: if something goes wrong\n"
                 "outputs compiled shader/text assembly to stdout\n"
                 "modes:\n"
                 "hlsl - compiles hlsl shader\n"
                 "hlsl2asm - compiles hlsl shader and returns text assembly\n"
                 "glsl2hlsl - converts glsl shader to hlsl\n"
                 "or use: shader_compiler gencache \%src_dir\% \%dst_dir\%"
                 "\n";

                 //ToDo: allow sampler index assignment
                 //or glsl2hlsl is only for debug purpose?

bool compile_hlsl_code(const char *code,bool text_asm)
{
    if(!code)
        return false;

    const bool is_ps=strstr(code,"SV_TARGET")!=0;
    const char *profile=is_ps?"ps_4_0_level_9_3":"vs_4_0_level_9_3";
    ID3D10Blob *compiled=0, *error=0;
    D3DCompile(code,strlen(code),0,0,0,"main",profile,0,0,&compiled,&error);
    if(error)
    {
        fprintf(stderr,"Error: can`t compile shader with profile %s\n",profile);
        std::string error_text((const char *)error->GetBufferPointer(),error->GetBufferSize());
        fprintf(stderr,"%s\n",error_text.c_str());
        error->Release();
        return false;
    }

    if(!compiled)
    {
        fprintf(stderr,"Error: unknown compile error\n");
        return false;
    }

    if(text_asm)
    {
        ID3D10Blob *asm_blob;
        D3DDisassemble(compiled->GetBufferPointer(),compiled->GetBufferSize(),
                       D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING,"",&asm_blob);
        if(!asm_blob)
            return false;

        fwrite(asm_blob->GetBufferPointer(),1,asm_blob->GetBufferSize(),stdout);
        asm_blob->Release();
    }
    else
        fwrite(compiled->GetBufferPointer(),1,compiled->GetBufferSize(),stdout);

    compiled->Release();
    return true;
}

int main(int argc, char* argv[])
{
    if(argc<2)
    {
        fprintf(stderr,"Error: no arguments\n");
        printf("%s",help);
        return 0;
    }

    setmode(fileno(stdout),O_BINARY);
    setmode(fileno(stdin),O_BINARY);

    nya_log::set_log(&nya_log::no_log());

    std::string shader_code;
    char buf[512];
    for(size_t size=fread(buf,1,sizeof(buf),stdin);size>0;size=fread(buf,1,sizeof(buf),stdin))
        shader_code.append(buf,size);

    if(shader_code.empty())
    {
        fprintf(stderr,"Error: empty stdin\n");
        printf("%s",help);
        return 0;
    }

    if(strcmp(argv[1],"hlsl")==0)
        return compile_hlsl_code(shader_code.c_str(),false)?0:-1;

    if(strcmp(argv[1],"hlsl2asm")==0)
        return compile_hlsl_code(shader_code.c_str(),true)?0:-1;

    if(strcmp(argv[1],"glsl2hlsl")==0)
    {
        nya_render::shader_code_parser parser(shader_code.c_str());
        if(!parser.convert_to_hlsl())
        {
            fprintf(stderr,"Error: cannot convert to hlsl\n");
            return -1;
        }

        return compile_hlsl_code(parser.get_code(),false)?0:-1;
    }

    if(strcmp(argv[1],"gencache")==0)
    {
        if(argc!=4)
        {
            fprintf(stderr,"Error: src and dst dir not specified\n");
            printf("Usage: shader_compiler gencache \%src_dir\% \%dst_dir\%\n");
            return -1;
        }

        //ToDo
    }

    fprintf(stderr,"Error: invalid compile mode: %s\n",argv[1]);
	return -1;
}
<|endoftext|>


<commit_before>#ifndef CTHREAD_UNORDERED_MAP
#define CTHREAD_UNORDERED_MAP
#include<functional>	//equal_to, hash
#include<memory>	//allocator
#include<mutex>
#include<unordered_map>
#include<utility>	//forward, move

namespace nThread
{
	template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Allocator=std::allocator<std::pair<const Key,T>>>
	class CThread_unordered_map
	{
		std::unordered_map<Key,T,Hash,KeyEqual,Allocator> map_;
		std::mutex mut_;
		template<class KeyFwdRef>
		T& subscript_(KeyFwdRef &&key)
		{
			std::lock_guard<std::mutex> lock{mut_};
			return map_[std::forward<KeyFwdRef>(key)];
		}
		template<class KeyFwdRef,class ... Args>
		bool try_emplace_(KeyFwdRef &&key,Args &&...args)
		{
			std::lock_guard<std::mutex> lock{mut_};
			if(!find(key))
			{
				map_.emplace(std::forward<KeyFwdRef>(key),std::forward<Args>(args)...);
				return true;
			}
			return false;
		}
		template<class KeyFwdRef,class Gen>
		bool try_emplace_func_(KeyFwdRef &&key,const Gen gen)
		{
			std::lock_guard<std::mutex> lock{mut_};
			if(!find(key))
			{
				map_.emplace(std::forward<KeyFwdRef>(key),gen());
				return true;
			}
			return false;
		}
	public:
		CThread_unordered_map()=default;
		CThread_unordered_map(const CThread_unordered_map &)=delete;
		inline T& at(const Key &key)
		{
			return map_.at(key);
		}
		inline const T& at(const Key &key) const
		{
			return map_.at(key);
		}
		inline bool find(const Key &key) const
		{
			return map_.find(key)!=map_.end();
		}
		template<class ... Args>
		bool emplace(Args &&...args)
		{
			std::lock_guard<std::mutex> lock{mut_};
			return map_.emplace(std::forward<Args>(args)...).second;
		}
		template<class ... Args>
		inline bool try_emplace(const Key &key,Args &&...args)
		{
			return try_emplace_(key,std::forward<Args>(args)...);
		}
		template<class ... Args>
		inline bool try_emplace(Key &&key,Args &&...args)
		{
			return try_emplace_(std::move(key),std::forward<Args>(args)...);
		}
		template<class Gen>
		inline bool try_emplace_func(const Key &key,const Gen gen)
		{
			return try_emplace_func_(key,gen);
		}
		template<class Gen>
		inline bool try_emplace_func(Key &&key,const Gen gen)
		{
			return try_emplace_func_(std::move(key),gen);
		}
		CThread_unordered_map& operator=(const CThread_unordered_map &)=delete;
		inline T& operator[](const Key &key)
		{
			return subscript_(key);
		}
		inline T& operator[](Key &&key)
		{
			return subscript_(std::move(key));
		}
	};
}

#endif<commit_msg>rename try_emplace_func to try_emplace_gen<commit_after>#ifndef CTHREAD_UNORDERED_MAP
#define CTHREAD_UNORDERED_MAP
#include<functional>	//equal_to, hash
#include<memory>	//allocator
#include<mutex>
#include<unordered_map>
#include<utility>	//forward, move

namespace nThread
{
	template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Allocator=std::allocator<std::pair<const Key,T>>>
	class CThread_unordered_map
	{
		std::unordered_map<Key,T,Hash,KeyEqual,Allocator> map_;
		std::mutex mut_;
		template<class KeyFwdRef>
		T& subscript_(KeyFwdRef &&key)
		{
			std::lock_guard<std::mutex> lock{mut_};
			return map_[std::forward<KeyFwdRef>(key)];
		}
		template<class KeyFwdRef,class ... Args>
		bool try_emplace_(KeyFwdRef &&key,Args &&...args)
		{
			std::lock_guard<std::mutex> lock{mut_};
			if(!find(key))
			{
				map_.emplace(std::forward<KeyFwdRef>(key),std::forward<Args>(args)...);
				return true;
			}
			return false;
		}
		template<class KeyFwdRef,class Gen>
		bool try_emplace_gen_(KeyFwdRef &&key,const Gen gen)
		{
			std::lock_guard<std::mutex> lock{mut_};
			if(!find(key))
			{
				map_.emplace(std::forward<KeyFwdRef>(key),gen());
				return true;
			}
			return false;
		}
	public:
		CThread_unordered_map()=default;
		CThread_unordered_map(const CThread_unordered_map &)=delete;
		inline T& at(const Key &key)
		{
			return map_.at(key);
		}
		inline const T& at(const Key &key) const
		{
			return map_.at(key);
		}
		inline bool find(const Key &key) const
		{
			return map_.find(key)!=map_.end();
		}
		template<class ... Args>
		bool emplace(Args &&...args)
		{
			std::lock_guard<std::mutex> lock{mut_};
			return map_.emplace(std::forward<Args>(args)...).second;
		}
		template<class ... Args>
		inline bool try_emplace(const Key &key,Args &&...args)
		{
			return try_emplace_(key,std::forward<Args>(args)...);
		}
		template<class ... Args>
		inline bool try_emplace(Key &&key,Args &&...args)
		{
			return try_emplace_(std::move(key),std::forward<Args>(args)...);
		}
		template<class Gen>
		inline bool try_emplace_gen(const Key &key,const Gen gen)
		{
			return try_emplace_gen_(key,gen);
		}
		template<class Gen>
		inline bool try_emplace_gen(Key &&key,const Gen gen)
		{
			return try_emplace_gen_(std::move(key),gen);
		}
		CThread_unordered_map& operator=(const CThread_unordered_map &)=delete;
		inline T& operator[](const Key &key)
		{
			return subscript_(key);
		}
		inline T& operator[](Key &&key)
		{
			return subscript_(std::move(key));
		}
	};
}

#endif<|endoftext|>


<commit_before>/*******************************************************************************
* Copyright 2016 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/

/* Authors: Hye-Jong KIM, Darby Lim*/

#include "../../../include/open_manipulator/OMKinematics.h"

void OMKinematicsMethod::solveKinematicsSinglePoint(Manipulator* manipulator, Name component_name, bool* error = false)
{
  Pose parent_pose;
  Pose link_relative_pose;
  Eigen::Matrix3f rodrigues_rotation_matrix;
  Pose result_pose;

  parent_pose = MANAGER::getComponentPoseToWorld(manipulator, MANAGER::getComponentParentName(manipulator, component_name, error), error);
  link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, component_name, error);
  rodrigues_rotation_matrix = MATH::rodriguesRotationMatrix(getComponentJointAxis(manipulator, component_name, error), MANAGER::getComponentJointAngle(manipulator, component_name, error));

  result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position;
  result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation * rodrigues_rotation_matrix;

  MANAGER::setComponentPoseToWorld(manipulator, component_name, result_pose, error);
  for(int i = 0; i > MANAGER::getComponentChildName(manipulator, component_name, error).size(); i++)
  {
    solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, component_name, error).at(i), error);
  }
}

void OMKinematicsMethod::forward(Manipulator* manipulator, bool* error = false)
{
  Pose pose_to_wolrd;
  Pose link_relative_pose;
  Eigen::Matrix3f rodrigues_rotation_matrix;
  Pose result_pose;

  //Base Pose Set (from world)
  parent_pose = MANAGER::getWorldPose(manipulator, error);
  link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, MANAGER::getWorldChildName(manipulator, error), error);

  result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position;
  result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation;
  MANAGER::setComponentPoseToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), result_pose, error);

  //Next Component Pose Set
  for(int i = 0; i > MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).size(); i++)
  {
    solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).at(i), error);
  }
}

Eigen::MatrixXf OMKinematicsMethod::jacobian(Manipulator* manipulator, int8_t tool_component_name, bool *error = false)
{
  Eigen::MatrixXf jacobian(6,MANAGER::getDOF(manipulator, error));
  Eigen::Vector3f position_changed    = Eigen::Vector3f::Zero();
  Eigen::Vector3f orientation_changed = Eigen::Vector3f::Zero();
  Eigen::VectorXf pose_changed(6);
   map<Name, Component> temp_component = MANAGER::getAllComponent(manipulator, error);
  map<Name, Component>::iterator it_component_;
  int8_t j = 0;

  for(it_component_ = temp_component.begin(); it_component_ != temp_component.end(); it_component_++)
  {
    if(MANAGER::getComponentJointId(it_component_->first, error) >= 0)
    {
      position_changed = MATH::skewSymmetricMatrix(getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error))
                        * (MANAGER::getComponentPositionToWorld(manipulator, tool_component_name, error) - MANAGER::getComponentPositionToWorld(manipulator, it_component_->first, error));
      orientation_changed = MANAGER::getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error);

      pose_changed   << position_changed(0),
                        position_changed(1),
                        position_changed(2),
                        orientation_changed(0),
                        orientation_changed(1),
                        orientation_changed(2);

      jacobian.col(j) = pose_changed;
      j++;
    }
  }
  return jacobian
}

void OMLinkKinematics::forward(Manipulator* manipulator, bool *error = false)
{
  KINEMATICS::getPassiveJointAngle(manipulator, error)
  OMKinematicsMethod::forward(manipulator, error);
}

Eigen::VectorXf OMLinkKinematics::geometricInverse(Manipulator* manipulator, Name tool_number, Pose target_pose, bool *error = false) //for basic model
{
  Eigen::VectorXf target_angle_vector(3);
  Eigen::Vector3f control_position; //joint6-joint1
  Eigen::Vector3f tool_relative_position = MANAGER::getComponentRelativePositionToParent(manipulator, tool_number, error);
  Eigen::Vector3f base_position = MANAGER::getComponentPositionToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), error);
  Eigen::Vector3f temp_vector;

  float target_angle[3];
  float link[3];
  float temp_x;
  float temp_y;

  temp_y = target_pose.position(0)-base_position(0);
  temp_x = target_pose.position(1)-base_position(1);
  target_angle[0] = atan2(temp_y, temp_x);

  control_position(0) = target_pose.position(0) - tool_relative_position(0)*cos(target_angle[0]);
  control_position(1) = target_pose.position(1) - tool_relative_position(0)*sin(target_angle[0]);
  control_position(2) = target_pose.position(2) - tool_relative_position(2);

    // temp_vector = omlink.link_[0].getRelativeJointPosition(1,0);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error), error);
  link[0] = temp_vector(2);
    // temp_vector = omlink.link_[1].getRelativeJointPosition(5,1);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error);
  link[1] = temp_vector(0);
    // temp_vector = omlink.link_[4].getRelativeJointPosition(6,5);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error);
  link[2] = -temp_vector(0);

  temp_y = control_position(2)-base_position(2);
  temp_x = (control_position(0)-base_position(0))*cos(target_angle[0]);

  target_angle[1] = acos(((temp_x*temp_x+temp_y*temp_y+link[1]*link[1]-link[2]*link[2]))/(2*link[1]*sqrt(temp_x*temp_x+temp_y*temp_y))) + atan2(temp_y, temp_x);
  target_angle[2] = acos((link[1]*link[1]+link[2]*link[2]-(temp_x*temp_x+temp_y*temp_y))/(2*link[1]*link[2])) + target_angle[1];

  target_angle_vector << target_angle[0],
                         target_angle[1],
                         target_angle[2];
  return target_angle_vector;
}

<commit_msg>fix error<commit_after>/*******************************************************************************
* Copyright 2016 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/

/* Authors: Hye-Jong KIM, Darby Lim*/

#include "../../../include/open_manipulator/OMKinematics.h"

void OMKinematicsMethod::solveKinematicsSinglePoint(Manipulator* manipulator, Name component_name, bool* error = false)
{
  Pose parent_pose;
  Pose link_relative_pose;
  Eigen::Matrix3f rodrigues_rotation_matrix;
  Pose result_pose;

  parent_pose = MANAGER::getComponentPoseToWorld(manipulator, MANAGER::getComponentParentName(manipulator, component_name, error), error);
  link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, component_name, error);
  rodrigues_rotation_matrix = MATH::rodriguesRotationMatrix(getComponentJointAxis(manipulator, component_name, error), MANAGER::getComponentJointAngle(manipulator, component_name, error));

  result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position;
  result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation * rodrigues_rotation_matrix;

  MANAGER::setComponentPoseToWorld(manipulator, component_name, result_pose, error);
  for(int i = 0; i > MANAGER::getComponentChildName(manipulator, component_name, error).size(); i++)
  {
    solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, component_name, error).at(i), error);
  }
}

void OMKinematicsMethod::forward(Manipulator* manipulator, bool* error = false)
{
  Pose pose_to_wolrd;
  Pose link_relative_pose;
  Eigen::Matrix3f rodrigues_rotation_matrix;
  Pose result_pose;

  //Base Pose Set (from world)
  parent_pose = MANAGER::getWorldPose(manipulator, error);
  link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, MANAGER::getWorldChildName(manipulator, error), error);

  result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position;
  result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation;
  MANAGER::setComponentPoseToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), result_pose, error);

  //Next Component Pose Set
  for(int i = 0; i > MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).size(); i++)
  {
    solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).at(i), error);
  }
}

Eigen::MatrixXf OMKinematicsMethod::jacobian(Manipulator* manipulator, int8_t tool_component_name, bool *error = false)
{
  Eigen::MatrixXf jacobian(6,MANAGER::getDOF(manipulator, error));
  Eigen::Vector3f position_changed    = Eigen::Vector3f::Zero();
  Eigen::Vector3f orientation_changed = Eigen::Vector3f::Zero();
  Eigen::VectorXf pose_changed(6);
   map<Name, Component> temp_component = MANAGER::getAllComponent(manipulator, error);
  map<Name, Component>::iterator it_component_;
  int8_t j = 0;

  for(it_component_ = temp_component.begin(); it_component_ != temp_component.end(); it_component_++)
  {
    if(MANAGER::getComponentJointId(it_component_->first, error) >= 0)
    {
      position_changed = MATH::skewSymmetricMatrix(getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error))
                        * (MANAGER::getComponentPositionToWorld(manipulator, tool_component_name, error) - MANAGER::getComponentPositionToWorld(manipulator, it_component_->first, error));
      orientation_changed = MANAGER::getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error);

      pose_changed   << position_changed(0),
                        position_changed(1),
                        position_changed(2),
                        orientation_changed(0),
                        orientation_changed(1),
                        orientation_changed(2);

      jacobian.col(j) = pose_changed;
      j++;
    }
  }
  return jacobian
}

void OMLinkKinematics::forward(Manipulator* manipulator, bool *error = false)
{
  // KINEMATICS::getPassiveJointAngle(manipulator, error);
  OMKinematicsMethod::forward(manipulator, error);
}

Eigen::VectorXf OMLinkKinematics::geometricInverse(Manipulator* manipulator, Name tool_number, Pose target_pose, bool *error = false) //for basic model
{
  Eigen::VectorXf target_angle_vector(3);
  Eigen::Vector3f control_position; //joint6-joint1
  Eigen::Vector3f tool_relative_position = MANAGER::getComponentRelativePositionToParent(manipulator, tool_number, error);
  Eigen::Vector3f base_position = MANAGER::getComponentPositionToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), error);
  Eigen::Vector3f temp_vector;

  float target_angle[3];
  float link[3];
  float temp_x;
  float temp_y;

  temp_y = target_pose.position(0)-base_position(0);
  temp_x = target_pose.position(1)-base_position(1);
  target_angle[0] = atan2(temp_y, temp_x);

  control_position(0) = target_pose.position(0) - tool_relative_position(0)*cos(target_angle[0]);
  control_position(1) = target_pose.position(1) - tool_relative_position(0)*sin(target_angle[0]);
  control_position(2) = target_pose.position(2) - tool_relative_position(2);

    // temp_vector = omlink.link_[0].getRelativeJointPosition(1,0);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error), error);
  link[0] = temp_vector(2);
    // temp_vector = omlink.link_[1].getRelativeJointPosition(5,1);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error);
  link[1] = temp_vector(0);
    // temp_vector = omlink.link_[4].getRelativeJointPosition(6,5);
  temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error);
  link[2] = -temp_vector(0);

  temp_y = control_position(2)-base_position(2);
  temp_x = (control_position(0)-base_position(0))*cos(target_angle[0]);

  target_angle[1] = acos(((temp_x*temp_x+temp_y*temp_y+link[1]*link[1]-link[2]*link[2]))/(2*link[1]*sqrt(temp_x*temp_x+temp_y*temp_y))) + atan2(temp_y, temp_x);
  target_angle[2] = acos((link[1]*link[1]+link[2]*link[2]-(temp_x*temp_x+temp_y*temp_y))/(2*link[1]*link[2])) + target_angle[1];

  target_angle_vector << target_angle[0],
                         target_angle[1],
                         target_angle[2];
  return target_angle_vector;
}

<|endoftext|>


<commit_before>/*
 * $Id$
 */

#include "crf.h"
#include <vector>
#include <cmath>
#include <cfloat>
#include <map>

using namespace std;

bool USE_EDGE_TRIGRAMS = false;

const static int PERCEPTRON_NITER = 7;
int LOOKAHEAD_DEPTH = 2;

const double PERCEPTRON_MARGIN = 40;

const static int HV_OFFSET = 3;

void CRF_Model::lookahead_initialize_state_weights(const Sequence &seq) {
  vector<double> powv(_num_classes);
  for (size_t i = 0; i < seq.vs.size(); i++) {
    powv.assign(_num_classes, 0.0);
    const Sample &s = seq.vs[i];
    for (vector<int>::const_iterator j = s.positive_features.begin();
         j != s.positive_features.end(); j++) {
      for (vector<int>::const_iterator k = _feature2mef[*j].begin();
           k != _feature2mef[*j].end(); k++) {
        const double w = _vl[*k];
        powv[_fb.Feature(*k).label()] += w;
      }
    }

    for (int j = 0; j < _num_classes; j++) {
      state_weight(i, j) = powv[j];
    }
  }
}

double CRF_Model::lookahead_search(const Sequence &seq, vector<int> &history,
                                   const int start, const int max_depth,
                                   const int depth, double current_score,
                                   vector<int> &best_seq,
                                   const bool follow_gold,
                                   const vector<int> *forbidden_seq) {
  assert(history[HV_OFFSET + start - 1 + depth] >= 0);
  assert(history[HV_OFFSET + start - 1] >= 0);

  if (current_score > 0.001 * DBL_MAX || current_score < -0.001 * DBL_MAX) {
    cerr << "error: overflow in lookahead_search()" << endl;
    exit(1);
  }

  if (forbidden_seq && depth == 1) {
    if ((*forbidden_seq)[depth - 1] != history[HV_OFFSET + start + depth - 1])
      forbidden_seq = NULL;
  }

  if (depth >= max_depth || start + depth >= (int)seq.vs.size()) {
    best_seq.clear();
    if (forbidden_seq)
      return current_score;
    else
      return current_score + PERCEPTRON_MARGIN;
  }

  double m = -DBL_MAX;
  for (int i = 0; i < _num_classes; i++) {
    if (follow_gold && i != seq.vs[start + depth].label) continue;

    double new_score = current_score;
    // edge unigram features (state bigrams)
    new_score +=
        _vl[edge_feature_id(history[HV_OFFSET + start + depth - 1], i)];

    // edge bigram features (state trigrams)
    if (depth + start > 0)
      new_score +=
          _vl[edge_feature_id2(history[HV_OFFSET + start + depth - 2],
                               history[HV_OFFSET + start + depth - 1], i)];

    // edge trigram features (state 4-grams)
    if (USE_EDGE_TRIGRAMS) {
      if (depth + start > 1)
        new_score +=
            _vl[edge_feature_id3(history[HV_OFFSET + start + depth - 3],
                                 history[HV_OFFSET + start + depth - 2],
                                 history[HV_OFFSET + start + depth - 1], i)];
    }

    // state + observation features
    new_score += state_weight(start + depth, i);

    history[HV_OFFSET + start + depth] = i;

    vector<int> tmp_seq;
    const double score =
        lookahead_search(seq, history, start, max_depth, depth + 1, new_score,
                         tmp_seq, false, forbidden_seq);
    if (score > m) {
      m = score;
      best_seq.clear();
      best_seq.push_back(i);
      copy(tmp_seq.begin(), tmp_seq.end(), back_inserter(best_seq));
    }
  }

  return m;
}

void CRF_Model::calc_diff(const double val, const Sequence &seq,
                          const int start, const vector<int> &history,
                          const int depth, const int max_depth,
                          map<int, double> &diff) {
  if (start + depth == (int)seq.vs.size()) return;
  if (depth >= max_depth) return;

  const int label = history[HV_OFFSET + start + depth];

  int eid = -1;
  eid = edge_feature_id(history[HV_OFFSET + start + depth - 1], label);
  assert(eid >= 0);
  diff[eid] += val;

  int eid2 = -1;
  eid2 = edge_feature_id2(history[HV_OFFSET + start + depth - 2],
                          history[HV_OFFSET + start + depth - 1], label);
  if (eid2 >= 0) diff[eid2] += val;

  if (USE_EDGE_TRIGRAMS) {
    const int eid3 =
        edge_feature_id3(history[HV_OFFSET + start + depth - 3],
                         history[HV_OFFSET + start + depth - 2],
                         history[HV_OFFSET + start + depth - 1], label);
    if (eid3 >= 0) diff[eid3] += val;
  }

  assert(start + depth < (int)seq.vs.size());
  const Sample &s = seq.vs[start + depth];
  for (vector<int>::const_iterator j = s.positive_features.begin();
       j != s.positive_features.end(); j++) {
    for (vector<int>::const_iterator k = _feature2mef[*j].begin();
         k != _feature2mef[*j].end(); k++) {
      if (_fb.Feature(*k).label() == label) diff[*k] += val;
    }
  }

  calc_diff(val, seq, start, history, depth + 1, max_depth, diff);
}

static void print_bestsq(const vector<int> &bestsq) {
  for (vector<int>::const_iterator i = bestsq.begin(); i != bestsq.end(); i++) {
    cout << *i << " ";
  }
  cout << endl;
}

int CRF_Model::update_weights_sub2(const Sequence &seq, vector<int> &history,
                                   const int x, map<int, double> &diff) {
  // gold-standard sequence
  vector<int> gold_seq;
  const double gold_score =
      lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0, gold_seq, true);

  vector<int> best_seq;
  const double score = lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0,
                                        best_seq, false, &gold_seq);

  if (best_seq.front() == gold_seq.front()) return 0;

  map<int, double> vdiff;

  copy(gold_seq.begin(), gold_seq.end(), history.begin() + HV_OFFSET + x);
  calc_diff(1, seq, x, history, 0, LOOKAHEAD_DEPTH, vdiff);
  copy(best_seq.begin(), best_seq.end(), history.begin() + HV_OFFSET + x);
  calc_diff(-1, seq, x, history, 0, LOOKAHEAD_DEPTH, vdiff);

  for (map<int, double>::const_iterator j = vdiff.begin(); j != vdiff.end();
       j++) {
    diff[j->first] += j->second;
  }

  return 1;
}

int CRF_Model::lookaheadtrain_sentence(const Sequence &seq, int &t,
                                       vector<double> &wa) {
  lookahead_initialize_state_weights(seq);

  const int len = seq.vs.size();

  vector<int> history(len + HV_OFFSET, -1);
  int error_num = 0;
  for (int x = 0; x < len; x++) {
    map<int, double> diff;

    error_num += update_weights_sub2(seq, history, x, diff);
    history[HV_OFFSET + x] = seq.vs[x].label;

    for (map<int, double>::const_iterator i = diff.begin(); i != diff.end();
         i++) {
      const double v = 1.0 * i->second;
      _vl[i->first] += v;
      wa[i->first] += t * v;
    }
    t++;
  }

  return error_num;
}

double CRF_Model::heldout_lookahead_error() {
  int nerrors = 0, total_len = 0;

  for (std::vector<Sequence>::const_iterator i = _heldout.begin();
       i != _heldout.end(); i++) {
    total_len += i->vs.size();

    vector<int> vs(i->vs.size());
    decode_lookahead_sentence(*i, vs);

    for (size_t j = 0; j < vs.size(); j++) {
      if (vs[j] != i->vs[j].label) nerrors++;
    }
  }
  _heldout_error = (double)nerrors / total_len;

  return 0;
}

int CRF_Model::perform_LookaheadTraining() {
  cerr << "lookahead depth = " << LOOKAHEAD_DEPTH << endl;
  cerr << "perceptron margin = " << PERCEPTRON_MARGIN << endl;
  cerr << "perceptron niter = " << PERCEPTRON_NITER << endl;

  const int dim = _fb.Size();

  vector<double> wa(dim, 0);

  int t = 1;

  int iter = 0;
  while (iter < PERCEPTRON_NITER) {
    iter++;

    vector<int> r(_vs.size());
    for (int i = 0; i < (int)_vs.size(); i++) r[i] = i;
    random_shuffle(r.begin(), r.end());

    int error_num = 0;
    for (int i = 0; i < (int)_vs.size(); i++) {
      const Sequence &seq = _vs[r[i]];

      error_num += lookaheadtrain_sentence(seq, t, wa);
    }
    cerr << "iter = " << iter << " num_errors = " << error_num;

    if (_heldout.size() > 0) {
      vector<double> tmpvl = _vl;
      for (int i = 0; i < dim; i++) _vl[i] -= wa[i] / t;
      heldout_lookahead_error();
      cerr << "\theldout_error = " << _heldout_error;
      _vl = tmpvl;
    }
    cerr << endl;

    if (error_num == 0) break;
  }

  for (int i = 0; i < dim; i++) _vl[i] -= wa[i] / t;

  return 0;
}

int CRF_Model::decode_lookahead_sentence(const Sequence &seq, vector<int> &vs) {
  lookahead_initialize_state_weights(seq);

  const int len = seq.vs.size();

  vector<int> history(len + HV_OFFSET, -1);
  fill(history.begin(), history.begin() + HV_OFFSET, _num_classes);  // BOS
  int error_num = 0;
  for (int x = 0; x < len; x++) {
    vector<int> bestsq;
    const double score =
        lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0, bestsq);

    vs[x] = bestsq.front();
    history[HV_OFFSET + x] = vs[x];
  }

  return error_num;
}

void CRF_Model::decode_lookahead(CRF_Sequence &s0) {
  if (s0.vs.size() >= MAX_LEN) {
    cerr << "error: sequence is too long." << endl;
    return;
  }

  Sequence seq;

  for (vector<CRF_State>::const_iterator i = s0.vs.begin(); i != s0.vs.end();
       i++) {
    Sample s;
    for (vector<string>::const_iterator j = i->features.begin();
         j != i->features.end(); j++) {
      const int id = _featurename_bag.Id(*j);
      if (id >= 0) s.positive_features.push_back(id);
    }
    seq.vs.push_back(s);
  }

  vector<int> vs(seq.vs.size());
  decode_lookahead_sentence(seq, vs);

  for (size_t i = 0; i < seq.vs.size(); i++) {
    s0.vs[i].label = _label_bag.Str(vs[i]);
  }
}
<commit_msg>lookahead.cpp: prefer prefix ++operator for non-primitive types<commit_after>/*
 * $Id$
 */

#include "crf.h"
#include <vector>
#include <cmath>
#include <cfloat>
#include <map>

using namespace std;

bool USE_EDGE_TRIGRAMS = false;

const static int PERCEPTRON_NITER = 7;
int LOOKAHEAD_DEPTH = 2;

const double PERCEPTRON_MARGIN = 40;

const static int HV_OFFSET = 3;

void CRF_Model::lookahead_initialize_state_weights(const Sequence &seq) {
  vector<double> powv(_num_classes);
  for (size_t i = 0; i < seq.vs.size(); i++) {
    powv.assign(_num_classes, 0.0);
    const Sample &s = seq.vs[i];
    for (vector<int>::const_iterator j = s.positive_features.begin();
         j != s.positive_features.end(); ++j) {
      for (vector<int>::const_iterator k = _feature2mef[*j].begin();
           k != _feature2mef[*j].end(); ++k) {
        const double w = _vl[*k];
        powv[_fb.Feature(*k).label()] += w;
      }
    }

    for (int j = 0; j < _num_classes; j++) {
      state_weight(i, j) = powv[j];
    }
  }
}

double CRF_Model::lookahead_search(const Sequence &seq, vector<int> &history,
                                   const int start, const int max_depth,
                                   const int depth, double current_score,
                                   vector<int> &best_seq,
                                   const bool follow_gold,
                                   const vector<int> *forbidden_seq) {
  assert(history[HV_OFFSET + start - 1 + depth] >= 0);
  assert(history[HV_OFFSET + start - 1] >= 0);

  if (current_score > 0.001 * DBL_MAX || current_score < -0.001 * DBL_MAX) {
    cerr << "error: overflow in lookahead_search()" << endl;
    exit(1);
  }

  if (forbidden_seq && depth == 1) {
    if ((*forbidden_seq)[depth - 1] != history[HV_OFFSET + start + depth - 1])
      forbidden_seq = NULL;
  }

  if (depth >= max_depth || start + depth >= (int)seq.vs.size()) {
    best_seq.clear();
    if (forbidden_seq)
      return current_score;
    else
      return current_score + PERCEPTRON_MARGIN;
  }

  double m = -DBL_MAX;
  for (int i = 0; i < _num_classes; i++) {
    if (follow_gold && i != seq.vs[start + depth].label) continue;

    double new_score = current_score;
    // edge unigram features (state bigrams)
    new_score +=
        _vl[edge_feature_id(history[HV_OFFSET + start + depth - 1], i)];

    // edge bigram features (state trigrams)
    if (depth + start > 0)
      new_score +=
          _vl[edge_feature_id2(history[HV_OFFSET + start + depth - 2],
                               history[HV_OFFSET + start + depth - 1], i)];

    // edge trigram features (state 4-grams)
    if (USE_EDGE_TRIGRAMS) {
      if (depth + start > 1)
        new_score +=
            _vl[edge_feature_id3(history[HV_OFFSET + start + depth - 3],
                                 history[HV_OFFSET + start + depth - 2],
                                 history[HV_OFFSET + start + depth - 1], i)];
    }

    // state + observation features
    new_score += state_weight(start + depth, i);

    history[HV_OFFSET + start + depth] = i;

    vector<int> tmp_seq;
    const double score =
        lookahead_search(seq, history, start, max_depth, depth + 1, new_score,
                         tmp_seq, false, forbidden_seq);
    if (score > m) {
      m = score;
      best_seq.clear();
      best_seq.push_back(i);
      copy(tmp_seq.begin(), tmp_seq.end(), back_inserter(best_seq));
    }
  }

  return m;
}

void CRF_Model::calc_diff(const double val, const Sequence &seq,
                          const int start, const vector<int> &history,
                          const int depth, const int max_depth,
                          map<int, double> &diff) {
  if (start + depth == (int)seq.vs.size()) return;
  if (depth >= max_depth) return;

  const int label = history[HV_OFFSET + start + depth];

  int eid = -1;
  eid = edge_feature_id(history[HV_OFFSET + start + depth - 1], label);
  assert(eid >= 0);
  diff[eid] += val;

  int eid2 = -1;
  eid2 = edge_feature_id2(history[HV_OFFSET + start + depth - 2],
                          history[HV_OFFSET + start + depth - 1], label);
  if (eid2 >= 0) diff[eid2] += val;

  if (USE_EDGE_TRIGRAMS) {
    const int eid3 =
        edge_feature_id3(history[HV_OFFSET + start + depth - 3],
                         history[HV_OFFSET + start + depth - 2],
                         history[HV_OFFSET + start + depth - 1], label);
    if (eid3 >= 0) diff[eid3] += val;
  }

  assert(start + depth < (int)seq.vs.size());
  const Sample &s = seq.vs[start + depth];
  for (vector<int>::const_iterator j = s.positive_features.begin();
       j != s.positive_features.end(); ++j) {
    for (vector<int>::const_iterator k = _feature2mef[*j].begin();
         k != _feature2mef[*j].end(); ++k) {
      if (_fb.Feature(*k).label() == label) diff[*k] += val;
    }
  }

  calc_diff(val, seq, start, history, depth + 1, max_depth, diff);
}

static void print_bestsq(const vector<int> &bestsq) {
  for (vector<int>::const_iterator i = bestsq.begin(); i != bestsq.end(); ++i) {
    cout << *i << " ";
  }
  cout << endl;
}

int CRF_Model::update_weights_sub2(const Sequence &seq, vector<int> &history,
                                   const int x, map<int, double> &diff) {
  // gold-standard sequence
  vector<int> gold_seq;
  const double gold_score =
      lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0, gold_seq, true);

  vector<int> best_seq;
  const double score = lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0,
                                        best_seq, false, &gold_seq);

  if (best_seq.front() == gold_seq.front()) return 0;

  map<int, double> vdiff;

  copy(gold_seq.begin(), gold_seq.end(), history.begin() + HV_OFFSET + x);
  calc_diff(1, seq, x, history, 0, LOOKAHEAD_DEPTH, vdiff);
  copy(best_seq.begin(), best_seq.end(), history.begin() + HV_OFFSET + x);
  calc_diff(-1, seq, x, history, 0, LOOKAHEAD_DEPTH, vdiff);

  for (map<int, double>::const_iterator j = vdiff.begin(); j != vdiff.end();
       ++j) {
    diff[j->first] += j->second;
  }

  return 1;
}

int CRF_Model::lookaheadtrain_sentence(const Sequence &seq, int &t,
                                       vector<double> &wa) {
  lookahead_initialize_state_weights(seq);

  const int len = seq.vs.size();

  vector<int> history(len + HV_OFFSET, -1);
  int error_num = 0;
  for (int x = 0; x < len; x++) {
    map<int, double> diff;

    error_num += update_weights_sub2(seq, history, x, diff);
    history[HV_OFFSET + x] = seq.vs[x].label;

    for (map<int, double>::const_iterator i = diff.begin(); i != diff.end();
         ++i) {
      const double v = 1.0 * i->second;
      _vl[i->first] += v;
      wa[i->first] += t * v;
    }
    t++;
  }

  return error_num;
}

double CRF_Model::heldout_lookahead_error() {
  int nerrors = 0, total_len = 0;

  for (std::vector<Sequence>::const_iterator i = _heldout.begin();
       i != _heldout.end(); ++i) {
    total_len += i->vs.size();

    vector<int> vs(i->vs.size());
    decode_lookahead_sentence(*i, vs);

    for (size_t j = 0; j < vs.size(); j++) {
      if (vs[j] != i->vs[j].label) nerrors++;
    }
  }
  _heldout_error = (double)nerrors / total_len;

  return 0;
}

int CRF_Model::perform_LookaheadTraining() {
  cerr << "lookahead depth = " << LOOKAHEAD_DEPTH << endl;
  cerr << "perceptron margin = " << PERCEPTRON_MARGIN << endl;
  cerr << "perceptron niter = " << PERCEPTRON_NITER << endl;

  const int dim = _fb.Size();

  vector<double> wa(dim, 0);

  int t = 1;

  int iter = 0;
  while (iter < PERCEPTRON_NITER) {
    iter++;

    vector<int> r(_vs.size());
    for (int i = 0; i < (int)_vs.size(); i++) r[i] = i;
    random_shuffle(r.begin(), r.end());

    int error_num = 0;
    for (int i = 0; i < (int)_vs.size(); i++) {
      const Sequence &seq = _vs[r[i]];

      error_num += lookaheadtrain_sentence(seq, t, wa);
    }
    cerr << "iter = " << iter << " num_errors = " << error_num;

    if (_heldout.size() > 0) {
      vector<double> tmpvl = _vl;
      for (int i = 0; i < dim; i++) _vl[i] -= wa[i] / t;
      heldout_lookahead_error();
      cerr << "\theldout_error = " << _heldout_error;
      _vl = tmpvl;
    }
    cerr << endl;

    if (error_num == 0) break;
  }

  for (int i = 0; i < dim; i++) _vl[i] -= wa[i] / t;

  return 0;
}

int CRF_Model::decode_lookahead_sentence(const Sequence &seq, vector<int> &vs) {
  lookahead_initialize_state_weights(seq);

  const int len = seq.vs.size();

  vector<int> history(len + HV_OFFSET, -1);
  fill(history.begin(), history.begin() + HV_OFFSET, _num_classes);  // BOS
  int error_num = 0;
  for (int x = 0; x < len; x++) {
    vector<int> bestsq;
    const double score =
        lookahead_search(seq, history, x, LOOKAHEAD_DEPTH, 0, 0, bestsq);

    vs[x] = bestsq.front();
    history[HV_OFFSET + x] = vs[x];
  }

  return error_num;
}

void CRF_Model::decode_lookahead(CRF_Sequence &s0) {
  if (s0.vs.size() >= MAX_LEN) {
    cerr << "error: sequence is too long." << endl;
    return;
  }

  Sequence seq;

  for (vector<CRF_State>::const_iterator i = s0.vs.begin(); i != s0.vs.end();
       ++i) {
    Sample s;
    for (vector<string>::const_iterator j = i->features.begin();
         j != i->features.end(); ++j) {
      const int id = _featurename_bag.Id(*j);
      if (id >= 0) s.positive_features.push_back(id);
    }
    seq.vs.push_back(s);
  }

  vector<int> vs(seq.vs.size());
  decode_lookahead_sentence(seq, vs);

  for (size_t i = 0; i < seq.vs.size(); i++) {
    s0.vs[i].label = _label_bag.Str(vs[i]);
  }
}
<|endoftext|>


<commit_before><commit_msg>Problem clipping gtk text. BUG=26266i TEST=NONE<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Baldur Karlsson
 *
 * 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 <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include "os/os_specific.h"
#include "serialise/string_utils.h"

using std::string;

namespace Network
{
void Init()
{
}

void Shutdown()
{
}

Socket::~Socket()
{
  Shutdown();
}

void Socket::Shutdown()
{
  if(Connected())
  {
    shutdown((int)socket, SHUT_RDWR);
    close((int)socket);
    socket = -1;
  }
}

bool Socket::Connected() const
{
  return (int)socket != -1;
}

uint32_t Socket::GetRemoteIP() const
{
  sockaddr_in addr = {};
  socklen_t len = sizeof(addr);

  getpeername((int)socket, (sockaddr *)&addr, &len);

  return ntohl(addr.sin_addr.s_addr);
}

Socket *Socket::AcceptClient(bool wait)
{
  do
  {
    int s = accept(socket, NULL, NULL);

    if(s != -1)
    {
      int flags = fcntl(s, F_GETFL, 0);
      fcntl(s, F_SETFL, flags | O_NONBLOCK);

      int nodelay = 1;
      setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));

      return new Socket((ptrdiff_t)s);
    }

    int err = errno;

    if(err != EWOULDBLOCK && err != EAGAIN)
    {
      RDCWARN("accept: %d", err);
      Shutdown();
    }

    Threading::Sleep(4);
  } while(wait);

  return NULL;
}

bool Socket::SendDataBlocking(const void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t sent = 0;

  char *src = (char *)buf;

  int flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);

  while(sent < length)
  {
    int ret = send(socket, src, length - sent, 0);

    if(ret <= 0)
    {
      int err = errno;

      if(err == EWOULDBLOCK || err == EAGAIN)
      {
        ret = 0;
      }
      else
      {
        RDCWARN("send: %d", err);
        Shutdown();
        return false;
      }
    }

    sent += ret;
    src += ret;
  }

  flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);

  RDCASSERT(sent == length);

  return true;
}

bool Socket::IsRecvDataWaiting()
{
  char dummy;
  int ret = recv(socket, &dummy, 1, MSG_PEEK);

  if(ret == 0)
  {
    Shutdown();
    return false;
  }
  else if(ret <= 0)
  {
    int err = errno;

    if(err == EWOULDBLOCK || err == EAGAIN)
    {
      ret = 0;
    }
    else
    {
      RDCWARN("recv: %d", err);
      Shutdown();
      return false;
    }
  }

  return ret > 0;
}

bool Socket::RecvDataBlocking(void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t received = 0;

  char *dst = (char *)buf;

  int flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);

  while(received < length)
  {
    int ret = recv(socket, dst, length - received, 0);

    if(ret == 0)
    {
      Shutdown();
      return false;
    }
    else if(ret <= 0)
    {
      int err = errno;

      if(err == EWOULDBLOCK || err == EAGAIN)
      {
        ret = 0;
      }
      else
      {
        RDCWARN("recv: %d", err);
        Shutdown();
        return false;
      }
    }

    received += ret;
    dst += ret;
  }

  flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);

  RDCASSERT(received == length);

  return true;
}

Socket *CreateServerSocket(const char *bindaddr, uint16_t port, int queuesize)
{
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  int yes = 1;
  setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

  if(s == -1)
    return NULL;

  sockaddr_in addr;
  RDCEraseEl(addr);

  hostent *hp = gethostbyname(bindaddr);

  addr.sin_family = AF_INET;
  memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  addr.sin_port = htons(port);

  int result = bind(s, (sockaddr *)&addr, sizeof(addr));
  if(result == -1)
  {
    RDCWARN("Failed to bind to %s:%d - %d", bindaddr, port, errno);
    close(s);
    return NULL;
  }

  result = listen(s, queuesize);
  if(result == -1)
  {
    RDCWARN("Failed to listen on %s:%d - %d", bindaddr, port, errno);
    close(s);
    return NULL;
  }

  int flags = fcntl(s, F_GETFL, 0);
  fcntl(s, F_SETFL, flags | O_NONBLOCK);

  return new Socket((ptrdiff_t)s);
}

Socket *CreateClientSocket(const char *host, uint16_t port, int timeoutMS)
{
  char portstr[7] = {0};
  StringFormat::snprintf(portstr, 6, "%d", port);

  addrinfo hints;
  RDCEraseEl(hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  addrinfo *result = NULL;
  getaddrinfo(host, portstr, &hints, &result);

  for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next)
  {
    int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if(s == -1)
      return NULL;

    int flags = fcntl(s, F_GETFL, 0);
    fcntl(s, F_SETFL, flags | O_NONBLOCK);

    int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen);
    if(result == -1)
    {
      fd_set set;
      FD_ZERO(&set);
      FD_SET(s, &set);

      int err = errno;

      if(err == EWOULDBLOCK || err == EINPROGRESS)
      {
        timeval timeout;
        timeout.tv_sec = (timeoutMS / 1000);
        timeout.tv_usec = (timeoutMS % 1000) * 1000;
        result = select(0, NULL, &set, NULL, &timeout);

        if(result <= 0)
        {
          RDCDEBUG("connect timed out");
          close(s);
          continue;
        }
        else
        {
          RDCDEBUG("connect before timeout");
        }
      }
      else
      {
        RDCDEBUG("problem other than blocking");
        close(s);
        continue;
      }
    }
    else
    {
      RDCDEBUG("connected immediately");
    }

    int nodelay = 1;
    setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));

    return new Socket((ptrdiff_t)s);
  }

  RDCWARN("Failed to connect to %S:%d", host, port);
  return NULL;
}

bool ParseIPRangeCIDR(const char *str, uint32_t &ip, uint32_t &mask)
{
  uint32_t a = 0, b = 0, c = 0, d = 0, num = 0;

  int ret = sscanf(str, "%u.%u.%u.%u/%u", &a, &b, &c, &d, &num);

  ip = MakeIP(a, b, c, d);

  if(num == 0)
  {
    mask = 0;
  }
  else
  {
    num = 32 - num;
    mask = ((~0U) >> num) << num;
  }

  return ret == 5;
}
};
<commit_msg>Fix char* format specifier.<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Baldur Karlsson
 *
 * 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 <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include "os/os_specific.h"
#include "serialise/string_utils.h"

using std::string;

namespace Network
{
void Init()
{
}

void Shutdown()
{
}

Socket::~Socket()
{
  Shutdown();
}

void Socket::Shutdown()
{
  if(Connected())
  {
    shutdown((int)socket, SHUT_RDWR);
    close((int)socket);
    socket = -1;
  }
}

bool Socket::Connected() const
{
  return (int)socket != -1;
}

uint32_t Socket::GetRemoteIP() const
{
  sockaddr_in addr = {};
  socklen_t len = sizeof(addr);

  getpeername((int)socket, (sockaddr *)&addr, &len);

  return ntohl(addr.sin_addr.s_addr);
}

Socket *Socket::AcceptClient(bool wait)
{
  do
  {
    int s = accept(socket, NULL, NULL);

    if(s != -1)
    {
      int flags = fcntl(s, F_GETFL, 0);
      fcntl(s, F_SETFL, flags | O_NONBLOCK);

      int nodelay = 1;
      setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));

      return new Socket((ptrdiff_t)s);
    }

    int err = errno;

    if(err != EWOULDBLOCK && err != EAGAIN)
    {
      RDCWARN("accept: %d", err);
      Shutdown();
    }

    Threading::Sleep(4);
  } while(wait);

  return NULL;
}

bool Socket::SendDataBlocking(const void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t sent = 0;

  char *src = (char *)buf;

  int flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);

  while(sent < length)
  {
    int ret = send(socket, src, length - sent, 0);

    if(ret <= 0)
    {
      int err = errno;

      if(err == EWOULDBLOCK || err == EAGAIN)
      {
        ret = 0;
      }
      else
      {
        RDCWARN("send: %d", err);
        Shutdown();
        return false;
      }
    }

    sent += ret;
    src += ret;
  }

  flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);

  RDCASSERT(sent == length);

  return true;
}

bool Socket::IsRecvDataWaiting()
{
  char dummy;
  int ret = recv(socket, &dummy, 1, MSG_PEEK);

  if(ret == 0)
  {
    Shutdown();
    return false;
  }
  else if(ret <= 0)
  {
    int err = errno;

    if(err == EWOULDBLOCK || err == EAGAIN)
    {
      ret = 0;
    }
    else
    {
      RDCWARN("recv: %d", err);
      Shutdown();
      return false;
    }
  }

  return ret > 0;
}

bool Socket::RecvDataBlocking(void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t received = 0;

  char *dst = (char *)buf;

  int flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);

  while(received < length)
  {
    int ret = recv(socket, dst, length - received, 0);

    if(ret == 0)
    {
      Shutdown();
      return false;
    }
    else if(ret <= 0)
    {
      int err = errno;

      if(err == EWOULDBLOCK || err == EAGAIN)
      {
        ret = 0;
      }
      else
      {
        RDCWARN("recv: %d", err);
        Shutdown();
        return false;
      }
    }

    received += ret;
    dst += ret;
  }

  flags = fcntl(socket, F_GETFL, 0);
  fcntl(socket, F_SETFL, flags | O_NONBLOCK);

  RDCASSERT(received == length);

  return true;
}

Socket *CreateServerSocket(const char *bindaddr, uint16_t port, int queuesize)
{
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  int yes = 1;
  setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

  if(s == -1)
    return NULL;

  sockaddr_in addr;
  RDCEraseEl(addr);

  hostent *hp = gethostbyname(bindaddr);

  addr.sin_family = AF_INET;
  memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  addr.sin_port = htons(port);

  int result = bind(s, (sockaddr *)&addr, sizeof(addr));
  if(result == -1)
  {
    RDCWARN("Failed to bind to %s:%d - %d", bindaddr, port, errno);
    close(s);
    return NULL;
  }

  result = listen(s, queuesize);
  if(result == -1)
  {
    RDCWARN("Failed to listen on %s:%d - %d", bindaddr, port, errno);
    close(s);
    return NULL;
  }

  int flags = fcntl(s, F_GETFL, 0);
  fcntl(s, F_SETFL, flags | O_NONBLOCK);

  return new Socket((ptrdiff_t)s);
}

Socket *CreateClientSocket(const char *host, uint16_t port, int timeoutMS)
{
  char portstr[7] = {0};
  StringFormat::snprintf(portstr, 6, "%d", port);

  addrinfo hints;
  RDCEraseEl(hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  addrinfo *result = NULL;
  getaddrinfo(host, portstr, &hints, &result);

  for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next)
  {
    int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if(s == -1)
      return NULL;

    int flags = fcntl(s, F_GETFL, 0);
    fcntl(s, F_SETFL, flags | O_NONBLOCK);

    int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen);
    if(result == -1)
    {
      fd_set set;
      FD_ZERO(&set);
      FD_SET(s, &set);

      int err = errno;

      if(err == EWOULDBLOCK || err == EINPROGRESS)
      {
        timeval timeout;
        timeout.tv_sec = (timeoutMS / 1000);
        timeout.tv_usec = (timeoutMS % 1000) * 1000;
        result = select(0, NULL, &set, NULL, &timeout);

        if(result <= 0)
        {
          RDCDEBUG("connect timed out");
          close(s);
          continue;
        }
        else
        {
          RDCDEBUG("connect before timeout");
        }
      }
      else
      {
        RDCDEBUG("problem other than blocking");
        close(s);
        continue;
      }
    }
    else
    {
      RDCDEBUG("connected immediately");
    }

    int nodelay = 1;
    setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));

    return new Socket((ptrdiff_t)s);
  }

  RDCWARN("Failed to connect to %s:%d", host, port);
  return NULL;
}

bool ParseIPRangeCIDR(const char *str, uint32_t &ip, uint32_t &mask)
{
  uint32_t a = 0, b = 0, c = 0, d = 0, num = 0;

  int ret = sscanf(str, "%u.%u.%u.%u/%u", &a, &b, &c, &d, &num);

  ip = MakeIP(a, b, c, d);

  if(num == 0)
  {
    mask = 0;
  }
  else
  {
    num = 32 - num;
    mask = ((~0U) >> num) << num;
  }

  return ret == 5;
}
};
<|endoftext|>