<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__

#include "persistenceDiagrams/PersistenceDiagram.hh"

#include "persistentHomology/PersistencePairing.hh"

#include "topology/SimplicialComplex.hh"
#include "topology/UnionFind.hh"

#include <algorithm>
#include <tuple>
#include <unordered_map>
#include <vector>

namespace aleph
{

namespace traits
{

template <class Pairing> class PersistencePairingCalculation
{
public:

  PersistencePairingCalculation( Pairing& pairing )
    : _pairing( pairing )
  {
  }

  using IndexType = typename Pairing::IndexType;

  void add( IndexType u, IndexType v )
  {
    _pairing.add( u, v );
  }

  void add( IndexType u )
  {
    _pairing.add( u );
  }

private:
  Pairing& _pairing;
};

template <class Pairing> class NoPersistencePairingCalculation
{
public:

  NoPersistencePairingCalculation( Pairing& pairing )
    : _pairing( pairing )
  {
  }

  using IndexType = typename Pairing::IndexType;

  void add( IndexType /* u */, IndexType /* v */ ) const noexcept
  {
  }

  void add( IndexType /* u */ ) const noexcept
  {
  }

private:
  Pairing& _pairing;
};

class DiagonalElementCalculation
{
public:
  template <class T> bool operator()( T /* creation */, T /* destruction */ ) const noexcept
  {
    return true;
  }
};

class NoDiagonalElementCalculation
{
public:
  template <class T> bool operator()( T creation, T destruction ) const noexcept
  {
    return creation != destruction;
  }
};

} // namespace traits

/**
  Calculates zero-dimensional persistent homology, i.e. tracking of connected
  components, for a given simplicial complex. This is highly-efficient, as it
  only requires a suitable 'Union--Find' data structure.

  As usual, the function assumes that the simplicial complex is in filtration
  order, meaning that faces are preceded by their cofaces. The function won't
  check this, though!
*/

template <
  class Simplex,
  class PairingCalculationTraits = traits::NoPersistencePairingCalculation< PersistencePairing<typename Simplex::VertexType> >,
  class ElementCalculationTraits = traits::NoDiagonalElementCalculation
>
  std::tuple<
    PersistenceDiagram<typename Simplex::DataType>,
    PersistencePairing<typename Simplex::VertexType>,
    std::unordered_map<typename Simplex::VertexType, unsigned>
  >
calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K )
{
  using DataType   = typename Simplex::DataType;
  using VertexType = typename Simplex::VertexType;

  using namespace topology;

  std::vector<VertexType> vertices;
  K.vertices( std::back_inserter( vertices ) );

  UnionFind<VertexType> uf( vertices.begin(), vertices.end() );
  PersistenceDiagram<DataType> pd;                               // Persistence diagram
  PersistencePairing<VertexType> pp;                             // Persistence pairing
  std::unordered_map<VertexType, unsigned> cs;                   // Component sizes
  std::unordered_map<VertexType, std::vector<VertexType> > cc;   // Connected components
  std::unordered_map<VertexType, DataType> ap;                   // Accumulated persistence

  PairingCalculationTraits ct( pp );
  ElementCalculationTraits et;

  for( auto&& vertex : vertices )
  {
    cs[vertex] = 1;
    cc[vertex] = { vertex };
  }

  for( auto&& simplex : K )
  {
    // Only edges can destroy a component; we may safely skip any other
    // simplex with a different dimension.
    if( simplex.dimension() != 1 )
      continue;

    // Prepare component destruction -----------------------------------

    VertexType u = *( simplex.begin() );
    VertexType v = *( simplex.begin() + 1 );

    auto youngerComponent = uf.find( u );
    auto olderComponent   = uf.find( v );

    // If the component has already been merged by some other edge, we are
    // not interested in it any longer.
    if( youngerComponent == olderComponent )
      continue;

    // Ensures that the younger component is always the first component. A
    // component is younger if it its parent vertex precedes the other one
    // in the current filtration.
    auto uIndex = K.index( Simplex( youngerComponent ) );
    auto vIndex = K.index( Simplex( olderComponent ) );

    // The younger component must have the _larger_ index as it is born
    // _later_ in the filtration.
    if( uIndex < vIndex )
    {
      std::swap( youngerComponent, olderComponent );
      std::swap( uIndex, vIndex );
    }

    auto creation    = K[uIndex].data();
    auto destruction = simplex.data();

    uf.merge( youngerComponent, olderComponent );

    cs[olderComponent] += cs[youngerComponent];

    cc[olderComponent].insert( cc[olderComponent].end(),
                               cc[youngerComponent].begin(), cc[youngerComponent].end() );

    for( auto&& vertex : cc[youngerComponent] )
      ap[vertex] += DataType( destruction - creation );

    cc.erase(youngerComponent);

    if( et( creation, destruction ) )
    {
      pd.add( creation                         , destruction                                   );
      ct.add( static_cast<VertexType>( uIndex ), static_cast<VertexType>( K.index( simplex ) ) );
    }
    else
      cs.erase( youngerComponent );
  }

  // Store information about unpaired simplices ------------------------
  //
  // All components in the Union--Find data structure now correspond to
  // essential 0-dimensional homology classes of the input complex.

  std::vector<VertexType> roots;
  uf.roots( std::back_inserter( roots ) );

  for( auto&& root : roots )
  {
    auto creator = *K.find( Simplex( root ) );

    pd.add( creator.data()                                );
    ct.add( static_cast<VertexType>( K.index( creator ) ) );
  }

  return std::make_tuple( pd, pp, cs );
}

} // namespace aleph

#endif
<commit_msg>Extended zero-dimensional persistent homology calculation with functors<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__

#include "persistenceDiagrams/PersistenceDiagram.hh"

#include "persistentHomology/PersistencePairing.hh"

#include "topology/SimplicialComplex.hh"
#include "topology/UnionFind.hh"

#include "utilities/EmptyFunctor.hh"

#include <algorithm>
#include <tuple>
#include <unordered_map>
#include <vector>

namespace aleph
{

namespace traits
{

template <class Pairing> class PersistencePairingCalculation
{
public:

  PersistencePairingCalculation( Pairing& pairing )
    : _pairing( pairing )
  {
  }

  using IndexType = typename Pairing::IndexType;

  void add( IndexType u, IndexType v )
  {
    _pairing.add( u, v );
  }

  void add( IndexType u )
  {
    _pairing.add( u );
  }

private:
  Pairing& _pairing;
};

template <class Pairing> class NoPersistencePairingCalculation
{
public:

  NoPersistencePairingCalculation( Pairing& pairing )
    : _pairing( pairing )
  {
  }

  using IndexType = typename Pairing::IndexType;

  void add( IndexType /* u */, IndexType /* v */ ) const noexcept
  {
  }

  void add( IndexType /* u */ ) const noexcept
  {
  }

private:
  Pairing& _pairing;
};

class DiagonalElementCalculation
{
public:
  template <class T> bool operator()( T /* creation */, T /* destruction */ ) const noexcept
  {
    return true;
  }
};

class NoDiagonalElementCalculation
{
public:
  template <class T> bool operator()( T creation, T destruction ) const noexcept
  {
    return creation != destruction;
  }
};

} // namespace traits

/**
  Calculates zero-dimensional persistent homology, i.e. tracking of connected
  components, for a given simplicial complex. This is highly-efficient, as it
  only requires a suitable 'Union--Find' data structure.

  As usual, the function assumes that the simplicial complex is in filtration
  order, meaning that faces are preceded by their cofaces. The function won't
  check this, though!
*/

template <
  class Simplex,
  class PairingCalculationTraits = traits::NoPersistencePairingCalculation< PersistencePairing<typename Simplex::VertexType> >,
  class ElementCalculationTraits = traits::NoDiagonalElementCalculation,
  class Functor = aleph::utilities::EmptyFunctor
>
  std::tuple<
    PersistenceDiagram<typename Simplex::DataType>,
    PersistencePairing<typename Simplex::VertexType>,
    std::unordered_map<typename Simplex::VertexType, unsigned>
  >
calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K, Functor functor = Functor() )
{
  using DataType   = typename Simplex::DataType;
  using VertexType = typename Simplex::VertexType;

  using namespace topology;

  std::vector<VertexType> vertices;
  K.vertices( std::back_inserter( vertices ) );

  UnionFind<VertexType> uf( vertices.begin(), vertices.end() );
  PersistenceDiagram<DataType> pd;                               // Persistence diagram
  PersistencePairing<VertexType> pp;                             // Persistence pairing
  std::unordered_map<VertexType, unsigned> cs;                   // Component sizes
  std::unordered_map<VertexType, std::vector<VertexType> > cc;   // Connected components
  std::unordered_map<VertexType, DataType> ap;                   // Accumulated persistence

  PairingCalculationTraits ct( pp );
  ElementCalculationTraits et;

  for( auto&& vertex : vertices )
  {
    cs[vertex] = 1;
    cc[vertex] = { vertex };

    functor.initialize( vertex );
  }

  for( auto&& simplex : K )
  {
    // Only edges can destroy a component; we may safely skip any other
    // simplex with a different dimension.
    if( simplex.dimension() != 1 )
      continue;

    // Prepare component destruction -----------------------------------

    VertexType u = *( simplex.begin() );
    VertexType v = *( simplex.begin() + 1 );

    auto youngerComponent = uf.find( u );
    auto olderComponent   = uf.find( v );

    // If the component has already been merged by some other edge, we are
    // not interested in it any longer.
    if( youngerComponent == olderComponent )
      continue;

    // Ensures that the younger component is always the first component. A
    // component is younger if it its parent vertex precedes the other one
    // in the current filtration.
    auto uIndex = K.index( Simplex( youngerComponent ) );
    auto vIndex = K.index( Simplex( olderComponent ) );

    // The younger component must have the _larger_ index as it is born
    // _later_ in the filtration.
    if( uIndex < vIndex )
    {
      std::swap( youngerComponent, olderComponent );
      std::swap( uIndex, vIndex );
    }

    auto creation    = K[uIndex].data();
    auto destruction = simplex.data();

    uf.merge( youngerComponent, olderComponent );

    cs[olderComponent] += cs[youngerComponent];

    cc[olderComponent].insert( cc[olderComponent].end(),
                               cc[youngerComponent].begin(), cc[youngerComponent].end() );

    functor( youngerComponent,
             olderComponent,
             creation,
             destruction );

    for( auto&& vertex : cc[youngerComponent] )
      ap[vertex] += DataType( destruction - creation );

    cc.erase(youngerComponent);

    if( et( creation, destruction ) )
    {
      pd.add( creation                         , destruction                                   );
      ct.add( static_cast<VertexType>( uIndex ), static_cast<VertexType>( K.index( simplex ) ) );
    }
    else
      cs.erase( youngerComponent );
  }

  // Store information about unpaired simplices ------------------------
  //
  // All components in the Union--Find data structure now correspond to
  // essential 0-dimensional homology classes of the input complex.

  std::vector<VertexType> roots;
  uf.roots( std::back_inserter( roots ) );

  for( auto&& root : roots )
  {
    auto creator = *K.find( Simplex( root ) );

    pd.add( creator.data()                                );
    ct.add( static_cast<VertexType>( K.index( creator ) ) );

    functor( root,
             creator.data() );
  }

  return std::make_tuple( pd, pp, cs );
}

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#pragma once

#include "common/SerializeCustom.hpp"
#include "util/RapidjsonHelpers.hpp"

#include <QRegularExpression>
#include <QString>
#include <memory>
#include <pajlada/settings/serialize.hpp>

namespace chatterino {

class HighlightPhrase
{
    QString pattern;
    bool alert;
    bool sound;
    bool _isRegex;
    QRegularExpression regex;

public:
    bool operator==(const HighlightPhrase &other) const
    {
        return std::tie(this->pattern, this->sound, this->alert, this->_isRegex) ==
               std::tie(other.pattern, other.sound, other.alert, other._isRegex);
    }

    HighlightPhrase(const QString &_pattern, bool _alert, bool _sound, bool isRegex)
        : pattern(_pattern)
        , alert(_alert)
        , sound(_sound)
        , _isRegex(isRegex)
        , regex(_isRegex ? _pattern : "\\b" + QRegularExpression::escape(_pattern) + "\\b",
                QRegularExpression::CaseInsensitiveOption |
                    QRegularExpression::UseUnicodePropertiesOption)
    {
    }

    const QString &getPattern() const
    {
        return this->pattern;
    }
    bool getAlert() const
    {
        return this->alert;
    }
    bool getSound() const
    {
        return this->sound;
    }
    bool isRegex() const
    {
        return this->_isRegex;
    }

    bool isValid() const
    {
        return !this->pattern.isEmpty() && this->regex.isValid();
    }

    bool isMatch(const QString &subject) const
    {
        return this->isValid() && this->regex.match(subject).hasMatch();
    }

    //    const QRegularExpression &getRegex() const
    //    {
    //        return this->regex;
    //    }
};
}  // namespace chatterino

namespace pajlada {
namespace Settings {

template <>
struct Serialize<chatterino::HighlightPhrase> {
    static rapidjson::Value get(const chatterino::HighlightPhrase &value,
                                rapidjson::Document::AllocatorType &a)
    {
        rapidjson::Value ret(rapidjson::kObjectType);

        AddMember(ret, "pattern", value.getPattern(), a);
        AddMember(ret, "alert", value.getAlert(), a);
        AddMember(ret, "sound", value.getSound(), a);
        AddMember(ret, "regex", value.isRegex(), a);

        return ret;
    }
};

template <>
struct Deserialize<chatterino::HighlightPhrase> {
    static chatterino::HighlightPhrase get(const rapidjson::Value &value)
    {
        if (!value.IsObject()) {
            return chatterino::HighlightPhrase(QString(), true, false, false);
        }

        QString _pattern;
        bool _alert = true;
        bool _sound = false;
        bool _isRegex = false;

        chatterino::rj::getSafe(value, "pattern", _pattern);
        chatterino::rj::getSafe(value, "alert", _alert);
        chatterino::rj::getSafe(value, "sound", _sound);
        chatterino::rj::getSafe(value, "regex", _isRegex);

        return chatterino::HighlightPhrase(_pattern, _alert, _sound, _isRegex);
    }
};

}  // namespace Settings
}  // namespace pajlada
<commit_msg>Remove unused include<commit_after>#pragma once

#include "common/SerializeCustom.hpp"
#include "util/RapidjsonHelpers.hpp"

#include <QRegularExpression>
#include <QString>
#include <pajlada/settings/serialize.hpp>

namespace chatterino {

class HighlightPhrase
{
    QString pattern;
    bool alert;
    bool sound;
    bool _isRegex;
    QRegularExpression regex;

public:
    bool operator==(const HighlightPhrase &other) const
    {
        return std::tie(this->pattern, this->sound, this->alert, this->_isRegex) ==
               std::tie(other.pattern, other.sound, other.alert, other._isRegex);
    }

    HighlightPhrase(const QString &_pattern, bool _alert, bool _sound, bool isRegex)
        : pattern(_pattern)
        , alert(_alert)
        , sound(_sound)
        , _isRegex(isRegex)
        , regex(_isRegex ? _pattern : "\\b" + QRegularExpression::escape(_pattern) + "\\b",
                QRegularExpression::CaseInsensitiveOption |
                    QRegularExpression::UseUnicodePropertiesOption)
    {
    }

    const QString &getPattern() const
    {
        return this->pattern;
    }
    bool getAlert() const
    {
        return this->alert;
    }
    bool getSound() const
    {
        return this->sound;
    }
    bool isRegex() const
    {
        return this->_isRegex;
    }

    bool isValid() const
    {
        return !this->pattern.isEmpty() && this->regex.isValid();
    }

    bool isMatch(const QString &subject) const
    {
        return this->isValid() && this->regex.match(subject).hasMatch();
    }

    //    const QRegularExpression &getRegex() const
    //    {
    //        return this->regex;
    //    }
};
}  // namespace chatterino

namespace pajlada {
namespace Settings {

template <>
struct Serialize<chatterino::HighlightPhrase> {
    static rapidjson::Value get(const chatterino::HighlightPhrase &value,
                                rapidjson::Document::AllocatorType &a)
    {
        rapidjson::Value ret(rapidjson::kObjectType);

        AddMember(ret, "pattern", value.getPattern(), a);
        AddMember(ret, "alert", value.getAlert(), a);
        AddMember(ret, "sound", value.getSound(), a);
        AddMember(ret, "regex", value.isRegex(), a);

        return ret;
    }
};

template <>
struct Deserialize<chatterino::HighlightPhrase> {
    static chatterino::HighlightPhrase get(const rapidjson::Value &value)
    {
        if (!value.IsObject()) {
            return chatterino::HighlightPhrase(QString(), true, false, false);
        }

        QString _pattern;
        bool _alert = true;
        bool _sound = false;
        bool _isRegex = false;

        chatterino::rj::getSafe(value, "pattern", _pattern);
        chatterino::rj::getSafe(value, "alert", _alert);
        chatterino::rj::getSafe(value, "sound", _sound);
        chatterino::rj::getSafe(value, "regex", _isRegex);

        return chatterino::HighlightPhrase(_pattern, _alert, _sound, _isRegex);
    }
};

}  // namespace Settings
}  // namespace pajlada
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <winscard.h>
#include "CSmartCard.h"

CSmartCard::CSmartCard()
{

}

CSmartCard::~CSmartCard()
{
	Uninit();
}

bool CSmartCard::Init()
{
	bool ret = false;
	LONG result;

	LPTSTR pReaders, pReader;

	// context
	result = SCardEstablishContext(SCARD_SCOPE_USER,  NULL, NULL, &m_hContext);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardEstablishContext\n");
		goto FINISH;
	}

	// get readers
	m_dwReaders = SCARD_AUTOALLOCATE;
	result = SCardListReaders(m_hContext, NULL, (LPTSTR)&pReaders, &m_dwReaders);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardListReaders\n");
		goto FINISH;
	}

	pReader = pReaders;
	while(*pReader != '\0')
	{
		std::wstring tmp = (wchar_t*)pReaders;
		m_pReadersList.push_back(tmp);
		pReader = pReader + wcslen((wchar_t *)pReader) + 1;
	}

	// free the memory
	result = SCardFreeMemory(m_hContext, pReaders);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardFreeMemory\n");
		goto FINISH;
	}

	ret = true;

FINISH:
	return ret;
}

void CSmartCard::Uninit()
{
	m_pReadersList.clear();
	SCardReleaseContext(m_hContext);
}

std::vector<std::wstring> CSmartCard::GetReaders()
{
	return m_pReadersList;
}

bool CSmartCard::Connect(std::wstring szReader)
{
	if(SCardConnect(m_hContext, (LPCTSTR)szReader.c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &m_hCard, &m_dwProtocol) != SCARD_S_SUCCESS)
		return false;

	return true;
}

void CSmartCard::Disconnect()
{
	SCardDisconnect(m_hCard, SCARD_LEAVE_CARD);
}

// implementation of GP_ITransmitter virtual method for securing APDU request
bool CSmartCard::Secure(GPAPI::GP_SecurityInfo* pSecurityInfo, const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput)
{
	fprintf(stderr,"SECURITY LEVEL: %d\r\n", pSecurityInfo->GetSecurityLevel());
	fprintf(stderr,"KEY VERSION: %d\r\n", pSecurityInfo->GetKeyVersion());
	fprintf(stderr,"KEY IDENTIFIER: %d\r\n", pSecurityInfo->GetKeyIdentifier());

	// simulates C-MAC computation (will not work for real application)
	unsigned char CMAC[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

	// add C-MAC
	*cOutput = cInput+sizeof(CMAC);
	memcpy(pOutput+cInput, CMAC, sizeof(CMAC));
	memcpy(pOutput, pInput, cInput);

	// modify Lc
	pOutput[4] = (char)(*cOutput-5);

	return true;
}

// implementation of GP_ITransmitter virtual method for exchanging APDU messages
bool CSmartCard::Exchange(const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput)
{
	// print request
	fprintf(stderr, ">> ");
	for(int i=0; i<(int)cInput; i++)
		fprintf(stderr,"%.2x ", pInput[i]);
	fprintf(stderr,"\r\n");

	// send request to smart-card and get its response
	if(SCardTransmit(m_hCard, SCARD_PCI_T1, pInput, cInput, NULL, pOutput, cOutput) != SCARD_S_SUCCESS)
		return false;

	// print response
	fprintf(stderr, "<< ");
	for(int i=0; i<(int)cOutput; i++)
		fprintf(stderr,"%.2x ", pOutput[i]);
	fprintf(stderr,"\r\n");

	return true;
}
<commit_msg>fixed bug of access to size of response data<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <winscard.h>
#include "CSmartCard.h"

CSmartCard::CSmartCard()
{

}

CSmartCard::~CSmartCard()
{
	Uninit();
}

bool CSmartCard::Init()
{
	bool ret = false;
	LONG result;

	LPTSTR pReaders, pReader;

	// context
	result = SCardEstablishContext(SCARD_SCOPE_USER,  NULL, NULL, &m_hContext);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardEstablishContext\n");
		goto FINISH;
	}

	// get readers
	m_dwReaders = SCARD_AUTOALLOCATE;
	result = SCardListReaders(m_hContext, NULL, (LPTSTR)&pReaders, &m_dwReaders);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardListReaders\n");
		goto FINISH;
	}

	pReader = pReaders;
	while(*pReader != '\0')
	{
		std::wstring tmp = (wchar_t*)pReaders;
		m_pReadersList.push_back(tmp);
		pReader = pReader + wcslen((wchar_t *)pReader) + 1;
	}

	// free the memory
	result = SCardFreeMemory(m_hContext, pReaders);
	if(result != SCARD_S_SUCCESS)
	{
		fprintf(stderr,"error: SCardFreeMemory\n");
		goto FINISH;
	}

	ret = true;

FINISH:
	return ret;
}

void CSmartCard::Uninit()
{
	m_pReadersList.clear();
	SCardReleaseContext(m_hContext);
}

std::vector<std::wstring> CSmartCard::GetReaders()
{
	return m_pReadersList;
}

bool CSmartCard::Connect(std::wstring szReader)
{
	if(SCardConnect(m_hContext, (LPCTSTR)szReader.c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &m_hCard, &m_dwProtocol) != SCARD_S_SUCCESS)
		return false;

	return true;
}

void CSmartCard::Disconnect()
{
	SCardDisconnect(m_hCard, SCARD_LEAVE_CARD);
}

// implementation of GP_ITransmitter virtual method for securing APDU request
bool CSmartCard::Secure(GPAPI::GP_SecurityInfo* pSecurityInfo, const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput)
{
	fprintf(stderr,"SECURITY LEVEL: %d\r\n", pSecurityInfo->GetSecurityLevel());
	fprintf(stderr,"KEY VERSION: %d\r\n", pSecurityInfo->GetKeyVersion());
	fprintf(stderr,"KEY IDENTIFIER: %d\r\n", pSecurityInfo->GetKeyIdentifier());

	// simulates C-MAC computation (will not work for real application)
	unsigned char CMAC[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

	// add C-MAC
	*cOutput = cInput+sizeof(CMAC);
	memcpy(pOutput+cInput, CMAC, sizeof(CMAC));
	memcpy(pOutput, pInput, cInput);

	// modify Lc
	pOutput[4] = (char)(*cOutput-5);

	return true;
}

// implementation of GP_ITransmitter virtual method for exchanging APDU messages
bool CSmartCard::Exchange(const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput)
{
	// print request
	fprintf(stderr, ">> ");
	for(int i=0; i<(int)cInput; i++)
		fprintf(stderr,"%.2x ", pInput[i]);
	fprintf(stderr,"\r\n");

	// send request to smart-card and get its response
	if(SCardTransmit(m_hCard, SCARD_PCI_T1, pInput, cInput, NULL, pOutput, cOutput) != SCARD_S_SUCCESS)
		return false;

	// print response
	fprintf(stderr, "<< ");
	for(int i=0; i<(int)*cOutput; i++)
		fprintf(stderr,"%.2x ", pOutput[i]);
	fprintf(stderr,"\r\n");

	return true;
}
<|endoftext|>


<commit_before>#include "OpenGLTexture.h"

#include "TextureRef.h"
#include "Image.h"

#define GL_GLEXT_PROTOTYPES

#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elsif defined GL_ES
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES

#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif

#include <GL/gl.h>

#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif

#endif

#include <cassert>

using namespace std;
using namespace canvas;

size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;

static GLenum getOpenGLInternalFormat(InternalFormat internal_format) {
  switch (internal_format) {
  case RG8: return GL_RG8;
  case RGB565: return GL_RGB565;
  case RGBA4: return GL_RGBA4;
  case RGBA8: return GL_RGBA8;
#ifdef __linux__
  case COMPRESSED_RG: return GL_RG8;
  case COMPRESSED_RGB: return GL_RGB5;
  case COMPRESSED_RGBA: return GL_RGBA8;
#else
  case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC;
  case COMPRESSED_RGB: return GL_COMPRESSED_RGB8_ETC2;
  case COMPRESSED_RGBA: return GL_COMPRESSED_RGBA8_ETC2_EAC;
#endif
  case LUMINANCE_ALPHA: return GL_RG8;
  }
  return 0;
}

static GLenum getOpenGLFilterType(FilterMode mode) {
  switch (mode) {
  case NEAREST: return GL_NEAREST;
  case LINEAR: return GL_LINEAR;
  case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
  }
  return 0;
}

void
OpenGLTexture::updateData(const void * buffer) {
  updateData(buffer, 0, 0, getActualWidth(), getActualHeight());
}

void
OpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) {
  assert(buffer);

  bool initialize = false;
  if (!texture_id) {
    initialize = true;
    glGenTextures(1, &texture_id);
    if (texture_id >= 1) total_textures++;
  }
  assert(texture_id >= 1);

  glBindTexture(GL_TEXTURE_2D, texture_id);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
  if (initialize) {
    // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
  }

  if (getInternalFormat() == LUMINANCE_ALPHA) {
    Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32);
    auto tmp_image2 = tmp_image.changeFormat(ImageFormat::LUMALPHA8);
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RG, GL_UNSIGNED_BYTE, tmp_image2->getData());
  } else if (getInternalFormat() == RGB565) {
    Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32);
    auto tmp_image2 = tmp_image.changeFormat(ImageFormat::RGB565);
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image2->getData());
  } else {
#ifdef __APPLE__
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
#else
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer);
#endif
  }
  if (has_mipmaps) {
    glGenerateMipmap(GL_TEXTURE_2D);
  }

  glBindTexture(GL_TEXTURE_2D, 0);
}

void
OpenGLTexture::releaseTextures() {
  // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl;

  for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {
    GLuint texid = *it;
    glDeleteTextures(1, &texid);
  }
  freed_textures.clear();
}

TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
  return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
<commit_msg>test different compressed formats<commit_after>#include "OpenGLTexture.h"

#include "TextureRef.h"
#include "Image.h"

#define GL_GLEXT_PROTOTYPES

#if defined __APPLE__
#include <OpenGLES/ES3/gl.h>
#include <OpenGLES/ES3/glext.h>
#elif (defined GL_ES)
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#else
#define GL_GLEXT_PROTOTYPES

#ifdef _WIN32
#include <GL/glew.h>
#include <windows.h>
#endif

#include <GL/gl.h>

#ifdef _WIN32
#include "glext.h"
#else
#include <GL/glext.h>
#endif

#endif

#include <cassert>

using namespace std;
using namespace canvas;

size_t OpenGLTexture::total_textures = 0;
vector<unsigned int> OpenGLTexture::freed_textures;

static GLenum getOpenGLInternalFormat(InternalFormat internal_format) {
  switch (internal_format) {
  case RG8: return GL_RG8;
  case RGB565: return GL_RGB565;
  case RGBA4: return GL_RGBA4;
  case RGBA8: return GL_RGBA8;
#ifdef __linux__
  case COMPRESSED_RG: return GL_RG8;
  case COMPRESSED_RGB: return GL_RGB5;
  case COMPRESSED_RGBA: return GL_RGBA8;
#else
  case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC;
  case COMPRESSED_RGB:
      assert(0);
      return GL_COMPRESSED_RGB8_ETC2;
      // return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  case COMPRESSED_RGBA:
      // assert(0);
      // return GL_COMPRESSED_RGBA8_ETC2_EAC;
      return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
#endif
  case LUMINANCE_ALPHA: return GL_RG8;
  }
  return 0;
}

static GLenum getOpenGLFilterType(FilterMode mode) {
  switch (mode) {
  case NEAREST: return GL_NEAREST;
  case LINEAR: return GL_LINEAR;
  case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
  }
  return 0;
}

void
OpenGLTexture::updateData(const void * buffer) {
  updateData(buffer, 0, 0, getActualWidth(), getActualHeight());
}

void
OpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) {
  assert(buffer);

  bool initialize = false;
  if (!texture_id) {
    initialize = true;
    glGenTextures(1, &texture_id);
    if (texture_id >= 1) total_textures++;
  }
  assert(texture_id >= 1);

  glBindTexture(GL_TEXTURE_2D, texture_id);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR;
  if (initialize) {
    // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight());

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter()));
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter()));
  }

  if (getInternalFormat() == LUMINANCE_ALPHA) {
    Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32);
    auto tmp_image2 = tmp_image.changeFormat(ImageFormat::LUMALPHA8);
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RG, GL_UNSIGNED_BYTE, tmp_image2->getData());
  } else if (getInternalFormat() == RGB565) {
    Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32);
    auto tmp_image2 = tmp_image.changeFormat(ImageFormat::RGB565);
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image2->getData());
  } else {
#ifdef __APPLE__
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
#else
    glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer);
#endif
  }
  if (has_mipmaps) {
    glGenerateMipmap(GL_TEXTURE_2D);
  }

  glBindTexture(GL_TEXTURE_2D, 0);
}

void
OpenGLTexture::releaseTextures() {
  // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl;

  for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) {
    GLuint texid = *it;
    glDeleteTextures(1, &texid);
  }
  freed_textures.clear();
}

TextureRef
OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) {
  return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels));
}
<|endoftext|>


<commit_before>/*
 * OstringStream.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "log4cpp/Portability.hh"
#include <stdio.h>
#include "log4cpp/OstringStream.hh"

#if defined(_MSC_VER)
    #define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
    #define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */

#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF

#include "snprintf.c"
#define VSNPRINTF portable_snprintf

#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER

namespace {

    std::string vstrprintf(const char* format, va_list args)
    {
	int         size   = 1024;
	char*       buffer = new char[size];

	while (1) {
	    int n = VSNPRINTF(buffer, size, format, args);

	    // If that worked, return a string.
	    if (n > -1 && n < size) {
		std::string s(buffer);
		delete [] buffer;
		return s;
	    }

	    // Else try again with more space.
	    if (n > -1)     size  = n+1;    // ISO/IEC 9899:1999
	    else            size *= 2;      // twice the old size

	    delete [] buffer;
	    buffer = new char[size];
	}
    }

}

namespace log4cpp {

#ifndef LOG4CPP_HAVE_SSTREAM
    std::string OstringStream::str() {
        (*this) << '\0';
        std::string msg(ostrstream::str());
        ostrstream::freeze(false); //unfreeze stream
        return msg;

    }
#endif

    void OstringStream::vform(const char* format, va_list args) {
	*this << vstrprintf(format, args);
    }

}

<commit_msg>Added some #includes for portable snprintf().<commit_after>/*
 * OstringStream.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "log4cpp/Portability.hh"
#include <stdio.h>
#include "log4cpp/OstringStream.hh"

#if defined(_MSC_VER)
    #define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
    #define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */

#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF

#include <stdlib.h>
#include <stdarg.h>
#include "snprintf.c"
#define VSNPRINTF portable_snprintf

#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER

namespace {

    std::string vstrprintf(const char* format, va_list args)
    {
	int         size   = 1024;
	char*       buffer = new char[size];

	while (1) {
	    int n = VSNPRINTF(buffer, size, format, args);

	    // If that worked, return a string.
	    if (n > -1 && n < size) {
		std::string s(buffer);
		delete [] buffer;
		return s;
	    }

	    // Else try again with more space.
	    if (n > -1)     size  = n+1;    // ISO/IEC 9899:1999
	    else            size *= 2;      // twice the old size

	    delete [] buffer;
	    buffer = new char[size];
	}
    }

}

namespace log4cpp {

#ifndef LOG4CPP_HAVE_SSTREAM
    std::string OstringStream::str() {
        (*this) << '\0';
        std::string msg(ostrstream::str());
        ostrstream::freeze(false); //unfreeze stream
        return msg;

    }
#endif

    void OstringStream::vform(const char* format, va_list args) {
	*this << vstrprintf(format, args);
    }

}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

void carr_func(int * vec)
{
	std::cout << "carr_func - vec: " << vec << std::endl;
}

int main(void)
{
	std::vector<int> v1 = {-1, 3, 5, -8, 0};
	std::vector<int> v2;
	auto v3(v1); //initialize v3 via copy

	/**
	* Managing std::vector capacity
	*/

	//Unlike std::array, std::vector has a more sensible empty() function
	//v2 is currently empty
	std::cout << "v1.empty(): " << v1.empty() << std::endl;
	std::cout << "v2.empty(): " << v2.empty() << std::endl;

	// size() tells you the number of elements
	std::cout << "v1.size(): " << v1.size() << std::endl;
	std::cout << "v2.size(): " << v2.size() << std::endl;

	// max_size() is huuuuuuuuuge for my host machine
	std::cout << "v1.max_size(): " << v1.max_size() << std::endl;
	std::cout << "v2.max_size(): " << v2.max_size() << std::endl;

	// Capacity tells you how many elements can be stored in the currently allocated memory
	std::cout << "v1.capacity(): " << v1.capacity() << std::endl;
	std::cout << "v2.capacity(): " << v2.capacity() << std::endl;

	v2.reserve(10);
	std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl;
	std::cout << "v2.size(): " << v2.size() << std::endl;

	//If you have reserved space greater than your current needs, you can shrink the buffer
	v2.shrink_to_fit();
	std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl;

	/**
	* Accessing std::vector elements
	*/
	std::cout << "v1.front(): " << v1.front() << std::endl;
	std::cout << "v1.back(): " << v1.back() << std::endl;
	std::cout << "v1[0]: " << v1[0] << std::endl;
	std::cout << "v1.at(4): " << v1.at(4) << std::endl;

	// Bounds checking will generate exceptions. Try:
	//auto b = v2.at(10);

	//However, operator [] is not bounds checked!
	//This may or may not seg fault
	//std::cout << "v2[6]: " << v2[6] << std::endl;

	/*
	* If you need to interface with legacy code or libraries requiring
	* a C-style array interface, you can get to the underlying array data ptr
	*/

	//Error:
	//carr_func(v1);

	//OK:
	carr_func(v1.data());

	/**
	* Playing around with vectors
	*/
	v2 = v1; //copy

	std::cout << "v2.size() after copy: " << v2.size() << std::endl;
	v2.clear();
	std::cout << "v2.size() after clear: " << v2.size() << std::endl;
	std::cout << "v2.capacity(): " << v2.capacity() << std::endl;

	v2.insert(v2.begin(), -1); //insert an element - you need an iterator
	v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator
	v2.push_back(0); //adds element to end
	v2.emplace_back(int(10)); //constructs an element in place at the end

	std::cout << std::endl << "v2: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	v2.resize(7); //resize to 7. The new elements will be 0-initialized
	v2.resize(10, -1); //resize to 10. New elements initialized with -1

	v2.pop_back(); //removes last element

	std::cout << std::endl << "v2 resized: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	v2.resize(4); //shrink and strip off extra elements

	//Container operations work
	std::sort(v2.begin(), v2.end());

	std::cout << std::endl << "v2 shrunk & sorted: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	return 0;
}
<commit_msg>Add erase to vector example<commit_after>#include <iostream>
#include <vector>

void carr_func(int * vec)
{
	std::cout << "carr_func - vec: " << vec << std::endl;
}

int main(void)
{
	std::vector<int> v1 = {-1, 3, 5, -8, 0}; //initialize with list
	std::vector<int> v2; //don't initialize
	auto v3(v1); //initialize v3 via copy

	/**
	* Managing std::vector capacity
	*/

	//Unlike std::array, std::vector has a more sensible empty() function
	//v2 is currently empty
	std::cout << "v1.empty(): " << v1.empty() << std::endl;
	std::cout << "v2.empty(): " << v2.empty() << std::endl;

	// size() tells you the number of elements
	std::cout << "v1.size(): " << v1.size() << std::endl;
	std::cout << "v2.size(): " << v2.size() << std::endl;

	// max_size() is huuuuuuuuuge for my host machine
	std::cout << "v1.max_size(): " << v1.max_size() << std::endl;
	std::cout << "v2.max_size(): " << v2.max_size() << std::endl;

	// Capacity tells you how many elements can be stored in the currently allocated memory
	std::cout << "v1.capacity(): " << v1.capacity() << std::endl;
	std::cout << "v2.capacity(): " << v2.capacity() << std::endl;

	v2.reserve(10);
	std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl;
	std::cout << "v2.size(): " << v2.size() << std::endl;

	//If you have reserved space greater than your current needs, you can shrink the buffer
	v2.shrink_to_fit();
	std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl;

	/**
	* Accessing std::vector elements
	*/
	std::cout << "v1.front(): " << v1.front() << std::endl;
	std::cout << "v1.back(): " << v1.back() << std::endl;
	std::cout << "v1[0]: " << v1[0] << std::endl;
	std::cout << "v1.at(4): " << v1.at(4) << std::endl;

	// Bounds checking will generate exceptions. Try:
	//auto b = v2.at(10);

	//However, operator [] is not bounds checked!
	//This may or may not seg fault
	//std::cout << "v2[6]: " << v2[6] << std::endl;

	/*
	* If you need to interface with legacy code or libraries requiring
	* a C-style array interface, you can get to the underlying array data ptr
	*/

	//Error:
	//carr_func(v1);

	//OK:
	carr_func(v1.data());

	/**
	* Playing around with vectors
	*/
	v2 = v1; //copy

	std::cout << "v2.size() after copy: " << v2.size() << std::endl;
	v2.clear();
	std::cout << "v2.size() after clear: " << v2.size() << std::endl;
	std::cout << "v2.capacity(): " << v2.capacity() << std::endl;

	v2.insert(v2.begin(), -1); //insert an element - you need an iterator
	v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator
	v2.push_back(0); //adds element to end
	v2.emplace_back(int(10)); //constructs an element in place at the end

	std::cout << std::endl << "v2: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	v2.resize(7); //resize to 7. The new elements will be 0-initialized
	v2.resize(10, -1); //resize to 10. New elements initialized with -1

	v2.pop_back(); //removes last element
	v2.erase(v2.begin()); //removes first element

	std::cout << std::endl << "v2 resized: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	v2.resize(4); //shrink and strip off extra elements

	//Container operations work
	std::sort(v2.begin(), v2.end());

	std::cout << std::endl << "v2 shrunk & sorted: " << std::endl;
	for (const auto & t : v2)
	{
		std::cout << t << " ";
	}
	std::cout << std::endl;

	return 0;
}
<|endoftext|>


<commit_before>/**
@file config.hpp
@brief Configuration.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_CONFIG_HPP_
#define HORD_CONFIG_HPP_

#include <cstddef>
#include <cstdint>

/**
	@addtogroup config
	@{
*/

/**
	Allocator for auxiliary specializations.
*/
#define HORD_AUX_ALLOCATOR std::allocator

/** @cond INTERNAL */
#define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR
#define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR

#define HORD_STRINGIFY_INNER__(x) #x
/** @endcond */

/**
	Stringify an identifier.
*/
#define HORD_STRINGIFY(x) \
	HORD_STRINGIFY_INNER__(x)

/**
	@name Error reporting

	These macros are for error reporting.
	A class implementation file should
	@code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode
	and
	@code #undef HORD_SCOPE_CLASS_IDENT__ @endcode
	around its implementation space. Throwing functions should
	likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within
	the body. All of these macros require these definitions.

	@note <Hord/String.hpp> and <Hord/Error.hpp> are required to use
	these.

	@note All throw macros except for #HORD_THROW_ERROR_S encapsulate
	the final message in #HORD_STR_LIT (that is, @a m__ needn't be
	#HORD_STR_LIT-ized).

	@remarks I quite despise this method, but there is no @c __fqn__.
	Luckily, a nice a side-effect of this method is that it cuts down
	on both implementation complexity and dynamic allocation -- both
	good in my book, even if the cost is paid in 2 gnarly
	preprocessing directives per throwing function.
	@{
*/

#ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI
/**
	Current class identifier.

	This is defined surrounding class implementations.
*/
#define HORD_SCOPE_CLASS_IDENT__

/**
	Current function identifier.

	This is defined surrounding function implementations.
*/
#define HORD_SCOPE_FUNC_IDENT__
#endif

/**
	Returns the string literal of @c HORD_SCOPE_CLASS_IDENT__.
*/
#define HORD_SCOPE_CLASS \
	HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__)

/**
	Returns the string literal of @c HORD_SCOPE_FUNC_IDENT__.
*/
#define HORD_SCOPE_FUNC \
	HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__)

/**
	Returns the fully-qualified name of the current function.
*/
#define HORD_SCOPE_FQN \
	HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC

/** @cond INTERNAL */
#define HORD_MSG_SCOPED_IMPL__(s__, m__) \
		HORD_STR_LIT(s__ ": " m__)
/** @endcond */

/**
	Build message string literal with class scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_CLASS(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_CLASS, m__)

/**
	Build message string literal with function scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_FUNC(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FUNC, m__)

/**
	Build message string literal with fully-qualified scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_FQN(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FQN, m__)

/** @cond INTERNAL */
#define HORD_THROW_ERROR_IMPL__(e__, m__)	\
	throw std::move(::Hord::Error{			\
		e__,								\
		::Hord::String{m__}					\
	})
/** @endcond */

/**
	Throw error with message.

	@param e__ ErrorCode.
	@param m__ Message (string literal).
*/
#define HORD_THROW_ERROR(e__, m__) \
	HORD_THROW_ERROR_IMPL__(e__, HORD_STR_LIT(m__))

/**
	Throw error with message.

	@param e__ ErrorCode.
	@param m__ Message (String).
*/
#define HORD_THROW_ERROR_S(e__, m__) \
	HORD_THROW_ERROR_IMPL__(e__, m__)

/**
	Throw error with class scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_FUNC,
		HORD_THROW_ERROR_SCOPED_FQN
*/
#define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_CLASS(m__)				\
	)

/**
	Throw error with function scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_CLASS,
		HORD_THROW_ERROR_SCOPED_FQN
*/
#define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_FUNC(m__)				\
	)

/**
	Throw error with fully-qualified scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_CLASS,
		HORD_THROW_ERROR_SCOPED_FUNC
*/
#define HORD_THROW_ERROR_SCOPED_FQN(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_FQN(m__)				\
	)

/** @} */ // end of name-group Error reporting

namespace Hord {
} // namespace Hord

/** @} */ // end of doc-group config

#endif // HORD_CONFIG_HPP_
<commit_msg>config: added HORD_FMT_SCOPED_* and HORD_THROW_ERROR_F macros.<commit_after>/**
@file config.hpp
@brief Configuration.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_CONFIG_HPP_
#define HORD_CONFIG_HPP_

#include <cstddef>
#include <cstdint>

/**
	@addtogroup config
	@{
*/

/**
	Allocator for auxiliary specializations.
*/
#define HORD_AUX_ALLOCATOR std::allocator

/** @cond INTERNAL */
#define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR
#define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR

#define HORD_STRINGIFY_INNER__(x) #x
/** @endcond */

/**
	Stringify an identifier.
*/
#define HORD_STRINGIFY(x) \
	HORD_STRINGIFY_INNER__(x)

/**
	@name Error reporting

	These macros are for error reporting.
	A class implementation file should
	@code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode
	and
	@code #undef HORD_SCOPE_CLASS_IDENT__ @endcode
	around its implementation space. Throwing functions should
	likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within
	the body. All of these macros require these definitions.

	@note <Hord/String.hpp> and <Hord/Error.hpp> are required to use
	these.

	@note <ceformat/Format.hpp> is required for
	the @c HORD_FMT_SCOPED_* macros, and <ceformat/print.hpp> is
	required for #HORD_THROW_ERROR_F.

	@note All throw macros except for #HORD_THROW_ERROR_S encapsulate
	the final message in #HORD_STR_LIT (that is, @a m__ needn't be
	#HORD_STR_LIT-ized).

	@remarks I quite despise this method, but there is no @c __fqn__.
	Luckily, a nice a side-effect of this method is that it cuts down
	on both implementation complexity and dynamic allocation -- both
	good in my book, even if the cost is paid in 2 gnarly
	preprocessing directives per throwing function.
	@{
*/

#ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI
/**
	Current class identifier.

	This is defined surrounding class implementations.
*/
#define HORD_SCOPE_CLASS_IDENT__

/**
	Current function identifier.

	This is defined surrounding function implementations.
*/
#define HORD_SCOPE_FUNC_IDENT__
#endif

/**
	Returns the string literal of #HORD_SCOPE_CLASS_IDENT__.
*/
#define HORD_SCOPE_CLASS \
	HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__)

/**
	Returns the string literal of #HORD_SCOPE_FUNC_IDENT__.
*/
#define HORD_SCOPE_FUNC \
	HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__)

/**
	Returns the fully-qualified name of the current function.
*/
#define HORD_SCOPE_FQN \
	HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC

/** @cond INTERNAL */
#define HORD_MSG_SCOPED_IMPL__(s__, m__) \
	HORD_STR_LIT(s__ ": " m__)

#define HORD_FMT_SCOPED_IMPL__(ident__, f__)	\
	static constexpr ceformat::Format const	\
	ident__{f__}
/** @endcond */

// class scope

/**
	Build message string literal with class scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_CLASS(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_CLASS, m__)

/**
	Define format message with class scope.

	@param ident__ Identifier for format message.
	@param f__ Format message.
*/
#define HORD_FMT_SCOPED_CLASS(ident__, f__) \
	HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_CLASS(f__))

// function scope

/**
	Build message string literal with function scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_FUNC(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FUNC, m__)

/**
	Define format message with function scope.

	@param ident__ Identifier for format message.
	@param f__ Format message.
*/
#define HORD_FMT_SCOPED_FUNC(ident__, f__) \
	HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_FUNC(f__))

// fully-qualified scope

/**
	Build message string literal with fully-qualified scope.

	@param m__ Message.
*/
#define HORD_MSG_SCOPED_FQN(m__) \
	HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FQN, m__)

/**
	Define format message with fully-qualified scope.

	@param ident__ Identifier for format message.
	@param f__ Format message.
*/
#define HORD_FMT_SCOPED_FQN(ident__, f__) \
	HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_FQN(f__))

/** @cond INTERNAL */
#define HORD_THROW_ERROR_IMPL__(e__, m__)	\
	throw std::move(::Hord::Error{			\
		e__,								\
		::Hord::String{m__}					\
	})
/** @endcond */

/**
	Throw error with message.

	@param e__ ErrorCode.
	@param m__ Message (string literal).
*/
#define HORD_THROW_ERROR(e__, m__) \
	HORD_THROW_ERROR_IMPL__(e__, HORD_STR_LIT(m__))

/**
	Throw error with message.

	@param e__ ErrorCode.
	@param m__ Message (String).
*/
#define HORD_THROW_ERROR_S(e__, m__) \
	HORD_THROW_ERROR_IMPL__(e__, m__)

/**
	Throw error with format message.

	@param e__ ErrorCode.
	@param f__ @c ceformat::Format message.
	@param ... Arguments.
*/
#define HORD_THROW_ERROR_F(e__, f__, ...)	\
	HORD_THROW_ERROR_IMPL__(				\
		e__,								\
		ceformat::print<f__>(__VA_ARGS__)	\
	)

/**
	Throw error with class scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_FUNC,
		HORD_THROW_ERROR_SCOPED_FQN
*/
#define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_CLASS(m__)				\
	)

/**
	Throw error with function scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_CLASS,
		HORD_THROW_ERROR_SCOPED_FQN
*/
#define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_FUNC(m__)				\
	)

/**
	Throw error with fully-qualified scope.

	@param e__ ErrorCode.
	@param m__ Message (string literal).

	@sa HORD_THROW_ERROR_SCOPED_CLASS,
		HORD_THROW_ERROR_SCOPED_FUNC
*/
#define HORD_THROW_ERROR_SCOPED_FQN(e__, m__)	\
	HORD_THROW_ERROR_IMPL__(					\
		e__,									\
		HORD_MSG_SCOPED_FQN(m__)				\
	)

/** @} */ // end of name-group Error reporting

namespace Hord {
} // namespace Hord

/** @} */ // end of doc-group config

#endif // HORD_CONFIG_HPP_
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkImageWriter.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkTestingMacros.h"

#include <iostream>

/**
*  Simple example for a test for the (non-existent) class "ImageWriter".
*
*  argc and argv are the command line parameters which were passed to
*  the ADD_TEST command in the CMakeLists.txt file. For the automatic
*  tests, argv is either empty for the simple tests or contains the filename
*  of a test image for the image tests (see CMakeLists.txt).
*/
int mitkImageWriterTest(int  argc , char* argv[])
{
  // always start with this!
  MITK_TEST_BEGIN("ImageWriter")

    // let's create an object of our class
    mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation")

    // write your own tests here and use the macros from mitkTestingMacros.h !!!
    // do not write to std::cout and do not return from this function yourself!

    // load image
    std::cout << "Loading file: " << std::flush;
  if(argc==0)
  {
    std::cout<<"no file specified [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    std::cout<<argv[1]<<std::endl;
    factory->SetFileName( argv[1] );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      std::cout<<"file could not be loaded [FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied [PASSED]"<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch ( itk::ExceptionObject & ex )
  {
    std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL")

    try{
      // test for exception handling
      MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject)
      myImageWriter->SetInput(image);
      myImageWriter->SetFileName("/usr/bin");
      myImageWriter->Update();
      MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject)
  }
  catch(...) {
    //this means that a wrong exception (i.e. no itk:Exception) has been thrown
    std::cout << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  // always end with this!
  MITK_TEST_END()
}

<commit_msg>FIX (#3149): use testing macros consistently<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkImageWriter.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkTestingMacros.h"

#include <iostream>

/**
*  test for "ImageWriter".
*
*  argc and argv are the command line parameters which were passed to
*  the ADD_TEST command in the CMakeLists.txt file. For the automatic
*  tests, argv is either empty for the simple tests or contains the filename
*  of a test image for the image tests (see CMakeLists.txt).
*/
int mitkImageWriterTest(int  argc , char* argv[])
{
  // always start with this!
  MITK_TEST_BEGIN("ImageWriter")

    // let's create an object of our class
    mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation")

    // write your own tests here and use the macros from mitkTestingMacros.h !!!
    // do not write to std::cout and do not return from this function yourself!

    // load image

  MITK_TEST_CONDITION_REQUIRED(argc != 0, "File to load has been specified");

  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();

  try
  {
    MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]);
    factory->SetFileName( argv[1] );
    factory->Update();
    MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded");

    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied."<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch (itk::ExceptionObject & ex)
  {
    MITK_TEST_FAILED_MSG(<< "Exception during file loading: " << ex.GetDescription());
  }

  MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL")

  // test for exception handling
  try
  {
    MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject)
    myImageWriter->SetInput(image);
    myImageWriter->SetFileName("/usr/bin");
    myImageWriter->Update();
    MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject)
  }
  catch(...) {
    //this means that a wrong exception (i.e. no itk:Exception) has been thrown
    MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write");
  }

  // always end with this!
  MITK_TEST_END();
}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkImageVtkMapper2D.h"
//#include "mitkMapper.h"
//#include "mitkDataNode.h"
//#include "mitkBaseRenderer.h"
//#include "mitkProperties.h"

#include <vtkImageQuantizeRGBToIndex.h>
#include <vtkImageToPolyDataFilter.h>
#include <vtkTriangleFilter.h>
#include <vtkImageDataGeometryFilter.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageShiftScale.h>
#include <vtkImageCast.h>
#include <vtkImageReslice.h>
#include <vtkLinearTransform.h>
#include <vtkMatrix4x4.h>
#include <vtkProperty2D.h>
#include <vtkImageBlend.h>
#include <vtkImage.h>
#include <vtkImageProperty.h>
#include <vtkOpenGLImageResliceMapper.h>
#include <mitkVtkPropRenderer.h>

mitk::ImageVtkMapper2D::ImageVtkMapper2D()
{
  this->m_VtkBased = true;
  this->m_TimeStep = 0;
  this->m_VtkActor = vtkSmartPointer<vtkImage>::New();
  this->m_VtkImage = vtkSmartPointer<vtkImageData>::New();
  this->m_VtkMapper = vtkSmartPointer<vtkOpenGLImageResliceMapper>::New();
}

mitk::ImageVtkMapper2D::~ImageVtkMapper2D()
{
}

const mitk::Image* mitk::ImageVtkMapper2D::GetInput()
{
  return static_cast<const mitk::Image* > ( GetData() );
}

void mitk::ImageVtkMapper2D::GenerateData(mitk::BaseRenderer* renderer)
{
  MITK_INFO << "Generate Data called";
  if ( !this->IsVisible(renderer) )
  {
    itkWarningMacro( << "Renderer not visible!" );
    return;
  }
  mitk::Image::Pointer input = const_cast<mitk::Image*>( this->GetInput() );
  if ( input.IsNull() ) return ;

  vtkSmartPointer<vtkImageData> image = input->GetVtkImageData();
//  image->SetScalarTypeToUnsignedChar();
//  vtkSmartPointer<vtkImageShiftScale> imageShiftSacle = vtkImageShiftScale::New();
//  imageShiftSacle->SetOutputScalarTypeToUnsignedChar();
//  imageShiftSacle->ClampOverflowOn();
//  imageShiftSacle->SetInput(image);

//  vtkSmartPointer<vtkImageCast> imageCast = vtkSmartPointer<vtkImageCast>::New();
//  imageCast->SetOutputScalarTypeToUnsignedChar();
//  imageCast->ClampOverflowOn();
//  imageCast->SetInput(image);
//  m_VtkImage->SetScalarTypeToUnsignedChar();
//  m_VtkImage = imageCast->GetOutput();
  m_VtkImage = image;

//  float opacity = 1.0f;
//  GetOpacity(opacity, renderer);
//  MITK_INFO << opacity;
////  m_VtkActor->GetProperty()->SetOpacity(opacity);
////  MITK_INFO << m_VtkActor->GetProperty()->GetOpacity();

//  vtkSmartPointer<vtkImageBlend> blend =
//    vtkSmartPointer<vtkImageBlend>::New();
////  blend->AddInputConnection(image->GetOutputPort());
//  blend->AddInputConnection(image->GetProducerPort());
//  blend->SetOpacity(0,opacity);

//  m_VtkImage = blend->GetOutput(0);

  if( m_VtkImage )
  {
//    mitk::LevelWindow levelWindow;
//    GetLevelWindow(levelWindow, renderer);
//    double range =

//    const mitk::VtkPropRenderer* glRenderer = dynamic_cast<const mitk::VtkPropRenderer*>(renderer);
//    if (glRenderer == NULL)
//      return;
//    vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer();

//    vtkSmartPointer<vtkImageProperty> ip = vtkSmartPointer<vtkImageProperty>::New();
//    ip->SetColorLevel(1000);
//    ip->SetColorWindow(2000);
//    ip->SetInterpolationTypeToLinear();

//    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();

//    renderWindowInteractor->SetInteractorStyle(imageStyle);
//    renderWindowInteractor->SetRenderWindow(renderWindow);

//    m_VtkMapper->SetInputConnection(iExtended2Dmage->GetProducerPort());
    m_VtkMapper->SetInput(m_VtkImage);
//    m_VtkMapper->SetInputConnection(blend->GetOutputPort());
//    m_VtkMapper->SetColorLevel(levelWindow.GetLowerWindowBound());
//    m_VtkMapper->SetColorWindow(levelWindow.GetUpperWindowBound());

    m_VtkActor->SetMapper(m_VtkMapper);
//    m_VtkActor->SetProperty(ip);

//    m_VtkActor->SetVisibility(1);

  }
  else
  {
    itkWarningMacro( << "m_VtkImage is NULL!" );
    return ;
  }
}

void mitk::ImageVtkMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}
void mitk::ImageVtkMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
  }
}

void mitk::ImageVtkMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
//BUG (#1551) changed VTK_MINOR_VERSION FROM 3 to 2 cause RenderTranslucentGeometry was changed in minor version 2
#if ( ( VTK_MAJOR_VERSION >= 5 ) && ( VTK_MINOR_VERSION>=2)  )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
#else
    this->GetVtkProp(renderer)->RenderTranslucentGeometry(renderer->GetVtkRenderer());
#endif
}

void mitk::ImageVtkMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
    return;

  if ( GetVtkProp(renderer)->GetVisibility() )
    GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}

vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer)
{
//  m_VtkActor->GetProperty()->SetColor(0,1,0);
  return m_VtkActor;
}

vtkImageData *mitk::ImageVtkMapper2D::GenerateTestImageForTSFilter()
{
  // a 2x2x2 image
  unsigned char myData[] =
  {

    234,234,
    123,565,

//    -213,800,
//    1000,-20
  };
  vtkImageData *i = vtkImageData::New();

  i->SetExtent(0,1,0,1,0,0);

  i->SetScalarTypeToUnsignedChar();

  i->AllocateScalars();

  unsigned char *p = (unsigned char*)i->GetScalarPointer();

  memcpy(p,myData,2*2*1*sizeof(unsigned char));

  return i;
}
<commit_msg>added 0,0 to GetVtkImageData<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkImageVtkMapper2D.h"
//#include "mitkMapper.h"
//#include "mitkDataNode.h"
//#include "mitkBaseRenderer.h"
//#include "mitkProperties.h"

#include <vtkImageQuantizeRGBToIndex.h>
#include <vtkImageToPolyDataFilter.h>
#include <vtkTriangleFilter.h>
#include <vtkImageDataGeometryFilter.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageShiftScale.h>
#include <vtkImageCast.h>
#include <vtkImageReslice.h>
#include <vtkLinearTransform.h>
#include <vtkMatrix4x4.h>
#include <vtkProperty2D.h>
#include <vtkImageBlend.h>
#include <vtkImage.h>
#include <vtkImageProperty.h>
#include <vtkOpenGLImageResliceMapper.h>
#include <mitkVtkPropRenderer.h>

mitk::ImageVtkMapper2D::ImageVtkMapper2D()
{
  this->m_VtkBased = true;
  this->m_TimeStep = 0;
  this->m_VtkActor = vtkSmartPointer<vtkImage>::New();
  this->m_VtkImage = vtkSmartPointer<vtkImageData>::New();
  this->m_VtkMapper = vtkSmartPointer<vtkOpenGLImageResliceMapper>::New();
}

mitk::ImageVtkMapper2D::~ImageVtkMapper2D()
{
}

const mitk::Image* mitk::ImageVtkMapper2D::GetInput()
{
  return static_cast<const mitk::Image* > ( GetData() );
}

void mitk::ImageVtkMapper2D::GenerateData(mitk::BaseRenderer* renderer)
{
  MITK_INFO << "Generate Data called";
  if ( !this->IsVisible(renderer) )
  {
    itkWarningMacro( << "Renderer not visible!" );
    return;
  }
  mitk::Image::Pointer input = const_cast<mitk::Image*>( this->GetInput() );
  if ( input.IsNull() ) return ;

  vtkSmartPointer<vtkImageData> image = input->GetVtkImageData(0,0);
//  image->SetScalarTypeToUnsignedChar();
//  vtkSmartPointer<vtkImageShiftScale> imageShiftSacle = vtkImageShiftScale::New();
//  imageShiftSacle->SetOutputScalarTypeToUnsignedChar();
//  imageShiftSacle->ClampOverflowOn();
//  imageShiftSacle->SetInput(image);

//  vtkSmartPointer<vtkImageCast> imageCast = vtkSmartPointer<vtkImageCast>::New();
//  imageCast->SetOutputScalarTypeToUnsignedChar();
//  imageCast->ClampOverflowOn();
//  imageCast->SetInput(image);
//  m_VtkImage->SetScalarTypeToUnsignedChar();
//  m_VtkImage = imageCast->GetOutput();
  m_VtkImage = image;

//  float opacity = 1.0f;
//  GetOpacity(opacity, renderer);
//  MITK_INFO << opacity;
////  m_VtkActor->GetProperty()->SetOpacity(opacity);
////  MITK_INFO << m_VtkActor->GetProperty()->GetOpacity();

//  vtkSmartPointer<vtkImageBlend> blend =
//    vtkSmartPointer<vtkImageBlend>::New();
////  blend->AddInputConnection(image->GetOutputPort());
//  blend->AddInputConnection(image->GetProducerPort());
//  blend->SetOpacity(0,opacity);

//  m_VtkImage = blend->GetOutput(0);

  if( m_VtkImage )
  {
//    mitk::LevelWindow levelWindow;
//    GetLevelWindow(levelWindow, renderer);
//    double range =

//    const mitk::VtkPropRenderer* glRenderer = dynamic_cast<const mitk::VtkPropRenderer*>(renderer);
//    if (glRenderer == NULL)
//      return;
//    vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer();

//    vtkSmartPointer<vtkImageProperty> ip = vtkSmartPointer<vtkImageProperty>::New();
//    ip->SetColorLevel(1000);
//    ip->SetColorWindow(2000);
//    ip->SetInterpolationTypeToLinear();

//    vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();

//    renderWindowInteractor->SetInteractorStyle(imageStyle);
//    renderWindowInteractor->SetRenderWindow(renderWindow);

//    m_VtkMapper->SetInputConnection(iExtended2Dmage->GetProducerPort());
    m_VtkMapper->SetInput(m_VtkImage);
//    m_VtkMapper->SetInputConnection(blend->GetOutputPort());
//    m_VtkMapper->SetColorLevel(levelWindow.GetLowerWindowBound());
//    m_VtkMapper->SetColorWindow(levelWindow.GetUpperWindowBound());

    m_VtkActor->SetMapper(m_VtkMapper);
//    m_VtkActor->SetProperty(ip);

//    m_VtkActor->SetVisibility(1);

  }
  else
  {
    itkWarningMacro( << "m_VtkImage is NULL!" );
    return ;
  }
}

void mitk::ImageVtkMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
  }
}
void mitk::ImageVtkMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible( renderer )==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
  {
    this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
  }
}

void mitk::ImageVtkMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
  if ( this->IsVisible(renderer)==false )
    return;

  if ( this->GetVtkProp(renderer)->GetVisibility() )
//BUG (#1551) changed VTK_MINOR_VERSION FROM 3 to 2 cause RenderTranslucentGeometry was changed in minor version 2
#if ( ( VTK_MAJOR_VERSION >= 5 ) && ( VTK_MINOR_VERSION>=2)  )
    this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());
#else
    this->GetVtkProp(renderer)->RenderTranslucentGeometry(renderer->GetVtkRenderer());
#endif
}

void mitk::ImageVtkMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
  if(IsVisible(renderer)==false)
    return;

  if ( GetVtkProp(renderer)->GetVisibility() )
    GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());
}

vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer)
{
//  m_VtkActor->GetProperty()->SetColor(0,1,0);
  return m_VtkActor;
}

vtkImageData *mitk::ImageVtkMapper2D::GenerateTestImageForTSFilter()
{
  // a 2x2x2 image
  unsigned char myData[] =
  {

    234,234,
    123,565,

//    -213,800,
//    1000,-20
  };
  vtkImageData *i = vtkImageData::New();

  i->SetExtent(0,1,0,1,0,0);

  i->SetScalarTypeToUnsignedChar();

  i->AllocateScalars();

  unsigned char *p = (unsigned char*)i->GetScalarPointer();

  memcpy(p,myData,2*2*1*sizeof(unsigned char));

  return i;
}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPointSet.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkTestingMacros.h"
#include <itksys/SystemTools.hxx>

//unsigned int numberOfTestPointSets = 1;
unsigned int numberOfTimeSeries = 5;
// create one test PointSet
class mitkPointSetFileIOTestClass { public:

static mitk::PointSet::Pointer CreateTestPointSet(unsigned int which)
{
  mitk::PointSet::Pointer pointSet = mitk::PointSet::New();

  for(unsigned int t= 0; t<numberOfTimeSeries; t++)
  {
    unsigned int position(0);
    mitk::Point3D point;
    mitk::FillVector3D(point, 1.0+t+which, 2.0+t+which, 3.0+t+which);
    pointSet->SetPoint(position, point, t);

    mitk::FillVector3D(point, 2.0+t+which, 3.0+t+which, 4.0+t+which);
    ++position;
    pointSet->SetPoint(position, point, t);

    mitk::FillVector3D(point, 3.0+t+which, 4.0+t+which, 5.0+t+which);
    ++position;
    pointSet->SetPoint(position, point, t);
  }

  return pointSet;

}

static void PointSetCompare(mitk::PointSet::Pointer pointSet2, mitk::PointSet::Pointer pointSet1, bool& identical)
{

  MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" );

  for (unsigned int t=0; t<numberOfTimeSeries; t++)
  {
    for (unsigned int i = 0; i < (unsigned int)pointSet1->GetSize(t); ++i)
    {
      mitk::Point3D p1 = pointSet1->GetPoint(i);
      mitk::Point3D p2 = pointSet2->GetPoint(i);

      double difference = (   (p1[0] - p2[0])
                            + (p1[1] - p2[1])
                            + (p1[2] - p2[2])
                          );

      MITK_TEST_CONDITION(difference <= 0.0001, "Testing if Points are at the same Position" );

    }
  }

}

static bool PointSetWrite(unsigned int numberOfPointSets)
{
    try
      {
        mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New();

        pointSetWriter->SetFileName("test_pointset_new.mps");
        for(unsigned int i=0; i<numberOfPointSets; i++)
        {
          pointSetWriter->SetInput(i, CreateTestPointSet(i));
        }
        pointSetWriter->Write();
      }
      catch ( std::exception& e )
      {
        return false;
      }

      return true;
}

static void PointSetLoadAndCompareTest(unsigned int numberOfPointSets)
{
  try
    {
      mitk::PointSetReader::Pointer pointSetReader = mitk::PointSetReader::New();
      mitk::PointSet::Pointer pointSet;

      pointSetReader->SetFileName("test_pointset_new.mps");
      for(unsigned int i=0; i<numberOfPointSets; i++)
      {
        pointSetReader->Update();
        pointSet = pointSetReader->GetOutput(i);
        MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" );

        bool identical(true);
        PointSetCompare(pointSet.GetPointer(), CreateTestPointSet(i).GetPointer(), identical);
      }
    }
    catch ( std::exception& e )
    {
    }
}

}; //mitkPointSetFileIOTestClass

int mitkPointSetFileIOTest(int, char*[])
{
  MITK_TEST_BEGIN("PointSet");
  unsigned int numberOfPointSets(1);

  // write
  MITK_TEST_CONDITION(mitkPointSetFileIOTestClass::PointSetWrite(numberOfPointSets), "Testing if the PointSetWriter writes Data" );

  // load - compare
  mitkPointSetFileIOTestClass::PointSetLoadAndCompareTest(numberOfPointSets);

  MITK_TEST_END();
}

<commit_msg>ENH (#1571): extended the test for reading and writing floating point number.<commit_after>/*=========================================================================

 Program:   Medical Imaging & Interaction Toolkit
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPointSet.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkTestingMacros.h"
#include <vector>
#include <itksys/SystemTools.hxx>
#include <time.h>

//unsigned int numberOfTestPointSets = 1;
unsigned int numberOfTimeSeries = 5;
// create one test PointSet
class mitkPointSetFileIOTestClass
{
public:

  std::vector<mitk::PointSet::Pointer> m_SavedPointSet;

  mitkPointSetFileIOTestClass()
  {

  }

  mitk::PointSet::Pointer CreateTestPointSet()
  {
    mitk::PointSet::Pointer pointSet = mitk::PointSet::New();

    for (unsigned int t = 0; t < numberOfTimeSeries; t++)
    {
      unsigned int position(0);
      mitk::Point3D point;
      mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0);
      pointSet->SetPoint(position, point, t);

      mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0);
      ++position;
      pointSet->SetPoint(position, point, t);

      mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0);
      ++position;
      pointSet->SetPoint(position, point, t);
    }
    m_SavedPointSet.push_back(pointSet);

    return pointSet;

  }

  void PointSetCompare(mitk::PointSet::Pointer pointSet2,
      mitk::PointSet::Pointer pointSet1, bool& identical)
  {

    MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" );

    for (unsigned int t = 0; t < numberOfTimeSeries; t++)
    {
      for (unsigned int i = 0; i < (unsigned int) pointSet1->GetSize(t); ++i)
      {
        mitk::Point3D p1 = pointSet1->GetPoint(i);
        mitk::Point3D p2 = pointSet2->GetPoint(i);

          //test
          std::cout << "r point: " << p2 << std::endl;
          std::cout << "w point: " << p1 << std::endl;

          //test end

        MITK_TEST_CONDITION((p1[0] - p2[0]) <= 0.0001, "Testing if X coordinates of the Point are at the same Position" );
        MITK_TEST_CONDITION((p1[1] - p2[1]) <= 0.0001, "Testing if Y coordinates of the Point are at the same Position" );
        MITK_TEST_CONDITION((p1[2] - p2[2]) <= 0.0001, "Testing if Z coordinates of the Point are at the same Position" );

      }
    }

  }

  bool PointSetWrite(unsigned int numberOfPointSets)
  {
    try
    {
      m_SavedPointSet.clear();
      mitk::PointSetWriter::Pointer pointSetWriter =
          mitk::PointSetWriter::New();

      pointSetWriter->SetFileName("/home/wangxi/test_pointset_new.mps");
      for (unsigned int i = 0; i < numberOfPointSets; i++)
      {
        pointSetWriter->SetInput(i, CreateTestPointSet());
      }
      pointSetWriter->Write();
    } catch (std::exception& e)
    {
      return false;
    }

    return true;
  }

  void PointSetLoadAndCompareTest(unsigned int numberOfPointSets)
  {
    try
    {
      mitk::PointSetReader::Pointer pointSetReader =
          mitk::PointSetReader::New();
      mitk::PointSet::Pointer pointSet;

      pointSetReader->SetFileName("/home/wangxi/test_pointset_new.mps");
      for (unsigned int i = 0; i < numberOfPointSets; i++)
      {
        pointSetReader->Update();
        pointSet = pointSetReader->GetOutput(i);
        MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" );

        bool identical(true);
        PointSetCompare(pointSet.GetPointer(), m_SavedPointSet.at(i).GetPointer(),
            identical);
      }
    } catch (std::exception& e)
    {
    }
  }

}; //mitkPointSetFileIOTestClass

int mitkPointSetFileIOTest(int, char*[])
{
  MITK_TEST_BEGIN("PointSet");
    unsigned int numberOfPointSets(100);

    mitkPointSetFileIOTestClass* test = new mitkPointSetFileIOTestClass();

    // write
    MITK_TEST_CONDITION(test->PointSetWrite(numberOfPointSets), "Testing if the PointSetWriter writes Data" );

    // load - compare
    test->PointSetLoadAndCompareTest(numberOfPointSets);

  MITK_TEST_END();
}

<|endoftext|>


<commit_before><commit_msg>adding chisquare output<commit_after><|endoftext|>


<commit_before><commit_msg>Doubles up on register mirroring. Will do for now. More to come.<commit_after><|endoftext|>


<commit_before><commit_msg>修改提示框字符高度计算<commit_after><|endoftext|>


<commit_before>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64TargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;

static cl::opt<bool>
EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
           cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
                     cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
                    " integer instructions"), cl::init(false), cl::Hidden);

static cl::opt<bool>
EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
                      "constant pass"), cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
                 " linker optimization hints (LOH)"), cl::init(true),
                 cl::Hidden);

static cl::opt<bool>
EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
                              cl::desc("Enable the pass that removes dead"
                                       " definitons and replaces stores to"
                                       " them with stores to the zero"
                                       " register"),
                              cl::init(true));

static cl::opt<bool>
EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
                   " optimization pass"), cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
                 cl::desc("Run SimplifyCFG after expanding atomic operations"
                          " to make use of cmpxchg flow-based information"),
                 cl::init(true));

extern "C" void LLVMInitializeAArch64Target() {
  // Register the target.
  RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
  RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);

  RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64leTarget);
  RegisterTargetMachine<AArch64beTargetMachine> W(TheARM64beTarget);
}

/// TargetMachine ctor - Create an AArch64 architecture model.
///
AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT,
                                           StringRef CPU, StringRef FS,
                                           const TargetOptions &Options,
                                           Reloc::Model RM, CodeModel::Model CM,
                                           CodeGenOpt::Level OL,
                                           bool LittleEndian)
    : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
      Subtarget(TT, CPU, FS, *this, LittleEndian) {
  initAsmInfo();
}

void AArch64leTargetMachine::anchor() { }

AArch64leTargetMachine::
AArch64leTargetMachine(const Target &T, StringRef TT,
                       StringRef CPU, StringRef FS, const TargetOptions &Options,
                       Reloc::Model RM, CodeModel::Model CM,
                       CodeGenOpt::Level OL)
  : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}

void AArch64beTargetMachine::anchor() { }

AArch64beTargetMachine::
AArch64beTargetMachine(const Target &T, StringRef TT,
                       StringRef CPU, StringRef FS, const TargetOptions &Options,
                       Reloc::Model RM, CodeModel::Model CM,
                       CodeGenOpt::Level OL)
  : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}

namespace {
/// AArch64 Code Generator Pass Configuration Options.
class AArch64PassConfig : public TargetPassConfig {
public:
  AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
      : TargetPassConfig(TM, PM) {}

  AArch64TargetMachine &getAArch64TargetMachine() const {
    return getTM<AArch64TargetMachine>();
  }

  void addIRPasses()  override;
  bool addPreISel() override;
  bool addInstSelector() override;
  bool addILPOpts() override;
  bool addPreRegAlloc() override;
  bool addPostRegAlloc() override;
  bool addPreSched2() override;
  bool addPreEmitPass() override;
};
} // namespace

void AArch64TargetMachine::addAnalysisPasses(PassManagerBase &PM) {
  // Add first the target-independent BasicTTI pass, then our AArch64 pass. This
  // allows the AArch64 pass to delegate to the target independent layer when
  // appropriate.
  PM.add(createBasicTargetTransformInfoPass(this));
  PM.add(createAArch64TargetTransformInfoPass(this));
}

TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
  return new AArch64PassConfig(this, PM);
}

void AArch64PassConfig::addIRPasses() {
  // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
  // ourselves.
  addPass(createAtomicExpandLoadLinkedPass(TM));

  // Cmpxchg instructions are often used with a subsequent comparison to
  // determine whether it succeeded. We can exploit existing control-flow in
  // ldrex/strex loops to simplify this, but it needs tidying up.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
    addPass(createCFGSimplificationPass());

  TargetPassConfig::addIRPasses();
}

// Pass Pipeline Configuration
bool AArch64PassConfig::addPreISel() {
  // Run promote constant before global merge, so that the promoted constants
  // get a chance to be merged
  if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
    addPass(createAArch64PromoteConstantPass());
  if (TM->getOptLevel() != CodeGenOpt::None)
    addPass(createGlobalMergePass(TM));
  if (TM->getOptLevel() != CodeGenOpt::None)
    addPass(createAArch64AddressTypePromotionPass());

  return false;
}

bool AArch64PassConfig::addInstSelector() {
  addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));

  // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
  // references to _TLS_MODULE_BASE_ as possible.
  if (TM->getSubtarget<AArch64Subtarget>().isTargetELF() &&
      getOptLevel() != CodeGenOpt::None)
    addPass(createAArch64CleanupLocalDynamicTLSPass());

  return false;
}

bool AArch64PassConfig::addILPOpts() {
  if (EnableCCMP)
    addPass(createAArch64ConditionalCompares());
  addPass(&EarlyIfConverterID);
  if (EnableStPairSuppress)
    addPass(createAArch64StorePairSuppressPass());
  return true;
}

bool AArch64PassConfig::addPreRegAlloc() {
  // Use AdvSIMD scalar instructions whenever profitable.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar)
    addPass(createAArch64AdvSIMDScalar());
  return true;
}

bool AArch64PassConfig::addPostRegAlloc() {
  // Change dead register definitions to refer to the zero register.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
    addPass(createAArch64DeadRegisterDefinitions());
  return true;
}

bool AArch64PassConfig::addPreSched2() {
  // Expand some pseudo instructions to allow proper scheduling.
  addPass(createAArch64ExpandPseudoPass());
  // Use load/store pair instructions when possible.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
    addPass(createAArch64LoadStoreOptimizationPass());
  return true;
}

bool AArch64PassConfig::addPreEmitPass() {
  // Relax conditional branch instructions if they're otherwise out of
  // range of their destination.
  addPass(createAArch64BranchRelaxation());
  if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
      TM->getSubtarget<AArch64Subtarget>().isTargetMachO())
    addPass(createAArch64CollectLOHPass());
  return true;
}
<commit_msg>AArch64: Temporarily disable AArch64AddressTypePromotion<commit_after>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64TargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;

static cl::opt<bool>
EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
           cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
                     cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
                    " integer instructions"), cl::init(false), cl::Hidden);

static cl::opt<bool>
EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
                      "constant pass"), cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
                 " linker optimization hints (LOH)"), cl::init(true),
                 cl::Hidden);

static cl::opt<bool>
EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
                              cl::desc("Enable the pass that removes dead"
                                       " definitons and replaces stores to"
                                       " them with stores to the zero"
                                       " register"),
                              cl::init(true));

static cl::opt<bool>
EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
                   " optimization pass"), cl::init(true), cl::Hidden);

static cl::opt<bool>
EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
                 cl::desc("Run SimplifyCFG after expanding atomic operations"
                          " to make use of cmpxchg flow-based information"),
                 cl::init(true));

extern "C" void LLVMInitializeAArch64Target() {
  // Register the target.
  RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
  RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);

  RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64leTarget);
  RegisterTargetMachine<AArch64beTargetMachine> W(TheARM64beTarget);
}

/// TargetMachine ctor - Create an AArch64 architecture model.
///
AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT,
                                           StringRef CPU, StringRef FS,
                                           const TargetOptions &Options,
                                           Reloc::Model RM, CodeModel::Model CM,
                                           CodeGenOpt::Level OL,
                                           bool LittleEndian)
    : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
      Subtarget(TT, CPU, FS, *this, LittleEndian) {
  initAsmInfo();
}

void AArch64leTargetMachine::anchor() { }

AArch64leTargetMachine::
AArch64leTargetMachine(const Target &T, StringRef TT,
                       StringRef CPU, StringRef FS, const TargetOptions &Options,
                       Reloc::Model RM, CodeModel::Model CM,
                       CodeGenOpt::Level OL)
  : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}

void AArch64beTargetMachine::anchor() { }

AArch64beTargetMachine::
AArch64beTargetMachine(const Target &T, StringRef TT,
                       StringRef CPU, StringRef FS, const TargetOptions &Options,
                       Reloc::Model RM, CodeModel::Model CM,
                       CodeGenOpt::Level OL)
  : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}

namespace {
/// AArch64 Code Generator Pass Configuration Options.
class AArch64PassConfig : public TargetPassConfig {
public:
  AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
      : TargetPassConfig(TM, PM) {}

  AArch64TargetMachine &getAArch64TargetMachine() const {
    return getTM<AArch64TargetMachine>();
  }

  void addIRPasses()  override;
  bool addPreISel() override;
  bool addInstSelector() override;
  bool addILPOpts() override;
  bool addPreRegAlloc() override;
  bool addPostRegAlloc() override;
  bool addPreSched2() override;
  bool addPreEmitPass() override;
};
} // namespace

void AArch64TargetMachine::addAnalysisPasses(PassManagerBase &PM) {
  // Add first the target-independent BasicTTI pass, then our AArch64 pass. This
  // allows the AArch64 pass to delegate to the target independent layer when
  // appropriate.
  PM.add(createBasicTargetTransformInfoPass(this));
  PM.add(createAArch64TargetTransformInfoPass(this));
}

TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
  return new AArch64PassConfig(this, PM);
}

void AArch64PassConfig::addIRPasses() {
  // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
  // ourselves.
  addPass(createAtomicExpandLoadLinkedPass(TM));

  // Cmpxchg instructions are often used with a subsequent comparison to
  // determine whether it succeeded. We can exploit existing control-flow in
  // ldrex/strex loops to simplify this, but it needs tidying up.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
    addPass(createCFGSimplificationPass());

  TargetPassConfig::addIRPasses();
}

// Pass Pipeline Configuration
bool AArch64PassConfig::addPreISel() {
  // Run promote constant before global merge, so that the promoted constants
  // get a chance to be merged
  if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
    addPass(createAArch64PromoteConstantPass());
  if (TM->getOptLevel() != CodeGenOpt::None)
    addPass(createGlobalMergePass(TM));

  return false;
}

bool AArch64PassConfig::addInstSelector() {
  addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));

  // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
  // references to _TLS_MODULE_BASE_ as possible.
  if (TM->getSubtarget<AArch64Subtarget>().isTargetELF() &&
      getOptLevel() != CodeGenOpt::None)
    addPass(createAArch64CleanupLocalDynamicTLSPass());

  return false;
}

bool AArch64PassConfig::addILPOpts() {
  if (EnableCCMP)
    addPass(createAArch64ConditionalCompares());
  addPass(&EarlyIfConverterID);
  if (EnableStPairSuppress)
    addPass(createAArch64StorePairSuppressPass());
  return true;
}

bool AArch64PassConfig::addPreRegAlloc() {
  // Use AdvSIMD scalar instructions whenever profitable.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar)
    addPass(createAArch64AdvSIMDScalar());
  return true;
}

bool AArch64PassConfig::addPostRegAlloc() {
  // Change dead register definitions to refer to the zero register.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
    addPass(createAArch64DeadRegisterDefinitions());
  return true;
}

bool AArch64PassConfig::addPreSched2() {
  // Expand some pseudo instructions to allow proper scheduling.
  addPass(createAArch64ExpandPseudoPass());
  // Use load/store pair instructions when possible.
  if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
    addPass(createAArch64LoadStoreOptimizationPass());
  return true;
}

bool AArch64PassConfig::addPreEmitPass() {
  // Relax conditional branch instructions if they're otherwise out of
  // range of their destination.
  addPass(createAArch64BranchRelaxation());
  if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
      TM->getSubtarget<AArch64Subtarget>().isTargetMachO())
    addPass(createAArch64CollectLOHPass());
  return true;
}
<|endoftext|>