<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSarImageMetadataInterface.h"
#include "otbSentinel1ImageMetadataInterface.h"

#include "otbMacro.h"
#include "itkMetaDataObject.h"
#include "otbImageKeywordlist.h"

//useful constants
#include <otbMath.h>

namespace otb
{

Sentinel1ImageMetadataInterface
::Sentinel1ImageMetadataInterface()
{

}

bool
Sentinel1ImageMetadataInterface::CanRead() const
{
  std::string sensorID = GetSensorID();

  if (sensorID.find("SENTINEL-1") != std::string::npos)
    {
    return true;
    }
  else
    return false;
}

void
Sentinel1ImageMetadataInterface
::CreateCalibrationLookupData(const short type)
  {
    bool sigmaLut = false;
    bool betaLut = false;
    bool gammaLut = false;
    bool dnLut = false;

    switch (type)
      {
      case SarCalibrationLookupData::BETA:
      {
      betaLut = true;
      }
      break;

      case SarCalibrationLookupData::GAMMA:
      {
      gammaLut = true;
      }
      break;

      case SarCalibrationLookupData::DN:
      {
      dnLut = true;
      }
      break;

      case SarCalibrationLookupData::SIGMA:
      default:
        sigmaLut = true;
        break;
      }

  const ImageKeywordlistType imageKeywordlist =  this->GetImageKeywordlist();

  const double firstLineTime = Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey("calibration.startTime"), "calibration.startTime(double)");

  const double lastLineTime = Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey("calibration.stopTime"), "calibration.stopTime(double)");

  const std::string bandPrefix = "Band[0]."; //make && use GetBandPrefix(subSwath, polarisation)

  const int numOfLines = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey(bandPrefix + "number_lines"), bandPrefix + "number_lines(int)");

  const int count = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey("calibration.count"), "calibration.count");

  std::vector<Sentinel1CalibrationStruct> calibrationVectorList(count);

  for(int i = 0; i < count; i++)
    {
    Sentinel1CalibrationStruct calibrationVector;

    std::stringstream prefix;
    prefix << "calibration.calibrationVector[" << i << "].";

    calibrationVector.line = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey(prefix.str() + "line"), prefix.str() + "line");

    calibrationVector.timeMJD =  Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey(prefix.str() + "azimuthTime"), prefix.str() + "azimuthTime");

    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "pixel"), calibrationVector.pixels, prefix.str() + "pixel");

    if (sigmaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "sigmaNought"), calibrationVector.vect, prefix.str() + "sigmaNought");
      }

    if (betaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "betaNought"), calibrationVector.vect, prefix.str() + "betaNought");
    }

    if (gammaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "gamma"), calibrationVector.vect, prefix.str() + "gamma");
    }

    if (dnLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "dn"), calibrationVector.vect, prefix.str() + "dn");
    }

    calibrationVectorList[i] = calibrationVector;

    }

  Sentinel1CalibrationLookupData::Pointer sarLut;
  sarLut = Sentinel1CalibrationLookupData::New();
  sarLut->InitParameters(type, firstLineTime, lastLineTime, numOfLines, count, calibrationVectorList);
  this->SetCalibrationLookupData(sarLut);

  }

void
Sentinel1ImageMetadataInterface
::ParseDateTime(const char* key, std::vector<int>& dateFields) const
{
  if(dateFields.size() < 1 )
    {
    //parse from keyword list
    if (!this->CanRead())
      {
      itkExceptionMacro(<< "Invalid Metadata, not a valid product");
      }

    const ImageKeywordlistType imageKeywordlist  = this->GetImageKeywordlist();
    if (!imageKeywordlist.HasKey(key))
      {
      itkExceptionMacro( << "no key named " << key );
      }

    const std::string date_time_str = imageKeywordlist.GetMetadataByKey(key);
    Utils::ConvertStringToVector(date_time_str, dateFields, key, " T:-.");
    }

}

int
Sentinel1ImageMetadataInterface::GetYear() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 0 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[0], " support_data.image_date:year(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid year" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetMonth() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 1 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[1], " support_data.image_date:month(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid month" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetDay() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 2 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[2], " support_data.image_date:day(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid day" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetHour() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 3 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[3], " support_data.image_date:hour(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid hour" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetMinute() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 4 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[4], " support_data.image_date:minute(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid minute" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetProductionYear() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 0 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[0], " support_data.date:year(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production year" );
    }
  return value;

}

int
Sentinel1ImageMetadataInterface::GetProductionMonth() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 1 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[1], " support_data.date:month(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production month" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetProductionDay() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 2 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[2], " support_data.date:day(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production day" );
    }
  return value;
}

double
Sentinel1ImageMetadataInterface::GetPRF() const
{
  double value = 0;
  const ImageKeywordlistType imageKeywordlist  = this->GetImageKeywordlist();
  if (!imageKeywordlist.HasKey("support_data.pulse_repetition_frequency"))
    {
    return value;
    }

  value = Utils::LexicalCast<double>( imageKeywordlist.GetMetadataByKey("support_data.pulse_repetition_frequency"),
                                      "support_data.pulse_repetition_frequency(double)" );

  return value;
}

Sentinel1ImageMetadataInterface::UIntVectorType
Sentinel1ImageMetadataInterface::GetDefaultDisplay() const
{
  UIntVectorType rgb(3);
  rgb[0] = 0;
  rgb[1] = 0;
  rgb[2] = 0;
  return rgb;
}

double
Sentinel1ImageMetadataInterface::GetRSF() const
{
  return 0;
}

double
Sentinel1ImageMetadataInterface::GetRadarFrequency() const
{
  return 0;
}

double
Sentinel1ImageMetadataInterface::GetCenterIncidenceAngle() const
{
  return 0;
}

} // end namespace otb
<commit_msg>ENH: remove extra space in the errmsg argument<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSarImageMetadataInterface.h"
#include "otbSentinel1ImageMetadataInterface.h"

#include "otbMacro.h"
#include "itkMetaDataObject.h"
#include "otbImageKeywordlist.h"

//useful constants
#include <otbMath.h>

namespace otb
{

Sentinel1ImageMetadataInterface
::Sentinel1ImageMetadataInterface()
{

}

bool
Sentinel1ImageMetadataInterface::CanRead() const
{
  std::string sensorID = GetSensorID();

  if (sensorID.find("SENTINEL-1") != std::string::npos)
    {
    return true;
    }
  else
    return false;
}

void
Sentinel1ImageMetadataInterface
::CreateCalibrationLookupData(const short type)
  {
    bool sigmaLut = false;
    bool betaLut = false;
    bool gammaLut = false;
    bool dnLut = false;

    switch (type)
      {
      case SarCalibrationLookupData::BETA:
      {
      betaLut = true;
      }
      break;

      case SarCalibrationLookupData::GAMMA:
      {
      gammaLut = true;
      }
      break;

      case SarCalibrationLookupData::DN:
      {
      dnLut = true;
      }
      break;

      case SarCalibrationLookupData::SIGMA:
      default:
        sigmaLut = true;
        break;
      }

  const ImageKeywordlistType imageKeywordlist =  this->GetImageKeywordlist();

  const double firstLineTime = Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey("calibration.startTime"), "calibration.startTime(double)");

  const double lastLineTime = Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey("calibration.stopTime"), "calibration.stopTime(double)");

  const std::string bandPrefix = "Band[0]."; //make && use GetBandPrefix(subSwath, polarisation)

  const int numOfLines = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey(bandPrefix + "number_lines"), bandPrefix + "number_lines(int)");

  const int count = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey("calibration.count"), "calibration.count");

  std::vector<Sentinel1CalibrationStruct> calibrationVectorList(count);

  for(int i = 0; i < count; i++)
    {
    Sentinel1CalibrationStruct calibrationVector;

    std::stringstream prefix;
    prefix << "calibration.calibrationVector[" << i << "].";

    calibrationVector.line = Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey(prefix.str() + "line"), prefix.str() + "line");

    calibrationVector.timeMJD =  Utils::LexicalCast<double>(imageKeywordlist.GetMetadataByKey(prefix.str() + "azimuthTime"), prefix.str() + "azimuthTime");

    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "pixel"), calibrationVector.pixels, prefix.str() + "pixel");

    if (sigmaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "sigmaNought"), calibrationVector.vect, prefix.str() + "sigmaNought");
      }

    if (betaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "betaNought"), calibrationVector.vect, prefix.str() + "betaNought");
    }

    if (gammaLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "gamma"), calibrationVector.vect, prefix.str() + "gamma");
    }

    if (dnLut) {
    Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey(prefix.str() + "dn"), calibrationVector.vect, prefix.str() + "dn");
    }

    calibrationVectorList[i] = calibrationVector;

    }

  Sentinel1CalibrationLookupData::Pointer sarLut;
  sarLut = Sentinel1CalibrationLookupData::New();
  sarLut->InitParameters(type, firstLineTime, lastLineTime, numOfLines, count, calibrationVectorList);
  this->SetCalibrationLookupData(sarLut);

  }

void
Sentinel1ImageMetadataInterface
::ParseDateTime(const char* key, std::vector<int>& dateFields) const
{
  if(dateFields.size() < 1 )
    {
    //parse from keyword list
    if (!this->CanRead())
      {
      itkExceptionMacro(<< "Invalid Metadata, not a valid product");
      }

    const ImageKeywordlistType imageKeywordlist  = this->GetImageKeywordlist();
    if (!imageKeywordlist.HasKey(key))
      {
      itkExceptionMacro( << "no key named " << key );
      }

    const std::string date_time_str = imageKeywordlist.GetMetadataByKey(key);
    Utils::ConvertStringToVector(date_time_str, dateFields, key, "T:-.");
    }

}

int
Sentinel1ImageMetadataInterface::GetYear() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 0 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[0], "support_data.image_date:year(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid year" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetMonth() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 1 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[1], "support_data.image_date:month(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid month" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetDay() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 2 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[2], "support_data.image_date:day(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid day" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetHour() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 3 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[3], "support_data.image_date:hour(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid hour" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetMinute() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if(m_AcquisitionDateFields.size() > 4 )
    {
    value = Utils::LexicalCast<int>( m_AcquisitionDateFields[4], "support_data.image_date:minute(int)");
    }
  else
    {
    itkExceptionMacro( << "Invalid minute" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetProductionYear() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 0 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[0], "support_data.date:year(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production year" );
    }
  return value;

}

int
Sentinel1ImageMetadataInterface::GetProductionMonth() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 1 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[1], "support_data.date:month(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production month" );
    }
  return value;
}

int
Sentinel1ImageMetadataInterface::GetProductionDay() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if(m_ProductionDateFields.size() > 2 )
    {
    value = Utils::LexicalCast<int>( m_ProductionDateFields[2], "support_data.date:day(int)" );
    }
  else
    {
    itkExceptionMacro( << "Invalid production day" );
    }
  return value;
}

double
Sentinel1ImageMetadataInterface::GetPRF() const
{
  double value = 0;
  const ImageKeywordlistType imageKeywordlist  = this->GetImageKeywordlist();
  if (!imageKeywordlist.HasKey("support_data.pulse_repetition_frequency"))
    {
    return value;
    }

  value = Utils::LexicalCast<double>( imageKeywordlist.GetMetadataByKey("support_data.pulse_repetition_frequency"),
                                      "support_data.pulse_repetition_frequency(double)" );

  return value;
}

Sentinel1ImageMetadataInterface::UIntVectorType
Sentinel1ImageMetadataInterface::GetDefaultDisplay() const
{
  UIntVectorType rgb(3);
  rgb[0] = 0;
  rgb[1] = 0;
  rgb[2] = 0;
  return rgb;
}

double
Sentinel1ImageMetadataInterface::GetRSF() const
{
  return 0;
}

double
Sentinel1ImageMetadataInterface::GetRadarFrequency() const
{
  return 0;
}

double
Sentinel1ImageMetadataInterface::GetCenterIncidenceAngle() const
{
  return 0;
}

} // end namespace otb
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#include "XMLSectionFootnoteConfigImport.hxx"
#endif

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

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_PROPMAPPINGTYPES_HXX
#include <xmloff/maptype.hxx>
#endif

#ifndef _XMLOFF_XMLNUMI_HXX
#include <xmloff/xmlnumi.hxx>
#endif

#ifndef _XMLOFF_TEXTPRMAP_HXX_
#include <xmloff/txtprmap.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include <vector>

using namespace ::xmloff::token;
using namespace ::com::sun::star::style;

using ::rtl::OUString;
using ::std::vector;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;

TYPEINIT1(XMLSectionFootnoteConfigImport, SvXMLImportContext);

XMLSectionFootnoteConfigImport::XMLSectionFootnoteConfigImport(
    SvXMLImport& rImport,
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    vector<XMLPropertyState> & rProps,
    const UniReference<XMLPropertySetMapper> & rMapperRef) :
        SvXMLImportContext(rImport, nPrefix, rLocalName),
        rProperties(rProps),
        rMapper(rMapperRef)
{
}

XMLSectionFootnoteConfigImport::~XMLSectionFootnoteConfigImport()
{
}

void XMLSectionFootnoteConfigImport::StartElement(
    const Reference<XAttributeList> & xAttrList)
{
    sal_Bool bEnd = sal_True;   // we're inside the element, so this is true
    sal_Bool bNumOwn = sal_False;
    sal_Bool bNumRestart = sal_False;
    sal_Bool bEndnote = sal_False;
    sal_Int16 nNumRestartAt = 0;
    OUString sNumPrefix;
    OUString sNumSuffix;
    OUString sNumFormat;
    OUString sNumLetterSync;

    // iterate over xattribute list and fill values
    sal_Int16 nLength = xAttrList->getLength();
    for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
                              &sLocalName );
        OUString sAttrValue = xAttrList->getValueByIndex(nAttr);

        if (XML_NAMESPACE_TEXT == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_START_VALUE))
            {
                sal_Int32 nTmp;
                if (SvXMLUnitConverter::convertNumber(nTmp, sAttrValue))
                {
                    nNumRestartAt = static_cast< sal_Int16 >( nTmp ) - 1;
                    bNumRestart = sal_True;
                }
            }
            else if( IsXMLToken( sLocalName, XML_NOTE_CLASS ) )
            {
                if( IsXMLToken( sAttrValue, XML_ENDNOTE ) )
                    bEndnote = sal_True;
            }
        }
        else if (XML_NAMESPACE_STYLE == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_NUM_PREFIX))
            {
                sNumPrefix = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_SUFFIX))
            {
                sNumSuffix = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_FORMAT))
            {
                sNumFormat = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_LETTER_SYNC))
            {
                sNumLetterSync = sAttrValue;
                bNumOwn = sal_True;
            }
        }
    }

    // OK, now we have all values and can fill the XMLPropertyState vector
    Any aAny;

    aAny.setValue( &bNumOwn, ::getBooleanCppuType() );
    sal_Int32 nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_OWN : CTF_SECTION_FOOTNOTE_NUM_OWN );
    XMLPropertyState aNumOwn( nIndex, aAny );
    rProperties.push_back( aNumOwn );

    aAny.setValue( &bNumRestart, ::getBooleanCppuType() );
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_RESTART : CTF_SECTION_FOOTNOTE_NUM_RESTART );
    XMLPropertyState aNumRestart( nIndex, aAny );
    rProperties.push_back( aNumRestart );

    aAny <<= nNumRestartAt;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_RESTART_AT :
        CTF_SECTION_FOOTNOTE_NUM_RESTART_AT );
    XMLPropertyState aNumRestartAtState( nIndex, aAny );
    rProperties.push_back( aNumRestartAtState );

    sal_Int16 nNumType = NumberingType::ARABIC;
    GetImport().GetMM100UnitConverter().convertNumFormat( nNumType,
                                                    sNumFormat,
                                                    sNumLetterSync );
    aAny <<= nNumType;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_TYPE : CTF_SECTION_FOOTNOTE_NUM_TYPE );
    XMLPropertyState aNumFormatState( nIndex, aAny );
    rProperties.push_back( aNumFormatState );

    aAny <<= sNumPrefix;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_PREFIX : CTF_SECTION_FOOTNOTE_NUM_PREFIX );
    XMLPropertyState aPrefixState( nIndex, aAny );
    rProperties.push_back( aPrefixState );

    aAny <<= sNumSuffix;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_SUFFIX : CTF_SECTION_FOOTNOTE_NUM_SUFFIX );
    XMLPropertyState aSuffixState( nIndex, aAny );
    rProperties.push_back( aSuffixState );

    aAny.setValue( &bEnd, ::getBooleanCppuType() );
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_END : CTF_SECTION_FOOTNOTE_END );
    XMLPropertyState aEndState( nIndex, aAny );
    rProperties.push_back( aEndState );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.162); FILE MERGED 2008/04/01 16:10:10 thb 1.9.162.3: #i85898# Stripping all external header guards 2008/04/01 13:05:28 thb 1.9.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:35 rt 1.9.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: XMLSectionFootnoteConfigImport.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLSectionFootnoteConfigImport.hxx"

#ifndef _RTL_USTRING
#include <rtl/ustring.hxx>
#endif
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/style/NumberingType.hpp>
#include <xmloff/xmlimp.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmluconv.hxx>
#include <xmloff/xmlprmap.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#include <xmloff/maptype.hxx>
#include <xmloff/xmlnumi.hxx>
#include <xmloff/txtprmap.hxx>
#include <tools/debug.hxx>

#include <vector>

using namespace ::xmloff::token;
using namespace ::com::sun::star::style;

using ::rtl::OUString;
using ::std::vector;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;

TYPEINIT1(XMLSectionFootnoteConfigImport, SvXMLImportContext);

XMLSectionFootnoteConfigImport::XMLSectionFootnoteConfigImport(
    SvXMLImport& rImport,
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    vector<XMLPropertyState> & rProps,
    const UniReference<XMLPropertySetMapper> & rMapperRef) :
        SvXMLImportContext(rImport, nPrefix, rLocalName),
        rProperties(rProps),
        rMapper(rMapperRef)
{
}

XMLSectionFootnoteConfigImport::~XMLSectionFootnoteConfigImport()
{
}

void XMLSectionFootnoteConfigImport::StartElement(
    const Reference<XAttributeList> & xAttrList)
{
    sal_Bool bEnd = sal_True;   // we're inside the element, so this is true
    sal_Bool bNumOwn = sal_False;
    sal_Bool bNumRestart = sal_False;
    sal_Bool bEndnote = sal_False;
    sal_Int16 nNumRestartAt = 0;
    OUString sNumPrefix;
    OUString sNumSuffix;
    OUString sNumFormat;
    OUString sNumLetterSync;

    // iterate over xattribute list and fill values
    sal_Int16 nLength = xAttrList->getLength();
    for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
                              &sLocalName );
        OUString sAttrValue = xAttrList->getValueByIndex(nAttr);

        if (XML_NAMESPACE_TEXT == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_START_VALUE))
            {
                sal_Int32 nTmp;
                if (SvXMLUnitConverter::convertNumber(nTmp, sAttrValue))
                {
                    nNumRestartAt = static_cast< sal_Int16 >( nTmp ) - 1;
                    bNumRestart = sal_True;
                }
            }
            else if( IsXMLToken( sLocalName, XML_NOTE_CLASS ) )
            {
                if( IsXMLToken( sAttrValue, XML_ENDNOTE ) )
                    bEndnote = sal_True;
            }
        }
        else if (XML_NAMESPACE_STYLE == nPrefix)
        {
            if (IsXMLToken(sLocalName, XML_NUM_PREFIX))
            {
                sNumPrefix = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_SUFFIX))
            {
                sNumSuffix = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_FORMAT))
            {
                sNumFormat = sAttrValue;
                bNumOwn = sal_True;
            }
            else if (IsXMLToken(sLocalName, XML_NUM_LETTER_SYNC))
            {
                sNumLetterSync = sAttrValue;
                bNumOwn = sal_True;
            }
        }
    }

    // OK, now we have all values and can fill the XMLPropertyState vector
    Any aAny;

    aAny.setValue( &bNumOwn, ::getBooleanCppuType() );
    sal_Int32 nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_OWN : CTF_SECTION_FOOTNOTE_NUM_OWN );
    XMLPropertyState aNumOwn( nIndex, aAny );
    rProperties.push_back( aNumOwn );

    aAny.setValue( &bNumRestart, ::getBooleanCppuType() );
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_RESTART : CTF_SECTION_FOOTNOTE_NUM_RESTART );
    XMLPropertyState aNumRestart( nIndex, aAny );
    rProperties.push_back( aNumRestart );

    aAny <<= nNumRestartAt;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_RESTART_AT :
        CTF_SECTION_FOOTNOTE_NUM_RESTART_AT );
    XMLPropertyState aNumRestartAtState( nIndex, aAny );
    rProperties.push_back( aNumRestartAtState );

    sal_Int16 nNumType = NumberingType::ARABIC;
    GetImport().GetMM100UnitConverter().convertNumFormat( nNumType,
                                                    sNumFormat,
                                                    sNumLetterSync );
    aAny <<= nNumType;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_TYPE : CTF_SECTION_FOOTNOTE_NUM_TYPE );
    XMLPropertyState aNumFormatState( nIndex, aAny );
    rProperties.push_back( aNumFormatState );

    aAny <<= sNumPrefix;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_PREFIX : CTF_SECTION_FOOTNOTE_NUM_PREFIX );
    XMLPropertyState aPrefixState( nIndex, aAny );
    rProperties.push_back( aPrefixState );

    aAny <<= sNumSuffix;
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_NUM_SUFFIX : CTF_SECTION_FOOTNOTE_NUM_SUFFIX );
    XMLPropertyState aSuffixState( nIndex, aAny );
    rProperties.push_back( aSuffixState );

    aAny.setValue( &bEnd, ::getBooleanCppuType() );
    nIndex = rMapper->FindEntryIndex( bEndnote ?
        CTF_SECTION_ENDNOTE_END : CTF_SECTION_FOOTNOTE_END );
    XMLPropertyState aEndState( nIndex, aAny );
    rProperties.push_back( aEndState );
}
<|endoftext|>


<commit_before>/**
 * \file TubeFilter.cpp
 */

#include "TubeFilter.h"

#include <cassert>

#include <ATK/Utility/SimplifiedVectorizedNewtonRaphson.h>
#include <ATK/Utility/VectorizedNewtonRaphson.h>

namespace ATK
{
  template <typename DataType_>
  class TubeFunction
  {
  protected:
    const DataType_ mu;
    const DataType_ K;
    const DataType_ Kp;
    const DataType_ Kvb;
    const DataType_ Kg;
    const DataType_ Ex;

    DataType_ Lb(DataType_ Vbe, DataType_ Vce)
    {
      if(mu * Vbe + Vce > 0)
        return K * std::pow(mu * Vbe + Vce, 1.5);
      return 0;
    }

    DataType_ Lb_Vbe(DataType_ Vbe, DataType_ Vce)
    {
      if (mu * Vbe + Vce > 0)
        return 0;
      return 0;
    }

    DataType_ Lb_Vce(DataType_ Vbe, DataType_ Vce)
    {
      if (mu * Vbe + Vce > 0)
        return 0;
      return 0;
    }

    DataType_ Lc(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
      {
        DataType_ E1 = Vce / Kp * std::log(1 + std::exp(Kp * (1/mu + Vbe / std::sqrt(Kvb + Vce * Vce))));
        return 2 / Kg * std::pow(E1, Ex);
      }
      return 0;
    }

    DataType_ Lc_Vbe(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
        return 0;
      return 0;
    }

    DataType_ Lc_Vce(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
        return 0;
      return 0;
    }

    TubeFunction(DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :mu(mu), K(K), Kp(Kp), Kvb(Kvb), Kg(Kg), Ex(Ex)
    {
    }

  };

  template <typename DataType_>
  class TubeFilter<DataType_>::CommonCathodeTriodeFunction : public TubeFunction<DataType_>
  {
    const DataType_ dt;

    const DataType_ Rp;
    const DataType_ Rg;
    const DataType_ Ro;
    const DataType_ Rk;
    const DataType_ VBias;
    const DataType_ Co;
    const DataType_ Ck;

  public:
    typedef DataType_ DataType;
    typedef Eigen::Matrix<DataType, 4, 1> Vector;
    typedef Eigen::Matrix<DataType, 4, 4> Matrix;

    CommonCathodeTriodeFunction(DataType dt, DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType Co, DataType Ck, DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :TubeFunction<DataType_>(mu, K, Kp, Kvb, Kg, Ex), dt(dt), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias), Co(Co), Ck(Ck)
    {
    }

    Vector estimate(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)
    {
      Vector y0 = Vector::Zero();
      for(int j = 0; j < 4; ++j)
      {
        y0.data()[j] = output[j][i-1];
      }

      return y0;
    }

    std::pair<Vector, Matrix> operator()(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output, const Vector& y1)
    {
      auto Ib_old = Lb(output[3][i-1] - output[0][i-1], output[2][i-1] - output[0][i-1]);
      auto Ic_old = Lc(output[3][i-1] - output[0][i-1], output[2][i-1] - output[0][i-1]);

      auto Ib = Lb(y1(3) - y1(0), y1(2) - y1(0));
      auto Ic = Lc(y1(3) - y1(0), y1(2) - y1(0));

      auto Ib_Vbe = Lb_Vbe(y1(3) - y1(0), y1(2) - y1(0));
      auto Ib_Vce = Lb_Vce(y1(3) - y1(0), y1(2) - y1(0));

      auto Ic_Vbe = Lc_Vbe(y1(3) - y1(0), y1(2) - y1(0));
      auto Ic_Vce = Lc_Vce(y1(3) - y1(0), y1(2) - y1(0));

      auto f1_old = - output[0][i-1] / (Rk * Ck) + (Ib_old + Ic_old) / Ck;
      auto f2_old = - (output[1][i-1] + output[2][i-1]) / (Ro * Co);

      auto f1 = - y1(0) / (Rk * Ck) + (Ib + Ic) / Ck;
      auto f2 = - (y1(1) + y1(2)) / (Ro * Co);

      auto g1 = y1(2) + Rp * (Ic + (y1(1) + y1(2)) / Ro) - VBias;
      auto g2 = y1(3) - input[0][i] + Rg * Ib;

      Vector F(Vector::Zero());
      F << (dt / 2 * (f1 + f1_old) + output[0][i-1] - y1(0)),
           (dt / 2 * (f2 + f2_old) + output[1][i-1] - y1(1)),
           (g1),
           (g2);

      Matrix M(Matrix::Zero());
      M << (-1 -dt/2/(Rk * Ck)) - dt/2*((Ib_Vbe + Ic_Vbe + Ib_Vce + Ic_Vce)/ Ck), 0, dt/2*(Ib_Vce + Ic_Vce) / Ck, dt/2*(Ib_Vbe + Ic_Vbe) / Ck,
            0, -1 -dt/2*(Ro * Co), -dt/2*(Ro * Co), 0,
            -Rp * (Ic_Vbe + Ic_Vce), Rp / Ro, 1 + Rp / Ro + Rp * Ic_Vce, Rp * Ic_Vbe,
            -Rg * (Ib_Vbe + Ib_Vce), 0, Rg * Ib_Vce, Rg * Ib_Vbe + 1;

      return std::make_pair(F, M);
    }

  };

  template <typename DataType_>
  class CommonCathodeTriodeInitialFunction : public TubeFunction<DataType_>
  {
    const DataType_ Rp;
    const DataType_ Rg;
    const DataType_ Ro;
    const DataType_ Rk;
    const DataType_ VBias;

  public:
    typedef DataType_ DataType;
    typedef Eigen::Matrix<DataType, 3, 1> Vector;
    typedef Eigen::Matrix<DataType, 3, 3> Matrix;

    CommonCathodeTriodeInitialFunction(DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :TubeFunction<DataType_>(mu, K, Kp, Kvb, Kg, Ex), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias)
    {
    }

    std::pair<Vector, Matrix> operator()(const Vector& y1)
    {
      auto Ib = Lb(y1(0) - y1(1), y1(0) - y1(2));
      auto Ic = Lc(y1(0) - y1(1), y1(0) - y1(2));

      auto Ib_Vbe = Lb_Vbe(y1(0) - y1(1), y1(0) - y1(2));
      auto Ib_Vce = Lb_Vce(y1(0) - y1(1), y1(0) - y1(2));

      auto Ic_Vbe = Lc_Vbe(y1(0) - y1(1), y1(0) - y1(2));
      auto Ic_Vce = Lc_Vce(y1(0) - y1(1), y1(0) - y1(2));

      Vector F(Vector::Zero());
      F << y1(0) - VBias + Ic * Rp,
        Ib * Rg + y1(1),
        y1(2) - (Ib + Ic) * Rk;

      Matrix M(Matrix::Zero());
      M << 1 + Rp * (Ic_Vbe + Ic_Vce), -Rp * Ic_Vbe, -Rp * Ic_Vce,
        (Ib_Vbe + Ib_Vce) * Rg, 1 - Rg * Ib_Vbe, -Rg * Ib_Vce,
        -(Ic_Vbe + Ic_Vce + Ib_Vbe + Ib_Vce) * Rk, (Ic_Vbe + Ib_Vbe) * Rk, 1 + (Ic_Vce + Ib_Vce) * Rk;

      return std::make_pair(F, M);
    }
  };

  template <typename DataType>
  TubeFilter<DataType>::TubeFilter(DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType Co, DataType Ck, DataType mu, DataType K, DataType Kp, DataType Kvb, DataType Kg, DataType Ex)
    :Parent(1, 5), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias), Co(Co), Ck(Ck), mu(mu), K(K), Kp(Kp), Kvb(Kvb), Kg(Kg), Ex(Ex)
  {
    input_delay = output_delay = 1;
  }

  template <typename DataType>
  TubeFilter<DataType>::TubeFilter(TubeFilter&& other)
    :Parent(std::move(other)), Rp(other.Rp), Rg(other.Rg), Ro(other.Ro), Rk(other.Rk), VBias(other.VBias), Co(other.Co), Ck(other.Ck), mu(other.mu), K(other.K), Kp(other.Kp), Kvb(other.Kvb), Kg(other.Kg), Ex(other.Ex)
  {
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::setup()
  {
    Parent::setup();
    optimizer.reset(new VectorizedNewtonRaphson<CommonCathodeTriodeFunction, 4, 10, true>(CommonCathodeTriodeFunction(static_cast<DataType>(1. / input_sampling_rate),
      Rp, Rg, Ro, Rk, //R
      VBias, // VBias
      Co, Ck, // C
      mu, K, Kp, Kvb, Kg, Ex // tube
      )));
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::full_setup()
  {
    Parent::full_setup();
    // setup default_output

    SimplifiedVectorizedNewtonRaphson<CommonCathodeTriodeInitialFunction<DataType_>, 3, 10> custom(CommonCathodeTriodeInitialFunction<DataType_>(
      Rp, Rg, Ro, Rk, //R
      VBias, // VBias
      mu, K, Kp, Kvb, Kg, Ex // tube
      ));

    auto stable = custom.optimize();

    default_output[0] = 0;
    default_output[1] = stable(2);
    default_output[2] = -stable(0);
    default_output[3] = stable(0);
    default_output[4] = stable(1);
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::process_impl(int64_t size) const
  {
    assert(input_sampling_rate == output_sampling_rate);

    for(int64_t i = 0; i < size; ++i)
    {
      optimizer->optimize(i, converted_inputs.data(), outputs.data() + 1);
      outputs[0][i] = outputs[2][i] + outputs[3][i];
    }
  }

  template<typename DataType_>
  TubeFilter<DataType_> TubeFilter<DataType_>::build_standard_filter()
  {
    return TubeFilter<DataType_>(100e3, 220e3, 22e3, 2.7e3, //R
      400, // VBias
      20e-9, 10e-6, // C
      88.5, 1.73e-6, 600, 300, 1060, 1.4 // transistor
      );
  }

  template class TubeFilter<float>;
  template class TubeFilter<double>;
}
<commit_msg>First one should be easy enough!<commit_after>/**
 * \file TubeFilter.cpp
 */

#include "TubeFilter.h"

#include <cassert>

#include <ATK/Utility/SimplifiedVectorizedNewtonRaphson.h>
#include <ATK/Utility/VectorizedNewtonRaphson.h>

namespace ATK
{
  template <typename DataType_>
  class TubeFunction
  {
  protected:
    const DataType_ mu;
    const DataType_ K;
    const DataType_ Kp;
    const DataType_ Kvb;
    const DataType_ Kg;
    const DataType_ Ex;

    DataType_ Lb(DataType_ Vbe, DataType_ Vce)
    {
      if(mu * Vbe + Vce > 0)
        return K * std::pow(mu * Vbe + Vce, 1.5);
      return 0;
    }

    DataType_ Lb_Vbe(DataType_ Vbe, DataType_ Vce)
    {
      if (mu * Vbe + Vce > 0)
        return K * mu * 1.5 * std::sqrt(mu * Vbe + Vce);
      return 0;
    }

    DataType_ Lb_Vce(DataType_ Vbe, DataType_ Vce)
    {
      if (mu * Vbe + Vce > 0)
        return K * 1.5 * std::sqrt(mu * Vbe + Vce);;
      return 0;
    }

    DataType_ Lc(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
      {
        DataType_ E1 = Vce / Kp * std::log(1 + std::exp(Kp * (1/mu + Vbe / std::sqrt(Kvb + Vce * Vce))));
        return 2 / Kg * std::pow(E1, Ex);
      }
      return 0;
    }

    DataType_ Lc_Vbe(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
        return 0;
      return 0;
    }

    DataType_ Lc_Vce(DataType_ Vbe, DataType_ Vce)
    {
      if (Vce > 0)
        return 0;
      return 0;
    }

    TubeFunction(DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :mu(mu), K(K), Kp(Kp), Kvb(Kvb), Kg(Kg), Ex(Ex)
    {
    }

  };

  template <typename DataType_>
  class TubeFilter<DataType_>::CommonCathodeTriodeFunction : public TubeFunction<DataType_>
  {
    const DataType_ dt;

    const DataType_ Rp;
    const DataType_ Rg;
    const DataType_ Ro;
    const DataType_ Rk;
    const DataType_ VBias;
    const DataType_ Co;
    const DataType_ Ck;

  public:
    typedef DataType_ DataType;
    typedef Eigen::Matrix<DataType, 4, 1> Vector;
    typedef Eigen::Matrix<DataType, 4, 4> Matrix;

    CommonCathodeTriodeFunction(DataType dt, DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType Co, DataType Ck, DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :TubeFunction<DataType_>(mu, K, Kp, Kvb, Kg, Ex), dt(dt), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias), Co(Co), Ck(Ck)
    {
    }

    Vector estimate(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)
    {
      Vector y0 = Vector::Zero();
      for(int j = 0; j < 4; ++j)
      {
        y0.data()[j] = output[j][i-1];
      }

      return y0;
    }

    std::pair<Vector, Matrix> operator()(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output, const Vector& y1)
    {
      auto Ib_old = Lb(output[3][i-1] - output[0][i-1], output[2][i-1] - output[0][i-1]);
      auto Ic_old = Lc(output[3][i-1] - output[0][i-1], output[2][i-1] - output[0][i-1]);

      auto Ib = Lb(y1(3) - y1(0), y1(2) - y1(0));
      auto Ic = Lc(y1(3) - y1(0), y1(2) - y1(0));

      auto Ib_Vbe = Lb_Vbe(y1(3) - y1(0), y1(2) - y1(0));
      auto Ib_Vce = Lb_Vce(y1(3) - y1(0), y1(2) - y1(0));

      auto Ic_Vbe = Lc_Vbe(y1(3) - y1(0), y1(2) - y1(0));
      auto Ic_Vce = Lc_Vce(y1(3) - y1(0), y1(2) - y1(0));

      auto f1_old = - output[0][i-1] / (Rk * Ck) + (Ib_old + Ic_old) / Ck;
      auto f2_old = - (output[1][i-1] + output[2][i-1]) / (Ro * Co);

      auto f1 = - y1(0) / (Rk * Ck) + (Ib + Ic) / Ck;
      auto f2 = - (y1(1) + y1(2)) / (Ro * Co);

      auto g1 = y1(2) + Rp * (Ic + (y1(1) + y1(2)) / Ro) - VBias;
      auto g2 = y1(3) - input[0][i] + Rg * Ib;

      Vector F(Vector::Zero());
      F << (dt / 2 * (f1 + f1_old) + output[0][i-1] - y1(0)),
           (dt / 2 * (f2 + f2_old) + output[1][i-1] - y1(1)),
           (g1),
           (g2);

      Matrix M(Matrix::Zero());
      M << (-1 -dt/2/(Rk * Ck)) - dt/2*((Ib_Vbe + Ic_Vbe + Ib_Vce + Ic_Vce)/ Ck), 0, dt/2*(Ib_Vce + Ic_Vce) / Ck, dt/2*(Ib_Vbe + Ic_Vbe) / Ck,
            0, -1 -dt/2*(Ro * Co), -dt/2*(Ro * Co), 0,
            -Rp * (Ic_Vbe + Ic_Vce), Rp / Ro, 1 + Rp / Ro + Rp * Ic_Vce, Rp * Ic_Vbe,
            -Rg * (Ib_Vbe + Ib_Vce), 0, Rg * Ib_Vce, Rg * Ib_Vbe + 1;

      return std::make_pair(F, M);
    }

  };

  template <typename DataType_>
  class CommonCathodeTriodeInitialFunction : public TubeFunction<DataType_>
  {
    const DataType_ Rp;
    const DataType_ Rg;
    const DataType_ Ro;
    const DataType_ Rk;
    const DataType_ VBias;

  public:
    typedef DataType_ DataType;
    typedef Eigen::Matrix<DataType, 3, 1> Vector;
    typedef Eigen::Matrix<DataType, 3, 3> Matrix;

    CommonCathodeTriodeInitialFunction(DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType_ mu, DataType_ K, DataType_ Kp, DataType_ Kvb, DataType_ Kg, DataType_ Ex)
      :TubeFunction<DataType_>(mu, K, Kp, Kvb, Kg, Ex), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias)
    {
    }

    std::pair<Vector, Matrix> operator()(const Vector& y1)
    {
      auto Ib = Lb(y1(0) - y1(1), y1(0) - y1(2));
      auto Ic = Lc(y1(0) - y1(1), y1(0) - y1(2));

      auto Ib_Vbe = Lb_Vbe(y1(0) - y1(1), y1(0) - y1(2));
      auto Ib_Vce = Lb_Vce(y1(0) - y1(1), y1(0) - y1(2));

      auto Ic_Vbe = Lc_Vbe(y1(0) - y1(1), y1(0) - y1(2));
      auto Ic_Vce = Lc_Vce(y1(0) - y1(1), y1(0) - y1(2));

      Vector F(Vector::Zero());
      F << y1(0) - VBias + Ic * Rp,
        Ib * Rg + y1(1),
        y1(2) - (Ib + Ic) * Rk;

      Matrix M(Matrix::Zero());
      M << 1 + Rp * (Ic_Vbe + Ic_Vce), -Rp * Ic_Vbe, -Rp * Ic_Vce,
        (Ib_Vbe + Ib_Vce) * Rg, 1 - Rg * Ib_Vbe, -Rg * Ib_Vce,
        -(Ic_Vbe + Ic_Vce + Ib_Vbe + Ib_Vce) * Rk, (Ic_Vbe + Ib_Vbe) * Rk, 1 + (Ic_Vce + Ib_Vce) * Rk;

      return std::make_pair(F, M);
    }
  };

  template <typename DataType>
  TubeFilter<DataType>::TubeFilter(DataType Rp, DataType Rg, DataType Ro, DataType Rk, DataType VBias, DataType Co, DataType Ck, DataType mu, DataType K, DataType Kp, DataType Kvb, DataType Kg, DataType Ex)
    :Parent(1, 5), Rp(Rp), Rg(Rg), Ro(Ro), Rk(Rk), VBias(VBias), Co(Co), Ck(Ck), mu(mu), K(K), Kp(Kp), Kvb(Kvb), Kg(Kg), Ex(Ex)
  {
    input_delay = output_delay = 1;
  }

  template <typename DataType>
  TubeFilter<DataType>::TubeFilter(TubeFilter&& other)
    :Parent(std::move(other)), Rp(other.Rp), Rg(other.Rg), Ro(other.Ro), Rk(other.Rk), VBias(other.VBias), Co(other.Co), Ck(other.Ck), mu(other.mu), K(other.K), Kp(other.Kp), Kvb(other.Kvb), Kg(other.Kg), Ex(other.Ex)
  {
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::setup()
  {
    Parent::setup();
    optimizer.reset(new VectorizedNewtonRaphson<CommonCathodeTriodeFunction, 4, 10, true>(CommonCathodeTriodeFunction(static_cast<DataType>(1. / input_sampling_rate),
      Rp, Rg, Ro, Rk, //R
      VBias, // VBias
      Co, Ck, // C
      mu, K, Kp, Kvb, Kg, Ex // tube
      )));
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::full_setup()
  {
    Parent::full_setup();
    // setup default_output

    SimplifiedVectorizedNewtonRaphson<CommonCathodeTriodeInitialFunction<DataType_>, 3, 10> custom(CommonCathodeTriodeInitialFunction<DataType_>(
      Rp, Rg, Ro, Rk, //R
      VBias, // VBias
      mu, K, Kp, Kvb, Kg, Ex // tube
      ));

    auto stable = custom.optimize();

    default_output[0] = 0;
    default_output[1] = stable(2);
    default_output[2] = -stable(0);
    default_output[3] = stable(0);
    default_output[4] = stable(1);
  }

  template<typename DataType_>
  void TubeFilter<DataType_>::process_impl(int64_t size) const
  {
    assert(input_sampling_rate == output_sampling_rate);

    for(int64_t i = 0; i < size; ++i)
    {
      optimizer->optimize(i, converted_inputs.data(), outputs.data() + 1);
      outputs[0][i] = outputs[2][i] + outputs[3][i];
    }
  }

  template<typename DataType_>
  TubeFilter<DataType_> TubeFilter<DataType_>::build_standard_filter()
  {
    return TubeFilter<DataType_>(100e3, 220e3, 22e3, 2.7e3, //R
      400, // VBias
      20e-9, 10e-6, // C
      88.5, 1.73e-6, 600, 300, 1060, 1.4 // transistor
      );
  }

  template class TubeFilter<float>;
  template class TubeFilter<double>;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <pcap.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
#include "util.h"
#include "packetheader.h"
#include "handlepacket.h"

using namespace std;

#define max_number_of_operands 7007

namespace {
	u_int16_t number_of_operands;
	int32_t operands[max_number_of_operands];
	u_int8_t operators[max_number_of_operands-1];                                   // Defined by the MATH_OPERATOR_* constants
	u_int8_t number_of_operators_after_operand[max_number_of_operands];             // The positions of the operators is as required for Reverse Polish Notation.
	int32_t answer = 0;
	const u_int16_t end_packet_magic_number = 21845;
};

int calcans () {
	stack<int> S;
	int operators_iterator = 0;
	int nooao = 0;
	for ( int i = 0; i < number_of_operands; i++ ) {
		S.push(operands[i]);
		nooao = number_of_operators_after_operand[i];
		while ( nooao > 0 ) {
			int b = S.top();
			S.pop();
			int a = S.top();
			S.pop();
			switch ( operators[operators_iterator] ) {
				case MATH_OPERATOR_PLUS:
					S.push(a+b);
					break;
				case MATH_OPERATOR_MINUS:
					S.push(a-b);
					break;
				case MATH_OPERATOR_MULTIPLY:
					S.push(a*b);
					break;
				case MATH_OPERATOR_DIVIDE:
					S.push(a/b);
					break;
				case MATH_OPERATOR_MODULO:
					S.push(a%b);
					break;
				case MATH_OPERATOR_BITWISE_AND:
					S.push(a&b);
					break;
				case MATH_OPERATOR_BITWISE_OR:
					S.push(a|b);
					break;
				case MATH_OPERATOR_BITWISE_XOR:
					S.push(a^b);
					break;
			}
			operators_iterator++;
			nooao--;
		}
	}
	return S.top();
}

void fill_array_from_packet( u_int8_t buffer[] ) {
	int lengthread = 0;
	memcpy(operands,buffer,number_of_operands*4);
	lengthread += number_of_operands*4;
	memcpy(operators,buffer+lengthread,number_of_operands-1);
	lengthread += (number_of_operands-1);
	memcpy(number_of_operators_after_operand,buffer+lengthread,number_of_operands);
	lengthread += number_of_operands;
	memcpy(&answer,buffer+lengthread,4);
}

void server (pcap_t *handle) {
	MathPacketHeader header;
	//get packet
	//send ack
	answer = calcans();
	//send ans
	//wait for ack
}<commit_msg>add function to do various server side functions<commit_after>#include <iostream>
#include <pcap.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
#include "util.h"
#include "packetheader.h"
#include "handlepacket.h"

using namespace std;

#define max_number_of_operands 7007

namespace {
	u_int16_t number_of_operands;
	int32_t operands[max_number_of_operands];
	u_int8_t operators[max_number_of_operands-1];                                   // Defined by the MATH_OPERATOR_* constants
	u_int8_t number_of_operators_after_operand[max_number_of_operands];             // The positions of the operators is as required for Reverse Polish Notation.
	int32_t answer = 0;
	const u_int16_t end_packet_magic_number = 21845;
	u_int32_t user_id_of_requester;
	u_int32_t user_id_of_sender;
	u_int32_t request_id;
};

int calcans () {
	stack<int> S;
	int operators_iterator = 0;
	int nooao = 0;
	for ( int i = 0; i < number_of_operands; i++ ) {
		S.push(operands[i]);
		nooao = number_of_operators_after_operand[i];
		while ( nooao > 0 ) {
			int b = S.top();
			S.pop();
			int a = S.top();
			S.pop();
			switch ( operators[operators_iterator] ) {
				case MATH_OPERATOR_PLUS:
					S.push(a+b);
					break;
				case MATH_OPERATOR_MINUS:
					S.push(a-b);
					break;
				case MATH_OPERATOR_MULTIPLY:
					S.push(a*b);
					break;
				case MATH_OPERATOR_DIVIDE:
					S.push(a/b);
					break;
				case MATH_OPERATOR_MODULO:
					S.push(a%b);
					break;
				case MATH_OPERATOR_BITWISE_AND:
					S.push(a&b);
					break;
				case MATH_OPERATOR_BITWISE_OR:
					S.push(a|b);
					break;
				case MATH_OPERATOR_BITWISE_XOR:
					S.push(a^b);
					break;
			}
			operators_iterator++;
			nooao--;
		}
	}
	return S.top();
}

void fill_array_from_packet( u_int8_t buffer[] ) {
	int lengthread = 0;
	memcpy(operands,buffer,number_of_operands*4);
	lengthread += number_of_operands*4;
	memcpy(operators,buffer+lengthread,number_of_operands-1);
	lengthread += (number_of_operands-1);
	memcpy(number_of_operators_after_operand,buffer+lengthread,number_of_operands);
	lengthread += number_of_operands;
	memcpy(&answer,buffer+lengthread,4);
}

namespace {
	void send_packet ( pcap_t *handle, MathPacketHeader header ) {
		u_int8_t buffer[900];
		if ( header.type_of_packet == MATH_TYPE_SEND_ANSWER ) {
			int packet_size = 0;
			memcpy(buffer,operands,number_of_operands*4);
			packet_size += number_of_operands*4;
			memcpy(buffer+packet_size,operators,number_of_operands-1);
			packet_size += (number_of_operands-1);
			memcpy(buffer+packet_size,number_of_operators_after_operand,number_of_operands);
			packet_size += number_of_operands;
			memcpy(buffer+packet_size,&answer,4);
			packet_size += 4;
			memcpy(buffer+packet_size,&end_packet_magic_number,2);
			packet_size += 2;
			send_packet_with_data(handle,header,buffer,packet_size);
		} else if ( header.type_of_packet == MATH_TYPE_ACK_REQUEST ) {
			send_ack_packet(handle,header);
		}
	}

	bool get_ack (pcap_t *handle) {
		MathPacketHeader temphead;
		return ( get_ack_packet(handle,&temphead) &&
				 temphead.type_of_packet == MATH_TYPE_ACK_ANSWER &&
				 is_request_id_same(temphead,request_id) );
	}

	bool get_req_packet (pcap_t *handle, MathPacketHeader *header, u_int8_t pktbuf[]) {
		return ( get_packet(handle,header,pktbuf) &&
				 header->type_of_packet == MATH_TYPE_REQUEST);
	}
};

void server (pcap_t *handle) {
	MathPacketHeader header;
	u_int8_t buffer[1000];
	user_id_of_sender = get_user_id_of_sender();
	user_id_of_requester = 0;
	request_id = 0;
	//get packet
	while ( !get_req_packet(handle,&header,buffer) );
	display_message_related_to_packet("Answer requested by a client.");
	header.user_id_of_sender = user_id_of_sender;
	user_id_of_requester = header.user_id_of_requester;
	request_id = header.request_id;
	number_of_operands = header.number_of_operands;
	fill_array_from_packet(buffer);
	display_message_related_to_packet("Sending request arrived acknowledgement.");
	for ( int i = 0; i < 1000; i++ ) {
		header.type_of_packet = MATH_TYPE_ACK_REQUEST;
		send_packet(handle,header);
	}
	display_message_related_to_packet("Calulating answer.");
	answer = calcans();
	display_message_related_to_packet("Sending answer to the client.");
	header.type_of_packet = MATH_TYPE_SEND_ANSWER;
	send_packet(handle,header);
	int c = 0;
	while ( !get_ack(handle) ) {
		header.type_of_packet = MATH_TYPE_SEND_ANSWER;
		c = (c+1)%100;
		if ( c == 0 )
			send_packet(handle,header);
	}
	ack_message("Answer received by client.");
}
<|endoftext|>


<commit_before>//
// Created by sancar koyunlu on 6/17/13.
// Copyright (c) 2013 hazelcast. All rights reserved.

#include "hazelcast/client/spi/LifecycleService.h"
#include "hazelcast/client/spi/PartitionService.h"
#include "hazelcast/client/spi/ClientContext.h"
#include "hazelcast/client/spi/InvocationService.h"
#include "hazelcast/client/spi/ClusterService.h"
#include "hazelcast/client/ClientConfig.h"
#include "hazelcast/client/connection/ConnectionManager.h"
#include "hazelcast/client/LifecycleListener.h"

namespace hazelcast {
    namespace client {
        namespace spi {

            LifecycleService::LifecycleService(ClientContext &clientContext, const ClientConfig &clientConfig)
            :clientContext(clientContext)
            , active(false) {
                std::set<LifecycleListener *> const &lifecycleListeners = clientConfig.getLifecycleListeners();
                listeners.insert(lifecycleListeners.begin(), lifecycleListeners.end());
                fireLifecycleEvent(LifecycleEvent::STARTING);
            };

            bool LifecycleService::start() {
                active = true;
                fireLifecycleEvent(LifecycleEvent::STARTED);
                if (!clientContext.getConnectionManager().start()) {
                    return false;
                }
                if (!clientContext.getClusterService().start()) {
                    return false;
                }
                clientContext.getInvocationService().start();
                if (!clientContext.getPartitionService().start()) {
                    return false;
                }
                return true;
            }

            void LifecycleService::shutdown() {
                util::LockGuard lg(lifecycleLock);
                if (!active)
                    return;
                active = false;
                fireLifecycleEvent(LifecycleEvent::SHUTTING_DOWN);
                clientContext.getConnectionManager().stop();
                clientContext.getClusterService().stop();
                clientContext.getPartitionService().stop();
                fireLifecycleEvent(LifecycleEvent::SHUTDOWN);
            };

            void LifecycleService::addLifecycleListener(LifecycleListener *lifecycleListener) {
                util::LockGuard lg(listenerLock);
                listeners.insert(lifecycleListener);
            };

            bool LifecycleService::removeLifecycleListener(LifecycleListener *lifecycleListener) {
                util::LockGuard lg(listenerLock);
                return listeners.erase(lifecycleListener) == 1;
            };

            void LifecycleService::fireLifecycleEvent(const LifecycleEvent &lifecycleEvent) {
                util::LockGuard lg(listenerLock);
                util::ILogger &logger = util::ILogger::getLogger();
                switch (lifecycleEvent.getState()) {
                    case LifecycleEvent::STARTING :
                        logger.info("LifecycleService::LifecycleEvent STARTING");
                        break;
                    case LifecycleEvent::STARTED :
                        logger.info("LifecycleService::LifecycleEvent STARTED");
                        break;
                    case LifecycleEvent::SHUTTING_DOWN :
                        logger.info("LifecycleService::LifecycleEvent SHUTTING_DOWN");
                        break;
                    case LifecycleEvent::SHUTDOWN :
                        logger.info("LifecycleService::LifecycleEvent SHUTDOWN");
                        break;
                    case LifecycleEvent::CLIENT_CONNECTED :
                        logger.info("LifecycleService::LifecycleEvent CLIENT_CONNECTED");
                        break;
                    case LifecycleEvent::CLIENT_DISCONNECTED :
                        logger.info("LifecycleService::LifecycleEvent CLIENT_DISCONNECTED");
                        break;
                }

                for (std::set<LifecycleListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it) {
                    (*it)->stateChanged(lifecycleEvent);
                }

            };

            bool LifecycleService::isRunning() {
                return active;
            };
        }
    }
}
<commit_msg>small improvement in logs<commit_after>//
// Created by sancar koyunlu on 6/17/13.
// Copyright (c) 2013 hazelcast. All rights reserved.

#include "hazelcast/client/spi/LifecycleService.h"
#include "hazelcast/client/spi/PartitionService.h"
#include "hazelcast/client/spi/ClientContext.h"
#include "hazelcast/client/spi/InvocationService.h"
#include "hazelcast/client/spi/ClusterService.h"
#include "hazelcast/client/ClientConfig.h"
#include "hazelcast/client/connection/ConnectionManager.h"
#include "hazelcast/client/LifecycleListener.h"

namespace hazelcast {
    namespace client {
        namespace spi {

            LifecycleService::LifecycleService(ClientContext &clientContext, const ClientConfig &clientConfig)
            :clientContext(clientContext)
            , active(false) {
                std::set<LifecycleListener *> const &lifecycleListeners = clientConfig.getLifecycleListeners();
                listeners.insert(lifecycleListeners.begin(), lifecycleListeners.end());

            };

            bool LifecycleService::start() {
                fireLifecycleEvent(LifecycleEvent::STARTING);
                active = true;
                if (!clientContext.getConnectionManager().start()) {
                    return false;
                }
                if (!clientContext.getClusterService().start()) {
                    return false;
                }
                clientContext.getInvocationService().start();
                if (!clientContext.getPartitionService().start()) {
                    return false;
                }
                fireLifecycleEvent(LifecycleEvent::STARTED);
                return true;
            }

            void LifecycleService::shutdown() {
                util::LockGuard lg(lifecycleLock);
                if (!active)
                    return;
                active = false;
                fireLifecycleEvent(LifecycleEvent::SHUTTING_DOWN);
                clientContext.getConnectionManager().stop();
                clientContext.getClusterService().stop();
                clientContext.getPartitionService().stop();
                fireLifecycleEvent(LifecycleEvent::SHUTDOWN);
            };

            void LifecycleService::addLifecycleListener(LifecycleListener *lifecycleListener) {
                util::LockGuard lg(listenerLock);
                listeners.insert(lifecycleListener);
            };

            bool LifecycleService::removeLifecycleListener(LifecycleListener *lifecycleListener) {
                util::LockGuard lg(listenerLock);
                return listeners.erase(lifecycleListener) == 1;
            };

            void LifecycleService::fireLifecycleEvent(const LifecycleEvent &lifecycleEvent) {
                util::LockGuard lg(listenerLock);
                util::ILogger &logger = util::ILogger::getLogger();
                switch (lifecycleEvent.getState()) {
                    case LifecycleEvent::STARTING :
                        logger.info("LifecycleService::LifecycleEvent STARTING");
                        break;
                    case LifecycleEvent::STARTED :
                        logger.info("LifecycleService::LifecycleEvent STARTED");
                        break;
                    case LifecycleEvent::SHUTTING_DOWN :
                        logger.info("LifecycleService::LifecycleEvent SHUTTING_DOWN");
                        break;
                    case LifecycleEvent::SHUTDOWN :
                        logger.info("LifecycleService::LifecycleEvent SHUTDOWN");
                        break;
                    case LifecycleEvent::CLIENT_CONNECTED :
                        logger.info("LifecycleService::LifecycleEvent CLIENT_CONNECTED");
                        break;
                    case LifecycleEvent::CLIENT_DISCONNECTED :
                        logger.info("LifecycleService::LifecycleEvent CLIENT_DISCONNECTED");
                        break;
                }

                for (std::set<LifecycleListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it) {
                    (*it)->stateChanged(lifecycleEvent);
                }

            };

            bool LifecycleService::isRunning() {
                return active;
            };
        }
    }
}
<|endoftext|>


<commit_before>/** @file camera.hpp
    @brief Implements a basic free-fly camera to help testing. Uses SFML.
*/

#ifndef CAMERA_HPP
#define CAMERA_HPP

#include <cmath>
#include <SFML/Window.hpp>

namespace oglwrap {

/// Purely virtual interface class for cameras.
class Camera {
public:
    /// Returns the camera matrix.
    virtual glm::mat4 cameraMatrix() const = 0;

    /// Returns the camera's position.
    virtual glm::vec3 getPos() const = 0;

    /// Returns the camera's target.
    virtual glm::vec3 getTarget() const = 0;

    /// Returns the looking direction of the camera
    virtual glm::vec3 getForward() const {
        return glm::normalize(getTarget() - getPos());
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is neg Z (forwards), Pi/2 is pos Y (up) */
    virtual float getRotx() const {
        return asin(getForward().y);
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is pos X (right), Pi/2 is pos Z (backwards) */
    virtual float getRoty() const {
        glm::vec3 fwd = getForward();
        return atan2(fwd.z, fwd.x);
    }

    /// Returns the camera's CCW rotation angle around the Z Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is neg Z (forwards), Pi/2 is pos Y (up) */
    virtual float getRotz() const {
        return 0;
    }
};

/// A simple free-fly camera class using SFML. It's rather for testing than serious use.
/** It can be controlled with the WASD keys and the mouse */
class FreeFlyCamera : public Camera {
    /// The camera's position and the normalized forward vector
    glm::vec3 pos, fwd;

    /// Rotation angles(in radians) around the x and y Euler axes.
    float rotx, roty;

    /// Private constant numbers
    const float speedPerSec, maxPitchAngle, mouseSensitivity;
public:
    /// @brief Creates the free-fly camera.
    /// @param pos - The position of the camera.
    /// @param target - The position of the camera's target (what it is looking at).
    /// @param speedPerSec - Move speed in OpenGL units per second
    FreeFlyCamera(const glm::vec3& pos,
                  const glm::vec3& target = glm::vec3(),
                  float speedPerSec = 5.0f,
                  float mouseSensitivity = 1.0f)
        : pos(pos)
        , fwd(glm::normalize(target - pos))
        , rotx(asin(fwd.y))
        , roty(atan2(fwd.z, fwd.x))
        , speedPerSec(speedPerSec)
        , maxPitchAngle(85./90. * M_PI_2)
        , mouseSensitivity(mouseSensitivity) {

        assert(fabs(rotx) < maxPitchAngle);
    }

    /// Updates the camera's position and rotation.
    /// @param window - The currently active SFML window.
    /// @param fixMouse - Specifies if the mouse should be locked into the middle of the screen.
    void update(const sf::Window& window, bool fixMouse = false) {
        using namespace glm;
        static sf::Clock clock;
        static float prevTime;
        float time = clock.getElapsedTime().asSeconds();
        float dt =  time - prevTime;
        prevTime = time;

        sf::Vector2i loc = sf::Mouse::getPosition(window);
        sf::Vector2i diff;
        if(fixMouse) {
            sf::Vector2i screenHalf = sf::Vector2i(window.getSize().x / 2, window.getSize().y / 2);
            diff = loc - screenHalf;
            sf::Mouse::setPosition(screenHalf, window);
        } else {
            static sf::Vector2i prevLoc;
            diff = loc - prevLoc;
            prevLoc = loc;
        }

        static bool firstExec = true, lastFixMouse = fixMouse;
        if(firstExec || lastFixMouse != fixMouse) {
            firstExec = false;
            lastFixMouse = fixMouse;
            return;
        }

        // Mouse movement - update the coordinate system
        if(diff.x || diff.y) {
            roty += diff.x * mouseSensitivity * 0.0035f;
            rotx += -diff.y * mouseSensitivity * 0.0035f;

            if(fabs(rotx) > maxPitchAngle)
                rotx = rotx/fabs(rotx) * maxPitchAngle;
        }

        // WASD movement
        float ds = dt * speedPerSec;
        fwd = vec3(
                  cos(rotx) * cos(roty),
                  sin(rotx),
                  cos(rotx) * sin(roty)
              );
        vec3 right = normalize(cross(fwd, vec3(0.0f, 1.0f, 0.0f)));

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            pos += fwd * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            pos -= fwd * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
            pos += right * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
            pos -= right * ds;
    }

    /// Returns the camera matrix.
    glm::mat4 cameraMatrix() const {
        return glm::lookAt(pos, pos + fwd, glm::vec3(0.0f, 1.0f, 0.0f));
    }

    /// Returns the camera's target.
    glm::vec3 getTarget() const {
        return pos + fwd;
    }

    /// Returns the camera's position.
    glm::vec3 getPos() const {
        return pos;
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    float getRotx() const {
        return rotx;
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    float getRoty() const {
        return roty;
    }
}; // FreeFlyCamera

/// A simple camera class using SFML. Its position depends on an external target, usually a character.
/** It can be controlled with the WASD keys and the mouse */
class ThirdPersonalCamera : public Camera {
    // The target's position and the normalized forward vector
    glm::vec3 target, fwd;

    // Rotation angles(in radians) relative to the pos Z axis in the XZ and YZ planes.
    float rotx, roty;

    // Initial distance  between the camera and target, and the current and destination distance modifier.
    /* It's nearly a must to interpolate this, it looks very ugly without it */
    float currDistMod, destDistMod;

    // Don't interpolate at the first updateTarget call.
    bool firstCall;

    // Private constant number
    const float initialDistance, maxPitchAngle, mouseSensitivity, mouseScrollSensitivity;
public:
    /// @brief Creates the third-personal camera.
    /// @param pos - The position of the camera.
    /// @param target - The position of the camera's target (what it is looking at).
    /// @param speedPerSec - Move speed in OpenGL units per second
    ThirdPersonalCamera(const glm::vec3& pos,
                        const glm::vec3& target = glm::vec3(),
                        float mouseSensitivity = 1.0f,
                        float mouseScrollSensitivity = 1.0f)
        : target(pos)
        , fwd(glm::normalize(target - pos))
        , rotx(asin(fwd.y))
        , roty(atan2(fwd.z, fwd.x))
        , currDistMod(1.0)
        , destDistMod(1.0)
        , firstCall(true)
        , initialDistance(glm::length(target - pos))
        , maxPitchAngle(60./90. * M_PI_2)
        , mouseSensitivity(mouseSensitivity)
        , mouseScrollSensitivity(mouseScrollSensitivity) {

        assert(fabs(rotx) < maxPitchAngle);
    }

    /// Updates the camera's position and rotation.
    /// @param window - The currently active SFML window.
    /// @param fixMouse - Specifies if the mouse should be locked into the middle of the screen.
    void updateRotation(float time, const sf::Window& window, bool fixMouse = false) {
        using namespace glm;

        static float lastTime = 0;
        float dt = time - lastTime;
        lastTime = time;

        sf::Vector2i loc = sf::Mouse::getPosition(window);
        sf::Vector2i diff;
        if(fixMouse) {
            sf::Vector2i screenHalf = sf::Vector2i(window.getSize().x / 2, window.getSize().y / 2);
            diff = loc - screenHalf;
            sf::Mouse::setPosition(screenHalf, window);
        } else {
            static sf::Vector2i prevLoc;
            diff = loc - prevLoc;
            prevLoc = loc;
        }

        // We get invalid diff values at the startup or if fixMouse has just changed
        static bool firstExec = true, lastFixMouse = fixMouse;
        if(firstExec || lastFixMouse != fixMouse) {
            firstExec = false;
            lastFixMouse = fixMouse;
            diff = sf::Vector2i(0, 0);
        }

        // Mouse movement - update the coordinate system
        if(diff.x || diff.y) {
            roty += diff.x * mouseSensitivity * 0.0035f;
            rotx += -diff.y * mouseSensitivity * 0.0035f;

            if(fabs(rotx) > maxPitchAngle)
                rotx = rotx/fabs(rotx) * maxPitchAngle;
        }

        float distDiffMod = destDistMod - currDistMod;
        if(fabs(distDiffMod) > 1e-2) {
            int sign = distDiffMod / fabs(distDiffMod);
            currDistMod += sign * dt * mouseScrollSensitivity;
        }

        fwd = (initialDistance * currDistMod) * vec3(
            cos(rotx) * cos(roty),
            sin(rotx),
            cos(rotx) * sin(roty)
        );
    }

    /// Changes the distance in which the camera should follow the target.
    /// @param mouseWheelTicks - The number of ticks, the mouse wheel was scrolled. Expect positive on up scroll.
    void scrolling(int mouseWheelTicks) {
        destDistMod -= mouseWheelTicks / 10.0f * mouseScrollSensitivity;
        if(destDistMod < 0.5f)
            destDistMod = 0.5f;
        else if(destDistMod > 2.0f)
            destDistMod = 2.0f;
    }

    /// Updates the target of the camera. Is expected to be called every frame.
    /// @param target - the position of the object the camera should follow.
    void updateTarget(const glm::vec3& _target) {
        if(firstCall) {
            target = _target;
            firstCall = false;
            return;
        }

        target = glm::vec3(_target.x, target.y, _target.z);

        float diff = _target.y - target.y;
        const float offs = std::max(fabs(diff * diff / 5.0), 0.1);
        if(fabs(diff) > offs) { // FIXME @ this constant
            target.y += diff / fabs(diff) * offs;
        }
    }

    /// Returns the camera matrix.
    glm::mat4 cameraMatrix() const {
        return glm::lookAt(target - fwd, target, glm::vec3(0.0f, 1.0f, 0.0f));
    }

    /// Returns the camera's target.
    glm::vec3 getTarget() const {
        return target;
    }

    /// Returns the camera's position.
    glm::vec3 getPos() const {
        return target - fwd;
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    float getRotx() const {
        return rotx;
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    float getRoty() const {
        return roty;
    }
}; // ThirdPersonalCamera

} // namespace oglwrap

#endif // header guard

<commit_msg>Small changes.<commit_after>/** @file camera.hpp
    @brief Implements a basic free-fly camera to help testing. Uses SFML.
*/

#ifndef CAMERA_HPP
#define CAMERA_HPP

#include <cmath>
#include <SFML/Window.hpp>

namespace oglwrap {

/// Purely virtual interface class for cameras.
class Camera {
public:
    /// Returns the camera matrix.
    virtual glm::mat4 cameraMatrix() const = 0;

    /// Returns the camera's position.
    virtual glm::vec3 getPos() const = 0;

    /// Returns the camera's target.
    virtual glm::vec3 getTarget() const = 0;

    /// Returns the looking direction of the camera
    virtual glm::vec3 getForward() const {
        return glm::normalize(getTarget() - getPos());
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is neg Z (forwards), Pi/2 is pos Y (up) */
    virtual float getRotx() const {
        return asin(getForward().y);
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is pos X (right), Pi/2 is pos Z (backwards) */
    virtual float getRoty() const {
        glm::vec3 fwd = getForward();
        return atan2(fwd.z, fwd.x);
    }

    /// Returns the camera's CCW rotation angle around the Z Euler axe.
    /** Assuming that (0,1,0) is up, angle 0 is neg Z (forwards), Pi/2 is pos Y (up) */
    virtual float getRotz() const {
        return 0;
    }
};

/// A simple free-fly camera class using SFML. It's rather for testing than serious use.
/** It can be controlled with the WASD keys and the mouse */
class FreeFlyCamera : public Camera {
    /// The camera's position and the normalized forward vector
    glm::vec3 pos, fwd;

    /// Rotation angles(in radians) around the x and y Euler axes.
    float rotx, roty;

    /// Private constant numbers
    const float speedPerSec, maxPitchAngle, mouseSensitivity;
public:
    /// @brief Creates the free-fly camera.
    /// @param pos - The position of the camera.
    /// @param target - The position of the camera's target (what it is looking at).
    /// @param speedPerSec - Move speed in OpenGL units per second
    FreeFlyCamera(const glm::vec3& pos,
                  const glm::vec3& target = glm::vec3(),
                  float speedPerSec = 5.0f,
                  float mouseSensitivity = 1.0f)
        : pos(pos)
        , fwd(glm::normalize(target - pos))
        , rotx(asin(fwd.y))
        , roty(atan2(fwd.z, fwd.x))
        , speedPerSec(speedPerSec)
        , maxPitchAngle(85./90. * M_PI_2)
        , mouseSensitivity(mouseSensitivity) {

        assert(fabs(rotx) < maxPitchAngle);
    }

    /// Updates the camera's position and rotation.
    /// @param window - The currently active SFML window.
    /// @param fixMouse - Specifies if the mouse should be locked into the middle of the screen.
    void update(const sf::Window& window, bool fixMouse = false) {
        using namespace glm;
        static sf::Clock clock;
        static float prevTime;
        float time = clock.getElapsedTime().asSeconds();
        float dt =  time - prevTime;
        prevTime = time;

        sf::Vector2i loc = sf::Mouse::getPosition(window);
        sf::Vector2i diff;
        if(fixMouse) {
            sf::Vector2i screenHalf = sf::Vector2i(window.getSize().x / 2, window.getSize().y / 2);
            diff = loc - screenHalf;
            sf::Mouse::setPosition(screenHalf, window);
        } else {
            static sf::Vector2i prevLoc;
            diff = loc - prevLoc;
            prevLoc = loc;
        }

        static bool firstExec = true, lastFixMouse = fixMouse;
        if(firstExec || lastFixMouse != fixMouse) {
            firstExec = false;
            lastFixMouse = fixMouse;
            return;
        }

        // Mouse movement - update the coordinate system
        if(diff.x || diff.y) {
            roty += diff.x * mouseSensitivity * 0.0035f;
            rotx += -diff.y * mouseSensitivity * 0.0035f;

            if(fabs(rotx) > maxPitchAngle)
                rotx = rotx/fabs(rotx) * maxPitchAngle;
        }

        // WASD movement
        float ds = dt * speedPerSec;
        fwd = vec3(
                  cos(rotx) * cos(roty),
                  sin(rotx),
                  cos(rotx) * sin(roty)
              );
        vec3 right = normalize(cross(fwd, vec3(0.0f, 1.0f, 0.0f)));

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            pos += fwd * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            pos -= fwd * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
            pos += right * ds;
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
            pos -= right * ds;
    }

    /// Returns the camera matrix.
    glm::mat4 cameraMatrix() const {
        return glm::lookAt(pos, pos + fwd, glm::vec3(0.0f, 1.0f, 0.0f));
    }

    /// Returns the camera's target.
    glm::vec3 getTarget() const {
        return pos + fwd;
    }

    /// Returns the camera's position.
    glm::vec3 getPos() const {
        return pos;
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    float getRotx() const {
        return rotx;
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    float getRoty() const {
        return roty;
    }
}; // FreeFlyCamera

/// A simple camera class using SFML. Its position depends on an external target, usually a character.
/** It can be controlled with the WASD keys and the mouse */
class ThirdPersonalCamera : public Camera {
    // The target's position and the normalized forward vector
    glm::vec3 target, fwd;

    // Rotation angles(in radians) relative to the pos Z axis in the XZ and YZ planes.
    float rotx, roty;

    // Initial distance  between the camera and target, and the current and destination distance modifier.
    /* It's nearly a must to interpolate this, it looks very ugly without it */
    float currDistMod, destDistMod;

    // Don't interpolate at the first updateTarget call.
    bool firstCall;

    // Private constant number
    const float initialDistance, maxPitchAngle, mouseSensitivity, mouseScrollSensitivity;
public:
    /// @brief Creates the third-personal camera.
    /// @param pos - The position of the camera.
    /// @param target - The position of the camera's target (what it is looking at).
    /// @param speedPerSec - Move speed in OpenGL units per second
    ThirdPersonalCamera(const glm::vec3& pos,
                        const glm::vec3& target = glm::vec3(),
                        float mouseSensitivity = 1.0f,
                        float mouseScrollSensitivity = 1.0f)
        : target(pos)
        , fwd(glm::normalize(target - pos))
        , rotx(asin(fwd.y))
        , roty(atan2(fwd.z, fwd.x))
        , currDistMod(1.0)
        , destDistMod(1.0)
        , firstCall(true)
        , initialDistance(glm::length(target - pos))
        , maxPitchAngle(60./90. * M_PI_2)
        , mouseSensitivity(mouseSensitivity)
        , mouseScrollSensitivity(mouseScrollSensitivity) {

        assert(fabs(rotx) < maxPitchAngle);
    }

    /// Updates the camera's position and rotation.
    /// @param window - The currently active SFML window.
    /// @param fixMouse - Specifies if the mouse should be locked into the middle of the screen.
    void updateRotation(float time, const sf::Window& window, bool fixMouse = false) {
        using namespace glm;

        static float lastTime = 0;
        float dt = time - lastTime;
        lastTime = time;

        sf::Vector2i loc = sf::Mouse::getPosition(window);
        sf::Vector2i diff;
        if(fixMouse) {
            sf::Vector2i screenHalf = sf::Vector2i(window.getSize().x / 2, window.getSize().y / 2);
            diff = loc - screenHalf;
            sf::Mouse::setPosition(screenHalf, window);
        } else {
            static sf::Vector2i prevLoc;
            diff = loc - prevLoc;
            prevLoc = loc;
        }

        // We get invalid diff values at the startup or if fixMouse has just changed
        static bool firstExec = true, lastFixMouse = fixMouse;
        if(firstExec || lastFixMouse != fixMouse) {
            firstExec = false;
            lastFixMouse = fixMouse;
            diff = sf::Vector2i(0, 0);
        }

        // Mouse movement - update the coordinate system
        if(diff.x || diff.y) {
            roty += diff.x * mouseSensitivity * 0.0035f;
            rotx += -diff.y * mouseSensitivity * 0.0035f;

            if(fabs(rotx) > maxPitchAngle)
                rotx = rotx/fabs(rotx) * maxPitchAngle;
        }

        float distDiffMod = destDistMod - currDistMod;
        if(fabs(distDiffMod) > 1e-2) {
            int sign = distDiffMod / fabs(distDiffMod);
            currDistMod += sign * dt * mouseScrollSensitivity;
        }

        fwd = (initialDistance * currDistMod) * vec3(
            cos(rotx) * cos(roty),
            sin(rotx),
            cos(rotx) * sin(roty)
        );
    }

    /// Changes the distance in which the camera should follow the target.
    /// @param mouseWheelTicks - The number of ticks, the mouse wheel was scrolled. Expect positive on up scroll.
    void scrolling(int mouseWheelTicks) {
        destDistMod -= mouseWheelTicks / 10.0f * mouseScrollSensitivity;
        if(destDistMod < 0.5f)
            destDistMod = 0.5f;
        else if(destDistMod > 2.0f)
            destDistMod = 2.0f;
    }

    /// Updates the target of the camera. Is expected to be called every frame.
    /// @param target - the position of the object the camera should follow.
    void updateTarget(const glm::vec3& _target) {
        if(firstCall) {
            target = _target;
            firstCall = false;
            return;
        }

        target = glm::vec3(_target.x, target.y, _target.z);

        float diff = _target.y - target.y;
        const float offs = std::max(fabs(diff * diff / 5.0), 0.05);
        if(fabs(diff) > offs) { // FIXME @ this constant
            target.y += diff / fabs(diff) * offs;
        }
    }

    /// Returns the camera matrix.
    glm::mat4 cameraMatrix() const {
        return glm::lookAt(target - fwd, target, glm::vec3(0, 1, 0));
    }

    /// Returns the camera's target.
    glm::vec3 getTarget() const {
        return target;
    }

    /// Returns the camera's position.
    glm::vec3 getPos() const {
        return target - fwd;
    }

    /// Returns the camera's CCW rotation angle around the X Euler axe.
    float getRotx() const {
        return rotx;
    }

    /// Returns the camera's CCW rotation angle around the Y Euler axe.
    float getRoty() const {
        return roty;
    }
}; // ThirdPersonalCamera

} // namespace oglwrap

#endif // header guard

<|endoftext|>


<commit_before>#include "carta.h"
#include <iostream>
#include <C:\SDL2-2.0.5\x86_64-w64-mingw32\include\SDL2\SDL.h>
#include <C:\SDL2-2.0.5\x86_64-w64-mingw32\include\SDL2\SDL_image.h>
#include "textura.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

int main(){
	// Janela principal
	SDL_Window* gWindow = NULL;

	// Renderizador principal
	SDL_Renderer* gRenderer = NULL;

	// Classe texture
	// Textura t = NULL;

	// Eventos
	SDL_Event event;

	// Responsavel pelo loop principal
	bool quit = false;

	// Cria a janela
	gWindow = SDL_CreateWindow("Presidente", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if(gWindow == NULL){
		cout << "Window could not be created. SDL Error: " << SDL_GetError() << endl;
	} else {
		// Cria o renderizador
		gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if(gRenderer == NULL) {
			cout << "Renderer could not be created. SDL Error: " << SDL_GetError() << endl;
		} else {
			// Inicializa a cor do renderizador
			SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

			// Inicializa o carregamento de PNG
			int imgFlags = IMG_INIT_PNG;
			if(!(IMG_Init(imgFlags) & imgFlags)){
				cout << "SDL could not initialize image. SDL Error: " << IMG_GetError() << endl;
			}
		}
	}

	Carta c = Carta(23, gRenderer);

	/*if(t == NULL){
		cout << "Failed to load texture." << endl;
	}*/

	// Loop  principal
	while(!quit){
		// Responsavel pelos eventos em espera
		while(SDL_PollEvent(&event) != 0){
			// Evento de saída
			if( event.type == SDL_QUIT)
				quit = true;
		}

		// Limpa a tela
		SDL_RenderClear(gRenderer);

		// Renderiza a carta
		c.renderCard();

		// Atualiza a tela
		SDL_RenderPresent(gRenderer);
	}

	// Destroi a janela
	SDL_DestroyRenderer(gRenderer);
	SDL_DestroyWindow(gWindow);
	gRenderer = NULL;
	gWindow = NULL;

	// Sai dos subsistemas
	IMG_Quit();
	SDL_Quit();

	return 0;
}
<commit_msg>Desnecessário o include do SDL<commit_after>#include "carta.h"
#include <iostream>
#include "textura.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

int main(){
	// Janela principal
	SDL_Window* gWindow = NULL;

	// Renderizador principal
	SDL_Renderer* gRenderer = NULL;

	// Classe texture
	// Textura t = NULL;

	// Eventos
	SDL_Event event;

	// Responsavel pelo loop principal
	bool quit = false;

	// Cria a janela
	gWindow = SDL_CreateWindow("Presidente", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if(gWindow == NULL){
		cout << "Window could not be created. SDL Error: " << SDL_GetError() << endl;
	} else {
		// Cria o renderizador
		gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if(gRenderer == NULL) {
			cout << "Renderer could not be created. SDL Error: " << SDL_GetError() << endl;
		} else {
			// Inicializa a cor do renderizador
			SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

			// Inicializa o carregamento de PNG
			int imgFlags = IMG_INIT_PNG;
			if(!(IMG_Init(imgFlags) & imgFlags)){
				cout << "SDL could not initialize image. SDL Error: " << IMG_GetError() << endl;
			}
		}
	}

	Carta c = Carta(23, gRenderer);

	/*if(t == NULL){
		cout << "Failed to load texture." << endl;
	}*/

	// Loop  principal
	while(!quit){
		// Responsavel pelos eventos em espera
		while(SDL_PollEvent(&event) != 0){
			// Evento de saída
			if( event.type == SDL_QUIT)
				quit = true;
		}

		// Limpa a tela
		SDL_RenderClear(gRenderer);

		// Renderiza a carta
		c.renderCard();

		// Atualiza a tela
		SDL_RenderPresent(gRenderer);
	}

	// Destroi a janela
	SDL_DestroyRenderer(gRenderer);
	SDL_DestroyWindow(gWindow);
	gRenderer = NULL;
	gWindow = NULL;

	// Sai dos subsistemas
	IMG_Quit();
	SDL_Quit();

	return 0;
}
<|endoftext|>


<commit_before>#pragma once
#ifndef SCOPEEXIT_HPP
# define SCOPEEXIT_HPP

#include <utility>

/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)

/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9

/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10

namespace detail
{

template <typename T>
class scope_exit
{
public:
  explicit scope_exit(T&& f) : f_(std::move(f)) { }

  scope_exit(scope_exit&& other) : f_(std::move(other.f_)) { }

  ~scope_exit() { f_(); }

private:
  T const f_;
};

class scope_exit_helper { };

template<typename T>
inline scope_exit<T> make_scope_exit(T&& f)
{
  return scope_exit<T>(std::forward<T>(f));
}

template<typename T>
inline scope_exit<T> operator+(scope_exit_helper&&, T&& f)
{
  return scope_exit<T>(std::forward<T>(f));
}

}

#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__)\
  (::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]{LAST(__VA_ARGS__);}))
#define SCOPE_EXIT2(...) auto const CAT(scope_exit_, __LINE__)\
  =::detail::scope_exit_helper()+[__VA_ARGS__]

#endif // SCOPEEXIT_HPP
<commit_msg>some styles fixes<commit_after>#pragma once
#ifndef SCOPEEXIT_HPP
# define SCOPEEXIT_HPP

#include <utility>

/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)

/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9

/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10

namespace detail
{

template <typename T>
class scope_exit
{
public:
  explicit scope_exit(T&& f) : f_(std::move(f))
  {
    static_assert(noexcept(f_()), "throwing functors are unsupported");
  }

  scope_exit(scope_exit&& other) : f_(std::move(other.f_)) { }

  ~scope_exit() { f_(); }

private:
  T const f_;
};

class scope_exit_helper { };

template<typename T>
inline scope_exit<T> make_scope_exit(T&& f)
{
  return scope_exit<T>(std::forward<T>(f));
}

template<typename T>
inline scope_exit<T> operator+(scope_exit_helper&&, T&& f)
{
  return scope_exit<T>(std::forward<T>(f));
}

}

#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__)  \
  (::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]() noexcept\
    { LAST(__VA_ARGS__); }))
#define SCOPE_EXIT2(...) auto const CAT(scope_exit_, __LINE__)\
  =::detail::scope_exit_helper()+[__VA_ARGS__]() noexcept

#endif // SCOPEEXIT_HPP
<|endoftext|>